Compare commits

...

648 Commits

Author SHA1 Message Date
0acc0d94a3 更新 'simgear/scene/tgdb/obj.cxx' 2022-12-09 13:46:31 +08:00
33aad9aee1 更新 'simgear/scene/tgdb/obj.cxx' 2022-12-09 13:17:32 +08:00
8577cbfbef 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:55:14 +08:00
83c6dfe13d 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:51:50 +08:00
4380326ab5 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:39:33 +08:00
18b6c87d7d 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:37:27 +08:00
febafabff8 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:35:54 +08:00
6ebe2f23c1 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:25:33 +08:00
f763c90c23 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:21:55 +08:00
7c09c0f664 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:16:37 +08:00
09a3d9cd92 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:15:59 +08:00
64fba53506 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:14:12 +08:00
76575c512c 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-24 15:06:43 +08:00
3091de98ca 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-14 20:26:52 +08:00
e3fde842b3 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-14 20:20:19 +08:00
11cfcfa8c5 更新 'simgear/scene/tsync/terrasync.cxx' 2022-11-14 19:51:04 +08:00
e507a95b55 下载地址 terrasync.jingweiht.com 2022-10-22 14:04:18 +08:00
Florent Rougon
0d3ec0c148 sample_group.cxx: remove unneeded #include directive 2022-10-17 17:58:48 +02:00
Florent Rougon
3ae3a9fb72 SGSampleGroup::remove(): immediately remove from _samples by default
Code in AudioIdent::setIdent() expects that SGSampleGroup::remove() does
remove the corresponding item from _samples, however SG commit 47aae88ab
broke this assumption, which caused the bug reported at [1].

Restore the immediate removal from _samples by default. For the special
case where we do need delayed removal (i.e., while
SGSampleGroup::update() is iterating over _samples), the new optional
parameter is passed the value true. For a longer explanation, see [2].

This fixes a crash when swapping the selected and standby frequencies
for the NAV1 or NAV2 instrument (more precise description at [1]).

[1] https://forum.flightgear.org/viewtopic.php?f=25&t=40890
[2] https://sourceforge.net/p/flightgear/mailman/message/37721699/
2022-10-17 17:57:07 +02:00
Stuart Buchanan
96a9abfd7a WS30: Improved Atlas encapsulation 2022-10-14 21:36:25 +01:00
Scott Giese
2b9a319e76 portability: change uint to unsigned int 2022-10-11 10:14:49 -05:00
Scott Giese
eb5499fb10 maintenance: eliminated 19 compiler warnings 2022-10-09 18:36:37 -05:00
Stuart Buchanan
e50337e36a Ensure Build Bounding Box doesn't collapse
Previously the Bounding Box of a group of building was calculated
purely based on the position of each building.  Depending on the
geometry of the various buildings, this could result in a zero-volume
box, which would be culled away.

This change ensures that the BB is at least a 20x20x20 volume, by
increasing the convex hull size.

Fixes https://sourceforge.net/p/flightgear/codetickets/2542/
2022-10-08 22:41:48 +01:00
James Turner
836ee9a3f0 Accept old XML model paths for some models
Update my work-around for this from last year, and handle another
case (where models are loaded directly rather using the delayed
callback via the osgDB::Pager)

Where we replaced the XMl-wrapper with an AC model in FGData or
TerraSync, accept the old path ending in .xml, to avoid many errors
loading custom scenery.
2022-10-03 14:45:19 +01:00
James Turner
3ef521b53f Add parse test for CB with no coverage
Causes crashes but inside FlightGear
2022-10-03 14:36:20 +01:00
Erik Hofman
47aae88aba Revert a8d3397fb4 and arase entries from the _sample map after the loop 2022-10-03 13:53:24 +02:00
Richard Harrison
49dd3cad33 Change axis object animations to be compatible with <=2020.3 refs Ticket #2706
The changes to the sorting rules caused a breaking change that was incompatible.

The solution to this is to revert to being compatible with <=2020.3 but also to allow modellers to choose the new sorting rules.

I've added a new tag <defaults> which can contain either <axis-animation-vertex-order-xyz/> or <axis-animation-vertex-order-x/>. The defaults will affect all animations in the .xml and also any included models unless the included model also has a <defaults> section.

So for modelers that want to use the new definitive vertex sorting rules adding the following to the main model is sufficient.

    <defaults>
        <axis-animation-vertex-order-xyz/>
    </defaults>

There are also a couple of new tags that can be used in the <axis> section.

1. <order-by-xyz/> - use the new sorting rules
2. <order-by-x/> - use the 2020.3 sorting rules
3. <swap-axis-direction/> - when the animation goes the wrong way this is an elegant way to fix it.

See https://sourceforge.net/p/flightgear/codetickets/2706/
2022-09-30 19:04:11 +01:00
Scott Giese
0851dd5cf1 suppress warning: does not guard.
whitespace fix.
2022-09-24 22:02:07 -05:00
Erik Hofman
a8d3397fb4 std::map entries can not be removed when inside a for (auto current : _samples) loop. Rework the removal code to accept the iterator itself and move incrementing the iterator until after the erase action or let the erase action assign the new iterator. 2022-09-24 10:23:52 +02:00
Erik Hofman
9e20d853f7 Tie the SoundGroup to the listener (not really necessary in this case but it provides a good hint) and call the soundmanager update after setting the position and orientation to activate the repositioning. This wil make the first sample to be heard immidiately. 2022-09-23 11:53:01 +02:00
Erik Hofman
3ffbec41ee Prevent NaNs for orientation too 2022-09-23 11:24:50 +02:00
James Turner
c66a2bffe5 XML submodel: log the model name in the error.
Try to improve diagnosis of problems where overlay XML Nodes are used,
and the model path might be empty, as happened with the 737-800
2022-09-12 13:30:33 +01:00
James Turner
423fd4e842 Model XML: pass the model path to osgDB::Options
To allow giving better error feedback in the AC3D loader, pass the
file path explicitly as a plugin data string, so we can report it.
2022-09-09 12:17:11 +01:00
James Turner
272399e833 XMLSound: report failures via the new system
Ensure that misconfigured XML-sound files are traced to the aircraft
2022-09-09 12:04:45 +01:00
James Turner
b2666c40f7 DNSClient: reorder timeout check
Check completion before timeout, so that complete requests which have
also exceeded their timeout don’t crash
2022-09-09 12:03:43 +01:00
Florent Rougon
cc3fab04a3 ResourceManager::findPath(): remove the first validate() call and warning
- Remove the SGPath::validate() call added in commit
  22779ee2c4 (first part of findPath():
  when it is called with a non-null second argument).

- Remove the warning printed when the assembled path is absolute and
  fails the SGPath::validate() read permission test (this caused too
  much noise and confusion).

- Keep the behavior or accepting absolute, existing paths that pass the
  SGPath::validate() read permission test.

This way, the 'play-audio-sample' FGCommand will continue to work with
absolute paths. If/when the built-in launcher is updated to set up the
read-allowed paths early enough, maybe we can revert FG commits
3ee54cbd72bd8f and 896be707ae558 and re-add the SGPath::validate()
call in the first part of findPath()---assuming it is deemed useful.
2022-08-28 14:53:05 +02:00
Florent Rougon
f906d82213 embedded_resources_test.cxx: fix warnings 2022-08-27 11:08:21 +02:00
Florent Rougon
64c5ed2be1 ResourceManager::findPath(): adjust a comment
Based on a discussion on flightgear-devel (see in particular James
Turner's message at [1]).

[1] https://sourceforge.net/p/flightgear/mailman/message/37697739/
2022-08-24 15:03:44 +02:00
Florent Rougon
22779ee2c4 ResourceManager::findPath(): validate; accept absolute, read-allowed paths
- Perform the SGPath::validate() test for read access before returning a
  path obtained with a non-null second argument ("aContext").

- If SGPath(aContext, aResource) is an absolute path for which read
  access is authorized by SGPath::validate(), return it. This restores
  the possibility of using the 'play-audio-sample' FGCommand with an
  absolute, read-allowed path (was lost in FG commit 8853fded2953959).

- Because a fair number of the existing uses of
  ResourceManager::findPath() are not quite correct IMO, we execute the
  final part where all providers are tried in turn even if
  SGPath(aContext, aResource) is an absolute path (otherwise, the sim
  wouldn't start because it couldn't load materials.xml---see [1]).

- The SG_LOG call will spot a few errors in calling code/data, such as
  access tried for
  '/Aircraft/Generic/flightrecorder/generic-piston-propeller-4.xml' and
  '/Textures/Sky/cl_cumulus2.png'; since the function does not return at
  this point, these incorrect absolute paths which should be relative
  will still be given a chance with the BasePathProvider that has its
  base path set to $FG_ROOT; thus, they will be found as before this
  commit despite the new "access refused" warning (but please fix
  them!).

This commit requires FlightGear commit e7594f46876fc6b0b.

[1] https://sourceforge.net/p/flightgear/mailman/message/37697516/
2022-08-24 01:33:57 +02:00
Florent Rougon
9608072787 SGPath: make read_allowed_paths and write_allowed_paths static data members
No functional change, only a tidier organization.
2022-08-22 23:59:37 +02:00
Florent Rougon
e002a481f4 Import FlightGear's fgValidatePath() as SGPath::validate()
This will allow us to perform access control validation in SimGear. The
current implementation of SGPath::validate() is 99% Rebecca Palmer's
work (see fgValidatePath() in FlightGear commit
6a30e7086ea2f1a060dd77dab6e7e8a15b43e82d); only the coding style has
been slightly modernized here since we can now use, for instance,
C++11's range-based for loop.
2022-08-22 13:15:48 +02:00
Florent Rougon
1ef4a7eb9e SGPath: rename validate() to updateAttrsIfNull()
This is to avoid confusion because the following commit will make
SGPath::validate(bool) replace the fgValidatePath() function from the
FlightGear repository.
2022-08-22 12:58:11 +02:00
Florent Rougon
8febf6b9f5 SGSoundSample constructor changes
- Add an explicit constructor SGSoundSample(const SGPath& file) that
  directly uses the specified path instead of going through
  ResourceManager::findPath().

- Reimplement the existing constructor as
  SGSoundSample(const std::string& file, const SGPath& dir),
  delegating to the new one.

- The first argument of the delegating constructor is now a
  const std::string& instead of a const char*.

Among others, this will allow a better implementation of
FGSoundManager::playAudioSampleCommand(). More explanations can be found
here:

  https://sourceforge.net/p/flightgear/mailman/message/37695786/
2022-08-20 08:20:38 +02:00
James Hogan
8e43ccc87b Compositor: Fix log message about shadow pass
Fix a slightly messy log message about a pass not being a shadow pass,
where there was no end quote or space after the pass name.
2022-07-30 23:56:57 +01:00
Erik Hofman
aead0a305f Jean-Paul Acneaux (www2):
Update the world magnetic model data set from WMM2015 to WMM2020.
2022-07-24 08:29:48 +02:00
James Turner
b1dbb9499c METAR parsing: parse more cloud covers
Parse cloud coverage with no coverage or height
SF-ID: https://sourceforge.net/p/flightgear/codetickets/2750/
2022-07-01 16:24:36 +02:00
James Turner
a74181ded9 Allow specifing TerraSync DNS nameserver 2022-06-07 23:15:29 +01:00
Lars Toenning
8f940ed4f2 Fix SPDX license identifier 2022-06-03 09:58:56 +01:00
James Turner
a47b214c18 Allow SGVec<> isNaN in release build 2022-06-01 14:57:37 +01:00
Lars Toenning
4259db0b8f Add unittest for SGTimer/SGTimerQueue 2022-05-29 19:12:06 +01:00
Stuart Buchanan
a8cb72d653 WS30: Improved coastlines
Build a high resolution texture containing coastline
data that will be mixed with the landclass texture
in the ws30 shader.

Replaces the previous approach of creating a separate
coastline mesh.
2022-05-28 21:03:48 +01:00
Lars Toenning
e04f89e8b2 Use std::function for callbacks
Reduce complexity by using std::function for callbacks instead of our own class.
2022-05-25 10:37:26 +01:00
James Turner
e1aba1364b Disable the 'no shaders defined' error for now
Until we have a way to mark techqniues as permanently disabled,
remove this check, since it generates false positives. Especially,
see model-combined technnique n=9.
2022-05-25 10:36:43 +01:00
James Turner
5afeb44cec Effects: pass model XML file path, not dir path
Pass the full path to the XML file, not is containg directory, through
effects, so that it's available for error reporting. Convert to an
actual directory when using the path to lookup other resources.
2022-05-25 10:35:31 +01:00
Lars Toenning
e0e3456a68 Refactor SGTimerQueue
Use std::unique_ptrs to handle SGTimer
Use std::vector as container together with STL heap functions
2022-05-16 09:50:54 +01:00
Julian Smith
13ca3cec56 simgear/screen/video-encoder*: build fixes for ffmpeg code on Windows.
simgear/screen/video-encoder-internal.hxx:
    Fixed initialisation of AVRational instance to work on Windows.
simgear/screen/video-encoder.cxx:
    av_log(): vasprintf() is not available on Windows so use fixed buffer on
    Windows.
2022-05-04 17:54:46 +01:00
Julian Smith
20898923e0 simgear/timing/rawprofile.hxx: minor update to docs. 2022-05-01 23:24:42 +01:00
Julian Smith
eb94d12c4f simgear/screen/video-encoder.cxx: fixed build failure when SG_FFMPEG undefined. 2022-05-01 23:24:42 +01:00
Julian Smith
ac37f734ba simgear/screen/video-encoder*: support for logging timing info for sws_scale(). 2022-05-01 15:18:58 +01:00
Julian Smith
8037a0eb20 simgear/timing/rawprofile.hxx: support for profiling single piece of code. 2022-05-01 15:18:54 +01:00
Julian Smith
294e0b0bb7 simgear/structure/commands.cxx: removed assert that fires if we don't use thread-cpu affinities. 2022-04-30 00:45:23 +01:00
Erik Hofman
12c0166f92 Calculate if the sound source is within the mach cone relateive the the listener and calculate the offset within the mach code for use by the sound configuration file. 2022-04-29 15:07:14 +02:00
Erik Hofman
6719a8e3d5 Add functions to return the squared length of a vector: Comparing two squared values prevents two computionally heavy sqrt calls. 2022-04-25 10:48:07 +02:00
Stuart Buchanan
fa2b5911b7 WS30: Add waterline-start and waterline-end params
Used for coastline mixing.
2022-04-09 16:24:51 +01:00
James Turner
363906828f Reduce log noise for a common message in input 2022-04-06 07:50:36 +01:00
Lars Toenning
b01e8f51f1 Add missing include 2022-03-27 20:07:27 +01:00
Erik Hofman
718b09d7c3 Do not use ShaderVG until it's ready for use 2022-03-25 07:40:51 +01:00
James Turner
2993671fa4 Subsystems: only record timings if enabled
Avoid some overhead in copying std::map<>, in the common case where
subsystem timing reporting is not enabled.
2022-03-24 16:06:09 +00:00
Julian Smith
de0ab92cca simgear/nasal/code.c: fixed conversion of strings to bool.
We need to check IS_OBJ(r) after IS_STR(r) because all strings are also
objects.

For example this fixes a bug where an empty string evaluated as true.
2022-03-20 15:07:13 +00:00
Richard Harrison
3cc7b9a17b DDS-TC: Add origin to CanvasImage loadImage
Method loadImage should set the canvas origin to allow the DDS texture cache to act appropriately (i.e. not include anything from Canvas)
2022-03-17 11:43:46 +01:00
Richard Harrison
9e0ab6e268 DDS-TC : Always exclude all of canvas origin
The assumption is that all images coming from Canvas should be excluded from inclusion into the DDS texture cache.

Previously there was special logic that only excluded transparent images of Canvas origin but this was probably wrong.
2022-03-17 11:42:33 +01:00
Richard Harrison
91eca221f9 Fix Translate axis animation Refs ticket #2706
Due to an error I made in 7ac90850 all AxisObject-based translate animations were inverted.

I think this correctly fixes the animations so that a value of zero is the 'start' vertex of the axis and a value of 1.0 is the 'end' value of the axis.

Start and end are now defined on the lowest x,y,z that aren't equivalent (within 0.01mm)

see: https://sourceforge.net/p/flightgear/codetickets/2706/
2022-03-14 16:58:12 +01:00
Richard Harrison
83eda09558 Remove threaded Nasal garbage collection refs #2674 Nasal corruption:
refs: https://sourceforge.net/p/flightgear/codetickets/2674/

Because disabling threaded GC wouldn't result in exactly the same allocation and GC due to changes I made to the GC as part of the threaded GC work the only safe thing to do is to remove it all.

Once we have figured out if it is the threaded GC causing the problem or not then we will at least know what needs fixing.
2022-03-13 21:37:28 +01:00
Richard Harrison
30736ea057 Use helper method for OSGText alignment 2022-03-10 20:13:25 +01:00
Richard Harrison
92c4ea9f45 Added helper method for OSGText alignment conversion 2022-03-10 15:11:52 +01:00
James Turner
56e3a652f9 Fix ShaderVG compilation on macOS (and others?)
We had a manual change in ShivaVG, to include the shConfig.h file
explicitly, since the sources do not include it themselves. Replicate
this change in our copy of ShaderVG.

Necessary to fix compilation on macOS and likely FreeBSD as well.
2022-03-09 10:43:22 +00:00
James Turner
ddb5e52885 Nasal: extend boolify() to work on containers/objects
Consider non-empty containers and non-nil objects (eg, ghosts) to be
true-like, in boolify(). This makes for more natural testing of return
values.

Since these types previously caused a runtime error, should be backwards
compatible, unless code was relying on the error. This seems improbable,
if it happens in practice, we can revert and find a different solution.
2022-03-09 10:36:58 +00:00
James Turner
47a103f7ea Nasal: add str() helper to force a type to be a string
Calls existing naStringValue internally.
2022-03-09 09:58:37 +00:00
James Turner
6bbf7ed109 Add missing declaration to SpacerItem 2022-03-09 09:58:37 +00:00
James Turner
a6bd613159 Remove log message, now property changes are stable 2022-03-09 09:58:37 +00:00
Erik Hofman
6a32b758af Remove a mistake, GLEW is not required when including the correct headers 2022-02-26 13:24:07 +01:00
James Turner
bb18c59530 Grid: Add row/column stretch implementation
Also add a basic test case for stretch behaviour.
2022-02-26 11:23:21 +00:00
James Turner
6b9575d076 Expat: build on older GLibC versions
getrandom() is only in GLibC >= 2.2.5, and CentOS 7 uses an older
GCC version, so add CMake logic to fallback to /dev/urandom as the
Expat entroy source.
2022-02-25 20:59:20 +00:00
James Turner
7ee427c202 Add GridLayout for Canvas.Layout
Need a grid layout in addition to the existing vbox/hbox layouts,
add a basic one. Still work in progress, minimal test cases pass.
No height-for-width support yet, but row/column spanning and stretch
factors are supported.

Move some functionality from Layout.cxx into BoxLayout.cxx, which
is specific to the one-dimensions layout types.
2022-02-25 16:39:39 +00:00
Lars Toenning
d146c0561f Fix compilation with libavcodec >5
API was constified: 626535f6a1
2022-02-25 10:54:37 +01:00
Stuart Buchanan
1a37dcf3d5 WS30: Improved algorithm for airport placement
Previously the vertices directly underneath an airport were
displaced downwards.  In general this worked OK, but for airports
surrounded by higher terrain, this could cause "ridges" from
edges from vertices just outside the airport boundary.

This commit modifies the algorithm to also reduce the elevation
of vertices immediately outside the airport boundary as well.
2022-02-24 22:29:34 +00:00
Erik Hofman
b157f9cb9f Make the option ShivaVG or ShaderVG a Cmake option: USE_SHADERVG 2022-02-20 15:37:33 +01:00
Erik Hofman
6451e505d8 Add ShaderVG, a shader based version of ShivaVG
All FlighGear specific patches applied to ShivaVG are also applied to
ShaderVG, if appropriate.

For testing only for now, it is not yet fully functional.
2022-02-17 13:34:21 +01:00
James Turner
c1179f2e3b Update to Expat 2.4.4
Required to address reported in-the-wild CVEs in older Expats.

This may need a tweak for Linux / BSDs to set appropriate values in
our custom expat_config.h : only macOS and Windows tested so far.
2022-02-13 17:26:57 +02:00
Stuart Buchanan
4485505381 Fix rotation of cloud sprites (#2359)
Previously 3D cloud re-position code did not re-orientate
the sprites, leading to the sprites being at an angle for
long flights.

Fix from Michael DANILOV to address this.
2022-02-06 15:39:16 +00:00
James Turner
8722ea0fb6 Model animation loading errors
Another fix, for a different exception type, spotted by Michael D.

SF-ID: https://sourceforge.net/p/flightgear/codetickets/2702/
2022-02-06 10:56:05 +00:00
Stuart Buchanan
f17bd77030 WS30: Better water detection 2022-02-05 15:21:39 +00:00
James Turner
93adb8508e Effects: pass the model XML path through to makeEffects
This gives knowledge of how to resolve relative paths, to makeEffects
invocation of findDataFile, and hence gives a more familiar lookup
ordering, for Aircraft-supplied effects.

SF-ID: https://sourceforge.net/p/flightgear/codetickets/2678/
2022-02-04 12:08:46 +00:00
James Turner
13595ce05d Throw exception for broken XML animations.
Throwing an exception causes normal error-collecting to trigger for
the XML model load, so this is sufficient to avoid the crash and
also report back to the aircraft developer & user.

Thanks to Michael Danilov for catching this.

SF-ID: https://sourceforge.net/p/flightgear/codetickets/2702/
2022-02-04 12:07:24 +00:00
Stuart Buchanan
30b5bbe7d5 WS30: Add property controlling splitting water mesh
Previously a separate mesh was created for parts of the
terrain identified as being water.

This adds a property (/scenery/elevation-mesh/separate-water-mesh)
which controls whether this separate mesh is generated.
2022-02-01 17:05:31 +00:00
Stuart Buchanan
28e2ccda01 MR104: Added the Milky Way onto the night sky
From Chris RINGEVAL

Squashed commit of the following:

commit ee2ec625ef10ab372a99397a82d1272670d767ec
Author: Chris Ringeval <eatdirt@protonmail.com>
Date:   Mon Jan 31 00:01:39 2022 +0100

    Replace galaxy texture by our own and update galactic coordinates

commit 26f3d80df6385913668635013912f1c4fef50e60
Author: Chris Ringeval <eatdirt@protonmail.com>
Date:   Tue Dec 7 22:02:10 2021 +0100

    Cleanup white lines and comments

commit 55e9f9b4bcbe21a34be7be874b120bda73c49cb8
Author: Chris Ringeval <eatdirt@protonmail.com>
Date:   Sun Dec 5 15:53:15 2021 +0100

    Cleanup cxx parts to the minimal required, moving all rendering to the shaders

commit 0cff2827bb3c18f85780cce5c0178ee37c590fe5
Author: Chris Ringeval <eatdirt@protonmail.com>
Date:   Wed Dec 1 22:55:41 2021 +0100

    Adding moon direction uniform vector used in the Milky Way shader

commit 24485079673c299bad95fc1f800542a6d73e8e95
Author: Chris Ringeval <eatdirt@protonmail.com>
Date:   Wed Dec 1 22:54:54 2021 +0100

    Adding Milky Way texturing and dark sky brightness effects
2022-02-01 16:13:44 +00:00
Erik Hofman
a6624b8c89 Add ALS prodecural lights compatible pointing_x, pointing_y, pointing_z. You can now use the same direction vector for both ALS and the Compositor lights 2022-01-29 13:29:44 +01:00
Stuart Buchanan
76f1ffa269 WS30: Fix passing of edge-hardness to shader 2022-01-22 15:44:19 +00:00
Fahim Imaduddin Dalvi
1afbda9833 WS20: Object mask bug fix for random lights
The random lights placement algorithm was using the incorrect channel
from the object mask image, (red instead of blue as mentioned in
Docs/README.materials). This commit rectifies the mismatch.
2022-01-17 22:13:38 +03:00
Stuart Buchanan
4ed559d5a9 WS30: Pass material parameter/edge-hardness to shader 2022-01-15 14:52:33 +00:00
Stuart Buchanan
a95b531409 WS30: Road shader - add required Uniforms 2022-01-12 21:31:47 +00:00
James Turner
0459406f84 Supress missing-override warnings in GCC/Clang
Due to OSG's age, I get a lot of these with Clang & XCodee
2022-01-10 15:01:58 +00:00
Julian Smith
085a71b934 simgear/screen/video-encoder*: changed licenses to be LGPL-2.0-or-later. 2022-01-08 10:34:11 +00:00
Julian Smith
b3f9aa7f32 simgear/screen/video-encoder*: added GPL SPDX-License-Identifier license text. 2022-01-07 17:20:03 +00:00
James Turner
1f1b047981 Add range() function to Nasal 2022-01-07 16:14:44 +00:00
Julian Smith
8772ff4e2a simgear/props/props.*: added SGPropertyNode::getValue<std::string>() specialisation.
This is needed for external VR code that used to use
SGPropertyNode::getValue<const char*>() (which has been removed).
2022-01-06 22:02:45 +00:00
Fahim Imaduddin Dalvi
c4c5829d37 Added airport terrain check for random objects
Random objects like lights and trees are not placed on airport terrain
anymore. This commit also refactors some of the existing code for clarity.
Discussion can be found here [1] and detailed history here [2].

[1] https://sourceforge.net/p/flightgear/simgear/merge-requests/102/
[2] https://sourceforge.net/u/fahimdalvi/simgear/ci/bugfix/ws30_random_objects_avoid_airports/~/tree/

Squashed commit of the following:

commit 643198f8d52da8d65a674b052c508f03d7f83ac0
Author: Fahim Imaduddin Dalvi <dalvifahim@gmail.com>
Date:   Tue Jan 4 09:57:34 2022 +0300

    Implemented corrected airport intersection logic

    We now convert the point into the correct coordinate system before
    checking for intersections with the airport geometry.

commit 7e0819e4f88992658301a2c15d890fc489cfe3b6
Author: Fahim Imaduddin Dalvi <dalvifahim@gmail.com>
Date:   Wed Nov 10 19:59:04 2021 +0300

    Added airport terrain check code for random objects

    This commit does not work as expected. The light-coverage check is disabled
    to amplify the bug.

commit eb21e8fd256dcf124857ac51afc0d7c3c90ae1c6
Author: Fahim Imaduddin Dalvi <dalvifahim@gmail.com>
Date:   Wed Nov 10 19:53:44 2021 +0300

    Refactored elevation constraint checking code

    This commit provides a separate elevation constraint function that does not
    displace the given point. The current function has been renamed to indicate
    the displacement side effect.
2022-01-04 18:10:03 +03:00
Fahim Imaduddin Dalvi
d4b02d58d6 Refactored constraint checking for random objects
The Random objects check now happens in the scanline read in VPBTechnique,
rather in the VBPMaterialHandler objects. These checks are not specific
to any handler, and are thus better suited to be outside of specific
material handling logic.
2022-01-04 17:56:41 +03:00
Stuart Buchanan
65542e7521 WS30: Disable texture cache for material atlas
The texture cache interacts badly with the code creating the WS30
texture atlas, resulting in a bad atlas.  This change adds a new
SGReaderWriterOptions::LoadOriginHint::ORIGIN_MATERIAL_ATLAS
which causes the material cache not to cache the texture.
2022-01-03 17:17:17 +00:00
Scott Giese
301da53ba4 Remove FormFeeds 2021-12-27 02:29:46 -06:00
Jonathan Redpath
25f66995da osgText: improve code to search aircraft directory for font 2021-12-25 15:20:53 +00:00
James Turner
782378a1b6 Always set USE_OPENALSOFT
WIthout this, the generated SimgearConfig.cmake is a bit
unhappy.
2021-12-24 15:30:31 +00:00
Julian Smith
5fe9fd0fc6 simgear/props/props.cxx: moved common members into SGPropertyLock base class. 2021-12-24 14:49:09 +00:00
Julian Smith
23b3824170 simgear/props/props.*: added defaultValue arg to node get*Value() methods.
Add defaultValue arg to get*Value() methods that previously took no args. We
do this for getBoolValue(), getIntValue(), getLongValue(), getFloatValue() and
getDoubleValue(). The default value is returned if the node's string is not
convertible to the requested type.

This can enable some calling code to be optimised where it previously checked
for getStringValue() (which is slow now that it returns a std::string)
returning an empty string, before calling getDoubleValue().
2021-12-24 14:49:09 +00:00
Lars Toenning
dd09e5f466 Make SGPropertyNode::getStringValue() thread-safe.
This is by Lars Toenning <dev@ltoenning.de>, Roman Ludwicki <romek21@op.pl> and
SDeAstis <salvatore.deastis@gmail.com>, in 2021 Hackathon.

SGPropertyNode::getStringValue() now returns std::string by value instead of
const char* pointer into SGPropertyNode's internal data.

Patched up various call sites to use new API.

Remove SGPropertyNode::getName() and use SGPropertyNode::getNameString()
everywhere.
2021-12-24 14:49:08 +00:00
James Turner
da3507f3df CMake config option to use OpenAL-soft
THis enables overriding the Apple OpenAL.framework on
macOS, and using OpenAL-soft instead.
2021-12-24 13:23:34 +00:00
Scott Giese
854ad8c3fa apt_signs: provide content with Apt Sign messages.
Useful to help track down which sign failed to parse.
2021-12-22 23:41:58 -06:00
Scott Giese
578ffec2da SGText: minor typo correction 2021-12-22 23:39:44 -06:00
Henning Stahlke
d448ad4eb3 simgear/scene/model/SGLight.cxx: listen to entire /scenery/lights subtree.
Set VALUE_CHANGED_DOWN attribute on /scenery/lights so that listeners see
changes to all nodes in subtree.
2021-12-22 21:13:15 +00:00
Erik Hofman
9a9b1a8db4 Revert 1269a8d27c, the friction factor on ice relies on too many parameters to calculate here. 2021-12-22 08:24:51 +01:00
Erik Hofman
1269a8d27c Introduce a factor for when the lakes are frozen over and use it to alter the fricton factor, bumpiness and load resistance factor 2021-12-21 10:30:30 +01:00
Erik Hofman
612dff2ea1 Remove a stale character 2021-12-19 11:20:46 +01:00
Erik Hofman
33b0c39dbd Make it possible to use a property reference for the solid property of a material. e.g.: <solid><property>/sim/ice</property></solid> 2021-12-19 11:18:49 +01:00
Stuart Buchanan
06ecfe1927 WS30: Revert to green channel for texture atlas 2021-12-18 21:45:50 +00:00
James Turner
db5a2353bd FFmpeg: tweak components we use 2021-12-12 19:48:54 +00:00
James Turner
dd61ad8bd0 FFmpeg Cmake support for video recording 2021-12-12 18:32:01 +00:00
Julian Smith
5627b135b4 simgear/screen/: added support for video encoding.
Uses ffmpeg libraries to provide video encoding of an osg::GraphicsContext
(which could be for Flightgear's main window) to file.

The video codec is specified as a string at runtime. Success depends on what is
supported by the system's ffmpeg installation.

Handling of resize doesn't always work. We finish current stream and create a
new encoder and continue. Works ok with mpeg2, but with more modern codecs vlc
usually fails to handle the change.

We call the encoder on a separate thread to avoid latency.

If SG_FFMPEG is not defined, we don't make calls to ffmpeg libraries and
VideoEncoder class's constructor always throws an exception.
2021-12-08 10:31:27 +00:00
Stuart Buchanan
0e13e48123 WS30: Improved material Uniforms 2021-12-05 13:45:01 +00:00
b'James Turner
922ad8d2e7 Merge /u/r-a-sattarov/simgear/ branch next into next
https://sourceforge.net/p/flightgear/simgear/merge-requests/103/
2021-11-29 10:18:36 +00:00
Stuart Buchanan
8a014df26d WS30: Improved atlas with multi-texture support.
- Prefix all WS30 Uniforms with "fg_"
- fix modelOffset (needs to be passed in as a float)
- Create a true atlas with indexes for relevant material textures
2021-11-28 19:28:54 +00:00
r-a-sattarov
21e9bf4678 nasal/naref.h: added e2k endianness (MCST Elbrus 2000) 2021-11-24 23:52:58 +03:00
r-a-sattarov
f364aedf96 math/simd.hxx: fix build by MCST lcc compiler when using ENABLE_SIMD_CODE=ON
MCST E2K (Elbrus 2000) - this is VLIW/EPIC architecture, like Intel Itanium (IA-64) architecture.

e2k architecture has half native / half software support of most Intel/AMD SIMD
e.g. MMX/SSE/SSE2/SSE3/SSSE3/SSE4.1/SSE4.2/AES/AVX/AVX2 & 3DNow!/SSE4a/XOP/FMA4

Ref: https://en.wikipedia.org/wiki/Elbrus_2000
2021-11-23 22:26:33 +03:00
Stuart Buchanan
fee4481ef6 WS30: Add zUpTransform and modelOffset Uniforms. 2021-11-19 22:05:47 +00:00
James Turner
6562546771 Nasal Math: add precision to floor(), add trunc()
To simplify various rounding / truncation operations, especially when
dealing with frequency values, give floor() the same precision control
already present in math.round(), and add math.trunc() which always 
truncates towards zero.
2021-11-16 10:59:01 +00:00
Julian Smith
ddea2de3a0 simgear/nasal/codegen.c: avoid compiler warning in findConstantIndex(). 2021-11-12 23:03:47 +00:00
Julian Smith
5ce5044dce simgear/scene/tgdb/VPBTechnique.*: fix a clang sign-comparison warning.
Also removed unnecessary initialisation of _fileName to "".
2021-11-12 22:58:56 +00:00
Julian Smith
067875ab93 simgear/scene/util/OrthophotoManager.cxx: added missing break statement. 2021-11-12 22:58:51 +00:00
Julian Smith
7cd5d5312e simgear/props/props.hxx:SGPropertyNode: removed ununsed debug state for locking. 2021-11-11 21:07:09 +00:00
Stuart Buchanan
0470375889 WS30 Uniform arrays and photoscenery search path 2021-11-10 22:57:08 +00:00
Stuart Buchanan
2ec9df7597 Fix compile error on MacOS 2021-11-09 22:10:26 +00:00
Stuart Buchanan
6be17cc9e8 WS30: Add photoScenery Uniform for orthoscenery 2021-11-09 18:13:16 +00:00
Stuart Buchanan
9528bd0749 WS30: Photoscenery code cleanup, reduce log spam 2021-11-07 09:16:45 +00:00
Stuart Buchanan
7a7b26e75d WS30: Initial photoscenery work
Hack for hackathon
2021-11-06 14:42:23 +00:00
Stuart Buchanan
6ea99e43f1 WS30: Use NEAREST_MIPMAP_NEAREST for landclass
Only for the MIN filter, as the MAX filter causes
significant interpolation issues.
2021-11-05 01:12:01 +00:00
Stuart Buchanan
1553ac2e17 WS30: Minor cleanup and run generators for ALS (If required) 2021-11-04 21:44:01 +00:00
Fahim Imaduddin Dalvi
419e9bc128 WS30: Fix random lights density
Earlier calculations assumed degrees instead of radians for the
granularity of random lights, resulting to the wrong density. This
is now fixed. The scanline for random lights is also more efficient
now, taking the lower limit of light-coverage into account.
2021-10-30 13:07:35 +03:00
Stuart Buchanan
a1d748a0de WS30: Fix filtering of texture atlas
Previously we were taking the nearest pixel from the nearest
mipmap.  Which was braindead.  Now just use the OSG defaults,
which are NEAREST_MIPMAP_LINEAR for MIN and LINEAR for MAX.

Thanks to Julian and Henning for helping diagnose this on
the weekly hangout.
2021-10-24 21:25:08 +01:00
Stuart Buchanan
7916dfb61d WS30 Move VPB tile loading to the tile manager
Previously VPB tiles were loaded by the STG file handler.
Now they are loaded directly by the tile manager, allowing
better management of tile loading.
2021-10-20 23:37:59 +01:00
b'Fernando Garc\xc3\xada Li\xc3\xb1\xc3\xa1n
fc1d02110c Merge /u/amalon/simgear/ branch vr_5 into next
https://sourceforge.net/p/flightgear/simgear/merge-requests/100/
2021-10-20 22:21:01 +00:00
Fahim Imaduddin Dalvi
6e7fa6b139 WS30: Generic Materials handler and Random tile lights
This commit implements a generic materials handler providing an easy way to
extend the efficient landclass scanning code for new material-specific
processing like trees, random lights, random buildings etc. The existing
vegetation code has been ported to make use of this generic interface,
and random tile lights have been added as well. Detailed commit log can
be found at [1], discussions can be found at [2] and [3].

[1] https://sourceforge.net/u/fahimdalvi/simgear/ci/feat/ws30_random_lights/~/tree/
[2] https://sourceforge.net/p/flightgear/mailman/flightgear-devel/thread/AC818EC5-84A3-425B-98CB-352CCB0B8910%40gmail.com/#msg37356997
[3] https://sourceforge.net/p/flightgear/simgear/merge-requests/99/
2021-10-21 00:34:32 +03:00
James Turner
6d71ab75b2 METAR: Remove duplicate lines from manual merge
Thanks to Tobias Dammers for pointing this out.
2021-10-20 13:16:31 +01:00
Richard Harrison
148ba367ee Material animation include model directory
Include model directory in the texture path - to allows short paths relative to model root when set via a texture-prop
2021-10-18 11:40:25 +02:00
Richard Harrison
7ac90850d3 Fix axis object in translate animation
This will allow an object to be moved using a line (with 2d points).

Use the factor to switch direction (direction will depend on the order of definition of the end points of the vertex and) together with a (usually normalised property to define how much of the translation to apply).

<animation>
    <type>translate</type>
    <object-name>mm_radios-display</object-name>
    <property>/sim/model/f-14/radio-position-norm</property>
    <factor>-1</factor>
    <axis>
        <object-name>mm_radios-display-alt-position-axis</object-name>
    </axis>
</animation>
2021-10-18 11:40:25 +02:00
James Turner
bf1db210d7 SGMetar: avoid raw char pointers in the public API
Ideally would refactor to remove the raw pointers internally, but this
is a good first step.
2021-10-15 15:31:06 +01:00
James Turner
6fe7c307b2 SGmetar: catch bad temp/pressure data and throw
Also replace raw pointer with managed storage for the raw data, to
avoid manual clean-up on exception-throw paths.
2021-10-15 12:12:51 +01:00
Stuart Buchanan
119f3d9814 WS30: Remove VPB Max range and LoD scaling
Better to scale from the camera than mess with the LoD itself.
2021-10-12 21:40:09 +01:00
James Hogan
0c4c092b9f Sky dome: Enable depth test but mask depth changes
On VR with visibility masking the depth buffer is first set to the
nearest possible value in parts of the frame that won't be visible
through the VR headset's lenses. This is meant to reduce GPU fragment
load.

The sky dome however is rendered with depth testing disabled which
bypasses the visibility masking. To allow invisible parts of the sky
dome to be culled, enable depth testing but set the depth mask to false
to prevent modification of the depth buffer.
2021-10-08 23:36:15 +01:00
Stuart Buchanan
a760730285 WS30: +50% fps by not loading tiles every loader
Previously the STG Loader had a class member keeping track
of each WS30 tile that had been loaded, to ensure the terrain
was only loaded once.

However, this was a class member on a loader, and we have multiple
OSG loading threads.  So the WS30 terrain was loaded ~6 times.

Change to a static, protected with a mutex so we only load the tile
once.

50% improvement in fps from the reduction in vertices, and an
improvement in loading.
2021-10-08 20:55:06 +01:00
b'Fernando Garc\xc3\xada Li\xc3\xb1\xc3\xa1n
f7e378a05a Merge /u/amalon/simgear/ branch vr_3 into next
https://sourceforge.net/p/flightgear/simgear/merge-requests/98/
2021-10-08 14:16:34 +00:00
Julian Smith
50170da13d simgear/scene/model: expose some animation info for use by Highlight system.
simgear/scene/model/animation.*: added TransformExpression() - returns SGExpressiond
if given a SGRotAnimTransform or SGTranslateTransform.

simgear/scene/model/SGTranslateTransform.hxx:SGTranslateTransform: added copy
of SGExpressiond for use by TransformExpression().
2021-10-05 22:54:52 +01:00
Stuart Buchanan
e7cca0c407 WS30 - Line feature texturing 2021-10-01 22:03:47 +01:00
Stuart Buchanan
0f946abc36 WS30: Correct texture coords for roads 2021-09-28 21:38:16 +01:00
James Hogan
1d0a99a077 Add LEFT & RIGHT nodemask bits
Add LEFT_BIT and RIGHT_BIT node masks, which are only shown on the left
or right viewports. These will be used for eye specific visibility masks
with VR.
2021-09-18 08:27:24 +01:00
James Hogan
d4496d3b2c Compositor: Add resetOrderOffset()
To allow for custom compositors and passes created by C++ code alongside
those created by Compositor::create(), add a resetOrderOffset() function
which resets _order_offset back to zero. This will allow FlightGear to
prevent repeated compositor reloads from increasing _order_offset
indefinitely, which soon results in render orders beyond those set
statically for the GUI and upcoming VR mirror compositors.
2021-09-11 16:32:18 +01:00
Julian Smith
a68a0b1ccb simgear/props/props.cxx: fixed deadlock in SGPropertyNode::addChildren().
Was causing fatal "Resource deadlock avoided" error with crj700.
2021-09-05 15:55:37 +01:00
Fernando García Liñán
876e5534fd Fix precision issues on shadow mapping 2021-09-02 02:23:05 +02:00
Fernando García Liñán
0ee08cfa06 Compositor: fg_Viewport now contains the viewport properties of the specific pass it's being used on 2021-08-31 18:09:36 +02:00
Fernando García Liñán
da750c5995 Canvas: Set pointers to NULL instead of calling .release()
The Canvas camera and texture get recreated in several circumstances.
Calling .release() on a ref_ptr will just return the raw pointer and
'delete' won't be called. The proper way to explicitly delete an object
managed by a ref_ptr is to set the ref_ptr to NULL. This will delete it
as long as it's not referenced by any other ref_ptr.
2021-08-31 18:09:36 +02:00
Fernando García Liñán
2371065375 Canvas: Image depth refers to the amount of depth slices, not the bit depth 2021-08-31 18:09:36 +02:00
Stuart Buchanan
5c4bbc7552 WS30: Improved streetlights
- Use a single LightBin per tile, rather than per road
- Support lights offset on either side of the road.
2021-08-29 18:27:18 +01:00
Fernando García Liñán
a97e148a94 Canvas: Change the node mask of the ODGauge camera
Since the Canvas cameras are no longer in the scene graph, we no longer
need to explicitly make them render only in the Classic pipeline's far
camera.
2021-08-27 21:21:28 +02:00
James Turner
e76b684c20 Attempt to deal with the XML -> AC model rename
Add a fallback when a .xml model is not found, and see if we can load
a .ac instead. This logs a dev warning since dependant uses should
be updated.
2021-08-27 15:33:33 +01:00
Julian Smith
629b681a29 simgear/nasal/code.c:setupFuncall(): improve diagnostic if not callable.
If we have an uncallable object error, also show the type and value of the
uncallable object.

To make this work, have upgraded simgear/nasal/lib.c:dosprintf() to be globally
available. Could perhaps rename it and declare in a different header. But it's
C so we don't want to make it part of simgear's general utility functions.
2021-08-26 23:24:39 +01:00
Julian Smith
624581f470 simgear/nasal/code.c:logError(): simplified the code. 2021-08-26 23:24:39 +01:00
Julian Smith
d4701c309b simgear/nasal/code.c: naRuntimeError(): added disabled code to show info. 2021-08-26 23:24:39 +01:00
Fernando García Liñán
2c82cd4475 glTF: Remove separate occlusion texture 2021-08-27 00:06:47 +02:00
Julian Smith
d7dd7e2c6e 3rdparty/tiny_gltf/tiny_gltf.h: fix for OpenBSD - no wordexp.h. 2021-08-25 23:10:03 +01:00
Fernando García Liñán
6d891eae7e Compositor: Add missing #define for buffer format 2021-08-23 22:29:24 +02:00
Fernando García Liñán
81fb4e7dfd Compositor: Add extra buffer formats
These formats are not defined by OSG, so we manually define them. Some GPUs might not support them as we are using a GL compatibility context, but it shouldn't matter for now as they are only being used by the HDR pipeline.
2021-08-23 12:45:55 +02:00
Stuart Buchanan
fafa259c1d WS30: Lighting for roads
Using attributes on the LINE_FEATURE_LIST we now generate
lighting for roads.
2021-08-21 17:18:18 +01:00
Erik Hofman
1174124144 Michael Danilov: Fix issue #2169 Sound with condition=false will play when moving into its max-dist (patch available) 2021-08-20 11:47:03 +02:00
Stuart Buchanan
e7659941ef WS30: Better landclass cache for tree generation 2021-08-19 19:57:09 +01:00
Fernando García Liñán
b5d78f7c1d Fix typo 2021-08-19 14:04:25 +02:00
Fernando García Liñán
ab1d7792bd Compositor: Add another precomputed uniform for the skydome shader 2021-08-19 13:08:14 +02:00
Fernando García Liñán
6cea6b7fdf Add support for glTF transparent objects
Also added some Compositor uniforms.
2021-08-19 01:40:24 +02:00
Fernando García Liñán
2b9933c0b5 Remove explicit LINKER_LANGUAGE when compiling TinyGLTF 2021-08-17 12:01:54 +02:00
Fernando García Liñán
6d3089ad6b Compositor: Add the LOD scale parameter to scene passes
This should allow us to change the LOD level for WS 3.0 on a per-pass basis.
2021-08-16 17:02:21 +02:00
Fernando García Liñán
910225532e Initial support for glTF models 2021-08-16 17:00:57 +02:00
Fahim Imaduddin Dalvi
65483a373f Shader-based scenery lights.
This commit implements shader-based scenery lights with support for
efficient rendering of a large number of lights, animations and
directionality. Detailed commit log can be found at [1]. Detailed
discussions can be found on the mailing list [2][3][4].

[1] https://sourceforge.net/u/fahimdalvi/fgdata/ci/feat/scenery-shader-lights/~/tree/
[2] (Timed animation stops working in certain configurations) https://sourceforge.net/p/flightgear/mailman/flightgear-devel/thread/4A7AC359-63B3-4D8A-815B-09823BCEFF27%40gmail.com/#msg37095923
[3] (Shader-based scenery lights) https://sourceforge.net/p/flightgear/mailman/flightgear-devel/thread/63E3C131-7662-4F59-B2E6-03208C78EF96%40gmail.com/#msg37190517
[4] (Shader-based scenery lights Part 2) https://sourceforge.net/p/flightgear/mailman/flightgear-devel/thread/74F18179-CA34-4901-A44E-15498ECC230A%40gmail.com/#msg37331695
2021-08-07 21:47:56 +03:00
James Turner
67806a59b0 Fix a dumb crash I introduced. 2021-08-04 09:08:16 +01:00
Stuart Buchanan
578a8acff4 WS30: Improve tile loading times by ~50%
Previously on my system, generating vegetation for a given tile
took 0.15-0.2s (for ~ 56k positions), of ~0.4s.  While this is done in a
separate loading thread, the sheer number of tiles being loaded
caused noticeable delays and popping of higher LoD tiles.

As a tile at the highest LoD is typically 6x6km, and vegetation
is generated on a scanline of individual triangles, there is a _lot_
of temporal locality on the landclass of a series of points.

By caching the material information required from the landclass lookup
we can avoid a whole much of material lookups for each successive
vegetation point.

On my system this reduced the time to generate vegetation down to
0.02s per tile, and total tile generation time down to ~0.2s.
2021-08-03 20:56:56 +01:00
Julian Smith
e93839a9c5 simgear/environment/visual_enviro.cxx: fixed include of simgear/math/sg_random.hxx. 2021-08-03 09:20:35 +01:00
Julian Smith
ded91614ab simgear/debug/logstream.cxx: enable file:line on startup if SG_LOG_FILE_LINE is 1.
E.g. allows file:line in diagnostics when running test-suite.
2021-08-02 21:04:29 +01:00
Stuart Buchanan
d1e9134a89 WS30: Improved vegetation constraints
Unlike the elevation constraints, the vegetation constraints
don't need to be global.  So no need for mutexes.  Big speed up.
2021-08-02 17:47:48 +01:00
Stuart Buchanan
8cc3c15712 WS30: Stop trees from growing on roads, rivers. 2021-08-02 17:10:49 +01:00
Stuart Buchanan
dc1d6284fd WS30: Fix crash on reset caused by VPBTechnique 2021-08-01 20:48:27 +01:00
Stuart Buchanan
4f01f758ae WS30: Fix deadlock introduced by fb436be8f1 2021-08-01 20:47:38 +01:00
Fernando García Liñán
2039f49691 Add missing call to glReadBuffer() when doing depth-only FBOs 2021-08-01 08:35:25 +02:00
James Turner
d8874c26b6 Control over reporting from SimGear
To avoid exposign Sentry to Simgear, add some abstract reporting controls
which can be toggled easily without any extra dependencies.
2021-07-31 18:31:10 +01:00
legoboyvdlp R
b44f187328 Canvas: instead of setting anisotropy directly, set it by the same mechanism as mipmapping 2021-07-31 15:27:36 +01:00
Julian Smith
3ba8c383b4 simgear/io/HTTPRepository.cxx: fixed some compiler warnings. 2021-07-31 10:29:25 +01:00
Julian Smith
f9b485a915 simgear/package/Package.cxx: removed assert that cannot fire due to unsigned.
This avoids a compiler warning.
2021-07-31 10:29:25 +01:00
Julian Smith
109da4eb49 simgear/environment/metar.cxx: fix use of std::string::rfind().
Need to compare result with std::string::npos, not for -ve.
2021-07-31 10:29:25 +01:00
Julian Smith
0da173cfd8 simgear/nasal/lex.c: show line and column if illegal character is found.
Makes it easier to track down e.g. missing quotes in Nasal source within .xml
files.
2021-07-31 10:29:25 +01:00
Julian Smith
95239fea87 simgear/io/iostreams/zlibstream.*: improved support for reading compressed data.
Added support for seeking (forwards only) - in ZlibAbstractIStreambuf, added
seekoff().

Also disabled assert that checked that we reach EOF compressed data at same
time as EOF uncompressed data; was breaking things when using embedded
compressed streams within fgtape recording.

Added ZLibCompressionFormat::ZLIB_RAW, uses windowBits=-15, for zlib compressed
streams without header or trailer.

Fixed clang build error with std::min().
2021-07-31 10:29:25 +01:00
James Turner
d01e9ca2e6 Use owning refs in some places
Avoid explicit deletes of ref-counted SGMaterialCache
2021-07-29 17:51:35 +01:00
James Turner
fb436be8f1 MaterialLib: make it thread-safe 2021-07-29 17:51:03 +01:00
James Turner
9e3e4a1ab5 TileDetails: set group names for debugging 2021-07-29 17:50:33 +01:00
James Turner
d6e452ea08 Fix a ref-count loop in Paticles manager 2021-07-29 17:50:33 +01:00
Fernando García Liñán
67bb39083c Fix shadows on Mac OS 2021-07-29 15:48:55 +02:00
Fernando García Liñán
df66decdda Compositor: Replace OSG camera resize function by own implementation 2021-07-29 08:38:18 +02:00
Fernando García Liñán
7f4fb15636 Compositor: Change uniform enum names to avoid name clashing on Windows 2021-07-28 15:18:21 +02:00
Fernando García Liñán
db8b66203d WS 3.0: Apply the TERRAIN_BIT nodemask to all geodes 2021-07-28 10:50:14 +02:00
James Turner
1d59135652 Report errors on TileDetails callback failures
This callback can do out of memory and other failures, so catch
those and report them.
2021-07-27 16:05:03 +01:00
James Turner
2478bee97f Don't report PropsIO exceptions 2021-07-27 14:23:09 +01:00
Fernando García Liñán
a256110c02 Compositor: Do not clear buffers by default 2021-07-26 16:14:58 +02:00
Fernando García Liñán
908dc467a8 Compositor: add new uniforms
Provide the sunlight direction in view and world space and the near/far distance given by the CameraGroup.
2021-07-26 12:04:56 +02:00
Fernando García Liñán
420555c69c Fix issue with Effect techniques that have the highest index and a scheme
We previously used the last technique, but now we use the last technique that has no scheme.
2021-07-24 19:47:09 +02:00
Fernando García Liñán
d85205212a Compositor: Attach color and depth render buffers by default 2021-07-24 19:19:44 +02:00
Fernando García Liñán
a83048bc37 Remove another problematic buffer format 2021-07-24 13:41:29 +02:00
Fernando García Liñán
4ee1d820ba Remove the GL_R11F_G11F_B10F image format 2021-07-24 07:02:20 +02:00
Fernando García Liñán
b3b863a3c4 Preliminary changes for the HDR pipeline
- Add an Effect to stars and planets so they don't disappear when not using the fixed-pipeline.
- Allow usage of the shadow mapping related uniforms in 'quad' passes as well.
- Add extra buffer formats (some of them only work under the core profile).
- Better handling of mipmapping in the Compositor.
2021-07-23 06:43:08 +02:00
James Turner
877c3a68e6 Optimise sidereal_course performance
Avoid calling into sgTimeGMT (which calls into the C library)
every single update.
2021-07-21 22:54:11 +01:00
James Turner
5f334d3839 ModelRegistry: Special case empty file names
Related to ticket:
https://sourceforge.net/p/flightgear/codetickets/2609/
2021-07-21 22:53:12 +01:00
James Turner
999e499ce5 Nasal Hash: add isNil wrapper 2021-07-12 09:29:52 +01:00
James Turner
7db6651970 Fix Cyclone-DDS test linkage 2021-07-12 09:29:10 +01:00
James Turner
b50d8e38e6 Error reporting for animations / conditions
Don’t report errors for each condition parse failure, but do 
aggregate them at the animation level in ReaderWriterXML

Sentry-Id: FLIGHTGEAR-DD
2021-06-26 16:27:22 +01:00
James Turner
069483e6d0 Add try/catch wrappers in SGSubsystemGroup
Attempt to narrow down the source of some fatal exceptions we see
on Senty, which occur during init/startup. All these blocks re-throw
so user behaviour is unchanged, but we’ll log the name of the subsytem.
2021-06-23 13:26:40 +01:00
James Turner
820b76d894 Fix deadlock on quit for Linux 2021-06-22 16:25:41 +01:00
Stuart Buchanan
bbdc9f2318 WS30: Adjust based vegetation density
Previously, by observation comparing actual vegetation density
on Medium, WS30 had many more trees than WS20.

This adjusts the base vegetation density down to match WS20.

Note that at High and Very High densities, there is still a disparity
that needs to be addressed.
2021-06-19 18:11:49 +01:00
James Turner
a49619fa6c TerraSync: add another ‘is downloading’ helper 2021-06-18 09:34:30 +01:00
James Turner
59307e9ba2 Emesary: allo main loop recipient shutdown 2021-06-17 15:53:16 +01:00
James Turner
c279557d32 Attempt to fix realpath() recursion
Sentry-Id: FLIGHTGEAR-D6W
2021-06-14 13:52:22 +01:00
James Turner
84eda17958 Make out-of-memory in computeHash fatal 2021-06-14 12:10:47 +01:00
James Turner
9ec9d8e423 TerraSync: set scenery path suffixes explicitly 2021-06-11 10:00:54 +01:00
Stuart Buchanan
1a6bf3c284 WS30: Don't defer reading of line features
Previously, reading LINE_FEATURE_LIST/AREA_FEATURE_LIST/COASTLINE_LIST
files were not read with the .stg file, but deferred into the
DelayLoadReadFileCallback.  When the the Callback was executed, the
files were read and appropriate terrain tiles dirtied for regeneration.

However, re-generating dirtied tiles caused significant frame pauses
and was disabled in commit
deb802f74a

This meant that the Line/Area/Coastline features would only be rendered
when the next LoD tile was generated.  Which created a race condition
on startup for the tile the user starts on, between the
DelayLoadReadFileCallback and the tile itself.

This commit reads these files at the same time as the initial terrain
so that the VPB has all the data required when the tile is initially
rendered.  The downside is that line data is read for every tile,
even if it is far away.  As the line data is stored as a series of
lat/lon floats, this is assumed to be OK.

An alternative would be to re-instate the Visitor, and instead
of dirtying existing terrain, generate the roads, and flag them to
the UpdateVisitor to add to the terrain node.
2021-06-06 22:10:52 +01:00
Julian Smith
16778e5c02 simgear/props/props_test.cxx: use VALUE_CHANGED_DOWN to make tests pass.
This checks old behaviour works. Need to add tests of the new default behaviour
where property changes do not call parent nodes' listeners.
2021-06-03 23:12:58 +01:00
Julian Smith
087d04db8e simgear/canvas/Canvas.cxx: Canvas::Canvas(): mark tree with VALUE_CHANGED_DOWN.
This is required for canvas to work - relies on value-changes being visible to
higher nodes.
2021-06-02 22:19:21 +01:00
Julian Smith
f8b5e6ab81 simgear/props/props.*: Modification to calling of listeners when property values change.
We now default to not calling parent nodes' listeners when a node's value
changes.

This avoid overheads introduced by recent addition of locking - walking up the
parent nodes needs to lock/unlock at each step, and was previously happening
whenever any node in the entire tree had its value changed, causing noticable
slowdown.

Node creation/removal still calls parent nodes' listeners as before.

If a node has new attribute VALUE_CHANGED_UP set, we do call its parent node's
listeners.

New SGPropertyNode::Attribute's VALUE_CHANGED_UP and VALUE_CHANGED_DOWN:

    VALUE_CHANGED_UP: if set, when fireValueChanged() is called we also call
    our parent node's fireValueChanged().

    VALUE_CHANGED_DOWN: if set, new and existing child nodes have their
    VALUE_CHANGED_UP and VALUE_CHANGED_DOWN attributes set.

    Once set, these attributes cannot be cleared (because to correctly handle
    this would require reference counting).

SGPropertyLockControl(): added parent_listeners arg. If true, we always call
parent node's fireValueChanged() when a node value changes; this restores
previous property system behaviour. Default is false.

Extra overall timing diagnostics.
2021-06-02 22:19:21 +01:00
Julian Smith
c9051cedca simgear/props/props.cxx: fixed bug in SGPropertyNode::removeChild().
Don't set node->_parent to null before calling
SGPropertyNodeImpl::fireChildRemoved().

This fixes problem with Jaguar-GR1 HUD.

[Should probably set node->_parent to null before returning, but previous
(non-locked) code didn't do this, and it would require acquiring mutex.
2021-05-29 23:14:02 +01:00
James Turner
f74ba148ab Precomputed random numbers API
Use precomputed tables to give stable random numbers : replaces previous
recompuation when we exhaust the RNG pool.

By Marc Eberhard
2021-05-25 12:53:36 +01:00
Fernando García Liñán
e7fbf83155 Compositor: Allow changing the implicit buffer attachments 2021-05-24 23:49:45 +02:00
James Turner
26995ba13b Raise minimum OSG version to 3.6 2021-05-24 16:47:56 +01:00
James Turner
bd6a18bb96 CMake: set OpenGL VND policy to NEW to see if it works
OLD is causing shouty warnings from CMake, let’s see what happens if
we try for NEW.
2021-05-24 12:40:32 +01:00
James Turner
8d0d1f9047 Props changes: fix a link error with Clang 2021-05-24 12:40:32 +01:00
Stuart Buchanan
e91c06223a WS30: Reduce log spam
Previously blank lines in the various .txt LIST files
created spurious error logging.  This commit does some
simple length checking and ignore blank lines rather than
complaining (and then ignoring).
2021-05-23 21:25:16 +01:00
Julian Smith
0b6678f745 simgear/structure/SGSharedPtr.hxx: reformatted to make it readable. 2021-05-23 08:10:57 +01:00
Julian Smith
46e79aba11 simgear/math/simd4x4.hxx: avoid -Wdeprecated-copy warnings.
Added simd4x4_t::operator=().
2021-05-23 08:10:57 +01:00
Julian Smith
0f78bcaa49 simgear/props/props.*: various debugging/diagnostics additions to property locking.
Added runtime control of property locking active, and lock contention
diagnostics; new SGPropertyLockControl() allows associated property nodes to be
registered.

Added code to measure time spent locking/unlocking; disabled via preprocesor by
default because gives small decrease in fps even when disabled at runtime.

If SG_PROPS_UNTHREADSAFE is defined we defer to the old property code at build
time (requires old files to be available as props-unsafe.{hxx,cxx}). This
facility will hopefully be be removed at some point, but for now makes it
easier to compare before/after speed.
2021-05-23 08:06:02 +01:00
Julian Smith
f1dd7901cb simgear/props/props.*: added locking using read/write mutex.
Added a std::shared_mutex to SGPropertyNode and changed all props code to use
shared or exclusive locks as necessary whenever reading/writing data.

SG_PROPERTY_LOCKING=0 or 1 can be used to control whether locking is
active. Default is 1.

SG_PROPERTY_LOCKING_VERBOSE=0 or 1 can be used to cause diagnostics to be
generated if we get lock contention. Default is 0.

Removed most of the inline implementation code in props.hxx - now that we use
locking, nearly all calls eventually end up in props.cxx in order to take out
a lock so there's no point inlining. For template code this also means that we
now explicitly instantiate / specialise in props.cxx.

Reformateed props.hxx to use consistent indentation. Also condensed identical
comments for related methods such as getBoolValue(), getIntValue() etc, which
results in more readable visual grouping.

Much of the internal implementation code for SGPropertyNode is now in the form
of static methods in a new SGPropertyNodeImpl class in props.cxx. This class is
marked as a friend of SGPropertyNode in props.hxx so these methods can access
all SGPropertyNode internal data without being declared in props.hxx. So one
can change implementation code without recompiling everything.

Removed TEST_READ and TEST_WRITE macros.

Removed SGPropertyNode::MAX_STRING_LEN - was only used in compare_strings() and
it is unnecessary.
2021-05-22 23:52:36 +01:00
Fernando García Liñán
64e4adf0b9 Fix osgText issues under OSG 3.6
It looks like assigning an Effect to the geode containing the osgText is
enough and there aren't any conflicts with OSG own shaders. This might
change in the future if the switch to the core profile happens.

The text shaders also rely on fixed pipeline features like
gl_FrontColor. This is because aircraft developers are used to using
material animations to change the text color.
2021-05-14 22:47:28 +02:00
Stuart Buchanan
d0f4e9018c WS30: Fix regression of lakes
Fix regression that stopped lakes from being generated.
2021-05-12 21:36:11 +01:00
Stuart Buchanan
81b93cffbb WS30 - Minor roads and coastline improvements
- Correct normals on line features and coastlines
- Ignore coastline segments < 10m
- Clean up logging.
2021-05-08 20:46:38 +01:00
Stuart Buchanan
b6c4245b35 WS30: Don't compress landclass textures
Previously landclass textures were compressed by
out internal optimizer.  This caused bad artifacts
on landclass boundaries, e.g. where landclass 1 met
landclass 10 there would be compression/interpolation
artifact with a value of (say) 5.

This disables compression for such landclass textures.
2021-05-08 15:44:38 +01:00
James Turner
51bf76846c Thread-safe error reporting in lowlevel.cxx
Use an exception rather than polling a flag, for checking errors
during BTG reading. This should allow us to give a correctly
identified error, at exactly the point the read fails.
2021-05-03 16:22:24 +01:00
Stuart Buchanan
fc93788ab1 WS30: Initial coastlines 2021-05-03 15:43:59 +01:00
Richard Harrison
8464ef48e8 Fixes #2579 Emesary segfault on reset.
Need to call OnDeregister before the object is deleted (because not using smart pointers for receivers).
2021-05-02 17:35:24 +02:00
James Turner
5e30d83a43 Error-reporting: improve reports for STGs and effects
When an effect defines no shader sources, special case this error to
avoid confusing result from SGProgram.

Add error-context for readNode STG loading, so failures inside an
STG can be attributed
2021-04-30 13:47:34 +01:00
Fernando García Liñán
0299764619 Remove unsupported buffer format 2021-04-29 13:03:29 +02:00
Fernando García Liñán
ccebbc4bb3 Compositor: Move cull mask setter to a separate function 2021-04-29 12:29:35 +02:00
James Turner
fa40a6d1b8 Error reports: default to SG_LOG(SG_ALERT
When no callback is registered, just fall back to a plain SG_ALERT
2021-04-23 12:46:48 +01:00
James Turner
ede4484b8d Particles: guard against duplicate init 2021-04-23 12:46:20 +01:00
James Turner
2871a2df85 Effects: better error reporting 2021-04-21 21:55:04 +01:00
James Turner
d521625307 Asan: fix leaks in Catalog code 2021-04-21 21:54:45 +01:00
James Turner
1304624f30 ASan: fix a leak in GZ extraction 2021-04-21 21:53:56 +01:00
James Turner
83b58b68ae HTTP tests: fix an ASan warning. 2021-04-21 12:45:56 +01:00
James Turner
f9f5977cca NasalEmeserayInterface to an explicit pointer.
Also move to its own file, and give it a real header so it can be
directly initialised. (Requires corresponding FlightGear commit)
2021-04-21 12:45:42 +01:00
Richard Harrison
2690fadca1 Emesary IReceiver no longer shared ptr.
The use of SGShared for IReceiver derived conflicted with other uses of SGShared / SGReferenced - and after consideration transmitters should probably remain static for the lifetime of the application.

Any dynamic transmitters will need careful consideration if working in a threaded environment to ensure that a transmitter doesn't go out of scope before any notifications that it has issued have finished being processed by other threads.
2021-04-16 21:13:13 +02:00
Erik Hofman
41d06ee092 IReceivers are shared pointers now 2021-04-16 14:30:46 +02:00
Erik Hofman
c85f29c8d1 Converting a static variable into a shared_ptr is a bad idea, start with a shared_ptr from the start 2021-04-15 11:42:24 +02:00
Erik Hofman
e0d7a92eba Fix a bunch of compiler errors 2021-04-15 10:05:22 +02:00
Erik Hofman
93299bf191 Fix a compiler warning: not defining a virtual destructor results in undefined behavior 2021-04-15 10:05:05 +02:00
Erik Hofman
986867f5c5 Make size_t available 2021-04-15 10:04:00 +02:00
Erik Hofman
bcfff2a967 Bi-directional I/O using Data Distribution Services requires a separate reader and writer. 2021-04-15 09:45:17 +02:00
Richard Harrison
9b3265c46c Emesary: lock free performance improvements
After testing with multithreading there were still problems related to
scope and transmitters - because a transmitter that was on the stack
as an object could go out of scope before a notify all had finished
and lead to invalid data and a crash

The solution is to always have Recipients allocated via new() and to
use a shared pointer to manage the scope and garbage collect when the
last reference goes out of scope.

To achieve the threadsafe minimal locking the rules are as follows;

* All recipients must be allocated via new()
* Register and DeRegister will only happen when on the outermost
  level of NotifyAll.
 - all other add or delete will be put into the pending queue and
   added at the start of the next outer notify all
 - at outer level notify all a lock will be taken to process pending
   items
* during the main notify processing there will be no locks - however
  it is also assumed that the recipient list will not be changed
2021-04-11 00:42:49 +02:00
Richard Harrison
739c76e862 Win32 console; added method to ignore errors
This is mainly for standalone FGCOM - because the error message is always shown because it is a console app and --console isn't required.
2021-04-08 21:57:31 +02:00
Erik Hofman
9ae26d7f80 Get the GUID from DDS and store it for future use. Which coul be handy for point-to-point connections over DDS. 2021-04-07 11:51:32 +02:00
James Turner
89271e85a0 Shaders: report all shader file paths
When reporting a shader log error, include all the shader file
paths and the effect path in the detailed error information.
2021-04-05 12:06:55 +01:00
Erik Hofman
e4c214578b Allow parsing a DDS configuration file. Add a guard condition to wake up the waitset at exit. 2021-04-05 12:38:13 +02:00
Stuart Buchanan
769e00ffdf WS30: AREA_FEATURE_LIST STG verb - lakes, lochs
- Add and AREA_FEATURE_LIST STG verb.
- /sim/rendering/static-lod/area-features-lod-level to control point at
  which such feature are rendered
- /sim/rendering/static-lod/lod-leve[n]/area-features-min-width sets
  the minimum width for feature rendering at that LoD level.

STG Format:

AREA_FEATURE_LIST <file> <material>

File format:

Area Attrib A B C D lon0 lat0 lon1 lat1 lon2 lat2 lon3 lat4....

where:
 Area is the area of the feature in m^2
 Attrib is an integer attribute (currently unused)
 A, B, C, D are generic float attributes.  Their interpretation may vary by feature type
 lon[n], lat[n] are pairs of lon/lat defining straight road segments
2021-04-04 16:25:04 +01:00
James Turner
5f026c840c TerraSync: better reporting of permissions failures removing files
Log a ‘failed to remove orphan’ error as an error with the repository,
instead of failing the entire sync
2021-04-02 16:46:47 +01:00
James Turner
ae920c6ebd TerraSync: add a warning file to the root dir.
Try to discourage users from adding custom content underneath the
Terrasync dir, since it can be over-written.
2021-04-02 16:45:50 +01:00
James Turner
0343ef7246 Fix windows build, missing <algorithm> 2021-04-02 16:45:03 +01:00
Fernando García Liñán
00a6f02a55 Sort lights when we can only render a limited number of them
This ensures that higher priority lights and lights that are closer to the viewer get rendered.
2021-04-01 03:14:12 +02:00
Fernando García Liñán
eb761fc7ee Add compile_commands.json to .gitignore 2021-04-01 01:40:22 +02:00
Erik Hofman
9cb98475b2 Fix MingW and MSVC builds: return a uniform type name across platforms. 2021-03-29 16:08:06 +02:00
Erik Hofman
e58ca605b6 Delete the readers and writers (which closes them automatically) to prevent memory leaks. 2021-03-29 11:41:12 +02:00
Stuart Buchanan
deb802f74a WS30: Improve random vegetation, reduce frame paus
- Generate vegetation based on underlying landclass material mapping
- Reduce frame pauses by removing terrain init from update visitor
- Fix a couple of small timing windows causing crashes.
2021-03-28 19:50:26 +01:00
Erik Hofman
17c79caea3 Add a convenience constructor which uses the types typename to call setup, eliminating the need to call setup separately. 2021-03-28 08:57:37 +02:00
Erik Hofman
8e97b5e414 Add a helper function which converts the template typename into a topic name. 2021-03-27 15:21:22 +01:00
Erik Hofman
5e837b50c4 Add a fubction which converts a template typename to a string 2021-03-27 15:19:23 +01:00
Erik Hofman
0530bc2cd7 Add a templated helper function for read and write to simplify the code 2021-03-27 13:56:21 +01:00
Erik Hofman
4b530e9376 Fix a mistake of effectively multiplying by DDS_NSECS_IN_SEC twice. 2021-03-27 13:16:24 +01:00
James Turner
0a7e6b9b84 Subsystems: add checks to avoid crash on early exit
Don’t crash if the user exits before subsystems are bound / init-ed
2021-03-23 17:06:05 +00:00
James Turner
676a2e3880 Fix for local particle update
See issue at:
https://sourceforge.net/p/flightgear/codetickets/2568/
2021-03-22 19:28:14 +00:00
James Turner
4c89e8a9d5 Packages: add ‘provides’ listing support
Support a list of provided files on a package, to make it easier to 
identify which package to install based on a required file path.
2021-03-21 16:00:33 +00:00
James Turner
4810eaab92 HTTP: permit cancels inside callbacks 2021-03-21 13:26:04 +00:00
James Turner
224b557573 Packages: support a type enum
Work towards other package types, conceptually. (Not actually
implemented yet)
2021-03-21 13:26:04 +00:00
Stuart Buchanan
a02353a280 WS30: Separate Water mesh and Effects
- Rip out various pieces of irrelevant code, simplifying VPBTechnique.
  Largely dealing with multiple textures per terrain tile, which we
  don't need.
- Use a lookup of the landclass of mesh vertices to identify sections of
  the mesh that are entirely in water, and split those out into a
  separate water mesh, using it's own Effect.
2021-03-20 22:01:12 +00:00
Erik Hofman
55e0d4760f Rename the SG_DDS class to SG_DDS_Topic and create a new SG_DDS class which can handle multiple SG_DDS_Topic classes with a single waitset. Add a unit test for DDS 2021-03-19 13:51:58 +01:00
James Turner
8e338389dd MMap: fix a missed change to use pimpl. 2021-03-16 20:33:44 +00:00
James Turner
522aed9b73 MMap : improved error reporting, Win32 compat
Use strutils::sterror to print errno; convert to pimpl idiom to
avoid pulling Windows.h into public view.
2021-03-16 15:49:58 +00:00
Erik Hofman
0c72b5e622 Of course Windows has it's own _read and _write function whcih conflict with our own. Rename to mmap_read and mmap_write. 2021-03-16 11:55:40 +01:00
Erik Hofman
c6a7dbd755 Do not allocate any memory but work directly on the mmapped buffer 2021-03-16 10:30:58 +01:00
Erik Hofman
84f7faea05 Set EOF when reaching the end of the mmap buffer 2021-03-16 10:30:27 +01:00
Erik Hofman
e8cbcebad8 Make life easier by implementing the system read and write function and call that from the classes read and write functions. Add a forward and rewind function. Add a test_untar derived mmap test utility. 2021-03-16 09:51:37 +01:00
James Turner
cf2fe76bb8 Log positions in courseDeg/distanceM failures
Trying to understand what causes FLIGHTGEAR-71G on Sentry; suspect it
might be passing in uninitalised values.
2021-03-15 15:45:19 +00:00
James Turner
798e690279 ReadWav: error reporting
Report errors from readWAV, and improve attribution for the
format error (include the file path). As a result, mark the individual
exceptions as dont-report, since we will report higher up.
2021-03-15 15:45:19 +00:00
Erik Hofman
931a696007 Add a setup function which takes the topic name from the descriptors typename 2021-03-15 15:16:28 +01:00
Erik Hofman
76cf1e01c6 Sigh, fix a stupid typo. 2021-03-15 15:16:00 +01:00
Erik Hofman
88beb40090 Make simple_mmap and simple_unmmap static private members of SGMMapFile. This should also fix the Windows build error on Jenkins. 2021-03-15 14:45:52 +01:00
Erik Hofman
c539f7ebb6 Add an advance function to step through the mmaped buffer 2021-03-15 13:29:39 +01:00
Erik Hofman
4ace6bda60 Use the new mmap functionality to access the timezone file, removing the need to keep the database in memory. 2021-03-15 11:08:22 +01:00
Erik Hofman
f00a825e2d Add a cross-platform file mmap class and use it to access the timezone file, removing the need to keep the database in memory. 2021-03-15 10:58:17 +01:00
Erik Hofman
508a511070 More gracefully bail out on a missing timzeone file 2021-03-13 13:09:59 +01:00
Erik Hofman
1ea11d987e Add a function to get the timezone description 2021-03-13 10:12:46 +01:00
James Turner
feaac37705 Make SGTimeZoneCOntainer using a pimpl
Keeps zonedetect data private to SimGear
2021-03-12 14:44:26 +00:00
James Turner
4a1809b566 TerraSync: allow an explicit osm2city server
Fixes an error case where a manual TerraSync server is specified; we
would attempt to use an empty string as the OSM2City server, with
hilarious consequences.

Sentry-Id: FLIGHTGEAR-NCZ
2021-03-12 12:47:51 +00:00
Erik Hofman
a9615869e3 If a reader is detected there is no need to test it further, just set a boolean. 2021-03-12 10:48:12 +01:00
Erik Hofman
878b742558 Display the time file that fails 2021-03-12 10:45:01 +01:00
Erik Hofman
9bbb615fbf Use sg_ifstream to load the timezone database into a buffer, and access the database from that buffer. This prevents opening and closing the files too often and allows for wide character paths on Windows. 2021-03-12 09:27:15 +01:00
Erik Hofman
c9e24dcb0b Use a vector database to get the timezone based on territorial boundaries 2021-03-11 15:59:52 +01:00
Stuart Buchanan
bbd84a944a WS30: Improved Road rendering
- Remove road vertices too close together (slicer artifacts)
- Generate linked polygons to remove most gaps.
2021-03-10 22:12:25 +00:00
Erik Hofman
b6c80f2e6a Postpone reader detection to the write call and skip writing if there is no reader yet. 2021-03-10 16:14:30 +01:00
Erik Hofman
c0205f7eb2 Use the find_dependency option to parse Simgear dependencies to FlightGear 2021-03-08 16:15:14 +01:00
Erik Hofman
023364e245 Fix reading from DDS: read data in the requested buffer and not in our own private buffer. 2021-03-08 13:45:18 +01:00
Stuart Buchanan
7b336d2018 WS30 Improve LineFeature Mesh
- Rely on the Slicer for path vertices
- Remove redundant vertices (<1m distance)
2021-03-07 22:26:25 +00:00
James Turner
c86b6fe96c Catalogs: check for local IO failures writing to disk
Sentry.io shows some examples where we failed to write valid data
to disk; check for that if possible.
2021-03-07 15:34:57 +00:00
James Turner
71358dca92 Error-reporting: show XML path when 3D load fails 2021-03-07 12:30:36 +00:00
James Turner
087547c6a0 Report out-of-memory in some loading places
BTG can throw bad-alloc in the wild; catch this case and report it.
2021-03-07 12:30:36 +00:00
James Turner
b7234be625 TerraSync: report errors during downloading
Report various out-of-memory and IO failure conditions; especially,
failure to write downloaded to disk, which was previously not 
recorded.
2021-03-07 12:30:36 +00:00
Stuart Buchanan
0b986beac6 WS30 - Line feature accuracy and width control
- Fix a bug causing roads to be displaced from their
true position (caused by incorrect assumption in ElevationSlicer).

- Add control of the minimum width of roads that are rendered at
each LoD level.  Control properties under /sim/rendering/static-lod

- Improve marking tiles for re-rendering.
2021-03-06 17:23:34 +00:00
Julian Smith
4c25e7898e simgear/io/HTTP*: added support for enabling compression when downloading.
Uses underlying curl library's CURLOPT_ACCEPT_ENCODING.
2021-03-06 08:52:11 +00:00
Julian Smith
58279d03d4 simgear/scene/material/EffectCullVisitor.cxx: avoid c++ warning.
osg::Object() is a virtual base class and clang++ warns unless we explicitly construct it.
2021-03-06 08:52:11 +00:00
Erik Hofman
09156b90fe Per request: Rename DDS to DataDistributionService to prevent confusion with DDS the image format. 2021-03-06 09:10:20 +01:00
Erik Hofman
ae573877da Remove a typo 2021-03-05 15:40:11 +01:00
Erik Hofman
90e9d0a9d8 Support CycloneDDS as a SGIOChannel 2021-03-05 15:23:25 +01:00
Stuart Buchanan
c147c5eb55 WS30 - Move expensive conversion to loading thread 2021-03-04 21:00:12 +00:00
Stuart Buchanan
ce197ea828 WS30 - Improve line feature loading
- Mark tiles that require re-loading after .STG loading, removing a race
condition
- Only re-build line features rather than the entire tile
2021-03-04 20:20:41 +00:00
James Turner
40ead1f71a Add osg::Program wrapper for error-reporting 2021-03-01 11:57:30 +00:00
James Turner
802ce5ad23 ErrorReporting: set context for STG loading
Ensure the STG absolute path can be propagated to all files triggered
by STG loading, including the delayed files and proxied files. This
allows us to attribute errors to the correct scenery path.
2021-03-01 09:42:04 +00:00
Stuart Buchanan
f4dfa854ec WS30 Fix invalid search-and-replace 2021-02-27 16:17:25 +00:00
James Turner
7352e992e6 Allow delayed setup of ErrorContext data
Permit no model data to be provided, when loading a model via the
modelLib API (d’oh)
2021-02-25 12:24:43 +00:00
Stuart Buchanan
1bc0f86cc0 WS30 Line Features - fix build
Add missing files.
2021-02-25 10:54:05 +00:00
James Turner
cb15502b41 Error reporting: add SGModelData context support
Allow us to pass the current error-context from the main thread
into the osgDB loader thread. This is necessary so we can attribute
AIModel (etc) load problems to the correct source.
2021-02-25 09:04:45 +00:00
James Turner
a402eda151 Error-reporting: add some errors for Effect shaders 2021-02-25 09:04:45 +00:00
Stuart Buchanan
716835c7ad WS30 Line Features
Adds a LINE_FEATURES STG Verb of the form

LINE_FEATURES <file.txt> <Material>

Where <file.txt> is a text file consisting of line features to be
rendered with the appropriate <Material> definition.

Each line of <file.txt> has the form
<w> <attr> <a> <b> <c> <d> <lon1> <lat1> <lon2> <lat2> ...

Where
<w> is the line feature width in m
<attr> is an integer for attributes - likely a bitmask*
<a> <b> <c> <d> are floats*
<lonN> <latN> are the lon/lat of point N on the line feature

* denotes values that may be feature-dependent.  For example to indicate
street lighting, kerbing etc.

There must be at least two points on the line feature.
2021-02-24 21:49:42 +00:00
James Turner
93e2bccb0e Error reporting for submodels
Also add some error codes I forgot for AI and traffic.
2021-02-21 19:16:53 +00:00
James Turner
b8b88995cf Add failure reporting / context to various places.
Not total coverage by far, but working through the list of common
failure points as seen on Sentry
2021-02-20 19:57:29 +00:00
James Turner
041c247c0f Suppress reports on some common exception throws 2021-02-20 19:57:29 +00:00
James Turner
e3f4c44685 Add sg_location to all exceptions, add report flag
Move sg_location member up to the base clase, since it’s potentially
useful in more types.

Allow suppression of the report callback when the exception is thrown
2021-02-20 19:57:29 +00:00
James Turner
7b4dc51f93 Add new error reporting function / callback 2021-02-20 19:57:29 +00:00
James Turner
368cbcb377 Remove stray include of std::filesystem 2021-02-20 19:57:29 +00:00
Julian Smith
3521ed44e4 simgear/io/HTTPFileRequest.cxx: Reinstated std::function callback.
Also fixed setCallback() to call the supplied function immediately if transfer
has already finished.
2021-02-20 13:30:13 +00:00
Julian Smith
97828a8e4e simgear/io/HTTPFileRequest.*: Use fnptr rather than std::function to avoid SEGVs with g++ on Linux.
Previous code sometimes gave a SEGV in _callback's destructor when
setCallback() was called; this is on Linux with g++-8.3.0. Have tried various
alternative ways to initialise _callback but the problem persistend.

So have switched to an old-style function-pointer plus void* approach.
2021-02-18 23:20:46 +00:00
Julian Smith
f9ecf455ba simgear/io/: exteded http client support to allow replaying of recordings from a URL.
simgear/io/HTTPClient.cxx
    Support range in HTTPRequest's. Set CURLOPT_MAX_RECV_SPEED_LARGE if request's
    getMaxBytesPerSec() is non-zero.
simgear/io/HTTPFileRequest.cxx
simgear/io/HTTPFileRequest.hxx
    Added 'bool append' to constructor args; if specified we assume that, if
    the output file already exists, it is from an interrupted download, and we
    use an http Range header to append any remaining data.
    Support a std::function callback when new data is available.
    Added setMaxBytesPerSec() to limit download bandwidth; useful for testing.
simgear/io/HTTPRequest.cxx
simgear/io/HTTPRequest.hxx
   Added support for setting Range header.

In both simgear/io/HTTPClient.cxx and simgear/io/HTTPRequest.cxx, if
a range is specified, we treat http results 206 'Partial Content' and
416 'Range Not Satisfiable' as success.
2021-02-18 09:30:56 +00:00
legoboyvdlp R
7f83686853 TerraSync: counter to fetch number of bytes which have been extracted from a tarball file 2021-02-14 17:08:00 +00:00
Scott Giese
d1509d6096 NULL check after malloc 2021-02-13 22:25:31 -06:00
Scott Giese
469a28c49a Remove obsolete, unused variable 2021-02-13 21:44:25 -06:00
Scott Giese
a1f83542cb Remove unncessary cmake policy definitions 2021-02-13 21:43:48 -06:00
James Turner
6319254d71 Fix ownership of SGLight::appendLight, using a ref_ptr
Fix some other C++11-isms as well.
2021-02-11 11:23:38 +00:00
James Turner
1ad7161465 SGLight: use copyProperties 2021-02-10 14:51:18 +00:00
James Turner
6a78bc2cdb Fix VPB compilation with OSG 3.4.x 2021-02-10 14:51:02 +00:00
Stuart Buchanan
6fb47e8e68 WS30: Random vegetation from Marc EBERHARD
Generate random vegetation of VPB tiles.  Currently
prototype that generates same vegetation for all landclass types.

Needs additional work to
a) make the scenegraph more efficient
b) support different material definitions of vegetation.
2021-02-09 17:52:52 +00:00
Stuart Buchanan
bf62554da9 WS30: Apply correct technique to top-leve tile. 2021-02-09 11:20:53 +00:00
Henning Stahlke
fd0e7ac2d8 Make SGLight configurable at runtime. 2021-02-08 12:43:10 +01:00
James Turner
9561895335 Text-animation: fix missing encoding specification
Ensure we can pass full UTF-8 strings into text animations. Will consider
for back-port after discussion on the devel list.

Ticket-Id: https://sourceforge.net/p/flightgear/codetickets/2512/
2021-02-07 13:02:31 +00:00
James Turner
b6c0f5ba00 Particles: fix handling of world-attached particles
Fix the cull callback to continue with normal culling. Also move
where the particle frame is added to the scene graph, to be sure
we don’t modify the scene during OSG traversals.
2021-02-07 11:38:04 +00:00
Stuart Buchanan
95b7e84d9e WS30: Improve MaterialTextureAtlas
- Set Anisotropic from properties
- Only generate the TextureAtlas for VPB (not used in WS2.0)
- Only resize textures if required
2021-02-06 12:53:12 +00:00
James Turner
be49f880b8 Fix HTTPClient reset() behaviour
Ensure all data members are correctly re-initialzied when doing a reset.

This shoed up as negative ‘bytes downloaded’ counts after a TerraSync
abandon and retry.
2021-02-05 10:37:23 +00:00
James Turner
059285ed6f Particles: replace use of ParticleSystemUpdater
Extend our own particle manager to replace the OSG particle system
updater. This fixes thread-safety and also timing (better match to
simulation dt values). We also use weak pointers (observer_ptr in
OSG terminology) to ensure particle systems are released once their
frame is gone.
2021-02-03 21:47:51 +00:00
Stuart Buchanan
bbef23deae WS30: Terrasync compatible files, LoD control
Change WS30 file format to match standard scenery directory
structure, add controls for LOD ranges.
2021-02-02 19:08:23 +00:00
Fernando García Liñán
23a4fb1429 Add missing null check to SGLight's dim-factor expression 2021-02-02 18:40:54 +01:00
Julian Smith
a7a53921e4 simgear/misc/sg_path.*: added SGPath::makeLink(), for making softlinks.
Note that on Windows there is no implementation yet and it always returns
false.
2021-01-30 13:27:55 +00:00
Julian Smith
b888a46e67 simgear/scene/model/SGReaderWriterXML.cxx: removed unused static variable. 2021-01-30 13:27:55 +00:00
Julian Smith
edb1f8b9f8 Improved diagnostics if terrasync fails.
Increased some diagnostics to SG_ALERT if terrasync checksums fail.

Show failed URLs; show SyncItem::Type enum names; show SyncItem::Status enum
names.
2021-01-30 13:25:29 +00:00
Julian Smith
a72941fdb7 simgear/props/props.cxx: Improved diagnostics for illegal property names. 2021-01-30 13:23:26 +00:00
Stuart Buchanan
d695d37563 WS30: Property configuration VPB
Configure the VPB elevation mesh via properties:
/scenery/elevation-mesh/sample-ratio controls the elevation
mesh sampling, allowing reduction in mesh size

/scenery/elevation-mesh/vertical-scale is just for fun and
scales the mesh vertically making mountains taller.

/scenery/elevation-mesh/constraint-gap-m controls how much below
airports etc. elevation vertices are forced to be.
2021-01-27 20:00:39 +00:00
Fernando García Liñán
b04cdbc491 Add a priority parameter to SGLight
In the future this will help choose which lights should be displayed if
the user sets the maximum number of lights to a low enough value.
2021-01-26 13:41:51 +01:00
Stuart Buchanan
3b1eb4a7f7 Remove Terrain simplifier - now redundant 2021-01-17 14:26:35 +00:00
Stuart Buchanan
b8ddf517f4 WS3.0 Add OBJECT STG entries as elevation constraints
Note this is for OBJECT only (e.g. airports), not
OBJECT_STATIC or OBJECT_SHARED
2021-01-14 11:32:07 +00:00
Stuart Buchanan
0a59de8c46 WS3.0: Add elevation constraints for airports
Previously if the elevation of the terrain vertices was higher
than the airport, the terrain pushed through the airport, looking
ugly.

This adds the concept of elevation constraint models, which the
VPBTechnique applies when generating terrain vertices.

Simply add a scenery model to the contraints on the technique,
and terrain won't poke through it.
2021-01-13 20:26:28 +00:00
Colin Geniet
d54e9b7675 Animations: Fix spin for Compositor lights
The 'spin' animation has a strange behaviour:
it pushes a temporary rotation matrix on the transformation stack during
cull traversal, and removes it thereafter.
Thus, the rotation matrix is missing outside of cull traversal, e.g.
when the position of Compositor lights is computed.

The same issue was fixed for the 'rotate' animation by commit
e202d4e4a5
(this mentions broken 'picking' animations as a different manifestation
of the same issue).

Fix this by setting the angle of the persistent SGRotateTransform,
instead of creating a temporary rotation matrix.
2021-01-13 12:18:22 +01:00
James Turner
0b9849d232 CMake: remove .cmake extensions
These seem to break include()’s regular path searching, which is odd.
2021-01-10 13:32:59 +00:00
James Turner
fa1f13cbe2 CMake: add upstream FindLibLZMA.cmake
Required since older CMake versions of this don't define an imported target
2021-01-10 11:56:22 +00:00
James Turner
d4a7cb1ee2 ArchiveExtractor .Xz compression of tar-balls
Allow use of LibZLMA / XZ compressed tarballs, which are significantly
smaller. Extend unit-tests to cover this.
2021-01-09 16:30:50 +00:00
James Turner
14494afd2f Tolerate blank lines in buildings lists 2021-01-08 19:39:37 +00:00
James Turner
9fbf56004b HTTPRepository: improving handling of archives
Avoid hard-coding the archive extension, and ensure the extracted
archive directory is not orphaned on update. Finally, use the
literal filename in the .dirindex when computing the hash, rather
than adding a .tgz extension.
2021-01-08 19:39:14 +00:00
James Turner
161f76508d TerraSync: allow separate OSM2City server
Lookup OSM2City using a separate service profile, and use this server
for requests for OSM2City suffix dirs.
2021-01-08 19:38:02 +00:00
James Turner
08906ebbb0 Launhcer: fix crashes adding a catalog
Traversing a container which is modified causes crashes, take a copy
during traversal for firePackageStatus.

Sentry-Id: FLIGHTGEAR-CJF
Sentry-Id: FLIGHTGEAR-CJ5
2021-01-01 15:34:17 +00:00
Fernando García Liñán
e606609a00 Remove unused Rembrandt stuff 2021-01-01 10:35:49 +01:00
Fernando García Liñán
5a2c348b12 Our cull visitor no longer collects light sources by default 2021-01-01 10:35:49 +01:00
Stuart Buchanan
b62808bb4c Fix hang on "Loading Scenery" over the sea
Previously attempting to start on an ocean tile with static
models present cause FG to spin on "Loading Scenery".

This was caused by not creating a BVH for an ocean tile in
the specific case where there was STG models, due to a PagedLOD
node being inserted in the scene graph.  So
FG never thought the scenery was loaded sufficient to place
the aircraft.

By explicitly creating a BVH for ocean tiles the problem is
fixed.

Candidate for 2020.X
2020-12-30 16:38:04 +00:00
Erik Hofman
62501e5ede Eatdirt: Implement parallax effects for the Moon at the rendering stage and not with the ephemeris. 2020-12-30 11:13:42 +01:00
Fernando García Liñán
60f5df2998 Make light animation definitions from Rembrandt compatible with SGLight
This effectively makes unmaintained aircraft with Rembrandt light definitions
automatically compatible with Compositor lights.
2020-12-30 09:28:29 +01:00
Fernando García Liñán
8f2e7824ab SGLight: Add support for dimming through a SGExpression ala Rembrandt 2020-12-30 09:27:30 +01:00
xDraconian
28015085ec Merge /p/flightgear-photoscenery/simgear/ branch next-photoscenery-r8 into next
https://sourceforge.net/p/flightgear/simgear/merge-requests/90/
2020-12-27 04:18:40 +00:00
Nathaniel MacArthur-Warner
1960a1b264 Get rid of duplicate log 2020-12-24 14:55:34 -08:00
Nathaniel MacArthur-Warner
7572d8f6ee Another logging improvement 2020-12-24 14:43:14 -08:00
Scott Giese
074cb31c28 fix: sky and cockpit to turn black
Metar sky condition without base layer height (e.g. FEW///) is the cause of this issue.
Randomize the base layer height when the actual height is unknown.
2020-12-24 15:39:39 -06:00
Nathaniel MacArthur-Warner
7dc8a86524 Warn when loading uncompressed DDS files since it causes problems on some systems 2020-12-24 12:26:30 -08:00
Nathaniel MacArthur-Warner
3fc6df203c Attempt to convert subimage on pixel format mismatch, provide more helpful logs 2020-12-23 23:39:39 -08:00
Nathaniel MacArthur-Warner
a56d1718de Check for and scale down oversize composite orthophotos 2020-12-23 22:38:03 -08:00
Nathaniel MacArthur-Warner
6ed37c880a When creating composite orthophoto, only scale sub images when necessary 2020-12-23 17:32:31 -08:00
Nathaniel MacArthur-Warner
0e7cf378a4 Indent fix 2020-12-23 14:07:34 -08:00
Nathaniel MacArthur-Warner
851ccb0ca7 Fix creation of composite orthophotos in case where aspect ratio of input photos doesn't match tile 2020-12-23 11:37:38 -08:00
Fernando García Liñán
0f482c14dd Do not let OSG cull lights away 2020-12-23 12:50:06 +01:00
Fernando García Liñán
a84133e945 (Another) significant rework of the clustered shading feature
This time it tries to be as compatible as possible with older hardware setups.
The only feature that might not be supported by some really old hardware
(or picky drivers) is floating point textures. There is no way around that
though, so this is as compatible as we can be with GL 2.1 level hardware.
2020-12-22 10:52:02 +01:00
Julian Smith
718a23cbbe Fixed build failure caused by flightgear now #including logdelta.hxx.
The fix is to add logdelta.hxx to list of headerss in
simgear/debug/CMakeLists.txt.
2020-12-22 00:35:40 +00:00
Julian Smith
687e65fa36 simgear/debug/logdelta.*: added logDeltaSet() to allow dynamic control. 2020-12-21 22:36:37 +00:00
James Turner
284667c18f Fix BTG error reporting
Use gzerror, not strerror, for these codes.
2020-12-21 13:26:04 +00:00
Fernando García Liñán
68caf780b0 Clustered Shading: Don't use static variables, use class member variables instead 2020-12-18 23:29:08 +01:00
Julian Smith
d1aa5a0b82 simgear/props/props.*: added method to add exising SGPropertyNode_ptr as child.
Avoids the need to create a new child and copy recursively.
2020-12-18 17:44:57 +00:00
Julian Smith
42c89ba6d3 simgear/props/props.cxx: parse_name(): improved exception text.
Also fixed indentation.
2020-12-18 17:44:57 +00:00
Fernando García Liñán
995608fc9e Fix wrong Compositor buffer formats 2020-12-18 01:45:26 +01:00
Scott Giese
e8f715c255 Maintenance: convert atoi to modern equivalence
Out of range results in undefined behavior in the C library.
Coverting to C++ library to avoid this risk.
2020-12-17 18:01:49 -06:00
Scott Giese
e031ea7f7c Crash prevention: throw during dtor
get_manager() will be called during dtor, so throwing an exception would cause a hard crash.
2020-12-17 17:02:40 -06:00
Scott Giese
9bac911fe1 Maintenance: Use empty instead of size==0 2020-12-17 16:08:06 -06:00
Scott Giese
cdd5cf8cd5 Remove unreachable code 2020-12-17 15:41:51 -06:00
Nathaniel Warner
3898ca5c09 Fix aiport signs appearing black when photoscenery enabled 2020-12-17 10:54:00 +00:00
Fernando García Liñán
5c21df742c Compositor no longer inherits from osg::Referenced 2020-12-17 06:35:55 +01:00
Scott Giese
39d616a0d5 Support Boost v1.75
Resolved a breaking change.
2020-12-15 01:41:32 -06:00
James Turner
b660061812 Fix Nasal GC errors on tests/reset
Ensure the Context temps are cleared, and when recycling an naCode,
ensure old values are cleared explicily.

Sentry-Id: FLIGHTGEAR-Y
2020-12-13 17:26:27 +00:00
James Turner
deda20d5bd SGGeod: add static constructor of an invalid Geod
Use this to allow explicitly initializing a value which isValid
will return false for.
2020-12-13 17:26:27 +00:00
xDraconian
b9c39fd2ab Merge /p/flightgear-photoscenery/simgear/ branch next-photoscenery-r6 into next
https://sourceforge.net/p/flightgear/simgear/merge-requests/88/
2020-12-12 23:13:37 +00:00
Nathaniel Warner
9e103fe7bf Prefer DDS over PNG for orthophoto 2020-12-12 13:59:52 -08:00
Nathaniel Warner
88be307540 Gracefully handle pixel format mismatch 2020-12-12 11:44:55 -08:00
Julian Smith
89fabafa15 simgear/props/props_io.*: added class for inline calling of writeProperties().
E.g. allows:

    SG_LOG(SG_VIEW, SG_ALERT, "returning:\n" << writePropertiesInline(config, true /*write_all*/));
2020-12-12 11:24:33 +00:00
Nathaniel Warner
4c0f6d7638 Add support for dds, avoid creating non power of two textures 2020-12-11 18:39:20 -08:00
Stuart Buchanan
8954a54e2e WS30: Improved material atlas
Add
- texture size
- shininess
- diffuse
- specular

from material.xml into the fragment shader via sampler1D.
2020-12-08 21:12:01 +00:00
Fernando García Liñán
915982de85 Move makeNewProjMat somewhere public so it can be accessed by flightgear 2020-12-08 14:08:43 +01:00
Richard Harrison
aaaae0f567 Remove mutex lock on realizeTechniques
This was causing a deadlock - and I can't quite remember what problem it was intended to solve so it is best to remove it.
2020-12-07 15:12:15 +01:00
Nathaniel Warner
f72ff7d2a2 Fix segfault when trying to load corrupt orthophoto 2020-12-06 11:44:04 -08:00
Fernando García Liñán
00ff35cdb7 Better shadow map depth ranges 2020-12-06 14:41:09 +01:00
Stuart Buchanan
8641d3616a WS30: Texture array texture lookup for landclass
- Create a Texture2DArray for a MaterialCache
- Adjust the landclass image to index into the above array
- Add the array to as a Uniform for rendering.
2020-12-05 13:09:35 +00:00
James Turner
02cf42359d Reporting of std::bad_alloc in Subsystem::update
Trying to trace down our bad-alloc exception, starting with the simplest
place for now.
2020-12-03 21:37:26 +00:00
James Turner
4271b710ef Add reporting callback option to SimGear
Allows us to trigger an error logging callback explicitly, which can
be used to drive Sentry.io on the FlightGear side.
2020-12-03 21:37:26 +00:00
Fernando García Liñán
f1212dfa73 Initial support for texture arrays in Effects 2020-12-03 18:36:56 +01:00
James Turner
191d546b54 TerraSync: stronger fix for handling 0-byte files
Change logic so we create an empty file for such cases, i.e exactly
matching the repository. This simplifies logic in downstream code,
compared with not creating a local file.

Add a test-case to cover this

Modify TerraSync to detect a failure of Airports_archive downloading,
and fall back to file-by-file updating.
2020-12-03 16:40:48 +00:00
James Turner
57a4dc53f2 HTTPRepository: don’t crash on empty files
Fix some additional crash cases around 0-length files
2020-12-02 21:28:37 +00:00
James Turner
e370477e4e Unzip: adjust error reporting mechanism
Don’t use local exception throw+catch to report failures in extracting
a zip archive, since this generates noise in Sentry.
2020-12-02 12:12:56 +00:00
James Turner
c88b8b201a State-machines: don’t require name for transitions
Allow anonymous transitions, since the name is purely informational
(unlike for states).

Sentry-Id: FLIGHTGEAR-9H
2020-11-30 16:17:59 +00:00
Nathaniel Warner
fee2c592c0 Use observer_ptr in OrthophotoManager 2020-11-29 15:02:09 -08:00
Stuart Buchanan
023a3de5f1 WS30: Landclass to material mapping
Using indirection in materials.xml

<landclass-mapping>
  <map>
    <description>111 - Continuous urban fabric</description>
    <landclass>1</landclass>
    <material-name>Urban</material-name>
  </map>
</landclass-mapping>
2020-11-29 19:28:58 +00:00
James Turner
de268300fb TerraSync: fix crashes with null file return
Not sure how this is happening, but, check for a null file object
in FileGetRequest::onDone.
2020-11-29 16:22:21 +00:00
Scott Giese
79252d889c Merge branch 'next' of https://git.code.sf.net/p/flightgear/simgear into next 2020-11-27 17:56:52 -06:00
Nathaniel Warner
ca38d9110c Fix orthophotos not being cleaned up on scenery reload 2020-11-27 17:54:28 -06:00
Stuart Buchanan
6ece39e34c Set minimum expiry time on STG nodes. 2020-11-26 22:55:56 +00:00
Scott Giese
aab373ac3a Model Loading: Overlays
Cannot copy overlays until the props has been read.
Ticket: #2429
2020-11-24 11:26:57 -06:00
Nathaniel Warner
d4d149f3c0 Rebase photoscenery patch on next 2020-11-23 17:49:24 -06:00
Scott Giese
59809ab61f smell: avoid uncasting with left-shift 2020-11-23 16:17:28 -06:00
Scott Giese
7673da3832 smell: throwing heap object
null check.
2020-11-23 16:16:14 -06:00
Scott Giese
112c9a110b smell: potential div-by-0 2020-11-23 16:14:37 -06:00
Scott Giese
59e62b1414 warning: unreachable code 2020-11-23 16:13:43 -06:00
Scott Giese
43bf10d803 warning: defined but not used 2020-11-23 16:12:07 -06:00
Scott Giese
20bcb0f245 warning: defined but not used
clean up whitespace.
2020-11-23 16:11:08 -06:00
Scott Giese
c469f072f1 warning: ‘Active’ will be initialized after 'CanWait' 2020-11-23 16:08:55 -06:00
Scott Giese
62f3923692 warning: comparison of integer expressions of different signedness 2020-11-23 16:07:39 -06:00
Scott Giese
03abb674dc warning: unused variable ‘fd’ 2020-11-23 16:06:43 -06:00
Scott Giese
f6e63e1831 warning: unused variable ‘idx’ 2020-11-23 16:05:03 -06:00
Fernando García Liñán
cc8b2bbf72 Add support for anisotropic filtering in Canvas 2020-11-23 16:33:09 +01:00
Stuart Buchanan
0a37986551 Use ref_ptr for ReaderWriterSPT 2020-11-21 21:45:09 +00:00
Chris Frey
04ca40ad81 tgdb: check result of readRefNodeFile and log 2020-11-21 21:41:10 +00:00
Chris Frey
42ceb429a7 Small spelling/grammar fix in comments in ReaderWriterSPT.cxx 2020-11-21 21:39:17 +00:00
Chris Frey
6ae7eb31a6 BucketBox: fixed possibility of writing one past the end of the given array 2020-11-21 21:38:19 +00:00
Richard Harrison
5d5f1779c6 Reduce severity of ".." at model root
It seems more sensible to return nullptr rather than throwing an exception.
2020-11-21 14:56:16 +01:00
Richard Harrison
2cb6499f1c Model loading; overlay properties earlier
This is to permit an <overlay> section in <model> to be present whilst the rest of the model is loaded - otherwise the overlay is only present after the model is loaded;

e.g. to allow a model specific registration to be applied to a shared model;

    <model>
        <overlay>
            <texture-file>island_68.png</texture-file>
            <carrier-name>Nimitz</carrier-name>
            <carrier-registration>CVN-68</carrier-registration>
        </overlay>
        <path>nimitz-class.xml</path>
    </model>
2020-11-21 14:56:16 +01:00
Julian Smith
e2596eaeea simgear/debug/logdelta.cxx: remove initial diagnostic if SG_LOG_DELTAS uset. 2020-11-21 12:17:59 +00:00
Scott Giese
da39e30439 METAR: mitigate wind sensor failures 2020-11-20 21:13:47 -06:00
Automatic Release Builder
15c6f73136 Catalogs: fix ownership of new Catalogs
When doing the initial download of a Catalog, ensure we still keep
an owning ref to it.
2020-11-18 17:32:10 +00:00
Fernando García Liñán
da53e8fb1b Make sure we render the CameraGroup cameras one after another 2020-11-18 14:30:06 +01:00
Stuart Buchanan
1852e3c7fc Use BB radius rather than range for STG entries
Also remove excess logging from TREE_LIST
2020-11-17 21:34:57 +00:00
Stuart Buchanan
25d922cf6b TREE_LIST STG verb
Add a TREE_LIST STG analogous to the existing BUILDING_LIST verb

  TREE_LIST <filename> <material name> <lon> <lat> <elev>

where <filename> is a file containing a set of trees to generate
using the defined <material name> at the given location.

The referenced <filename> contains lines of the form

X Y Z A B C

Where:
- X,Y,Z are the cartesian coordinates of the tree. +X is East, +Y is North
- A,B,C is optional and represents the normal of the underlying terrain.  Used for shadows.  Defaults to (0,0,1)
2020-11-17 21:17:04 +00:00
Stuart Buchanan
158ac28e60 Add a range noun to STG verbs
Previously the PagedLoD range for OBJECT_STATIC etc. was purely
measured from the object reference point.  For large meshes from
osm2city this was problematic, particular at DETAILED LOD ranges,
where the range of (say) 1500m would result in the mesh being
rendered at 500m distance from the edge.  We fudged this by adding
1400m to the DETAILED LOD range.

Now, such meshes can specify their radius in the STG file, ensuring
they are loaded at the correct distance.
2020-11-17 19:56:01 +00:00
Richard Harrison
02b20462e1 DDS-TC add option to exclude all Canvas orignated images. 2020-11-17 19:08:38 +01:00
Richard Harrison
be6d28557a Emesary : change to use scoped lock
- scoped locks using lock_guard are better
- because of this the exception handler can also be removed;
  although this was originally intended to manage the locks
  it never did work properly with C++ exceptions.
2020-11-17 19:08:38 +01:00
Richard Harrison
cac3739a6b Emesary: add missing property initialisation to constructor 2020-11-17 19:08:38 +01:00
Julian Smith
d98d893f3e simgear/props/props.cxx: use rmutex to protect SGPropertyNodeListeners.
Also added asserts to check _num_iterators always >= 0.
2020-11-17 15:08:25 +00:00
Julian Smith
79e1ea02ab simgear/debug/logdelta.cxx: protect cache with a std::mutex. 2020-11-17 15:08:25 +00:00
Fernando García Liñán
a77551aa02 Only merge fallback effects if the Effect hasn't been realized yet 2020-11-17 15:21:49 +01:00
Fernando García Liñán
31170b11a0 Fix frustum parameters not being initialized 2020-11-17 13:08:30 +01:00
Fernando García Liñán
42ee05fd0e Check for 0 value before doing log2 2020-11-17 12:34:03 +01:00
Fernando García Liñán
79b858d6d8 Replace more references to GL_RGBA32F with GL_RGBA32F_ARB 2020-11-16 16:39:30 +01:00
Fernando García Liñán
6ae0dba659 Fix compilation issue on Mac and other graphics drivers 2020-11-16 16:19:27 +01:00
Fernando García Liñán
8f214fff7d Make Compositor default
- Remove prepending shader filenames with Compositor/.
- Always check for fallback effects in Effects/schemes.xml.
- Shadow mapping can now be disabled at night.
- New clustered shading implementation for older systems (GLSL 120 compatible).
- Miscellaneous bug fixes.
2020-11-16 13:21:51 +01:00
Erik Hofman
c9e23231da Keep the region name with the material. 2020-11-15 09:29:26 +01:00
Stuart Buchanan
94630733ff WS3.0: Pass tile_level, tile_width, tile_height
Create Uniforms for the tile_level, tile_width and tile_height.

These can be used by the fragment shader to determine the level
of detail to render and also to perform samples for borders of
landclasses.
2020-11-14 21:01:55 +00:00
James Turner
2fb20f793b Try to capture cause of BTG load failures 2020-11-12 09:37:04 +00:00
James Turner
f3847bd10f TerraSync: fix local-file copying
Avoid downloading data corresponding to files shipped in FGData.
2020-11-12 09:36:53 +00:00
James Turner
f8e4c2bae6 Untar: log error details when output create fails
Trying to understand why writing to the output files fails for some
users.

Sentry-Id: FLIGHTGEAR-SS
2020-11-12 09:36:49 +00:00
James Turner
bf69827990 TerraSync: make tarball extraction asynchronous 2020-11-12 09:36:43 +00:00
James Turner
ca857fcb25 Strutils: add printf format validation
Moved from NewGUI code in FG, better it lives here for re-use.
2020-11-10 23:49:25 +00:00
Stuart Buchanan
f72e093714 WS3.0: Replace OSG 3.6 methods with OSG 3.4 2020-11-10 16:20:25 +00:00
Stuart Buchanan
8d5428bf77 WS3.0: Initial commit to load and render WS3.0 2020-11-08 22:36:45 +00:00
Stuart Buchanan
cbd8e3acc4 WS3.0 : Initial technique to load and render WS3.0 scenery 2020-11-08 22:35:33 +00:00
James Turner
7f0a83388d DNSClient: own requests, and cancel them on timeout
Fixes crashes where a request times-out, but then is completed by
UDN sometime afterwards, with a free-d object. Have the DNS::Client own
requests, and be able to retrieve the udns_query to cancel them, in 
the timeout case.

Fixes a couple of Sentry reports.
2020-11-04 22:31:43 +00:00
Julian Smith
49484d5e86 simgear/debug/logdelta.cxx: don't use and/or keywords, appears to break on vc++? 2020-11-01 11:50:12 +00:00
Julian Smith
2a74cc9e5f Added logdelta system to allow control of log priorities based on source filename, line and function name.
See simgear/debug/logdelta.hxx for usage.
2020-10-31 23:58:57 +00:00
Julian Smith
365e5265c8 simgear/nasal/cppbind/test/cppbind_test_ghost.cxx: workaround for OpenBSD.
OpenBSD's clang++ can't cope with this code, so we disable it.
2020-10-31 23:52:23 +00:00
Julian Smith
cc699871a3 simgear/scene/model/SGReaderWriterXML.cxx: minor change to addTooltipAnimations().
Improved calculation of num_new_animations.
2020-10-31 23:52:23 +00:00
Julian Smith
510b25f8b8 Allow use of old zlib-1.2.3 on OpenBSD.
As of 2020-08-01, OpenBSD's system zlib is 1.2.3 which doesn't
have gzoffset(). However we can get away with this by making
gzfilebuf::approxOffset() always return zero.
2020-10-31 23:52:23 +00:00
James Turner
99bd9bb4c0 Terrasync: tarball extraction, use larger buffer
Use a 1MB buffer, 2kByte is very 1979 :)
2020-10-30 22:50:44 +00:00
James Turner
8d6d671cc1 TerraSync: switch to per-directory hash caching
Avoid a central hash cache becoming enormous, now we use the selective
download scheme for the tile dirs.

Hash name is changed to co-exist with older versions.
2020-10-30 22:49:53 +00:00
James Turner
990c53fc9c Fix Airports/ initial sync 2020-10-30 19:23:00 +00:00
James Turner
0dd046065d TerraSync: avoid 404s to probe missing tiles
Use the top-level dirIndex files to determine if a 1x1 tile dir
exists, instead of proving the server via a 404. This reduces the
number of requests we make considerably, which is … important.
2020-10-30 16:45:45 +00:00
James Turner
1ab1cae199 TerraSync: validate local dirs incrementally
Add a process() method to HTTPRepository, and use this to
incrementally validate subdirs after the .dirIndex is received. This 
avoids large pauses of the TerraSync thread, when all of Airports/
is validated at once.
2020-10-30 11:51:26 +00:00
James Turner
87558f8dde TerraSync: use an unordered_map for the hash cache
Linear-scan is a bit slow in debug builds, for the large Airports/ tree;
switch to an unordered_map.

Will back-port to the LTS once tested a bit more.
2020-10-29 23:13:10 +00:00
James Turner
e04249ba48 Props: allow flushing the atomic change listener
Trying to narrow down causes of the ‘unregister listeners crashes on
shutdown’ reports.
2020-10-29 17:26:38 +00:00
Automatic Release Builder
afcbf2ff3a Catalog migration: migrate packages too
When doing a catalog migration to a new ID (eg, 2018 -> 2020), also
mark the installed packages for installation, on the new catalog.

Related to this, when manually removing a catalog, record this fact,
so we don’t re-add it automatically due to migration.

Add unit-tests covering both of these cases.
2020-10-29 14:09:36 +00:00
Automatic Release Builder
d395a5c495 Sound: readWAV: avoid common exceptions.
Avoid exceptions for the common ‘file not found’ case, and instead
return false / nullptr. Erik says it’s fine.
2020-10-29 14:09:29 +00:00
Automatic Release Builder
29d4899f1f TerraSync: retry after socket failures
Assume socket failures are intermittent, up to some maximum count
(currently configured as 16). Add a test case to cover this.
2020-10-29 14:08:47 +00:00
Automatic Release Builder
baf95da93a TerraSync: Rate-limit hash-cache writes
This helps with IO-limited performance on Windows
2020-10-29 14:07:04 +00:00
Automatic Release Builder
dd6dfafabf SGPath: optimise exists() on Windows
For a very common existence only check, use a dedicated win32 API
function, to save some time.
2020-10-29 14:06:26 +00:00
Automatic Release Builder
439fa4c4a1 TerraSync: fix Windows behaviour
SGDir on Windows returns dot-files by default, which includes our
hash-cache, causing it to be orphaned.
2020-10-29 14:02:58 +00:00
Automatic Release Builder
b7308fa3ad Add a hasInstance to ResourceManager
This is needed to allow order-independent shutdown, due to the dumb
ownership behaviour for providers.
2020-10-29 14:02:50 +00:00
Automatic Release Builder
fba00d6894 SGFile::computeHash: check malloc result
Trying to fix a reported crash, in this code. malloc() returning null
seems unlikely but worth checking for. ALso use a unique_ptr with
a custom deleter to avoid a leak if we throw.

Sentry-Id: FLIGHTGEAR-3Y
2020-10-29 14:02:36 +00:00
Automatic Release Builder
77786e8e9b XMLSound: Avoid using exceptions for missing file
Reducing how noisy our exception reporting is, by using simple return
value from SGXMLSound::init.
2020-10-29 14:02:30 +00:00
Automatic Release Builder
a5dd5cdc80 TerraSync: fast start Airports/ sync
If TerraSync/Airports is missing, download Airport_archive.tgz instead.
In all other cases update as normal. This has the effect, that fresh
installs make many fewer requests to TerraSync servers.
2020-10-29 14:01:52 +00:00
Automatic Release Builder
ed357c5c8f Terrasync: re-add persistent update cache
Re-add (with some tweaks) the persistent tile-cache code, so that
TerraSync checks the server at most once per 24 hour period, for a
given repository path.

(Disbale the cache by setting /sim/terrasync/enable-persistent-cache=0)
2020-10-29 14:00:55 +00:00
Automatic Release Builder
6d892e8d18 Packages: fix circular refernece bug
Packages had a strong back-pointer to their catalog, creating a circular
reference loop. Break this so catalogs & packages are freed on exit.
2020-10-29 14:00:47 +00:00
Automatic Release Builder
ed8ff68114 Catalogs: fix enabling/disabling
Relates to bug Michael found in the launcher:
https://sourceforge.net/p/flightgear/codetickets/2380/
2020-10-29 14:00:40 +00:00
Automatic Release Builder
c0323e34a5 TerraSync: tweak warnings around checksum failures
Trying to reduce log spam when there is a server-side failure.
2020-10-29 14:00:22 +00:00
Automatic Release Builder
1ebb0787ad Fix level of terrasync start/stop messages 2020-10-29 14:00:12 +00:00
Automatic Release Builder
5e37c2092a Harden Repo::computeHashForPath
Check for some error cases in computeHashForPath, since this showed up
in some crash reports.
2020-10-29 14:00:01 +00:00
Automatic Release Builder
b3fc8deb5c Exceptions: optional callback for exception throws.
This is to allow recording an error+stacktrace whenever an exception
is thrown, since that’s the point when the stack is interesting.
2020-10-29 13:59:44 +00:00
James Turner
f489232cdb Fix for crash reported by Michael Danilov
In case uDNS returns a NULL txt pointer, don’t try to create a
std::string from it, since this will crash,

See: https://sourceforge.net/p/flightgear/codetickets/2398/
2020-10-25 18:59:37 +00:00
Scott Giese
f393a246ac METAR: When Wind unit not specified, default to knots.
FLIGHTGEAR-F6 resolved
2020-10-23 23:26:28 -05:00
Scott Giese
d7a149e8cd METAR Wind Sensor Failure.
FLIGHTGEAR-F9 resolved.
2020-10-23 22:12:51 -05:00
Erik Hofman
4a660e3827 callers already compensate for year-from-1900 and mont-start-from-0 2020-10-22 10:45:06 +02:00
Erik Hofman
ce187e614a Fix the way struct tm works, year is since 1900 (so fix a year-2000 problem...) and month is 0-11 instead of 1-12. Return a string we constructed ourselves to prevent a possible buffer overrflow. Luckily the function isn't used in active code. 2020-10-22 10:20:37 +02:00
James Turner
83500dd413 CMake: use same 3rdParty logic as FlightGear
Avoids need to specify the 3rd-party dir, in the standard/fgmeta
layout of source directories, and accept more combinations of path,
when the user specifies a value.
2020-10-20 16:51:20 +01:00
Automatic Release Builder
2ad6e351ac Update version file 2020-10-13 22:28:42 +01:00
Bertrand Coconnier
8c51d30ddb Make CMake stop complaining about target "Udns::Udns" not found when rebuilding SimGear. 2020-10-03 17:58:11 +02:00
James Turner
670460a079 Set GCC RelwtihDebInfo opt flags 2020-09-29 17:40:25 +01:00
Scott Giese
cb4f3b1ca9 REVIEW: Memory Leaks 2020-09-24 22:24:12 -05:00
James Turner
4560095c36 Change props.cxx to throw std::exception
Throwing std::string is slightly unconventional, switch to throwing
exceptions inheriting std::exception.
2020-09-10 11:25:15 +01:00
Stuart Buchanan
b279384aef Check correctly for failed BUILDING_LIST
Previous additional checks for a value BUILDING_LIST entry
used an enum incorrectly, resulting in all BUILDING_LIST entries
failing.  Now fixed to check bad() / fail() which are bool.
2020-09-09 21:44:20 +01:00
Erik Hofman
01a190fea8 Fix a bug in the rotation_matrix function 2020-09-09 15:50:25 +02:00
James Turner
1341d1e1f2 Missed fix for logging in the test-suite 2020-09-08 12:34:37 +01:00
James Turner
051c920a99 Fix Linux compilation
Missing <cstring> header for strdup.
2020-09-08 08:15:41 +01:00
James Turner
0efcc14e91 Add MANDATORY_INFO log priority.
New log-level to avoid using ‘ALERT’ for expected mandatory messages,
since I want to do error collection on real alerts in a future commit.

As part of this, split logstream.hxx into separate header files, and
add a new virtual hook to LogCallback which takes the complete log-entry
2020-09-07 14:44:29 +01:00
James Turner
c7f013e7e5 Don’t wipe startup message on pausing logging. 2020-09-07 14:42:16 +01:00
James Turner
19ace8f0f9 Silence an alert message 2020-09-06 14:48:17 +01:00
James Turner
908496d43d ASan: make copied files in log entries safe at init.
Ensure that if we copy file-names of log entries while startup
logging is active, we free them, but only once startup logging is
disabled, or on shutdown. This is needed to avoid crashes when
we use file-name copying for the Qt message handler.
2020-09-05 10:43:01 +01:00
James Turner
52c0f04e6e Bindings: don’t cache the command pointer
Caching it complicates add/remove command logic, so making a simple
fix for now, which can be back-ported to 2020.2; ideally we would
cache the pointer but have an invalidation scheme, but that’s
considerably more work and risk.

Relates to Sentry crash:
https://sentry.io/organizations/flightgear/issues/1858764364
2020-09-04 10:51:32 +01:00
James Turner
f6656354b8 Refactor SGBuildingBin
Trying to trace a crash that was reported, but along the way fix a leak
of BuildingBins. Also avoid allocating some std::strings on the heap.
2020-09-03 20:35:50 +01:00
Erik Hofman
4928509646 Mipmapping requires a power-of-two destination buffer even if the source isn't. Neglecting this causes a massive bufferoverflow of the destination buffer. So for now we do not mipmap non-power-of-two textures and throw a warning. This affects at least the PC-9M and F-16, presumable many others. The effect will be a black texture when zoomed out and the proper texture when zooming in close enough. 2020-08-29 14:45:47 +02:00
Scott Giese
9ecb90edda Clean up memory leak comment 2020-08-27 23:41:19 -05:00
Scott Giese
0d5552851b Memory Leak Fixed - SGTexturedTriangleBin
Reclaimed 42,560 bytes in 280 blocks
2020-08-27 23:40:25 -05:00
James Turner
6f2b81b477 Fix for the fact we find_package(AAX) all the time.
Since we probe for AeonWave first, we set AAX_LIBRARY to NOT_FOUND,
which then upsets CMake if we try to use it. So add some temporary
ugly logic, until I have time to define a proper ALIAS target for the
audio backend.
2020-08-24 11:14:16 +01:00
Erik Hofman
af1b170059 Use consistent naming 2020-08-24 10:58:55 +02:00
Erik Hofman
f235a81519 Temporary fix for AeonWave support 2020-08-24 10:58:22 +02:00
Scott Giese
5b0f44f0db Memory Leak Fix - matlib
Reclaimed 61,560 bytes in 405 blocks
2020-08-24 00:20:59 -05:00
Scott Giese
f14bcfb3c5 Memory Leak Fix - SGMaterial
Reclaimed 61,560 bytes in 405 blocks
2020-08-24 00:20:26 -05:00
Scott Giese
e1e70e8d33 Memory Leak Fix - BVHStaticGeometryBuilder
Was resolved at some point over the last two weeks.
Reclaimed 4,518,880 bytes in 141,215 blocks
2020-08-23 22:38:06 -05:00
Scott Giese
bd01e741ac Memory Leak Fix - sg_path
Resolved via HTTPRespository fix
Reclaimed 272,181 bytes in 2,833 blocks
2020-08-23 22:22:18 -05:00
Scott Giese
423a0f65b0 Memory Leak Fix - HTTPRepository
Reclaimed 1,797,012 bytes in 7599 blocks
2020-08-23 22:15:28 -05:00
Scott Giese
b8e06453ea Temporary fix: SimGear OpenAL dependency
FG configuration fails due to SG find_dependency(OpenAL) issue.
Skipping this dependency since FG itself will find_package(OpenAL).
2020-08-23 20:15:18 -05:00
James Turner
bab083d072 For static builds, ensure we find the sound library
Should fix Erik’s issue with AeonWave.
2020-08-23 18:10:49 +01:00
James Turner
2c4120974c Follow rule of three for HTTPRepo:ChildInfo 2020-08-23 18:10:17 +01:00
James Turner
8b14e56f88 HTTPRepo: Fix ownership of HTTPDirectory 2020-08-23 18:08:49 +01:00
James Turner
3298260f11 GDAL is a public dependency :( 2020-08-23 11:27:09 +01:00
James Turner
2ed15eebfd CMake fixes for Linux 2020-08-23 11:27:09 +01:00
Scott Giese
720a1fe7d2 REVIEW: Memory Leak - naTempSave()
1,024 bytes in 1 blocks are still reachable
2020-08-23 01:02:27 -05:00
Scott Giese
fc1178fb39 REVIEW: Memory Leak - ODGauge
1,176 bytes in 3 blocks are indirectly lost
2020-08-23 00:57:39 -05:00
Scott Giese
7ac400a162 REVIEW: Memory Leak - vgCreateContextSH()
1,624 bytes in 1 blocks are still reachable
2020-08-23 00:27:31 -05:00
Scott Giese
3550047bc8 REVIEW: Memory Leak - condition.cxx
2,880 bytes in 40 blocks are indirectly lost
632 bytes in 79 blocks are indirectly lost
2020-08-23 00:07:19 -05:00
Scott Giese
b7d2eea4b2 REVIEW: Memory Leak - props.cxx
2,028 (1,976 direct, 52 indirect) bytes in 13 blocks are definitely lost
1,963 bytes in 47 blocks are indirectly lost
1,544 bytes in 193 blocks are indirectly lost
662 bytes in 32 blocks are indirectly lost
152 bytes in 1 blocks are definitely lost
32 bytes in 1 blocks are indirectly lost
8 bytes in 1 blocks are indirectly lost
2020-08-22 23:52:36 -05:00
Scott Giese
69ad4a39e3 REVIEW: Memory Leak - nasal newBlock()
168 bytes in 7 blocks are still reachable
2020-08-22 22:42:09 -05:00
Scott Giese
4ccaa68c6a REVIEW: Memory Leak - ODGauge
3,572 (136 direct, 3,436 indirect) bytes in 1 blocks are definitely lost
3,572 (8 direct, 3,564 indirect) bytes in 1 blocks are definitely lost
2,712 bytes in 3 blocks are indirectly lost
384 bytes in 3 blocks are indirectly lost
168 bytes in 3 blocks are indirectly lost
2020-08-22 22:38:33 -05:00
Scott Giese
fd6e4e7298 REVIEW: Memory Leak - nasal string.c; setlen()
3,953 bytes in 184 blocks are still reachable
2020-08-22 21:53:47 -05:00
Scott Giese
896f3b6928 REVIEW: Memory Leak - soundmgr_openal.cxx
4,136 bytes in 1 blocks are still reachable
2020-08-22 21:39:47 -05:00
Scott Giese
6f6c3a0e05 REVIEW: Memory Leak - SGReaderWriterXML sgLoad3DModel_internal()
4,352 bytes in 272 blocks are definitely lost
2020-08-22 21:30:41 -05:00
Scott Giese
6160fce2ae REVIEW: Memory Leak - SGComparisonCondition::setRightValue()
7,144 bytes in 47 blocks are indirectly lost
2020-08-22 18:23:19 -05:00
Scott Giese
e1a6602a59 REVIEW: Memory Leak - naNewContext()
8,184 bytes in 1 blocks are still reachable
2020-08-22 18:07:11 -05:00
Scott Giese
d18c9910e8 REVIEW: Memory Leak - SGMaterialLib::load()
8,800 bytes in 57 blocks are indirectly lost
2020-08-22 18:04:56 -05:00
Scott Giese
b4ba7db5c0 REVIEW: Memory Leak - SGMaterialLib::load()
10,240 (1,440 direct, 8,800 indirect) bytes in 60 blocks are definitely lost
2020-08-22 17:57:54 -05:00
Scott Giese
bdd7878d19 REVIEW: Memory Leak - condition::readAndConditions()
11,502 (1,560 direct, 9,942 indirect) bytes in 39 blocks are definitely lost
2020-08-22 17:42:58 -05:00
Scott Giese
f210d6ba94 REVIEW: Memory Leak - SGPropertyNode::getChild()
12,862 (11,856 direct, 1,006 indirect) bytes in 78 blocks are definitely lost
2020-08-22 17:39:58 -05:00
Scott Giese
0807a6ddf7 REVIEW: Memory Leak - SGPropertyNode::addChangeListener
24,928 bytes in 164 blocks are indirectly lost
2020-08-22 17:37:39 -05:00
Scott Giese
ea53e9af0c REVIEW: Memory Leak - UniformFactoryImpl::getUniform()
13,800 bytes in 69 blocks are indirectly lost
2020-08-22 17:36:43 -05:00
Scott Giese
bcb22691fc REVIEW: Memory Leak - SGTexturedTriangleBin::buildGeometry()
42,560 bytes in 280 blocks are definitely lost
2020-08-22 17:10:43 -05:00
Scott Giese
34ca004e95 REVIEW: Memory Leak - SGMaterial::read_properties()
61,560 bytes in 405 blocks are definitely lost
2020-08-22 16:57:21 -05:00
Scott Giese
53487ae732 // REVIEW: Memory Leak - HTTPRepository copy-ctor
93,275 bytes in 2,275 blocks are indirectly lost
2020-08-22 16:16:38 -05:00
Scott Giese
685866ffa7 // REVIEW: Memory Leak - nasal newBlock()
113,376 bytes in 1 blocks are still reachable
2020-08-22 16:11:52 -05:00
Scott Giese
e3ce59ee80 REVIEW: Memory Leak - Effect::buildAttribute()
144,400 bytes in 38 blocks are indirectly lost
2020-08-22 16:08:58 -05:00
Scott Giese
ce019a169b REVIEW: Memory Leak - EffectBuilder::InitFromParameters()
156,910 (2,320 direct, 154,590 indirect) bytes in 29 blocks are definitely lost
2020-08-22 15:53:25 -05:00
Scott Giese
03a76a1805 REVIEW: Memory Leak - hash::resize()
196,628 bytes in 1 blocks are still reachable
2020-08-22 15:40:07 -05:00
Scott Giese
8f76c2b401 REVIEW: Memory Leak - SGPath::append()
212,955 bytes in 2,277 blocks are indirectly lost
2020-08-22 15:28:37 -05:00
Scott Giese
39b83cdb51 REVIEW: Memory Leak - ModelRegistry
262,144 bytes in 1 blocks are indirectly lost
2020-08-22 15:09:46 -05:00
Scott Giese
10ffa82ea6 REVIEW: Memory Leak - ChildInfo copy-ctor
447,264 bytes in 39 blocks are indirectly lost
2020-08-22 14:59:27 -05:00
Scott Giese
38e38bf3d3 CMake Fix: FindGDAL
FindPackageHandleStandardArgs.cmake  is not located within simgear/CMakeModules.
Use the normal CMake folder.
2020-08-22 14:45:13 -05:00
James Turner
e85a3207ac Add newer FindGDAL with imported target support 2020-08-19 09:22:52 +01:00
James Turner
2846c5e579 Ensure simgear_config.h is round when building HLA 2020-08-19 09:22:33 +01:00
James Turner
456c63935c Cmake refresh
Use target objects everywhere, and simplify handling of system vs
local dependencies.
2020-08-18 11:40:27 +01:00
Scott Giese
995a176654 REVIEW: unique HTTPRepository is encapsulated within HTTPDirectory object. 2020-08-17 20:02:45 -05:00
Scott Giese
a8c13cf041 REVIEW: Memory Leak - HTTPDirectory
885,598 (3,072 direct, 882,526 indirect) bytes in 48 blocks are definitely lost.
Candidate for shared_ptr or destruction within parent's dtor.
2020-08-17 19:35:06 -05:00
Scott Giese
d79ecddaf9 REVIEW: Memory Leak - NASAL GC
1,032,712 bytes in 6 blocks are still reachable.
naFree(p->free0) is required during shutdown.
2020-08-17 19:11:01 -05:00
Scott Giese
e5bbd62e96 Merge branch 'next' of https://git.code.sf.net/p/flightgear/simgear into next 2020-08-17 19:04:00 -05:00
Scott Giese
5fdcd72de9 REVIEW: Memory Leak - NASAL
2,048,000 bytes in 1 blocks are still reachable.
naFree(globals->deadBlocks) is required during shutdown.
2020-08-17 19:03:20 -05:00
James Turner
3b41b0c6d3 Particles: fix a deadlock condition 2020-08-17 15:04:16 +01:00
James Turner
84c15f6384 Enable ASan for clang 2020-08-17 10:20:26 +01:00
James Turner
209b60504d Particles: rewrite global manager for thread-safety
Avoid re-registering the global node callback each time a new particle
animation is loaded, and use mutexes to protected all shared data.
2020-08-16 19:49:26 +01:00
James Turner
08bbe08205 Missed include for Linux 2020-08-14 21:16:37 +01:00
James Turner
297e509576 Avoid a race in MatModels loading
Add a mutex to ensure an SGMatModels only loads its models once. Caught
be ASan, hurrah.
2020-08-14 16:48:51 +01:00
James Turner
b874201806 API to reset the shared tree geometry 2020-08-14 15:40:47 +01:00
James Turner
e659ad3872 Destructor tweaks from some animation nodes 2020-08-14 11:12:51 +01:00
legoboyvdlp R
7b4c50fd7e Add METAR test for drizzle. These should be moved to the test suite but we'll add coverage here meantime. 2020-08-14 09:59:16 +01:00
James Turner
b8182a4d29 Fix for sprintf of nil numeric in Nasal
Spotted by valgrind, w00t. If you used a numerical formatter, such
as f,d or g, with. a nil value, we would read uninitialised data, and
generally get confused.
2020-08-14 09:42:14 +01:00
James Turner
7234b57288 Set OSG Object names on SGSky stuff
This is to help with debugging when nodes/effects dangle.
2020-08-11 17:19:01 +01:00
James Turner
bf7b064bbe Ensure SGTerraSync::unbind drops all properties
Avoid some noise on reset, by dropping /all/ our SGPropertyNodes
2020-08-11 17:17:58 +01:00
Hans Kunkell
5f1ca6b556 new method: makeStringSafeForPropertyName, replaces invalid chars 2020-08-10 10:23:38 +01:00
legoboyvdlp R
888a0a8ed5 Drizzle is considered to be light rain. Backportable to 2020.2. Fixes ticket 1792 2020-08-10 10:19:56 +01:00
Scott Giese
a93629a127 Revert "Memory Leak: 95 MB"
This reverts commit cb54815cfc.
2020-08-09 09:39:04 -05:00
Scott Giese
cb54815cfc Memory Leak: 95 MB
99,418,032 bytes in 654,066 blocks are still reachable in loss record 15,500 of 15,501
2020-08-08 20:34:59 -05:00
Scott Giese
f76c640b69 Memory Leak: fix low-hanging fruit 2020-08-08 00:23:39 -05:00
James Turner
abb1cd02cd SGBuildingBin: avoid read of un-inited memory
Where the building line is not as long as expected, ensure we read
valid memory.
2020-08-07 17:48:21 +01:00
James Turner
57c7d58f79 HTTP: Use curl_multi_wait everywhere
Also check the result of the curl methods, in case they fail
2020-08-07 17:47:34 +01:00
Richard Harrison
998f92592a Directional lighting fix
getLights modified to use points rather than triangles based on the configuration.

This fixes point lights (with directional disabled) on AMD
2020-08-07 12:04:21 +02:00
Scott Giese
084e2502ab Memory Leak: 4.3 MB
4,518,880 bytes in 141,215 blocks are still reachable in loss record 15,491 of 15,501
2020-08-06 22:15:43 -05:00
Scott Giese
da384d6f49 Logic error fix 2020-08-06 18:50:31 -05:00
James Turner
7943353a2a Terraysnc: fix incorrect handling of ‘entirely ocean’ tiles
We had some confusion between two error codes, meaning we would log an
error (and treat as a failure) a pure ocean 1x1 area, even though this
was entirely correct and expected behaviour.

Terrasync.cxx expected REPO_ERROR_NOT_FOUND, we need to convert the
file-level error to that, and avoid logging a warning.
2020-08-05 15:20:55 +01:00
James Turner
f72e2ae644 TerraSync: restart after max-errors is exceeded.
When we trip the max-error count for a session, back off for a period
of time and then retry (selecting a new TerraSync server).
2020-08-05 15:18:30 +01:00
James Turner
ece7dab47c TerraSync: handle reinit better
Fix various cases where re-init could get things blocked. Remove the
duplicate storage of the active paths; now we always check the primary
data, and hence it can’t be out of sync.

Also remove the obsolete persistent cache code.

Fixes some of the issues discussed in:
https://sourceforge.net/p/flightgear/codetickets/2308/

Further improvements still to come, especially to retry on a better
schedule for intermittent connections.
2020-08-03 18:01:34 +01:00
Richard Harrison
3643f1c064 XMLSound bugfixes
- using expressions for pitch and volume didn't work
- multiple volume elements not computed properly

Discussion here: https://web.archive.org/web/20200730232940/http://fguk.me/forum/development-hangar/8360-supersonic-audio?start=40#46287

          <volume>
                <property>/a/v1</property>
                <factor>0.1</factor>
            </volume>
            <volume>
                <property>/a/v2</property>
                <offset>1</offset>
                <factor>-3</factor>
            </volume>
            <volume>
                <property>/a/v3</property>
                <offset>1</offset>
                <factor>-1</factor>
            </volume>

evaluates as follows:

update(): Have 3 volume entries
 --> 0:prop /a[0]/v1[0] => 0.110000 factor = 0.100000 v=0.011000 offset 0.000000, now 0.000000, v=0.011000 vol=0.011000 ==> 0.011000
 --> 1:prop /a[0]/v2[0] => 0.120000 factor = 3.000000 v=0.360000 -ve offset 1.000000 1.360000 = 0.014960  ==> 0.014960
 --> 2:prop /a[0]/v3[0] => 0.130000 factor = 1.000000 v=0.130000 -ve offset 1.000000 1.130000 = 0.016905  ==> 0.016905
2020-07-31 01:31:27 +02:00
Richard Harrison
59da504cde Exclude images with less than 16 bits per pixel from the DDS Texture Cache 2020-07-31 01:18:33 +02:00
James Turner
2622004af4 Logging: add log overload which copies filename
This is needed to fix a Valgrind error in the test-cases, due to logging
Nasal filenames which are GCed.
2020-07-17 11:54:50 +01:00
James Turner
ec36ca8e71 Nasal CppBind: restrict which exceptions are caught
The previous catch policy breaks unit-testing, since CppUnit relies
on a special Exception type.

This could be made conditional based on testing or not, but trying the
simple way initially.
2020-07-08 15:16:27 +01:00
James Turner
286e2967fd Fix compilation for some MSVC versions 2020-07-04 14:43:44 +01:00
Julian Smith
fcc5e055ef Renamed version -> simgear-version to avoid breaking clang++ on OpenBSD.
It seems that clang++ headers #include <version>, which found simgear/version
because we need to put singear/ in include path for some code to compile.
2020-07-04 09:04:04 +01:00
Scott Giese
a3ffc77a9d Bug fix: Check for a valid effect before dereference
Reported on the dev list as...
Crash with custom scenery
2020-07-03 13:23:23 -05:00
Scott Giese
6d8e9e5bbc VPB: Initial commit
Not for LTS
2020-06-28 11:30:33 -05:00
James Turner
3fccee6e38 HTTP: allow CAINFO to be set
Env var is SIMGEAR_TLS_CERT_PATH
2020-06-25 16:13:09 +01:00
James Turner
7fc82a26bf Helper to map string to log priority 2020-06-25 11:00:27 +01:00
James Turner
a128272816 Fix CMake include paths 2020-06-24 13:57:27 +01:00
James Turner
2b391ef671 Bundle Cmake FindCURL, for imported target support
This is the one from CMake 3.17, it should work fine with 3.10 but
let’s see.
2020-06-24 11:12:01 +01:00
James Turner
abb73c566e Update to C++17.
This can be reverted easily, but let’s see if it goes.
2020-06-22 20:39:45 +01:00
James Turner
346344ee09 C++17: use an OBJECT_LIBRARY to build HLA
This allows us to easily have different CXX version for the HLA code,
to the rest of the project.
2020-06-21 19:31:35 +01:00
Julian Smith
26b207f20c Auto-tooltips: also show object name and multiple properties for same object.
E.g. tooltip for joystick might show elevator and aileron properties.
2020-06-21 10:58:41 +01:00
Julian Smith
d9470c1407 simgear/scene/model/SGReaderWriterXML.cxx: Added optional auto-generated tooltips for moving objects.
This allows one to see what properties are being used to control moving objects
such as needles and dials in the cockpit, or external moving objects such as
bomb doors.

The system works by optionally creating new animations with type=pick for all
animated objects. A side affect of this is that yellow highlighting of controls
from Ctrl-C will also highlight instrument needles in the cockpit and external
animations such as flaps, rudder, gear etc.

src/Model/acmodel.cxx:simgear::SGModelLib::loadModel() takes new param bool
autoTooltipsMaster and int autoTooltipsMasterMax, which is added into the
SGReaderWriterOptions that is passed to loadFile(). autoTooltipsMasterMax
limits the maximum number of tooltips, which appears to be necessary on 777 -
more than 45 can cause fg to fail to make progress.

The auto-generated tooltips show the name of the object and also the names and
values of the properties that control the animation. For example the tooltip
for a fuel gauge might say 'consumables/fuel/tank[1]/level-gal_imp=0.23456789'.
2020-06-20 11:09:35 +01:00
James Turner
9ccbf539c1 Raise minimum OSG version to 3.4.1 2020-06-18 17:22:55 +01:00
James Turner
720f681e0f Raise Cmake/Compiler versions for Next 2020-06-18 12:58:47 +01:00
James.Hester
259c1314de Allow OSG to recalculate terrain normals. 2020-06-18 09:11:52 +01:00
Julian Smith
27907c5e6f Avoid various gcc warnings. 2020-06-17 22:56:33 +01:00
James Turner
aa0f02706f API to reset the resource manager, and remove
providers.

Needed to fix a bug with parsing -set.xml files in the launcher;
correctly loading XML needs the resource paths to be defined.
2020-06-17 11:48:59 +01:00
Lars Toenning
b4d5374fb7 Fix compiler warning of different signedness 2020-06-16 12:11:24 +01:00
James Turner
60dcf00f2b Fix zero-interval repeat on pick/knob animation
See:
https://sourceforge.net/p/flightgear/codetickets/2241/

Note did not adjust bug in knob-animation ignoring repeatable flag
(always marked repeatable) since this might break some aircraft.
2020-06-15 16:11:18 +01:00
James Turner
3075b8bcc4 new version: 2020.3.0 2020-06-15 12:33:50 +01:00
443 changed files with 78368 additions and 16371 deletions

1
.gitignore vendored
View File

@@ -17,3 +17,4 @@ Build
CMakeLists.txt.user
3rdparty/expat_2.2.6/
nbproject
compile_commands.json

View File

@@ -2,6 +2,8 @@ if (NOT SYSTEM_EXPAT)
add_subdirectory(expat)
endif()
if (ENABLE_DNS AND NOT SYSTEM_UDNS)
if (NOT SYSTEM_UDNS)
add_subdirectory(udns)
endif()
add_subdirectory(tiny_gltf)

View File

@@ -1,3 +1,20 @@
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
check_cxx_source_compiles(
"#include <sys/random.h>
int main(void) {
return 0;
}
"
HAVE_GETRANDOM)
if (NOT HAVE_GETRANDOM)
# on older (GLibC < 2.25) fall back to /dev/urandom
set(XML_DEV_URANDOM 1)
else()
message(STATUS "Found <sys/random.h>")
endif()
endif()
configure_file (
"${PROJECT_SOURCE_DIR}/3rdparty/expat/expat_config_cmake.in"
@@ -26,8 +43,24 @@ set(expat_sources
sg_expat_external.h
)
foreach(s ${expat_sources})
set_property(GLOBAL
APPEND PROPERTY LOCAL_EXPAT_SOURCES
"${CMAKE_CURRENT_SOURCE_DIR}/${s}")
endforeach()
add_library(FGExpat STATIC ${expat_sources})
target_include_directories(FGExpat BEFORE PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
$<INSTALL_INTERFACE:include>)
# for the config file above
target_include_directories(FGExpat PRIVATE ${PROJECT_BINARY_DIR}/3rdparty/expat)
target_compile_definitions(FGExpat PUBLIC HAVE_SIMGEAR_EXPAT_CONFIG_H XML_STATIC)
# look like Expat found by find()
add_library(EXPAT::EXPAT ALIAS FGExpat)
# in the non-shared case, we need to export these as well
if (NOT SIMGEAR_SHARED)
install(TARGETS FGExpat
EXPORT SimGearTargets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()

View File

@@ -1,5 +1,36 @@
/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
See the file COPYING for copying permission.
/*
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1999-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2002 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2007 Karl Waclawek <karl@waclawek.net>
Copyright (c) 2017 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#define ASCII_A 0x41

View File

@@ -1,62 +1,66 @@
/*
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2002 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2017 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
The Original Code is expat.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The Initial Developer of the Original Code is James Clark.
Portions created by James Clark are Copyright (C) 1998, 1999
James Clark. All Rights Reserved.
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
Contributor(s):
Alternatively, the contents of this file may be used under the terms
of the GNU General Public License (the "GPL"), in which case the
provisions of the GPL are applicable instead of those above. If you
wish to allow use of your version of this file only under the terms of
the GPL and not to allow others to use your version of this file under
the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the
GPL. If you do not delete the provisions above, a recipient may use
your version of this file under either the MPL or the GPL.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML,
/* 0x0C */ BT_NONXML, BT_CR, BT_NONXML, BT_NONXML,
/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM,
/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS,
/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS,
/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL,
/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI,
/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST,
/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB,
/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT,
/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML,
/* 0x0C */ BT_NONXML, BT_CR, BT_NONXML, BT_NONXML,
/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM,
/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS,
/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS,
/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL,
/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI,
/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST,
/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB,
/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT,
/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER,

View File

@@ -10,6 +10,14 @@
#undef WIN32_LEAN_AND_MEAN
#endif
#cmakedefine HAVE_GETRANDOM
#cmakedefine XML_DEV_URANDOM
// we can assume > 10.7 macOS so always set this
#ifdef __APPLE__
#define HAVE_ARC4RANDOM_BUF
#endif
/* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */
#define BYTEORDER 1234

View File

@@ -1,63 +1,67 @@
/*
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2002 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2017 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
The Original Code is expat.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The Initial Developer of the Original Code is James Clark.
Portions created by James Clark are Copyright (C) 1998, 1999
James Clark. All Rights Reserved.
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
Contributor(s):
Alternatively, the contents of this file may be used under the terms
of the GNU General Public License (the "GPL"), in which case the
provisions of the GPL are applicable instead of those above. If you
wish to allow use of your version of this file only under the terms of
the GPL and not to allow others to use your version of this file under
the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the
GPL. If you do not delete the provisions above, a recipient may use
your version of this file under either the MPL or the GPL.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* Like asciitab.h, except that 0xD has code BT_S rather than BT_CR */
/* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML,
/* 0x0C */ BT_NONXML, BT_S, BT_NONXML, BT_NONXML,
/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM,
/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS,
/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS,
/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL,
/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI,
/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST,
/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB,
/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT,
/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML,
/* 0x0C */ BT_NONXML, BT_S, BT_NONXML, BT_NONXML,
/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM,
/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS,
/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS,
/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL,
/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI,
/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST,
/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB,
/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT,
/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER,

View File

@@ -18,9 +18,42 @@
Note: Use of these macros is based on judgement, not hard rules,
and therefore subject to change.
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 2002-2003 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2002-2006 Karl Waclawek <karl@waclawek.net>
Copyright (c) 2003 Greg Stein <gstein@users.sourceforge.net>
Copyright (c) 2016-2021 Sebastian Pipping <sebastian@pipping.org>
Copyright (c) 2018 Yury Gribov <tetra2005@gmail.com>
Copyright (c) 2019 David Loffredo <loffredo@steptools.com>
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#if defined(__GNUC__) && defined(__i386__) && !defined(__MINGW32__)
#if defined(__GNUC__) && defined(__i386__) && ! defined(__MINGW32__)
/* We'll use this version by default only where we know it helps.
regparm() generates warnings on Solaris boxes. See SF bug #692878.
@@ -30,8 +63,8 @@
#define FASTCALL __attribute__((stdcall, regparm(3)))
and let's try this:
*/
#define FASTCALL __attribute__((regparm(3)))
#define PTRFASTCALL __attribute__((regparm(3)))
# define FASTCALL __attribute__((regparm(3)))
# define PTRFASTCALL __attribute__((regparm(3)))
#endif
/* Using __fastcall seems to have an unexpected negative effect under
@@ -45,29 +78,86 @@
/* Make sure all of these are defined if they aren't already. */
#ifndef FASTCALL
#define FASTCALL
# define FASTCALL
#endif
#ifndef PTRCALL
#define PTRCALL
# define PTRCALL
#endif
#ifndef PTRFASTCALL
#define PTRFASTCALL
# define PTRFASTCALL
#endif
#ifndef XML_MIN_SIZE
#if !defined(__cplusplus) && !defined(inline)
#ifdef __GNUC__
#define inline __inline
#endif /* __GNUC__ */
#endif
# if ! defined(__cplusplus) && ! defined(inline)
# ifdef __GNUC__
# define inline __inline
# endif /* __GNUC__ */
# endif
#endif /* XML_MIN_SIZE */
#ifdef __cplusplus
#define inline inline
# define inline inline
#else
#ifndef inline
#define inline
# ifndef inline
# define inline
# endif
#endif
#include <limits.h> // ULONG_MAX
#if defined(_WIN32) && ! defined(__USE_MINGW_ANSI_STDIO)
# define EXPAT_FMT_ULL(midpart) "%" midpart "I64u"
# if defined(_WIN64) // Note: modifiers "td" and "zu" do not work for MinGW
# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "I64d"
# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "I64u"
# else
# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "d"
# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "u"
# endif
#else
# define EXPAT_FMT_ULL(midpart) "%" midpart "llu"
# if ! defined(ULONG_MAX)
# error Compiler did not define ULONG_MAX for us
# elif ULONG_MAX == 18446744073709551615u // 2^64-1
# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "ld"
# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "lu"
# else
# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "d"
# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "u"
# endif
#endif
#ifndef UNUSED_P
# define UNUSED_P(p) (void)p
#endif
/* NOTE BEGIN If you ever patch these defaults to greater values
for non-attack XML payload in your environment,
please file a bug report with libexpat. Thank you!
*/
#define EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT \
100.0f
#define EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT \
8388608 // 8 MiB, 2^23
/* NOTE END */
#include "sg_expat.h" // so we can use type XML_Parser below
#ifdef __cplusplus
extern "C" {
#endif
void _INTERNAL_trim_to_complete_utf8_characters(const char *from,
const char **fromLimRef);
#if defined(XML_DTD)
unsigned long long testingAccountingGetCountBytesDirect(XML_Parser parser);
unsigned long long testingAccountingGetCountBytesIndirect(XML_Parser parser);
const char *unsignedCharToPrintable(unsigned char c);
#endif
#ifdef __cplusplus
}
#endif

View File

@@ -1,62 +1,66 @@
/*
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2002 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2017 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
The Original Code is expat.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The Initial Developer of the Original Code is James Clark.
Portions created by James Clark are Copyright (C) 1998, 1999
James Clark. All Rights Reserved.
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
Contributor(s):
Alternatively, the contents of this file may be used under the terms
of the GNU General Public License (the "GPL"), in which case the
provisions of the GPL are applicable instead of those above. If you
wish to allow use of your version of this file only under the terms of
the GPL and not to allow others to use your version of this file under
the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the
GPL. If you do not delete the provisions above, a recipient may use
your version of this file under either the MPL or the GPL.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* 0x80 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x84 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x88 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x8C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x90 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x94 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x98 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x9C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xA0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xA4 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xA8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER,
/* 0xAC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xB0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xB4 */ BT_OTHER, BT_NMSTRT, BT_OTHER, BT_NAME,
/* 0xB8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER,
/* 0xBC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xC0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xC4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xC8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xCC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xD0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xD4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
/* 0xD8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xDC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xE0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xE4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xE8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xEC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xF0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xF4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
/* 0xF8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xFC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0x84 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x88 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x8C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x90 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x94 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x98 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0x9C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xA0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xA4 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xA8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER,
/* 0xAC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xB0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xB4 */ BT_OTHER, BT_NMSTRT, BT_OTHER, BT_NAME,
/* 0xB8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER,
/* 0xBC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
/* 0xC0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xC4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xC8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xCC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xD0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xD4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
/* 0xD8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xDC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xE0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xE4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xE8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xEC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xF0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xF4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
/* 0xF8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
/* 0xFC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,

View File

@@ -1,150 +1,136 @@
/*
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2017 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
static const unsigned namingBitmap[] = {
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0x00000000, 0x04000000, 0x87FFFFFE, 0x07FFFFFE,
0x00000000, 0x00000000, 0xFF7FFFFF, 0xFF7FFFFF,
0xFFFFFFFF, 0x7FF3FFFF, 0xFFFFFDFE, 0x7FFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFE00F, 0xFC31FFFF,
0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF,
0xFFFFFFFF, 0xF80001FF, 0x00000003, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xFFFFD740, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD,
0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF,
0xFFFF0003, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF,
0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE,
0x0000007F, 0x00000000, 0xFFFF0000, 0x000707FF,
0x00000000, 0x07FFFFFE, 0x000007FE, 0xFFFE0000,
0xFFFFFFFF, 0x7CFFFFFF, 0x002F7FFF, 0x00000060,
0xFFFFFFE0, 0x23FFFFFF, 0xFF000000, 0x00000003,
0xFFF99FE0, 0x03C5FDFF, 0xB0000000, 0x00030003,
0xFFF987E0, 0x036DFDFF, 0x5E000000, 0x001C0000,
0xFFFBAFE0, 0x23EDFDFF, 0x00000000, 0x00000001,
0xFFF99FE0, 0x23CDFDFF, 0xB0000000, 0x00000003,
0xD63DC7E0, 0x03BFC718, 0x00000000, 0x00000000,
0xFFFDDFE0, 0x03EFFDFF, 0x00000000, 0x00000003,
0xFFFDDFE0, 0x03EFFDFF, 0x40000000, 0x00000003,
0xFFFDDFE0, 0x03FFFDFF, 0x00000000, 0x00000003,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xFFFFFFFE, 0x000D7FFF, 0x0000003F, 0x00000000,
0xFEF02596, 0x200D6CAE, 0x0000001F, 0x00000000,
0x00000000, 0x00000000, 0xFFFFFEFF, 0x000003FF,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0xFFFFFFFF, 0xFFFF003F, 0x007FFFFF,
0x0007DAED, 0x50000000, 0x82315001, 0x002C62AB,
0x40000000, 0xF580C900, 0x00000007, 0x02010800,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0x0FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x03FFFFFF,
0x3F3FFFFF, 0xFFFFFFFF, 0xAAFF3F3F, 0x3FFFFFFF,
0xFFFFFFFF, 0x5FDFFFFF, 0x0FCF1FDC, 0x1FDC1FFF,
0x00000000, 0x00004C40, 0x00000000, 0x00000000,
0x00000007, 0x00000000, 0x00000000, 0x00000000,
0x00000080, 0x000003FE, 0xFFFFFFFE, 0xFFFFFFFF,
0x001FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x07FFFFFF,
0xFFFFFFE0, 0x00001FFF, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0x0000003F, 0x00000000, 0x00000000,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0x0000000F, 0x00000000, 0x00000000,
0x00000000, 0x07FF6000, 0x87FFFFFE, 0x07FFFFFE,
0x00000000, 0x00800000, 0xFF7FFFFF, 0xFF7FFFFF,
0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF,
0xFFFFFFFF, 0xF80001FF, 0x00030003, 0x00000000,
0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000003,
0xFFFFD7C0, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD,
0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF,
0xFFFF007B, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF,
0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE,
0xFFFE007F, 0xBBFFFFFB, 0xFFFF0016, 0x000707FF,
0x00000000, 0x07FFFFFE, 0x0007FFFF, 0xFFFF03FF,
0xFFFFFFFF, 0x7CFFFFFF, 0xFFEF7FFF, 0x03FF3DFF,
0xFFFFFFEE, 0xF3FFFFFF, 0xFF1E3FFF, 0x0000FFCF,
0xFFF99FEE, 0xD3C5FDFF, 0xB080399F, 0x0003FFCF,
0xFFF987E4, 0xD36DFDFF, 0x5E003987, 0x001FFFC0,
0xFFFBAFEE, 0xF3EDFDFF, 0x00003BBF, 0x0000FFC1,
0xFFF99FEE, 0xF3CDFDFF, 0xB0C0398F, 0x0000FFC3,
0xD63DC7EC, 0xC3BFC718, 0x00803DC7, 0x0000FF80,
0xFFFDDFEE, 0xC3EFFDFF, 0x00603DDF, 0x0000FFC3,
0xFFFDDFEC, 0xC3EFFDFF, 0x40603DDF, 0x0000FFC3,
0xFFFDDFEC, 0xC3FFFDFF, 0x00803DCF, 0x0000FFC3,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xFFFFFFFE, 0x07FF7FFF, 0x03FF7FFF, 0x00000000,
0xFEF02596, 0x3BFF6CAE, 0x03FF3F5F, 0x00000000,
0x03000000, 0xC2A003FF, 0xFFFFFEFF, 0xFFFE03FF,
0xFEBF0FDF, 0x02FE3FFF, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x1FFF0000, 0x00000002,
0x000000A0, 0x003EFFFE, 0xFFFFFFFE, 0xFFFFFFFF,
0x661FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x77FFFFFF,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x04000000,
0x87FFFFFE, 0x07FFFFFE, 0x00000000, 0x00000000, 0xFF7FFFFF, 0xFF7FFFFF,
0xFFFFFFFF, 0x7FF3FFFF, 0xFFFFFDFE, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFE00F, 0xFC31FFFF, 0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF,
0xFFFFFFFF, 0xF80001FF, 0x00000003, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0xFFFFD740, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD,
0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, 0xFFFF0003, 0xFFFFFFFF,
0xFFFF199F, 0x033FCFFF, 0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE,
0x0000007F, 0x00000000, 0xFFFF0000, 0x000707FF, 0x00000000, 0x07FFFFFE,
0x000007FE, 0xFFFE0000, 0xFFFFFFFF, 0x7CFFFFFF, 0x002F7FFF, 0x00000060,
0xFFFFFFE0, 0x23FFFFFF, 0xFF000000, 0x00000003, 0xFFF99FE0, 0x03C5FDFF,
0xB0000000, 0x00030003, 0xFFF987E0, 0x036DFDFF, 0x5E000000, 0x001C0000,
0xFFFBAFE0, 0x23EDFDFF, 0x00000000, 0x00000001, 0xFFF99FE0, 0x23CDFDFF,
0xB0000000, 0x00000003, 0xD63DC7E0, 0x03BFC718, 0x00000000, 0x00000000,
0xFFFDDFE0, 0x03EFFDFF, 0x00000000, 0x00000003, 0xFFFDDFE0, 0x03EFFDFF,
0x40000000, 0x00000003, 0xFFFDDFE0, 0x03FFFDFF, 0x00000000, 0x00000003,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFE, 0x000D7FFF,
0x0000003F, 0x00000000, 0xFEF02596, 0x200D6CAE, 0x0000001F, 0x00000000,
0x00000000, 0x00000000, 0xFFFFFEFF, 0x000003FF, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0xFFFFFFFF, 0xFFFF003F, 0x007FFFFF, 0x0007DAED, 0x50000000,
0x82315001, 0x002C62AB, 0x40000000, 0xF580C900, 0x00000007, 0x02010800,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0FFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0x03FFFFFF, 0x3F3FFFFF, 0xFFFFFFFF, 0xAAFF3F3F, 0x3FFFFFFF,
0xFFFFFFFF, 0x5FDFFFFF, 0x0FCF1FDC, 0x1FDC1FFF, 0x00000000, 0x00004C40,
0x00000000, 0x00000000, 0x00000007, 0x00000000, 0x00000000, 0x00000000,
0x00000080, 0x000003FE, 0xFFFFFFFE, 0xFFFFFFFF, 0x001FFFFF, 0xFFFFFFFE,
0xFFFFFFFF, 0x07FFFFFF, 0xFFFFFFE0, 0x00001FFF, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000000, 0x00000000,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0000000F,
0x00000000, 0x00000000, 0x00000000, 0x07FF6000, 0x87FFFFFE, 0x07FFFFFE,
0x00000000, 0x00800000, 0xFF7FFFFF, 0xFF7FFFFF, 0x00FFFFFF, 0x00000000,
0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xF80001FF, 0x00030003, 0x00000000,
0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000003, 0xFFFFD7C0, 0xFFFFFFFB,
0x547F7FFF, 0x000FFFFD, 0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF,
0xFFFF007B, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF, 0x00000000, 0xFFFE0000,
0x027FFFFF, 0xFFFFFFFE, 0xFFFE007F, 0xBBFFFFFB, 0xFFFF0016, 0x000707FF,
0x00000000, 0x07FFFFFE, 0x0007FFFF, 0xFFFF03FF, 0xFFFFFFFF, 0x7CFFFFFF,
0xFFEF7FFF, 0x03FF3DFF, 0xFFFFFFEE, 0xF3FFFFFF, 0xFF1E3FFF, 0x0000FFCF,
0xFFF99FEE, 0xD3C5FDFF, 0xB080399F, 0x0003FFCF, 0xFFF987E4, 0xD36DFDFF,
0x5E003987, 0x001FFFC0, 0xFFFBAFEE, 0xF3EDFDFF, 0x00003BBF, 0x0000FFC1,
0xFFF99FEE, 0xF3CDFDFF, 0xB0C0398F, 0x0000FFC3, 0xD63DC7EC, 0xC3BFC718,
0x00803DC7, 0x0000FF80, 0xFFFDDFEE, 0xC3EFFDFF, 0x00603DDF, 0x0000FFC3,
0xFFFDDFEC, 0xC3EFFDFF, 0x40603DDF, 0x0000FFC3, 0xFFFDDFEC, 0xC3FFFDFF,
0x00803DCF, 0x0000FFC3, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xFFFFFFFE, 0x07FF7FFF, 0x03FF7FFF, 0x00000000, 0xFEF02596, 0x3BFF6CAE,
0x03FF3F5F, 0x00000000, 0x03000000, 0xC2A003FF, 0xFFFFFEFF, 0xFFFE03FF,
0xFEBF0FDF, 0x02FE3FFF, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1FFF0000, 0x00000002,
0x000000A0, 0x003EFFFE, 0xFFFFFFFE, 0xFFFFFFFF, 0x661FFFFF, 0xFFFFFFFE,
0xFFFFFFFF, 0x77FFFFFF,
};
static const unsigned char nmstrtPages[] = {
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00,
0x00, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13,
0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x15, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x17,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x00, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, 0x00, 0x14, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x15, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};
static const unsigned char namePages[] = {
0x19, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x00,
0x00, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25,
0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13,
0x26, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x27, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x17,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x19, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x00, 0x00, 0x1F, 0x20, 0x21,
0x22, 0x23, 0x24, 0x25, 0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, 0x26, 0x14, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x27, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};

View File

@@ -1,19 +1,45 @@
/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
See the file COPYING for copying permission.
/*
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2000-2005 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2001-2002 Greg Stein <gstein@users.sourceforge.net>
Copyright (c) 2002-2016 Karl Waclawek <karl@waclawek.net>
Copyright (c) 2016-2022 Sebastian Pipping <sebastian@pipping.org>
Copyright (c) 2016 Cristian Rodríguez <crrodriguez@opensuse.org>
Copyright (c) 2016 Thomas Beutlich <tc@tbeu.de>
Copyright (c) 2017 Rhodri James <rhodri@wildebeest.org.uk>
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef Expat_INCLUDED
#define Expat_INCLUDED 1
#ifdef __VMS
/* 0 1 2 3 0 1 2 3
1234567890123456789012345678901 1234567890123456789012345678901 */
#define XML_SetProcessingInstructionHandler XML_SetProcessingInstrHandler
#define XML_SetUnparsedEntityDeclHandler XML_SetUnparsedEntDeclHandler
#define XML_SetStartNamespaceDeclHandler XML_SetStartNamespcDeclHandler
#define XML_SetExternalEntityRefHandlerArg XML_SetExternalEntRefHandlerArg
#endif
#include <stdlib.h>
#include "sg_expat_external.h"
@@ -24,10 +50,9 @@ extern "C" {
struct XML_ParserStruct;
typedef struct XML_ParserStruct *XML_Parser;
/* Should this be defined using stdbool.h when C99 is available? */
typedef unsigned char XML_Bool;
#define XML_TRUE ((XML_Bool) 1)
#define XML_FALSE ((XML_Bool) 0)
#define XML_TRUE ((XML_Bool)1)
#define XML_FALSE ((XML_Bool)0)
/* The XML_Status enum gives the possible return values for several
API functions. The preprocessor #defines are included so this
@@ -95,7 +120,13 @@ enum XML_Error {
/* Added in 2.0. */
XML_ERROR_RESERVED_PREFIX_XML,
XML_ERROR_RESERVED_PREFIX_XMLNS,
XML_ERROR_RESERVED_NAMESPACE_URI
XML_ERROR_RESERVED_NAMESPACE_URI,
/* Added in 2.2.1. */
XML_ERROR_INVALID_ARGUMENT,
/* Added in 2.3.0. */
XML_ERROR_NO_BUFFER,
/* Added in 2.4.0. */
XML_ERROR_AMPLIFICATION_LIMIT_BREACH
};
enum XML_Content_Type {
@@ -135,25 +166,23 @@ enum XML_Content_Quant {
typedef struct XML_cp XML_Content;
struct XML_cp {
enum XML_Content_Type type;
enum XML_Content_Quant quant;
XML_Char * name;
unsigned int numchildren;
XML_Content * children;
enum XML_Content_Type type;
enum XML_Content_Quant quant;
XML_Char *name;
unsigned int numchildren;
XML_Content *children;
};
/* This is called for an element declaration. See above for
description of the model argument. It's the caller's responsibility
to free model when finished with it.
*/
typedef void (XMLCALL *XML_ElementDeclHandler) (void *userData,
const XML_Char *name,
XML_Content *model);
typedef void(XMLCALL *XML_ElementDeclHandler)(void *userData,
const XML_Char *name,
XML_Content *model);
XMLPARSEAPI(void)
XML_SetElementDeclHandler(XML_Parser parser,
XML_ElementDeclHandler eldecl);
XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl);
/* The Attlist declaration handler is called for *each* attribute. So
a single Attlist declaration with multiple attributes declared will
@@ -163,17 +192,12 @@ XML_SetElementDeclHandler(XML_Parser parser,
value will be NULL in the case of "#REQUIRED". If "isrequired" is
true and default is non-NULL, then this is a "#FIXED" default.
*/
typedef void (XMLCALL *XML_AttlistDeclHandler) (
void *userData,
const XML_Char *elname,
const XML_Char *attname,
const XML_Char *att_type,
const XML_Char *dflt,
int isrequired);
typedef void(XMLCALL *XML_AttlistDeclHandler)(
void *userData, const XML_Char *elname, const XML_Char *attname,
const XML_Char *att_type, const XML_Char *dflt, int isrequired);
XMLPARSEAPI(void)
XML_SetAttlistDeclHandler(XML_Parser parser,
XML_AttlistDeclHandler attdecl);
XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl);
/* The XML declaration handler is called for *both* XML declarations
and text declarations. The way to distinguish is that the version
@@ -183,15 +207,13 @@ XML_SetAttlistDeclHandler(XML_Parser parser,
was no standalone parameter in the declaration, that it was given
as no, or that it was given as yes.
*/
typedef void (XMLCALL *XML_XmlDeclHandler) (void *userData,
const XML_Char *version,
const XML_Char *encoding,
int standalone);
typedef void(XMLCALL *XML_XmlDeclHandler)(void *userData,
const XML_Char *version,
const XML_Char *encoding,
int standalone);
XMLPARSEAPI(void)
XML_SetXmlDeclHandler(XML_Parser parser,
XML_XmlDeclHandler xmldecl);
XML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler xmldecl);
typedef struct {
void *(*malloc_fcn)(size_t size);
@@ -219,7 +241,6 @@ XML_ParserCreate(const XML_Char *encoding);
XMLPARSEAPI(XML_Parser)
XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator);
/* Constructs a new parser using the memory management suite referred to
by memsuite. If memsuite is NULL, then use the standard library memory
suite. If namespaceSeparator is non-NULL it creates a parser with
@@ -235,7 +256,7 @@ XML_ParserCreate_MM(const XML_Char *encoding,
const XML_Char *namespaceSeparator);
/* Prepare a parser object to be re-used. This is particularly
valuable when memory allocation overhead is disproportionatly high,
valuable when memory allocation overhead is disproportionately high,
such as when a large number of small documnents need to be parsed.
All handlers are cleared from the parser, except for the
unknownEncodingHandler. The parser's external state is re-initialized
@@ -249,31 +270,27 @@ XML_ParserReset(XML_Parser parser, const XML_Char *encoding);
/* atts is array of name/value pairs, terminated by 0;
names and values are 0 terminated.
*/
typedef void (XMLCALL *XML_StartElementHandler) (void *userData,
const XML_Char *name,
const XML_Char **atts);
typedef void (XMLCALL *XML_EndElementHandler) (void *userData,
const XML_Char *name);
typedef void(XMLCALL *XML_StartElementHandler)(void *userData,
const XML_Char *name,
const XML_Char **atts);
typedef void(XMLCALL *XML_EndElementHandler)(void *userData,
const XML_Char *name);
/* s is not 0 terminated. */
typedef void (XMLCALL *XML_CharacterDataHandler) (void *userData,
const XML_Char *s,
int len);
typedef void(XMLCALL *XML_CharacterDataHandler)(void *userData,
const XML_Char *s, int len);
/* target and data are 0 terminated */
typedef void (XMLCALL *XML_ProcessingInstructionHandler) (
void *userData,
const XML_Char *target,
const XML_Char *data);
typedef void(XMLCALL *XML_ProcessingInstructionHandler)(void *userData,
const XML_Char *target,
const XML_Char *data);
/* data is 0 terminated */
typedef void (XMLCALL *XML_CommentHandler) (void *userData,
const XML_Char *data);
typedef void(XMLCALL *XML_CommentHandler)(void *userData, const XML_Char *data);
typedef void (XMLCALL *XML_StartCdataSectionHandler) (void *userData);
typedef void (XMLCALL *XML_EndCdataSectionHandler) (void *userData);
typedef void(XMLCALL *XML_StartCdataSectionHandler)(void *userData);
typedef void(XMLCALL *XML_EndCdataSectionHandler)(void *userData);
/* This is called for any characters in the XML document for which
there is no applicable handler. This includes both characters that
@@ -288,25 +305,23 @@ typedef void (XMLCALL *XML_EndCdataSectionHandler) (void *userData);
default handler: for example, a comment might be split between
multiple calls.
*/
typedef void (XMLCALL *XML_DefaultHandler) (void *userData,
const XML_Char *s,
int len);
typedef void(XMLCALL *XML_DefaultHandler)(void *userData, const XML_Char *s,
int len);
/* This is called for the start of the DOCTYPE declaration, before
any DTD or internal subset is parsed.
*/
typedef void (XMLCALL *XML_StartDoctypeDeclHandler) (
void *userData,
const XML_Char *doctypeName,
const XML_Char *sysid,
const XML_Char *pubid,
int has_internal_subset);
typedef void(XMLCALL *XML_StartDoctypeDeclHandler)(void *userData,
const XML_Char *doctypeName,
const XML_Char *sysid,
const XML_Char *pubid,
int has_internal_subset);
/* This is called for the start of the DOCTYPE declaration when the
closing > is encountered, but after processing any external
subset.
*/
typedef void (XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);
typedef void(XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);
/* This is called for entity declarations. The is_parameter_entity
argument will be non-zero if the entity is a parameter entity, zero
@@ -314,7 +329,7 @@ typedef void (XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);
For internal entities (<!ENTITY foo "bar">), value will
be non-NULL and systemId, publicID, and notationName will be NULL.
The value string is NOT nul-terminated; the length is provided in
The value string is NOT null-terminated; the length is provided in
the value_length argument. Since it is legal to have zero-length
values, do not use this argument to test for internal entities.
@@ -326,23 +341,17 @@ typedef void (XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);
Note that is_parameter_entity can't be changed to XML_Bool, since
that would break binary compatibility.
*/
typedef void (XMLCALL *XML_EntityDeclHandler) (
void *userData,
const XML_Char *entityName,
int is_parameter_entity,
const XML_Char *value,
int value_length,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName);
typedef void(XMLCALL *XML_EntityDeclHandler)(
void *userData, const XML_Char *entityName, int is_parameter_entity,
const XML_Char *value, int value_length, const XML_Char *base,
const XML_Char *systemId, const XML_Char *publicId,
const XML_Char *notationName);
XMLPARSEAPI(void)
XML_SetEntityDeclHandler(XML_Parser parser,
XML_EntityDeclHandler handler);
XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler);
/* OBSOLETE -- OBSOLETE -- OBSOLETE
This handler has been superceded by the EntityDeclHandler above.
This handler has been superseded by the EntityDeclHandler above.
It is provided here for backward compatibility.
This is called for a declaration of an unparsed (NDATA) entity.
@@ -350,24 +359,20 @@ XML_SetEntityDeclHandler(XML_Parser parser,
entityName, systemId and notationName arguments will never be
NULL. The other arguments may be.
*/
typedef void (XMLCALL *XML_UnparsedEntityDeclHandler) (
void *userData,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName);
typedef void(XMLCALL *XML_UnparsedEntityDeclHandler)(
void *userData, const XML_Char *entityName, const XML_Char *base,
const XML_Char *systemId, const XML_Char *publicId,
const XML_Char *notationName);
/* This is called for a declaration of notation. The base argument is
whatever was set by XML_SetBase. The notationName will never be
NULL. The other arguments can be.
*/
typedef void (XMLCALL *XML_NotationDeclHandler) (
void *userData,
const XML_Char *notationName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId);
typedef void(XMLCALL *XML_NotationDeclHandler)(void *userData,
const XML_Char *notationName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId);
/* When namespace processing is enabled, these are called once for
each namespace declaration. The call to the start and end element
@@ -375,14 +380,12 @@ typedef void (XMLCALL *XML_NotationDeclHandler) (
declaration handlers. For an xmlns attribute, prefix will be
NULL. For an xmlns="" attribute, uri will be NULL.
*/
typedef void (XMLCALL *XML_StartNamespaceDeclHandler) (
void *userData,
const XML_Char *prefix,
const XML_Char *uri);
typedef void(XMLCALL *XML_StartNamespaceDeclHandler)(void *userData,
const XML_Char *prefix,
const XML_Char *uri);
typedef void (XMLCALL *XML_EndNamespaceDeclHandler) (
void *userData,
const XML_Char *prefix);
typedef void(XMLCALL *XML_EndNamespaceDeclHandler)(void *userData,
const XML_Char *prefix);
/* This is called if the document is not standalone, that is, it has an
external subset or a reference to a parameter entity, but does not
@@ -393,7 +396,7 @@ typedef void (XMLCALL *XML_EndNamespaceDeclHandler) (
conditions above this handler will only be called if the referenced
entity was actually read.
*/
typedef int (XMLCALL *XML_NotStandaloneHandler) (void *userData);
typedef int(XMLCALL *XML_NotStandaloneHandler)(void *userData);
/* This is called for a reference to an external parsed general
entity. The referenced entity is not automatically parsed. The
@@ -429,12 +432,11 @@ typedef int (XMLCALL *XML_NotStandaloneHandler) (void *userData);
Note that unlike other handlers the first argument is the parser,
not userData.
*/
typedef int (XMLCALL *XML_ExternalEntityRefHandler) (
XML_Parser parser,
const XML_Char *context,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId);
typedef int(XMLCALL *XML_ExternalEntityRefHandler)(XML_Parser parser,
const XML_Char *context,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId);
/* This is called in two situations:
1) An entity reference is encountered for which no declaration
@@ -446,10 +448,9 @@ typedef int (XMLCALL *XML_ExternalEntityRefHandler) (
the event would be out of sync with the reporting of the
declarations or attribute values
*/
typedef void (XMLCALL *XML_SkippedEntityHandler) (
void *userData,
const XML_Char *entityName,
int is_parameter_entity);
typedef void(XMLCALL *XML_SkippedEntityHandler)(void *userData,
const XML_Char *entityName,
int is_parameter_entity);
/* This structure is filled in by the XML_UnknownEncodingHandler to
provide information to the parser about encodings that are unknown
@@ -506,8 +507,8 @@ typedef void (XMLCALL *XML_SkippedEntityHandler) (
typedef struct {
int map[256];
void *data;
int (XMLCALL *convert)(void *data, const char *s);
void (XMLCALL *release)(void *data);
int(XMLCALL *convert)(void *data, const char *s);
void(XMLCALL *release)(void *data);
} XML_Encoding;
/* This is called for an encoding that is unknown to the parser.
@@ -523,25 +524,21 @@ typedef struct {
Otherwise it must return XML_STATUS_ERROR.
If info does not describe a suitable encoding, then the parser will
return an XML_UNKNOWN_ENCODING error.
return an XML_ERROR_UNKNOWN_ENCODING error.
*/
typedef int (XMLCALL *XML_UnknownEncodingHandler) (
void *encodingHandlerData,
const XML_Char *name,
XML_Encoding *info);
typedef int(XMLCALL *XML_UnknownEncodingHandler)(void *encodingHandlerData,
const XML_Char *name,
XML_Encoding *info);
XMLPARSEAPI(void)
XML_SetElementHandler(XML_Parser parser,
XML_StartElementHandler start,
XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,
XML_EndElementHandler end);
XMLPARSEAPI(void)
XML_SetStartElementHandler(XML_Parser parser,
XML_StartElementHandler handler);
XML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler handler);
XMLPARSEAPI(void)
XML_SetEndElementHandler(XML_Parser parser,
XML_EndElementHandler handler);
XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler handler);
XMLPARSEAPI(void)
XML_SetCharacterDataHandler(XML_Parser parser,
@@ -551,8 +548,7 @@ XMLPARSEAPI(void)
XML_SetProcessingInstructionHandler(XML_Parser parser,
XML_ProcessingInstructionHandler handler);
XMLPARSEAPI(void)
XML_SetCommentHandler(XML_Parser parser,
XML_CommentHandler handler);
XML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler);
XMLPARSEAPI(void)
XML_SetCdataSectionHandler(XML_Parser parser,
@@ -572,20 +568,17 @@ XML_SetEndCdataSectionHandler(XML_Parser parser,
default handler, or to the skipped entity handler, if one is set.
*/
XMLPARSEAPI(void)
XML_SetDefaultHandler(XML_Parser parser,
XML_DefaultHandler handler);
XML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler);
/* This sets the default handler but does not inhibit expansion of
internal entities. The entity reference will not be passed to the
default handler.
*/
XMLPARSEAPI(void)
XML_SetDefaultHandlerExpand(XML_Parser parser,
XML_DefaultHandler handler);
XML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler);
XMLPARSEAPI(void)
XML_SetDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start,
XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,
XML_EndDoctypeDeclHandler end);
XMLPARSEAPI(void)
@@ -593,16 +586,14 @@ XML_SetStartDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start);
XMLPARSEAPI(void)
XML_SetEndDoctypeDeclHandler(XML_Parser parser,
XML_EndDoctypeDeclHandler end);
XML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end);
XMLPARSEAPI(void)
XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
XML_UnparsedEntityDeclHandler handler);
XMLPARSEAPI(void)
XML_SetNotationDeclHandler(XML_Parser parser,
XML_NotationDeclHandler handler);
XML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler);
XMLPARSEAPI(void)
XML_SetNamespaceDeclHandler(XML_Parser parser,
@@ -630,8 +621,7 @@ XML_SetExternalEntityRefHandler(XML_Parser parser,
instead of the parser object.
*/
XMLPARSEAPI(void)
XML_SetExternalEntityRefHandlerArg(XML_Parser parser,
void *arg);
XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg);
XMLPARSEAPI(void)
XML_SetSkippedEntityHandler(XML_Parser parser,
@@ -706,11 +696,11 @@ XML_UseParserAsHandlerArg(XML_Parser parser);
be called, despite an external subset being parsed.
Note: If XML_DTD is not defined when Expat is compiled, returns
XML_ERROR_FEATURE_REQUIRES_XML_DTD.
Note: If parser == NULL, returns XML_ERROR_INVALID_ARGUMENT.
*/
XMLPARSEAPI(enum XML_Error)
XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD);
/* Sets the base to be used for resolving relative URIs in system
identifiers in declarations. Resolving relative identifiers is
left to the application: this value will be passed through as the
@@ -728,16 +718,17 @@ XML_GetBase(XML_Parser parser);
/* Returns the number of the attribute/value pairs passed in last call
to the XML_StartElementHandler that were specified in the start-tag
rather than defaulted. Each attribute/value pair counts as 2; thus
this correspondds to an index into the atts array passed to the
XML_StartElementHandler.
this corresponds to an index into the atts array passed to the
XML_StartElementHandler. Returns -1 if parser == NULL.
*/
XMLPARSEAPI(int)
XML_GetSpecifiedAttributeCount(XML_Parser parser);
/* Returns the index of the ID attribute passed in the last call to
XML_StartElementHandler, or -1 if there is no ID attribute. Each
attribute/value pair counts as 2; thus this correspondds to an
index into the atts array passed to the XML_StartElementHandler.
XML_StartElementHandler, or -1 if there is no ID attribute or
parser == NULL. Each attribute/value pair counts as 2; thus this
corresponds to an index into the atts array passed to the
XML_StartElementHandler.
*/
XMLPARSEAPI(int)
XML_GetIdAttributeIndex(XML_Parser parser);
@@ -749,10 +740,10 @@ XML_GetIdAttributeIndex(XML_Parser parser);
info->valueEnd - info->valueStart = 4 bytes.
*/
typedef struct {
XML_Index nameStart; /* Offset to beginning of the attribute name. */
XML_Index nameEnd; /* Offset after the attribute name's last byte. */
XML_Index valueStart; /* Offset to beginning of the attribute value. */
XML_Index valueEnd; /* Offset after the attribute value's last byte. */
XML_Index nameStart; /* Offset to beginning of the attribute name. */
XML_Index nameEnd; /* Offset after the attribute name's last byte. */
XML_Index valueStart; /* Offset to beginning of the attribute value. */
XML_Index valueEnd; /* Offset after the attribute value's last byte. */
} XML_AttrInfo;
/* Returns an array of XML_AttrInfo structures for the attribute/value pairs
@@ -788,20 +779,20 @@ XML_ParseBuffer(XML_Parser parser, int len, int isFinal);
(resumable = 0) an already suspended parser. Some call-backs may
still follow because they would otherwise get lost. Examples:
- endElementHandler() for empty elements when stopped in
startElementHandler(),
- endNameSpaceDeclHandler() when stopped in endElementHandler(),
startElementHandler(),
- endNameSpaceDeclHandler() when stopped in endElementHandler(),
and possibly others.
Can be called from most handlers, including DTD related call-backs,
except when parsing an external parameter entity and resumable != 0.
Returns XML_STATUS_OK when successful, XML_STATUS_ERROR otherwise.
Possible error codes:
Possible error codes:
- XML_ERROR_SUSPENDED: when suspending an already suspended parser.
- XML_ERROR_FINISHED: when the parser has already finished.
- XML_ERROR_SUSPEND_PE: when suspending while parsing an external PE.
When resumable != 0 (true) then parsing is suspended, that is,
XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED.
When resumable != 0 (true) then parsing is suspended, that is,
XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED.
Otherwise, parsing is aborted, that is, XML_Parse() and XML_ParseBuffer()
return XML_STATUS_ERROR with error code XML_ERROR_ABORTED.
@@ -812,7 +803,7 @@ XML_ParseBuffer(XML_Parser parser, int len, int isFinal);
the externalEntityRefHandler() to call XML_StopParser() on the parent
parser (recursively), if one wants to stop parsing altogether.
When suspended, parsing can be resumed by calling XML_ResumeParser().
When suspended, parsing can be resumed by calling XML_ResumeParser().
*/
XMLPARSEAPI(enum XML_Status)
XML_StopParser(XML_Parser parser, XML_Bool resumable);
@@ -820,7 +811,7 @@ XML_StopParser(XML_Parser parser, XML_Bool resumable);
/* Resumes parsing after it has been suspended with XML_StopParser().
Must not be called from within a handler call-back. Returns same
status codes as XML_Parse() or XML_ParseBuffer().
Additional error code XML_ERROR_NOT_SUSPENDED possible.
Additional error code XML_ERROR_NOT_SUSPENDED possible.
*Note*:
This must be called on the most deeply nested child parser instance
@@ -832,12 +823,7 @@ XML_StopParser(XML_Parser parser, XML_Bool resumable);
XMLPARSEAPI(enum XML_Status)
XML_ResumeParser(XML_Parser parser);
enum XML_Parsing {
XML_INITIALIZED,
XML_PARSING,
XML_FINISHED,
XML_SUSPENDED
};
enum XML_Parsing { XML_INITIALIZED, XML_PARSING, XML_FINISHED, XML_SUSPENDED };
typedef struct {
enum XML_Parsing parsing;
@@ -869,8 +855,7 @@ XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status);
Otherwise returns a new XML_Parser object.
*/
XMLPARSEAPI(XML_Parser)
XML_ExternalEntityParserCreate(XML_Parser parser,
const XML_Char *context,
XML_ExternalEntityParserCreate(XML_Parser parser, const XML_Char *context,
const XML_Char *encoding);
enum XML_ParamEntityParsing {
@@ -901,6 +886,7 @@ enum XML_ParamEntityParsing {
entities is requested; otherwise it will return non-zero.
Note: If XML_SetParamEntityParsing is called after XML_Parse or
XML_ParseBuffer, then it has no effect and will always return 0.
Note: If parser == NULL, the function will do nothing and return 0.
*/
XMLPARSEAPI(int)
XML_SetParamEntityParsing(XML_Parser parser,
@@ -910,10 +896,10 @@ XML_SetParamEntityParsing(XML_Parser parser,
Helps in preventing DoS attacks based on predicting hash
function behavior. This must be called before parsing is started.
Returns 1 if successful, 0 when called after parsing has started.
Note: If parser == NULL, the function will do nothing and return 0.
*/
XMLPARSEAPI(int)
XML_SetHashSalt(XML_Parser parser,
unsigned long hash_salt);
XML_SetHashSalt(XML_Parser parser, unsigned long hash_salt);
/* If XML_Parse or XML_ParseBuffer have returned XML_STATUS_ERROR, then
XML_GetErrorCode returns information about the error.
@@ -930,12 +916,16 @@ XML_GetErrorCode(XML_Parser parser);
be within the relevant markup. When called outside of the callback
functions, the position indicated will be just past the last parse
event (regardless of whether there was an associated callback).
They may also be called after returning from a call to XML_Parse
or XML_ParseBuffer. If the return value is XML_STATUS_ERROR then
the location is the location of the character at which the error
was detected; otherwise the location is the location of the last
parse event, as described above.
Note: XML_GetCurrentLineNumber and XML_GetCurrentColumnNumber
return 0 to indicate an error.
Note: XML_GetCurrentByteIndex returns -1 to indicate an error.
*/
XMLPARSEAPI(XML_Size) XML_GetCurrentLineNumber(XML_Parser parser);
XMLPARSEAPI(XML_Size) XML_GetCurrentColumnNumber(XML_Parser parser);
@@ -958,14 +948,12 @@ XML_GetCurrentByteCount(XML_Parser parser);
the handler that makes the call.
*/
XMLPARSEAPI(const char *)
XML_GetInputContext(XML_Parser parser,
int *offset,
int *size);
XML_GetInputContext(XML_Parser parser, int *offset, int *size);
/* For backwards compatibility with previous versions. */
#define XML_GetErrorLineNumber XML_GetCurrentLineNumber
#define XML_GetErrorLineNumber XML_GetCurrentLineNumber
#define XML_GetErrorColumnNumber XML_GetCurrentColumnNumber
#define XML_GetErrorByteIndex XML_GetCurrentByteIndex
#define XML_GetErrorByteIndex XML_GetCurrentByteIndex
/* Frees the content model passed to the element declaration handler */
XMLPARSEAPI(void)
@@ -973,9 +961,12 @@ XML_FreeContentModel(XML_Parser parser, XML_Content *model);
/* Exposing the memory handling functions used in Expat */
XMLPARSEAPI(void *)
XML_ATTR_MALLOC
XML_ATTR_ALLOC_SIZE(2)
XML_MemMalloc(XML_Parser parser, size_t size);
XMLPARSEAPI(void *)
XML_ATTR_ALLOC_SIZE(3)
XML_MemRealloc(XML_Parser parser, void *ptr, size_t size);
XMLPARSEAPI(void)
@@ -1017,28 +1008,40 @@ enum XML_FeatureEnum {
XML_FEATURE_SIZEOF_XML_LCHAR,
XML_FEATURE_NS,
XML_FEATURE_LARGE_SIZE,
XML_FEATURE_ATTR_INFO
XML_FEATURE_ATTR_INFO,
/* Added in Expat 2.4.0. */
XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT,
XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT
/* Additional features must be added to the end of this enum. */
};
typedef struct {
enum XML_FeatureEnum feature;
const XML_LChar *name;
long int value;
enum XML_FeatureEnum feature;
const XML_LChar *name;
long int value;
} XML_Feature;
XMLPARSEAPI(const XML_Feature *)
XML_GetFeatureList(void);
#ifdef XML_DTD
/* Added in Expat 2.4.0. */
XMLPARSEAPI(XML_Bool)
XML_SetBillionLaughsAttackProtectionMaximumAmplification(
XML_Parser parser, float maximumAmplificationFactor);
/* Expat follows the GNU/Linux convention of odd number minor version for
beta/development releases and even number minor version for stable
releases. Micro is bumped with each release, and set to 0 with each
change to major or minor version.
/* Added in Expat 2.4.0. */
XMLPARSEAPI(XML_Bool)
XML_SetBillionLaughsAttackProtectionActivationThreshold(
XML_Parser parser, unsigned long long activationThresholdBytes);
#endif
/* Expat follows the semantic versioning convention.
See http://semver.org.
*/
#define XML_MAJOR_VERSION 2
#define XML_MINOR_VERSION 1
#define XML_MICRO_VERSION 0
#define XML_MINOR_VERSION 4
#define XML_MICRO_VERSION 4
#ifdef __cplusplus
}

View File

@@ -1,5 +1,40 @@
/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
See the file COPYING for copying permission.
/*
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2000-2004 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2001-2002 Greg Stein <gstein@users.sourceforge.net>
Copyright (c) 2002-2006 Karl Waclawek <karl@waclawek.net>
Copyright (c) 2016 Cristian Rodríguez <crrodriguez@opensuse.org>
Copyright (c) 2016-2019 Sebastian Pipping <sebastian@pipping.org>
Copyright (c) 2017 Rhodri James <rhodri@wildebeest.org.uk>
Copyright (c) 2018 Yury Gribov <tetra2005@gmail.com>
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef Expat_External_INCLUDED
@@ -7,10 +42,6 @@
/* External API definitions */
#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)
#define XML_USE_MSC_EXTENSIONS 1
#endif
/* Expat tries very hard to make the API boundary very specifically
defined. There are two macros defined to control this boundary;
each of these can be defined before including this header to
@@ -34,11 +65,11 @@
system headers may assume the cdecl convention.
*/
#ifndef XMLCALL
#if defined(_MSC_VER)
#define XMLCALL __cdecl
#elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER)
#define XMLCALL __attribute__((cdecl))
#else
# if defined(_MSC_VER)
# define XMLCALL __cdecl
# elif defined(__GNUC__) && defined(__i386) && ! defined(__INTEL_COMPILER)
# define XMLCALL __attribute__((cdecl))
# else
/* For any platform which uses this definition and supports more than
one calling convention, we need to extend this definition to
declare the convention used on that platform, if it's possible to
@@ -49,28 +80,47 @@
pre-processor and how to specify the same calling convention as the
platform's malloc() implementation.
*/
#define XMLCALL
#endif
#endif /* not defined XMLCALL */
# define XMLCALL
# endif
#endif /* not defined XMLCALL */
#if !defined(XML_STATIC) && !defined(XMLIMPORT)
#ifndef XML_BUILDING_EXPAT
#if ! defined(XML_STATIC) && ! defined(XMLIMPORT)
# ifndef XML_BUILDING_EXPAT
/* using Expat from an application */
#ifdef XML_USE_MSC_EXTENSIONS
#define XMLIMPORT __declspec(dllimport)
# if defined(_MSC_EXTENSIONS) && ! defined(__BEOS__) && ! defined(__CYGWIN__)
# define XMLIMPORT __declspec(dllimport)
# endif
# endif
#endif /* not defined XML_STATIC */
#ifndef XML_ENABLE_VISIBILITY
# define XML_ENABLE_VISIBILITY 0
#endif
#if ! defined(XMLIMPORT) && XML_ENABLE_VISIBILITY
# define XMLIMPORT __attribute__((visibility("default")))
#endif
#endif /* not defined XML_STATIC */
/* If we didn't define it above, define it away: */
#ifndef XMLIMPORT
#define XMLIMPORT
# define XMLIMPORT
#endif
#if defined(__GNUC__) \
&& (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96))
# define XML_ATTR_MALLOC __attribute__((__malloc__))
#else
# define XML_ATTR_MALLOC
#endif
#if defined(__GNUC__) \
&& ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
# define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x)))
#else
# define XML_ATTR_ALLOC_SIZE(x)
#endif
#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL
@@ -79,30 +129,30 @@ extern "C" {
#endif
#ifdef XML_UNICODE_WCHAR_T
#define XML_UNICODE
# ifndef XML_UNICODE
# define XML_UNICODE
# endif
# if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2)
# error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc"
# endif
#endif
#ifdef XML_UNICODE /* Information is UTF-16 encoded. */
#ifdef XML_UNICODE_WCHAR_T
#ifdef XML_UNICODE /* Information is UTF-16 encoded. */
# ifdef XML_UNICODE_WCHAR_T
typedef wchar_t XML_Char;
typedef wchar_t XML_LChar;
#else
# else
typedef unsigned short XML_Char;
typedef char XML_LChar;
#endif /* XML_UNICODE_WCHAR_T */
#else /* Information is UTF-8 encoded. */
# endif /* XML_UNICODE_WCHAR_T */
#else /* Information is UTF-8 encoded. */
typedef char XML_Char;
typedef char XML_LChar;
#endif /* XML_UNICODE */
#endif /* XML_UNICODE */
#ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */
#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
typedef __int64 XML_Index;
typedef unsigned __int64 XML_Size;
#else
#ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */
typedef long long XML_Index;
typedef unsigned long long XML_Size;
#endif
#else
typedef long XML_Index;
typedef unsigned long XML_Size;

393
3rdparty/expat/siphash.h vendored Normal file
View File

@@ -0,0 +1,393 @@
/* ==========================================================================
* siphash.h - SipHash-2-4 in a single header file
* --------------------------------------------------------------------------
* Derived by William Ahern from the reference implementation[1] published[2]
* by Jean-Philippe Aumasson and Daniel J. Berstein.
* Minimal changes by Sebastian Pipping and Victor Stinner on top, see below.
* Licensed under the CC0 Public Domain Dedication license.
*
* 1. https://www.131002.net/siphash/siphash24.c
* 2. https://www.131002.net/siphash/
* --------------------------------------------------------------------------
* HISTORY:
*
* 2020-10-03 (Sebastian Pipping)
* - Drop support for Visual Studio 9.0/2008 and earlier
*
* 2019-08-03 (Sebastian Pipping)
* - Mark part of sip24_valid as to be excluded from clang-format
* - Re-format code using clang-format 9
*
* 2018-07-08 (Anton Maklakov)
* - Add "fall through" markers for GCC's -Wimplicit-fallthrough
*
* 2017-11-03 (Sebastian Pipping)
* - Hide sip_tobin and sip_binof unless SIPHASH_TOBIN macro is defined
*
* 2017-07-25 (Vadim Zeitlin)
* - Fix use of SIPHASH_MAIN macro
*
* 2017-07-05 (Sebastian Pipping)
* - Use _SIP_ULL macro to not require a C++11 compiler if compiled as C++
* - Add const qualifiers at two places
* - Ensure <=80 characters line length (assuming tab width 4)
*
* 2017-06-23 (Victor Stinner)
* - Address Win64 compile warnings
*
* 2017-06-18 (Sebastian Pipping)
* - Clarify license note in the header
* - Address C89 issues:
* - Stop using inline keyword (and let compiler decide)
* - Replace _Bool by int
* - Turn macro siphash24 into a function
* - Address invalid conversion (void pointer) by explicit cast
* - Address lack of stdint.h for Visual Studio 2003 to 2008
* - Always expose sip24_valid (for self-tests)
*
* 2012-11-04 - Born. (William Ahern)
* --------------------------------------------------------------------------
* USAGE:
*
* SipHash-2-4 takes as input two 64-bit words as the key, some number of
* message bytes, and outputs a 64-bit word as the message digest. This
* implementation employs two data structures: a struct sipkey for
* representing the key, and a struct siphash for representing the hash
* state.
*
* For converting a 16-byte unsigned char array to a key, use either the
* macro sip_keyof or the routine sip_tokey. The former instantiates a
* compound literal key, while the latter requires a key object as a
* parameter.
*
* unsigned char secret[16];
* arc4random_buf(secret, sizeof secret);
* struct sipkey *key = sip_keyof(secret);
*
* For hashing a message, use either the convenience macro siphash24 or the
* routines sip24_init, sip24_update, and sip24_final.
*
* struct siphash state;
* void *msg;
* size_t len;
* uint64_t hash;
*
* sip24_init(&state, key);
* sip24_update(&state, msg, len);
* hash = sip24_final(&state);
*
* or
*
* hash = siphash24(msg, len, key);
*
* To convert the 64-bit hash value to a canonical 8-byte little-endian
* binary representation, use either the macro sip_binof or the routine
* sip_tobin. The former instantiates and returns a compound literal array,
* while the latter requires an array object as a parameter.
* --------------------------------------------------------------------------
* NOTES:
*
* o Neither sip_keyof, sip_binof, nor siphash24 will work with compilers
* lacking compound literal support. Instead, you must use the lower-level
* interfaces which take as parameters the temporary state objects.
*
* o Uppercase macros may evaluate parameters more than once. Lowercase
* macros should not exhibit any such side effects.
* ==========================================================================
*/
#ifndef SIPHASH_H
#define SIPHASH_H
#include <stddef.h> /* size_t */
#include <stdint.h> /* uint64_t uint32_t uint8_t */
/*
* Workaround to not require a C++11 compiler for using ULL suffix
* if this code is included and compiled as C++; related GCC warning is:
* warning: use of C++11 long long integer constant [-Wlong-long]
*/
#define _SIP_ULL(high, low) (((uint64_t)high << 32) | low)
#define SIP_ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b))))
#define SIP_U32TO8_LE(p, v) \
(p)[0] = (uint8_t)((v) >> 0); \
(p)[1] = (uint8_t)((v) >> 8); \
(p)[2] = (uint8_t)((v) >> 16); \
(p)[3] = (uint8_t)((v) >> 24);
#define SIP_U64TO8_LE(p, v) \
SIP_U32TO8_LE((p) + 0, (uint32_t)((v) >> 0)); \
SIP_U32TO8_LE((p) + 4, (uint32_t)((v) >> 32));
#define SIP_U8TO64_LE(p) \
(((uint64_t)((p)[0]) << 0) | ((uint64_t)((p)[1]) << 8) \
| ((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) \
| ((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) \
| ((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56))
#define SIPHASH_INITIALIZER \
{ 0, 0, 0, 0, {0}, 0, 0 }
struct siphash {
uint64_t v0, v1, v2, v3;
unsigned char buf[8], *p;
uint64_t c;
}; /* struct siphash */
#define SIP_KEYLEN 16
struct sipkey {
uint64_t k[2];
}; /* struct sipkey */
#define sip_keyof(k) sip_tokey(&(struct sipkey){{0}}, (k))
static struct sipkey *
sip_tokey(struct sipkey *key, const void *src) {
key->k[0] = SIP_U8TO64_LE((const unsigned char *)src);
key->k[1] = SIP_U8TO64_LE((const unsigned char *)src + 8);
return key;
} /* sip_tokey() */
#ifdef SIPHASH_TOBIN
# define sip_binof(v) sip_tobin((unsigned char[8]){0}, (v))
static void *
sip_tobin(void *dst, uint64_t u64) {
SIP_U64TO8_LE((unsigned char *)dst, u64);
return dst;
} /* sip_tobin() */
#endif /* SIPHASH_TOBIN */
static void
sip_round(struct siphash *H, const int rounds) {
int i;
for (i = 0; i < rounds; i++) {
H->v0 += H->v1;
H->v1 = SIP_ROTL(H->v1, 13);
H->v1 ^= H->v0;
H->v0 = SIP_ROTL(H->v0, 32);
H->v2 += H->v3;
H->v3 = SIP_ROTL(H->v3, 16);
H->v3 ^= H->v2;
H->v0 += H->v3;
H->v3 = SIP_ROTL(H->v3, 21);
H->v3 ^= H->v0;
H->v2 += H->v1;
H->v1 = SIP_ROTL(H->v1, 17);
H->v1 ^= H->v2;
H->v2 = SIP_ROTL(H->v2, 32);
}
} /* sip_round() */
static struct siphash *
sip24_init(struct siphash *H, const struct sipkey *key) {
H->v0 = _SIP_ULL(0x736f6d65U, 0x70736575U) ^ key->k[0];
H->v1 = _SIP_ULL(0x646f7261U, 0x6e646f6dU) ^ key->k[1];
H->v2 = _SIP_ULL(0x6c796765U, 0x6e657261U) ^ key->k[0];
H->v3 = _SIP_ULL(0x74656462U, 0x79746573U) ^ key->k[1];
H->p = H->buf;
H->c = 0;
return H;
} /* sip24_init() */
#define sip_endof(a) (&(a)[sizeof(a) / sizeof *(a)])
static struct siphash *
sip24_update(struct siphash *H, const void *src, size_t len) {
const unsigned char *p = (const unsigned char *)src, *pe = p + len;
uint64_t m;
do {
while (p < pe && H->p < sip_endof(H->buf))
*H->p++ = *p++;
if (H->p < sip_endof(H->buf))
break;
m = SIP_U8TO64_LE(H->buf);
H->v3 ^= m;
sip_round(H, 2);
H->v0 ^= m;
H->p = H->buf;
H->c += 8;
} while (p < pe);
return H;
} /* sip24_update() */
static uint64_t
sip24_final(struct siphash *H) {
const char left = (char)(H->p - H->buf);
uint64_t b = (H->c + left) << 56;
switch (left) {
case 7:
b |= (uint64_t)H->buf[6] << 48;
/* fall through */
case 6:
b |= (uint64_t)H->buf[5] << 40;
/* fall through */
case 5:
b |= (uint64_t)H->buf[4] << 32;
/* fall through */
case 4:
b |= (uint64_t)H->buf[3] << 24;
/* fall through */
case 3:
b |= (uint64_t)H->buf[2] << 16;
/* fall through */
case 2:
b |= (uint64_t)H->buf[1] << 8;
/* fall through */
case 1:
b |= (uint64_t)H->buf[0] << 0;
/* fall through */
case 0:
break;
}
H->v3 ^= b;
sip_round(H, 2);
H->v0 ^= b;
H->v2 ^= 0xff;
sip_round(H, 4);
return H->v0 ^ H->v1 ^ H->v2 ^ H->v3;
} /* sip24_final() */
static uint64_t
siphash24(const void *src, size_t len, const struct sipkey *key) {
struct siphash state = SIPHASH_INITIALIZER;
return sip24_final(sip24_update(sip24_init(&state, key), src, len));
} /* siphash24() */
/*
* SipHash-2-4 output with
* k = 00 01 02 ...
* and
* in = (empty string)
* in = 00 (1 byte)
* in = 00 01 (2 bytes)
* in = 00 01 02 (3 bytes)
* ...
* in = 00 01 02 ... 3e (63 bytes)
*/
static int
sip24_valid(void) {
/* clang-format off */
static const unsigned char vectors[64][8] = {
{ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, },
{ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, },
{ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, },
{ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, },
{ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, },
{ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, },
{ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, },
{ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, },
{ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, },
{ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, },
{ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, },
{ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, },
{ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, },
{ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, },
{ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, },
{ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, },
{ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, },
{ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, },
{ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, },
{ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, },
{ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, },
{ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, },
{ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, },
{ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, },
{ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, },
{ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, },
{ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, },
{ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, },
{ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, },
{ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, },
{ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, },
{ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, },
{ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, },
{ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, },
{ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, },
{ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, },
{ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, },
{ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, },
{ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, },
{ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, },
{ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, },
{ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, },
{ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, },
{ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, },
{ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, },
{ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, },
{ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, },
{ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, },
{ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, },
{ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, },
{ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, },
{ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, },
{ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, },
{ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, },
{ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, },
{ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, },
{ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, },
{ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, },
{ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, },
{ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, },
{ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, },
{ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, },
{ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, },
{ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, }
};
/* clang-format on */
unsigned char in[64];
struct sipkey k;
size_t i;
sip_tokey(&k, "\000\001\002\003\004\005\006\007\010\011"
"\012\013\014\015\016\017");
for (i = 0; i < sizeof in; ++i) {
in[i] = (unsigned char)i;
if (siphash24(in, i, &k) != SIP_U8TO64_LE(vectors[i]))
return 0;
}
return 1;
} /* sip24_valid() */
#ifdef SIPHASH_MAIN
# include <stdio.h>
int
main(void) {
const int ok = sip24_valid();
if (ok)
puts("OK");
else
puts("FAIL");
return ! ok;
} /* main() */
#endif /* SIPHASH_MAIN */
#endif /* SIPHASH_H */

View File

@@ -1,63 +1,66 @@
/*
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2002 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2017 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
The Original Code is expat.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The Initial Developer of the Original Code is James Clark.
Portions created by James Clark are Copyright (C) 1998, 1999
James Clark. All Rights Reserved.
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
Contributor(s):
Alternatively, the contents of this file may be used under the terms
of the GNU General Public License (the "GPL"), in which case the
provisions of the GPL are applicable instead of those above. If you
wish to allow use of your version of this file only under the terms of
the GPL and not to allow others to use your version of this file under
the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the
GPL. If you do not delete the provisions above, a recipient may use
your version of this file under either the MPL or the GPL.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* 0x80 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x88 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x8C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x90 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x94 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x98 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x9C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xA0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xA4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xA8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xAC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xB0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xB4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xB8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xBC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xC0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xC4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xC8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xCC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xD0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xD4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xD8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xDC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xE0 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
/* 0xE4 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
/* 0xE8 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
/* 0xEC */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
/* 0xF0 */ BT_LEAD4, BT_LEAD4, BT_LEAD4, BT_LEAD4,
/* 0xF4 */ BT_LEAD4, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0xF8 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0xFC */ BT_NONXML, BT_NONXML, BT_MALFORM, BT_MALFORM,
/* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x88 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x8C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x90 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x94 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x98 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x9C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xA0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xA4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xA8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xAC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xB0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xB4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xB8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xBC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0xC0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xC4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xC8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xCC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xD0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xD4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xD8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xDC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
/* 0xE0 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
/* 0xE4 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
/* 0xE8 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
/* 0xEC */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
/* 0xF0 */ BT_LEAD4, BT_LEAD4, BT_LEAD4, BT_LEAD4,
/* 0xF4 */ BT_LEAD4, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0xF8 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
/* 0xFC */ BT_NONXML, BT_NONXML, BT_MALFORM, BT_MALFORM,

45
3rdparty/expat/winconfig.h vendored Normal file
View File

@@ -0,0 +1,45 @@
/*
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2002 Greg Stein <gstein@users.sourceforge.net>
Copyright (c) 2005 Karl Waclawek <karl@waclawek.net>
Copyright (c) 2017-2021 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WINCONFIG_H
#define WINCONFIG_H
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#include <memory.h>
#include <string.h>
#endif /* ndef WINCONFIG_H */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,36 @@
/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
See the file COPYING for copying permission.
/*
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2002 Karl Waclawek <karl@waclawek.net>
Copyright (c) 2002 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2017 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef XmlRole_INCLUDED
@@ -8,7 +39,7 @@
#ifdef __VMS
/* 0 1 2 3 0 1 2 3
1234567890123456789012345678901 1234567890123456789012345678901 */
#define XmlPrologStateInitExternalEntity XmlPrologStateInitExternalEnt
# define XmlPrologStateInitExternalEntity XmlPrologStateInitExternalEnt
#endif
#include "xmltok.h"
@@ -85,11 +116,8 @@ enum {
};
typedef struct prolog_state {
int (PTRCALL *handler) (struct prolog_state *state,
int tok,
const char *ptr,
const char *end,
const ENCODING *enc);
int(PTRCALL *handler)(struct prolog_state *state, int tok, const char *ptr,
const char *end, const ENCODING *enc);
unsigned level;
int role_none;
#ifdef XML_DTD
@@ -104,8 +132,8 @@ void XmlPrologStateInit(PROLOG_STATE *);
void XmlPrologStateInitExternalEntity(PROLOG_STATE *);
#endif /* XML_DTD */
#define XmlTokenRole(state, tok, ptr, end, enc) \
(((state)->handler)(state, tok, ptr, end, enc))
#define XmlTokenRole(state, tok, ptr, end, enc) \
(((state)->handler)(state, tok, ptr, end, enc))
#ifdef __cplusplus
}

1522
3rdparty/expat/xmltok.c vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,37 @@
/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
See the file COPYING for copying permission.
/*
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2002 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2002-2005 Karl Waclawek <karl@waclawek.net>
Copyright (c) 2016-2017 Sebastian Pipping <sebastian@pipping.org>
Copyright (c) 2017 Rhodri James <rhodri@wildebeest.org.uk>
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef XmlTok_INCLUDED
@@ -10,16 +42,18 @@ extern "C" {
#endif
/* The following token may be returned by XmlContentTok */
#define XML_TOK_TRAILING_RSQB -5 /* ] or ]] at the end of the scan; might be
start of illegal ]]> sequence */
#define XML_TOK_TRAILING_RSQB \
-5 /* ] or ]] at the end of the scan; might be \
start of illegal ]]> sequence */
/* The following tokens may be returned by both XmlPrologTok and
XmlContentTok.
*/
#define XML_TOK_NONE -4 /* The string to be scanned is empty */
#define XML_TOK_TRAILING_CR -3 /* A CR at the end of the scan;
might be part of CRLF sequence */
#define XML_TOK_PARTIAL_CHAR -2 /* only part of a multibyte sequence */
#define XML_TOK_PARTIAL -1 /* only part of a token */
#define XML_TOK_NONE -4 /* The string to be scanned is empty */
#define XML_TOK_TRAILING_CR \
-3 /* A CR at the end of the scan; \
might be part of CRLF sequence */
#define XML_TOK_PARTIAL_CHAR -2 /* only part of a multibyte sequence */
#define XML_TOK_PARTIAL -1 /* only part of a token */
#define XML_TOK_INVALID 0
/* The following tokens are returned by XmlContentTok; some are also
@@ -34,24 +68,24 @@ extern "C" {
#define XML_TOK_DATA_NEWLINE 7
#define XML_TOK_CDATA_SECT_OPEN 8
#define XML_TOK_ENTITY_REF 9
#define XML_TOK_CHAR_REF 10 /* numeric character reference */
#define XML_TOK_CHAR_REF 10 /* numeric character reference */
/* The following tokens may be returned by both XmlPrologTok and
XmlContentTok.
*/
#define XML_TOK_PI 11 /* processing instruction */
#define XML_TOK_XML_DECL 12 /* XML decl or text decl */
#define XML_TOK_PI 11 /* processing instruction */
#define XML_TOK_XML_DECL 12 /* XML decl or text decl */
#define XML_TOK_COMMENT 13
#define XML_TOK_BOM 14 /* Byte order mark */
#define XML_TOK_BOM 14 /* Byte order mark */
/* The following tokens are returned only by XmlPrologTok */
#define XML_TOK_PROLOG_S 15
#define XML_TOK_DECL_OPEN 16 /* <!foo */
#define XML_TOK_DECL_CLOSE 17 /* > */
#define XML_TOK_DECL_OPEN 16 /* <!foo */
#define XML_TOK_DECL_CLOSE 17 /* > */
#define XML_TOK_NAME 18
#define XML_TOK_NMTOKEN 19
#define XML_TOK_POUND_NAME 20 /* #name */
#define XML_TOK_OR 21 /* | */
#define XML_TOK_POUND_NAME 20 /* #name */
#define XML_TOK_OR 21 /* | */
#define XML_TOK_PERCENT 22
#define XML_TOK_OPEN_PAREN 23
#define XML_TOK_CLOSE_PAREN 24
@@ -62,14 +96,14 @@ extern "C" {
#define XML_TOK_INSTANCE_START 29
/* The following occur only in element type declarations */
#define XML_TOK_NAME_QUESTION 30 /* name? */
#define XML_TOK_NAME_ASTERISK 31 /* name* */
#define XML_TOK_NAME_PLUS 32 /* name+ */
#define XML_TOK_COND_SECT_OPEN 33 /* <![ */
#define XML_TOK_COND_SECT_CLOSE 34 /* ]]> */
#define XML_TOK_CLOSE_PAREN_QUESTION 35 /* )? */
#define XML_TOK_CLOSE_PAREN_ASTERISK 36 /* )* */
#define XML_TOK_CLOSE_PAREN_PLUS 37 /* )+ */
#define XML_TOK_NAME_QUESTION 30 /* name? */
#define XML_TOK_NAME_ASTERISK 31 /* name* */
#define XML_TOK_NAME_PLUS 32 /* name+ */
#define XML_TOK_COND_SECT_OPEN 33 /* <![ */
#define XML_TOK_COND_SECT_CLOSE 34 /* ]]> */
#define XML_TOK_CLOSE_PAREN_QUESTION 35 /* )? */
#define XML_TOK_CLOSE_PAREN_ASTERISK 36 /* )* */
#define XML_TOK_CLOSE_PAREN_PLUS 37 /* )+ */
#define XML_TOK_COMMA 38
/* The following token is returned only by XmlAttributeValueTok */
@@ -84,20 +118,20 @@ extern "C" {
#define XML_TOK_PREFIXED_NAME 41
#ifdef XML_DTD
#define XML_TOK_IGNORE_SECT 42
# define XML_TOK_IGNORE_SECT 42
#endif /* XML_DTD */
#ifdef XML_DTD
#define XML_N_STATES 4
# define XML_N_STATES 4
#else /* not XML_DTD */
#define XML_N_STATES 3
# define XML_N_STATES 3
#endif /* not XML_DTD */
#define XML_PROLOG_STATE 0
#define XML_CONTENT_STATE 1
#define XML_CDATA_SECTION_STATE 2
#ifdef XML_DTD
#define XML_IGNORE_SECTION_STATE 3
# define XML_IGNORE_SECTION_STATE 3
#endif /* XML_DTD */
#define XML_N_LITERAL_TYPES 2
@@ -125,49 +159,41 @@ typedef struct {
struct encoding;
typedef struct encoding ENCODING;
typedef int (PTRCALL *SCANNER)(const ENCODING *,
const char *,
const char *,
const char **);
typedef int(PTRCALL *SCANNER)(const ENCODING *, const char *, const char *,
const char **);
enum XML_Convert_Result {
XML_CONVERT_COMPLETED = 0,
XML_CONVERT_INPUT_INCOMPLETE = 1,
XML_CONVERT_OUTPUT_EXHAUSTED
= 2 /* and therefore potentially input remaining as well */
};
struct encoding {
SCANNER scanners[XML_N_STATES];
SCANNER literalScanners[XML_N_LITERAL_TYPES];
int (PTRCALL *sameName)(const ENCODING *,
const char *,
const char *);
int (PTRCALL *nameMatchesAscii)(const ENCODING *,
const char *,
const char *,
const char *);
int (PTRFASTCALL *nameLength)(const ENCODING *, const char *);
int(PTRCALL *nameMatchesAscii)(const ENCODING *, const char *, const char *,
const char *);
int(PTRFASTCALL *nameLength)(const ENCODING *, const char *);
const char *(PTRFASTCALL *skipS)(const ENCODING *, const char *);
int (PTRCALL *getAtts)(const ENCODING *enc,
const char *ptr,
int attsMax,
ATTRIBUTE *atts);
int (PTRFASTCALL *charRefNumber)(const ENCODING *enc, const char *ptr);
int (PTRCALL *predefinedEntityName)(const ENCODING *,
const char *,
const char *);
void (PTRCALL *updatePosition)(const ENCODING *,
const char *ptr,
const char *end,
POSITION *);
int (PTRCALL *isPublicId)(const ENCODING *enc,
const char *ptr,
const char *end,
const char **badPtr);
void (PTRCALL *utf8Convert)(const ENCODING *enc,
const char **fromP,
const char *fromLim,
char **toP,
const char *toLim);
void (PTRCALL *utf16Convert)(const ENCODING *enc,
const char **fromP,
const char *fromLim,
unsigned short **toP,
const unsigned short *toLim);
int(PTRCALL *getAtts)(const ENCODING *enc, const char *ptr, int attsMax,
ATTRIBUTE *atts);
int(PTRFASTCALL *charRefNumber)(const ENCODING *enc, const char *ptr);
int(PTRCALL *predefinedEntityName)(const ENCODING *, const char *,
const char *);
void(PTRCALL *updatePosition)(const ENCODING *, const char *ptr,
const char *end, POSITION *);
int(PTRCALL *isPublicId)(const ENCODING *enc, const char *ptr,
const char *end, const char **badPtr);
enum XML_Convert_Result(PTRCALL *utf8Convert)(const ENCODING *enc,
const char **fromP,
const char *fromLim, char **toP,
const char *toLim);
enum XML_Convert_Result(PTRCALL *utf16Convert)(const ENCODING *enc,
const char **fromP,
const char *fromLim,
unsigned short **toP,
const unsigned short *toLim);
int minBytesPerChar;
char isUtf8;
char isUtf16;
@@ -194,68 +220,62 @@ struct encoding {
the prolog outside literals, comments and processing instructions.
*/
#define XmlTok(enc, state, ptr, end, nextTokPtr) \
#define XmlTok(enc, state, ptr, end, nextTokPtr) \
(((enc)->scanners[state])(enc, ptr, end, nextTokPtr))
#define XmlPrologTok(enc, ptr, end, nextTokPtr) \
XmlTok(enc, XML_PROLOG_STATE, ptr, end, nextTokPtr)
#define XmlPrologTok(enc, ptr, end, nextTokPtr) \
XmlTok(enc, XML_PROLOG_STATE, ptr, end, nextTokPtr)
#define XmlContentTok(enc, ptr, end, nextTokPtr) \
XmlTok(enc, XML_CONTENT_STATE, ptr, end, nextTokPtr)
#define XmlContentTok(enc, ptr, end, nextTokPtr) \
XmlTok(enc, XML_CONTENT_STATE, ptr, end, nextTokPtr)
#define XmlCdataSectionTok(enc, ptr, end, nextTokPtr) \
XmlTok(enc, XML_CDATA_SECTION_STATE, ptr, end, nextTokPtr)
#define XmlCdataSectionTok(enc, ptr, end, nextTokPtr) \
XmlTok(enc, XML_CDATA_SECTION_STATE, ptr, end, nextTokPtr)
#ifdef XML_DTD
#define XmlIgnoreSectionTok(enc, ptr, end, nextTokPtr) \
XmlTok(enc, XML_IGNORE_SECTION_STATE, ptr, end, nextTokPtr)
# define XmlIgnoreSectionTok(enc, ptr, end, nextTokPtr) \
XmlTok(enc, XML_IGNORE_SECTION_STATE, ptr, end, nextTokPtr)
#endif /* XML_DTD */
/* This is used for performing a 2nd-level tokenization on the content
of a literal that has already been returned by XmlTok.
*/
#define XmlLiteralTok(enc, literalType, ptr, end, nextTokPtr) \
#define XmlLiteralTok(enc, literalType, ptr, end, nextTokPtr) \
(((enc)->literalScanners[literalType])(enc, ptr, end, nextTokPtr))
#define XmlAttributeValueTok(enc, ptr, end, nextTokPtr) \
XmlLiteralTok(enc, XML_ATTRIBUTE_VALUE_LITERAL, ptr, end, nextTokPtr)
#define XmlAttributeValueTok(enc, ptr, end, nextTokPtr) \
XmlLiteralTok(enc, XML_ATTRIBUTE_VALUE_LITERAL, ptr, end, nextTokPtr)
#define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \
XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr)
#define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \
XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr)
#define XmlSameName(enc, ptr1, ptr2) (((enc)->sameName)(enc, ptr1, ptr2))
#define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \
#define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \
(((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2))
#define XmlNameLength(enc, ptr) \
(((enc)->nameLength)(enc, ptr))
#define XmlNameLength(enc, ptr) (((enc)->nameLength)(enc, ptr))
#define XmlSkipS(enc, ptr) \
(((enc)->skipS)(enc, ptr))
#define XmlSkipS(enc, ptr) (((enc)->skipS)(enc, ptr))
#define XmlGetAttributes(enc, ptr, attsMax, atts) \
#define XmlGetAttributes(enc, ptr, attsMax, atts) \
(((enc)->getAtts)(enc, ptr, attsMax, atts))
#define XmlCharRefNumber(enc, ptr) \
(((enc)->charRefNumber)(enc, ptr))
#define XmlCharRefNumber(enc, ptr) (((enc)->charRefNumber)(enc, ptr))
#define XmlPredefinedEntityName(enc, ptr, end) \
#define XmlPredefinedEntityName(enc, ptr, end) \
(((enc)->predefinedEntityName)(enc, ptr, end))
#define XmlUpdatePosition(enc, ptr, end, pos) \
#define XmlUpdatePosition(enc, ptr, end, pos) \
(((enc)->updatePosition)(enc, ptr, end, pos))
#define XmlIsPublicId(enc, ptr, end, badPtr) \
#define XmlIsPublicId(enc, ptr, end, badPtr) \
(((enc)->isPublicId)(enc, ptr, end, badPtr))
#define XmlUtf8Convert(enc, fromP, fromLim, toP, toLim) \
#define XmlUtf8Convert(enc, fromP, fromLim, toP, toLim) \
(((enc)->utf8Convert)(enc, fromP, fromLim, toP, toLim))
#define XmlUtf16Convert(enc, fromP, fromLim, toP, toLim) \
#define XmlUtf16Convert(enc, fromP, fromLim, toP, toLim) \
(((enc)->utf16Convert)(enc, fromP, fromLim, toP, toLim))
typedef struct {
@@ -263,16 +283,11 @@ typedef struct {
const ENCODING **encPtr;
} INIT_ENCODING;
int XmlParseXmlDecl(int isGeneralTextEntity,
const ENCODING *enc,
const char *ptr,
const char *end,
const char **badPtr,
const char **versionPtr,
const char **versionEndPtr,
int XmlParseXmlDecl(int isGeneralTextEntity, const ENCODING *enc,
const char *ptr, const char *end, const char **badPtr,
const char **versionPtr, const char **versionEndPtr,
const char **encodingNamePtr,
const ENCODING **namedEncodingPtr,
int *standalonePtr);
const ENCODING **namedEncodingPtr, int *standalonePtr);
int XmlInitEncoding(INIT_ENCODING *, const ENCODING **, const char *name);
const ENCODING *XmlGetUtf8InternalEncoding(void);
@@ -281,34 +296,22 @@ int FASTCALL XmlUtf8Encode(int charNumber, char *buf);
int FASTCALL XmlUtf16Encode(int charNumber, unsigned short *buf);
int XmlSizeOfUnknownEncoding(void);
typedef int(XMLCALL *CONVERTER)(void *userData, const char *p);
typedef int (XMLCALL *CONVERTER) (void *userData, const char *p);
ENCODING *XmlInitUnknownEncoding(void *mem, int *table, CONVERTER convert,
void *userData);
ENCODING *
XmlInitUnknownEncoding(void *mem,
int *table,
CONVERTER convert,
void *userData);
int XmlParseXmlDeclNS(int isGeneralTextEntity,
const ENCODING *enc,
const char *ptr,
const char *end,
const char **badPtr,
const char **versionPtr,
const char **versionEndPtr,
int XmlParseXmlDeclNS(int isGeneralTextEntity, const ENCODING *enc,
const char *ptr, const char *end, const char **badPtr,
const char **versionPtr, const char **versionEndPtr,
const char **encodingNamePtr,
const ENCODING **namedEncodingPtr,
int *standalonePtr);
const ENCODING **namedEncodingPtr, int *standalonePtr);
int XmlInitEncodingNS(INIT_ENCODING *, const ENCODING **, const char *name);
const ENCODING *XmlGetUtf8InternalEncodingNS(void);
const ENCODING *XmlGetUtf16InternalEncodingNS(void);
ENCODING *
XmlInitUnknownEncodingNS(void *mem,
int *table,
CONVERTER convert,
void *userData);
ENCODING *XmlInitUnknownEncodingNS(void *mem, int *table, CONVERTER convert,
void *userData);
#ifdef __cplusplus
}
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,71 +1,74 @@
/*
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2017-2019 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
The Original Code is expat.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The Initial Developer of the Original Code is James Clark.
Portions created by James Clark are Copyright (C) 1998, 1999
James Clark. All Rights Reserved.
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
Contributor(s):
Alternatively, the contents of this file may be used under the terms
of the GNU General Public License (the "GPL"), in which case the
provisions of the GPL are applicable instead of those above. If you
wish to allow use of your version of this file only under the terms of
the GPL and not to allow others to use your version of this file under
the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the
GPL. If you do not delete the provisions above, a recipient may use
your version of this file under either the MPL or the GPL.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
enum {
BT_NONXML,
BT_MALFORM,
BT_LT,
BT_AMP,
BT_RSQB,
BT_LEAD2,
BT_LEAD3,
BT_LEAD4,
BT_TRAIL,
BT_CR,
BT_LF,
BT_GT,
BT_QUOT,
BT_APOS,
BT_EQUALS,
BT_QUEST,
BT_EXCL,
BT_SOL,
BT_SEMI,
BT_NUM,
BT_LSQB,
BT_S,
BT_NMSTRT,
BT_COLON,
BT_HEX,
BT_DIGIT,
BT_NAME,
BT_MINUS,
BT_OTHER, /* known not to be a name or name start character */
BT_NONXML, /* e.g. noncharacter-FFFF */
BT_MALFORM, /* illegal, with regard to encoding */
BT_LT, /* less than = "<" */
BT_AMP, /* ampersand = "&" */
BT_RSQB, /* right square bracket = "[" */
BT_LEAD2, /* lead byte of a 2-byte UTF-8 character */
BT_LEAD3, /* lead byte of a 3-byte UTF-8 character */
BT_LEAD4, /* lead byte of a 4-byte UTF-8 character */
BT_TRAIL, /* trailing unit, e.g. second 16-bit unit of a 4-byte char. */
BT_CR, /* carriage return = "\r" */
BT_LF, /* line feed = "\n" */
BT_GT, /* greater than = ">" */
BT_QUOT, /* quotation character = "\"" */
BT_APOS, /* aposthrophe = "'" */
BT_EQUALS, /* equal sign = "=" */
BT_QUEST, /* question mark = "?" */
BT_EXCL, /* exclamation mark = "!" */
BT_SOL, /* solidus, slash = "/" */
BT_SEMI, /* semicolon = ";" */
BT_NUM, /* number sign = "#" */
BT_LSQB, /* left square bracket = "[" */
BT_S, /* white space, e.g. "\t", " "[, "\r"] */
BT_NMSTRT, /* non-hex name start letter = "G".."Z" + "g".."z" + "_" */
BT_COLON, /* colon = ":" */
BT_HEX, /* hex letter = "A".."F" + "a".."f" */
BT_DIGIT, /* digit = "0".."9" */
BT_NAME, /* dot and middle dot = "." + chr(0xb7) */
BT_MINUS, /* minus = "-" */
BT_OTHER, /* known not to be a name or name start character */
BT_NONASCII, /* might be a name or name start character */
BT_PERCNT,
BT_LPAR,
BT_RPAR,
BT_AST,
BT_PLUS,
BT_COMMA,
BT_VERBAR
BT_PERCNT, /* percent sign = "%" */
BT_LPAR, /* left parenthesis = "(" */
BT_RPAR, /* right parenthesis = "(" */
BT_AST, /* asterisk = "*" */
BT_PLUS, /* plus sign = "+" */
BT_COMMA, /* comma = "," */
BT_VERBAR /* vertical bar = "|" */
};
#include <stddef.h>

View File

@@ -1,61 +1,83 @@
/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
See the file COPYING for copying permission.
/* This file is included!
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000 Clark Cooper <coopercc@users.sourceforge.net>
Copyright (c) 2002 Greg Stein <gstein@users.sourceforge.net>
Copyright (c) 2002 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
Copyright (c) 2002-2006 Karl Waclawek <karl@waclawek.net>
Copyright (c) 2017-2021 Sebastian Pipping <sebastian@pipping.org>
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* This file is included! */
#ifdef XML_TOK_NS_C
const ENCODING *
NS(XmlGetUtf8InternalEncoding)(void)
{
NS(XmlGetUtf8InternalEncoding)(void) {
return &ns(internal_utf8_encoding).enc;
}
const ENCODING *
NS(XmlGetUtf16InternalEncoding)(void)
{
#if BYTEORDER == 1234
NS(XmlGetUtf16InternalEncoding)(void) {
# if BYTEORDER == 1234
return &ns(internal_little2_encoding).enc;
#elif BYTEORDER == 4321
# elif BYTEORDER == 4321
return &ns(internal_big2_encoding).enc;
#else
# else
const short n = 1;
return (*(const char *)&n
? &ns(internal_little2_encoding).enc
: &ns(internal_big2_encoding).enc);
#endif
return (*(const char *)&n ? &ns(internal_little2_encoding).enc
: &ns(internal_big2_encoding).enc);
# endif
}
static const ENCODING * const NS(encodings)[] = {
&ns(latin1_encoding).enc,
&ns(ascii_encoding).enc,
&ns(utf8_encoding).enc,
&ns(big2_encoding).enc,
&ns(big2_encoding).enc,
&ns(little2_encoding).enc,
&ns(utf8_encoding).enc /* NO_ENC */
static const ENCODING *const NS(encodings)[] = {
&ns(latin1_encoding).enc, &ns(ascii_encoding).enc,
&ns(utf8_encoding).enc, &ns(big2_encoding).enc,
&ns(big2_encoding).enc, &ns(little2_encoding).enc,
&ns(utf8_encoding).enc /* NO_ENC */
};
static int PTRCALL
NS(initScanProlog)(const ENCODING *enc, const char *ptr, const char *end,
const char **nextTokPtr)
{
return initScan(NS(encodings), (const INIT_ENCODING *)enc,
XML_PROLOG_STATE, ptr, end, nextTokPtr);
const char **nextTokPtr) {
return initScan(NS(encodings), (const INIT_ENCODING *)enc, XML_PROLOG_STATE,
ptr, end, nextTokPtr);
}
static int PTRCALL
NS(initScanContent)(const ENCODING *enc, const char *ptr, const char *end,
const char **nextTokPtr)
{
return initScan(NS(encodings), (const INIT_ENCODING *)enc,
XML_CONTENT_STATE, ptr, end, nextTokPtr);
const char **nextTokPtr) {
return initScan(NS(encodings), (const INIT_ENCODING *)enc, XML_CONTENT_STATE,
ptr, end, nextTokPtr);
}
int
NS(XmlInitEncoding)(INIT_ENCODING *p, const ENCODING **encPtr,
const char *name)
{
const char *name) {
int i = getEncodingIndex(name);
if (i == UNKNOWN_ENC)
return 0;
@@ -69,10 +91,9 @@ NS(XmlInitEncoding)(INIT_ENCODING *p, const ENCODING **encPtr,
}
static const ENCODING *
NS(findEncoding)(const ENCODING *enc, const char *ptr, const char *end)
{
#define ENCODING_MAX 128
char buf[ENCODING_MAX];
NS(findEncoding)(const ENCODING *enc, const char *ptr, const char *end) {
# define ENCODING_MAX 128
char buf[ENCODING_MAX] = "";
char *p = buf;
int i;
XmlUtf8Convert(enc, &ptr, end, &p, p + ENCODING_MAX - 1);
@@ -88,28 +109,14 @@ NS(findEncoding)(const ENCODING *enc, const char *ptr, const char *end)
}
int
NS(XmlParseXmlDecl)(int isGeneralTextEntity,
const ENCODING *enc,
const char *ptr,
const char *end,
const char **badPtr,
const char **versionPtr,
const char **versionEndPtr,
const char **encodingName,
const ENCODING **encoding,
int *standalone)
{
return doParseXmlDecl(NS(findEncoding),
isGeneralTextEntity,
enc,
ptr,
end,
badPtr,
versionPtr,
versionEndPtr,
encodingName,
encoding,
standalone);
NS(XmlParseXmlDecl)(int isGeneralTextEntity, const ENCODING *enc,
const char *ptr, const char *end, const char **badPtr,
const char **versionPtr, const char **versionEndPtr,
const char **encodingName, const ENCODING **encoding,
int *standalone) {
return doParseXmlDecl(NS(findEncoding), isGeneralTextEntity, enc, ptr, end,
badPtr, versionPtr, versionEndPtr, encodingName,
encoding, standalone);
}
#endif /* XML_TOK_NS_C */

14
3rdparty/tiny_gltf/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,14 @@
add_library(FGTinyGLTF INTERFACE)
target_include_directories(FGTinyGLTF
INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
$<INSTALL_INTERFACE:include>)
# in the non-shared case, we need to export these as well
if (NOT SIMGEAR_SHARED)
install(TARGETS FGTinyGLTF
EXPORT SimGearTargets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()

20406
3rdparty/tiny_gltf/json.hpp vendored Normal file

File diff suppressed because it is too large Load Diff

7760
3rdparty/tiny_gltf/tiny_gltf.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,6 @@ CHECK_SYMBOL_EXISTS(AF_INET6 "netinet/in.h" HAVE_IPv6)
check_include_file(windows.h WINDOWS)
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_BINARY_DIR}/config.h)
include_directories(${CMAKE_BINARY_DIR})
set(HEADERS
)
@@ -38,4 +37,21 @@ set(SOURCES
udns_XtoX.c
)
simgear_component(udns 3rdparty/udns "${SOURCES}" "${HEADERS}")
add_library(FGUdns STATIC ${SOURCES})
target_include_directories(FGUdns BEFORE PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
$<INSTALL_INTERFACE:include>)
target_include_directories(FGUdns PRIVATE ${CMAKE_BINARY_DIR})
# match the name of imported UDns
add_librarY(Udns::Udns ALIAS FGUdns)
# in the non-shared case, we need to export these as well
if (NOT SIMGEAR_SHARED)
install(TARGETS FGUdns
EXPORT SimGearTargets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()

View File

@@ -55,7 +55,7 @@ modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
@@ -111,7 +111,7 @@ modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
@@ -158,7 +158,7 @@ Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
@@ -216,7 +216,7 @@ instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
@@ -267,7 +267,7 @@ Library will still fall under Section 6.)
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
@@ -329,7 +329,7 @@ restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
@@ -370,7 +370,7 @@ subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
@@ -422,7 +422,7 @@ conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
@@ -456,7 +456,7 @@ SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest

View File

@@ -339,10 +339,12 @@ int main(int argc, char **argv) {
char *home = getenv("HOME");
if (!home) home = ".";
path = malloc(strlen(home) + 1 + sizeof(".rblcheckrc"));
sprintf(path, "%s/.rblcheckrc", home);
if (!addzonefile(path))
addzonefile("/etc/rblcheckrc");
free(path);
if (path) {
sprintf(path, "%s/.rblcheckrc", home);
if (!addzonefile(path))
addzonefile("/etc/rblcheckrc");
free(path);
}
}
}
if (!nzones)

View File

@@ -1,26 +1,12 @@
cmake_minimum_required (VERSION 3.0)
cmake_minimum_required (VERSION 3.10)
if(COMMAND cmake_policy)
if(POLICY CMP0054)
cmake_policy(SET CMP0054 NEW)
endif()
if(POLICY CMP0042)
cmake_policy(SET CMP0042 NEW)
endif()
if(POLICY CMP0067)
cmake_policy(SET CMP0067 NEW)
endif()
# OpenGL VND policy : use the old definition for now, until we can audit this
if(POLICY CMP0072)
cmake_policy(SET CMP0072 OLD)
endif()
if(POLICY CMP0093)
cmake_policy(SET CMP0093 NEW)
endif()
if(POLICY CMP0072)
cmake_policy(SET CMP0072 NEW)
endif()
if(POLICY CMP0093)
cmake_policy(SET CMP0093 NEW)
endif()
message(STATUS "CMAKE Build type: ${CMAKE_BUILD_TYPE}")
# Set a default build type if none was specified
@@ -41,15 +27,13 @@ include (GenerateExportHeader)
# only relevant for building shared libs but let's set it regardless
set(CMAKE_OSX_RPATH 1)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.9" CACHE STRING "Minimum OS X deployment version")
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.12" CACHE STRING "Minimum OS X deployment version")
# let's use & require C++11 - note these are only functional with CMake 3.1
# we do manual fallbacks for CMake 3.0 in the compilers section
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED YES)
# read 'version' file into a variable (stripping any newlines or spaces)
file(READ version versionFile)
file(READ simgear-version versionFile)
string(STRIP ${versionFile} SIMGEAR_VERSION)
project(SimGear VERSION ${SIMGEAR_VERSION} LANGUAGES C CXX)
@@ -70,33 +54,12 @@ if(InSourceBuild)
message(WARNING " mkdir ../sgbuild && cd ../sgbuild && cmake ${CMAKE_SOURCE_DIR}")
endif(InSourceBuild)
#packaging
SET(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/COPYING")
SET(CPACK_RESOURCE_FILE_README "${PROJECT_SOURCE_DIR}/README")
SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Simulation support libraries for FlightGear and related projects")
SET(CPACK_PACKAGE_VENDOR "The FlightGear project")
SET(CPACK_GENERATOR "TBZ2")
SET(CPACK_INSTALL_CMAKE_PROJECTS ${CMAKE_CURRENT_BINARY_DIR};SimGear;ALL;/)
# split version string into components, note CMAKE_MATCH_0 is the entire regexp match
string(REGEX MATCH "([0-9]+)\\.([0-9]+)\\.([0-9]+)" CPACK_PACKAGE_VERSION ${SIMGEAR_VERSION} )
set(CPACK_PACKAGE_VERSION_MAJOR ${CMAKE_MATCH_1})
set(CPACK_PACKAGE_VERSION_MINOR ${CMAKE_MATCH_2})
set(CPACK_PACKAGE_VERSION_PATCH ${CMAKE_MATCH_3})
message(STATUS "version is ${CPACK_PACKAGE_VERSION_MAJOR} dot ${CPACK_PACKAGE_VERSION_MINOR} dot ${CPACK_PACKAGE_VERSION_PATCH}")
set(CPACK_SOURCE_GENERATOR TBZ2)
set(CPACK_SOURCE_PACKAGE_FILE_NAME "simgear-${SIMGEAR_VERSION}" CACHE INTERNAL "tarball basename")
set(CPACK_SOURCE_IGNORE_FILES
"^${PROJECT_SOURCE_DIR}/.git;\\\\.gitignore;Makefile.am;~$;${CPACK_SOURCE_IGNORE_FILES}")
include (CPack)
# We have some custom .cmake scripts not in the official distribution.
set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/CMakeModules;${CMAKE_MODULE_PATH}")
include(Packaging)
# Change the default build type to something fast
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING
@@ -127,21 +90,32 @@ set(SYSTEM_UDNS OFF)
endif()
option(SIMGEAR_HEADLESS "Set to ON to build SimGear without GUI/graphics support" OFF)
option(ENABLE_CYCLONE "Set to ON to build SimGear with Cyclone Data Distribution Service support" ON)
option(ENABLE_RTI "Set to ON to build SimGear with RTI support" OFF)
option(ENABLE_GDAL "Set to ON to build SimGear with GDAL support" OFF)
option(ENABLE_TESTS "Set to OFF to disable building SimGear's test applications" ON)
option(ENABLE_SOUND "Set to OFF to disable building SimGear's sound support" ON)
option(USE_SHADERVG "Set to ON to use SHaderVG instead of ShivaVG" OFF)
option(USE_AEONWAVE "Set to ON to use AeonWave instead of OpenAL" ON)
option(USE_OPENALSOFT "Set to ON to use OpenAL from OpenAL-soft" OFF)
option(ENABLE_PKGUTIL "Set to ON to build the sg_pkgutil application (default)" ON)
option(ENABLE_DNS "Set to ON to use udns library and DNS service resolver" ON)
option(ENABLE_SIMD "Enable SSE/SSE2 support for compilers" ON)
option(ENABLE_SIMD_CODE "Enable SSE/SSE2 support code for compilers" OFF)
option(ENABLE_OPENMP "Enable OpenMP compiler support" OFF)
option(ENABLE_ASAN "Set to ON to build SimGear with LLVM AddressSanitizer (ASan) support" OFF)
option(ENABLE_VIDEO_RECORD "Set to ON to build SimGear with video recording" ON)
if (NOT ENABLE_SIMD AND ENABLE_SIMD_CODE)
set(ENABLE_SIMD_CODE OFF)
endif()
if (USE_SHADERVG)
set(OPENVG ShaderVG)
else()
set(OPENVG ShivaVG)
endif()
message(STATUS "OpenVG: ${OPENVG}")
include (DetectArch)
include (ExportDebugSymbols)
@@ -149,93 +123,28 @@ include (ExportDebugSymbols)
# keep the compatability link option as the default
option(OSG_FSTREAM_EXPORT_FIXED "Set to ON if the osgDB fstream export patch is applied" OFF)
if (CMAKE_COMPILER_IS_GNUCXX OR CLANG)
if (CMAKE_VERSION VERSION_LESS 3.1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++${CMAKE_CXX_STANDARD}")
elseif (CMAKE_VERSION VERSION_LESS 3.8)
# policy CMP0067 (try_compile does not honor CMAKE_CXX_STANDARD)
set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -std=c++${CMAKE_CXX_STANDARD}")
endif()
endif()
if (MSVC)
GET_FILENAME_COMPONENT(PARENT_DIR ${PROJECT_BINARY_DIR} DIRECTORY)
if (CMAKE_CL_64)
SET(TEST_3RDPARTY_DIR "${PARENT_DIR}/3rdparty.x64")
else (CMAKE_CL_64)
SET(TEST_3RDPARTY_DIR "${PARENT_DIR}/3rdparty")
endif (CMAKE_CL_64)
if (EXISTS ${TEST_3RDPARTY_DIR})
set(MSVC_3RDPARTY_ROOT ${PARENT_DIR} CACHE PATH "Location where the third-party dependencies are extracted")
else (EXISTS ${TEST_3RDPARTY_DIR})
set(MSVC_3RDPARTY_ROOT NOT_FOUND CACHE PATH "Location where the third-party dependencies are extracted")
endif (EXISTS ${TEST_3RDPARTY_DIR})
# override CMake default RelWithDebInfo flags. This is important to ensure
# good performance
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "/Zi /O2 /Ob2 /D NDEBUG")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "/Zi /O2 /Ob2 /D NDEBUG")
else (MSVC)
set(MSVC_3RDPARTY_ROOT NOT_FOUND CACHE PATH "Location where the third-party dependencies are extracted")
endif (MSVC)
endif ()
if (MSVC AND MSVC_3RDPARTY_ROOT)
message(STATUS "3rdparty files located in ${MSVC_3RDPARTY_ROOT}")
string(SUBSTRING ${MSVC_VERSION} 0 2 MSVC_VERSION_MAJOR)
string(SUBSTRING ${MSVC_VERSION} 2 2 MSVC_VERSION_MINOR)
set( OSG_MSVC "msvc" )
if (${MSVC_VERSION_MAJOR} EQUAL "19")
if (${MSVC_VERSION_MINOR} GREATER_EQUAL "20")
set( OSG_MSVC ${OSG_MSVC}142 )
elseif (${MSVC_VERSION_MINOR} GREATER_EQUAL "10")
set( OSG_MSVC ${OSG_MSVC}141 )
else ()
set( OSG_MSVC ${OSG_MSVC}140 )
endif ()
elseif (${MSVC_VERSION_MAJOR} EQUAL "18")
set( OSG_MSVC ${OSG_MSVC}120 )
else ()
message(FATAL_ERROR "Visual Studio 2013 or higher is required")
endif ()
if (CMAKE_CL_64)
set( OSG_MSVC ${OSG_MSVC}-64 )
set( MSVC_3RDPARTY_DIR 3rdParty.x64 )
else (CMAKE_CL_64)
set( MSVC_3RDPARTY_DIR 3rdParty )
endif (CMAKE_CL_64)
set (CMAKE_LIBRARY_PATH ${MSVC_3RDPARTY_ROOT}/${MSVC_3RDPARTY_DIR}/lib ${MSVC_3RDPARTY_ROOT}/install/${OSG_MSVC}/OpenScenegraph/lib ${MSVC_3RDPARTY_ROOT}/install/${OSG_MSVC}/OpenRTI/lib )
set (CMAKE_INCLUDE_PATH ${MSVC_3RDPARTY_ROOT}/${MSVC_3RDPARTY_DIR}/include ${MSVC_3RDPARTY_ROOT}/install/${OSG_MSVC}/OpenScenegraph/include ${MSVC_3RDPARTY_ROOT}/install/${OSG_MSVC}/OpenRTI/include)
if(NOT BOOST_INCLUDEDIR)
# if this variable was not set by the user, set it to 3rdparty root's
# parent dir, which is the normal location for people using our
# windows-3rd-party repo
get_filename_component(MSVC_ROOT_PARENT_DIR ${MSVC_3RDPARTY_ROOT} DIRECTORY)
set(BOOST_INCLUDEDIR ${MSVC_ROOT_PARENT_DIR})
message(STATUS "BOOST_INCLUDEDIR is ${BOOST_INCLUDEDIR}")
endif()
set (OPENAL_INCLUDE_DIR ${MSVC_3RDPARTY_ROOT}/${MSVC_3RDPARTY_DIR}/include)
set (OPENAL_LIBRARY_DIR ${MSVC_3RDPARTY_ROOT}/${MSVC_3RDPARTY_DIR}/lib)
endif (MSVC AND MSVC_3RDPARTY_ROOT)
# Setup MSVC 3rd party directories
include( ConfigureMsvc3rdParty )
if(APPLE)
find_library(COCOA_LIBRARY Cocoa)
endif()
if(${CMAKE_SYSTEM_NAME} MATCHES "Linux" OR ${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
find_package(Threads REQUIRED)
endif()
find_package(Threads REQUIRED)
find_package(Boost REQUIRED)
set (BOOST_CXX_FLAGS "-DBOOST_BIMAP_DISABLE_SERIALIZATION -DBOOST_NO_STDLIB_CONFIG")
set (BOOST_CXX_FLAGS "-DBOOST_BIMAP_DISABLE_SERIALIZATION -DBOOST_NO_STDLIB_CONFIG -DBOOST_NO_AUTO_PTR -DBOOST_NO_CXX98_BINDERS")
include(BoostTestTargets)
set(SG_SOUND_USES_OPENALSOFT OFF) # default to off
if(SIMGEAR_HEADLESS)
message(STATUS "SimGear mode: HEADLESS")
set(ENABLE_SOUND 0)
@@ -250,17 +159,30 @@ else()
if(NOT AAX_FOUND)
set(USE_AEONWAVE FALSE)
find_package(OpenAL REQUIRED)
if (USE_OPENALSOFT)
message(STATUS "Sound requested to use OpenAL-soft: ensure Config.cmake files are in CMAKE_PREFIX_PATH")
find_package(OpenAL REQUIRED CONFIG)
if (TARGET OpenAL::OpenAL)
set(SG_SOUND_USES_OPENALSOFT ON)
endif()
else()
# regular OpenAL is found via the CMake distro-suppling FindOpenAL
find_package(OpenAL REQUIRED)
endif()
message(STATUS "OpenAL: ${OPENAL_LIBRARY}")
endif()
if(AAX_FOUND)
message(STATUS "Sound support: AeonWave")
elseif (TARGET OpenAL::OpenAL)
message(STATUS "Sound support: OpenAL-soft")
else()
message(STATUS "Sound support: OpenAL")
message(STATUS "Sound support: OpenAL (from system)")
endif()
endif(ENABLE_SOUND)
find_package(OpenSceneGraph 3.2.0 REQUIRED osgText osgSim osgDB osgParticle osgGA osgViewer osgUtil)
find_package(OpenSceneGraph 3.6.0 REQUIRED osgText osgSim osgDB osgParticle osgGA osgViewer osgUtil osgTerrain)
if (MSVC)
set(CMAKE_REQUIRED_INCLUDES ${OPENSCENEGRAPH_INCLUDE_DIRS})
@@ -278,7 +200,15 @@ else()
endif()
endif(SIMGEAR_HEADLESS)
find_package(ZLIB 1.2.4 REQUIRED)
if(${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD")
# As of 2020-08-01, OpenBSD's system zlib is slightly old, but it's usable
# with a workaround in simgear/io/iostreams/gzfstream.cxx.
find_package(ZLIB 1.2.3 REQUIRED)
else()
find_package(ZLIB 1.2.4 REQUIRED)
endif()
find_package(LibLZMA REQUIRED)
find_package(CURL REQUIRED)
if (SYSTEM_EXPAT)
@@ -288,26 +218,13 @@ if (SYSTEM_EXPAT)
else()
message(STATUS "Using built-in expat code")
set(EXPAT_INCLUDE_DIRS
${PROJECT_SOURCE_DIR}/3rdparty/expat
${PROJECT_BINARY_DIR}/3rdparty/expat)
endif(SYSTEM_EXPAT)
check_include_file(inttypes.h HAVE_INTTYPES_H)
check_include_file(sys/time.h HAVE_SYS_TIME_H)
check_include_file(unistd.h HAVE_UNISTD_H)
check_include_file(windows.h HAVE_WINDOWS_H)
if(HAVE_INTTYPES_H)
# ShivaVG needs inttypes.h
add_definitions(-DHAVE_INTTYPES_H)
endif()
if(ENABLE_RTI)
find_package(PkgConfig)
if(PKG_CONFIG_FOUND)
SET(ENV{PKG_CONFIG_PATH} "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/pkgconfig:$ENV{PKG_CONFIG_PATH}")
pkg_check_modules(RTI hla-rti13)
pkg_check_modules(RTI IMPORTED_TARGET hla-rti13)
endif(PKG_CONFIG_FOUND)
if(RTI_FOUND)
message(STATUS "RTI: ENABLED")
@@ -318,78 +235,38 @@ else()
message(STATUS "RTI: DISABLED")
endif(ENABLE_RTI)
if(ENABLE_CYCLONE)
find_package(CycloneDDS QUIET)
if (CycloneDDS_FOUND)
message(STATUS "Data Distribution Service support: CycloneDDS")
set(SG_HAVE_DDS 1)
else(CycloneDDS_FOUND)
message(STATUS "Data Distribution Service support: DISBLED")
endif(CycloneDDS_FOUND)
endif(ENABLE_CYCLONE)
if(ENABLE_GDAL)
find_package(GDAL 2.0.0 REQUIRED)
if (GDAL_FOUND)
include_directories(${GDAL_INCLUDE_DIR})
endif(GDAL_FOUND)
endif(ENABLE_GDAL)
check_function_exists(gettimeofday HAVE_GETTIMEOFDAY)
check_function_exists(rint HAVE_RINT)
check_function_exists(mkdtemp HAVE_MKDTEMP)
check_function_exists(bcopy HAVE_BCOPY)
check_function_exists(mmap HAVE_MMAP)
if (NOT MSVC)
check_function_exists(timegm HAVE_TIMEGM)
if (NOT HAVE_TIMEGM)
message(FATAL_ERROR "Non-Windows platforms must support timegm()")
if (ENABLE_VIDEO_RECORD)
find_package(FFmpeg COMPONENTS AVCODEC AVFORMAT AVUTIL SWSCALE)
if (FFmpeg_FOUND)
# set this so it's picked up in simgear_config.h
set(SG_FFMPEG 1)
else()
message(STATUS "Video recording was requested, but required FFmpeg/avcodec libaries not found")
endif()
endif()
if(HAVE_UNISTD_H)
set(CMAKE_REQUIRED_INCLUDES ${CMAKE_INCLUDE_PATH})
check_cxx_source_compiles(
"#include <unistd.h>
#if !defined(_POSIX_TIMERS) || (0 >= _POSIX_TIMERS)
#error clock_gettime is not supported
#endif
int main() { return 0; }
"
HAVE_CLOCK_GETTIME)
endif(HAVE_UNISTD_H)
set(RT_LIBRARY "")
if(HAVE_CLOCK_GETTIME)
check_library_exists(rt clock_gettime "" HAVE_RT)
if(HAVE_RT)
set(RT_LIBRARY rt)
endif(HAVE_RT)
endif(HAVE_CLOCK_GETTIME)
set(DL_LIBRARY "")
check_cxx_source_compiles(
"#include <dlfcn.h>
int main(void) {
return 0;
}
"
HAVE_DLFCN_H)
if(HAVE_DLFCN_H)
check_library_exists(dl dlerror "" HAVE_DL)
if(HAVE_DL)
set(DL_LIBRARY "dl")
endif()
endif()
include(CheckPOSIXFeatures)
SET(CMAKE_DEBUG_POSTFIX "d" CACHE STRING "add a postfix, usually 'd' on windows")
SET(CMAKE_RELEASE_POSTFIX "" CACHE STRING "add a postfix, usually empty on windows")
SET(CMAKE_RELWITHDEBINFO_POSTFIX "" CACHE STRING "add a postfix, usually empty on windows")
SET(CMAKE_MINSIZEREL_POSTFIX "" CACHE STRING "add a postfix, usually empty on windows")
# isnan might not be real symbol, so can't check using function_exists
check_cxx_source_compiles(
"#include <cmath>
int main() { return std::isnan(0.0);} "
HAVE_STD_ISNAN)
if (NOT ${HAVE_STD_ISNAN})
message(FATAL_ERROR "Your compiler lacks C++11 std::isnan, please update it")
endif()
# Check if the <regex> implementation in the C++ standard library is usable.
# This is necessary because g++ 4.8 lies about its C++11 compliance: its
# <regex> is utterly unusable, cf. [1].
@@ -419,10 +296,6 @@ if(CMAKE_COMPILER_IS_GNUCXX)
set(WARNING_FLAGS_CXX "-Wall -fPIC")
set(WARNING_FLAGS_C "-Wall -fPIC")
if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.4)
message(WARNING "GCC 4.4 will be required soon, please upgrade")
endif()
if (X86 OR X86_64)
set(SIMD_COMPILER_FLAGS "-msse2 -mfpmath=sse -ftree-vectorize -ftree-slp-vectorize")
endif()
@@ -433,6 +306,9 @@ if(CMAKE_COMPILER_IS_GNUCXX)
check_cxx_source_compiles(
"int main() { unsigned mValue; return __sync_add_and_fetch(&mValue, 1); }"
GCC_ATOMIC_BUILTINS_FOUND)
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O3 -g -DNDEBUG")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "-O3 -g -DNDEBUG")
endif(CMAKE_COMPILER_IS_GNUCXX)
if (CLANG)
@@ -442,7 +318,6 @@ if (CLANG)
set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++")
# fix Boost compilation :(
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
# override CMake default RelWithDebInfo flags.
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O3 -g -DNDEBUG")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "-O3 -g -DNDEBUG")
@@ -450,17 +325,14 @@ if (CLANG)
set(SIMD_COMPILER_FLAGS "-msse2 -mfpmath=sse -ftree-vectorize -ftree-slp-vectorize")
endif()
if (ENABLE_OPENMP)
find_package(OpenMP)
if(OPENMP_FOUND)
message(STATUS "OpenMP: ENABLED")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
else()
message(STATUS "OpenMP: NOT FOUND")
endif()
else()
message(STATUS "OpenMP: DISABLED")
if (ENABLE_ASAN)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=address")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address")
# needed for check_cxx_source_compiles
set(CMAKE_REQUIRED_LINK_OPTIONS "-fsanitize=address")
endif()
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
@@ -469,6 +341,11 @@ if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
if(HAS_NOWARN_UNUSED_TYPEDEFS)
set(WARNING_FLAGS_CXX " ${WARNING_FLAGS_CXX} -Wno-unused-local-typedefs")
endif()
check_cxx_compiler_flag(-Wno-inconsistent-missing-override HAS_NOWARN_MISSING_OVERRIDE)
if(HAS_NOWARN_MISSING_OVERRIDE)
set(WARNING_FLAGS_CXX " ${WARNING_FLAGS_CXX} -Wno-inconsistent-missing-override")
endif()
endif()
if(WIN32)
@@ -478,7 +355,7 @@ if(WIN32)
endif()
if(MSVC)
set(MSVC_FLAGS "-DWIN32 -DNOMINMAX -D_USE_MATH_DEFINES -D_CRT_SECURE_NO_WARNINGS -D__CRT_NONSTDC_NO_WARNINGS /MP")
set(MSVC_FLAGS "-D_HAS_STD_BYTE=0 -DWIN32 -DNOMINMAX -D_USE_MATH_DEFINES -D_CRT_SECURE_NO_WARNINGS -D__CRT_NONSTDC_NO_WARNINGS /MP /bigobj")
if (X86)
set(SIMD_COMPILER_FLAGS "/arch:SSE /arch:SSE2")
endif()
@@ -489,11 +366,6 @@ if(WIN32)
# symbols. Suspect this may be an OSG-DB export bug
set( MSVC_LD_FLAGS "/FORCE:MULTIPLE" )
endif ()
if (${MSVC_VERSION} GREATER 1899)
# needed for debug builds with VS2015
set( MSVC_FLAGS "${MSVC_FLAGS} /bigobj" )
endif()
endif(MSVC)
# assumed on Windows
@@ -524,14 +396,6 @@ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${MSVC_LD_FLAGS}")
include(CheckCXXFeatures)
# use BEFORE to ensure local directories are used first,
# ahead of system-installed libs
include_directories(BEFORE ${PROJECT_BINARY_DIR}/simgear)
if(${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD")
include_directories("/usr/X11R6/include")
endif()
add_definitions(-DHAVE_CONFIG_H)
# configure a header file to pass some of the CMake settings
@@ -541,49 +405,18 @@ configure_file (
"${PROJECT_BINARY_DIR}/simgear/simgear_config.h"
)
if(ENABLE_TESTS)
# enable CTest / make test target
message(STATUS "Tests: ENABLED")
include (Dart)
enable_testing()
else()
message(STATUS "Tests: DISABLED")
endif(ENABLE_TESTS)
# always set TEST_LIBS as it is also used by other tools/applications
set(TEST_LIBS_INTERNAL_CORE
${CMAKE_THREAD_LIBS_INIT}
${ZLIB_LIBRARY}
${WINSOCK_LIBRARY}
${SHLWAPI_LIBRARY}
${RT_LIBRARY}
${DL_LIBRARY}
${COCOA_LIBRARY}
${CURL_LIBRARIES}
${GDAL_LIBRARY})
set(TEST_LIBS SimGearCore ${TEST_LIBS_INTERNAL_CORE})
if(NOT SIMGEAR_HEADLESS)
set(TEST_LIBS SimGearScene ${OPENGL_LIBRARIES} ${TEST_LIBS})
endif()
include (Dart)
enable_testing()
include(AddSimGearTest) # helper to setup a test
install (FILES ${PROJECT_BINARY_DIR}/simgear/simgear_config.h DESTINATION include/simgear/)
if(ENABLE_DNS)
if(SYSTEM_UDNS)
message(STATUS "Requested to use system udns library, forcing SIMGEAR_SHARED to true")
set(SIMGEAR_SHARED ON)
find_package(Udns REQUIRED)
else()
message(STATUS "DNS resolver: ENABLED")
include_directories(3rdparty/udns)
endif()
else()
message(STATUS "DNS resolver: DISABLED")
if(SYSTEM_UDNS)
message(STATUS "Requested to use system udns library, forcing SIMGEAR_SHARED to true")
set(SIMGEAR_SHARED ON)
find_package(Udns REQUIRED)
endif()
add_subdirectory(3rdparty)
add_subdirectory(simgear)

View File

@@ -0,0 +1,30 @@
function(add_simgear_test _name _sources)
add_executable(${_name} ${_sources})
target_link_libraries(${_name} SimGearCore Threads::Threads)
# for simgear_config.h
target_include_directories(${_name} PRIVATE ${PROJECT_BINARY_DIR}/simgear)
endfunction()
function(add_simgear_autotest _name _sources)
add_executable(${_name} ${_sources})
target_link_libraries(${_name} SimGearCore Threads::Threads)
# for simgear_config.h
target_include_directories(${_name} PRIVATE ${PROJECT_BINARY_DIR}/simgear)
add_test(${_name} ${EXECUTABLE_OUTPUT_PATH}/${_name})
endfunction()
function(add_simgear_scene_autotest _name _sources)
add_executable(${_name} ${_sources})
target_link_libraries(${_name} SimGearScene Threads::Threads)
# for simgear_config.h
target_include_directories(${_name} PRIVATE ${PROJECT_BINARY_DIR}/simgear)
add_test(${_name} ${EXECUTABLE_OUTPUT_PATH}/${_name})
endfunction()

View File

@@ -0,0 +1,55 @@
check_function_exists(gettimeofday HAVE_GETTIMEOFDAY)
check_function_exists(rint HAVE_RINT)
check_function_exists(mkdtemp HAVE_MKDTEMP)
check_function_exists(bcopy HAVE_BCOPY)
check_function_exists(mmap HAVE_MMAP)
check_include_file(inttypes.h HAVE_INTTYPES_H)
check_include_file(sys/time.h HAVE_SYS_TIME_H)
check_include_file(unistd.h HAVE_UNISTD_H)
check_include_file(windows.h HAVE_WINDOWS_H)
if (NOT MSVC)
check_function_exists(timegm HAVE_TIMEGM)
if (NOT HAVE_TIMEGM)
message(FATAL_ERROR "Non-Windows platforms must support timegm()")
endif()
endif()
if(HAVE_UNISTD_H)
set(CMAKE_REQUIRED_INCLUDES ${CMAKE_INCLUDE_PATH})
check_cxx_source_compiles(
"#include <unistd.h>
#if !defined(_POSIX_TIMERS) || (0 >= _POSIX_TIMERS)
#error clock_gettime is not supported
#endif
int main() { return 0; }
"
HAVE_CLOCK_GETTIME)
endif(HAVE_UNISTD_H)
set(RT_LIBRARY "")
if(HAVE_CLOCK_GETTIME)
check_library_exists(rt clock_gettime "" HAVE_RT)
if(HAVE_RT)
set(RT_LIBRARY rt)
endif(HAVE_RT)
endif(HAVE_CLOCK_GETTIME)
set(DL_LIBRARY "")
check_cxx_source_compiles(
"#include <dlfcn.h>
int main(void) {
return 0;
}
"
HAVE_DLFCN_H)
if(HAVE_DLFCN_H)
check_library_exists(dl dlerror "" HAVE_DL)
if(HAVE_DL)
set(DL_LIBRARY "dl")
endif()
endif()

View File

@@ -0,0 +1,132 @@
# ConfigureMsvc3rdParty.cmake - Configure 3rd Party Library Paths on Windows
# we want to handle various cases here:
# fgmeta layout, where windows-3rd-party is a sibling of our flightgear source dir
# - this should work with no manual options
# explicitly specifying MSVC_3RDPARTY_ROOT: we'll select a subdir based on MSVC version
# and architecture. We want to allow for people specify various paths here:
# - path to windows-3rd-party
# - path to an MSVC versioned subdir, eg -DMSVC_3RDPARTY_ROOT=C:\FGFS\windows-3rd-party\msvc140
# - path to an architecture specific subdir, eg -DMSVC_3RDPARTY_ROOT=C:\FGFS\windows-3rd-party\msvc140\3rdparty.x64
set(_FOUND_3RDPARTY_DIR "NOTFOUND")
set(_FOUND_BOOST_INCLUDE_DIR "NOTFOUND")
# try various suffixes of a base directory, and
# set the variables above on success
function(_check_candidate_msvc_path pathToCheck)
unset (_freeTypeHeader CACHE )
unset (_zlibDll CACHE )
unset (_boostHeaders CACHE )
find_path(_freeTypeHeader include/ft2build.h
PATHS
${pathToCheck}
PATH_SUFFIXES
${ARCH_SUBDIR_NAME}
${MSVC_SUBDIR_NAME}/${ARCH_SUBDIR_NAME}
${COMPAT_SUBDIR_NAME}/${ARCH_SUBDIR_NAME}
NO_DEFAULT_PATH
)
find_path(_zlibDll bin/zlib.dll
PATHS
${pathToCheck}
PATH_SUFFIXES
${ARCH_SUBDIR_NAME}
${MSVC_SUBDIR_NAME}/${ARCH_SUBDIR_NAME}
${COMPAT_SUBDIR_NAME}/${ARCH_SUBDIR_NAME}
NO_DEFAULT_PATH
)
find_path(_boostHeaders boost/atomic.hpp
PATHS
${pathToCheck}
NO_DEFAULT_PATH
)
if (_freeTypeHeader AND _zlibDll)
set(_FOUND_3RDPARTY_DIR "${_freeTypeHeader}" PARENT_SCOPE)
if (_boostHeaders)
set(_FOUND_BOOST_INCLUDE_DIR "${_boostHeaders}" PARENT_SCOPE)
endif()
endif()
endfunction()
if (MSVC)
# compute values for the compiler and arch subdirs
string(SUBSTRING ${MSVC_VERSION} 0 2 MSVC_VERSION_MAJOR)
string(SUBSTRING ${MSVC_VERSION} 2 2 MSVC_VERSION_MINOR)
if (${MSVC_VERSION_MAJOR} EQUAL "19")
if (${MSVC_VERSION_MINOR} EQUAL "00")
set( MSVC_SUBDIR_NAME msvc140 )
else ()
set( MSVC_SUBDIR_NAME msvc141 )
set( COMPAT_SUBDIR_NAME msvc140 )
endif()
else ()
message(FATAL_ERROR "Visual Studio 2017 is required")
endif ()
if (CMAKE_CL_64)
SET(ARCH_SUBDIR_NAME "3rdParty.x64")
else (CMAKE_CL_64)
SET(ARCH_SUBDIR_NAME "3rdParty")
endif (CMAKE_CL_64)
# try the explicitly specified value first
if (EXISTS ${MSVC_3RDPARTY_ROOT})
_check_candidate_msvc_path("${MSVC_3RDPARTY_ROOT}")
endif()
# then try the fgmeta setup: look for a windows-3rdparty sibling of
# our source dir
get_filename_component(PARENT_SOURCE_DIR ${PROJECT_SOURCE_DIR} DIRECTORY)
get_filename_component(PARENT_BINARY_DIR ${PROJECT_BINARY_DIR} DIRECTORY)
if (NOT _FOUND_3RDPARTY_DIR AND EXISTS "${PARENT_SOURCE_DIR}/windows-3rd-party")
message(STATUS "Trying src 3rdparty")
_check_candidate_msvc_path("${PARENT_SOURCE_DIR}/windows-3rd-party")
endif()
if (NOT _FOUND_3RDPARTY_DIR AND EXISTS "${PARENT_BINARY_DIR}/windows-3rd-party")
message(STATUS "Trying bin 3rdparty")
_check_candidate_msvc_path("${PARENT_BINARY_DIR}/windows-3rd-party")
endif()
# try the Jenkins setup, whre the arch dir is copied into the WORKSPACE
if (NOT _FOUND_3RDPARTY_DIR AND EXISTS "${PARENT_BINARY_DIR}/${ARCH_SUBDIR_NAME}")
message(STATUS "Trying arch subdir ${PARENT_BINARY_DIR}/${ARCH_SUBDIR_NAME}")
_check_candidate_msvc_path("${PARENT_BINARY_DIR}/${ARCH_SUBDIR_NAME}")
endif()
if (NOT _FOUND_3RDPARTY_DIR)
message(WARNING "Failed to find the Windows 3rdparty files at all.")
set(MSVC_3RDPARTY_ROOT NOT_FOUND CACHE PATH "Location where the third-party dependencies are extracted")
endif()
else (MSVC)
set(MSVC_3RDPARTY_ROOT NOT_FOUND CACHE PATH "Location where the third-party dependencies are extracted")
endif (MSVC)
if (MSVC AND _FOUND_3RDPARTY_DIR)
message(STATUS "3rdparty files located in ${_FOUND_3RDPARTY_DIR}")
list(APPEND CMAKE_PREFIX_PATH ${_FOUND_3RDPARTY_DIR})
set(FINAL_MSVC_3RDPARTY_DIR ${_FOUND_3RDPARTY_DIR})
if (CMAKE_CL_64)
set( BOOST_LIB lib64 )
else (CMAKE_CL_64)
set( BOOST_LIB lib )
endif (CMAKE_CL_64)
if(NOT BOOST_INCLUDEDIR AND _FOUND_BOOST_INCLUDE_DIR)
set(BOOST_INCLUDEDIR ${_FOUND_BOOST_INCLUDE_DIR})
message(STATUS "found Boost headers at ${_FOUND_BOOST_INCLUDE_DIR}")
endif()
endif ()

View File

@@ -3,7 +3,7 @@
#
# AAX_FOUND - if false, do not try to link to AAX
# AAX_INCLUDE_DIR - where to find the headers
# AAX_LIBRARIES - Link these to use AAX
# AAX_LIBRARY - Link these to use AAX
#
# Copyright (C) 2016-2018 by Erik Hofman.
# Copyright (C) 2016-2018 by Adalin B.V.
@@ -59,7 +59,7 @@ else()
if (AAX_FOUND)
if (NOT Udns_FIND_QUIETLY)
message(STATUS "Found AeonWave: ${AAX_LIBRARIES}")
message(STATUS "Found AeonWave: ${AAX_LIBRARY}")
endif ()
else ()
if (Udns_FIND_REQUIRED)
@@ -67,8 +67,8 @@ else()
endif ()
endif ()
# show the AAX_INCLUDE_DIRS and AAX_LIBRARIES variables only in the advanced view
mark_as_advanced(AAX_INCLUDE_DIRS AAX_LIBRARIES)
# show the AAX_INCLUDE_DIR and AAX_LIBRARY variables only in the advanced view
mark_as_advanced(AAX_INCLUDE_DIR AAX_LIBRARY)
endif()

203
CMakeModules/FindCURL.cmake Normal file
View File

@@ -0,0 +1,203 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#[=======================================================================[.rst:
FindCURL
--------
Find the native CURL headers and libraries.
This module accept optional COMPONENTS to check supported features and
protocols::
PROTOCOLS: ICT FILE FTP FTPS GOPHER HTTP HTTPS IMAP IMAPS LDAP LDAPS POP3
POP3S RTMP RTSP SCP SFTP SMB SMBS SMTP SMTPS TELNET TFTP
FEATURES: SSL IPv6 UnixSockets libz AsynchDNS IDN GSS-API PSL SPNEGO
Kerberos NTLM NTLM_WB TLS-SRP HTTP2 HTTPS-proxy
IMPORTED Targets
^^^^^^^^^^^^^^^^
This module defines :prop_tgt:`IMPORTED` target ``CURL::libcurl``, if
curl has been found.
Result Variables
^^^^^^^^^^^^^^^^
This module defines the following variables:
``CURL_FOUND``
"True" if ``curl`` found.
``CURL_INCLUDE_DIRS``
where to find ``curl``/``curl.h``, etc.
``CURL_LIBRARIES``
List of libraries when using ``curl``.
``CURL_VERSION_STRING``
The version of ``curl`` found.
CURL CMake
^^^^^^^^^^
If CURL was built using the CMake buildsystem then it provides its own
``CURLConfig.cmake`` file for use with the :command:`find_package` command's
config mode. This module looks for this file and, if found,
returns its results with no further action.
Set ``CURL_NO_CURL_CMAKE`` to ``ON`` to disable this search.
#]=======================================================================]
include(FindPackageHandleStandardArgs)
if(NOT CURL_NO_CURL_CMAKE)
# do a find package call to specifically look for the CMake version
# of curl
find_package(CURL QUIET NO_MODULE)
mark_as_advanced(CURL_DIR)
# if we found the CURL cmake package then we are done, and
# can print what we found and return.
if(CURL_FOUND)
find_package_handle_standard_args(CURL HANDLE_COMPONENTS CONFIG_MODE)
return()
endif()
endif()
find_package(PkgConfig QUIET)
if(PKG_CONFIG_FOUND)
pkg_check_modules(PC_CURL QUIET libcurl)
if(PC_CURL_FOUND)
set(CURL_VERSION_STRING ${PC_CURL_VERSION})
pkg_get_variable(CURL_SUPPORTED_PROTOCOLS libcurl supported_protocols)
pkg_get_variable(CURL_SUPPORTED_FEATURES libcurl supported_features)
endif()
endif()
# Look for the header file.
find_path(CURL_INCLUDE_DIR
NAMES curl/curl.h
HINTS ${PC_CURL_INCLUDE_DIRS})
mark_as_advanced(CURL_INCLUDE_DIR)
if(NOT CURL_LIBRARY)
# Look for the library (sorted from most current/relevant entry to least).
find_library(CURL_LIBRARY_RELEASE NAMES
curl
# Windows MSVC prebuilts:
curllib
libcurl_imp
curllib_static
# Windows older "Win32 - MSVC" prebuilts (libcurl.lib, e.g. libcurl-7.15.5-win32-msvc.zip):
libcurl
HINTS ${PC_CURL_LIBRARY_DIRS}
)
mark_as_advanced(CURL_LIBRARY_RELEASE)
find_library(CURL_LIBRARY_DEBUG NAMES
# Windows MSVC CMake builds in debug configuration on vcpkg:
libcurl-d_imp
libcurl-d
HINTS ${PC_CURL_LIBRARY_DIRS}
)
mark_as_advanced(CURL_LIBRARY_DEBUG)
include(SelectLibraryConfigurations)
select_library_configurations(CURL)
endif()
if(CURL_INCLUDE_DIR AND NOT CURL_VERSION_STRING)
foreach(_curl_version_header curlver.h curl.h)
if(EXISTS "${CURL_INCLUDE_DIR}/curl/${_curl_version_header}")
file(STRINGS "${CURL_INCLUDE_DIR}/curl/${_curl_version_header}" curl_version_str REGEX "^#define[\t ]+LIBCURL_VERSION[\t ]+\".*\"")
string(REGEX REPLACE "^#define[\t ]+LIBCURL_VERSION[\t ]+\"([^\"]*)\".*" "\\1" CURL_VERSION_STRING "${curl_version_str}")
unset(curl_version_str)
break()
endif()
endforeach()
endif()
if(CURL_FIND_COMPONENTS)
set(CURL_KNOWN_PROTOCOLS ICT FILE FTP FTPS GOPHER HTTP HTTPS IMAP IMAPS LDAP LDAPS POP3 POP3S RTMP RTSP SCP SFTP SMB SMBS SMTP SMTPS TELNET TFTP)
set(CURL_KNOWN_FEATURES SSL IPv6 UnixSockets libz AsynchDNS IDN GSS-API PSL SPNEGO Kerberos NTLM NTLM_WB TLS-SRP HTTP2 HTTPS-proxy)
foreach(component IN LISTS CURL_KNOWN_PROTOCOLS CURL_KNOWN_FEATURES)
set(CURL_${component}_FOUND FALSE)
endforeach()
if(NOT PC_CURL_FOUND)
find_program(CURL_CONFIG_EXECUTABLE NAMES curl-config)
if(CURL_CONFIG_EXECUTABLE)
execute_process(COMMAND ${CURL_CONFIG_EXECUTABLE} --version
OUTPUT_VARIABLE CURL_CONFIG_VERSION_STRING
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND ${CURL_CONFIG_EXECUTABLE} --feature
OUTPUT_VARIABLE CURL_CONFIG_FEATURES_STRING
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE "\n" ";" CURL_SUPPORTED_FEATURES "${CURL_CONFIG_FEATURES_STRING}")
execute_process(COMMAND ${CURL_CONFIG_EXECUTABLE} --protocols
OUTPUT_VARIABLE CURL_CONFIG_PROTOCOLS_STRING
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE "\n" ";" CURL_SUPPORTED_PROTOCOLS "${CURL_CONFIG_PROTOCOLS_STRING}")
endif()
endif()
foreach(component IN LISTS CURL_FIND_COMPONENTS)
list(FIND CURL_KNOWN_PROTOCOLS ${component} _found)
if(_found)
list(FIND CURL_SUPPORTED_PROTOCOLS ${component} _found)
if(_found)
set(CURL_${component}_FOUND TRUE)
elseif(CURL_FIND_REQUIRED)
message(FATAL_ERROR "CURL: Required protocol ${component} is not found")
endif()
else()
list(FIND CURL_SUPPORTED_FEATURES ${component} _found)
if(_found)
set(CURL_${component}_FOUND TRUE)
elseif(CURL_FIND_REQUIRED)
message(FATAL_ERROR "CURL: Required feature ${component} is not found")
endif()
endif()
endforeach()
endif()
find_package_handle_standard_args(CURL
REQUIRED_VARS CURL_LIBRARY CURL_INCLUDE_DIR
VERSION_VAR CURL_VERSION_STRING
HANDLE_COMPONENTS)
if(CURL_FOUND)
set(CURL_LIBRARIES ${CURL_LIBRARY})
set(CURL_INCLUDE_DIRS ${CURL_INCLUDE_DIR})
if(NOT TARGET CURL::libcurl)
add_library(CURL::libcurl UNKNOWN IMPORTED)
set_target_properties(CURL::libcurl PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${CURL_INCLUDE_DIRS}")
if(EXISTS "${CURL_LIBRARY}")
set_target_properties(CURL::libcurl PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
IMPORTED_LOCATION "${CURL_LIBRARY}")
endif()
if(CURL_LIBRARY_RELEASE)
set_property(TARGET CURL::libcurl APPEND PROPERTY
IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(CURL::libcurl PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
IMPORTED_LOCATION_RELEASE "${CURL_LIBRARY_RELEASE}")
endif()
if(CURL_LIBRARY_DEBUG)
set_property(TARGET CURL::libcurl APPEND PROPERTY
IMPORTED_CONFIGURATIONS DEBUG)
set_target_properties(CURL::libcurl PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
IMPORTED_LOCATION_DEBUG "${CURL_LIBRARY_DEBUG}")
endif()
endif()
endif()

View File

@@ -0,0 +1,171 @@
# vim: ts=2 sw=2
# - Try to find the required ffmpeg components(default: AVFORMAT, AVUTIL, AVCODEC)
#
# Once done this will define
# FFMPEG_FOUND - System has the all required components.
# FFMPEG_INCLUDE_DIRS - Include directory necessary for using the required components headers.
# FFMPEG_LIBRARIES - Link these to use the required ffmpeg components.
# FFMPEG_DEFINITIONS - Compiler switches required for using the required ffmpeg components.
#
# For each of the components
# - AVCODEC
# - AVDEVICE
# - AVFORMAT
# - AVUTIL
# - POSTPROCESS
# - SWSCALE
# the following variables will be defined:
# <component>_FOUND - System has <component>
# <component>_INCLUDE_DIRS - Include directory necessary for using the <component> headers
# <component>_LIBRARIES - Link these to use <component>
# <component>_DEFINITIONS - Compiler switches required for using <component>
# <component>_VERSION - The components version
#
# As the versions of the various FFmpeg components differ for a given release,
# and CMake supports only one common version for all components, use the
# following to specify required versions for multiple components:
#
# find_package(FFmpeg 57.48 COMPONENTS AVCODEC)
# find_package(FFmpeg 57.40 COMPONENTS AVFORMAT)
# find_package(FFmpeg 55.27 COMPONENTS AVUTIL)
#
# SPDX-FileCopyrightText: 2006 Matthias Kretz <kretz@kde.org>
# SPDX-FileCopyrightText: 2008 Alexander Neundorf <neundorf@kde.org>
# SPDX-FileCopyrightText: 2011 Michael Jansen <kde@michael-jansen.biz>
# SPDX-FileCopyrightText: 2021 Stefan Brüns <stefan.bruens@rwth-aachen.de>
# SPDX-License-Identifier: BSD-3-Clause
include(FindPackageHandleStandardArgs)
if (NOT FFmpeg_FIND_COMPONENTS)
# The default components were taken from a survey over other FindFFMPEG.cmake files
set(FFmpeg_FIND_COMPONENTS AVCODEC AVFORMAT AVUTIL)
endif ()
list(LENGTH FFmpeg_FIND_COMPONENTS _numComponents)
if ((${_numComponents} GREATER 1) AND DEFINED ${FFmpeg_FIND_VERSION})
message(WARNING "Using a required version in combination with multiple COMPONENTS is not supported")
set(_FFmpeg_REQUIRED_VERSION 0)
elseif (DEFINED FFmpeg_FIND_VERSION)
set(_FFmpeg_REQUIRED_VERSION ${FFmpeg_FIND_VERSION})
else ()
set(_FFmpeg_REQUIRED_VERSION 0)
endif ()
set(_FFmpeg_ALL_COMPONENTS AVCODEC AVDEVICE AVFORMAT AVUTIL POSTPROCESS SWSCALE)
#
### Macro: set_component_found
#
# Marks the given component as found if both *_LIBRARIES AND *_INCLUDE_DIRS is present.
#
macro(set_component_found _component )
if (${_component}_LIBRARIES AND ${_component}_INCLUDE_DIRS)
set(${_component}_FOUND TRUE)
set(FFmpeg_${_component}_FOUND TRUE)
endif ()
endmacro()
#
### Macro: find_component
#
# Checks for the given component by invoking pkgconfig and then looking up the libraries and
# include directories.
#
macro(find_component _component _pkgconfig _library _header)
if (NOT WIN32)
# use pkg-config to get the directories and then use these values
# in the FIND_PATH() and FIND_LIBRARY() calls
find_package(PkgConfig)
if (PKG_CONFIG_FOUND)
pkg_check_modules(PC_${_component} QUIET ${_pkgconfig})
endif ()
endif (NOT WIN32)
find_path(${_component}_INCLUDE_DIRS ${_header}
HINTS
${PC_LIB${_component}_INCLUDEDIR}
${PC_LIB${_component}_INCLUDE_DIRS}
PATH_SUFFIXES
ffmpeg
)
find_library(${_component}_LIBRARIES NAMES ${_library}
HINTS
${PC_LIB${_component}_LIBDIR}
${PC_LIB${_component}_LIBRARY_DIRS}
)
set(${_component}_DEFINITIONS ${PC_${_component}_CFLAGS_OTHER} CACHE STRING "The ${_component} CFLAGS.")
set(${_component}_VERSION ${PC_${_component}_VERSION} CACHE STRING "The ${_component} version number.")
set_component_found(${_component})
mark_as_advanced(
${_component}_INCLUDE_DIRS
${_component}_LIBRARIES
${_component}_DEFINITIONS
${_component}_VERSION)
endmacro()
# Check for cached results. If there are skip the costly part.
if (NOT FFMPEG_LIBRARIES)
# Check for all possible component.
find_component(AVCODEC libavcodec avcodec libavcodec/avcodec.h)
find_component(AVFORMAT libavformat avformat libavformat/avformat.h)
find_component(AVDEVICE libavdevice avdevice libavdevice/avdevice.h)
find_component(AVUTIL libavutil avutil libavutil/avutil.h)
find_component(SWSCALE libswscale swscale libswscale/swscale.h)
find_component(POSTPROCESS libpostproc postproc libpostproc/postprocess.h)
# Check if the required components were found and add their stuff to the FFMPEG_* vars.
foreach (_component ${_FFmpeg_ALL_COMPONENTS})
if (${_component}_FOUND)
set(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} ${${_component}_LIBRARIES})
set(FFMPEG_DEFINITIONS ${FFMPEG_DEFINITIONS} ${${_component}_DEFINITIONS})
list(APPEND FFMPEG_INCLUDE_DIRS ${${_component}_INCLUDE_DIRS})
endif ()
endforeach ()
# Build the include path with duplicates removed.
if (FFMPEG_INCLUDE_DIRS)
list(REMOVE_DUPLICATES FFMPEG_INCLUDE_DIRS)
endif ()
# cache the vars.
set(FFMPEG_INCLUDE_DIRS ${FFMPEG_INCLUDE_DIRS} CACHE STRING "The FFmpeg include directories." FORCE)
set(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} CACHE STRING "The FFmpeg libraries." FORCE)
set(FFMPEG_DEFINITIONS ${FFMPEG_DEFINITIONS} CACHE STRING "The FFmpeg cflags." FORCE)
mark_as_advanced(FFMPEG_INCLUDE_DIRS
FFMPEG_LIBRARIES
FFMPEG_DEFINITIONS)
else ()
# Set the noncached _FOUND vars for the components.
foreach (_component ${_FFmpeg_ALL_COMPONENTS})
set_component_found(${_component})
endforeach ()
endif ()
# Compile the list of required vars
unset(_FFmpeg_REQUIRED_VARS)
set(_FFmpeg_FOUND_LIBRARIES "")
foreach (_component ${FFmpeg_FIND_COMPONENTS})
if (${_component}_FOUND)
if (${_component}_VERSION VERSION_LESS _FFmpeg_REQUIRED_VERSION)
message(STATUS "${_component}: ${${_component}_VERSION} < ${_FFmpeg_REQUIRED_VERSION}")
unset(${_component}_FOUND)
endif ()
list(APPEND _FFmpeg_FOUND_LIBRARIES ${${_component}_LIBRARIES})
endif ()
list(APPEND _FFmpeg_REQUIRED_VARS ${_component}_LIBRARIES ${_component}_INCLUDE_DIRS ${_component}_FOUND)
endforeach ()
list(INSERT _FFmpeg_REQUIRED_VARS 0 _FFmpeg_FOUND_LIBRARIES)
# Give a nice error message if some of the required vars are missing.
find_package_handle_standard_args(FFmpeg
REQUIRED_VARS ${_FFmpeg_REQUIRED_VARS}
HANDLE_COMPONENTS)

166
CMakeModules/FindGDAL.cmake Normal file
View File

@@ -0,0 +1,166 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#[=======================================================================[.rst:
FindGDAL
--------
Find Geospatial Data Abstraction Library (GDAL).
IMPORTED Targets
^^^^^^^^^^^^^^^^
This module defines :prop_tgt:`IMPORTED` target ``GDAL::GDAL``
if GDAL has been found.
Result Variables
^^^^^^^^^^^^^^^^
This module will set the following variables in your project:
``GDAL_FOUND``
True if GDAL is found.
``GDAL_INCLUDE_DIRS``
Include directories for GDAL headers.
``GDAL_LIBRARIES``
Libraries to link to GDAL.
``GDAL_VERSION``
The version of GDAL found.
Cache variables
^^^^^^^^^^^^^^^
The following cache variables may also be set:
``GDAL_LIBRARY``
The libgdal library file.
``GDAL_INCLUDE_DIR``
The directory containing ``gdal.h``.
Hints
^^^^^
Set ``GDAL_DIR`` or ``GDAL_ROOT`` in the environment to specify the
GDAL installation prefix.
#]=======================================================================]
# $GDALDIR is an environment variable that would
# correspond to the ./configure --prefix=$GDAL_DIR
# used in building gdal.
#
# Created by Eric Wing. I'm not a gdal user, but OpenSceneGraph uses it
# for osgTerrain so I whipped this module together for completeness.
# I actually don't know the conventions or where files are typically
# placed in distros.
# Any real gdal users are encouraged to correct this (but please don't
# break the OS X framework stuff when doing so which is what usually seems
# to happen).
# This makes the presumption that you are include gdal.h like
#
#include "gdal.h"
include(FindPackageHandleStandardArgs)
find_path(GDAL_INCLUDE_DIR gdal.h
HINTS
ENV GDAL_DIR
ENV GDAL_ROOT
PATH_SUFFIXES
include/gdal
include/GDAL
include
)
if(UNIX)
# Use gdal-config to obtain the library version (this should hopefully
# allow us to -lgdal1.x.y where x.y are correct version)
# For some reason, libgdal development packages do not contain
# libgdal.so...
find_program(GDAL_CONFIG gdal-config
HINTS
ENV GDAL_DIR
ENV GDAL_ROOT
PATH_SUFFIXES bin
)
if(GDAL_CONFIG)
exec_program(${GDAL_CONFIG} ARGS --libs OUTPUT_VARIABLE GDAL_CONFIG_LIBS)
if(GDAL_CONFIG_LIBS)
# treat the output as a command line and split it up
separate_arguments(args NATIVE_COMMAND "${GDAL_CONFIG_LIBS}")
# only consider libraries whose name matches this pattern
set(name_pattern "[gG][dD][aA][lL]")
# consider each entry as a possible library path, name, or parent directory
foreach(arg IN LISTS args)
# library name
if("${arg}" MATCHES "^-l(.*)$")
set(lib "${CMAKE_MATCH_1}")
# only consider libraries whose name matches the expected pattern
if("${lib}" MATCHES "${name_pattern}")
list(APPEND _gdal_lib "${lib}")
endif()
# library search path
elseif("${arg}" MATCHES "^-L(.*)$")
list(APPEND _gdal_libpath "${CMAKE_MATCH_1}")
# assume this is a full path to a library
elseif(IS_ABSOLUTE "${arg}" AND EXISTS "${arg}")
# extract the file name
get_filename_component(lib "${arg}" NAME)
# only consider libraries whose name matches the expected pattern
if(NOT "${lib}" MATCHES "${name_pattern}")
continue()
endif()
# extract the file directory
get_filename_component(dir "${arg}" DIRECTORY)
# remove library prefixes/suffixes
string(REGEX REPLACE "^(${CMAKE_SHARED_LIBRARY_PREFIX}|${CMAKE_STATIC_LIBRARY_PREFIX})" "" lib "${lib}")
string(REGEX REPLACE "(${CMAKE_SHARED_LIBRARY_SUFFIX}|${CMAKE_STATIC_LIBRARY_SUFFIX})$" "" lib "${lib}")
# use the file name and directory as hints
list(APPEND _gdal_libpath "${dir}")
list(APPEND _gdal_lib "${lib}")
endif()
endforeach()
endif()
endif()
endif()
find_library(GDAL_LIBRARY
NAMES ${_gdal_lib} gdal gdal_i gdal1.5.0 gdal1.4.0 gdal1.3.2 GDAL
HINTS
ENV GDAL_DIR
ENV GDAL_ROOT
${_gdal_libpath}
PATH_SUFFIXES lib
)
if (EXISTS "${GDAL_INCLUDE_DIR}/gdal_version.h")
file(STRINGS "${GDAL_INCLUDE_DIR}/gdal_version.h" _gdal_version
REGEX "GDAL_RELEASE_NAME")
string(REGEX REPLACE ".*\"\(.*\)\"" "\\1" GDAL_VERSION "${_gdal_version}")
unset(_gdal_version)
else ()
set(GDAL_VERSION GDAL_VERSION-NOTFOUND)
endif ()
FIND_PACKAGE_HANDLE_STANDARD_ARGS(GDAL
VERSION_VAR GDAL_VERSION
REQUIRED_VARS GDAL_LIBRARY GDAL_INCLUDE_DIR)
if (GDAL_FOUND AND NOT TARGET GDAL::GDAL)
add_library(GDAL::GDAL UNKNOWN IMPORTED)
set_target_properties(GDAL::GDAL PROPERTIES
IMPORTED_LOCATION "${GDAL_LIBRARY}"
INTERFACE_INCLUDE_DIRECTORIES "${GDAL_INCLUDE_DIR}")
endif ()
set(GDAL_LIBRARIES ${GDAL_LIBRARY})
set(GDAL_INCLUDE_DIRS ${GDAL_INCLUDE_DIR})

View File

@@ -0,0 +1,124 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#[=======================================================================[.rst:
FindLibLZMA
-----------
Find LZMA compression algorithm headers and library.
Imported Targets
^^^^^^^^^^^^^^^^
This module defines :prop_tgt:`IMPORTED` target ``LibLZMA::LibLZMA``, if
liblzma has been found.
Result variables
^^^^^^^^^^^^^^^^
This module will set the following variables in your project:
``LIBLZMA_FOUND``
True if liblzma headers and library were found.
``LIBLZMA_INCLUDE_DIRS``
Directory where liblzma headers are located.
``LIBLZMA_LIBRARIES``
Lzma libraries to link against.
``LIBLZMA_HAS_AUTO_DECODER``
True if lzma_auto_decoder() is found (required).
``LIBLZMA_HAS_EASY_ENCODER``
True if lzma_easy_encoder() is found (required).
``LIBLZMA_HAS_LZMA_PRESET``
True if lzma_lzma_preset() is found (required).
``LIBLZMA_VERSION_MAJOR``
The major version of lzma
``LIBLZMA_VERSION_MINOR``
The minor version of lzma
``LIBLZMA_VERSION_PATCH``
The patch version of lzma
``LIBLZMA_VERSION_STRING``
version number as a string (ex: "5.0.3")
#]=======================================================================]
find_path(LIBLZMA_INCLUDE_DIR lzma.h )
if(NOT LIBLZMA_LIBRARY)
find_library(LIBLZMA_LIBRARY_RELEASE NAMES lzma liblzma NAMES_PER_DIR PATH_SUFFIXES lib)
find_library(LIBLZMA_LIBRARY_DEBUG NAMES lzmad liblzmad NAMES_PER_DIR PATH_SUFFIXES lib)
include(SelectLibraryConfigurations)
select_library_configurations(LIBLZMA)
else()
file(TO_CMAKE_PATH "${LIBLZMA_LIBRARY}" LIBLZMA_LIBRARY)
endif()
if(LIBLZMA_INCLUDE_DIR AND EXISTS "${LIBLZMA_INCLUDE_DIR}/lzma/version.h")
file(STRINGS "${LIBLZMA_INCLUDE_DIR}/lzma/version.h" LIBLZMA_HEADER_CONTENTS REGEX "#define LZMA_VERSION_[A-Z]+ [0-9]+")
string(REGEX REPLACE ".*#define LZMA_VERSION_MAJOR ([0-9]+).*" "\\1" LIBLZMA_VERSION_MAJOR "${LIBLZMA_HEADER_CONTENTS}")
string(REGEX REPLACE ".*#define LZMA_VERSION_MINOR ([0-9]+).*" "\\1" LIBLZMA_VERSION_MINOR "${LIBLZMA_HEADER_CONTENTS}")
string(REGEX REPLACE ".*#define LZMA_VERSION_PATCH ([0-9]+).*" "\\1" LIBLZMA_VERSION_PATCH "${LIBLZMA_HEADER_CONTENTS}")
set(LIBLZMA_VERSION_STRING "${LIBLZMA_VERSION_MAJOR}.${LIBLZMA_VERSION_MINOR}.${LIBLZMA_VERSION_PATCH}")
unset(LIBLZMA_HEADER_CONTENTS)
endif()
# We're using new code known now as XZ, even library still been called LZMA
# it can be found in http://tukaani.org/xz/
# Avoid using old codebase
if (LIBLZMA_LIBRARY)
include(CheckLibraryExists)
set(CMAKE_REQUIRED_QUIET_SAVE ${CMAKE_REQUIRED_QUIET})
set(CMAKE_REQUIRED_QUIET ${LibLZMA_FIND_QUIETLY})
if(NOT LIBLZMA_LIBRARY_RELEASE AND NOT LIBLZMA_LIBRARY_DEBUG)
set(LIBLZMA_LIBRARY_check ${LIBLZMA_LIBRARY})
elseif(LIBLZMA_LIBRARY_RELEASE)
set(LIBLZMA_LIBRARY_check ${LIBLZMA_LIBRARY_RELEASE})
elseif(LIBLZMA_LIBRARY_DEBUG)
set(LIBLZMA_LIBRARY_check ${LIBLZMA_LIBRARY_DEBUG})
endif()
CHECK_LIBRARY_EXISTS(${LIBLZMA_LIBRARY_check} lzma_auto_decoder "" LIBLZMA_HAS_AUTO_DECODER)
CHECK_LIBRARY_EXISTS(${LIBLZMA_LIBRARY_check} lzma_easy_encoder "" LIBLZMA_HAS_EASY_ENCODER)
CHECK_LIBRARY_EXISTS(${LIBLZMA_LIBRARY_check} lzma_lzma_preset "" LIBLZMA_HAS_LZMA_PRESET)
unset(LIBLZMA_LIBRARY_check)
set(CMAKE_REQUIRED_QUIET ${CMAKE_REQUIRED_QUIET_SAVE})
endif ()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(LibLZMA REQUIRED_VARS LIBLZMA_LIBRARY
LIBLZMA_INCLUDE_DIR
LIBLZMA_HAS_AUTO_DECODER
LIBLZMA_HAS_EASY_ENCODER
LIBLZMA_HAS_LZMA_PRESET
VERSION_VAR LIBLZMA_VERSION_STRING
)
mark_as_advanced( LIBLZMA_INCLUDE_DIR LIBLZMA_LIBRARY )
if (LIBLZMA_FOUND)
set(LIBLZMA_LIBRARIES ${LIBLZMA_LIBRARY})
set(LIBLZMA_INCLUDE_DIRS ${LIBLZMA_INCLUDE_DIR})
if(NOT TARGET LibLZMA::LibLZMA)
add_library(LibLZMA::LibLZMA UNKNOWN IMPORTED)
set_target_properties(LibLZMA::LibLZMA PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${LIBLZMA_INCLUDE_DIR}
IMPORTED_LINK_INTERFACE_LANGUAGES C)
if(LIBLZMA_LIBRARY_RELEASE)
set_property(TARGET LibLZMA::LibLZMA APPEND PROPERTY
IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(LibLZMA::LibLZMA PROPERTIES
IMPORTED_LOCATION_RELEASE "${LIBLZMA_LIBRARY_RELEASE}")
endif()
if(LIBLZMA_LIBRARY_DEBUG)
set_property(TARGET LibLZMA::LibLZMA APPEND PROPERTY
IMPORTED_CONFIGURATIONS DEBUG)
set_target_properties(LibLZMA::LibLZMA PROPERTIES
IMPORTED_LOCATION_DEBUG "${LIBLZMA_LIBRARY_DEBUG}")
endif()
if(NOT LIBLZMA_LIBRARY_RELEASE AND NOT LIBLZMA_LIBRARY_DEBUG)
set_target_properties(LibLZMA::LibLZMA PROPERTIES
IMPORTED_LOCATION "${LIBLZMA_LIBRARY}")
endif()
endif()
endif ()

View File

@@ -38,5 +38,18 @@ else ()
# show the UDNS_INCLUDE_DIRS and UDNS_LIBRARIES variables only in the advanced view
mark_as_advanced(UDNS_INCLUDE_DIRS UDNS_LIBRARIES)
endif ()
if(UDNS_FOUND)
if(NOT TARGET Udns::Udns)
add_library(Udns::Udns UNKNOWN IMPORTED)
set_target_properties(Udns::Udns PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${UDNS_INCLUDE_DIRS}")
set_target_properties(Udns::Udns PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
IMPORTED_LOCATION "${UDNS_LIBRARIES}")
endif()
endif()

View File

@@ -0,0 +1,23 @@
#packaging
SET(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/COPYING")
SET(CPACK_RESOURCE_FILE_README "${PROJECT_SOURCE_DIR}/README")
SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Simulation support libraries for FlightGear and related projects")
SET(CPACK_PACKAGE_VENDOR "The FlightGear project")
SET(CPACK_GENERATOR "TBZ2")
SET(CPACK_INSTALL_CMAKE_PROJECTS ${CMAKE_CURRENT_BINARY_DIR};SimGear;ALL;/)
# split version string into components, note CMAKE_MATCH_0 is the entire regexp match
string(REGEX MATCH "([0-9]+)\\.([0-9]+)\\.([0-9]+)" CPACK_PACKAGE_VERSION ${SIMGEAR_VERSION} )
set(CPACK_PACKAGE_VERSION_MAJOR ${CMAKE_MATCH_1})
set(CPACK_PACKAGE_VERSION_MINOR ${CMAKE_MATCH_2})
set(CPACK_PACKAGE_VERSION_PATCH ${CMAKE_MATCH_3})
message(STATUS "version is ${CPACK_PACKAGE_VERSION_MAJOR} dot ${CPACK_PACKAGE_VERSION_MINOR} dot ${CPACK_PACKAGE_VERSION_PATCH}")
set(CPACK_SOURCE_GENERATOR TBZ2)
set(CPACK_SOURCE_PACKAGE_FILE_NAME "simgear-${SIMGEAR_VERSION}" CACHE INTERNAL "tarball basename")
set(CPACK_SOURCE_IGNORE_FILES
"^${PROJECT_SOURCE_DIR}/.git;\\\\.gitignore;Makefile.am;~$;${CPACK_SOURCE_IGNORE_FILES}")
include (CPack)

View File

@@ -1,36 +1,63 @@
include(CMakeFindDependencyMacro)
find_dependency(ZLIB)
find_dependency(LibLZMA)
find_dependency(Threads)
find_dependency(CURL)
# OSG
set(SIMGEAR_HEADLESS @SIMGEAR_HEADLESS@)
set(SIMGEAR_SOUND @ENABLE_SOUND@)
set(USE_AEONWAVE @USE_AEONWAVE@)
set(SG_SOUND_USES_OPENALSOFT @SG_SOUND_USES_OPENALSOFT@)
# OpenAL isn't a public dependency, so maybe not needed
#if (SIMGEAR_SOUND)
# find_dependency(OpenAL)
#endif()
set(USE_SHADERVG @USE_SHADERVG@)
if (USE_SHADERVG)
endif()
set(ENABLE_ASAN @ENABLE_ASAN@)
set(SIMGEAR_SHARED @SIMGEAR_SHARED@)
# SSE/SSE2 support
set(ENABLE_SIMD @ENABLE_SIMD@)
# SycloneDDS support
set(SG_HAVE_DDS @SG_HAVE_DDS@)
if(SG_HAVE_DDS)
find_dependency(CycloneDDS)
endif()
if (SIMGEAR_SOUND)
# find the sound dependency
if (USE_AEONWAVE)
find_dependency(AAX)
elseif(SG_SOUND_USES_OPENALSOFT)
# must force CONFIG mode when using OpenAL soft, to avoid picking
# the CMake supplied FindOpenAL and hence defaults to the system
# framework on macOS
find_dependency(OpenAL CONFIG)
else()
find_dependency(OpenAL)
endif()
endif()
# OpenRTI support
set(ENABLE_RTI @ENABLE_RTI@)
if(ENABLE_RTI)
set(RTI_FOUND @RTI_FOUND@)
if(RTI_FOUND)
set(RTI_INCLUDE_DIRS @RTI_INCLUDE_DIRS@)
set(RTI_LDFLAGS @RTI_LDFLAGS@)
endif(RTI_FOUND)
find_dependency(PkgConfig)
if(PKG_CONFIG_FOUND)
pkg_check_modules(RTI IMPORTED_TARGET hla-rti13)
endif(PKG_CONFIG_FOUND)
endif(ENABLE_RTI)
# Alternative terrain engine based on pagedLOD
set(ENABLE_GDAL @ENABLE_GDAL@)
set(ENABLE_OPENMP @ENABLE_OPENMP@)
if (ENABLE_GDAL)
find_dependency(GDAL)
endif()
include("${CMAKE_CURRENT_LIST_DIR}/SimGearTargets.cmake")

1
simgear-version Normal file
View File

@@ -0,0 +1 @@
2020.4.0

View File

@@ -48,7 +48,6 @@ install (FILES ${HEADERS} DESTINATION include/simgear/)
get_property(coreSources GLOBAL PROPERTY CORE_SOURCES)
get_property(sceneSources GLOBAL PROPERTY SCENE_SOURCES)
get_property(publicHeaders GLOBAL PROPERTY PUBLIC_HEADERS)
get_property(localExpatSources GLOBAL PROPERTY LOCAL_EXPAT_SOURCES)
if(SIMGEAR_SHARED)
message(STATUS "Library building mode: SHARED LIBRARIES")
@@ -89,7 +88,7 @@ else()
source_group("${name}\\Headers" FILES ${g2})
endforeach()
add_library(SimGearCore STATIC ${coreSources} ${localExpatSources})
add_library(SimGearCore STATIC ${coreSources})
if(NOT SIMGEAR_HEADLESS)
get_property(FG_GROUPS_SCENE_SOURCES_C GLOBAL PROPERTY FG_GROUPS_SCENE_SOURCES_C)
@@ -118,91 +117,98 @@ target_include_directories(SimGearCore BEFORE PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
$<INSTALL_INTERFACE:include>)
# so simgear/simgear_config.h is found
target_include_directories(SimGearCore BEFORE PUBLIC
$<BUILD_INTERFACE:${PROJECT_BINARY_DIR}>
$<INSTALL_INTERFACE:include>)
# for simgear_config.h
target_include_directories(SimGearCore PRIVATE ${PROJECT_BINARY_DIR}/simgear)
target_include_directories(SimGearCore PUBLIC
${Boost_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR})
target_include_directories(SimGearCore PRIVATE
${EXPAT_INCLUDE_DIRS} ${CURL_INCLUDE_DIRS})
${Boost_INCLUDE_DIRS})
if (NOT SYSTEM_EXPAT)
# XML_STATIC is important to avoid sg_expat_external.h
# declaring symbols as declspec(import)
target_compile_definitions(SimGearCore PRIVATE HAVE_SIMGEAR_EXPAT_CONFIG_H XML_STATIC)
endif()
install(TARGETS SimGearCore
EXPORT SimGearTargets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
if (NOT SIMGEAR_HEADLESS)
install(TARGETS SimGearScene
EXPORT SimGearTargets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
target_include_directories(SimGearScene BEFORE PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
$<INSTALL_INTERFACE:include>)
target_include_directories(SimGearScene PUBLIC ${OPENSCENEGRAPH_INCLUDE_DIRS})
if (USE_AEONWAVE)
target_include_directories(SimGearScene PRIVATE ${AAX_INCLUDE_DIR} )
else()
target_include_directories(SimGearScene PRIVATE ${OPENAL_INCLUDE_DIR} )
endif()
endif()
install(TARGETS SimGearCore
EXPORT SimGearTargets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
# we expose ZLib in some of our headers
target_link_libraries(SimGearCore PUBLIC ${ZLIB_LIBRARY})
target_link_libraries(SimGearCore PUBLIC ZLIB::ZLIB)
if (SG_HAVE_DDS)
target_link_libraries(SimGearCore PRIVATE CycloneDDS::ddsc)
endif()
if (ENABLE_RTI)
target_sources(SimGearCore PRIVATE $<TARGET_OBJECTS:rti> $<TARGET_OBJECTS:rti13>)
target_link_libraries(SimGearCore PRIVATE PkgConfig::RTI)
endif()
# all of these we keep privately
target_link_libraries(SimGearCore PRIVATE
${SHLWAPI_LIBRARY}
${RT_LIBRARY}
${DL_LIBRARY}
${CMAKE_THREAD_LIBS_INIT}
Threads::Threads
${COCOA_LIBRARY}
${CURL_LIBRARIES}
CURL::libcurl
EXPAT::EXPAT
Udns::Udns
LibLZMA::LibLZMA
${WINSOCK_LIBRARY})
if(SYSTEM_EXPAT)
target_link_libraries(SimGearCore PRIVATE ${EXPAT_LIBRARIES})
endif()
if(ENABLE_DNS AND SYSTEM_UDNS)
target_link_libraries(SimGearCore PRIVATE ${UDNS_LIBRARIES})
endif()
if(NOT SIMGEAR_HEADLESS)
target_include_directories(SimGearScene PRIVATE ${PROJECT_SOURCE_DIR}/simgear/canvas/ShivaVG/include)
target_include_directories(SimGearScene PRIVATE ${PROJECT_SOURCE_DIR}/simgear/canvas/${OPENVG}/include)
target_link_libraries(SimGearScene PUBLIC
SimGearCore
${OPENSCENEGRAPH_LIBRARIES}
)
if(HAVE_INTTYPES_H)
# ShivaVG/ShaderVG needs inttypes.h
target_compile_definitions(SimGearScene PRIVATE HAVE_INTTYPES_H)
endif()
target_link_libraries(SimGearScene PRIVATE
${ZLIB_LIBRARY}
${OPENAL_LIBRARY}
ZLIB::ZLIB
${OPENGL_LIBRARY}
${JPEG_LIBRARY})
${JPEG_LIBRARY}
${FFMPEG_LIBRARIES}
FGTinyGLTF)
# ToDo: define an ALIAS target for the sound backend, to get
# rid of this logic here
if (ENABLE_SOUND)
if (USE_AEONWAVE)
target_link_libraries(SimGearScene PRIVATE ${AAX_LIBRARY})
else()
target_link_libraries(SimGearScene PRIVATE ${OPENAL_LIBRARY} )
endif()
endif()
if(ENABLE_GDAL)
target_link_libraries(SimGearScene PRIVATE ${GDAL_LIBRARIES})
# FIXME: should be RIVATE, but we leak GDAL headers
# in our own headers :(
target_link_libraries(SimGearScene PUBLIC GDAL::GDAL)
endif()
# only actually needed by canvas/KeyboardEvent.cxx
target_include_directories(SimGearScene PRIVATE ${PROJECT_SOURCE_DIR}/3rdparty/utf8/source)
endif()
target_include_directories(SimGearScene PRIVATE ${FFMPEG_INCLUDE_DIRS})
if(ENABLE_RTI)
# Ugly first aid to make hla compile agian
set_property(SOURCE hla/RTI13InteractionClass.cxx hla/RTI13ObjectClass.cxx
hla/RTI13ObjectInstance.cxx hla/RTI13Federate.cxx
hla/RTI13FederateFactory.cxx
APPEND PROPERTY COMPILE_FLAGS "-I${RTI_INCLUDE_DIRS}")
endif(ENABLE_RTI)
install(TARGETS SimGearScene
EXPORT SimGearTargets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
target_include_directories(SimGearScene BEFORE PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
$<INSTALL_INTERFACE:include>)
# for simgear_config.h
target_include_directories(SimGearScene PRIVATE ${PROJECT_BINARY_DIR}/simgear)
target_include_directories(SimGearScene PUBLIC ${OPENSCENEGRAPH_INCLUDE_DIRS})
if (USE_AEONWAVE)
target_include_directories(SimGearScene PRIVATE ${AAX_INCLUDE_DIR} )
else()
target_include_directories(SimGearScene PRIVATE ${OPENAL_INCLUDE_DIR} )
endif()
endif()

View File

@@ -6,11 +6,6 @@ set(SOURCES newbucket.cxx)
simgear_component(bucket bucket "${SOURCES}" "${HEADERS}")
if(ENABLE_TESTS)
add_executable(test_bucket test_bucket.cxx)
add_test(test_bucket ${EXECUTABLE_OUTPUT_PATH}/test_bucket)
target_link_libraries(test_bucket ${TEST_LIBS})
add_simgear_autotest(test_bucket test_bucket.cxx)
endif(ENABLE_TESTS)

View File

@@ -184,6 +184,99 @@ void SGBucket::innerSet( double dlon, double dlat )
}
}
std::string SGBucket::gen_vpb_base() const {
// long int index;
int top_lon, top_lat, main_lon, main_lat;
char hem, pole;
char raw_path[256];
top_lon = lon / 10;
main_lon = lon;
if ( (lon < 0) && (top_lon * 10 != lon) ) {
top_lon -= 1;
}
top_lon *= 10;
if ( top_lon >= 0 ) {
hem = 'e';
} else {
hem = 'w';
top_lon *= -1;
}
if ( main_lon < 0 ) {
main_lon *= -1;
}
top_lat = lat / 10;
main_lat = lat;
if ( (lat < 0) && (top_lat * 10 != lat) ) {
top_lat -= 1;
}
top_lat *= 10;
if ( top_lat >= 0 ) {
pole = 'n';
} else {
pole = 's';
top_lat *= -1;
}
if ( main_lat < 0 ) {
main_lat *= -1;
}
::snprintf(raw_path, 256, "%c%03d%c%02d/%c%03d%c%02d/ws_%c%03d%c%02d",
hem, top_lon, pole, top_lat,
hem, main_lon, pole, main_lat,
hem, main_lon, pole, main_lat);
return raw_path;
}
std::string SGBucket::gen_vpb_subtile(int level, int x, int y) const {
// long int index;
int top_lon, top_lat, main_lon, main_lat;
char hem, pole;
char raw_path[256];
top_lon = lon / 10;
main_lon = lon;
if ( (lon < 0) && (top_lon * 10 != lon) ) {
top_lon -= 1;
}
top_lon *= 10;
if ( top_lon >= 0 ) {
hem = 'e';
} else {
hem = 'w';
top_lon *= -1;
}
if ( main_lon < 0 ) {
main_lon *= -1;
}
top_lat = lat / 10;
main_lat = lat;
if ( (lat < 0) && (top_lat * 10 != lat) ) {
top_lat -= 1;
}
top_lat *= 10;
if ( top_lat >= 0 ) {
pole = 'n';
} else {
pole = 's';
top_lat *= -1;
}
if ( main_lat < 0 ) {
main_lat *= -1;
}
::snprintf(raw_path, 256, "%c%03d%c%02d/%c%03d%c%02d/ws_%c%03d%c%02d_root_L0_X0_Y0/ws_%c%03d%c%02d_L%d_X%d_Y%d_subtile",
hem, top_lon, pole, top_lat,
hem, main_lon, pole, main_lat,
hem, main_lon, pole, main_lat,
hem, main_lon, pole, main_lat,
level, x, y);
return raw_path;
}
// Build the path name for this bucket
std::string SGBucket::gen_base_path() const {
// long int index;

View File

@@ -179,7 +179,21 @@ public:
* @return tile index
*/
inline long int gen_index() const {
return ((lon + 180) << 14) + ((lat + 90) << 6) + (y << 3) + x;
return ((lon + 180) << 14) + ((lat + 90) << 6) + static_cast<unsigned char>(y << 3) + x;
}
/**
* Generate a tile index for this bucket shared with all other buckets with the same lat/lon.
* Used as an index for VPB tiles, which are 1x1 in size.
*
* The index is constructed as follows:
*
* 9 bits - to represent 360 degrees of longitude (-180 to 179)
* 8 bits - to represent 180 degrees of latitude (-90 to 89)
* @return tile index
*/
inline long int gen_vpb_index() const {
return ((lon + 180) << 8) + (lat + 90);
}
/**
@@ -195,6 +209,14 @@ public:
*/
std::string gen_base_path() const;
/**
* Build the base path name for this bucket.
* @return base path in string form
*/
std::string gen_vpb_base() const;
std::string gen_vpb_base_alt() const;
std::string gen_vpb_subtile(int level, int x, int y) const;
/**
* @return the center lon of a tile.
*/

View File

@@ -1,37 +0,0 @@
// Copyright (C) 2008 - 2012 Mathias Froehlich - Mathias.Froehlich@web.de
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <simgear_config.h>
#include "BVHMaterial.hxx"
namespace simgear {
BVHMaterial::BVHMaterial() :
_solid(true),
_friction_factor(1),
_rolling_friction(0.02),
_bumpiness(0),
_load_resistance(1e30)
{
}
BVHMaterial::~BVHMaterial()
{
}
}

View File

@@ -1,4 +1,4 @@
// Copyright (C) 2008 - 2012 Mathias Froehlich - Mathias.Froehlich@web.de
// Copyright (C) 2008 - 2021 Mathias Froehlich - Mathias.Froehlich@web.de
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
@@ -19,19 +19,29 @@
#define BVHMaterial_hxx
#include <simgear/structure/SGReferenced.hxx>
#include <simgear/props/props.hxx>
#include <cstdio>
namespace simgear {
class BVHMaterial : public SGReferenced {
public:
BVHMaterial();
virtual ~BVHMaterial();
BVHMaterial() = default;
virtual ~BVHMaterial() = default;
/**
* Return if the surface material is solid, if it is not solid, a fluid
* can be assumed, that is usually water.
*/
bool get_solid () const { return _solid; }
bool get_solid () const {
return _solid_is_prop ? _solid_property->getBoolValue() : _solid;
}
/**
* Return whether the solid factor is a propery.
*/
bool solid_is_prop () const { return _solid_is_prop; }
/**
* Get the friction factor for that material
@@ -55,21 +65,26 @@ public:
protected:
// True if the material is solid, false if it is a fluid
bool _solid;
bool _solid = true;
// the friction factor of that surface material
double _friction_factor;
double _friction_factor = 1.0;
// the rolling friction of that surface material
double _rolling_friction;
double _rolling_friction = 0.02;
// the bumpiness of that surface material
double _bumpiness;
double _bumpiness = 0.0;
// the load resistance of that surface material
double _load_resistance;
double _load_resistance = 1e30;
// Placeholder for the solid property, if defined
SGPropertyNode_ptr _solid_property;
bool _solid_is_prop = false;
};
}
#endif

View File

@@ -47,8 +47,10 @@ public:
_currentMaterial(0),
_currentMaterialIndex(~0u)
{ }
virtual ~BVHStaticGeometryBuilder()
{ }
{
}
struct LeafRef {
LeafRef(const BVHStaticLeaf* leaf, const BVHStaticData& data) :
@@ -62,7 +64,7 @@ public:
};
typedef std::list<LeafRef> LeafRefList;
struct LeafRefLess : public std::binary_function<LeafRef, LeafRef, bool> {
struct LeafRefLess {
LeafRefLess(unsigned sortAxis) : _sortAxis(sortAxis) {}
bool operator()(const LeafRef& x, const LeafRef& y)
{ return x._center[_sortAxis] < y._center[_sortAxis]; }
@@ -111,6 +113,7 @@ public:
return;
_triangleSet.insert(indexKey);
BVHStaticTriangle* staticTriangle;
// REVIEW: Memory Leak - 11,680 bytes in 365 blocks are indirectly lost
staticTriangle = new BVHStaticTriangle(_currentMaterialIndex, indices);
_leafRefList.push_back(LeafRef(staticTriangle, *_staticData));
}

View File

@@ -39,14 +39,11 @@ set(SOURCES
BVHStaticNode.cxx
BVHStaticTriangle.cxx
BVHSubTreeCollector.cxx
BVHMaterial.cxx
BVHTransform.cxx
)
simgear_component(bvh bvh "${SOURCES}" "${HEADERS}")
if(ENABLE_TESTS)
add_executable(bvhtest bvhtest.cxx)
target_link_libraries(bvhtest SimGearCore)
add_test(bvhtest ${EXECUTABLE_OUTPUT_PATH}/bvhtest)
add_simgear_autotest(bvhtest bvhtest.cxx)
endif(ENABLE_TESTS)

View File

@@ -29,7 +29,7 @@ set(SOURCES
VGInitOperation.cxx
)
add_subdirectory(ShivaVG/src)
add_subdirectory(${OPENVG}/src)
add_subdirectory(elements)
add_subdirectory(events)
add_subdirectory(layout)

View File

@@ -137,6 +137,8 @@ namespace canvas
_status(node, "status"),
_status_msg(node, "status-msg")
{
// Looks like we need to propogate value changes upwards.
node->setAttribute(SGPropertyNode::VALUE_CHANGED_DOWN, true);
_status = 0;
setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
@@ -325,7 +327,7 @@ namespace canvas
if (!_screenshotCallback) {
// no draw callback yet
osg::Image* shot = new osg::Image();
shot->allocateImage(getSizeX(), getSizeY(), 24, GL_RGB, GL_UNSIGNED_BYTE);
shot->allocateImage(getSizeX(), getSizeY(), 1, GL_RGB, GL_UNSIGNED_BYTE);
camera->attach(osg::Camera::COLOR_BUFFER, shot);
camera->setFinalDrawCallback(new CanvasImageCallback(shot));
SG_LOG(SG_GENERAL,SG_INFO,"CanvasImage: attached image and draw callback to camera " << camera << " for canvas " << canvasname << ". Ready for subscriber now.");
@@ -400,6 +402,13 @@ namespace canvas
_sampling_dirty = false;
_render_dirty = true;
}
if( _anisotropy_dirty )
{
_texture.setMaxAnisotropy( _node->getFloatValue("anisotropy") );
_anisotropy_dirty = false;
_render_dirty = true;
}
while( !_dirty_placements.empty() )
{
@@ -691,6 +700,10 @@ namespace canvas
{
_sampling_dirty = true;
}
else if( name == "anisotropy" )
{
_anisotropy_dirty = true;
}
else if( name == "additive-blend" )
{
_texture.useAdditiveBlend( node->getBoolValue() );

View File

@@ -238,6 +238,7 @@ namespace canvas
PropertyObject<std::string> _status_msg;
bool _sampling_dirty {false},
_anisotropy_dirty {false},
_render_dirty {true},
_visible {true};

View File

@@ -45,7 +45,6 @@
#include <osg/ShadeModel>
#include <osg/StateSet>
#include <osg/FrameBufferObject> // for GL_DEPTH_STENCIL_EXT on Windows
#include <osg/Version>
#include <osgUtil/RenderBin>
#include <cassert>
@@ -202,11 +201,16 @@ namespace canvas
updateSampling();
}
//----------------------------------------------------------------------------
void ODGauge::setMaxAnisotropy(float anis)
{
texture->setMaxAnisotropy(anis);
}
//----------------------------------------------------------------------------
void ODGauge::setRender(bool render)
{
// Only the far camera should trigger this texture to be rendered.
camera->setNodeMask(render ? simgear::BACKGROUND_BIT : 0);
camera->setNodeMask(render ? 0xffffffff : 0);
}
//----------------------------------------------------------------------------
@@ -218,6 +222,7 @@ namespace canvas
//----------------------------------------------------------------------------
void ODGauge::allocRT(osg::NodeCallback* camera_cull_callback)
{
// REVIEW: Memory Leak - 2,712 bytes in 3 blocks are indirectly lost
camera = new osg::Camera;
camera->setDataVariance(osg::Object::DYNAMIC);
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
@@ -239,13 +244,16 @@ namespace canvas
stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
// REVIEW: Memory Leak - 168 bytes in 3 blocks are indirectly lost
stateSet->setAttributeAndModes(
new osg::PolygonMode( osg::PolygonMode::FRONT_AND_BACK,
osg::PolygonMode::FILL ),
osg::StateAttribute::ON );
// REVIEW: Memory Leak - 3,572 (8 direct, 3,564 indirect) bytes in 1 blocks are definitely lost
stateSet->setAttributeAndModes(
new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.001f),
osg::StateAttribute::ON );
// REVIEW: Memory Leak - 384 bytes in 3 blocks are indirectly lost
stateSet->setAttribute(new osg::ShadeModel(osg::ShadeModel::FLAT));
if( !texture )
@@ -256,6 +264,7 @@ namespace canvas
// and dynamic mipmap generation doesn't work.
osg::Image* image = new osg::Image;
image->allocateImage(_size_x, _size_y, 1, GL_RGBA, GL_UNSIGNED_BYTE);
// REVIEW: Memory Leak - 1,176 bytes in 3 blocks are indirectly lost
texture = new osg::Texture2D;
texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(image);
@@ -276,11 +285,7 @@ namespace canvas
{
osg::NodeCallback* cull_callback =
camera
#if OSG_VERSION_LESS_THAN(3,3,2)
? camera->getCullCallback()
#else
? dynamic_cast<osg::NodeCallback*>(camera->getCullCallback())
#endif
: 0;
clear();
@@ -292,8 +297,8 @@ namespace canvas
{
if( camera.valid() && Canvas::getSystemAdapter() )
Canvas::getSystemAdapter()->removeCamera(camera.get());
camera.release();
texture.release();
camera = nullptr;
texture = nullptr;
_flags &= ~AVAILABLE;
}
@@ -340,6 +345,7 @@ namespace canvas
if( _flags & USE_STENCIL )
{
// REVIEW: Memory Leak - 264 bytes in 3 blocks are indirectly lost
camera->attach( osg::Camera::PACKED_DEPTH_STENCIL_BUFFER,
GL_DEPTH_STENCIL_EXT );
mask |= GL_STENCIL_BUFFER_BIT;
@@ -378,6 +384,7 @@ namespace canvas
{
assert( camera );
// REVIEW: Memory Leak - 3,572 (136 direct, 3,436 indirect) bytes in 1 blocks are definitely lost
camera->getOrCreateStateSet()
->setAttributeAndModes
(

View File

@@ -109,6 +109,8 @@ namespace canvas
int coverage_samples = 0,
int color_samples = 0 );
void setMaxAnisotropy(float anis);
/**
* Enable/Disable updating the texture (If disabled the contents of the
* texture remains with the outcome of the last rendering pass)

View File

@@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@@ -0,0 +1,223 @@
# ShaderVG
<img src="/examples/test_tiger_shader.gif?raw=true" width="400px">
_**Note:** This project is based on https://github.com/tqm-dev/ShivaVG-2_
## Main Features
- Working on Shader-Based OpenGL
- API extensions for GLSL shader integrated to vector/image rendering
## Getting Started
### Prerequisites
- OpenGL development libraries and headers should be installed.
- freeglut must be installed for rendering on window system.
- jpeglib needs to be installed for example programs that use images.
### Compiling
Clone and enter the repository:
```
$ git clone https://github.com/tqm-dev/ShaderVG
$ cd ShaderVG
```
Under UNIX systems, execute configure and make:
```
$ sh autogen.sh
$ ./configure LIBS="-lGL -lglut -ljpeg"
$ make
```
### Testing
Move to examples directory, execute tests:
```
$ cd examples
$ ./test_tiger_shader
```
#### test_tiger_shader
Well known svg tiger meets GLSL vertex/fragment shading.
#### test_vgu
Constructs some path primitives using the VGU API.
#### test_tiger
The most simple performance test. It draws the well known svg
tiger using just simple stroke and fill of solid colors. It
consists of 240 paths.
#### test_dash
Shows different stroke dashing modes.
#### test_linear
A rectangle drawn using 3-color linear gradient fill paint
#### test_radial
A rectangle drawn using 3-color radial gradient fill paint
#### test_interpolate
Interpolates between two paths - an apple and a pear.
#### test_image
Images are drawn using VG_DRAW_IMAGE_MULTIPLY image mode to be
multiplied with radial gradient fill paint.
#### test_pattern
An image is drawn in multiply mode with an image pattern fill
paint.
## Implementation status
#### General
API | status
----------------------- | ---------------------
vgGetError | FULLY implemented
vgFlush | FULLY implemented
vgFinish | FULLY implemented
#### Getters and setters
API | status
----------------------- | ---------------------
vgSet | FULLY implemented
vgSeti | FULLY implemented
vgSetfv | FULLY implemented
vgSetiv | FULLY implemented
vgGetf | FULLY implemented
vgGeti | FULLY implemented
vgGetVectorSize | FULLY implemented
vgGetfv | FULLY implemented
vgGetiv | FULLY implemented
vgSetParameterf | FULLY implemented
vgSetParameteri | FULLY implemented
vgSetParameterfv | FULLY implemented
vgSetParameteriv | FULLY implemented
vgGetParameterf | FULLY implemented
vgGetParameteri | FULLY implemented
vgGetParameterVectorSize| FULLY implemented
vgGetParameterfv | FULLY implemented
vgGetParameteriv | FULLY implemented
#### Matrix Manipulation
API | status
----------------------- | ---------------------
vgLoadIdentity | FULLY implemented
vgLoadMatrix | FULLY implemented
vgGetMatrix | FULLY implemented
vgMultMatrix | FULLY implemented
vgTranslate | FULLY implemented
vgScale | FULLY implemented
vgShear | FULLY implemented
vgRotate | FULLY implemented
#### Masking and Clearing
API | status
----------------------- | ---------------------
vgMask | NOT implemented
vgClear | FULLY implemented
#### Paths
API | status
----------------------- | ---------------------
vgCreatePath | FULLY implemented
vgClearPath | FULLY implemented
vgDestroyPath | FULLY implemented
vgRemovePathCapabilities| FULLY implemented
vgGetPathCapabilities | FULLY implemented
vgAppendPath | FULLY implemented
vgAppendPathData | FULLY implemented
vgModifyPathCoords | FULLY implemented
vgTransformPath | FULLY implemented
vgInterpolatePath | FULLY implemented
vgPathLength | NOT implemented
vgPointAlongPath | NOT implemented
vgPathBounds | FULLY implemented
vgPathTransformedBounds | FULLY implemented
vgDrawPath | PARTIALLY implemented
#### Paint
API | status
----------------------- | ---------------------
vgCreatePaint | FULLY implemented
vgDestroyPaint | FULLY implemented
vgSetPaint | FULLY implemented
vgGetPaint | FULLY implemented
vgSetColor | FULLY implemented
vgGetColor | FULLY implemented
vgPaintPattern | FULLY implemented
#### Images
API | status
----------------------- | ---------------------
vgCreateImage | PARTIALLY implemented
vgDestroyImage | FULLY implemented
vgClearImage | FULLY implemented
vgImageSubData | PARTIALLY implemented
vgGetImageSubData | PARTIALLY implemented
vgChildImage | NOT implemented
vgGetParent | NOT implemented
vgCopyImage | FULLY implemented
vgDrawImage | PARTIALLY implemented
vgSetPixels | NOT implemented yet
vgWritePixels | NOT implemented yet
vgGetPixels | FULLY implemented
vgReadPixels | FULLY implemented
vgCopyPixels | NOT implemented yet
#### Image Filters
API | status
----------------------- | ---------------------
vgColorMatrix | NOT implemented
vgConvolve | NOT implemented
vgSeparableConvolve | NOT implemented
vgGaussianBlur | NOT implemented
vgLookup | NOT implemented
vgLookupSingle | NOT implemented
#### Queries
API | status
----------------------- | ---------------------
vgHardwareQuery | NOT implemented
vgGetString | FULLY implemented
#### VGU
API | status
----------------------- | ---------------------
vguLine | FULLY implemented
vguPolygon | FULLY implemented
vguRect | FULLY implemented
vguRoundRect | FULLY implemented
vguEllipse | FULLY implemented
vguArc | FULLY implemented
vguComputeWarpQuadToSquare | NOT implemented
vguComputeWarpSquareToQuad | NOT implemented
vguComputeWarpQuadToQuad | NOT implemented
## Extensions
### Manipulate the OpenVG context as a temporary replacement for EGL:
- VGboolean vgCreateContextSH(VGint width, VGint height)
Creates an OpenVG context on top of an existing OpenGL context
that should have been manually initialized by the user of the
library. Width and height specify the size of the rendering
surface. No multi-threading support has been implemented yet.
The context is created once per process.
- void vgResizeSurfaceSH(VGint width, VGint height)
Should be called whenever the size of the surface changes (e.g.
the owner window of the OpenGL context is resized).
- void vgDestroyContextSH()
Destroys the OpenVG context associated with the calling process.
## License
This project is licensed under the GNU Lesser General Public License v2.1 - see the [LICENSE](https://github.com/tqm-dev/ShaderVG/blob/master/COPYING) file for details

View File

@@ -0,0 +1,676 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef _OPENVG_H
#define _OPENVG_H
#define OPENVG_VERSION_1_0_1 1
/* Type definitions */
/* TODO: we can't use config.h in this header so there
must be some other technique to assert the proper
size of the basic types */
typedef float VGfloat;
typedef char VGbyte;
typedef unsigned char VGubyte;
typedef short VGshort;
typedef int VGint;
typedef unsigned int VGuint;
typedef unsigned int VGbitfield;
typedef enum {
VG_FALSE = 0,
VG_TRUE = 1
} VGboolean;
#define VG_MAXSHORT ((VGshort)((~((unsigned)0)) >> 1))
#define VG_MAXINT ((VGint)((~((unsigned)0)) >> 1))
/* Define handle to be of same length as any pointer */
typedef void * VGHandle;
#define VG_INVALID_HANDLE ((VGHandle)NULL)
/* Enumerations */
typedef enum {
VG_NO_ERROR = 0,
VG_BAD_HANDLE_ERROR = 0x1000,
VG_ILLEGAL_ARGUMENT_ERROR = 0x1001,
VG_OUT_OF_MEMORY_ERROR = 0x1002,
VG_PATH_CAPABILITY_ERROR = 0x1003,
VG_UNSUPPORTED_IMAGE_FORMAT_ERROR = 0x1004,
VG_UNSUPPORTED_PATH_FORMAT_ERROR = 0x1005,
VG_IMAGE_IN_USE_ERROR = 0x1006,
VG_NO_CONTEXT_ERROR = 0x1007
} VGErrorCode;
typedef enum {
/* Mode settings */
VG_MATRIX_MODE = 0x1100,
VG_FILL_RULE = 0x1101,
VG_IMAGE_QUALITY = 0x1102,
VG_RENDERING_QUALITY = 0x1103,
VG_BLEND_MODE = 0x1104,
VG_IMAGE_MODE = 0x1105,
/* Scissoring rectangles */
VG_SCISSOR_RECTS = 0x1106,
/* Stroke parameters */
VG_STROKE_LINE_WIDTH = 0x1110,
VG_STROKE_CAP_STYLE = 0x1111,
VG_STROKE_JOIN_STYLE = 0x1112,
VG_STROKE_MITER_LIMIT = 0x1113,
VG_STROKE_DASH_PATTERN = 0x1114,
VG_STROKE_DASH_PHASE = 0x1115,
VG_STROKE_DASH_PHASE_RESET = 0x1116,
/* Edge fill color for VG_TILE_FILL tiling mode */
VG_TILE_FILL_COLOR = 0x1120,
/* Color for vgClear */
VG_CLEAR_COLOR = 0x1121,
/* Enable/disable alpha masking and scissoring */
VG_MASKING = 0x1130,
VG_SCISSORING = 0x1131,
/* Pixel layout information */
VG_PIXEL_LAYOUT = 0x1140,
VG_SCREEN_LAYOUT = 0x1141,
/* Source format selection for image filters */
VG_FILTER_FORMAT_LINEAR = 0x1150,
VG_FILTER_FORMAT_PREMULTIPLIED = 0x1151,
/* Destination write enable mask for image filters */
VG_FILTER_CHANNEL_MASK = 0x1152,
/* Implementation limits (read-only) */
VG_MAX_SCISSOR_RECTS = 0x1160,
VG_MAX_DASH_COUNT = 0x1161,
VG_MAX_KERNEL_SIZE = 0x1162,
VG_MAX_SEPARABLE_KERNEL_SIZE = 0x1163,
VG_MAX_COLOR_RAMP_STOPS = 0x1164,
VG_MAX_IMAGE_WIDTH = 0x1165,
VG_MAX_IMAGE_HEIGHT = 0x1166,
VG_MAX_IMAGE_PIXELS = 0x1167,
VG_MAX_IMAGE_BYTES = 0x1168,
VG_MAX_FLOAT = 0x1169,
VG_MAX_GAUSSIAN_STD_DEVIATION = 0x116A
} VGParamType;
typedef enum {
VG_RENDERING_QUALITY_NONANTIALIASED = 0x1200,
VG_RENDERING_QUALITY_FASTER = 0x1201,
VG_RENDERING_QUALITY_BETTER = 0x1202 /* Default */
} VGRenderingQuality;
typedef enum {
VG_PIXEL_LAYOUT_UNKNOWN = 0x1300,
VG_PIXEL_LAYOUT_RGB_VERTICAL = 0x1301,
VG_PIXEL_LAYOUT_BGR_VERTICAL = 0x1302,
VG_PIXEL_LAYOUT_RGB_HORIZONTAL = 0x1303,
VG_PIXEL_LAYOUT_BGR_HORIZONTAL = 0x1304
} VGPixelLayout;
typedef enum {
VG_MATRIX_PATH_USER_TO_SURFACE = 0x1400,
VG_MATRIX_IMAGE_USER_TO_SURFACE = 0x1401,
VG_MATRIX_FILL_PAINT_TO_USER = 0x1402,
VG_MATRIX_STROKE_PAINT_TO_USER = 0x1403
} VGMatrixMode;
typedef enum {
VG_CLEAR_MASK = 0x1500,
VG_FILL_MASK = 0x1501,
VG_SET_MASK = 0x1502,
VG_UNION_MASK = 0x1503,
VG_INTERSECT_MASK = 0x1504,
VG_SUBTRACT_MASK = 0x1505
} VGMaskOperation;
#define VG_PATH_FORMAT_STANDARD 0
typedef enum {
VG_PATH_DATATYPE_S_8 = 0,
VG_PATH_DATATYPE_S_16 = 1,
VG_PATH_DATATYPE_S_32 = 2,
VG_PATH_DATATYPE_F = 3
} VGPathDatatype;
typedef enum {
VG_ABSOLUTE = 0,
VG_RELATIVE = 1
} VGPathAbsRel;
typedef enum {
VG_CLOSE_PATH = ( 0 << 1),
VG_MOVE_TO = ( 1 << 1),
VG_LINE_TO = ( 2 << 1),
VG_HLINE_TO = ( 3 << 1),
VG_VLINE_TO = ( 4 << 1),
VG_QUAD_TO = ( 5 << 1),
VG_CUBIC_TO = ( 6 << 1),
VG_SQUAD_TO = ( 7 << 1),
VG_SCUBIC_TO = ( 8 << 1),
VG_SCCWARC_TO = ( 9 << 1),
VG_SCWARC_TO = (10 << 1),
VG_LCCWARC_TO = (11 << 1),
VG_LCWARC_TO = (12 << 1)
} VGPathSegment;
typedef enum {
VG_MOVE_TO_ABS = VG_MOVE_TO | VG_ABSOLUTE,
VG_MOVE_TO_REL = VG_MOVE_TO | VG_RELATIVE,
VG_LINE_TO_ABS = VG_LINE_TO | VG_ABSOLUTE,
VG_LINE_TO_REL = VG_LINE_TO | VG_RELATIVE,
VG_HLINE_TO_ABS = VG_HLINE_TO | VG_ABSOLUTE,
VG_HLINE_TO_REL = VG_HLINE_TO | VG_RELATIVE,
VG_VLINE_TO_ABS = VG_VLINE_TO | VG_ABSOLUTE,
VG_VLINE_TO_REL = VG_VLINE_TO | VG_RELATIVE,
VG_QUAD_TO_ABS = VG_QUAD_TO | VG_ABSOLUTE,
VG_QUAD_TO_REL = VG_QUAD_TO | VG_RELATIVE,
VG_CUBIC_TO_ABS = VG_CUBIC_TO | VG_ABSOLUTE,
VG_CUBIC_TO_REL = VG_CUBIC_TO | VG_RELATIVE,
VG_SQUAD_TO_ABS = VG_SQUAD_TO | VG_ABSOLUTE,
VG_SQUAD_TO_REL = VG_SQUAD_TO | VG_RELATIVE,
VG_SCUBIC_TO_ABS = VG_SCUBIC_TO | VG_ABSOLUTE,
VG_SCUBIC_TO_REL = VG_SCUBIC_TO | VG_RELATIVE,
VG_SCCWARC_TO_ABS = VG_SCCWARC_TO | VG_ABSOLUTE,
VG_SCCWARC_TO_REL = VG_SCCWARC_TO | VG_RELATIVE,
VG_SCWARC_TO_ABS = VG_SCWARC_TO | VG_ABSOLUTE,
VG_SCWARC_TO_REL = VG_SCWARC_TO | VG_RELATIVE,
VG_LCCWARC_TO_ABS = VG_LCCWARC_TO | VG_ABSOLUTE,
VG_LCCWARC_TO_REL = VG_LCCWARC_TO | VG_RELATIVE,
VG_LCWARC_TO_ABS = VG_LCWARC_TO | VG_ABSOLUTE,
VG_LCWARC_TO_REL = VG_LCWARC_TO | VG_RELATIVE
} VGPathCommand;
typedef VGHandle VGPath;
typedef enum {
VG_PATH_CAPABILITY_APPEND_FROM = (1 << 0),
VG_PATH_CAPABILITY_APPEND_TO = (1 << 1),
VG_PATH_CAPABILITY_MODIFY = (1 << 2),
VG_PATH_CAPABILITY_TRANSFORM_FROM = (1 << 3),
VG_PATH_CAPABILITY_TRANSFORM_TO = (1 << 4),
VG_PATH_CAPABILITY_INTERPOLATE_FROM = (1 << 5),
VG_PATH_CAPABILITY_INTERPOLATE_TO = (1 << 6),
VG_PATH_CAPABILITY_PATH_LENGTH = (1 << 7),
VG_PATH_CAPABILITY_POINT_ALONG_PATH = (1 << 8),
VG_PATH_CAPABILITY_TANGENT_ALONG_PATH = (1 << 9),
VG_PATH_CAPABILITY_PATH_BOUNDS = (1 << 10),
VG_PATH_CAPABILITY_PATH_TRANSFORMED_BOUNDS = (1 << 11),
VG_PATH_CAPABILITY_ALL = (1 << 12) - 1
} VGPathCapabilities;
typedef enum {
VG_PATH_FORMAT = 0x1600,
VG_PATH_DATATYPE = 0x1601,
VG_PATH_SCALE = 0x1602,
VG_PATH_BIAS = 0x1603,
VG_PATH_NUM_SEGMENTS = 0x1604,
VG_PATH_NUM_COORDS = 0x1605
} VGPathParamType;
typedef enum {
VG_CAP_BUTT = 0x1700,
VG_CAP_ROUND = 0x1701,
VG_CAP_SQUARE = 0x1702
} VGCapStyle;
typedef enum {
VG_JOIN_MITER = 0x1800,
VG_JOIN_ROUND = 0x1801,
VG_JOIN_BEVEL = 0x1802
} VGJoinStyle;
typedef enum {
VG_EVEN_ODD = 0x1900,
VG_NON_ZERO = 0x1901
} VGFillRule;
typedef enum {
VG_STROKE_PATH = (1 << 0),
VG_FILL_PATH = (1 << 1)
} VGPaintMode;
typedef VGHandle VGPaint;
typedef enum {
/* Color paint parameters */
VG_PAINT_TYPE = 0x1A00,
VG_PAINT_COLOR = 0x1A01,
VG_PAINT_COLOR_RAMP_SPREAD_MODE = 0x1A02,
VG_PAINT_COLOR_RAMP_PREMULTIPLIED = 0x1A07,
VG_PAINT_COLOR_RAMP_STOPS = 0x1A03,
/* Linear gradient paint parameters */
VG_PAINT_LINEAR_GRADIENT = 0x1A04,
/* Radial gradient paint parameters */
VG_PAINT_RADIAL_GRADIENT = 0x1A05,
/* Pattern paint parameters */
VG_PAINT_PATTERN_TILING_MODE = 0x1A06
} VGPaintParamType;
typedef enum {
VG_PAINT_TYPE_COLOR = 0x1B00,
VG_PAINT_TYPE_LINEAR_GRADIENT = 0x1B01,
VG_PAINT_TYPE_RADIAL_GRADIENT = 0x1B02,
VG_PAINT_TYPE_PATTERN = 0x1B03
} VGPaintType;
typedef enum {
VG_COLOR_RAMP_SPREAD_PAD = 0x1C00,
VG_COLOR_RAMP_SPREAD_REPEAT = 0x1C01,
VG_COLOR_RAMP_SPREAD_REFLECT = 0x1C02
} VGColorRampSpreadMode;
typedef enum {
VG_TILE_FILL = 0x1D00,
VG_TILE_PAD = 0x1D01,
VG_TILE_REPEAT = 0x1D02,
VG_TILE_REFLECT = 0x1D03
} VGTilingMode;
typedef enum {
/* RGB{A,X} channel ordering */
VG_sRGBX_8888 = 0,
VG_sRGBA_8888 = 1,
VG_sRGBA_8888_PRE = 2,
VG_sRGB_565 = 3,
VG_sRGBA_5551 = 4,
VG_sRGBA_4444 = 5,
VG_sL_8 = 6,
VG_lRGBX_8888 = 7,
VG_lRGBA_8888 = 8,
VG_lRGBA_8888_PRE = 9,
VG_lL_8 = 10,
VG_A_8 = 11,
VG_BW_1 = 12,
/* {A,X}RGB channel ordering */
VG_sXRGB_8888 = 0 | (1 << 6),
VG_sARGB_8888 = 1 | (1 << 6),
VG_sARGB_8888_PRE = 2 | (1 << 6),
VG_sARGB_1555 = 4 | (1 << 6),
VG_sARGB_4444 = 5 | (1 << 6),
VG_lXRGB_8888 = 7 | (1 << 6),
VG_lARGB_8888 = 8 | (1 << 6),
VG_lARGB_8888_PRE = 9 | (1 << 6),
/* BGR{A,X} channel ordering */
VG_sBGRX_8888 = 0 | (1 << 7),
VG_sBGRA_8888 = 1 | (1 << 7),
VG_sBGRA_8888_PRE = 2 | (1 << 7),
VG_sBGR_565 = 3 | (1 << 7),
VG_sBGRA_5551 = 4 | (1 << 7),
VG_sBGRA_4444 = 5 | (1 << 7),
VG_lBGRX_8888 = 7 | (1 << 7),
VG_lBGRA_8888 = 8 | (1 << 7),
VG_lBGRA_8888_PRE = 9 | (1 << 7),
/* {A,X}BGR channel ordering */
VG_sXBGR_8888 = 0 | (1 << 6) | (1 << 7),
VG_sABGR_8888 = 1 | (1 << 6) | (1 << 7),
VG_sABGR_8888_PRE = 2 | (1 << 6) | (1 << 7),
VG_sABGR_1555 = 4 | (1 << 6) | (1 << 7),
VG_sABGR_4444 = 5 | (1 << 6) | (1 << 7),
VG_lXBGR_8888 = 7 | (1 << 6) | (1 << 7),
VG_lABGR_8888 = 8 | (1 << 6) | (1 << 7),
VG_lABGR_8888_PRE = 9 | (1 << 6) | (1 << 7)
} VGImageFormat;
typedef VGHandle VGImage;
typedef enum {
VG_IMAGE_QUALITY_NONANTIALIASED = (1 << 0),
VG_IMAGE_QUALITY_FASTER = (1 << 1),
VG_IMAGE_QUALITY_BETTER = (1 << 2)
} VGImageQuality;
typedef enum {
VG_IMAGE_FORMAT = 0x1E00,
VG_IMAGE_WIDTH = 0x1E01,
VG_IMAGE_HEIGHT = 0x1E02
} VGImageParamType;
typedef enum {
VG_DRAW_IMAGE_NORMAL = 0x1F00,
VG_DRAW_IMAGE_MULTIPLY = 0x1F01,
VG_DRAW_IMAGE_STENCIL = 0x1F02
} VGImageMode;
typedef enum {
VG_RED = (1 << 3),
VG_GREEN = (1 << 2),
VG_BLUE = (1 << 1),
VG_ALPHA = (1 << 0)
} VGImageChannel;
typedef enum {
VG_BLEND_SRC = 0x2000,
VG_BLEND_SRC_OVER = 0x2001,
VG_BLEND_DST_OVER = 0x2002,
VG_BLEND_SRC_IN = 0x2003,
VG_BLEND_DST_IN = 0x2004,
VG_BLEND_MULTIPLY = 0x2005,
VG_BLEND_SCREEN = 0x2006,
VG_BLEND_DARKEN = 0x2007,
VG_BLEND_LIGHTEN = 0x2008,
VG_BLEND_ADDITIVE = 0x2009,
VG_BLEND_SRC_OUT_SH = 0x200A,
VG_BLEND_DST_OUT_SH = 0x200B,
VG_BLEND_SRC_ATOP_SH = 0x200C,
VG_BLEND_DST_ATOP_SH = 0x200D
} VGBlendMode;
typedef enum {
VG_IMAGE_FORMAT_QUERY = 0x2100,
VG_PATH_DATATYPE_QUERY = 0x2101
} VGHardwareQueryType;
typedef enum {
VG_HARDWARE_ACCELERATED = 0x2200,
VG_HARDWARE_UNACCELERATED = 0x2201
} VGHardwareQueryResult;
typedef enum {
VG_VENDOR = 0x2300,
VG_RENDERER = 0x2301,
VG_VERSION = 0x2302,
VG_EXTENSIONS = 0x2303
} VGStringID;
/* Function Prototypes */
#if 0 // We are including ShivaVG directly into libSimGearScene and only using
// inside the library so there is no need for any dll import/export stuff
#if defined(_WIN32) || defined(__VC32__)
# if defined(VG_API_EXPORT)
# define VG_API_CALL __declspec(dllexport)
# else
# define VG_API_CALL __declspec(dllimport)
# endif
#else
# define VG_API_CALL extern
#endif
#else
# define VG_API_CALL
#endif
#if defined (__cplusplus)
extern "C" {
#endif
VG_API_CALL VGErrorCode vgGetError(void);
VG_API_CALL void vgFlush(void);
VG_API_CALL void vgFinish(void);
/* Getters and Setters */
VG_API_CALL void vgSetf (VGParamType type, VGfloat value);
VG_API_CALL void vgSeti (VGParamType type, VGint value);
VG_API_CALL void vgSetfv(VGParamType type, VGint count,
const VGfloat * values);
VG_API_CALL void vgSetiv(VGParamType type, VGint count,
const VGint * values);
VG_API_CALL VGfloat vgGetf(VGParamType type);
VG_API_CALL VGint vgGeti(VGParamType type);
VG_API_CALL VGint vgGetVectorSize(VGParamType type);
VG_API_CALL void vgGetfv(VGParamType type, VGint count, VGfloat * values);
VG_API_CALL void vgGetiv(VGParamType type, VGint count, VGint * values);
VG_API_CALL void vgSetParameterf(VGHandle object,
VGint paramType,
VGfloat value);
VG_API_CALL void vgSetParameteri(VGHandle object,
VGint paramType,
VGint value);
VG_API_CALL void vgSetParameterfv(VGHandle object,
VGint paramType,
VGint count, const VGfloat * values);
VG_API_CALL void vgSetParameteriv(VGHandle object,
VGint paramType,
VGint count, const VGint * values);
VG_API_CALL VGfloat vgGetParameterf(VGHandle object,
VGint paramType);
VG_API_CALL VGint vgGetParameteri(VGHandle object,
VGint paramType);
VG_API_CALL VGint vgGetParameterVectorSize(VGHandle object,
VGint paramType);
VG_API_CALL void vgGetParameterfv(VGHandle object,
VGint paramType,
VGint count, VGfloat * values);
VG_API_CALL void vgGetParameteriv(VGHandle object,
VGint paramType,
VGint count, VGint * values);
/* Matrix Manipulation */
VG_API_CALL void vgLoadIdentity(void);
VG_API_CALL void vgLoadMatrix(const VGfloat * m);
VG_API_CALL void vgGetMatrix(VGfloat * m);
VG_API_CALL void vgMultMatrix(const VGfloat * m);
VG_API_CALL void vgTranslate(VGfloat tx, VGfloat ty);
VG_API_CALL void vgScale(VGfloat sx, VGfloat sy);
VG_API_CALL void vgShear(VGfloat shx, VGfloat shy);
VG_API_CALL void vgRotate(VGfloat angle);
/* Masking and Clearing */
VG_API_CALL void vgMask(VGImage mask, VGMaskOperation operation,
VGint x, VGint y, VGint width, VGint height);
VG_API_CALL void vgClear(VGint x, VGint y, VGint width, VGint height);
/* Paths */
VG_API_CALL VGPath vgCreatePath(VGint pathFormat,
VGPathDatatype datatype,
VGfloat scale, VGfloat bias,
VGint segmentCapacityHint,
VGint coordCapacityHint,
VGbitfield capabilities);
VG_API_CALL void vgClearPath(VGPath path, VGbitfield capabilities);
VG_API_CALL void vgDestroyPath(VGPath path);
VG_API_CALL void vgRemovePathCapabilities(VGPath path,
VGbitfield capabilities);
VG_API_CALL VGbitfield vgGetPathCapabilities(VGPath path);
VG_API_CALL void vgAppendPath(VGPath dstPath, VGPath srcPath);
VG_API_CALL void vgAppendPathData(VGPath dstPath,
VGint numSegments,
const VGubyte * pathSegments,
const void * pathData);
VG_API_CALL void vgModifyPathCoords(VGPath dstPath, VGint startIndex,
VGint numSegments,
const void * pathData);
VG_API_CALL void vgTransformPath(VGPath dstPath, VGPath srcPath);
VG_API_CALL VGboolean vgInterpolatePath(VGPath dstPath,
VGPath startPath,
VGPath endPath,
VGfloat amount);
VG_API_CALL VGfloat vgPathLength(VGPath path,
VGint startSegment, VGint numSegments);
VG_API_CALL void vgPointAlongPath(VGPath path,
VGint startSegment, VGint numSegments,
VGfloat distance,
VGfloat * x, VGfloat * y,
VGfloat * tangentX, VGfloat * tangentY);
VG_API_CALL void vgPathBounds(VGPath path,
VGfloat * minX, VGfloat * minY,
VGfloat * width, VGfloat * height);
VG_API_CALL void vgPathTransformedBounds(VGPath path,
VGfloat * minX, VGfloat * minY,
VGfloat * width, VGfloat * height);
VG_API_CALL void vgDrawPath(VGPath path, VGbitfield paintModes);
/* Paint */
VG_API_CALL VGPaint vgCreatePaint(void);
VG_API_CALL void vgDestroyPaint(VGPaint paint);
VG_API_CALL void vgSetPaint(VGPaint paint, VGbitfield paintModes);
VG_API_CALL VGPaint vgGetPaint(VGPaintMode paintMode);
VG_API_CALL void vgSetColor(VGPaint paint, VGuint rgba);
VG_API_CALL VGuint vgGetColor(VGPaint paint);
VG_API_CALL void vgPaintPattern(VGPaint paint, VGImage pattern);
/* Images */
VG_API_CALL VGImage vgCreateImage(VGImageFormat format,
VGint width, VGint height,
VGbitfield allowedQuality);
VG_API_CALL void vgDestroyImage(VGImage image);
VG_API_CALL void vgClearImage(VGImage image,
VGint x, VGint y, VGint width, VGint height);
VG_API_CALL void vgImageSubData(VGImage image,
const void * data, VGint dataStride,
VGImageFormat dataFormat,
VGint x, VGint y, VGint width, VGint height);
VG_API_CALL void vgGetImageSubData(VGImage image,
void * data, VGint dataStride,
VGImageFormat dataFormat,
VGint x, VGint y,
VGint width, VGint height);
VG_API_CALL VGImage vgChildImage(VGImage parent,
VGint x, VGint y, VGint width, VGint height);
VG_API_CALL VGImage vgGetParent(VGImage image);
VG_API_CALL void vgCopyImage(VGImage dst, VGint dx, VGint dy,
VGImage src, VGint sx, VGint sy,
VGint width, VGint height,
VGboolean dither);
VG_API_CALL void vgDrawImage(VGImage image);
VG_API_CALL void vgSetPixels(VGint dx, VGint dy,
VGImage src, VGint sx, VGint sy,
VGint width, VGint height);
VG_API_CALL void vgWritePixels(const void * data, VGint dataStride,
VGImageFormat dataFormat,
VGint dx, VGint dy,
VGint width, VGint height);
VG_API_CALL void vgGetPixels(VGImage dst, VGint dx, VGint dy,
VGint sx, VGint sy,
VGint width, VGint height);
VG_API_CALL void vgReadPixels(void * data, VGint dataStride,
VGImageFormat dataFormat,
VGint sx, VGint sy,
VGint width, VGint height);
VG_API_CALL void vgCopyPixels(VGint dx, VGint dy,
VGint sx, VGint sy,
VGint width, VGint height);
/* Image Filters */
VG_API_CALL void vgColorMatrix(VGImage dst, VGImage src,
const VGfloat * matrix);
VG_API_CALL void vgConvolve(VGImage dst, VGImage src,
VGint kernelWidth, VGint kernelHeight,
VGint shiftX, VGint shiftY,
const VGshort * kernel,
VGfloat scale,
VGfloat bias,
VGTilingMode tilingMode);
VG_API_CALL void vgSeparableConvolve(VGImage dst, VGImage src,
VGint kernelWidth,
VGint kernelHeight,
VGint shiftX, VGint shiftY,
const VGshort * kernelX,
const VGshort * kernelY,
VGfloat scale,
VGfloat bias,
VGTilingMode tilingMode);
VG_API_CALL void vgGaussianBlur(VGImage dst, VGImage src,
VGfloat stdDeviationX,
VGfloat stdDeviationY,
VGTilingMode tilingMode);
VG_API_CALL void vgLookup(VGImage dst, VGImage src,
const VGubyte * redLUT,
const VGubyte * greenLUT,
const VGubyte * blueLUT,
const VGubyte * alphaLUT,
VGboolean outputLinear,
VGboolean outputPremultiplied);
VG_API_CALL void vgLookupSingle(VGImage dst, VGImage src,
const VGuint * lookupTable,
VGImageChannel sourceChannel,
VGboolean outputLinear,
VGboolean outputPremultiplied);
/* Hardware Queries */
VG_API_CALL VGHardwareQueryResult vgHardwareQuery(VGHardwareQueryType key,
VGint setting);
/* Renderer and Extension Information */
VG_API_CALL const VGubyte * vgGetString(VGStringID name);
/* Extensions */
#define OVG_SH_blend_src_out 1
#define OVG_SH_blend_dst_out 1
#define OVG_SH_blend_src_atop 1
#define OVG_SH_blend_dst_atop 1
VG_API_CALL VGboolean vgCreateContextSH(VGint width, VGint height);
VG_API_CALL VGboolean vgHasContextSH();
VG_API_CALL void vgResizeSurfaceSH(VGint width, VGint height);
VG_API_CALL void vgDestroyContextSH(void);
/* Extensions for ShaderVG */
#define VG_FRAGMENT_SHADER_SH 0
#define VG_VERTEX_SHADER_SH 1
#define VG_IMAGE_UNIT_OFFSET_SH 2
typedef enum {
VG_IMAGE_UNIT_0_SH = VG_IMAGE_UNIT_OFFSET_SH,
VG_IMAGE_UNIT_1_SH,
VG_IMAGE_UNIT_2_SH,
VG_IMAGE_UNIT_3_SH,
VG_IMAGE_UNIT_4_SH
} VGImageUnitSH;
VG_API_CALL void vgShaderSourceSH(VGuint shadertype, const VGbyte* string);
VG_API_CALL void vgCompileShaderSH(void);
VG_API_CALL void vgUniform1fSH(VGint location, VGfloat v0);
VG_API_CALL void vgUniform2fSH(VGint location, VGfloat v0, VGfloat v1);
VG_API_CALL void vgUniform3fSH(VGint location, VGfloat v0, VGfloat v1, VGfloat v2);
VG_API_CALL void vgUniform4fSH(VGint location, VGfloat v0, VGfloat v1, VGfloat v2, VGfloat v3);
VG_API_CALL void vgUniform1fvSH(VGint location, VGint count, const VGfloat *value);
VG_API_CALL void vgUniform2fvSH(VGint location, VGint count, const VGfloat *value);
VG_API_CALL void vgUniform3fvSH(VGint location, VGint count, const VGfloat *value);
VG_API_CALL void vgUniform4fvSH(VGint location, VGint count, const VGfloat *value);
VG_API_CALL void vgUniform1iSH(VGint location, VGint v0);
VG_API_CALL void vgUniform2iSH(VGint location, VGint v0, VGint v1);
VG_API_CALL void vgUniform3iSH(VGint location, VGint v0, VGint v1, VGint v2);
VG_API_CALL void vgUniform4iSH(VGint location, VGint v0, VGint v1, VGint v2, VGint v3);
VG_API_CALL void vgUniform1ivSH(VGint location, VGint count, const VGint *value);
VG_API_CALL void vgUniform2ivSH(VGint location, VGint count, const VGint *value);
VG_API_CALL void vgUniform3ivSH(VGint location, VGint count, const VGint *value);
VG_API_CALL void vgUniform4ivSH(VGint location, VGint count, const VGint *value);
VG_API_CALL void vgUniformMatrix2fvSH (VGint location, VGint count, VGboolean transpose, const VGfloat *value);
VG_API_CALL void vgUniformMatrix3fvSH (VGint location, VGint count, VGboolean transpose, const VGfloat *value);
VG_API_CALL void vgUniformMatrix4fvSH (VGint location, VGint count, VGboolean transpose, const VGfloat *value);
VG_API_CALL void vgBindImageSH(VGImage image, VGImageUnitSH unit);
VG_API_CALL VGint vgGetUniformLocationSH(const VGbyte *name);
VG_API_CALL void vgGetUniformfvSH(VGint location, VGfloat *params);
#if defined (__cplusplus)
} /* extern "C" */
#endif
#endif /* _OPENVG_H */

View File

@@ -0,0 +1,104 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _VGU_H
#define _VGU_H
#include "openvg.h"
#define VGU_VERSION_1_0 1
#define VGU_VERSION_1_0_1 1
#ifndef VGU_API_CALL
#define VGU_API_CALL VG_API_CALL
#endif
typedef enum {
VGU_NO_ERROR = 0,
VGU_BAD_HANDLE_ERROR = 0xF000,
VGU_ILLEGAL_ARGUMENT_ERROR = 0xF001,
VGU_OUT_OF_MEMORY_ERROR = 0xF002,
VGU_PATH_CAPABILITY_ERROR = 0xF003,
VGU_BAD_WARP_ERROR = 0xF004
} VGUErrorCode;
typedef enum {
VGU_ARC_OPEN = 0xF100,
VGU_ARC_CHORD = 0xF101,
VGU_ARC_PIE = 0xF102
} VGUArcType;
#ifdef __cplusplus
extern "C" {
#endif
VGU_API_CALL VGUErrorCode vguLine(VGPath path,
VGfloat x0, VGfloat y0,
VGfloat x1, VGfloat y1);
VGU_API_CALL VGUErrorCode vguPolygon(VGPath path,
const VGfloat * points, VGint count,
VGboolean closed);
VGU_API_CALL VGUErrorCode vguRect(VGPath path,
VGfloat x, VGfloat y,
VGfloat width, VGfloat height);
VGU_API_CALL VGUErrorCode vguRoundRect(VGPath path,
VGfloat x, VGfloat y,
VGfloat width, VGfloat height,
VGfloat arcWidth, VGfloat arcHeight);
VGU_API_CALL VGUErrorCode vguEllipse(VGPath path,
VGfloat cx, VGfloat cy,
VGfloat width, VGfloat height);
VGU_API_CALL VGUErrorCode vguArc(VGPath path,
VGfloat x, VGfloat y,
VGfloat width, VGfloat height,
VGfloat startAngle, VGfloat angleExtent,
VGUArcType arcType);
VGU_API_CALL VGUErrorCode vguComputeWarpQuadToSquare(VGfloat sx0, VGfloat sy0,
VGfloat sx1, VGfloat sy1,
VGfloat sx2, VGfloat sy2,
VGfloat sx3, VGfloat sy3,
VGfloat * matrix);
VGU_API_CALL VGUErrorCode vguComputeWarpSquareToQuad(VGfloat dx0, VGfloat dy0,
VGfloat dx1, VGfloat dy1,
VGfloat dx2, VGfloat dy2,
VGfloat dx3, VGfloat dy3,
VGfloat * matrix);
VGU_API_CALL VGUErrorCode vguComputeWarpQuadToQuad(VGfloat dx0, VGfloat dy0,
VGfloat dx1, VGfloat dy1,
VGfloat dx2, VGfloat dy2,
VGfloat dx3, VGfloat dy3,
VGfloat sx0, VGfloat sy0,
VGfloat sx1, VGfloat sy1,
VGfloat sx2, VGfloat sy2,
VGfloat sx3, VGfloat sy3,
VGfloat * matrix);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* #ifndef _VGU_H */

View File

@@ -0,0 +1,23 @@
include(SimGearComponent)
set(HEADERS
../include/vg/openvg.h
../include/vg/vgu.h
)
set(SOURCES
shaders.c
shArrays.c
shContext.c
shExtensions.c
shGeometry.c
shImage.c
shPaint.c
shParams.c
shPath.c
shPipeline.c
shVectors.c
shVgu.c
)
simgear_scene_component(ShaderVG canvas/ShaderVG "${SOURCES}" "${HEADERS}")

View File

@@ -0,0 +1,370 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/*------------------------------------------------------------
* The base for any type of array. According to appropriate
* macro definitions, specific array types will be generated
* and their manipulation functions respectively.
*
* This code assumes the following are defined:
* _ITEM_T: the type of the items in the array
* _ARRAY_T: the name of the structure
* _FUNC_T: the prefix to prepend to each function
*
* And at least one of these:
* _ARRAY_DECLARE: generate structure declaration
* _ARRAY_DEFINE: generate function definitions
*-----------------------------------------------------------*/
#ifndef __SHARRAYBASE_H
#define __SHARRAYBASE_H
#include "shDefs.h"
#define VAL(x,y) x ## y
#define JN(x,y) VAL(x,y)
#endif
/*--------------------------------------------
* The rest is not #ifndef protected to allow
* for various array type definitions.
*--------------------------------------------*/
#ifdef _ARRAY_DECLARE
typedef struct
{
_ITEM_T *items;
SHint32 capacity;
SHint32 size;
SHint outofmemory;
} _ARRAY_T;
#endif
void JN(_ARRAY_T,_ctor) (_ARRAY_T *a)
#ifdef _ARRAY_DEFINE
{
a->items = (_ITEM_T*)malloc(sizeof(_ITEM_T));
if (!a->items) {
a->outofmemory = 1;
a->capacity = 0;
a->size = 0;
return;
}
a->outofmemory = 0;
a->capacity = 1;
a->size = 0;
}
#else
;
#endif
void JN(_ARRAY_T,_dtor) (_ARRAY_T *a)
#ifdef _ARRAY_DEFINE
{
if (a->items) {
free(a->items);
a->items = NULL;
}
}
#else
;
#endif
void JN(_FUNC_T,Clear) (_ARRAY_T *a)
#ifdef _ARRAY_DEFINE
{
a->size = 0;
}
#else
;
#endif
/*--------------------------------------------------------
* Set the capacity of the array. In case of reallocation
* the items are not preserved.
*--------------------------------------------------------*/
int JN(_FUNC_T,Realloc) (_ARRAY_T *a, SHint newsize)
#ifdef _ARRAY_DEFINE
{
_ITEM_T *newitems = 0;
SH_ASSERT(newsize > 0);
if (newsize == a->capacity)
return 1;
newitems = (_ITEM_T*)malloc(newsize * sizeof(_ITEM_T));
if (!newitems) {
a->outofmemory = 1;
return 0;
}
if (a->items)
free(a->items);
a->outofmemory = 0;
a->items = newitems;
a->capacity = newsize;
a->size = 0;
return 1;
}
#else
;
#endif
/*------------------------------------------------------
* Asserts the capacity is at least [newsize]. In case
* of reallocation items are not preserved.
*------------------------------------------------------*/
int JN(_FUNC_T,Reserve) (_ARRAY_T *a, SHint newsize)
#ifdef _ARRAY_DEFINE
{
_ITEM_T *newitems = 0;
SH_ASSERT(newsize >= 0);
if (newsize <= a->capacity)
return 1;
newitems = (_ITEM_T*)malloc(newsize * sizeof(_ITEM_T));
if (!newitems) {
a->outofmemory = 1;
return 0;
}
if (a->items)
free(a->items);
a->outofmemory = 0;
a->items = newitems;
a->capacity = newsize;
a->size = 0;
return 1;
}
#else
;
#endif
/*------------------------------------------------------
* Asserts the capacity is at least [newsize]. In case
* of reallocation items are copied.
*------------------------------------------------------*/
int JN(_FUNC_T,ReserveAndCopy) (_ARRAY_T *a, SHint newsize)
#ifdef _ARRAY_DEFINE
{
_ITEM_T *newitems = 0;
SH_ASSERT(newsize >= 0);
if (newsize <= a->capacity)
return 1;
newitems = (_ITEM_T*)realloc(a->items, newsize * sizeof(_ITEM_T));
if (!newitems) {
a->outofmemory = 1;
return 0;
}
a->outofmemory = 0;
a->items = newitems;
a->capacity = newsize;
return 1;
}
#else
;
#endif
int JN(_FUNC_T,PushBack) (_ARRAY_T *a, _ITEM_T item)
#ifdef _ARRAY_DEFINE
{
if (a->capacity == 0) {
JN(_FUNC_T,Realloc)(a, 1);
if (a->outofmemory)
return 0;
}
if (a->size + 1 > a->capacity)
JN(_FUNC_T,ReserveAndCopy)(a, a->capacity*2);
if (a->outofmemory)
return 0;
a->items[a->size++] = item;
return 1;
}
#else
;
#endif
int JN(_FUNC_T,PushBackP) (_ARRAY_T *a, _ITEM_T *item)
#ifdef _ARRAY_DEFINE
{
if (a->capacity == 0) {
JN(_FUNC_T,Realloc)(a, 1);
if (a->outofmemory)
return 0;
}
if (a->size + 1 > a->capacity)
JN(_FUNC_T,ReserveAndCopy)(a, a->capacity*2);
if (a->outofmemory)
return 0;
a->items[a->size++] = *item;
return 1;
}
#else
;
#endif
void JN(_FUNC_T,PopBack) (_ARRAY_T *a)
#ifdef _ARRAY_DEFINE
{
SH_ASSERT(a->size);
--a->size;
}
#else
;
#endif
_ITEM_T JN(_FUNC_T,Front) (_ARRAY_T *a)
#ifdef _ARRAY_DEFINE
{
SH_ASSERT(a->size);
return a->items[0];
}
#else
;
#endif
_ITEM_T* JN(_FUNC_T,FrontP) (_ARRAY_T *a)
#ifdef _ARRAY_DEFINE
{
SH_ASSERT(a->size);
return &a->items[0];
}
#else
;
#endif
_ITEM_T JN(_FUNC_T,Back) (_ARRAY_T *a)
#ifdef _ARRAY_DEFINE
{
SH_ASSERT(a->size);
return a->items[a->size - 1];
}
#else
;
#endif
_ITEM_T* JN(_FUNC_T,BackP) (_ARRAY_T *a)
#ifdef _ARRAY_DEFINE
{
SH_ASSERT(a->size);
return &a->items[a->size - 1];
}
#else
;
#endif
_ITEM_T JN(_FUNC_T,At) (_ARRAY_T *a, SHint index)
#ifdef _ARRAY_DEFINE
{
SH_ASSERT(index >= 0);
SH_ASSERT(index < a->size);
return a->items[index];
}
#else
;
#endif
_ITEM_T* JN(_FUNC_T,AtP) (_ARRAY_T *a, SHint index)
#ifdef _ARRAY_DEFINE
{
SH_ASSERT(index >= 0);
SH_ASSERT(index < a->size);
return &a->items[index];
}
#else
;
#endif
SHint JN(_FUNC_T,Find) (_ARRAY_T *a, _ITEM_T item)
#ifdef _ARRAY_DEFINE
{
int i;
for (i=0; i<a->size; ++i) {
#ifdef _COMPARE_T
if (_COMPARE_T(a->items[i], item))
return i;
#else
if (a->items[i] == item)
return i;
#endif
}
return -1;
}
#else
;
#endif
void JN(_FUNC_T,RemoveAt) (_ARRAY_T *a, SHint index)
#ifdef _ARRAY_DEFINE
{
int i;
SH_ASSERT(index >= 0);
SH_ASSERT(index < a->size);
for (i=index; i<a->size-1; ++i)
a->items[i] = a->items[i+1];
a->size--;
}
#else
;
#endif
#undef _ITEM_T
#undef _ARRAY_T
#undef _FUNC_T
#undef _COMPARE_T
#undef _ARRAY_DEFINE
#undef _ARRAY_DECLARE

View File

@@ -0,0 +1,50 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/*--------------------------------------------
* Definitions of all the arrays used
*--------------------------------------------*/
#include "shArrays.h"
#define _ITEM_T SHint
#define _ARRAY_T SHIntArray
#define _FUNC_T shIntArray
#define _ARRAY_DEFINE
#include "shArrayBase.h"
#define _ITEM_T SHuint8
#define _ARRAY_T SHUint8Array
#define _FUNC_T shUint8Array
#define _ARRAY_DEFINE
#include "shArrayBase.h"
#define _ITEM_T SHfloat
#define _ARRAY_T SHFloatArray
#define _FUNC_T shFloatArray
#define _ARRAY_DEFINE
#include "shArrayBase.h"
#define _ITEM_T SHRectangle
#define _ARRAY_T SHRectArray
#define _FUNC_T shRectArray
#define _COMPARE_T(x,y) 1
#define _ARRAY_DEFINE
#include "shArrayBase.h"

View File

@@ -0,0 +1,55 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/*--------------------------------------------
* Declarations of all the arrays used
*--------------------------------------------*/
#ifndef __SHARRAYS_H
#define __SHARRAYS_H
#include "shVectors.h"
#define _ITEM_T SHint
#define _ARRAY_T SHIntArray
#define _FUNC_T shIntArray
#define _ARRAY_DECLARE
#include "shArrayBase.h"
#define _ITEM_T SHuint8
#define _ARRAY_T SHUint8Array
#define _FUNC_T shUint8Array
#define _ARRAY_DECLARE
#include "shArrayBase.h"
#define _ITEM_T SHfloat
#define _ARRAY_T SHFloatArray
#define _FUNC_T shFloatArray
#define _ARRAY_DECLARE
#include "shArrayBase.h"
#define _ITEM_T SHRectangle
#define _ARRAY_T SHRectArray
#define _FUNC_T shRectArray
#define _ARRAY_DECLARE
#include "shArrayBase.h"
#endif

View File

@@ -0,0 +1,51 @@
#ifndef __SHCONFIG_H
#define __SHCONFIG_H
////////////////////////////////////////////////////////////
// Identify the operating system
////////////////////////////////////////////////////////////
#if defined(_WIN32) || defined(__WIN32__)
// Windows
#define VG_API_WINDOWS
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#elif defined(linux) || defined(__linux)
// Linux
#define VG_API_LINUX
#elif defined(__APPLE__) || defined(MACOSX) || defined(macintosh) || defined(Macintosh)
// MacOS
#define VG_API_MACOSX
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
// FreeBSD
#define VG_API_FREEBSD
#elif defined(__OpenBSD__)
// FreeBSD
#define VG_API_OPENBSD
#else
// Unsupported system
#error This operating system is not supported by SFML library
#endif
// We currently do not support using images (inside paths). If we were going to
// use it loading and unloading needs to happen within OpenSceneGraph to handle
// synchronization correctly in multithreading mode.
#define SH_NO_IMAGE
#endif // __SHCONFIG_H

View File

@@ -0,0 +1,504 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#define VG_API_EXPORT
#include "vg/openvg.h"
#include "shContext.h"
#include "shaders.h"
#include <string.h>
#include <stdio.h>
/*-----------------------------------------------------
* Simple functions to create a VG context instance
* on top of an existing OpenGL context.
* TODO: There is no mechanics yet to asure the OpenGL
* context exists and to choose which context / window
* to bind to.
*-----------------------------------------------------*/
static VGContext *g_context = NULL;
VG_API_CALL VGboolean vgCreateContextSH(VGint width, VGint height)
{
/* return if already created */
if (g_context) return VG_TRUE;
/* create new context */
SH_NEWOBJ(VGContext, g_context);
if (!g_context) return VG_FALSE;
/* init surface info */
g_context->surfaceWidth = width;
g_context->surfaceHeight = height;
/* setup GL projection */
/* We handle viewport and projection ourselves...
glViewport(0,0,width,height); */
/* Setup shader for rendering*/
g_context->userShaderVertex = NULL;
g_context->userShaderFragment = NULL;
shInitPiplelineShaders();
/* Setup shaders for making color ramp */
shInitRampShaders();
return VG_TRUE;
}
VG_API_CALL VGboolean vgHasContextSH()
{
return g_context != NULL;
}
VG_API_CALL void vgResizeSurfaceSH(VGint width, VGint height)
{
VG_GETCONTEXT(VG_NO_RETVAL);
/* update surface info */
context->surfaceWidth = width;
context->surfaceHeight = height;
/* setup GL projection */
/* We handle viewport and projection ourselves...
glViewport(0,0,width,height); */
/* Setup projection matrix */
//float mat[16];
//float volume = fmax(width, height) / 2;
//shCalcOrtho2D(mat, 0, width, 0, height, -volume, volume);
glUseProgram(context->progDraw);
//glUniformMatrix4fv(context->locationDraw.projection, 1, GL_FALSE, mat);
GL_CEHCK_ERROR;
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgDestroyContextSH()
{
/* return if already released */
if (!g_context) return;
/* delete context object */
SH_DELETEOBJ(VGContext, g_context);
g_context = NULL;
}
VGContext* shGetContext()
{
SH_ASSERT(g_context);
return g_context;
}
/*-----------------------------------------------------
* VGContext constructor
*-----------------------------------------------------*/
void shLoadExtensions(void *c);
void VGContext_ctor(VGContext *c)
{
/* Surface info */
c->surfaceWidth = 0;
c->surfaceHeight = 0;
/* GetString info */
strncpy(c->vendor, "Takuma Hayashi", sizeof(c->vendor));
strncpy(c->renderer, "ShaderVG", sizeof(c->renderer));
strncpy(c->version, "1.0.0", sizeof(c->version));
strncpy(c->extensions, "", sizeof(c->extensions));
/* Mode settings */
c->matrixMode = VG_MATRIX_PATH_USER_TO_SURFACE;
c->fillRule = VG_EVEN_ODD;
c->imageQuality = VG_IMAGE_QUALITY_FASTER;
c->renderingQuality = VG_RENDERING_QUALITY_BETTER;
c->blendMode = VG_BLEND_SRC_OVER;
c->imageMode = VG_DRAW_IMAGE_NORMAL;
/* Scissor rectangles */
SH_INITOBJ(SHRectArray, c->scissor);
c->scissoring = VG_FALSE;
c->masking = VG_FALSE;
/* Stroke parameters */
c->strokeLineWidth = 1.0f;
c->strokeCapStyle = VG_CAP_BUTT;
c->strokeJoinStyle = VG_JOIN_MITER;
c->strokeMiterLimit = 4.0f;
c->strokeDashPhase = 0.0f;
c->strokeDashPhaseReset = VG_FALSE;
SH_INITOBJ(SHFloatArray, c->strokeDashPattern);
/* Edge fill color for vgConvolve and pattern paint */
CSET(c->tileFillColor, 0,0,0,0);
/* Color for vgClear */
CSET(c->clearColor, 0,0,0,0);
/* Color components layout inside pixel */
c->pixelLayout = VG_PIXEL_LAYOUT_UNKNOWN;
/* Source format for image filters */
c->filterFormatLinear = VG_FALSE;
c->filterFormatPremultiplied = VG_FALSE;
c->filterChannelMask = VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA;
/* Matrices */
SH_INITOBJ(SHMatrix3x3, c->pathTransform);
SH_INITOBJ(SHMatrix3x3, c->imageTransform);
SH_INITOBJ(SHMatrix3x3, c->fillTransform);
SH_INITOBJ(SHMatrix3x3, c->strokeTransform);
/* Paints */
c->fillPaint = NULL;
c->strokePaint = NULL;
SH_INITOBJ(SHPaint, c->defaultPaint);
/* Error */
c->error = VG_NO_ERROR;
/* Resources */
SH_INITOBJ(SHPathArray, c->paths);
SH_INITOBJ(SHPaintArray, c->paints);
SH_INITOBJ(SHImageArray, c->images);
shLoadExtensions(c);
}
/*-----------------------------------------------------
* VGContext constructor
*-----------------------------------------------------*/
void VGContext_dtor(VGContext *c)
{
int i;
SH_DEINITOBJ(SHRectArray, c->scissor);
SH_DEINITOBJ(SHFloatArray, c->strokeDashPattern);
/* Destroy resources */
for (i=0; i<c->paths.size; ++i)
SH_DELETEOBJ(SHPath, c->paths.items[i]);
for (i=0; i<c->paints.size; ++i)
SH_DELETEOBJ(SHPaint, c->paints.items[i]);
for (i=0; i<c->images.size; ++i)
SH_DELETEOBJ(SHImage, c->images.items[i]);
}
/*--------------------------------------------------
* Tries to find resources in this context
*--------------------------------------------------*/
SHint shIsValidPath(VGContext *c, VGHandle h)
{
int index = shPathArrayFind(&c->paths, (SHPath*)h);
return (index == -1) ? 0 : 1;
}
SHint shIsValidPaint(VGContext *c, VGHandle h)
{
int index = shPaintArrayFind(&c->paints, (SHPaint*)h);
return (index == -1) ? 0 : 1;
}
SHint shIsValidImage(VGContext *c, VGHandle h)
{
int index = shImageArrayFind(&c->images, (SHImage*)h);
return (index == -1) ? 0 : 1;
}
/*--------------------------------------------------
* Tries to find a resources in this context and
* return its type or invalid flag.
*--------------------------------------------------*/
SHResourceType shGetResourceType(VGContext *c, VGHandle h)
{
if (shIsValidPath(c, h))
return SH_RESOURCE_PATH;
else if (shIsValidPaint(c, h))
return SH_RESOURCE_PAINT;
else if (shIsValidImage(c, h))
return SH_RESOURCE_IMAGE;
else
return SH_RESOURCE_INVALID;
}
/*-----------------------------------------------------
* Sets the specified error on the given context if
* there is no pending error yet
*-----------------------------------------------------*/
void shSetError(VGContext *c, VGErrorCode e)
{
if (c->error == VG_NO_ERROR)
c->error = e;
}
/*--------------------------------------------------
* Returns the oldest error pending on the current
* context and clears its error code
*--------------------------------------------------*/
VG_API_CALL VGErrorCode vgGetError(void)
{
VGErrorCode error;
VG_GETCONTEXT(VG_NO_CONTEXT_ERROR);
error = context->error;
context->error = VG_NO_ERROR;
VG_RETURN(error);
}
VG_API_CALL void vgFlush(void)
{
VG_GETCONTEXT(VG_NO_RETVAL);
glFlush();
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgFinish(void)
{
VG_GETCONTEXT(VG_NO_RETVAL);
glFinish();
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgMask(VGImage mask, VGMaskOperation operation,
VGint x, VGint y, VGint width, VGint height)
{
}
VG_API_CALL void vgClear(VGint x, VGint y, VGint width, VGint height)
{
VG_GETCONTEXT(VG_NO_RETVAL);
/* Clip to window */
if (x < 0) x = 0;
if (y < 0) y = 0;
if (width > context->surfaceWidth) width = context->surfaceWidth;
if (height > context->surfaceHeight) height = context->surfaceHeight;
/* Check if scissoring needed */
if (x > 0 || y > 0 ||
width < context->surfaceWidth ||
height < context->surfaceHeight) {
glScissor(x, y, width, height);
glEnable(GL_SCISSOR_TEST);
}
/* Clear GL color buffer */
/* TODO: what about stencil and depth? when do we clear that?
we would need some kind of special "begin" function at
beginning of each drawing or clear the planes prior to each
drawing where it takes places */
glClearColor(context->clearColor.r,
context->clearColor.g,
context->clearColor.b,
context->clearColor.a);
glClear(GL_COLOR_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT);
glDisable(GL_SCISSOR_TEST);
VG_RETURN(VG_NO_RETVAL);
}
/*-----------------------------------------------------------
* Returns the matrix currently selected via VG_MATRIX_MODE
*-----------------------------------------------------------*/
SHMatrix3x3* shCurrentMatrix(VGContext *c)
{
switch(c->matrixMode) {
case VG_MATRIX_PATH_USER_TO_SURFACE:
return &c->pathTransform;
case VG_MATRIX_IMAGE_USER_TO_SURFACE:
return &c->imageTransform;
case VG_MATRIX_FILL_PAINT_TO_USER:
return &c->fillTransform;
default:
return &c->strokeTransform;
}
}
/*--------------------------------------
* Sets the current matrix to identity
*--------------------------------------*/
VG_API_CALL void vgLoadIdentity(void)
{
SHMatrix3x3 *m;
VG_GETCONTEXT(VG_NO_RETVAL);
m = shCurrentMatrix(context);
IDMAT((*m));
VG_RETURN(VG_NO_RETVAL);
}
/*-------------------------------------------------------------
* Loads values into the current matrix from the given array.
* Matrix affinity is preserved if an affine matrix is loaded.
*-------------------------------------------------------------*/
VG_API_CALL void vgLoadMatrix(const VGfloat * mm)
{
SHMatrix3x3 *m;
VG_GETCONTEXT(VG_NO_RETVAL);
VG_RETURN_ERR_IF(!mm, VG_ILLEGAL_ARGUMENT_ERROR, VG_NO_RETVAL);
/* TODO: check matrix array alignment */
m = shCurrentMatrix(context);
if (context->matrixMode == VG_MATRIX_IMAGE_USER_TO_SURFACE) {
SETMAT((*m),
mm[0], mm[3], mm[6],
mm[1], mm[4], mm[7],
mm[2], mm[5], mm[8]);
}else{
SETMAT((*m),
mm[0], mm[3], mm[6],
mm[1], mm[4], mm[7],
0.0f, 0.0f, 1.0f);
}
VG_RETURN(VG_NO_RETVAL);
}
/*---------------------------------------------------------------
* Outputs the values of the current matrix into the given array
*---------------------------------------------------------------*/
VG_API_CALL void vgGetMatrix(VGfloat * mm)
{
SHMatrix3x3 *m; int i,j,k=0;
VG_GETCONTEXT(VG_NO_RETVAL);
VG_RETURN_ERR_IF(!mm, VG_ILLEGAL_ARGUMENT_ERROR, VG_NO_RETVAL);
/* TODO: check matrix array alignment */
m = shCurrentMatrix(context);
for (i=0; i<3; ++i)
for (j=0; j<3; ++j)
mm[k++] = m->m[j][i];
VG_RETURN(VG_NO_RETVAL);
}
/*-------------------------------------------------------------
* Right-multiplies the current matrix with the one specified
* in the given array. Matrix affinity is preserved if an
* affine matrix is begin multiplied.
*-------------------------------------------------------------*/
VG_API_CALL void vgMultMatrix(const VGfloat * mm)
{
SHMatrix3x3 *m, mul, temp;
VG_GETCONTEXT(VG_NO_RETVAL);
VG_RETURN_ERR_IF(!mm, VG_ILLEGAL_ARGUMENT_ERROR, VG_NO_RETVAL);
/* TODO: check matrix array alignment */
m = shCurrentMatrix(context);
if (context->matrixMode == VG_MATRIX_IMAGE_USER_TO_SURFACE) {
SETMAT(mul,
mm[0], mm[3], mm[6],
mm[1], mm[4], mm[7],
mm[2], mm[5], mm[8]);
}else{
SETMAT(mul,
mm[0], mm[3], mm[6],
mm[1], mm[4], mm[7],
0.0f, 0.0f, 1.0f);
}
MULMATMAT((*m), mul, temp);
SETMATMAT((*m), temp);
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgTranslate(VGfloat tx, VGfloat ty)
{
SHMatrix3x3 *m;
VG_GETCONTEXT(VG_NO_RETVAL);
m = shCurrentMatrix(context);
TRANSLATEMATR((*m), tx, ty);
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgScale(VGfloat sx, VGfloat sy)
{
SHMatrix3x3 *m;
VG_GETCONTEXT(VG_NO_RETVAL);
m = shCurrentMatrix(context);
SCALEMATR((*m), sx, sy);
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgShear(VGfloat shx, VGfloat shy)
{
SHMatrix3x3 *m;
VG_GETCONTEXT(VG_NO_RETVAL);
m = shCurrentMatrix(context);
SHEARMATR((*m), shx, shy);
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgRotate(VGfloat angle)
{
SHfloat a;
SHMatrix3x3 *m;
VG_GETCONTEXT(VG_NO_RETVAL);
a = SH_DEG2RAD(angle);
m = shCurrentMatrix(context);
ROTATEMATR((*m), a);
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL VGHardwareQueryResult vgHardwareQuery(VGHardwareQueryType key,
VGint setting)
{
return VG_HARDWARE_UNACCELERATED;
}

View File

@@ -0,0 +1,196 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __SHCONTEXT_H
#define __SHCONTEXT_H
#include "shDefs.h"
#include "shVectors.h"
#include "shArrays.h"
#include "shPath.h"
#include "shPaint.h"
#include "shImage.h"
/*------------------------------------------------
* VGContext object
*------------------------------------------------*/
typedef enum
{
SH_RESOURCE_INVALID = 0,
SH_RESOURCE_PATH = 1,
SH_RESOURCE_PAINT = 2,
SH_RESOURCE_IMAGE = 3
} SHResourceType;
typedef struct
{
/* Surface info (since no EGL yet) */
SHint surfaceWidth;
SHint surfaceHeight;
/* GetString info */
char vendor[256];
char renderer[256];
char version[256];
char extensions[256];
/* Mode settings */
VGMatrixMode matrixMode;
VGFillRule fillRule;
VGImageQuality imageQuality;
VGRenderingQuality renderingQuality;
VGBlendMode blendMode;
VGImageMode imageMode;
/* Scissor rectangles */
SHRectArray scissor;
VGboolean scissoring;
VGboolean masking;
/* Stroke parameters */
SHfloat strokeLineWidth;
VGCapStyle strokeCapStyle;
VGJoinStyle strokeJoinStyle;
SHfloat strokeMiterLimit;
SHFloatArray strokeDashPattern;
SHfloat strokeDashPhase;
VGboolean strokeDashPhaseReset;
/* Edge fill color for vgConvolve and pattern paint */
SHColor tileFillColor;
/* Color for vgClear */
SHColor clearColor;
/* Color components layout inside pixel */
VGPixelLayout pixelLayout;
/* Source format for image filters */
VGboolean filterFormatLinear;
VGboolean filterFormatPremultiplied;
VGbitfield filterChannelMask;
/* Matrices */
SHMatrix3x3 pathTransform;
SHMatrix3x3 imageTransform;
SHMatrix3x3 fillTransform;
SHMatrix3x3 strokeTransform;
/* Paints */
SHPaint* fillPaint;
SHPaint* strokePaint;
SHPaint defaultPaint;
VGErrorCode error;
/* Resources */
SHPathArray paths;
SHPaintArray paints;
SHImageArray images;
/* Pointers to extensions */
/* GL locations */
struct {
GLint pos ;
GLint textureUV ;
GLint model ;
GLint projection ;
GLint paintInverted ;
GLint drawMode ;
GLint imageSampler ;
GLint imageMode ;
GLint paintType ;
GLint rampSampler ;
GLint patternSampler ;
GLint userSampler ;
GLint paintParams ;
GLint paintColor ;
GLint scaleFactorBias;
} locationDraw;
struct {
GLuint step;
GLuint stepColor;
} locationColorRamp;
/* GL programs */
GLuint progDraw;
GLuint progColorRamp;
/* GL shaders */
const void* userShaderVertex;
const void* userShaderFragment;
GLint vs;
GLint fs;
} VGContext;
void VGContext_ctor(VGContext *c);
void VGContext_dtor(VGContext *c);
void shSetError(VGContext *c, VGErrorCode e);
SHint shIsValidPath(VGContext *c, VGHandle h);
SHint shIsValidPaint(VGContext *c, VGHandle h);
SHint shIsValidImage(VGContext *c, VGHandle h);
SHResourceType shGetResourceType(VGContext *c, VGHandle h);
VGContext* shGetContext();
/*----------------------------------------------------
* TODO: Add mutex locking/unlocking to these macros
* to assure sequentiallity in multithreading.
*----------------------------------------------------*/
#define VG_NO_RETVAL
#define VG_GETCONTEXT(RETVAL) \
VGContext *context = shGetContext(); \
if (!context) return RETVAL;
#define VG_RETURN(RETVAL) \
{ return RETVAL; }
#define VG_RETURN_ERR(ERRORCODE, RETVAL) \
{ shSetError(context,ERRORCODE); return RETVAL; }
#define VG_RETURN_ERR_IF(COND, ERRORCODE, RETVAL) \
{ if (COND) {shSetError(context,ERRORCODE); return RETVAL;} }
/*-----------------------------------------------------------
* Same macros but no mutex handling - used by sub-functions
*-----------------------------------------------------------*/
#define SH_NO_RETVAL
#define SH_GETCONTEXT(RETVAL) \
VGContext *context = shGetContext(); \
if (!context) return RETVAL;
#define SH_RETURN(RETVAL) \
{ return RETVAL; }
#define SH_RETURN_ERR(ERRORCODE, RETVAL) \
{ shSetError(context,ERRORCODE); return RETVAL; }
#define SH_RETURN_ERR_IF(COND, ERRORCODE, RETVAL) \
{ if (COND) {shSetError(context,ERRORCODE); return RETVAL;} }
#endif /* __SHCONTEXT_H */

View File

@@ -0,0 +1,190 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __SHDEFS_H
#define __SHDEFS_H
// FlightGear change : include shConfig.h here, since the logic below requires it.
// wondering if this file is supposed to be auto-included, since there is no explicit
// include of it anywhere in Shader/Shiva sources.
#include "shConfig.h"
// end of FlightGear change
/* Standard headers */
#ifdef VG_API_WINDOWS
# include <windows.h>
#endif
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <float.h>
#if !defined(VG_API_MACOSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
# include <malloc.h>
#endif
/* Disable VGHandle-pointer conversion warnings since we
do deal with it by defining VGHandle properly */
#if defined(_MSC_VER)
# pragma warning(disable:4311)
# pragma warning(disable:4312)
#endif
/* Type definitions */
#if HAVE_INTTYPES_H
#include <inttypes.h>
#else
#define int8_t char
#define uint8_t unsigned char
#define int16_t short
#define uint16_t unsigned short
#define int32_t int
#define uint32_t unsigned int
#define int64_t long long
#define uint64_t unsigned long long
#endif
typedef int8_t SHint8;
typedef uint8_t SHuint8;
typedef int16_t SHint16;
typedef uint16_t SHuint16;
typedef int32_t SHint32;
typedef uint32_t SHuint32;
typedef float SHfloat32;
#define SHint SHint32
#define SHuint SHuint32
#define SHfloat SHfloat32
/* Maximum / minimum values */
#define SH_MAX_INT (0x7fffffff)
#define SH_MIN_INT (-0x7fffffff-1)
#define SH_MANTISSA_BITS 23
#define SH_EXPONENT_BITS 8
/* all 1s in exponent yields NaN in IEEE 754 so we take
1 less then maximum representable with exponent bits */
#define SH_MAX_EXPONENT ((1 << SH_EXPONENT_BITS) - 2)
/* maximum representable with mantissa bits */
#define SH_MAX_MANTISSA ((1 << SH_MANTISSA_BITS) - 1)
/* compose into IEEE754 floating point bit value */
#define SH_MAX_FLOAT_BITS (SH_MAX_EXPONENT << SH_MANTISSA_BITS) | SH_MAX_MANTISSA
typedef union {
float f;
unsigned int i;
} SHfloatint;
SHfloat getMaxFloat();
/* Portable function definitions */
#define SH_SQRT (float)sqrt
#define SH_COS (float)cos
#define SH_SIN (float)sin
#define SH_ACOS (float)acos
#define SH_ASIN (float)asin
#define SH_ATAN (float)atan
#define SH_FLOOR (float)floor
#define SH_CEIL (float)ceil
#define SH_ASSERT assert
#if defined(__isnan) || (defined(__APPLE__) && (__GNUC__ == 3))
# define SH_ISNAN __isnan
#elif defined(_isnan) || defined(WIN32)
# define SH_ISNAN _isnan
#else
# define SH_ISNAN isnan
#endif
/* Helper macros */
#define PI 3.141592654f
#define SH_DEG2RAD(a) (a * PI / 180.0f)
#define SH_RAD2DEG(a) (a * 180.0f / PI)
#define SH_ABS(a) ((a < 0.0f) ? -a : a)
#define SH_MAX(a,b) ((a > b) ? a : b)
#define SH_MIN(a,b) ((a < b) ? a : b)
#define SH_NEARZERO(a) (a >= -0.0001 && a < 0.0001)
#define SH_SWAP(a,b) {SHfloat t=a; a=b; b=t;}
#define SH_CLAMP(a,min,max) {if (a<min) a=min; if (a>max) a=max; }
#define SH_NEWOBJ(type,obj) { obj = (type*)malloc(sizeof(type)); if(obj) type ## _ctor(obj); }
#define SH_INITOBJ(type,obj){ type ## _ctor(&obj); }
#define SH_DEINITOBJ(type,obj) { type ## _dtor(&obj); }
#define SH_DELETEOBJ(type,obj) { if(obj) type ## _dtor(obj); free(obj); }
/* Implementation limits */
#define SH_MAX_SCISSOR_RECTS 1
#define SH_MAX_DASH_COUNT VG_MAXINT
#define SH_MAX_IMAGE_WIDTH VG_MAXINT
#define SH_MAX_IMAGE_HEIGHT VG_MAXINT
#define SH_MAX_IMAGE_PIXELS VG_MAXINT
#define SH_MAX_IMAGE_BYTES VG_MAXINT
#define SH_MAX_COLOR_RAMP_STOPS 256
#define SH_MAX_VERTICES 999999999
#define SH_MAX_RECURSE_DEPTH 16
#define SH_GRADIENT_TEX_WIDTH 1024
#define SH_GRADIENT_TEX_HEIGHT 1
#define SH_GRADIENT_TEX_COORDSIZE 4096 /* 1024 * RGBA */
/* OpenGL headers */
#if defined(VG_API_MACOSX)
# include <OpenGL/gl.h>
#elif defined(VG_API_WINDOWS)
# define GL_GLEXT_PROTOTYPES
# include <GL/glcorearb.h>
#else
# define GL_GLEXT_PROTOTYPES
# include <GL/glcorearb.h>
#endif
#include "shExtensions.h"
#define GL_GET_ERROR printf("glGetError() -> %d line:%d file:%s\r\n", glGetError(), __LINE__, __FILE__)
#define GL_CEHCK_ERROR \
{ \
GLint err = glGetError(); \
if(err){\
printf("glGetError() -> %d \r\n", err);\
assert(0);\
}\
}
// GL_TEXTURE0 :imageSampler
// GL_TEXTURE1 :rampSampler or patternSampler
// GL_TEXTURE2 :User defined
#define SH_TEXTURE_USER_TOP GL_TEXTURE2
#endif /* __SHDEFS_H */

View File

@@ -0,0 +1,136 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#define VG_API_EXPORT
#include "shExtensions.h"
#include <stdio.h>
#include <string.h>
#include <GL/glcorearb.h>
/*-----------------------------------------------------
* OpenGL core profile
*-----------------------------------------------------*/
#if defined(_WIN32)
PFNGLUNIFORM1IPROC glUniform1i;
PFNGLUNIFORM2FVPROC glUniform2fv;
PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv;
PFNGLUNIFORM2FPROC glUniform2f;
PFNGLUNIFORM4FVPROC glUniform4fv;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray;
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer;
PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray;
PFNGLUSEPROGRAMPROC glUseProgram;
PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv;
PFNGLCREATESHADERPROC glCreateShader;
PFNGLSHADERSOURCEPROC glShaderSource;
PFNGLCOMPILESHADERPROC glCompileShader;
PFNGLGETSHADERIVPROC glGetShaderiv;
PFNGLATTACHSHADERPROC glAttachShader;
PFNGLLINKPROGRAMPROC glLinkProgram;
PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation;
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
PFNGLDELETESHADERPROC glDeleteShader;
PFNGLDELETEPROGRAMPROC glDeleteProgram;
PFNGLUNIFORM1FPROC glUniform1f;
PFNGLUNIFORM3FPROC glUniform3f;
PFNGLUNIFORM4FPROC glUniform4f;
PFNGLUNIFORM1FVPROC glUniform1fv;
PFNGLUNIFORM3FVPROC glUniform3fv;
PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv;
PFNGLGETUNIFORMFVPROC glGetUniformfv;
PFNGLCREATEPROGRAMPROC glCreateProgram;
PFNGLACTIVETEXTUREPROC glActiveTexture;
#endif
/*-----------------------------------------------------
* Extensions check
*-----------------------------------------------------*/
static int checkExtension(const char *extensions, const char *name)
{
int nlen = (int)strlen(name);
int elen = (int)strlen(extensions);
const char *e = extensions;
if(nlen <= 0) return 0;
while (1) {
/* Try to find sub-string */
e = strstr(e, name);
if (e == NULL) return 0;
/* Check if last */
if (e == extensions + elen - nlen)
return 1;
/* Check if space follows (avoid same names with a suffix) */
if (*(e + nlen) == ' ')
return 1;
e += nlen;
}
return 0;
}
typedef void (*PFVOID)();
PFVOID shGetProcAddress(const char *name)
{
#if defined(_WIN32)
return (PFVOID)wglGetProcAddress(name);
#else
return (PFVOID)NULL;
#endif
}
void shLoadExtensions(void *c)
{
if(shGetProcAddress == NULL) return;
#if defined(_WIN32)
glUniform1i = shGetProcAddress("glUniform1i");
glUniform2fv = shGetProcAddress("glUniform2fv");
glUniformMatrix3fv = shGetProcAddress("glUniformMatrix3fv");
glUniform2f = shGetProcAddress("glUniform2f");
glUniform4fv = shGetProcAddress("glUniform4fv");
glEnableVertexAttribArray = shGetProcAddress("glEnableVertexAttribArray");
glVertexAttribPointer = shGetProcAddress("glVertexAttribPointer");
glDisableVertexAttribArray = shGetProcAddress("glDisableVertexAttribArray");
glUseProgram = shGetProcAddress("glUseProgram");
glUniformMatrix4fv = shGetProcAddress("glUniformMatrix4fv");
glCreateShader = shGetProcAddress("glCreateShader");
glShaderSource = shGetProcAddress("glShaderSource");
glCompileShader = shGetProcAddress("glCompileShader");
glGetShaderiv = shGetProcAddress("glGetShaderiv");
glAttachShader = shGetProcAddress("glAttachShader");
glLinkProgram = shGetProcAddress("glLinkProgram");
glGetAttribLocation = shGetProcAddress("glGetAttribLocation");
glGetUniformLocation = shGetProcAddress("glGetUniformLocation");
glDeleteShader = shGetProcAddress("glDeleteShader");
glDeleteProgram = shGetProcAddress("glDeleteProgram");
glUniform1f = shGetProcAddress("glUniform1f");
glUniform3f = shGetProcAddress("glUniform3f");
glUniform4f = shGetProcAddress("glUniform4f");
glUniform1fv = shGetProcAddress("glUniform1fv");
glUniform3fv = shGetProcAddress("glUniform3fv");
glUniformMatrix2fv = shGetProcAddress("glUniformMatrix2fv");
glGetUniformfv = shGetProcAddress("glGetUniformfv");
glCreateProgram = shGetProcAddress("glCreateProgram");
glActiveTexture = shGetProcAddress("glActiveTexture");
#endif
}

View File

@@ -0,0 +1,25 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __SHEXTENSIONS_H
#define __SHEXTENSIONS_H
#endif

View File

@@ -0,0 +1,937 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#define VG_API_EXPORT
#include "vg/openvg.h"
#include "shContext.h"
#include "shGeometry.h"
static int shAddVertex(SHPath *p, SHVertex *v, SHint *contourStart)
{
/* Assert contour was open */
SH_ASSERT((*contourStart) >= 0);
/* Check vertex limit */
if (p->vertices.size >= SH_MAX_VERTICES) return 0;
/* Add vertex to subdivision */
shVertexArrayPushBackP(&p->vertices, v);
/* Increment contour size. Its stored in
the flags of first contour vertex */
p->vertices.items[*contourStart].flags++;
return 1;
}
static void shSubrecurseQuad(SHPath *p, SHQuad *quad, SHint *contourStart)
{
SHVertex v;
SHVector2 mid, dif, c1, c2, c3;
SHQuad quads[SH_MAX_RECURSE_DEPTH];
SHQuad *q, *qleft, *qright;
SHint qindex=0;
quads[0] = *quad;
while (qindex >= 0) {
q = &quads[qindex];
/* Calculate distance of control point from its
counterpart on the line between end points */
SET2V(mid, q->p1); ADD2V(mid, q->p3); DIV2(mid, 2);
SET2V(dif, q->p2); SUB2V(dif, mid); ABS2(dif);
/* Cancel if the curve is flat enough */
if (dif.x + dif.y <= 1.0f || qindex == SH_MAX_RECURSE_DEPTH-1) {
/* Add subdivision point */
v.point = q->p3; v.flags = 0;
if (qindex == 0) return; /* Skip last point */
if (!shAddVertex(p, &v, contourStart)) return;
--qindex;
}else{
/* Left recursion goes on top of stack! */
qright = q; qleft = &quads[++qindex];
/* Subdivide into 2 sub-curves */
SET2V(c1, q->p1); ADD2V(c1, q->p2); DIV2(c1, 2);
SET2V(c3, q->p2); ADD2V(c3, q->p3); DIV2(c3, 2);
SET2V(c2, c1); ADD2V(c2, c3); DIV2(c2, 2);
/* Add left recursion onto stack */
qleft->p1 = q->p1;
qleft->p2 = c1;
qleft->p3 = c2;
/* Add right recursion onto stack */
qright->p1 = c2;
qright->p2 = c3;
qright->p3 = q->p3;
}
}
}
static void shSubrecurseCubic(SHPath *p, SHCubic *cubic, SHint *contourStart)
{
SHVertex v;
SHfloat dx1, dy1, dx2, dy2;
SHVector2 mm, c1, c2, c3, c4, c5;
SHCubic cubics[SH_MAX_RECURSE_DEPTH];
SHCubic *c, *cleft, *cright;
SHint cindex = 0;
cubics[0] = *cubic;
while (cindex >= 0) {
c = &cubics[cindex];
/* Calculate distance of control points from their
counterparts on the line between end points */
dx1 = 3.0f*c->p2.x - 2.0f*c->p1.x - c->p4.x; dx1 *= dx1;
dy1 = 3.0f*c->p2.y - 2.0f*c->p1.y - c->p4.y; dy1 *= dy1;
dx2 = 3.0f*c->p3.x - 2.0f*c->p4.x - c->p1.x; dx2 *= dx2;
dy2 = 3.0f*c->p3.y - 2.0f*c->p4.y - c->p1.y; dy2 *= dy2;
if (dx1 < dx2) dx1 = dx2;
if (dy1 < dy2) dy1 = dy2;
/* Cancel if the curve is flat enough */
if (dx1+dy1 <= 1.0 || cindex == SH_MAX_RECURSE_DEPTH-1) {
/* Add subdivision point */
v.point = c->p4; v.flags = 0;
if (cindex == 0) return; /* Skip last point */
if (!shAddVertex(p, &v, contourStart)) return;
--cindex;
}else{
/* Left recursion goes on top of stack! */
cright = c; cleft = &cubics[++cindex];
/* Subdivide into 2 sub-curves */
SET2V(c1, c->p1); ADD2V(c1, c->p2); DIV2(c1, 2);
SET2V(mm, c->p2); ADD2V(mm, c->p3); DIV2(mm, 2);
SET2V(c5, c->p3); ADD2V(c5, c->p4); DIV2(c5, 2);
SET2V(c2, c1); ADD2V(c2, mm); DIV2(c2, 2);
SET2V(c4, mm); ADD2V(c4, c5); DIV2(c4, 2);
SET2V(c3, c2); ADD2V(c3, c4); DIV2(c3, 2);
/* Add left recursion to stack */
cleft->p1 = c->p1;
cleft->p2 = c1;
cleft->p3 = c2;
cleft->p4 = c3;
/* Add right recursion to stack */
cright->p1 = c3;
cright->p2 = c4;
cright->p3 = c5;
cright->p4 = c->p4;
}
}
}
static void shSubrecurseArc(SHPath *p, SHArc *arc,
SHVector2 *c,SHVector2 *ux, SHVector2 *uy,
SHint *contourStart)
{
SHVertex v;
SHfloat am, cosa, sina, dx, dy;
SHVector2 uux, uuy, c1, m;
SHArc arcs[SH_MAX_RECURSE_DEPTH];
SHArc *a, *aleft, *aright;
SHint aindex=0;
arcs[0] = *arc;
while (aindex >= 0) {
a = &arcs[aindex];
/* Middle angle and its cos/sin */
am = (a->a1 + a->a2)/2;
cosa = SH_COS(am);
sina = SH_SIN(am);
/* New point */
SET2V(uux, (*ux)); MUL2(uux, cosa);
SET2V(uuy, (*uy)); MUL2(uuy, sina);
SET2V(c1, (*c)); ADD2V(c1, uux); ADD2V(c1, uuy);
/* Check distance from linear midpoint */
SET2V(m, a->p1); ADD2V(m, a->p2); DIV2(m, 2);
dx = c1.x - m.x; dy = c1.y - m.y;
if (dx < 0.0f) dx = -dx;
if (dy < 0.0f) dy = -dy;
/* Stop if flat enough */
if (dx+dy <= 1.0f || aindex == SH_MAX_RECURSE_DEPTH-1) {
/* Add middle subdivision point */
v.point = c1; v.flags = 0;
if (!shAddVertex(p, &v, contourStart)) return;
if (aindex == 0) return; /* Skip very last point */
/* Add end subdivision point */
v.point = a->p2; v.flags = 0;
if (!shAddVertex(p, &v, contourStart)) return;
--aindex;
}else{
/* Left subdivision goes on top of stack! */
aright = a; aleft = &arcs[++aindex];
/* Add left recursion to stack */
aleft->p1 = a->p1;
aleft->a1 = a->a1;
aleft->p2 = c1;
aleft->a2 = am;
/* Add right recursion to stack */
aright->p1 = c1;
aright->a1 = am;
aright->p2 = a->p2;
aright->a2 = a->a2;
}
}
}
static void shSubdivideSegment(SHPath *p, VGPathSegment segment,
VGPathCommand originalCommand,
SHfloat *data, void *userData)
{
SHVertex v;
SHint *contourStart = ((SHint**)userData)[0];
SHint *surfaceSpace = ((SHint**)userData)[1];
SHQuad quad; SHCubic cubic; SHArc arc;
SHVector2 c, ux, uy;
VG_GETCONTEXT(VG_NO_RETVAL);
switch (segment)
{
case VG_MOVE_TO:
/* Set contour start here */
(*contourStart) = p->vertices.size;
/* First contour vertex */
v.point.x = data[2];
v.point.y = data[3];
v.flags = 0;
if (*surfaceSpace)
TRANSFORM2(v.point, context->pathTransform);
break;
case VG_CLOSE_PATH:
/* Last contour vertex */
v.point.x = data[2];
v.point.y = data[3];
v.flags = SH_VERTEX_FLAG_SEGEND | SH_VERTEX_FLAG_CLOSE;
if (*surfaceSpace)
TRANSFORM2(v.point, context->pathTransform);
break;
case VG_LINE_TO:
/* Last segment vertex */
v.point.x = data[2];
v.point.y = data[3];
v.flags = SH_VERTEX_FLAG_SEGEND;
if (*surfaceSpace)
TRANSFORM2(v.point, context->pathTransform);
break;
case VG_QUAD_TO:
/* Recurse subdivision */
SET2(quad.p1, data[0], data[1]);
SET2(quad.p2, data[2], data[3]);
SET2(quad.p3, data[4], data[5]);
if (*surfaceSpace) {
TRANSFORM2(quad.p1, context->pathTransform);
TRANSFORM2(quad.p2, context->pathTransform);
TRANSFORM2(quad.p3, context->pathTransform); }
shSubrecurseQuad(p, &quad, contourStart);
/* Last segment vertex */
v.point.x = data[4];
v.point.y = data[5];
v.flags = SH_VERTEX_FLAG_SEGEND;
if (*surfaceSpace)
TRANSFORM2(v.point, context->pathTransform);
break;
case VG_CUBIC_TO:
/* Recurse subdivision */
SET2(cubic.p1, data[0], data[1]);
SET2(cubic.p2, data[2], data[3]);
SET2(cubic.p3, data[4], data[5]);
SET2(cubic.p4, data[6], data[7]);
if (*surfaceSpace) {
TRANSFORM2(cubic.p1, context->pathTransform);
TRANSFORM2(cubic.p2, context->pathTransform);
TRANSFORM2(cubic.p3, context->pathTransform);
TRANSFORM2(cubic.p4, context->pathTransform); }
shSubrecurseCubic(p, &cubic, contourStart);
/* Last segment vertex */
v.point.x = data[6];
v.point.y = data[7];
v.flags = SH_VERTEX_FLAG_SEGEND;
if (*surfaceSpace)
TRANSFORM2(v.point, context->pathTransform);
break;
default:
SH_ASSERT(segment==VG_SCWARC_TO || segment==VG_SCCWARC_TO ||
segment==VG_LCWARC_TO || segment==VG_LCCWARC_TO);
/* Recurse subdivision */
SET2(arc.p1, data[0], data[1]);
SET2(arc.p2, data[10], data[11]);
arc.a1 = data[8]; arc.a2 = data[9];
SET2(c, data[2], data[3]);
SET2(ux, data[4], data[5]);
SET2(uy, data[6], data[7]);
if (*surfaceSpace) {
TRANSFORM2(arc.p1, context->pathTransform);
TRANSFORM2(arc.p2, context->pathTransform);
TRANSFORM2(c, context->pathTransform);
TRANSFORM2DIR(ux, context->pathTransform);
TRANSFORM2DIR(uy, context->pathTransform); }
shSubrecurseArc(p, &arc, &c, &ux, &uy, contourStart);
/* Last segment vertex */
v.point.x = data[10];
v.point.y = data[11];
v.flags = SH_VERTEX_FLAG_SEGEND;
if (*surfaceSpace) {
TRANSFORM2(v.point, context->pathTransform); }
break;
}
/* Add subdivision vertex */
shAddVertex(p, &v, contourStart);
}
/*--------------------------------------------------
* Processes path data by simplfying it and sending
* each segment to subdivision callback function
*--------------------------------------------------*/
void shFlattenPath(SHPath *p, SHint surfaceSpace)
{
SHint contourStart = -1;
//SHint surfSpace = surfaceSpace;
SHint *userData[2];
SHint processFlags =
SH_PROCESS_SIMPLIFY_LINES |
SH_PROCESS_SIMPLIFY_CURVES |
SH_PROCESS_CENTRALIZE_ARCS |
SH_PROCESS_REPAIR_ENDS;
userData[0] = &contourStart;
userData[1] = &surfaceSpace;
shVertexArrayClear(&p->vertices);
shProcessPathData(p, processFlags, shSubdivideSegment, userData);
}
/*-------------------------------------------
* Adds a rectangle to the path's stroke.
*-------------------------------------------*/
static void shPushStrokeQuad(SHPath *p, SHVector2 *p1, SHVector2 *p2,
SHVector2 *p3, SHVector2 *p4)
{
shVector2ArrayPushBackP(&p->stroke, p1);
shVector2ArrayPushBackP(&p->stroke, p2);
shVector2ArrayPushBackP(&p->stroke, p3);
shVector2ArrayPushBackP(&p->stroke, p3);
shVector2ArrayPushBackP(&p->stroke, p4);
shVector2ArrayPushBackP(&p->stroke, p1);
}
/*-------------------------------------------
* Adds a triangle to the path's stroke.
*-------------------------------------------*/
static void shPushStrokeTri(SHPath *p, SHVector2 *p1,
SHVector2 *p2, SHVector2 *p3)
{
shVector2ArrayPushBackP(&p->stroke, p1);
shVector2ArrayPushBackP(&p->stroke, p2);
shVector2ArrayPushBackP(&p->stroke, p3);
}
/*-----------------------------------------------------------
* Adds a miter join to the path's stroke at the given
* turn point [c], with the end of the previous segment
* outset [o1] and the beginning of the next segment
* outset [o2], transiting from tangent [d1] to [d2].
*-----------------------------------------------------------*/
static void shStrokeJoinMiter(SHPath *p, SHVector2 *c,
SHVector2 *o1, SHVector2 *d1,
SHVector2 *o2, SHVector2 *d2)
{
/* Init miter top to first point in case lines are colinear */
SHVector2 x; SET2V(x,(*o1));
/* Find intersection of two outer turn edges
(lines defined by origin and direction) */
shLineLineXsection(o1, d1, o2, d2, &x);
/* Add a "diamond" quad with top on intersected point
and bottom on center of turn (on the line) */
shPushStrokeQuad(p, &x, o1, c, o2);
}
/*-----------------------------------------------------------
* Adds a round join to the path's stroke at the given
* turn point [c], with the end of the previous segment
* outset [pstart] and the beginning of the next segment
* outset [pend], transiting from perpendicular vector
* [tstart] to [tend].
*-----------------------------------------------------------*/
static void shStrokeJoinRound(SHPath *p, SHVector2 *c,
SHVector2 *pstart, SHVector2 *tstart,
SHVector2 *pend, SHVector2 *tend)
{
SHVector2 p1, p2;
SHfloat a, ang, cosa, sina;
/* Find angle between lines */
ang = ANGLE2((*tstart),(*tend));
/* Begin with start point */
SET2V(p1,(*pstart));
for (a=0.0f; a<ang; a+=PI/12) {
/* Rotate perpendicular vector around and
find next offset point from center */
cosa = SH_COS(-a);
sina = SH_SIN(-a);
SET2(p2, tstart->x*cosa - tstart->y*sina,
tstart->x*sina + tstart->y*cosa);
ADD2V(p2, (*c));
/* Add triangle, save previous */
shPushStrokeTri(p, &p1, &p2, c);
SET2V(p1, p2);
}
/* Add last triangle */
shPushStrokeTri(p, &p1, pend, c);
}
static void shStrokeCapRound(SHPath *p, SHVector2 *c, SHVector2 *t, SHint start)
{
SHint a;
SHfloat ang, cosa, sina;
SHVector2 p1, p2;
SHint steps = 12;
SHVector2 tt;
/* Revert perpendicular vector if start cap */
SET2V(tt, (*t));
if (start) MUL2(tt, -1);
/* Find start point */
SET2V(p1, (*c));
ADD2V(p1, tt);
for (a = 1; a<=steps; ++a) {
/* Rotate perpendicular vector around and
find next offset point from center */
ang = (SHfloat)a * PI / steps;
cosa = SH_COS(-ang);
sina = SH_SIN(-ang);
SET2(p2, tt.x*cosa - tt.y*sina,
tt.x*sina + tt.y*cosa);
ADD2V(p2, (*c));
/* Add triangle, save previous */
shPushStrokeTri(p, &p1, &p2, c);
SET2V(p1, p2);
}
}
static void shStrokeCapSquare(SHPath *p, SHVector2 *c, SHVector2 *t, SHint start)
{
SHVector2 tt, p1, p2, p3, p4;
/* Revert perpendicular vector if start cap */
SET2V(tt, (*t));
if (start) MUL2(tt, -1);
/* Find four corners of the quad */
SET2V(p1, (*c));
ADD2V(p1, tt);
SET2V(p2, p1);
ADD2(p2, tt.y, -tt.x);
SET2V(p3, p2);
ADD2(p3, -2*tt.x, -2*tt.y);
SET2V(p4, p3);
ADD2(p4, -tt.y, tt.x);
shPushStrokeQuad(p, &p1, &p2, &p3, &p4);
}
/*-----------------------------------------------------------
* Generates stroke of a path according to VGContext state.
* Produces quads for every linear subdivision segment or
* dash "on" segment, handles line caps and joins.
*-----------------------------------------------------------*/
void shStrokePath(VGContext* c, SHPath *p)
{
/* Line width and vertex count */
SHfloat w = c->strokeLineWidth / 2;
SHfloat mlimit = c->strokeMiterLimit;
SHint vertsize = p->vertices.size;
/* Contour state */
SHint contourStart = 0;
SHint contourLength = 0;
SHint start = 0;
SHint end = 0;
SHint loop = 0;
SHint close = 0;
SHint segend = 0;
/* Current vertices */
SHint i1=0, i2=0;
SHVertex *v1, *v2;
SHVector2 *p1, *p2;
SHVector2 d, t, dprev, tprev;
SHfloat norm, cross, mlength;
/* Stroke edge points */
SHVector2 l1, r1, l2, r2, lprev, rprev;
/* Dash state */
SHint dashIndex = 0;
SHfloat dashLength = 0.0f, strokeLength = 0.0f;
SHint dashSize = c->strokeDashPattern.size;
SHfloat *dashPattern = c->strokeDashPattern.items;
SHint dashOn = 1;
/* Dash edge points */
SHVector2 dash1, dash2;
SHVector2 dashL1, dashR1;
SHVector2 dashL2, dashR2;
SHfloat nextDashLength, dashOffset;
/* Discard odd dash segment */
dashSize -= dashSize % 2;
/* Init previous so compiler doesn't warn
for uninitialized usage */
SET2(tprev, 0,0); SET2(dprev, 0,0);
SET2(lprev, 0,0); SET2(rprev, 0,0);
/* Walk over subdivision vertices */
for (i1=0; i1<vertsize; ++i1) {
if (loop) {
/* Start new contour if exists */
if (contourStart < vertsize)
i1 = contourStart;
else break;
}
start = end = loop = close = segend = 0;
i2 = i1 + 1;
if (i1 == contourStart) {
/* Contour has started. Get length */
contourLength = p->vertices.items[i1].flags;
start = 1;
}
if (contourLength <= 1) {
/* Discard empty contours. */
contourStart = i1 + 1;
loop = 1;
continue;
}
v1 = &p->vertices.items[i1];
v2 = &p->vertices.items[i2];
if (i2 == contourStart + contourLength-1) {
/* Contour has ended. Check close */
close = v2->flags & SH_VERTEX_FLAG_CLOSE;
end = 1;
}
if (i1 == contourStart + contourLength-1) {
/* Loop back to first edge. Check close */
close = v1->flags & SH_VERTEX_FLAG_CLOSE;
i2 = contourStart+1;
contourStart = i1 + 1;
i1 = i2 - 1;
loop = 1;
}
if (!start && !loop) {
/* We are inside a contour. Check segment end. */
segend = (v1->flags & SH_VERTEX_FLAG_SEGEND);
}
if (dashSize > 0 && start &&
(contourStart == 0 || c->strokeDashPhaseReset)) {
/* Reset pattern phase at contour start */
dashLength = -c->strokeDashPhase;
strokeLength = 0.0f;
dashIndex = 0;
dashOn = 1;
if (dashLength < 0.0f) {
/* Consume dash segments forward to reach stroke start */
while (dashLength + dashPattern[dashIndex] <= 0.0f) {
dashLength += dashPattern[dashIndex];
dashIndex = (dashIndex + 1) % dashSize;
dashOn = !dashOn; }
}else if (dashLength > 0.0f) {
/* Consume dash segments backward to return to stroke start */
dashIndex = dashSize;
while (dashLength > 0.0f) {
dashIndex = dashIndex ? (dashIndex-1) : (dashSize-1);
dashLength -= dashPattern[dashIndex];
dashOn = !dashOn; }
}
}
/* Subdiv segment vertices and points */
v1 = &p->vertices.items[i1];
v2 = &p->vertices.items[i2];
p1 = &v1->point;
p2 = &v2->point;
/* Direction vector */
SET2(d, p2->x-p1->x, p2->y-p1->y);
norm = NORM2(d);
if (norm == 0.0f) d = dprev;
else DIV2(d, norm);
/* Perpendicular vector */
SET2(t, -d.y, d.x);
MUL2(t, w);
cross = CROSS2(t,tprev);
/* Left and right edge points */
SET2V(l1, (*p1)); ADD2V(l1, t);
SET2V(r1, (*p1)); SUB2V(r1, t);
SET2V(l2, (*p2)); ADD2V(l2, t);
SET2V(r2, (*p2)); SUB2V(r2, t);
/* Check if join needed */
if ((segend || (loop && close)) && dashOn) {
switch (c->strokeJoinStyle) {
case VG_JOIN_ROUND:
/* Add a round join to stroke */
if (cross >= 0.0f)
shStrokeJoinRound(p, p1, &lprev, &tprev, &l1, &t);
else{
SHVector2 _t, _tprev;
SET2(_t, -t.x, -t.y);
SET2(_tprev, -tprev.x, -tprev.y);
shStrokeJoinRound(p, p1, &r1, &_t, &rprev, &_tprev);
}
break;
case VG_JOIN_MITER:
/* Add a miter join to stroke */
mlength = 1/SH_COS((ANGLE2(t, tprev))/2);
if (mlength <= mlimit) {
if (cross > 0.0f)
shStrokeJoinMiter(p, p1, &lprev, &dprev, &l1, &d);
else if (cross < 0.0f)
shStrokeJoinMiter(p, p1, &rprev, &dprev, &r1, &d);
break;
}/* Else fall down to bevel */
case VG_JOIN_BEVEL:
/* Add a bevel join to stroke */
if (cross > 0.0f)
shPushStrokeTri(p, &l1, &lprev, p1);
else if (cross < 0.0f)
shPushStrokeTri(p, &r1, &rprev, p1);
break;
}
}else if (!start && !loop && dashOn) {
/* Fill gap with previous (= bevel join) */
if (cross > 0.0f)
shPushStrokeTri(p, &l1, &lprev, p1);
else if (cross < 0.0f)
shPushStrokeTri(p, &r1, &rprev, p1);
}
/* Apply cap to start of a non-closed contour or
if we are dashing and dash segment is on */
if ((dashSize == 0 && loop && !close) ||
(dashSize > 0 && start && dashOn)) {
switch (c->strokeCapStyle) {
case VG_CAP_ROUND:
shStrokeCapRound(p, p1, &t, 1); break;
case VG_CAP_SQUARE:
shStrokeCapSquare(p, p1, &t, 1); break;
default: break;
}
}
if (loop)
continue;
/* Handle dashing */
if (dashSize > 0) {
/* Start with beginning of subdiv segment */
SET2V(dash1, (*p1)); SET2V(dashL1, l1); SET2V(dashR1, r1);
do {
/* Interpolate point on the current subdiv segment */
nextDashLength = dashLength + dashPattern[dashIndex];
dashOffset = (nextDashLength - strokeLength) / norm;
if (dashOffset > 1.0f) dashOffset = 1;
SET2V(dash2, (*p2)); SUB2V(dash2, (*p1));
MUL2(dash2, dashOffset); ADD2V(dash2, (*p1));
/* Left and right edge points */
SET2V(dashL2, dash2); ADD2V(dashL2, t);
SET2V(dashR2, dash2); SUB2V(dashR2, t);
/* Add quad for this dash segment */
if (dashOn) shPushStrokeQuad(p, &dashL2, &dashL1, &dashR1, &dashR2);
/* Move to next dash segment if inside this subdiv segment */
if (nextDashLength <= strokeLength + norm) {
dashIndex = (dashIndex + 1) % dashSize;
dashLength = nextDashLength;
dashOn = !dashOn;
SET2V(dash1, dash2);
SET2V(dashL1, dashL2);
SET2V(dashR1, dashR2);
/* Apply cap to dash segment */
switch (c->strokeCapStyle) {
case VG_CAP_ROUND:
shStrokeCapRound(p, &dash1, &t, dashOn); break;
case VG_CAP_SQUARE:
shStrokeCapSquare(p, &dash1, &t, dashOn); break;
default: break;
}
}
/* Consume dash segments until subdiv end met */
} while (nextDashLength < strokeLength + norm);
}else{
/* Add quad for this line segment */
shPushStrokeQuad(p, &l2, &l1, &r1, &r2);
}
/* Apply cap to end of a non-closed contour or
if we are dashing and dash segment is on */
if ((dashSize == 0 && end && !close) ||
(dashSize > 0 && end && dashOn)) {
switch (c->strokeCapStyle) {
case VG_CAP_ROUND:
shStrokeCapRound(p, p2, &t, 0); break;
case VG_CAP_SQUARE:
shStrokeCapSquare(p, p2, &t, 0); break;
default: break;
}
}
/* Save previous edge */
strokeLength += norm;
SET2V(lprev, l2);
SET2V(rprev, r2);
dprev = d;
tprev = t;
}
}
/*-------------------------------------------------------------
* Transforms the tessellation vertices using the given matrix
*-------------------------------------------------------------*/
void shTransformVertices(SHMatrix3x3 *m, SHPath *p)
{
SHVector2 *v;
int i = 0;
for (i = p->vertices.size-1; i>=0; --i) {
v = (&p->vertices.items[i].point);
TRANSFORM2((*v), (*m)); }
}
/*--------------------------------------------------------
* Finds the tight bounding box of path's tesselation
* vertices. Depends on whether the path had been
* tesselated in user or surface space.
*--------------------------------------------------------*/
void shFindBoundbox(SHPath *p)
{
int i;
if (p->vertices.size == 0) {
SET2(p->min, 0,0);
SET2(p->max, 0,0);
return;
}
p->min.x = p->max.x = p->vertices.items[0].point.x;
p->min.y = p->max.y = p->vertices.items[0].point.y;
for (i=0; i<p->vertices.size; ++i) {
SHVector2 *v = &p->vertices.items[i].point;
if (v->x < p->min.x) p->min.x = v->x;
if (v->x > p->max.x) p->max.x = v->x;
if (v->y < p->min.y) p->min.y = v->y;
if (v->y > p->max.y) p->max.y = v->y;
}
}
/*--------------------------------------------------------
* Outputs a tight bounding box of a path in path's own
* coordinate system.
*--------------------------------------------------------*/
VG_API_CALL void vgPathBounds(VGPath path,
VGfloat * minX, VGfloat * minY,
VGfloat * width, VGfloat * height)
{
SHPath *p = NULL;
VG_GETCONTEXT(VG_NO_RETVAL);
VG_RETURN_ERR_IF(!shIsValidPath(context, path),
VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);
VG_RETURN_ERR_IF(minX == NULL || minY == NULL ||
width == NULL || height == NULL,
VG_ILLEGAL_ARGUMENT_ERROR, VG_NO_RETVAL);
/* TODO: check output pointer alignment */
p = (SHPath*)path;
VG_RETURN_ERR_IF(!(p->caps & VG_PATH_CAPABILITY_PATH_BOUNDS),
VG_PATH_CAPABILITY_ERROR, VG_NO_RETVAL);
/* Update path geometry */
shFlattenPath(p, 0);
shFindBoundbox(p);
/* Output bounds */
*minX = p->min.x;
*minY = p->min.y;
*width = p->max.x - p->min.x;
*height = p->max.y - p->min.y;
VG_RETURN(VG_NO_RETVAL);
}
/*------------------------------------------------------------
* Outputs a bounding box of a path defined by its control
* points that is guaranteed to enclose the path geometry
* after applying the current path-user-to-surface transform
*------------------------------------------------------------*/
VG_API_CALL void vgPathTransformedBounds(VGPath path,
VGfloat * minX, VGfloat * minY,
VGfloat * width, VGfloat * height)
{
SHPath *p = NULL;
VG_GETCONTEXT(VG_NO_RETVAL);
VG_RETURN_ERR_IF(!shIsValidPath(context, path),
VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);
VG_RETURN_ERR_IF(minX == NULL || minY == NULL ||
width == NULL || height == NULL,
VG_ILLEGAL_ARGUMENT_ERROR, VG_NO_RETVAL);
/* TODO: check output pointer alignment */
p = (SHPath*)path;
VG_RETURN_ERR_IF(!(p->caps & VG_PATH_CAPABILITY_PATH_BOUNDS),
VG_PATH_CAPABILITY_ERROR, VG_NO_RETVAL);
/* Update path geometry */
shFlattenPath(p, 1);
shFindBoundbox(p);
/* Output bounds */
*minX = p->min.x;
*minY = p->min.y;
*width = p->max.x - p->min.x;
*height = p->max.y - p->min.y;
/* Invalidate subdivision for rendering */
p->cacheDataValid = VG_FALSE;
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL VGfloat vgPathLength(VGPath path,
VGint startSegment, VGint numSegments)
{
return 0.0f;
}
VG_API_CALL void vgPointAlongPath(VGPath path,
VGint startSegment, VGint numSegments,
VGfloat distance,
VGfloat * x, VGfloat * y,
VGfloat * tangentX, VGfloat * tangentY)
{
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __SH_GEOMETRY_H
#include "shDefs.h"
#include "shContext.h"
#include "shVectors.h"
#include "shPath.h"
void shFlattenPath(SHPath *p, SHint surfaceSpace);
void shStrokePath(VGContext* c, SHPath *p);
void shTransformVertices(SHMatrix3x3 *m, SHPath *p);
void shFindBoundbox(SHPath *p);
#endif /* __SH_GEOMETRY_H */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,154 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __SHIMAGE_H
#define __SHIMAGE_H
#include "shDefs.h"
/*-----------------------------------------------------------
* ColorFormat holds the data necessary to pack/unpack color
* components from a pixel of each supported image format
*-----------------------------------------------------------*/
typedef struct
{
VGImageFormat vgformat;
SHuint8 bytes;
SHuint32 rmask;
SHuint8 rshift;
SHuint8 rmax;
SHuint32 gmask;
SHuint8 gshift;
SHuint8 gmax;
SHuint32 bmask;
SHuint8 bshift;
SHuint8 bmax;
SHuint32 amask;
SHuint8 ashift;
SHuint8 amax;
GLenum glintformat;
GLenum glformat;
GLenum gltype;
} SHImageFormatDesc;
typedef struct
{
SHfloat r,g,b,a;
} SHColor;
void SHColor_ctor(SHColor *c);
void SHColor_dtor(SHColor *c);
#define _ITEM_T SHColor
#define _ARRAY_T SHColorArray
#define _FUNC_T shColorArray
#define _ARRAY_DECLARE
#include "shArrayBase.h"
typedef struct
{
SHuint8 *data;
SHint width;
SHint height;
SHImageFormatDesc fd;
SHint texwidth;
SHint texheight;
SHfloat texwidthK;
SHfloat texheightK;
GLuint texture;
} SHImage;
void SHImage_ctor(SHImage *i);
void SHImage_dtor(SHImage *i);
#define _ITEM_T SHImage*
#define _ARRAY_T SHImageArray
#define _FUNC_T shImageArray
#define _ARRAY_DECLARE
#include "shArrayBase.h"
/*-------------------------------------------------------
* Color operators
*-------------------------------------------------------*/
#define CSET(c, rr,gg,bb,aa) { c.r=rr; c.g=gg; c.b=bb; c.a=aa; }
#define CSETC(c1, c2) { c1.r=c2.r; c1.g=c2.g; c1.b=c2.b; c1.a=c2.a; }
#define CSUB(c1, rr,gg,bb,aa) { c.r-=rr; c.g-=gg; c.b-=bb; c.a-=aa; }
#define CSUBC(c1, c2) { c1.r-=c2.r; c1.g-=c2.g; c1.b-=c2.b; c1.a-=c2.a; }
#define CSUBCTO(c1, c2, c3) { c3.r=c1.r-c2.r; c3.g=c1.g-c2.g; c3.b=c1.b-c2.b; c3.a=c1.a-c2.a; }
#define CADD(c1, rr,gg,bb,aa) { c.r+=rr; c.g+=gg; c.b+=bb; c.a+=aa; }
#define CADDC(c1, c2) { c1.r+=c2.r; c1.g+=c2.g; c1.b+=c2.b; c1.a+=c2.a; }
#define CADDTO(c1, c2, c3) { c3.r=c1.r+c2.r; c3.g=c1.g+c2.g; c3.b=c1.b+c2.b; c3.a=c1.a+c2.a; }
#define CADDCK(c1, c2, k) { c1.r+=k*c2.r; c1.g+=k*c2.g; c1.b+=k*c2.b; c1.a+=k*c2.a; }
#define CMUL(c, s) { c.r*=s; c.g*=s; c.b*=s; c.a*=s; }
#define CDIV(c, s) { c.r/=s; c.g/=s; c.b/=s; c.a/=s; }
#define CPREMUL(c) { c.r*=c.a; c.g*=c.a; c.b*=c.a; }
#define CUNPREMUL(c) { c.r/=c.a; c.g/=c.a; c.b/=c.a; }
/*-------------------------------------------------------
* Color-to-memory functions
*-------------------------------------------------------*/
#define CSTORE_RGBA1D_8(c, rgba, x) { \
rgba[x*4+0] = (SHuint8)SH_FLOOR(c.r * 255); \
rgba[x*4+1] = (SHuint8)SH_FLOOR(c.g * 255); \
rgba[x*4+2] = (SHuint8)SH_FLOOR(c.b * 255); \
rgba[x*4+3] = (SHuint8)SH_FLOOR(c.a * 255); }
#define CSTORE_RGBA1D_F(c, rgba, x) { \
rgba[x*4+0] = c.r; \
rgba[x*4+1] = c.g; \
rgba[x*4+2] = c.b; \
rgba[x*4+3] = c.a; }
#define CSTORE_RGBA2D_8(c, rgba, x, y, width) { \
rgba[y*width*4+x*4+0] = (SHuint8)SH_FLOOR(c.r * 255); \
rgba[y*width*4+x*4+1] = (SHuint8)SH_FLOOR(c.g * 255); \
rgba[y*width*4+x*4+2] = (SHuint8)SH_FLOOR(c.b * 255); \
rgba[y*width*4+x*4+3] = (SHuint8)SH_FLOOR(c.a * 255); }
#define CSTORE_RGBA2D_F(c, rgba, x, y, width) { \
rgba[y*width*4+x*4+0] = c.r; \
rgba[y*width*4+x*4+1] = c.g; \
rgba[y*width*4+x*4+2] = c.b; \
rgba[y*width*4+x*4+3] = c.a; }
#define INT2COLCOORD(i, max) ( (SHfloat)i / (SHfloat)max )
#define COL2INTCOORD(c, max) ( (SHuint)SH_FLOOR(c * (SHfloat)max + 0.5f) )
void shStoreColor(SHColor *c, void *data, SHImageFormatDesc *f);
void shLoadColor(SHColor *c, const void *data, SHImageFormatDesc *f);
#endif /* __SHIMAGE_H */

View File

@@ -0,0 +1,501 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#define VG_API_EXPORT
#include "vg/openvg.h"
#include "shContext.h"
#include "shPaint.h"
#include <stdio.h>
#define _ITEM_T SHStop
#define _ARRAY_T SHStopArray
#define _FUNC_T shStopArray
#define _COMPARE_T(s1,s2) 0
#define _ARRAY_DEFINE
#include "shArrayBase.h"
#define _ITEM_T SHPaint*
#define _ARRAY_T SHPaintArray
#define _FUNC_T shPaintArray
#define _ARRAY_DEFINE
#include "shArrayBase.h"
void SHPaint_ctor(SHPaint *p)
{
int i;
p->type = VG_PAINT_TYPE_COLOR;
CSET(p->color, 0,0,0,1);
SH_INITOBJ(SHStopArray, p->instops);
SH_INITOBJ(SHStopArray, p->stops);
p->premultiplied = VG_FALSE;
p->spreadMode = VG_COLOR_RAMP_SPREAD_PAD;
p->tilingMode = VG_TILE_FILL;
for (i=0; i<4; ++i) p->linearGradient[i] = 0.0f;
for (i=0; i<5; ++i) p->radialGradient[i] = 0.0f;
p->pattern = VG_INVALID_HANDLE;
glGenTextures(1, &p->texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, p->texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, SH_GRADIENT_TEX_WIDTH, SH_GRADIENT_TEX_HEIGHT, 0,
GL_RGBA, GL_FLOAT, NULL);
GL_CEHCK_ERROR;
}
void SHPaint_dtor(SHPaint *p)
{
SH_DEINITOBJ(SHStopArray, p->instops);
SH_DEINITOBJ(SHStopArray, p->stops);
if (glIsTexture(p->texture))
glDeleteTextures(1, &p->texture);
}
VG_API_CALL VGPaint vgCreatePaint(void)
{
SHPaint *p = NULL;
VG_GETCONTEXT(VG_INVALID_HANDLE);
/* Create new paint object */
SH_NEWOBJ(SHPaint, p);
VG_RETURN_ERR_IF(!p, VG_OUT_OF_MEMORY_ERROR,
VG_INVALID_HANDLE);
/* Add to resource list */
shPaintArrayPushBack(&context->paints, p);
VG_RETURN((VGPaint)p);
}
VG_API_CALL void vgDestroyPaint(VGPaint paint)
{
SHint index;
VG_GETCONTEXT(VG_NO_RETVAL);
/* Check if handle valid */
index = shPaintArrayFind(&context->paints, (SHPaint*)paint);
VG_RETURN_ERR_IF(index == -1, VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);
/* Delete object and remove resource */
SH_DELETEOBJ(SHPaint, (SHPaint*)paint);
shPaintArrayRemoveAt(&context->paints, index);
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgSetPaint(VGPaint paint, VGbitfield paintModes)
{
VG_GETCONTEXT(VG_NO_RETVAL);
/* Check if handle valid */
VG_RETURN_ERR_IF(!shIsValidPaint(context, paint) &&
paint != VG_INVALID_HANDLE,
VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);
/* Check for invalid mode */
VG_RETURN_ERR_IF(paintModes & ~(VG_STROKE_PATH | VG_FILL_PATH),
VG_ILLEGAL_ARGUMENT_ERROR, VG_NO_RETVAL);
/* Set stroke / fill */
if (paintModes & VG_STROKE_PATH)
context->strokePaint = (SHPaint*)paint;
if (paintModes & VG_FILL_PATH)
context->fillPaint = (SHPaint*)paint;
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgPaintPattern(VGPaint paint, VGImage pattern)
{
VG_GETCONTEXT(VG_NO_RETVAL);
/* Check if handle valid */
VG_RETURN_ERR_IF(!shIsValidPaint(context, paint),
VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);
/* Check if pattern image valid */
VG_RETURN_ERR_IF(!shIsValidImage(context, pattern),
VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);
/* TODO: Check if pattern image is current rendering target */
/* Set pattern image */
((SHPaint*)paint)->pattern = pattern;
VG_RETURN(VG_NO_RETVAL);
}
void shUpdateColorRampTexture(SHPaint *p)
{
SHint s=0;
SHStop *stop1, *stop2;
SHfloat rgba[SH_GRADIENT_TEX_COORDSIZE];
SHint x1=0, x2=0, dx, x;
SHColor dc, c;
SHfloat k;
/* Write first pixel color */
stop1 = &p->stops.items[0];
CSTORE_RGBA1D_F(stop1->color, rgba, x1);
/* Walk stops */
for (s=1; s<p->stops.size; ++s, x1=x2, stop1=stop2) {
/* Pick next stop */
stop2 = &p->stops.items[s];
x2 = (SHint)(stop2->offset * (SH_GRADIENT_TEX_WIDTH-1));
SH_ASSERT(x1 >= 0 && x1 < SH_GRADIENT_TEX_WIDTH &&
x2 >= 0 && x2 < SH_GRADIENT_TEX_WIDTH &&
x1 <= x2);
dx = x2 - x1;
CSUBCTO(stop2->color, stop1->color, dc);
/* Interpolate inbetween */
for (x=x1+1; x<=x2; ++x) {
k = (SHfloat)(x-x1)/dx;
CSETC(c, stop1->color);
CADDCK(c, dc, k);
CSTORE_RGBA1D_F(c, rgba, x);
}
}
/* Update texture image */
glBindTexture(GL_TEXTURE_2D, p->texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
for(int i = 0; i < SH_GRADIENT_TEX_HEIGHT ; i++)
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, i, SH_GRADIENT_TEX_WIDTH, 1, GL_RGBA, GL_FLOAT, rgba);
GL_CEHCK_ERROR;
}
void shValidateInputStops(SHPaint *p)
{
SHStop *instop, stop = {0, {0,0,0,0}};
SHfloat lastOffset=0.0f;
int i;
shStopArrayClear(&p->stops);
shStopArrayReserve(&p->stops, p->instops.size);
/* Assure input stops are properly defined */
for (i=0; i<p->instops.size; ++i) {
/* Copy stop color */
instop = &p->instops.items[i];
stop.color = instop->color;
/* Offset must be in [0,1] */
if (instop->offset < 0.0f || instop->offset > 1.0f)
continue;
/* Discard whole sequence if not in ascending order */
if (instop->offset < lastOffset)
{shStopArrayClear(&p->stops); break;}
/* Add stop at offset 0 with same color if first not at 0 */
if (p->stops.size == 0 && instop->offset != 0.0f) {
stop.offset = 0.0f;
shStopArrayPushBackP(&p->stops, &stop);}
/* Add current stop to array */
stop.offset = instop->offset;
shStopArrayPushBackP(&p->stops, &stop);
/* Save last offset */
lastOffset = instop->offset;
}
/* Add stop at offset 1 with same color if last not at 1 */
if (p->stops.size > 0 && lastOffset != 1.0f) {
stop.offset = 1.0f;
shStopArrayPushBackP(&p->stops, &stop);
}
/* Add 2 default stops if no valid found */
if (p->stops.size == 0) {
/* First opaque black */
stop.offset = 0.0f;
CSET(stop.color, 0,0,0,1);
shStopArrayPushBackP(&p->stops, &stop);
/* Last opaque white */
stop.offset = 1.0f;
CSET(stop.color, 1,1,1,1);
shStopArrayPushBackP(&p->stops, &stop);
}
/* Update texture */
shUpdateColorRampTexture(p);
}
void shGenerateStops(SHPaint *p, SHfloat minOffset, SHfloat maxOffset,
SHStopArray *outStops)
{
SHStop *s1,*s2;
SHint i1,i2;
SHfloat o=0.0f;
SHfloat ostep=0.0f;
SHint istep=1;
SHint istart=0;
SHint iend=p->stops.size-1;
SHint minDone=0;
SHint maxDone=0;
SHStop outStop;
/* Start below zero? */
if (minOffset < 0.0f) {
if (p->spreadMode == VG_COLOR_RAMP_SPREAD_PAD) {
/* Add min offset stop */
outStop = p->stops.items[0];
outStop.offset = minOffset;
shStopArrayPushBackP(outStops, &outStop);
/* Add max offset stop and exit */
if (maxOffset < 0.0f) {
outStop.offset = maxOffset;
shStopArrayPushBackP(outStops, &outStop);
return; }
}else{
/* Pad starting offset to nearest factor of 2 */
SHint ioff = (SHint)SH_FLOOR(minOffset);
o = (SHfloat)(ioff - (ioff & 1));
}
}
/* Construct stops until max offset reached */
for (i1=istart, i2=istart+istep; maxDone!=1;
i1+=istep, i2+=istep, o+=ostep) {
/* All stops consumed? */
if (i1==iend) { switch(p->spreadMode) {
case VG_COLOR_RAMP_SPREAD_PAD:
/* Pick last stop */
outStop = p->stops.items[i1];
if (!minDone) {
/* Add min offset stop with last color */
outStop.offset = minOffset;
shStopArrayPushBackP(outStops, &outStop); }
/* Add max offset stop with last color */
outStop.offset = maxOffset;
shStopArrayPushBackP(outStops, &outStop);
return;
case VG_COLOR_RAMP_SPREAD_REPEAT:
/* Reset iteration */
i1=istart; i2=istart+istep;
/* Add stop1 if past min offset */
if (minDone) {
outStop = p->stops.items[0];
outStop.offset = o;
shStopArrayPushBackP(outStops, &outStop); }
break;
case VG_COLOR_RAMP_SPREAD_REFLECT:
/* Reflect iteration direction */
istep = -istep;
i2 = i1 + istep;
iend = (istep==1) ? p->stops.size-1 : 0;
break;
}
}
/* 2 stops and their offset distance */
s1 = &p->stops.items[i1];
s2 = &p->stops.items[i2];
ostep = s2->offset - s1->offset;
ostep = SH_ABS(ostep);
/* Add stop1 if reached min offset */
if (!minDone && o+ostep > minOffset) {
minDone = 1;
outStop = *s1;
outStop.offset = o;
shStopArrayPushBackP(outStops, &outStop);
}
/* Mark done if reached max offset */
if (o+ostep > maxOffset)
maxDone = 1;
/* Add stop2 if past min offset */
if (minDone) {
outStop = *s2;
outStop.offset = o+ostep;
shStopArrayPushBackP(outStops, &outStop);
}
}
}
void shSetGradientTexGLState(SHPaint *p)
{
glBindTexture(GL_TEXTURE_2D, p->texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
switch (p->spreadMode) {
case VG_COLOR_RAMP_SPREAD_PAD:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); break;
case VG_COLOR_RAMP_SPREAD_REPEAT:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); break;
case VG_COLOR_RAMP_SPREAD_REFLECT:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); break;
}
}
void shSetPatternTexGLState(SHPaint *p, VGContext *c)
{
glBindTexture(GL_TEXTURE_2D, ((SHImage*)p->pattern)->texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
switch(p->tilingMode) {
case VG_TILE_FILL:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR,
(GLfloat*)&c->tileFillColor);
break;
case VG_TILE_PAD:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
break;
case VG_TILE_REPEAT:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
break;
case VG_TILE_REFLECT:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
break;
}
}
int shLoadLinearGradientMesh(SHPaint *p, VGPaintMode mode, VGMatrixMode matrixMode)
{
SHMatrix3x3 *m = 0;
SHMatrix3x3 mu2p;
GLfloat u2p[9];
/* Pick paint transform matrix */
SH_GETCONTEXT(0);
if (mode == VG_FILL_PATH)
m = &context->fillTransform;
else if (mode == VG_STROKE_PATH)
m = &context->strokeTransform;
/* Back to paint space */
shInvertMatrix(m, &mu2p);
shMatrixToVG(&mu2p, (SHfloat*)u2p);
/* Setup shader */
glUniform1i(context->locationDraw.paintType, VG_PAINT_TYPE_LINEAR_GRADIENT);
glUniform2fv(context->locationDraw.paintParams, 2, p->linearGradient);
glUniformMatrix3fv(context->locationDraw.paintInverted, 1, GL_FALSE, u2p);
glActiveTexture(GL_TEXTURE1);
shSetGradientTexGLState(p);
glEnable(GL_TEXTURE_2D);
glUniform1i(context->locationDraw.rampSampler, 1);
GL_CEHCK_ERROR;
return 1;
}
int shLoadRadialGradientMesh(SHPaint *p, VGPaintMode mode, VGMatrixMode matrixMode)
{
SHMatrix3x3 *m = 0;
SHMatrix3x3 mu2p;
GLfloat u2p[9];
/* Pick paint transform matrix */
SH_GETCONTEXT(0);
if (mode == VG_FILL_PATH)
m = &context->fillTransform;
else if (mode == VG_STROKE_PATH)
m = &context->strokeTransform;
/* Back to paint space */
shInvertMatrix(m, &mu2p);
shMatrixToVG(&mu2p, (SHfloat*)u2p);
/* Setup shader */
glUniform1i(context->locationDraw.paintType, VG_PAINT_TYPE_RADIAL_GRADIENT);
glUniform2fv(context->locationDraw.paintParams, 3, p->radialGradient);
glUniformMatrix3fv(context->locationDraw.paintInverted, 1, GL_FALSE, u2p);
glActiveTexture(GL_TEXTURE1);
shSetGradientTexGLState(p);
glEnable(GL_TEXTURE_2D);
glUniform1i(context->locationDraw.rampSampler, 1);
GL_CEHCK_ERROR;
return 1;
}
int shLoadPatternMesh(SHPaint *p, VGPaintMode mode, VGMatrixMode matrixMode)
{
SHImage *i = (SHImage*)p->pattern;
SHMatrix3x3 *m = 0;
SHMatrix3x3 mu2p;
GLfloat u2p[9];
/* Pick paint transform matrix */
SH_GETCONTEXT(0);
if (mode == VG_FILL_PATH)
m = &context->fillTransform;
else if (mode == VG_STROKE_PATH)
m = &context->strokeTransform;
/* Back to paint space */
shInvertMatrix(m, &mu2p);
shMatrixToVG(&mu2p, (SHfloat*)u2p);
/* Setup shader */
glUniform1i(context->locationDraw.paintType, VG_PAINT_TYPE_PATTERN);
glUniform2f(context->locationDraw.paintParams, (GLfloat)i->width, (GLfloat)i->height);
glUniformMatrix3fv(context->locationDraw.paintInverted, 1, GL_FALSE, u2p);
glActiveTexture(GL_TEXTURE1);
shSetPatternTexGLState(p, context);
glEnable(GL_TEXTURE_2D);
glUniform1i(context->locationDraw.patternSampler, 1);
GL_CEHCK_ERROR;
return 1;
}
int shLoadOneColorMesh(SHPaint *p)
{
static GLfloat id[9] = {
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f };
SH_GETCONTEXT(0);
/* Setup shader */
glUniform1i(context->locationDraw.paintType, VG_PAINT_TYPE_COLOR);
glUniform4fv(context->locationDraw.paintColor, 1, (GLfloat*)&p->color);
glUniformMatrix3fv(context->locationDraw.paintInverted, 1, GL_FALSE, id);
return 1;
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __SHPAINT_H
#define __SHPAINT_H
#include "shDefs.h"
#include "shArrays.h"
#include "shImage.h"
typedef struct
{
float offset;
SHColor color;
} SHStop;
#define _ITEM_T SHStop
#define _ARRAY_T SHStopArray
#define _FUNC_T shStopArray
#define _ARRAY_DECLARE
#include "shArrayBase.h"
typedef struct
{
VGPaintType type;
SHColor color;
SHColorArray colors;
SHStopArray instops;
SHStopArray stops;
VGboolean premultiplied;
VGColorRampSpreadMode spreadMode;
VGTilingMode tilingMode;
SHfloat linearGradient[4];
SHfloat radialGradient[5];
GLuint texture;
VGImage pattern;
} SHPaint;
void SHPaint_ctor(SHPaint *p);
void SHPaint_dtor(SHPaint *p);
#define _ITEM_T SHPaint*
#define _ARRAY_T SHPaintArray
#define _FUNC_T shPaintArray
#define _ARRAY_DECLARE
#include "shArrayBase.h"
void shValidateInputStops(SHPaint *p);
void shSetGradientTexGLState(SHPaint *p);
int shLoadLinearGradientMesh(SHPaint *p, VGPaintMode mode, VGMatrixMode matrixMode);
int shLoadRadialGradientMesh(SHPaint *p, VGPaintMode mode, VGMatrixMode matrixMode);
int shLoadPatternMesh(SHPaint *p, VGPaintMode mode, VGMatrixMode matrixMode);
int shLoadOneColorMesh(SHPaint *p);
#endif /* __SHPAINT_H */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,142 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __SHPATH_H
#define __SHPATH_H
#include "shVectors.h"
#include "shArrays.h"
/* Helper structures for subdivision */
typedef struct {
SHVector2 p1;
SHVector2 p2;
SHVector2 p3;
} SHQuad;
typedef struct {
SHVector2 p1;
SHVector2 p2;
SHVector2 p3;
SHVector2 p4;
} SHCubic;
typedef struct {
SHVector2 p1;
SHVector2 p2;
SHfloat a1;
SHfloat a2;
} SHArc;
/* SHVertex */
typedef struct
{
SHVector2 point;
SHVector2 tangent;
SHfloat length;
SHuint flags;
} SHVertex;
/* Vertex flags for contour definition */
#define SH_VERTEX_FLAG_CLOSE (1 << 0)
#define SH_VERTEX_FLAG_SEGEND (1 << 1)
#define SH_SEGMENT_TYPE_COUNT 13
/* Vertex array */
#define _ITEM_T SHVertex
#define _ARRAY_T SHVertexArray
#define _FUNC_T shVertexArray
#define _ARRAY_DECLARE
#include "shArrayBase.h"
/* SHPath */
typedef struct SHPath
{
/* Properties */
VGint format;
SHfloat scale;
SHfloat bias;
SHint segHint;
SHint dataHint;
VGbitfield caps;
VGPathDatatype datatype;
/* Raw data */
SHuint8 *segs;
void *data;
SHint segCount;
SHint dataCount;
/* Subdivision */
SHVertexArray vertices;
SHVector2 min, max;
/* Additional stroke geometry (dash vertices if
path dashed or triangle vertices if width > 1 */
SHVector2Array stroke;
/* Cache */
VGboolean cacheDataValid;
VGboolean cacheTransformInit;
SHMatrix3x3 cacheTransform;
VGboolean cacheStrokeInit;
VGboolean cacheStrokeTessValid;
SHfloat cacheStrokeLineWidth;
VGCapStyle cacheStrokeCapStyle;
VGJoinStyle cacheStrokeJoinStyle;
SHfloat cacheStrokeMiterLimit;
SHfloat cacheStrokeDashPhase;
VGboolean cacheStrokeDashPhaseReset;
} SHPath;
void SHPath_ctor(SHPath *p);
void SHPath_dtor(SHPath *p);
/* Processing normalization flags */
#define SH_PROCESS_SIMPLIFY_LINES (1 << 0)
#define SH_PROCESS_SIMPLIFY_CURVES (1 << 1)
#define SH_PROCESS_CENTRALIZE_ARCS (1 << 2)
#define SH_PROCESS_REPAIR_ENDS (1 << 3)
/* Segment callback function type */
typedef void (*SegmentFunc) (SHPath *p, VGPathSegment segment,
VGPathCommand originalCommand,
SHfloat *data, void *userData);
/* Processes raw path data into normalized segments */
void shProcessPathData(SHPath *p, int flags,
SegmentFunc callback,
void *userData);
/* Pointer-to-path array */
#define _ITEM_T SHPath*
#define _ARRAY_T SHPathArray
#define _FUNC_T shPathArray
#define _ARRAY_DECLARE
#include "shArrayBase.h"
#endif /* __SHPATH_H */

View File

@@ -0,0 +1,522 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#define VG_API_EXPORT
#include "vg/openvg.h"
#include "shDefs.h"
#include "shExtensions.h"
#include "shContext.h"
#include "shPath.h"
#include "shImage.h"
#include "shGeometry.h"
#include "shPaint.h"
void shPremultiplyFramebuffer()
{
/* Multiply target color with its own alpha */
glBlendFunc(GL_ZERO, GL_DST_ALPHA);
}
void shUnpremultiplyFramebuffer()
{
/* TODO: hmmmm..... any idea? */
}
void updateBlendingStateGL(VGContext *c, int alphaIsOne)
{
/* Most common drawing mode (SRC_OVER with alpha=1)
as well as SRC is optimized by turning OpenGL
blending off. In other cases its turned on. */
switch (c->blendMode)
{
case VG_BLEND_SRC:
glBlendFunc(GL_ONE, GL_ZERO);
glDisable(GL_BLEND); break;
case VG_BLEND_SRC_IN:
glBlendFunc(GL_DST_ALPHA, GL_ZERO);
glEnable(GL_BLEND); break;
case VG_BLEND_DST_IN:
glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
glEnable(GL_BLEND); break;
case VG_BLEND_SRC_OUT_SH:
glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);
glEnable(GL_BLEND); break;
case VG_BLEND_DST_OUT_SH:
glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND); break;
case VG_BLEND_SRC_ATOP_SH:
glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND); break;
case VG_BLEND_DST_ATOP_SH:
glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA);
glEnable(GL_BLEND); break;
case VG_BLEND_DST_OVER:
glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_DST_ALPHA);
glEnable(GL_BLEND); break;
case VG_BLEND_SRC_OVER: default:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
if (alphaIsOne) {
glDisable(GL_BLEND);
} else {
glEnable(GL_BLEND);
}
break;
};
}
/*-----------------------------------------------------------
* Draws the triangles representing the stroke of a path.
*-----------------------------------------------------------*/
static void shDrawStroke(SHPath *p)
{
VG_GETCONTEXT(VG_NO_RETVAL);
glEnableVertexAttribArray(context->locationDraw.pos);
glVertexAttribPointer(context->locationDraw.pos, 2, GL_FLOAT, GL_FALSE, 0, p->stroke.items);
glDrawArrays(GL_TRIANGLES, 0, p->stroke.size);
glDisableVertexAttribArray(context->locationDraw.pos);
GL_CEHCK_ERROR;
}
/*-----------------------------------------------------------
* Draws the subdivided vertices in the OpenGL mode given
* (this could be VG_TRIANGLE_FAN or VG_LINE_STRIP).
*-----------------------------------------------------------*/
static void shDrawVertices(SHPath *p, GLenum mode)
{
int start = 0;
int size = 0;
/* We separate vertex arrays by contours to properly
handle the fill modes */
VG_GETCONTEXT(VG_NO_RETVAL);
glEnableVertexAttribArray(context->locationDraw.pos);
glVertexAttribPointer(context->locationDraw.pos, 2, GL_FLOAT, GL_FALSE, sizeof(SHVertex), p->vertices.items);
while (start < p->vertices.size) {
size = p->vertices.items[start].flags;
glDrawArrays(mode, start, size);
start += size;
}
glDisableVertexAttribArray(context->locationDraw.pos);
GL_CEHCK_ERROR;
}
/*--------------------------------------------------------------
* Constructs & draws colored OpenGL primitives that cover the
* given bounding box to represent the currently selected
* stroke or fill paint
*--------------------------------------------------------------*/
static void shDrawPaintMesh(VGContext *c, SHVector2 *min, SHVector2 *max,
VGPaintMode mode, GLenum texUnit)
{
SHPaint *p = 0;
SHVector2 pmin, pmax;
SHfloat K = 1.0f;
/* Pick the right paint */
if (mode == VG_FILL_PATH) {
p = (c->fillPaint ? c->fillPaint : &c->defaultPaint);
}else if (mode == VG_STROKE_PATH) {
p = (c->strokePaint ? c->strokePaint : &c->defaultPaint);
K = SH_CEIL(c->strokeMiterLimit * c->strokeLineWidth) + 1.0f;
}
/* We want to be sure to cover every pixel of this path so better
take a pixel more than leave some out (multisampling is tricky). */
SET2V(pmin, (*min)); SUB2(pmin, K,K);
SET2V(pmax, (*max)); ADD2(pmax, K,K);
/* Construct appropriate OpenGL primitives so as
to fill the stencil mask with select paint */
switch (p->type) {
case VG_PAINT_TYPE_LINEAR_GRADIENT:
shLoadLinearGradientMesh(p, mode, VG_MATRIX_PATH_USER_TO_SURFACE);
break;
case VG_PAINT_TYPE_RADIAL_GRADIENT:
shLoadRadialGradientMesh(p, mode, VG_MATRIX_PATH_USER_TO_SURFACE);
break;
case VG_PAINT_TYPE_PATTERN:
if (p->pattern != VG_INVALID_HANDLE) {
shLoadPatternMesh(p, mode, VG_MATRIX_PATH_USER_TO_SURFACE);
break;
}/* else behave as a color paint */
case VG_PAINT_TYPE_COLOR:
shLoadOneColorMesh(p);
break;
}
GLfloat v[] = { pmin.x, pmin.y,
pmax.x, pmin.y,
pmin.x, pmax.y,
pmax.x, pmax.y };
glEnableVertexAttribArray(c->locationDraw.pos);
glVertexAttribPointer(c->locationDraw.pos, 2, GL_FLOAT, GL_FALSE, 0, v);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(c->locationDraw.pos);
GL_CEHCK_ERROR;
}
VGboolean shIsTessCacheValid (VGContext *c, SHPath *p)
{
SHfloat nX, nY;
SHVector2 X, Y;
SHMatrix3x3 mi; //, mchange;
VGboolean valid = VG_TRUE;
if (p->cacheDataValid == VG_FALSE) {
valid = VG_FALSE;
}
else if (p->cacheTransformInit == VG_FALSE) {
valid = VG_FALSE;
}
else if (shInvertMatrix( &p->cacheTransform, &mi ) == VG_FALSE) {
valid = VG_FALSE;
}
else
{
/* TODO: Compare change matrix for any scale or shear */
// MULMATMAT( c->pathTransform, mi, mchange );
SET2( X, mi.m[0][0], mi.m[1][0] );
SET2( Y, mi.m[0][1], mi.m[1][1] );
nX = NORM2( X ); nY = NORM2( Y );
if (nX > 1.01f || nX < 0.99 ||
nY > 1.01f || nY < 0.99)
valid = VG_FALSE;
}
if (valid == VG_FALSE)
{
/* Update cache */
p->cacheDataValid = VG_TRUE;
p->cacheTransformInit = VG_TRUE;
p->cacheTransform = c->pathTransform;
p->cacheStrokeTessValid = VG_FALSE;
}
return valid;
}
VGboolean shIsStrokeCacheValid (VGContext *c, SHPath *p)
{
VGboolean valid = VG_TRUE;
if (p->cacheStrokeInit == VG_FALSE) {
valid = VG_FALSE;
}
else if (p->cacheStrokeTessValid == VG_FALSE) {
valid = VG_FALSE;
}
else if (c->strokeDashPattern.size > 0) {
valid = VG_FALSE;
}
else if (p->cacheStrokeLineWidth != c->strokeLineWidth ||
p->cacheStrokeCapStyle != c->strokeCapStyle ||
p->cacheStrokeJoinStyle != c->strokeJoinStyle ||
p->cacheStrokeMiterLimit != c->strokeMiterLimit) {
valid = VG_FALSE;
}
if (valid == VG_FALSE)
{
/* Update cache */
p->cacheStrokeInit = VG_TRUE;
p->cacheStrokeTessValid = VG_TRUE;
p->cacheStrokeLineWidth = c->strokeLineWidth;
p->cacheStrokeCapStyle = c->strokeCapStyle;
p->cacheStrokeJoinStyle = c->strokeJoinStyle;
p->cacheStrokeMiterLimit = c->strokeMiterLimit;
}
return valid;
}
/*-----------------------------------------------------------
* Tessellates / strokes the path and draws it according to
* VGContext state.
*-----------------------------------------------------------*/
VG_API_CALL void vgDrawPath(VGPath path, VGbitfield paintModes)
{
SHPath *p;
SHMatrix3x3 mi;
SHfloat mgl[16];
SHPaint *fill, *stroke;
SHRectangle *rect;
VG_GETCONTEXT(VG_NO_RETVAL);
VG_RETURN_ERR_IF(!shIsValidPath(context, path),
VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);
VG_RETURN_ERR_IF(paintModes & (~(VG_STROKE_PATH | VG_FILL_PATH)),
VG_ILLEGAL_ARGUMENT_ERROR, VG_NO_RETVAL);
/* Check whether scissoring is enabled and scissor
rectangle is valid */
if (context->scissoring == VG_TRUE) {
rect = &context->scissor.items[0];
if (context->scissor.size == 0) VG_RETURN( VG_NO_RETVAL );
if (rect->w <= 0.0f || rect->h <= 0.0f) VG_RETURN( VG_NO_RETVAL );
glScissor( (GLint)rect->x, (GLint)rect->y, (GLint)rect->w, (GLint)rect->h );
glEnable( GL_SCISSOR_TEST );
}
p = (SHPath*)path;
/* If user-to-surface matrix invertible tessellate in
surface space for better path resolution */
if (shIsTessCacheValid( context, p ) == VG_FALSE)
{
if (shInvertMatrix(&context->pathTransform, &mi)) {
shFlattenPath(p, 1);
shTransformVertices(&mi, p);
}else shFlattenPath(p, 0);
shFindBoundbox(p);
}
/* Pick paint if available or default*/
fill = (context->fillPaint ? context->fillPaint : &context->defaultPaint);
stroke = (context->strokePaint ? context->strokePaint : &context->defaultPaint);
/* Apply transformation */
shMatrixToGL(&context->pathTransform, mgl);
glUseProgram(context->progDraw);
glUniformMatrix4fv(context->locationDraw.model, 1, GL_FALSE, mgl);
glUniform1i(context->locationDraw.drawMode, 0); /* drawMode: path */
GL_CEHCK_ERROR;
if (paintModes & VG_FILL_PATH) {
/* Tesselate into stencil */
glEnable(GL_STENCIL_TEST);
if( context->fillRule == VG_EVEN_ODD )
{
glStencilFunc(GL_ALWAYS, 0, 0);
glStencilOp(GL_INVERT, GL_INVERT, GL_INVERT);
}
else
{
// pseudo non-zero fill rule. Fill everything at least covered once, don't
// care for possible decrements.
// TODO implement real non-zero fill-rule
glStencilFunc(GL_ALWAYS, 1, 1);
glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
}
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
shDrawVertices(p, GL_TRIANGLE_FAN);
/* Setup blending */
updateBlendingStateGL(context,
fill->type == VG_PAINT_TYPE_COLOR &&
fill->color.a == 1.0f);
/* Draw paint where stencil odd */
glStencilFunc(GL_EQUAL, 1, 1);
glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
shDrawPaintMesh(context, &p->min, &p->max, VG_FILL_PATH, GL_TEXTURE0);
/* Reset state */
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDisable(GL_STENCIL_TEST);
// glDisable(GL_BLEND);
}
if ((paintModes & VG_STROKE_PATH) &&
context->strokeLineWidth > 0.0f) {
#if 0
if (1) {/*context->strokeLineWidth > 1.0f) {*/
#endif
if (shIsStrokeCacheValid( context, p ) == VG_FALSE)
{
/* Generate stroke triangles in user space */
shVector2ArrayClear(&p->stroke);
shStrokePath(context, p);
}
/* Stroke into stencil */
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_NOTEQUAL, 1, 1);
glStencilOp(GL_KEEP, GL_INCR, GL_INCR);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
shDrawStroke(p);
/* Setup blending */
updateBlendingStateGL(context,
stroke->type == VG_PAINT_TYPE_COLOR &&
stroke->color.a == 1.0f);
/* Draw paint where stencil odd */
glStencilFunc(GL_EQUAL, 1, 1);
glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
shDrawPaintMesh(context, &p->min, &p->max, VG_STROKE_PATH, GL_TEXTURE0);
/* Reset state */
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDisable(GL_STENCIL_TEST);
// glDisable(GL_BLEND);
#if 0
}else{
/* Simulate thin stroke by alpha */
SHColor c = stroke->color;
if (context->strokeLineWidth < 1.0f)
c.a *= context->strokeLineWidth;
/* Draw contour as a line */
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
shDrawVertices(p, GL_LINE_STRIP);
glDisable(GL_BLEND);
}
#endif
}
if (context->scissoring == VG_TRUE)
glDisable( GL_SCISSOR_TEST );
VG_RETURN(VG_NO_RETVAL);
}
VG_API_CALL void vgDrawImage(VGImage image)
{
SHImage *i;
SHfloat mgl[16];
SHPaint *fill;
//SHVector2 min, max;
SHRectangle *rect;
VG_GETCONTEXT(VG_NO_RETVAL);
VG_RETURN_ERR_IF(!shIsValidImage(context, image),
VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);
/* TODO: check if image is current render target */
/* Check whether scissoring is enabled and scissor
rectangle is valid */
if (context->scissoring == VG_TRUE) {
rect = &context->scissor.items[0];
if (context->scissor.size == 0) VG_RETURN( VG_NO_RETVAL );
if (rect->w <= 0.0f || rect->h <= 0.0f) VG_RETURN( VG_NO_RETVAL );
glScissor( (GLint)rect->x, (GLint)rect->y, (GLint)rect->w, (GLint)rect->h );
glEnable( GL_SCISSOR_TEST );
}
/* Apply image-user-to-surface transformation */
i = (SHImage*)image;
shMatrixToGL(&context->imageTransform, mgl);
glUseProgram(context->progDraw);
glUniformMatrix4fv(context->locationDraw.model, 1, GL_FALSE, mgl);
glUniform1i(context->locationDraw.drawMode, 1); /* drawMode: image */
GL_CEHCK_ERROR;
/* Clamp to edge for proper filtering, modulate for multiply mode */
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, i->texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
/* Adjust antialiasing to settings */
if (context->imageQuality == VG_IMAGE_QUALITY_NONANTIALIASED) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}else{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
glEnableVertexAttribArray(context->locationDraw.textureUV);
GLfloat uv[] = { 0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f };
glVertexAttribPointer(context->locationDraw.textureUV, 2, GL_FLOAT, GL_FALSE, 0, uv);
glUniform1i(context->locationDraw.imageSampler, 0);
GL_CEHCK_ERROR;
/* Pick fill paint */
fill = (context->fillPaint ? context->fillPaint : &context->defaultPaint);
/* Setup blending */
updateBlendingStateGL(context, 0);
/* Draw textured quad */
glEnable(GL_TEXTURE_2D);
if (context->imageMode == VG_DRAW_IMAGE_MULTIPLY){
/* Multiply each colors */
glUniform1i(context->locationDraw.imageMode, VG_DRAW_IMAGE_MULTIPLY );
switch(fill->type){
case VG_PAINT_TYPE_RADIAL_GRADIENT:
shLoadRadialGradientMesh(fill, VG_FILL_PATH, VG_MATRIX_IMAGE_USER_TO_SURFACE);
break;
case VG_PAINT_TYPE_LINEAR_GRADIENT:
shLoadLinearGradientMesh(fill, VG_FILL_PATH, VG_MATRIX_IMAGE_USER_TO_SURFACE);
break;
case VG_PAINT_TYPE_PATTERN:
shLoadPatternMesh(fill, VG_FILL_PATH, VG_MATRIX_IMAGE_USER_TO_SURFACE);
break;
default:
case VG_PAINT_TYPE_COLOR:
shLoadOneColorMesh(fill);
break;
}
} else {
glUniform1i(context->locationDraw.imageMode, VG_DRAW_IMAGE_NORMAL );
}
GLfloat v[] = { 0.0f, 0.0f,
i->width, 0.0f,
0.0f, i->height,
i->width, i->height };
glVertexAttribPointer(context->locationDraw.pos, 2, GL_FLOAT, GL_FALSE, 0, v);
glEnableVertexAttribArray(context->locationDraw.pos);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(context->locationDraw.pos);
glDisable(GL_TEXTURE_2D);
GL_CEHCK_ERROR;
glDisableVertexAttribArray(context->locationDraw.textureUV);
if (context->scissoring == VG_TRUE)
glDisable( GL_SCISSOR_TEST );
VG_RETURN(VG_NO_RETVAL);
}

View File

@@ -0,0 +1,184 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "shVectors.h"
#define _ITEM_T SHVector2
#define _ARRAY_T SHVector2Array
#define _FUNC_T shVector2Array
#define _COMPARE_T(v1,v2) EQ2V(v1,v2)
#define _ARRAY_DEFINE
#include "shArrayBase.h"
void SHVector2_ctor(SHVector2 *v) {
v->x=0.0f; v->y=0.0f;
}
void SHVector2_dtor(SHVector2 *v) {
}
void SHVector3_ctor(SHVector3 *v) {
v->x=0.0f; v->y=0.0f; v->z=0.0f;
}
void SHVector3_dtor(SHVector3 *v) {
}
void SHVector4_ctor(SHVector4 *v) {
v->x=0.0f; v->y=0.0f; v->z=0.0f; v->w=0.0f;
}
void SHVector4_dtor(SHVector4 *v) {
}
void SHRectangle_ctor(SHRectangle *r) {
r->x=0.0f; r->y=0.0f; r->w=0.0f; r->h=0.0f;
}
void SHRectangle_dtor(SHRectangle *r) {
}
void shRectangleSet(SHRectangle *r, SHfloat x,
SHfloat y, SHfloat w, SHfloat h)
{
r->x=x; r->y=y; r->w=w; r->h=h;
}
void SHMatrix3x3_ctor(SHMatrix3x3 *mt)
{
IDMAT((*mt));
}
void SHMatrix3x3_dtor(SHMatrix3x3 *mt)
{
}
void shMatrixToGL(SHMatrix3x3 *m, SHfloat mgl[16])
{
/* When 2D vectors are specified OpenGL defaults Z to 0.0f so we
have to shift the third column of our 3x3 matrix to right */
mgl[0] = m->m[0][0]; mgl[4] = m->m[0][1]; mgl[8] = 0.0f; mgl[12] = m->m[0][2];
mgl[1] = m->m[1][0]; mgl[5] = m->m[1][1]; mgl[9] = 0.0f; mgl[13] = m->m[1][2];
mgl[2] = 0.0f; mgl[6] = 0.0f ; mgl[10] = 1.0f; mgl[14] = 0.0f;
mgl[3] = m->m[2][0]; mgl[7] = m->m[2][1]; mgl[11] = 0.0f; mgl[15] = m->m[2][2];
}
int shInvertMatrix(SHMatrix3x3 *m, SHMatrix3x3 *mout)
{
/* Calculate determinant */
SHfloat D0 = m->m[1][1]*m->m[2][2] - m->m[2][1]*m->m[1][2];
SHfloat D1 = m->m[2][0]*m->m[1][2] - m->m[1][0]*m->m[2][2];
SHfloat D2 = m->m[1][0]*m->m[2][1] - m->m[2][0]*m->m[1][1];
SHfloat D = m->m[0][0]*D0 + m->m[0][1]*D1 + m->m[0][2]*D2;
/* Check if singular */
if( D == 0.0f ) return 0;
D = 1.0f / D;
/* Calculate inverse */
mout->m[0][0] = D * D0;
mout->m[1][0] = D * D1;
mout->m[2][0] = D * D2;
mout->m[0][1] = D * (m->m[2][1]*m->m[0][2] - m->m[0][1]*m->m[2][2]);
mout->m[1][1] = D * (m->m[0][0]*m->m[2][2] - m->m[2][0]*m->m[0][2]);
mout->m[2][1] = D * (m->m[2][0]*m->m[0][1] - m->m[0][0]*m->m[2][1]);
mout->m[0][2] = D * (m->m[0][1]*m->m[1][2] - m->m[1][1]*m->m[0][2]);
mout->m[1][2] = D * (m->m[1][0]*m->m[0][2] - m->m[0][0]*m->m[1][2]);
mout->m[2][2] = D * (m->m[0][0]*m->m[1][1] - m->m[1][0]*m->m[0][1]);
return 1;
}
SHfloat shVectorOrientation(SHVector2 *v) {
SHfloat norm = (SHfloat)NORM2((*v));
SHfloat cosa = v->x/norm;
SHfloat sina = v->y/norm;
return (SHfloat)(sina>=0 ? SH_ACOS(cosa) : 2*PI-SH_ACOS(cosa));
}
int shLineLineXsection(SHVector2 *o1, SHVector2 *v1,
SHVector2 *o2, SHVector2 *v2,
SHVector2 *xsection)
{
SHfloat rightU = o2->x - o1->x;
SHfloat rightD = o2->y - o1->y;
SHfloat D = v1->x * (-v2->y) - v1->y * (-v2->x);
SHfloat DX = rightU * (-v2->y) - rightD * (-v2->x);
/*SHfloat DY = v1.x * rightD - v1.y * rightU;*/
SHfloat t1 = DX / D;
if (D == 0.0f)
return 0;
xsection->x = o1->x + t1*v1->x;
xsection->y = o1->y + t1*v1->y;
return 1;
}
void shCalcOrtho2D(float* mat, float left, float right, float bottom, float top, float near, float far)
{
/* http://en.wikipedia.org/wiki/Orthographic_projection */
const float zNear = near;
const float zFar = far;
const float inv_z = 1.0f / (zFar - zNear);
const float inv_y = 1.0f / (top - bottom);
const float inv_x = 1.0f / (right - left);
/* first column */
*mat++ = (2.0f*inv_x);
*mat++ = (0.0f);
*mat++ = (0.0f);
*mat++ = (0.0f);
/* second */
*mat++ = (0.0f);
*mat++ = (2.0*inv_y);
*mat++ = (0.0f);
*mat++ = (0.0f);
/* third */
*mat++ = (0.0f);
*mat++ = (0.0f);
*mat++ = (-2.0f*inv_z);
*mat++ = (0.0f);
/* fourth */
*mat++ = (-(right + left)*inv_x);
*mat++ = (-(top + bottom)*inv_y);
*mat++ = (-(zFar + zNear)*inv_z);
*mat++ = (1.0f);
}
void shMatrixToVG(SHMatrix3x3 *m, SHfloat mvg[9])
{
mvg[0] = m->m[0][0]; mvg[3] = m->m[0][1]; mvg[6] = m->m[0][2];
mvg[1] = m->m[1][0]; mvg[4] = m->m[1][1]; mvg[7] = m->m[1][2];
mvg[2] = m->m[2][0]; mvg[5] = m->m[2][1]; mvg[8] = m->m[2][2];
}
void shIdMatrixGL(SHfloat mgl[16])
{
mgl[0] = 1.0f; mgl[4] = 0.0f; mgl[8] = 0.0f; mgl[12] = 0.0f;
mgl[1] = 0.0f; mgl[5] = 1.0f; mgl[9] = 0.0f; mgl[13] = 0.0f;
mgl[2] = 0.0f; mgl[6] = 0.0f; mgl[10] = 1.0f; mgl[14] = 0.0f;
mgl[3] = 0.0f; mgl[7] = 0.0f; mgl[11] = 0.0f; mgl[15] = 1.0f;
}

View File

@@ -0,0 +1,278 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __SHVECTORS_H
#define __SHVECTORS_H
#include "shDefs.h"
/* Vector structures
*--------------------------------------------------------------*/
typedef struct
{
SHfloat x,y;
} SHVector2;
void SHVector2_ctor(SHVector2 *v);
void SHVector2_dtor(SHVector2 *v);
typedef struct
{
SHfloat x,y,z;
} SHVector3;
void SHVector3_ctor(SHVector3 *v);
void SHVector3_dtor(SHVector3 *v);
typedef struct
{
SHfloat x,y,z,w;
} SHVector4;
void SHVector4_ctor(SHVector4 *v);
void SHVector4_dtor(SHVector4 *v);
typedef struct
{
SHfloat x,y,w,h;
} SHRectangle;
void SHRectangle_ctor(SHRectangle *r);
void SHRectangle_dtor(SHRectangle *r);
void shRectangleSet(SHRectangle *r, SHfloat x,
SHfloat y, SHfloat w, SHfloat h);
typedef struct
{
SHfloat m[3][3];
} SHMatrix3x3;
void SHMatrix3x3_ctor(SHMatrix3x3 *m);
void SHMatrix3x3_dtor(SHMatrix3x3 *m);
/*------------------------------------------------------------
* Vector Arrays
*------------------------------------------------------------*/
#define _ITEM_T SHVector2
#define _ARRAY_T SHVector2Array
#define _FUNC_T shVector2Array
#define _ARRAY_DECLARE
#include "shArrayBase.h"
/*--------------------------------------------------------
* Macros for typical vector operations. The only way to
* inline in C is to actually write a macro
*--------------------------------------------------------- */
#define SET2(v,xs,ys) { v.x=xs; v.y=ys; }
#define SET3(v,xs,ys,zs) { v.x=xs; v.y=ys; v.z=zs; }
#define SET4(v,xs,ys,zs,ws) { v.x=xs; v.y=ys; v.z=zs; v.w=ws; }
#define SET2V(v1,v2) { v1.x=v2.x; v1.y=v2.y; }
#define SET3V(v1,v2) { v1.x=v2.x; v1.y=v2.y; v1.z=v2.z; }
#define SET4V(v1,v2) { v1.x=v2.x; v1.y=v2.y; v1.z=v2.z; v1.w=v2.w; }
#define EQ2(v,xx,yy) ( v.x==xx && v.y==yy )
#define EQ3(v,xx,yy,zz) ( v.x==xx && v.y==yy && v.z==zz )
#define EQ4(v,xx,yy,zz,ww) ( v.x==xx && v.y==yy && v.z==zz && v.w==ww )
#define ISZERO2(v) ( v.x==0.0f && v.y==0.0f )
#define ISZERO3(v) ( v.x==0.0f && v.y==0.0f && v.z==0.0f)
#define ISZERO4(v) ( v.x==0.0f && v.y==0.0f && v.z==0.0f && v.w==0.0f )
#define EQ2V(v1,v2) ( v1.x==v2.x && v1.y==v2.y )
#define EQ3V(v1,v2) ( v1.x==v2.x && v1.y==v2.y && v1.z==v2.z )
#define EQ4V(v1,v2) ( v1.x==v2.x && v1.y==v2.y && v1.z==v2.z && v1.w==v2.w )
#define ADD2(v,xx,yy) { v.x+=xx; v.y+=yy; }
#define ADD3(v,xx,yy,zz) { v.x+=xx; v.y+=yy; v.z+=zz; }
#define ADD4(v,xx,yy,zz,ww) { v.x+=xx; v.y+=yy; v.z+=zz; v.w+=ww; }
#define ADD2V(v1,v2) { v1.x+=v2.x; v1.y+=v2.y; }
#define ADD3V(v1,v2) { v1.x+=v2.x; v1.y+=v2.y; v1.z+=v2.z; }
#define ADD4V(v1,v2) { v1.x+=v2.x; v1.y+=v2.y; v1.z+=v2.z; v1.w+=v2.w; }
#define SUB2(v,xx,yy) { v.x-=xx; v.y-=yy; }
#define SUB3(v,xx,yy,zz) { v.x-=xx; v.y-=yy; v.z-=zz; }
#define SUB4(v,xx,yy,zz,ww) { v.x-=xx; v.y-=yy; v.z-=zz; v.w-=v2.w; }
#define SUB2V(v1,v2) { v1.x-=v2.x; v1.y-=v2.y; }
#define SUB3V(v1,v2) { v1.x-=v2.x; v1.y-=v2.y; v1.z-=v2.z; }
#define SUB4V(v1,v2) { v1.x-=v2.x; v1.y-=v2.y; v1.z-=v2.z; v1.w-=v2.w; }
#define MUL2(v,f) { v.x*=f; v.y*=f; }
#define MUL3(v,f) { v.x*=f; v.y*=f; v.z*=z; }
#define MUL4(v,f) { v.x*=f; v.y*=f; v.z*=z; v.w*=w; }
#define DIV2(v,f) { v.x/=f; v.y/=f; }
#define DIV3(v,f) { v.x/=f; v.y/=f; v.z/=z; }
#define DIV4(v,f) { v.x/=f; v.y/=f; v.z/=z; v.w/=w; }
#define ABS2(v) { v.x=SH_ABS(v.x); v.y=SH_ABS(v.y); }
#define ABS3(v) { v.x=SH_ABS(v.x); v.y=SH_ABS(v.y); v.z=SH_ABS(v.z); }
#define ABS4(v) { v.x=SH_ABS(v.x); v.y=SH_ABS(v.y); v.z=SH_ABS(v.z); v.w=SH_ABS(v.w); }
#define NORMSQ2(v) (v.x*v.x + v.y*v.y)
#define NORMSQ3(v) (v.x*v.x + v.y*v.y + v.z*v.z)
#define NORMSQ4(v) (v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w)
#define NORM2(v) SH_SQRT(NORMSQ2(v))
#define NORM3(v) SH_SQRT(NORMSQ3(v))
#define NORM4(v) SH_SQRT(NORMSQ4(v))
#define NORMALIZE2(v) { SHfloat n=NORM2(v); v.x/=n; v.y/=n; }
#define NORMALIZE3(v) { SHfloat n=NORM3(v); v.x/=n; v.y/=n; v.z/=n; }
#define NORMALIZE4(v) { SHfloat n=NORM4(v); v.x/=n; v.y/=n; v.z/=n; v.w/=w; }
#define DOT2(v1,v2) (v1.x*v2.x + v1.y*v2.y)
#define DOT3(v1,v2) (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z)
#define DOT4(v1,v2) (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z + v1.w*v2.w)
#define CROSS2(v1,v2) (v1.x*v2.y - v2.x*v1.y)
#define ANGLE2(v1,v2) (SH_ACOS( DOT2(v1,v2) / (NORM2(v1)*NORM2(v2)) ))
#define ANGLE2N(v1,v2) (SH_ACOS( DOT2(v1,v2) ))
#define OFFSET2V(v, o, s) { v.x += o.x*s; v.y += o.y*s; }
#define OFFSET3V(v, o, s) { v.x += o.x*s; v.y += o.y*s; v.z += o.z*s; }
#define OFFSET4V(v, o, s) { v.x += o.x*s; v.y += o.y*s; v.z += o.z*s; v.w += o.w*s; }
/*-----------------------------------------------------
* Macros for matrix operations
*-----------------------------------------------------*/
#define SETMAT(mat, m00, m01, m02, m10, m11, m12, m20, m21, m22) { \
mat.m[0][0] = m00; mat.m[0][1] = m01; mat.m[0][2] = m02; \
mat.m[1][0] = m10; mat.m[1][1] = m11; mat.m[1][2] = m12; \
mat.m[2][0] = m20; mat.m[2][1] = m21; mat.m[2][2] = m22; }
#define SETMATMAT(m1, m2) { \
int i,j; \
for(i=0;i<3;i++) \
for(j=0;j<3;j++) \
m1.m[i][j] = m2.m[i][j]; }
#define MULMATS(mat, s) { \
int i,j; \
for(i=0;i<3;i++) \
for(j=0;j<3;j++) \
mat.m[i][j] *= s; }
#define DIVMATS(mat, s) { \
int i,j; \
for(i=0;i<3;i++) \
for(j=0;j<3;j++) \
mat.m[i][j] /= s; }
#define MULMATMAT(m1, m2, mout) { \
int i,j; \
for(i=0;i<3;i++) \
for(j=0;j<3;j++) \
mout.m[i][j] = \
m1.m[i][0] * m2.m[0][j] + \
m1.m[i][1] * m2.m[1][j] + \
m1.m[i][2] * m2.m[2][j]; }
#define IDMAT(mat) SETMAT(mat, 1,0,0, 0,1,0, 0,0,1)
#define TRANSLATEMATL(mat, tx, ty) { \
SHMatrix3x3 trans,temp; \
SETMAT(trans, 1,0,tx, 0,1,ty, 0,0,1); \
MULMATMAT(trans, mat, temp); \
SETMATMAT(mat, temp); }
#define TRANSLATEMATR(mat, tx, ty) { \
SHMatrix3x3 trans,temp; \
SETMAT(trans, 1,0,tx, 0,1,ty, 0,0,1); \
MULMATMAT(mat, trans, temp); \
SETMATMAT(mat, temp); }
#define SCALEMATL(mat, sx, sy) { \
SHMatrix3x3 scale, temp; \
SETMAT(scale, sx,0,0, 0,sy,0, 0,0,1); \
MULMATMAT(scale, mat, temp); \
SETMATMAT(mat, temp); }
#define SCALEMATR(mat, sx, sy) { \
SHMatrix3x3 scale, temp; \
SETMAT(scale, sx,0,0, 0,sy,0, 0,0,1); \
MULMATMAT(mat, scale, temp); \
SETMATMAT(mat, temp); }
#define SHEARMATL(mat, shx, shy) {\
SHMatrix3x3 shear, temp;\
SETMAT(shear, 1,shx,0, shy,1,0, 0,0,1); \
MULMATMAT(shear, mat, temp); \
SETMATMAT(mat, temp); }
#define SHEARMATR(mat, shx, shy) {\
SHMatrix3x3 shear, temp;\
SETMAT(shear, 1,shx,0, shy,1,0, 0,0,1); \
MULMATMAT(mat, shear, temp); \
SETMATMAT(mat, temp); }
#define ROTATEMATL(mat, a) { \
SHfloat cosa=SH_COS(a), sina=SH_SIN(a); \
SHMatrix3x3 rot, temp; \
SETMAT(rot, cosa,-sina,0, sina,cosa,0, 0,0,1); \
MULMATMAT(rot, mat, temp); \
SETMATMAT(mat, temp); }
#define ROTATEMATR(mat, a) { \
SHfloat cosa=SH_COS(a), sina=SH_SIN(a); \
SHMatrix3x3 rot, temp; \
SETMAT(rot, cosa,-sina,0, sina,cosa,0, 0,0,1); \
MULMATMAT(mat, rot, temp); \
SETMATMAT(mat, temp); }
#define TRANSFORM2TO(v, mat, vout) { \
vout.x = v.x*mat.m[0][0] + v.y*mat.m[0][1] + 1*mat.m[0][2]; \
vout.y = v.x*mat.m[1][0] + v.y*mat.m[1][1] + 1*mat.m[1][2]; }
#define TRANSFORM2(v, mat) { \
SHVector2 temp; TRANSFORM2TO(v, mat, temp); v = temp; }
#define TRANSFORM2DIRTO(v, mat, vout) { \
vout.x = v.x*mat.m[0][0] + v.y*mat.m[0][1]; \
vout.y = v.x*mat.m[1][0] + v.y*mat.m[1][1]; }
#define TRANSFORM2DIR(v, mat) { \
SHVector2 temp; TRANSFORM2DIRTO(v, mat, temp); v = temp; }
/*--------------------------------------------------------
* Additional functions
*--------------------------------------------------------- */
void shMatrixToGL(SHMatrix3x3 *m, SHfloat mgl[16]);
SHint shInvertMatrix(SHMatrix3x3 *m, SHMatrix3x3 *mout);
SHfloat shVectorOrientation(SHVector2 *v);
int shLineLineXsection(SHVector2 *o1, SHVector2 *v1,
SHVector2 *o2, SHVector2 *v2,
SHVector2 *xsection);
void shCalcOrtho2D(float* mat, float left, float right, float bottom, float top, float near, float far);
void shMatrixToVG(SHMatrix3x3 *m, SHfloat mvg[9]);
void shIdMatrixGL(SHfloat mgl[16]);
#endif/* __SHVECTORS_H */

View File

@@ -0,0 +1,426 @@
/*
* Copyright (c) 2007 Ivan Leben
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#define VG_API_EXPORT
#include "vg/openvg.h"
#include "vg/vgu.h"
#include "shDefs.h"
#include "shContext.h"
#include <math.h>
static VGUErrorCode shAppend(VGPath path, SHint commSize, const VGubyte *comm,
SHint dataSize, const VGfloat *data)
{
VGErrorCode err = VG_NO_ERROR;
VGPathDatatype type = vgGetParameterf(path, VG_PATH_DATATYPE);
VGfloat scale = vgGetParameterf(path, VG_PATH_SCALE);
VGfloat bias = vgGetParameterf(path, VG_PATH_BIAS);
SH_ASSERT(dataSize <= 26);
switch(type)
{
case VG_PATH_DATATYPE_S_8: {
SHint8 data8[26]; int i;
for (i=0; i<dataSize; ++i)
data8[i] = (SHint8)SH_FLOOR((data[i] - bias) / scale + 0.5f);
vgAppendPathData(path, commSize, comm, data8);
break;}
case VG_PATH_DATATYPE_S_16: {
SHint16 data16[26]; int i;
for (i=0; i<dataSize; ++i)
data16[i] = (SHint16)SH_FLOOR((data[i] - bias) / scale + 0.5f);
vgAppendPathData(path, commSize, comm, data16);
break;}
case VG_PATH_DATATYPE_S_32: {
SHint32 data32[26]; int i;
for (i=0; i<dataSize; ++i)
data32[i] = (SHint32)SH_FLOOR((data[i] - bias) / scale + 0.5f);
vgAppendPathData(path, commSize, comm, data32);
break;}
default: {
VGfloat dataF[26]; int i;
for (i=0; i<dataSize; ++i)
dataF[i] = (data[i] - bias) / scale;
vgAppendPathData(path, commSize, comm, dataF);
break;}
}
err = vgGetError();
if (err == VG_PATH_CAPABILITY_ERROR)
return VGU_PATH_CAPABILITY_ERROR;
else if (err == VG_BAD_HANDLE_ERROR)
return VGU_BAD_HANDLE_ERROR;
else if (err == VG_OUT_OF_MEMORY_ERROR)
return VGU_OUT_OF_MEMORY_ERROR;
return VGU_NO_ERROR;
}
VGU_API_CALL VGUErrorCode vguLine(VGPath path,
VGfloat x0, VGfloat y0,
VGfloat x1, VGfloat y1)
{
VGUErrorCode err = VGU_NO_ERROR;
const VGubyte comm[] = {VG_MOVE_TO_ABS, VG_LINE_TO_ABS};
VGfloat data[4];
data[0] = x0; data[1] = y0;
data[2] = x1; data[3] = y1;
err = shAppend(path, 2, comm, 4, data);
return err;
}
VGU_API_CALL VGUErrorCode vguPolygon(VGPath path,
const VGfloat * points, VGint count,
VGboolean closed)
{
VGint i;
VGubyte *comm = NULL;
VGUErrorCode err = VGU_NO_ERROR;
if (points == NULL || count <= 0)
return VGU_ILLEGAL_ARGUMENT_ERROR;
/* TODO: check points array alignment */
comm = (VGubyte*)malloc( (count+1) * sizeof(VGubyte) );
if (comm == NULL) return VGU_OUT_OF_MEMORY_ERROR;
comm[0] = VG_MOVE_TO_ABS;
for (i=1; i<count; ++i)
comm[i] = VG_LINE_TO_ABS;
comm[count] = VG_CLOSE_PATH;
if (closed) err = shAppend(path, count+1, comm, count*2, points);
else err = shAppend(path, count, comm, count*2, points);
free(comm);
return err;
}
VGU_API_CALL VGUErrorCode vguRect(VGPath path,
VGfloat x, VGfloat y,
VGfloat width, VGfloat height)
{
VGUErrorCode err = VGU_NO_ERROR;
VGubyte comm[5] = {
VG_MOVE_TO_ABS, VG_HLINE_TO_REL,
VG_VLINE_TO_REL, VG_HLINE_TO_REL,
VG_CLOSE_PATH };
VGfloat data[5];
if (width <= 0 || height <= 0)
return VGU_ILLEGAL_ARGUMENT_ERROR;
data[0] = x; data[1] = y;
data[2] = width; data[3] = height;
data[4] = -width;
err = shAppend(path, 5, comm, 5, data);
return err;
}
VGU_API_CALL VGUErrorCode vguRoundRect(VGPath path,
VGfloat x, VGfloat y,
VGfloat width, VGfloat height,
VGfloat arcWidth, VGfloat arcHeight)
{
VGUErrorCode err = VGU_NO_ERROR;
VGubyte comm[10] = {
VG_MOVE_TO_ABS,
VG_HLINE_TO_REL, VG_SCCWARC_TO_REL,
VG_VLINE_TO_REL, VG_SCCWARC_TO_REL,
VG_HLINE_TO_REL, VG_SCCWARC_TO_REL,
VG_VLINE_TO_REL, VG_SCCWARC_TO_REL,
VG_CLOSE_PATH };
VGfloat data[26];
VGfloat rx, ry;
if (width <= 0 || height <= 0)
return VGU_ILLEGAL_ARGUMENT_ERROR;
SH_CLAMP(arcWidth, 0.0f, width);
SH_CLAMP(arcHeight, 0.0f, height);
rx = arcWidth/2;
ry = arcHeight/2;
data[0] = x + rx; data[1] = y;
data[2] = width - arcWidth;
data[3] = rx; data[4] = ry; data[5] = 0;
data[6] = rx; data[7] = ry;
data[8] = height - arcHeight;
data[9] = rx; data[10] = ry; data[11] = 0;
data[12] = -rx; data[13] = ry;
data[14] = -(width - arcWidth);
data[15] = rx; data[16] = ry; data[17] = 0;
data[18] = -rx; data[19] = -ry;
data[20] = -(height - arcHeight);
data[21] = rx; data[22] = ry; data[23] = 0;
data[24] = rx; data[25] = -ry;
err = shAppend(path, 10, comm, 26, data);
return err;
}
VGU_API_CALL VGUErrorCode vguEllipse(VGPath path,
VGfloat cx, VGfloat cy,
VGfloat width, VGfloat height)
{
VGUErrorCode err = VGU_NO_ERROR;
const VGubyte comm[] = {
VG_MOVE_TO_ABS, VG_SCCWARC_TO_REL,
VG_SCCWARC_TO_REL, VG_CLOSE_PATH};
VGfloat data[12];
if (width <= 0 || height <= 0)
return VGU_ILLEGAL_ARGUMENT_ERROR;
data[0] = cx + width/2; data[1] = cy;
data[2] = width/2; data[3] = height/2; data[4] = 0;
data[5] = -width; data[6] = 0;
data[7] = width/2; data[8] = height/2; data[9] = 0;
data[10] = width; data[11] = 0;
err = shAppend(path, 4, comm, 12, data);
return err;
}
#include <stdio.h>
VGU_API_CALL VGUErrorCode vguArc(VGPath path,
VGfloat x, VGfloat y,
VGfloat width, VGfloat height,
VGfloat startAngle, VGfloat angleExtent,
VGUArcType arcType)
{
VGUErrorCode err = VGU_NO_ERROR;
VGubyte commStart[1] = {VG_MOVE_TO_ABS};
VGfloat dataStart[2];
VGubyte commArcCCW[1] = {VG_SCCWARC_TO_ABS};
VGubyte commArcCW[1] = {VG_SCWARC_TO_ABS};
VGfloat dataArc[5];
VGubyte commEndPie[2] = {VG_LINE_TO_ABS, VG_CLOSE_PATH};
VGfloat dataEndPie[2];
VGubyte commEndChord[1] = {VG_CLOSE_PATH};
VGfloat dataEndChord[1] = {0.0f};
VGfloat alast, a = 0.0f;
VGfloat rx = width/2, ry = height/2;
if (width <= 0 || height <= 0)
return VGU_ILLEGAL_ARGUMENT_ERROR;
if (arcType != VGU_ARC_OPEN &&
arcType != VGU_ARC_CHORD &&
arcType != VGU_ARC_PIE)
return VGU_ILLEGAL_ARGUMENT_ERROR;
startAngle = SH_DEG2RAD(startAngle);
angleExtent = SH_DEG2RAD(angleExtent);
alast = startAngle + angleExtent;
dataStart[0] = x + SH_COS(startAngle) * rx;
dataStart[1] = y + SH_SIN(startAngle) * ry;
err = shAppend(path, 1, commStart, 2, dataStart);
if (err != VGU_NO_ERROR) return err;
dataArc[0] = rx;
dataArc[1] = ry;
dataArc[2] = 0.0f;
if (angleExtent > 0) {
a = startAngle + PI;
while (a < alast) {
dataArc[3] = x + SH_COS(a) * rx;
dataArc[4] = y + SH_SIN(a) * ry;
err = shAppend(path, 1, commArcCCW, 5, dataArc);
if (err != VGU_NO_ERROR) return err;
a += PI; }
dataArc[3] = x + SH_COS(alast) * rx;
dataArc[4] = y + SH_SIN(alast) * ry;
err = shAppend(path, 1, commArcCCW, 5, dataArc);
if (err != VGU_NO_ERROR) return err;
}else{
a = startAngle - PI;
while (a > alast) {
dataArc[3] = x + SH_COS(a) * rx;
dataArc[4] = y + SH_SIN(a) * ry;
err = shAppend(path, 1, commArcCW, 5, dataArc);
if (err != VGU_NO_ERROR) return err;
a -= PI; }
dataArc[3] = x + SH_COS(alast) * rx;
dataArc[4] = y + SH_SIN(alast) * ry;
err = shAppend(path, 1, commArcCW, 5, dataArc);
if (err != VGU_NO_ERROR) return err;
}
if (arcType == VGU_ARC_PIE) {
dataEndPie[0] = x; dataEndPie[1] = y;
err = shAppend(path, 2, commEndPie, 2, dataEndPie);
}else if (arcType == VGU_ARC_CHORD) {
err = shAppend(path, 1, commEndChord, 0, dataEndChord);
}
return err;
}
VGU_API_CALL VGUErrorCode vguComputeWarpQuadToSquare(VGfloat sx0, VGfloat sy0,
VGfloat sx1, VGfloat sy1,
VGfloat sx2, VGfloat sy2,
VGfloat sx3, VGfloat sy3,
VGfloat * matrix)
{
/* Basic idea taken from the reference implementation */
VGfloat mat[3][3];
VGfloat det, det00, det01, det02;
if( !matrix )
return VGU_ILLEGAL_ARGUMENT_ERROR;
if( vguComputeWarpSquareToQuad( sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3,
(VGfloat*)mat )
== VGU_BAD_WARP_ERROR )
return VGU_BAD_WARP_ERROR;
// Invert the matrix...
det00 = mat[1][1]*mat[2][2] - mat[2][1]*mat[1][2];
det01 = mat[2][0]*mat[1][2] - mat[1][0]*mat[2][2];
det02 = mat[1][0]*mat[2][1] - mat[2][0]*mat[1][1];
det = mat[0][0]*det00 + mat[0][1]*det01 + mat[0][2]*det02;
if( det == 0.0f )
return VGU_BAD_WARP_ERROR;
det = 1 / det;
matrix[0] = det * det00;
matrix[3] = det * det01;
matrix[6] = det * det02;
matrix[1] = det * (mat[2][1]*mat[0][2] - mat[0][1]*mat[2][2]);
matrix[4] = det * (mat[0][0]*mat[2][2] - mat[2][0]*mat[0][2]);
matrix[7] = det * (mat[2][0]*mat[0][1] - mat[0][0]*mat[2][1]);
matrix[2] = det * (mat[0][1]*mat[1][2] - mat[1][1]*mat[0][2]);
matrix[5] = det * (mat[1][0]*mat[0][2] - mat[0][0]*mat[1][2]);
matrix[8] = det * (mat[0][0]*mat[1][1] - mat[1][0]*mat[0][1]);
return VGU_NO_ERROR;
}
VGU_API_CALL VGUErrorCode vguComputeWarpSquareToQuad(VGfloat dx0, VGfloat dy0,
VGfloat dx1, VGfloat dy1,
VGfloat dx2, VGfloat dy2,
VGfloat dx3, VGfloat dy3,
VGfloat * matrix)
{
/* Taken from https://github.com/mvr/shivavg (who has taken it from the
reference implementation) */
VGfloat diffx1 = dx1 - dx3;
VGfloat diffy1 = dy1 - dy3;
VGfloat diffx2 = dx2 - dx3;
VGfloat diffy2 = dy2 - dy3;
VGfloat det = diffx1*diffy2 - diffx2*diffy1;
VGfloat sumx = dx0 - dx1 + dx3 - dx2;
VGfloat sumy = dy0 - dy1 + dy3 - dy2;
VGfloat g, h, oodet;
if(!matrix)
return VGU_ILLEGAL_ARGUMENT_ERROR;
if(det == 0.0f)
return VGU_BAD_WARP_ERROR;
if(sumx == 0.0f && sumy == 0.0f)
{
/* Affine mapping */
matrix[0] = dx1 - dx0;
matrix[1] = dy1 - dy0;
matrix[2] = 0.0f;
matrix[3] = dx3 - dx1;
matrix[4] = dy3 - dy1;
matrix[5] = 0.0f;
matrix[6] = dx0;
matrix[7] = dy0;
matrix[8] = 1.0f;
return VGU_NO_ERROR;
}
oodet = 1.0f / det;
g = (sumx*diffy2 - diffx2*sumy) * oodet;
h = (diffx1*sumy - sumx*diffy1) * oodet;
matrix[0] = dx1-dx0+g*dx1;
matrix[1] = dy1-dy0+g*dy1;
matrix[2] = g;
matrix[3] = dx2-dx0+h*dx2;
matrix[4] = dy2-dy0+h*dy2;
matrix[5] = h;
matrix[6] = dx0;
matrix[7] = dy0;
matrix[8] = 1.0f;
return VGU_NO_ERROR;
}
VGU_API_CALL VGUErrorCode vguComputeWarpQuadToQuad(VGfloat dx0, VGfloat dy0,
VGfloat dx1, VGfloat dy1,
VGfloat dx2, VGfloat dy2,
VGfloat dx3, VGfloat dy3,
VGfloat sx0, VGfloat sy0,
VGfloat sx1, VGfloat sy1,
VGfloat sx2, VGfloat sy2,
VGfloat sx3, VGfloat sy3,
VGfloat * matrix)
{
return VGU_NO_ERROR;
}

View File

@@ -0,0 +1,494 @@
/*
* Copyright (c) 2021 Takuma Hayashi
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "vg/openvg.h"
#include "shContext.h"
#include "shDefs.h"
#include "shaders.h"
#include <string.h>
#include <stdio.h>
static const char* vgShaderVertexPipeline = R"glsl(
#version 330
/*** Input *******************/
in vec2 pos;
in vec2 textureUV;
uniform mat4 sh_Model;
uniform mat4 sh_Ortho;
uniform mat3 paintInverted;
/*** Output ******************/
out vec2 texImageCoord;
out vec2 paintCoord;
/*** Grobal variables ********************/
vec4 sh_Vertex;
/*** Functions ****************************************/
// User defined shader
void shMain(void);
/*** Main thread **************************************************/
void main() {
/* Stage 3: Transformation */
sh_Vertex = vec4(pos, 0, 1);
/* Extended Stage: User defined shader that affects gl_Position */
shMain();
/* 2D pos in texture space */
texImageCoord = textureUV;
/* 2D pos in paint space (Back to paint space) */
paintCoord = (paintInverted * vec3(pos, 1)).xy;
}
)glsl";
static const char* vgShaderVertexUserDefault = R"glsl(
void shMain(){ gl_Position = sh_Ortho * sh_Model * sh_Vertex; }
)glsl";
static const char* vgShaderFragmentPipeline = R"glsl(
#version 330
/*** Enum constans ************************************/
#define PAINT_TYPE_COLOR 0x1B00
#define PAINT_TYPE_LINEAR_GRADIENT 0x1B01
#define PAINT_TYPE_RADIAL_GRADIENT 0x1B02
#define PAINT_TYPE_PATTERN 0x1B03
#define DRAW_IMAGE_NORMAL 0x1F00
#define DRAW_IMAGE_MULTIPLY 0x1F01
#define DRAW_MODE_PATH 0
#define DRAW_MODE_IMAGE 1
/*** Interpolated *************************************/
in vec2 texImageCoord;
in vec2 paintCoord;
/*** Input ********************************************/
// Basic rendering Mode
uniform int drawMode;
// Image
uniform sampler2D imageSampler;
uniform int imageMode;
// Paint
uniform int paintType;
uniform vec4 paintColor;
uniform vec2 paintParams[3];
// Gradient
uniform sampler2D rampSampler;
// Pattern
uniform sampler2D patternSampler;
// Color transform
uniform vec4 scaleFactorBias[2];
/*** Output *******************************************/
//out vec4 fragColor;
/*** Built-in variables for shMain *******************************************/
vec4 sh_Color;
/*** Functions ****************************************/
// 9.3.1 Linear Gradients
float linearGradient(vec2 fragCoord, vec2 p0, vec2 p1){
float x = fragCoord.x;
float y = fragCoord.y;
float x0 = p0.x;
float y0 = p0.y;
float x1 = p1.x;
float y1 = p1.y;
float dx = x1 - x0;
float dy = y1 - y0;
return
( dx * (x - x0) + dy * (y - y0) )
/ ( dx*dx + dy*dy );
}
// 9.3.2 Radial Gradients
float radialGradient(vec2 fragCoord, vec2 centerCoord, vec2 focalCoord, float r){
float x = fragCoord.x;
float y = fragCoord.y;
float cx = centerCoord.x;
float cy = centerCoord.y;
float fx = focalCoord.x;
float fy = focalCoord.y;
float dx = x - fx;
float dy = y - fy;
float dfx = fx - cx;
float dfy = fy - cy;
return
( (dx * dfx + dy * dfy) + sqrt(r*r*(dx*dx + dy*dy) - pow(dx*dfy - dy*dfx, 2.0)) )
/ ( r*r - (dfx*dfx + dfy*dfy) );
}
// User defined shader
void shMain(void);
/*** Main thread *************************************/
void main()
{
vec4 col;
/* Stage 6: Paint Generation */
switch(paintType){
case PAINT_TYPE_LINEAR_GRADIENT:
{
vec2 x0 = paintParams[0];
vec2 x1 = paintParams[1];
float factor = linearGradient(paintCoord, x0, x1);
col = texture(rampSampler, vec2(factor, 0.5));
}
break;
case PAINT_TYPE_RADIAL_GRADIENT:
{
vec2 center = paintParams[0];
vec2 focal = paintParams[1];
float radius = paintParams[2].x;
float factor = radialGradient(paintCoord, center, focal, radius);
col = texture(rampSampler, vec2(factor, 0.5));
}
break;
case PAINT_TYPE_PATTERN:
{
float width = paintParams[0].x;
float height = paintParams[0].y;
vec2 texCoord = vec2(paintCoord.x / width, paintCoord.y / height);
col = texture(patternSampler, texCoord);
}
break;
default:
case PAINT_TYPE_COLOR:
col = paintColor;
break;
}
/* Stage 7: Image Interpolation */
if(drawMode == DRAW_MODE_IMAGE) {
col = texture(imageSampler, texImageCoord)
* (imageMode == DRAW_IMAGE_MULTIPLY ? col : vec4(1.0, 1.0, 1.0, 1.0));
}
/* Stage 8: Color Transformation, Blending, and Antialiasing */
sh_Color = col * scaleFactorBias[0] + scaleFactorBias[1] ;
/* Extended Stage: User defined shader that affects gl_FragColor */
shMain();
}
)glsl";
static const char* vgShaderFragmentUserDefault = R"glsl(
void shMain(){ gl_FragColor = sh_Color; };
)glsl";
static const char* vgShaderVertexColorRamp = R"glsl(
#version 330
in vec2 step;
in vec4 stepColor;
out vec4 interpolateColor;
void main()
{
gl_Position = vec4(step.xy, 0, 1);
interpolateColor = stepColor;
}
)glsl";
static const char* vgShaderFragmentColorRamp = R"glsl(
#version 330
in vec4 interpolateColor;
out vec4 fragColor;
void main()
{
fragColor = interpolateColor;
}
)glsl";
void shInitPiplelineShaders(void) {
VG_GETCONTEXT(VG_NO_RETVAL);
GLint compileStatus;
const char* extendedStage;
const char* buf[2];
GLint size[2];
context->vs = glCreateShader(GL_VERTEX_SHADER);
if(context->userShaderVertex){
extendedStage = (const char*)context->userShaderVertex;
} else {
extendedStage = vgShaderVertexUserDefault;
}
buf[0] = vgShaderVertexPipeline;
buf[1] = extendedStage;
size[0] = strlen(vgShaderVertexPipeline);
size[1] = strlen(extendedStage);
glShaderSource(context->vs, 2, buf, size);
glCompileShader(context->vs);
glGetShaderiv(context->vs, GL_COMPILE_STATUS, &compileStatus);
printf("Shader compile status :%d line:%d\n", compileStatus, __LINE__);
GL_CEHCK_ERROR;
context->fs = glCreateShader(GL_FRAGMENT_SHADER);
if(context->userShaderFragment){
extendedStage = (const char*)context->userShaderFragment;
} else {
extendedStage = vgShaderFragmentUserDefault;
}
buf[0] = vgShaderFragmentPipeline;
buf[1] = extendedStage;
size[0] = strlen(vgShaderFragmentPipeline);
size[1] = strlen(extendedStage);
glShaderSource(context->fs, 2, buf, size);
glCompileShader(context->fs);
glGetShaderiv(context->fs, GL_COMPILE_STATUS, &compileStatus);
printf("Shader compile status :%d line:%d\n", compileStatus, __LINE__);
GL_CEHCK_ERROR;
context->progDraw = glCreateProgram();
glAttachShader(context->progDraw, context->vs);
glAttachShader(context->progDraw, context->fs);
glLinkProgram(context->progDraw);
GL_CEHCK_ERROR;
context->locationDraw.pos = glGetAttribLocation(context->progDraw, "pos");
context->locationDraw.textureUV = glGetAttribLocation(context->progDraw, "textureUV");
context->locationDraw.model = glGetUniformLocation(context->progDraw, "sh_Model");
context->locationDraw.projection = glGetUniformLocation(context->progDraw, "sh_Ortho");
context->locationDraw.paintInverted = glGetUniformLocation(context->progDraw, "paintInverted");
context->locationDraw.drawMode = glGetUniformLocation(context->progDraw, "drawMode");
context->locationDraw.imageSampler = glGetUniformLocation(context->progDraw, "imageSampler");
context->locationDraw.imageMode = glGetUniformLocation(context->progDraw, "imageMode");
context->locationDraw.paintType = glGetUniformLocation(context->progDraw, "paintType");
context->locationDraw.rampSampler = glGetUniformLocation(context->progDraw, "rampSampler");
context->locationDraw.patternSampler = glGetUniformLocation(context->progDraw, "patternSampler");
context->locationDraw.paintParams = glGetUniformLocation(context->progDraw, "paintParams");
context->locationDraw.paintColor = glGetUniformLocation(context->progDraw, "paintColor");
context->locationDraw.scaleFactorBias= glGetUniformLocation(context->progDraw, "scaleFactorBias");
GL_CEHCK_ERROR;
// TODO: Support color transform to remove this from here
glUseProgram(context->progDraw);
GLfloat factor_bias[8] = {1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0};
glUniform4fv(context->locationDraw.scaleFactorBias, 2, factor_bias);
GL_CEHCK_ERROR;
/* Initialize uniform variables */
float mat[16];
float volume = fmax(context->surfaceWidth, context->surfaceHeight) / 2;
shCalcOrtho2D(mat, 0, context->surfaceWidth , 0, context->surfaceHeight, -volume, volume);
glUniformMatrix4fv(context->locationDraw.projection, 1, GL_FALSE, mat);
GL_CEHCK_ERROR;
}
void shDeinitPiplelineShaders(void){
VG_GETCONTEXT(VG_NO_RETVAL);
glDeleteShader(context->vs);
glDeleteShader(context->fs);
glDeleteProgram(context->progDraw);
GL_CEHCK_ERROR;
}
void shInitRampShaders(void) {
VG_GETCONTEXT(VG_NO_RETVAL);
GLint compileStatus;
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, &vgShaderVertexColorRamp, NULL);
glCompileShader(vs);
glGetShaderiv(vs, GL_COMPILE_STATUS, &compileStatus);
printf("Shader compile status :%d line:%d\n", compileStatus, __LINE__);
GL_CEHCK_ERROR;
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, &vgShaderFragmentColorRamp, NULL);
glCompileShader(fs);
glGetShaderiv(fs, GL_COMPILE_STATUS, &compileStatus);
printf("Shader compile status :%d line:%d\n", compileStatus, __LINE__);
GL_CEHCK_ERROR;
context->progColorRamp = glCreateProgram();
glAttachShader(context->progColorRamp, vs);
glAttachShader(context->progColorRamp, fs);
glLinkProgram(context->progColorRamp);
glDeleteShader(vs);
glDeleteShader(fs);
GL_CEHCK_ERROR;
context->locationColorRamp.step = glGetAttribLocation(context->progColorRamp, "step");
context->locationColorRamp.stepColor = glGetAttribLocation(context->progColorRamp, "stepColor");
GL_CEHCK_ERROR;
}
void shDeinitRampShaders(void){
VG_GETCONTEXT(VG_NO_RETVAL);
glDeleteProgram(context->progColorRamp);
}
VG_API_CALL void vgShaderSourceSH(VGuint shadertype, const VGbyte* string){
VG_GETCONTEXT(VG_NO_RETVAL);
switch(shadertype) {
case VG_FRAGMENT_SHADER_SH:
context->userShaderFragment = (const void*)string;
break;
case VG_VERTEX_SHADER_SH:
context->userShaderVertex = (const void*)string;
break;
default:
break;
}
}
VG_API_CALL void vgCompileShaderSH(void){
shDeinitPiplelineShaders();
shInitPiplelineShaders();
}
VG_API_CALL void vgUniform1fSH(VGint location, VGfloat v0){
glUniform1f(location, v0);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform2fSH(VGint location, VGfloat v0, VGfloat v1){
glUniform2f(location, v0, v1);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform3fSH(VGint location, VGfloat v0, VGfloat v1, VGfloat v2){
glUniform3f(location, v0, v1, v2);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform4fSH(VGint location, VGfloat v0, VGfloat v1, VGfloat v2, VGfloat v3){
glUniform4f(location, v0, v1, v2, v3);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform1fvSH(VGint location, VGint count, const VGfloat *value){
glUniform1fv(location, count, value);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform2fvSH(VGint location, VGint count, const VGfloat *value){
glUniform2fv(location, count, value);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform3fvSH(VGint location, VGint count, const VGfloat *value){
glUniform3fv(location, count, value);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform4fvSH(VGint location, VGint count, const VGfloat *value){
glUniform4fv(location, count, value);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniformMatrix2fvSH(VGint location, VGint count, VGboolean transpose, const VGfloat *value){
glUniformMatrix2fv(location, count, transpose, value);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniformMatrix3fvSH(VGint location, VGint count, VGboolean transpose, const VGfloat *value){
glUniformMatrix3fv(location, count, transpose, value);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniformMatrix4fvSH(VGint location, VGint count, VGboolean transpose, const VGfloat *value){
glUniformMatrix4fv(location, count, transpose, value);
GL_CEHCK_ERROR;
}
VG_API_CALL VGint vgGetUniformLocationSH(const VGbyte *name){
VG_GETCONTEXT(-1);
VGint retval = glGetUniformLocation(context->progDraw, name);
GL_CEHCK_ERROR;
return retval;
}
VG_API_CALL void vgGetUniformfvSH(VGint location, VGfloat *params){
VG_GETCONTEXT(VG_NO_RETVAL);
glGetUniformfv(context->progDraw, location, params);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform1iSH (VGint location, VGint v0){
glUniform1i (location, v0);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform2iSH (VGint location, VGint v0, VGint v1){
glUniform2i (location, v0, v1);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform3iSH (VGint location, VGint v0, VGint v1, VGint v2){
glUniform3i (location, v0, v1, v2);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform4iSH (VGint location, VGint v0, VGint v1, VGint v2, VGint v3){
glUniform4i (location, v0, v1, v2, v3);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform1ivSH (VGint location, VGint count, const VGint *value){
glUniform1iv (location, count, value);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform2ivSH (VGint location, VGint count, const VGint *value){
glUniform2iv (location, count, value);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform3ivSH (VGint location, VGint count, const VGint *value){
glUniform3iv (location, count, value);
GL_CEHCK_ERROR;
}
VG_API_CALL void vgUniform4ivSH (VGint location, VGint count, const VGint *value){
glUniform4iv (location, count, value);
GL_CEHCK_ERROR;
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright (c) 2021 Takuma Hayashi
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __SHADERS_H
#define __SHADERS_H
void shInitPiplelineShaders(void);
void shDeinitPiplelineShaders(void);
void shInitRampShaders(void);
void shDeinitRampShaders(void);
#endif /* __SHADERS_H */

View File

@@ -39,6 +39,7 @@ VG_API_CALL VGboolean vgCreateContextSH(VGint width, VGint height)
if (g_context) return VG_TRUE;
/* create new context */
// REVIEW: Memory Leak - 1,624 bytes in 1 blocks are still reachable
SH_NEWOBJ(VGContext, g_context);
if (!g_context) return VG_FALSE;

View File

@@ -22,5 +22,5 @@ simgear_scene_component(canvas-elements canvas/elements "${SOURCES}" "${HEADERS}
add_boost_test(canvas_element
SOURCES canvas_element_test.cpp
LIBRARIES ${TEST_LIBS}
LIBRARIES SimGearScene
)

View File

@@ -30,7 +30,6 @@
#include <osg/Drawable>
#include <osg/Geode>
#include <osg/StateAttribute>
#include <osg/Version>
#include <cassert>
#include <cmath>
@@ -255,7 +254,7 @@ namespace canvas
SG_LOG
(
SG_GENERAL,
SG_INFO,
SG_DEBUG,
"addEventListener(" << _node->getPath() << ", " << type_str << ")"
);
@@ -365,13 +364,7 @@ namespace canvas
// Drawables have a bounding box...
if( _drawable )
return _drawable->
#if OSG_VERSION_LESS_THAN(3,3,2)
getBound()
#else
getBoundingBox()
#endif
.contains(osg::Vec3f(local_pos, 0));
return _drawable->getBoundingBox().contains(osg::Vec3f(local_pos, 0));
else if( _scene_group.valid() )
// ... for other elements, i.e. groups only a bounding sphere is available
return _scene_group->getBound().contains(osg::Vec3f(parent_pos, 0));
@@ -643,11 +636,7 @@ namespace canvas
osg::BoundingBox Element::getBoundingBox() const
{
if( _drawable )
#if OSG_VERSION_LESS_THAN(3,3,2)
return _drawable->getBound();
#else
return _drawable->getBoundingBox();
#endif
osg::BoundingBox bb;
@@ -670,12 +659,7 @@ namespace canvas
return osg::BoundingBox();
osg::BoundingBox transformed;
const osg::BoundingBox& bb =
#if OSG_VERSION_LESS_THAN(3,3,2)
_drawable->getBound();
#else
_drawable->getBoundingBox();
#endif
const osg::BoundingBox& bb = _drawable->getBoundingBox();
for(int i = 0; i < 4; ++i)
transformed.expandBy( bb.corner(i) * m );
@@ -753,7 +737,7 @@ namespace canvas
return true;
// Parent values do not override if element has own value
return isStyleEmpty( _node->getChild(child->getName()) );
return isStyleEmpty( _node->getChild(child->getNameString()) );
}
//----------------------------------------------------------------------------

View File

@@ -414,7 +414,7 @@ namespace canvas
void (Derived::*setter)(const std::string&),
bool inheritable = true )
{
return addStyle<const char*, const std::string&>
return addStyle<std::string, const std::string&>
(
name,
type,
@@ -507,7 +507,7 @@ namespace canvas
OtherRef Derived::*instance_ref,
bool inheritable = true )
{
return addStyle<const char*, const std::string&>
return addStyle<std::string, const std::string&>
(
name,
type,

View File

@@ -120,7 +120,7 @@ namespace canvas
SG_GENERAL,
SG_WARN,
"Group::getOrCreateChild: type missmatch! "
"('" << type << "' != '" << child->getProps()->getName() << "', "
"('" << type << "' != '" << child->getProps()->getNameString() << "', "
"id = '" << id << "')"
);

View File

@@ -35,6 +35,7 @@
#include <osg/PrimitiveSet>
#include <osgDB/Registry>
#include <osg/Version>
#include <simgear/scene/util/SGReaderWriterOptions.hxx>
namespace simgear
{
@@ -179,13 +180,7 @@ namespace canvas
&& child->getNameString() == "visible"
&& child->getBoolValue() )
{
CullCallback* cb =
#if OSG_VERSION_LESS_THAN(3,3,2)
static_cast<CullCallback*>
#else
dynamic_cast<CullCallback*>
#endif
( _geom->getCullCallback() );
CullCallback* cb = dynamic_cast<CullCallback*>( _geom->getCullCallback() );
if( cb )
cb->cullNextFrame();
@@ -824,8 +819,12 @@ namespace canvas
{
SG_LOG(SG_IO, SG_DEBUG, "use image reader detected by " << type);
osg::ref_ptr<SGReaderWriterOptions> opt;
opt = SGReaderWriterOptions::copyOrCreate(osgDB::Registry::instance()->getOptions());
opt->setLoadOriginHint(SGReaderWriterOptions::LoadOriginHint::ORIGIN_CANVAS);
std::istringstream data_strm(data);
osgDB::ReaderWriter::ReadResult result = reader.readImage(data_strm);
osgDB::ReaderWriter::ReadResult result = reader.readImage(data_strm, opt);
if( result.success() )
{
setImage( result.takeImage() );
@@ -850,7 +849,7 @@ namespace canvas
void fillRow(GLubyte* row, GLuint pixel, GLuint width, GLuint pixelBytes)
{
GLubyte* dst = row;
for (int x = 0; x < width; ++x) {
for (GLuint x = 0; x < width; ++x) {
memcpy(dst, &pixel, pixelBytes);
dst += pixelBytes;
}

View File

@@ -142,7 +142,7 @@ namespace canvas
if( strutils::ends_with(child->getNameString(), GEO) )
// TODO remove from other node
_geo_nodes.erase(child);
else if( parent != _node && child->getName() == HDG )
else if( parent != _node && child->getNameString() == HDG )
{
_hdg_nodes.erase(child);

View File

@@ -24,7 +24,6 @@
#include <simgear/misc/strutils.hxx>
#include <osg/Drawable>
#include <osg/Version>
#include <vg/openvg.h>
#include <cassert>
@@ -559,12 +558,8 @@ namespace canvas
/**
* Compute the bounding box
*/
osg::BoundingBox
#if OSG_VERSION_LESS_THAN(3,3,2)
computeBound()
#else
computeBoundingBox()
#endif
osg::BoundingBox computeBoundingBox()
const override
{
if( _path == VG_INVALID_HANDLE || (_attributes_dirty & PATH) )

View File

@@ -61,11 +61,7 @@ namespace canvas
SGVec2i sizeForWidth(int w);
#endif
#if OSG_VERSION_LESS_THAN(3,3,2)
osg::BoundingBox computeBound() const override;
#else
osg::BoundingBox computeBoundingBox() const override;
#endif
protected:
friend class TextLine;
@@ -173,13 +169,9 @@ namespace canvas
#if OSG_VERSION_GREATER_OR_EQUAL(3,5,6)
// TODO: need 3.5.6 version of this.
#else
#if OSG_VERSION_LESS_THAN(3,3,5)
GlyphQuads::Coords2 const& coords = _quads->_coords;
#else
GlyphQuads::Coords2 refCoords = _quads->_coords;
GlyphQuads::Coords2::element_type &coords = *refCoords.get();
#endif
size_t global_i = _begin + i;
@@ -217,13 +209,9 @@ namespace canvas
#if OSG_VERSION_GREATER_OR_EQUAL(3,5,6)
// TODO: need 3.5.7 version of this.
return cursorPos(0);
#else
#if OSG_VERSION_LESS_THAN(3,3,5)
GlyphQuads::Coords2 const& coords = _quads->_coords;
#else
GlyphQuads::Coords2 refCoords = _quads->_coords;
GlyphQuads::Coords2::element_type &coords = *refCoords.get();
#endif
GlyphQuads::Glyphs const& glyphs = _quads->_glyphs;
@@ -649,28 +637,9 @@ namespace canvas
}
//----------------------------------------------------------------------------
#if OSG_VERSION_LESS_THAN(3,3,2)
osg::BoundingBox Text::TextOSG::computeBound() const
#else
osg::BoundingBox Text::TextOSG::computeBoundingBox() const
#endif
{
#if OSG_VERSION_LESS_THAN(3,3,2)
osg::BoundingBox bb = osgText::Text::computeBound();
#else
osg::BoundingBox bb = osgText::Text::computeBoundingBox();
#endif
#if OSG_VERSION_LESS_THAN(3,1,0)
if( bb.valid() )
{
// TODO bounding box still doesn't seem always right (eg. with center
// horizontal alignment not completely accurate)
bb._min.y() += _offset.y();
bb._max.y() += _offset.y();
}
#endif
osg::BoundingBox bb = osgText::Text::computeBoundingBox();
return bb;
}
@@ -685,12 +654,8 @@ namespace canvas
const GlyphQuads& quads = _textureGlyphQuadMap.begin()->second;
const GlyphQuads::Glyphs& glyphs = quads._glyphs;
#if OSG_VERSION_LESS_THAN(3,3,5)
GlyphQuads::Coords2 const& coords = quads._coords;
#else
GlyphQuads::Coords2 refCoords = quads._coords;
GlyphQuads::Coords2::element_type &coords = *refCoords.get();
#endif
const GlyphQuads::LineNumbers& line_numbers = quads._lineNumbers;
@@ -818,21 +783,20 @@ namespace canvas
}
//----------------------------------------------------------------------------
void Text::setText(const char* text)
void Text::setText(const std::string &text)
{
_text->setText(text, osgText::String::ENCODING_UTF8);
}
//----------------------------------------------------------------------------
void Text::setFont(const char* name)
void Text::setFont(const std::string& name)
{
_text->setFont( Canvas::getSystemAdapter()->getFont(name) );
}
//----------------------------------------------------------------------------
void Text::setAlignment(const char* align)
void Text::setAlignment(const std::string& align_string)
{
const std::string align_string(align);
if( 0 ) return;
#define ENUM_MAPPING(enum_val, string_val) \
else if( align_string == string_val )\

View File

@@ -44,9 +44,9 @@ namespace canvas
ElementWeakPtr parent = 0 );
~Text();
void setText(const char* text);
void setFont(const char* name);
void setAlignment(const char* align);
void setText(const std::string& text);
void setFont(const std::string& name);
void setAlignment(const std::string& align_string);
int heightForWidth(int w) const;
int maxWidth() const;

View File

@@ -89,12 +89,12 @@ namespace canvas
}
}
const char* getLat() const
std::string getLat() const
{
return _node_lat ? _node_lat->getStringValue() : "";
}
const char* getLon() const
std::string getLon() const
{
return _node_lon ? _node_lon->getStringValue() : "";
}

View File

@@ -18,11 +18,10 @@ simgear_scene_component(canvas-events canvas/events "${SOURCES}" "${HEADERS}")
add_boost_test(canvas_event
SOURCES event_test.cpp
LIBRARIES ${TEST_LIBS}
LIBRARIES SimGearScene
)
add_executable(input_event_demo input_event_demo.cxx)
add_simgear_test(input_event_demo input_event_demo.cxx)
target_link_libraries(input_event_demo
${TEST_LIBS}
${OPENSCENEGRAPH_LIBRARIES}
SimGearScene
)

View File

@@ -27,6 +27,41 @@ namespace simgear
namespace canvas
{
//----------------------------------------------------------------------------
void BoxLayout::ItemData::reset()
{
layout_item = 0;
size_hint = 0;
min_size = 0;
max_size = 0;
padding_orig = 0;
padding = 0;
size = 0;
stretch = 0;
visible = false;
has_align = false;
has_hfw = false;
done = false;
}
//----------------------------------------------------------------------------
int BoxLayout::ItemData::hfw(int w) const
{
if (has_hfw)
return layout_item->heightForWidth(w);
else
return layout_item->sizeHint().y();
}
//----------------------------------------------------------------------------
int BoxLayout::ItemData::mhfw(int w) const
{
if (has_hfw)
return layout_item->minimumHeightForWidth(w);
else
return layout_item->minimumSize().y();
}
//----------------------------------------------------------------------------
BoxLayout::BoxLayout(Direction dir):
_padding(5)
@@ -73,7 +108,7 @@ namespace canvas
int stretch,
uint8_t alignment )
{
ItemData item_data = {0};
ItemData item_data = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
item_data.layout_item = item;
item_data.stretch = std::max(0, stretch);
@@ -506,6 +541,197 @@ namespace canvas
callSetVisibleInternal(_layout_items[i].layout_item.get(), visible);
}
//----------------------------------------------------------------------------
void BoxLayout::distribute(LayoutItems& items, const ItemData& space)
{
const int num_children = static_cast<int>(items.size());
_num_not_done = 0;
SG_LOG(SG_GUI,
SG_DEBUG,
"BoxLayout::distribute(" << space.size << "px for "
<< num_children << " items, s.t."
<< " min=" << space.min_size
<< ", hint=" << space.size_hint
<< ", max=" << space.max_size << ")");
if (space.size < space.min_size) {
// TODO
SG_LOG(SG_GUI, SG_WARN, "BoxLayout: not enough size (not implemented)");
} else if (space.size < space.max_size) {
_sum_stretch = 0;
_space_stretch = 0;
bool less_then_hint = space.size < space.size_hint;
// Give min_size/size_hint to all items
_space_left = space.size - (less_then_hint ? space.min_size : space.size_hint);
for (int i = 0; i < num_children; ++i) {
ItemData& d = items[i];
if (!d.visible)
continue;
d.size = less_then_hint ? d.min_size : d.size_hint;
d.padding = d.padding_orig;
d.done = d.size >= (less_then_hint ? d.size_hint : d.max_size);
SG_LOG(
SG_GUI,
SG_DEBUG,
i << ") initial=" << d.size
<< ", min=" << d.min_size
<< ", hint=" << d.size_hint
<< ", max=" << d.max_size);
if (d.done)
continue;
_num_not_done += 1;
if (d.stretch > 0) {
_sum_stretch += d.stretch;
_space_stretch += d.size;
}
}
// Distribute remaining space to increase the size of each item up to its
// size_hint/max_size
while (_space_left > 0) {
if (_num_not_done <= 0) {
SG_LOG(SG_GUI, SG_WARN, "space left, but no more items?");
break;
}
int space_per_element = std::max(1, _space_left / _num_not_done);
SG_LOG(SG_GUI, SG_DEBUG, "space/element=" << space_per_element);
for (int i = 0; i < num_children; ++i) {
ItemData& d = items[i];
if (!d.visible)
continue;
SG_LOG(
SG_GUI,
SG_DEBUG,
i << ") left=" << _space_left
<< ", not_done=" << _num_not_done
<< ", sum=" << _sum_stretch
<< ", stretch=" << _space_stretch
<< ", stretch/unit=" << _space_stretch / std::max(1, _sum_stretch));
if (d.done)
continue;
if (_sum_stretch > 0 && d.stretch <= 0)
d.done = true;
else {
int target_size = 0;
int max_size = less_then_hint ? d.size_hint : d.max_size;
if (_sum_stretch > 0) {
target_size = (d.stretch * (_space_left + _space_stretch)) / _sum_stretch;
// Item would be smaller than minimum size or larger than maximum
// size, so just keep bounded size and ignore stretch factor
if (target_size <= d.size || target_size >= max_size) {
d.done = true;
_sum_stretch -= d.stretch;
_space_stretch -= d.size;
if (target_size >= max_size)
target_size = max_size;
else
target_size = d.size;
} else
_space_stretch += target_size - d.size;
} else {
// Give space evenly to all remaining elements in this round
target_size = d.size + std::min(_space_left, space_per_element);
if (target_size >= max_size) {
d.done = true;
target_size = max_size;
}
}
int old_size = d.size;
d.size = target_size;
_space_left -= d.size - old_size;
}
if (d.done) {
_num_not_done -= 1;
if (_sum_stretch <= 0 && d.stretch > 0)
// Distribute remaining space evenly to all non-stretchable items
// in a new round
break;
}
}
}
} else {
_space_left = space.size - space.max_size;
int num_align = 0;
for (int i = 0; i < num_children; ++i) {
if (!items[i].visible)
continue;
_num_not_done += 1;
if (items[i].has_align)
num_align += 1;
}
SG_LOG(
SG_GUI,
SG_DEBUG,
"Distributing excess space:"
" not_done="
<< _num_not_done
<< ", num_align=" << num_align
<< ", space_left=" << _space_left);
for (int i = 0; i < num_children; ++i) {
ItemData& d = items[i];
if (!d.visible)
continue;
d.padding = d.padding_orig;
d.size = d.max_size;
int space_add = 0;
if (d.has_align) {
// Equally distribute superfluous space and let each child items
// alignment handle the exact usage.
space_add = _space_left / num_align;
num_align -= 1;
d.size += space_add;
} else if (num_align <= 0) {
// Add superfluous space as padding
space_add = _space_left
// Padding after last child...
/ (_num_not_done + 1);
_num_not_done -= 1;
d.padding += space_add;
}
_space_left -= space_add;
}
}
SG_LOG(SG_GUI, SG_DEBUG, "distribute:");
for (int i = 0; i < num_children; ++i) {
ItemData const& d = items[i];
if (d.visible)
SG_LOG(SG_GUI, SG_DEBUG, i << ") pad=" << d.padding << ", size= " << d.size);
else
SG_LOG(SG_GUI, SG_DEBUG, i << ") [hidden]");
}
}
//----------------------------------------------------------------------------
HBoxLayout::HBoxLayout():
BoxLayout(LeftToRight)

View File

@@ -102,39 +102,74 @@ namespace canvas
bool horiz() const;
protected:
struct ItemData {
LayoutItemRef layout_item;
int size_hint,
min_size,
max_size,
padding_orig, //!< original padding as specified by the user
padding, //!< padding before element (layouted)
size, //!< layouted size
stretch; //!< stretch factor
bool visible : 1,
has_align : 1, //!< Has alignment factor set (!= AlignFill)
has_hfw : 1, //!< height for width
done : 1; //!< layouting done
typedef const int& (SGVec2i::*CoordGetter)() const;
CoordGetter _get_layout_coord, //!< getter for coordinate in layout
// direction
_get_fixed_coord; //!< getter for coordinate in secondary
// (fixed) direction
/** Clear values (reset to default/empty state) */
void reset();
int _padding;
Direction _direction;
int hfw(int w) const;
int mhfw(int w) const;
};
typedef std::vector<ItemData> LayoutItems;
using LayoutItems = std::vector<ItemData>;
mutable LayoutItems _layout_items;
mutable ItemData _layout_data;
/**
* Distribute the available @a space to all @a items
*/
void distribute(LayoutItems& items, const ItemData& space);
// Cache for last height-for-width query
mutable int _hfw_width,
_hfw_height,
_hfw_min_height;
void updateSizeHints() const;
void updateWFHCache(int w) const;
typedef const int& (SGVec2i::*CoordGetter)() const;
CoordGetter _get_layout_coord, //!< getter for coordinate in layout
// direction
_get_fixed_coord; //!< getter for coordinate in secondary
// (fixed) direction
virtual SGVec2i sizeHintImpl() const;
virtual SGVec2i minimumSizeImpl() const;
virtual SGVec2i maximumSizeImpl() const;
int _padding;
Direction _direction;
virtual int heightForWidthImpl(int w) const;
virtual int minimumHeightForWidthImpl(int w) const;
virtual void doLayout(const SGRecti& geom);
mutable LayoutItems _layout_items;
mutable ItemData _layout_data;
virtual void visibilityChanged(bool visible);
// Cache for last height-for-width query
mutable int _hfw_width,
_hfw_height,
_hfw_min_height;
void updateSizeHints() const;
void updateWFHCache(int w) const;
virtual SGVec2i sizeHintImpl() const;
virtual SGVec2i minimumSizeImpl() const;
virtual SGVec2i maximumSizeImpl() const;
virtual int heightForWidthImpl(int w) const;
virtual int minimumHeightForWidthImpl(int w) const;
virtual void doLayout(const SGRecti& geom);
virtual void visibilityChanged(bool visible);
private:
int _num_not_done = 0, //!< number of children not layouted yet
_sum_stretch = 0, //!< sum of stretch factors of all not yet layouted
// children
_space_stretch = 0, //!< space currently assigned to all not yet layouted
// stretchable children
_space_left = 0; //!< remaining space not used by any child yet
};
/**

View File

@@ -3,6 +3,7 @@ include (SimGearComponent)
set(HEADERS
AlignFlag_values.hxx
BoxLayout.hxx
GridLayout.hxx
Layout.hxx
LayoutItem.hxx
NasalWidget.hxx
@@ -11,6 +12,7 @@ set(HEADERS
set(SOURCES
BoxLayout.cxx
GridLayout.cxx
Layout.cxx
LayoutItem.cxx
NasalWidget.cxx
@@ -21,5 +23,5 @@ simgear_scene_component(canvas-layout canvas/layout "${SOURCES}" "${HEADERS}")
add_boost_test(canvas_layout
SOURCES canvas_layout_test.cxx
LIBRARIES ${TEST_LIBS}
LIBRARIES SimGearScene
)

View File

@@ -0,0 +1,693 @@
// GridLayout.cxx - grid layout for Canvas, closely
// modelled on the equivalent layouts in Gtk/Qt
// Copyright (C) 2022 James Turner
// SPDX-License-Identifier: LGPL-2.0-or-later
#include <simgear_config.h>
#include "GridLayout.hxx"
#include "SpacerItem.hxx"
#include <simgear/canvas/Canvas.hxx>
namespace simgear {
namespace canvas {
// see https://code.qt.io/cgit/qt/qtbase.git/tree/src/widgets/kernel/qgridlayout.cpp?h=dev
// for similar code :)
static bool isValidLocation(const SGVec2i& loc)
{
return loc.x() >= 0 && loc.y() >= 0;
}
//----------------------------------------------------------------------------
void GridLayout::ItemData::reset()
{
layout_item = 0;
size = {};
visible = false;
has_align = false;
has_hfw = false;
done = false;
}
void GridLayout::RowColumnData::resetSizeData()
{
minSize = 0;
hintSize = 0;
maxSize = 0;
calcStretch = stretch;
calcSize = 0;
calcStart = 0;
padding = 0;
hasVisible = false;
}
bool GridLayout::ItemData::containsCell(const SGVec2i& cell) const
{
return (layout_item->gridLocation().x() <= cell.x()) &&
(layout_item->gridLocation().y() <= cell.y()) &&
(layout_item->gridEnd().x() >= cell.x()) &&
(layout_item->gridEnd().y() >= cell.y());
}
//----------------------------------------------------------------------------
GridLayout::GridLayout()
{
// FIXME : share default padding value with BoxLayout
}
//----------------------------------------------------------------------------
GridLayout::~GridLayout()
{
_parent.reset(); // No need to invalidate parent again...
clear();
}
//----------------------------------------------------------------------------
void GridLayout::addItem(const LayoutItemRef& item, int column, int row, int colSpan, int rowSpan)
{
item->setGridLocation({column, row});
item->setGridSpan({colSpan, rowSpan});
addItem(item);
}
//----------------------------------------------------------------------------
void GridLayout::addItem(const LayoutItemRef& item)
{
if (isValidLocation(item->gridLocation())) {
// re-dimension as required
const auto itemEnd = item->gridEnd();
if (itemEnd.x() >= static_cast<int>(numColumns())) {
// expand columns
_dimensions.x() = itemEnd.x() + 1;
_columns.resize(_dimensions.x());
}
if (itemEnd.y() >= static_cast<int>(numRows())) {
// expand rows
_dimensions.y() = itemEnd.y() + 1;
_rows.resize(_dimensions.y());
}
} else {
// find first empty grid slot and use
auto loc = innerFindUnusedLocation(item->gridLocation());
}
ItemData d;
d.reset();
d.layout_item = item;
if (SGWeakReferenced::count(this)) {
item->setParent(this);
} else {
SG_LOG(SG_GUI,
SG_DEV_WARN,
"Adding item to expired or non-refcounted grid layout");
}
_layout_items.push_back(d);
invalidate();
}
void GridLayout::invalidate()
{
Layout::invalidate();
_cells.clear();
}
SGVec2i GridLayout::innerFindUnusedLocation(const SGVec2i& curLoc)
{
updateCells(); // build the cell-map on demand
// TODO: this code does work for spanning items yet, only for single cell items.
// special case: row was specified, but not column. This means only
// search that row, and maybe extend our dimension if there's no free slots
if (curLoc.y() >= 0) {
// TODO: implement me :)
}
const auto stride = _dimensions.x();
for (int j = 0; j < _dimensions.y(); ++j) {
for (int i = 0; i < stride; ++i) {
const auto ii = _cells.at(j * stride + i);
if (ii < 0) {
return {i, j};
}
}
}
// grid is full, add a new row on the bottom and return first column
// of it as our unused location.
_dimensions.y() += 1;
_rows.resize(_dimensions.y());
return {0, _dimensions.y() - 1};
}
void GridLayout::updateCells()
{
const auto dim = _dimensions.x() * _dimensions.y();
if (static_cast<int>(_cells.size()) == dim) {
return;
}
_cells.resize(dim);
const auto stride = _dimensions.x();
std::fill(_cells.begin(), _cells.end(), -1);
int itemIndex = 0;
for (auto& item : _layout_items) {
const auto topLeftCell = item.layout_item->gridLocation();
const auto bottomRightCell = item.layout_item->gridEnd();
for (int row = topLeftCell.y(); row <= bottomRightCell.y(); ++row) {
for (int cell = topLeftCell.x(); cell <= bottomRightCell.x(); ++cell) {
_cells[row * stride + cell] = itemIndex;
}
}
++itemIndex;
}
}
GridLayout::LayoutItems::iterator GridLayout::itemInCell(const SGVec2i& cell)
{
updateCells();
const auto stride = _dimensions.x();
const auto index = _cells.at(cell.y() * stride + cell.x());
if (index < 0)
return _layout_items.end();
return _layout_items.begin() + index;
}
GridLayout::LayoutItems::iterator GridLayout::firstInRow(int row)
{
updateCells();
const auto stride = _dimensions.x();
for (int col = 0; col < _dimensions.y(); ++col) {
if (_cells.at(row * stride + col) >= 0) {
return itemInCell({col, row});
}
}
return _layout_items.end();
}
//----------------------------------------------------------------------------
// void BoxLayout::insertItem( int index,
// const LayoutItemRef& item,
// int stretch,
// uint8_t alignment )
// {
// ItemData item_data = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// item_data.layout_item = item;
// item_data.stretch = std::max(0, stretch);
// if( alignment != AlignFill )
// item->setAlignment(alignment);
// if( SGWeakReferenced::count(this) )
// item->setParent(this);
// else
// SG_LOG( SG_GUI,
// SG_WARN,
// "Adding item to expired or non-refcounted layout" );
// if( index < 0 )
// _layout_items.push_back(item_data);
// else
// _layout_items.insert(_layout_items.begin() + index, item_data);
// invalidate();
// }
//----------------------------------------------------------------------------
size_t GridLayout::count() const
{
return _layout_items.size();
}
//----------------------------------------------------------------------------
LayoutItemRef GridLayout::itemAt(size_t index)
{
if (index >= _layout_items.size())
return {};
return _layout_items[index].layout_item;
}
//----------------------------------------------------------------------------
LayoutItemRef GridLayout::takeAt(size_t index)
{
if (index >= _layout_items.size())
return {};
auto it = _layout_items.begin() + index;
LayoutItemRef item = it->layout_item;
item->onRemove();
item->setParent(LayoutItemWeakRef());
_layout_items.erase(it);
invalidate();
return item;
}
//----------------------------------------------------------------------------
void GridLayout::clear()
{
std::for_each(_layout_items.begin(), _layout_items.end(), [](ItemData item) {
item.layout_item->onRemove();
item.layout_item->setParent({});
});
_layout_items.clear();
invalidate();
}
//----------------------------------------------------------------------------
void GridLayout::setSpacing(int spacing)
{
if (spacing == _padding)
return;
_padding = spacing;
invalidate();
}
//----------------------------------------------------------------------------
int GridLayout::spacing() const
{
return _padding;
}
//----------------------------------------------------------------------------
void GridLayout::setCanvas(const CanvasWeakPtr& canvas)
{
_canvas = canvas;
for (size_t i = 0; i < _layout_items.size(); ++i)
_layout_items[i].layout_item->setCanvas(canvas);
}
//----------------------------------------------------------------------------
void GridLayout::setDimensions(const SGVec2i& dim)
{
_dimensions = {
std::max(dim.x(), _dimensions.x()),
std::max(dim.y(), _dimensions.y())};
invalidate();
}
//----------------------------------------------------------------------------
size_t GridLayout::numRows() const
{
return _dimensions.y();
}
//----------------------------------------------------------------------------
size_t GridLayout::numColumns() const
{
return _dimensions.x();
}
//----------------------------------------------------------------------------
void GridLayout::setRowStretch(size_t index, int stretch)
{
if (static_cast<int>(index) >= _dimensions.y()) {
throw sg_range_exception("GridLayout::setRowStretch: invalid row");
}
if (stretch < 0) {
throw sg_range_exception("GridLayout: negative stretch values are forbidden");
}
// becuase we lazily update the rows data, we'd have nowhere to store the
// new stretch value, so actively resize it now.
if (index >= _rows.size()) {
_rows.resize(_dimensions.y());
}
_rows[index].stretch = stretch;
invalidate();
}
//----------------------------------------------------------------------------
void GridLayout::setColumnStretch(size_t index, int stretch)
{
if (static_cast<int>(index) >= _dimensions.x()) {
throw sg_range_exception("GridLayout::setColumnStretch: invalid column");
}
if (stretch < 0) {
throw sg_range_exception("GridLayout: negative stretch values are forbidden");
}
// becuase we lazily update the columns data, we'd have nowhere to store the
// new stretch value, so actively resize it now.
if (index >= _columns.size()) {
_columns.resize(_dimensions.x());
}
_columns[index].stretch = stretch;
invalidate();
}
//----------------------------------------------------------------------------
void GridLayout::updateSizeHints() const
{
_columns.resize(_dimensions.x());
_rows.resize(_dimensions.y());
// pre-pass: reset row/column data, compute stretch totals
int totalRowStretch = 0, totalColStretch = 0;
for (auto& r : _rows) {
r.resetSizeData();
totalRowStretch += r.stretch;
}
for (auto& c : _columns) {
c.resetSizeData();
totalColStretch += c.stretch;
}
// if no row/column has any stretch set, use '1' for every row/column
// this means we don't need to special case this in all the rest of the code
if (totalColStretch == 0) {
std::for_each(_columns.begin(), _columns.end(), [](RowColumnData& a) {
a.calcStretch = 1;
});
totalColStretch = _columns.size();
}
if (totalRowStretch == 0) {
std::for_each(_rows.begin(), _rows.end(), [](RowColumnData& a) {
a.calcStretch = 1;
});
totalRowStretch = _rows.size();
}
// first pass: do span=1 items, where the child size values
// can be mapped directly to the row/column
for (auto& i : _layout_items) {
if (!i.layout_item->isVisible()) {
continue;
}
const bool isSpacer = dynamic_cast<SpacerItem*>(i.layout_item.get()) != nullptr;
const auto minSize = i.layout_item->minimumSize();
const auto hint = i.layout_item->sizeHint();
const auto maxSize = i.layout_item->maximumSize();
// TODO: check hfw status of item
const auto span = i.layout_item->gridSpan();
const auto loc = i.layout_item->gridLocation();
if (span.x() == 1) {
auto& cd = _columns[loc.x()];
cd.minSize = std::max(cd.minSize, minSize.x());
cd.hintSize = std::max(cd.hintSize, hint.x());
cd.hasVisible |= !isSpacer;
if (maxSize.x() < MAX_SIZE.x()) {
cd.maxSize = std::max(cd.maxSize, maxSize.x());
}
}
if (span.y() == 1) {
auto& rd = _rows[loc.y()];
rd.minSize = std::max(rd.minSize, minSize.y());
rd.hintSize = std::max(rd.hintSize, hint.y());
rd.hasVisible |= !isSpacer;
if (maxSize.y() < MAX_SIZE.y()) {
rd.maxSize = std::max(rd.maxSize, maxSize.y());
}
}
} // of span=1 items
// second pass: spanning directions of items: add remaining min/hint size
// based on stretch factors. Doing this as a second pass means only add on
// the extra hint amounts, which depending on span=1 items, might not be
// very much at all
//
// when padding is specified for the grid, we need to remove the spanned
// padding from our hint/min sizes, since this will always be added back
// on to the geometry when laying out
for (auto& i : _layout_items) {
if (!i.layout_item->isVisible()) {
continue;
}
const auto minSize = i.layout_item->minimumSize();
const auto hint = i.layout_item->sizeHint();
const auto span = i.layout_item->gridSpan();
const auto loc = i.layout_item->gridLocation();
if (span.x() > 1) {
int spanStretch = 0;
int spanMinSize = 0;
int spanHint = 0;
for (int c = loc.x(); c < loc.x() + span.x(); ++c) {
spanStretch += _columns.at(c).calcStretch;
spanMinSize += _columns.at(c).minSize;
spanHint += _columns.at(c).hintSize;
}
// add spanned padding onto these totals as part of the 'space we
// already get' and hence don't need assign as extra below
const int spannedPadding = (span.x() - 1) * _padding;
spanHint += spannedPadding;
spanMinSize += spannedPadding;
// no stretch defined, just divide equally. This is not ideal
// but the user should specify stretch to get the result they
// want
if (spanStretch == 0) {
spanStretch = span.x();
}
int extraMinSize = minSize.x() - spanMinSize;
int extraSizeHint = hint.x() - spanHint;
for (int c = loc.x(); c < loc.x() + span.x(); ++c) {
auto& cd = _columns[c];
if (extraMinSize > 0) {
cd.minSize += extraMinSize * cd.calcStretch / spanStretch;
}
if (extraSizeHint > 0) {
cd.hintSize += extraSizeHint * cd.calcStretch / spanStretch;
}
}
}
if (span.y() > 1) {
int spanStretch = 0;
int spanMinSize = 0;
int spanHint = 0;
for (int r = loc.y(); r < loc.y() + span.y(); ++r) {
spanStretch += _rows.at(r).calcStretch;
spanMinSize += _rows.at(r).minSize;
spanHint += _rows.at(r).hintSize;
}
// add spanned padding onto these totals as part of the 'space we
// already get' and hence don't need assign as extra below
const int spannedPadding = (span.y() - 1) * _padding;
spanHint += spannedPadding;
spanMinSize += spannedPadding;
if (spanStretch == 0) {
spanStretch = span.y();
}
int extraMinSize = minSize.y() - spanMinSize;
int extraSizeHint = hint.y() - spanHint;
for (int r = loc.y(); r < loc.y() + span.y(); ++r) {
auto& rd = _rows[r];
if (extraMinSize > 0) {
rd.minSize += extraMinSize * rd.calcStretch / spanStretch;
}
if (extraSizeHint > 0) {
rd.hintSize += extraSizeHint * rd.calcStretch / spanStretch;
}
}
}
} // of second items iteratio
_min_size = {0, 0};
_max_size = MAX_SIZE;
_size_hint = {0, 0};
bool isFirst = true;
for (auto& rd : _rows) {
_min_size.y() += rd.minSize;
// TODO: handle max-size correctly
// _max_size.y() +=
_size_hint.y() += rd.hintSize;
if (isFirst) {
isFirst = false;
} else if (rd.hasVisible) {
rd.padding = _padding;
}
}
isFirst = true;
for (auto& cd : _columns) {
_min_size.x() += cd.minSize;
// TODO: handle max-size correctly
// _max_size.x() +=
_size_hint.x() += cd.hintSize;
if (isFirst) {
isFirst = false;
} else if (cd.hasVisible) {
cd.padding = _padding;
}
}
_flags &= ~SIZE_INFO_DIRTY;
}
//----------------------------------------------------------------------------
SGVec2i GridLayout::sizeHintImpl() const
{
updateSizeHints();
return _size_hint;
}
//----------------------------------------------------------------------------
SGVec2i GridLayout::minimumSizeImpl() const
{
updateSizeHints();
return _min_size;
}
//----------------------------------------------------------------------------
SGVec2i GridLayout::maximumSizeImpl() const
{
updateSizeHints();
return _max_size;
}
//----------------------------------------------------------------------------
void GridLayout::doLayout(const SGRecti& geom)
{
if (_flags & SIZE_INFO_DIRTY)
updateSizeHints();
int availWidth = geom.width();
int availHeight = geom.height();
// compute extra available space
int rowStretchTotal = 0;
int columnStretchTotal = 0;
SGVec2i totalMinSize = {0, 0},
totalPreferredSize = {0, 0};
for (auto row = 0; row < static_cast<int>(_rows.size()); ++row) {
totalMinSize.y() += _rows.at(row).minSize;
totalPreferredSize.y() += _rows.at(row).hintSize;
rowStretchTotal += _rows.at(row).calcStretch;
availHeight -= _rows.at(row).padding;
}
for (auto col = 0; col < static_cast<int>(_columns.size()); ++col) {
totalMinSize.x() += _columns.at(col).minSize;
totalPreferredSize.x() += _columns.at(col).hintSize;
columnStretchTotal += _columns.at(col).calcStretch;
availWidth -= _columns.at(col).padding;
}
SGVec2i toDistribute = {0, 0};
bool havePreferredWidth = false,
havePreferredHeight = false;
if (availWidth >= totalPreferredSize.x()) {
havePreferredWidth = true;
toDistribute.x() = availWidth - totalPreferredSize.x();
} else if (availWidth >= totalMinSize.x()) {
toDistribute.x() = availWidth - totalMinSize.x();
} else {
// available width is less than min, we will overflow
}
if (availHeight >= totalPreferredSize.y()) {
havePreferredHeight = true;
toDistribute.y() = availHeight - totalPreferredSize.y();
} else if (geom.height() >= totalMinSize.y()) {
toDistribute.y() = availHeight - totalMinSize.y();
} else {
// available height is less than min, we will overflow
}
// distribute according to stretch factors
for (auto col = 0; col < static_cast<int>(_columns.size()); ++col) {
auto& c = _columns[col];
c.calcSize = havePreferredWidth ? c.hintSize : c.minSize;
c.calcSize += (toDistribute.x() * c.calcStretch) / columnStretchTotal;
// compute running total of size to give us the actual start coordinate
if (col > 0) {
c.calcStart = _columns.at(col - 1).calcStart + _columns.at(col - 1).calcSize + c.padding;
}
}
// TODO: apply height-for-width to all items, to calculate real heights now
// re-calcualate row min/preferred now? Or is it not dependant?
for (auto row = 0; row < static_cast<int>(_rows.size()); ++row) {
auto& r = _rows[row];
r.calcSize = havePreferredHeight ? r.hintSize : r.minSize;
r.calcSize += (toDistribute.y() * r.calcStretch) / rowStretchTotal;
if (row > 0) {
r.calcStart = _rows.at(row - 1).calcStart + _rows.at(row - 1).calcSize + r.padding;
}
}
// set layout-ed geometry on items
for (auto& i : _layout_items) {
const auto loc = i.layout_item->gridLocation();
// from the end location, we can use the start+size to ensure all padding
// etc, in between was covered, since we already summed those above.
const auto end = i.layout_item->gridEnd();
const auto& endRow = _rows.at(end.y());
const auto& endCol = _columns.at(end.x());
// note this is building the rect as a min,max pair, and not as min+(w,h)
// as we normally do.
const auto geom = SGRecti{
SGVec2i{_columns.at(loc.x()).calcStart,
_rows.at(loc.y()).calcStart},
SGVec2i{endCol.calcStart + endCol.calcSize,
endRow.calcStart + endRow.calcSize},
};
// set geometry : alignment is handled internally
i.layout_item->setGeometry(geom);
}
}
//----------------------------------------------------------------------------
void GridLayout::visibilityChanged(bool visible)
{
for (size_t i = 0; i < _layout_items.size(); ++i)
callSetVisibleInternal(_layout_items[i].layout_item.get(), visible);
}
bool GridLayout::hasHeightForWidth() const
{
// FIXME
return false;
}
} // namespace canvas
} // namespace simgear

Some files were not shown because too many files have changed in this diff Show More