Compare commits

...

1039 Commits

Author SHA1 Message Date
9d457c295a Turn on Decklink by default 2016-06-08 00:08:43 +02:00
324bee2c3f Merge remote-tracking branch 'origin/master' into decklink 2016-06-07 23:30:03 +02:00
Julian Eisel
a506f4c74e Cleanup: Add comment on behavior of tweak events
It's not obvious that they use the mouse coordinate of the initial key-press event (behavior since rBf1f33ba7be2d), so added comment.

Also corrected other comments.
2016-06-07 23:13:27 +02:00
38f07a81b3 Fix T48600: VSE strip 'side selection' fails in 'Both' case.
Looks like a line was forgotten in the 'BOTH' case in code...
2016-06-07 22:37:31 +02:00
9081adf097 Cleanup - size_t is unsigned, so always >= 0! 2016-06-07 21:53:17 +02:00
5bd9e83289 GPU: Fix triple buffer w/ basic glsl shader
Needed to add GL_TEXTURE_RECTANGLE support to basic-shader.
2016-06-08 05:40:21 +10:00
91c146c42e Cuda 7.5 cannot be made to work with a supported cl.exe version in the same way as cuda 6.0 does allow, disabling cuda kernels on buildbot for now 2016-06-07 20:58:53 +02:00
d16635e497 Cuda 7.5 cannot be made to work with a supported cl.exe version in the same way as cuda 6.0 does allow, disabling cuda kernels on buildbot for now 2016-06-07 20:56:44 +02:00
f3d33a1a0f GPU: Fix for glDrawPixels drawing w/ glsl shader
The basic shader needs to be temporarily disabled in this case.
Add macros for temp store/restoring the state.
2016-06-08 04:13:21 +10:00
cf8a0d08b0 GPU: make using the glsl basic-shader a flag
This allows for it to be more easily tested.
2016-06-08 04:13:16 +10:00
bf54dcc3c9 Fix T48589: Compositor Backdrop crashes Blender 2016-06-07 16:44:15 +02:00
b595a692c8 Cycles: Limit degenerated triangle check got CUDA only
OpenCL seems to work fine here, and for some reason that comparison was
giving compilation error on OpenCL here.

Better to compile OpenCL kernel than to be fully robust to weird corner
cases.
2016-06-07 15:48:56 +02:00
b6954c8da1 Cycles: Fix regression introduced in c96a4c8
A few places still needed to be updated to use the new Mesh::num_triangles()
method; wrong number from triangles.size() was causing crashes.
2016-06-07 07:38:09 -04:00
f08018f928 Fix (unreported) EditNormal modifier: broken 'flip poly' feature.
Newly computed custom normals were forgotten during poly flipping, leading
to wrong custom normals being assigned to wrong loop...

Dead simple, but was tough to track down this one!
2016-06-07 13:07:01 +02:00
0036ffb3e6 Cleanup: warning 2016-06-07 19:23:43 +10:00
0da13ad1eb World space switch for BI nodes.
At the moment light shading in Blender is produced in viewspace. Apparently, that's why
shader nodes work with normals in camera space. But it is not convenient for artists.
The more convenient approach is implemented in Cycles where normals are represented in world space.
Blend4Web Team designed the engine keeping in mind shader parameters readability,
so normals are interpreted in world space as well. And now our users have to use some tweaks, like
empty node group with the name "Replace", which is replacing one input by another on the engine side
(replacing working configuration in Blender Viewport by the configuration that has the same behavior in the engine).

This patch adds the ability to switch to world space for normals and lamp vector in BI and Viewport.
This patch is very important to us and we crave to see this patch in Blender 2.7 because
it will significantly simplify Blend4Web material creation workflow.

{F315547}

{F315548}

Reviewers: campbellbarton, brecht

Reviewed By: brecht

Subscribers: homyachetser, Evgeny_Rodygin, AlexKowel, yurikovelenov

Differential Revision: https://developer.blender.org/D2046
2016-06-07 10:42:29 +03:00
441a440cbb readfile: optimization for undo
Was using O(n^2) lookup on ID's with undo.

This caused undo to hang with 1000's of data-blocks
(especially with heavy scenes & outliner-space, which doesn't even need to be visible to cause a slow-down).

Internally this uses a ghash per id-type, which is lazy-initialized.
Each key uses the name and library since there may be name collisions between libraries.

Developer Notes:

- Adds small `BKE_main_idmap_*` API.
- Needed to change linking order for this to build.
2016-06-07 17:27:52 +10:00
3054e33d67 BLO_idcode: Move ID_ID last
This lets us use MAX_LIBARRAY to loop over id-codes in Main.
2016-06-07 16:42:11 +10:00
2d9d17c031 readfile: avoid library lookups for every id on undo
Instead index libraries, makes minor speedup when using many libraries.
2016-06-07 14:13:22 +10:00
f12c55d2b8 Correct exit-code check 2016-06-07 14:02:32 +10:00
7a5a02509b Cycles: Use faster ray-quad-intersection test
The original quad intersection test works by just testing against the two triangles that define the quad.
However, in this case it's actually faster to use the same test that's also used for portals: Determining
the distance to the plane in which the quad lies, calculating the hitpoint and checking whether it's in the
quad by projecting onto the sides.

Reviewers: brecht, sergey, dingto

Reviewed By: dingto

Differential Revision: https://developer.blender.org/D2045
2016-06-06 23:38:50 +02:00
ac7feaed3d EditNormal modifier: add some 'maximum angle' limit.
Allows to avoid generating flipped faces when using extreme normal modifications.

Related to T48576.
2016-06-06 21:42:47 +02:00
c8e9e6dda0 Added P key toggle to allow mouse movement to control bevel profile (modal).
The Shift key can be held while adjusting profile to make finer changes
to the profile (just as it already does when adjusting offset).
2016-06-06 13:15:13 -04:00
78f7d0b714 Cleanup: remove unused Library.idblock 2016-06-07 00:34:54 +10:00
420bd15262 Cleanup: warning 2016-06-07 00:34:16 +10:00
14f9a5aa1d Fix T48571: Cycles/GPU - A lot of fireflies on SSS+Volume
Was some accumulated precision error happening.
2016-06-06 15:56:22 +02:00
122c59fba4 Fix T48582: Rigidbody simulation issue with new depsgraph
Being granular means we need to re-build depsgraph a bit more often..

The issue was caused by rigidbody requiring some special nodes to
handle physics which were not created with just tagging object for
update.
2016-06-06 14:38:12 +02:00
c276480b0f Fix compilation error on 32 bit Windows 2016-06-06 14:01:49 +02:00
fd7068ee28 Fix T48550: Imperfections when Bake displacement map to plane if camera is not in front
The issue was caused by non-watertight nature of intersection, which is now addressed.

Hopefully it doesn't cause any regression caused by uninitialized precalculated storage.
2016-06-06 13:55:04 +02:00
b277ba5c0d Cycles: Fix compilation error on OSX 2016-06-06 13:52:57 +02:00
47d0d9cca4 Depsgraph: Russian electric tape bodge to have multiple proxies work
Makes behavior of proxy_from backlink working similar to the old dependency graph.

it's nasty, but needed here in the studio to get proxies fixes ASAP.
2016-06-06 12:09:04 +02:00
24049c8196 readfile: add assert to check libmap isn't sorted 2016-06-06 19:12:13 +10:00
5d45ffc755 readfile: minor optimization, no need to count flags
in this case we only need to check if any id's need to be read.
2016-06-06 19:05:21 +10:00
894d24fb16 Cleanup: use const for old member in OldNew struct 2016-06-06 18:04:13 +10:00
a97bcc2985 Cleanup: rename flag -> tag
ID's have a flag member too, best avoid confusion here.
2016-06-06 18:04:13 +10:00
6046c03f5c Cycles: Ignore zero size instances in BVH
In certain types of animation it's possible to have some objects
scaling to zero. In this case we can save render times by avoid
traversing such instances.

Better to do ti ahead of a time, so traversal stays simple.

Reviewers: lukasstockner97, dingto, brecht

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D2048
2016-06-06 09:23:53 +02:00
b62faa54de Cycles: Add support of processor groups
Currently for windows only, this is an initial commit towards native
support of NUMA.

Current commit makes it so Cycles will use all logical processors on
Windows running on system with more than 64 threads.

Reviewers: juicyfruit, dingto, lukasstockner97, maiself, brecht

Subscribers: LazyDodo

Differential Revision: https://developer.blender.org/D2049
2016-06-06 09:14:37 +02:00
9d090ed1cd RNA: disable animating object dimensions 2016-06-06 12:57:17 +10:00
7f57c99be8 Fix T48579: RNA shadows new custom properties 2016-06-06 12:23:01 +10:00
04bcaf07dc Fix T48580: path / branched path UI grayed out with OpenCL device that is not used. 2016-06-04 23:21:44 +02:00
234801c8dc Fix T48587, constant fold should only be done for Mix Type. 2016-06-04 21:39:07 +02:00
1d8637ec69 buildbot work around cuda / msvc compatibility issues attempt 2/ passing a string from python to cmake to nvcc is harder then it looks 2016-06-04 17:41:11 +02:00
ebbfd92859 buildbot work around cuda / msvc compatibility issues 2016-06-04 12:37:46 +02:00
50f432b1e0 CMake, minor changes to make Visual studio 2015 use a compatible numpy and
the standard cmake CUDA/NVCC arguments flag allowing 2015 build to use
msvc 2013 for cuda
2016-06-04 11:42:48 +02:00
17fbce9549 Cleanup: avoid temp string edit 2016-06-04 10:55:14 +10:00
38410e6e25 changed use_connect from bool to a 3 state value (-1,0,1) 2016-06-03 18:31:51 +02:00
b000a01725 fix T48389 (wip) added warning for loops that define holes (polygons with holes not supported) 2016-06-03 18:31:49 +02:00
fac9f1c840 Workaround MSVC error 2016-06-04 01:00:40 +10:00
c6cc599311 Fix T48234: Glitch w/ action constraints sharing an action
FCurve evaluation depended on FCurve.curval, which isn't threadsafe.
Now only use this value for debug display,
and pass the value instead of storing in the FCurve for all but debug-display.
2016-06-04 00:57:44 +10:00
398180439b Fix Playercompile 2016-06-03 12:05:01 +02:00
b406b7be00 Cycles: Mark which CUDA device is used for display
It is really handy to know which one is display when having two cards of
same type in the machine.
2016-06-03 11:52:08 +02:00
f71feb34a3 Make playback invoked form animation editors more usable
This covers the following workflow. Animator will disable Update All 3D views
in order to get quick playback in a particular 3D editor. However, it also
handy to see playback in all editors and image editors to see comparison of
animation and reference footage.

So the idea here is to refresh reasonable editors when playback is invoked
from animation editors.

Commit to make Hjalti happy.
2016-06-03 11:46:57 +02:00
f54a98a1c5 Cycles: Simplify check for degenerated faces on GPU
Still not sure how to properly solve the issue, needs some trickery to get
actual optimized values from intersection function (using printf() avoids
some optimization and makes stuff render correct).

For the time being let's just simplify check.
2016-06-03 10:36:04 +02:00
e370806b38 Cleanup & simplify snapping functions
- the name of the enumerator `SNAP_NOT_OBEDIT` was changed to `SNAP_NOT_ACTIVE`.
- the parameter `snap_to_flag` was moved to outside `SnapObjectParams`.
- the member `use_object_edit` was renamed to `use_object_edit_cage`.
- added the arg `params` in `ED_transform_snap_object_project_ray`.
- simplifications in the loop of the function `snapObjectsRay`.
2016-06-03 16:56:16 +10:00
e9363483ca Fix possible uninitialized variable in snapping
Introduced in 0b5a0d84, thanks to Brecht for spotting.
2016-06-03 16:26:27 +10:00
8c154d67b2 Fix T48111: Auto-run fails w/ empty paths
Enabling auto-run, then excluding a path but leaving it set to a blank value would ignore all paths.
2016-06-03 15:28:32 +10:00
528539ef59 Fix T48575: Particle crash using 'Parting' setting 2016-06-03 15:13:20 +10:00
cd768a8df1 Add upstream information to wcwidth library 2016-06-03 02:43:24 +10:00
a055523899 Theme: 2.4x, correct graph region color 2016-06-03 01:59:53 +10:00
c5b2f12b36 Fix T48456: 2x pixel size clamps min brush size
Using double pixel size prevented 1px brushes

D2044 by @jeske
2016-06-03 01:11:12 +10:00
68d1348ca2 Fix T47637: Multiple multires objects in Sculpt mode make blender crash.
That was a nice and funny hunt, albeit rather time consumming!

To summarize, so far code was using a static global gpu_buffer for pbvh vbo drawing
of 'grid' types (multires mostly?).

There were two issues here:
1) Global gpu buffer was assigned to GPU_PBVH_Buffers->index_buf, but then nearly no
check was done when freeing that buffer, to ensure we were not freeing the global one
(not totally sure this one was actually causing any issue, but was bad and unsafe anyway).
Was solved by adding a flag to GPU_PBVH_Buffers to indicate when we are using some
'common' buffer here, which freeing is handled separately.

2) Main issue: if several multires objects in sculpt mode with different grid size
were present simultaneously, the global gpu buffer had to be resized for each object draw
(i.e., freed and re-allocated), but then the pbvh nodes from other objects storing freed reference
to that global buffer had no way to know that it had been freed, which was causing the segfault & crash.
Was solved by getting rid of that global buffer, and instead allocating one 'grid_commmon_gpu_buffer' per pbvh.

Told ya baby, globals are *PURE EVIL*!
2016-06-02 16:14:21 +02:00
ac8246cd89 Fix for GLSL uniform being update from inside glBegin/glEnd
This seems to be illegal and not productive anyway. Do it ahead of
a time now, which solves shading issues in edit mode and prevents
assert from happening.
2016-06-02 14:01:07 +02:00
Julian Eisel
664e854af7 Fix leak using UI_BTYPE_TEXT button w/o a callback
Moving ownership of the string to the button's 'rename_orig'
leaked when the button didn't have a uiAfterFunc.
2016-06-02 20:31:48 +10:00
64663b1f73 Cleanup: warnings in previous commit 2016-06-02 19:48:45 +10:00
cc7b817099 Minor edits to last commit
Failed with chunk merging disabled
2016-06-02 18:42:09 +10:00
0ce98b1ffb BLI_array_store: Move writing many chunks into a function
Minor optimization, avoid some checks each iteration.
2016-06-02 18:13:13 +10:00
7980c7c10f BLI_array_store: store max size in BArrayInfo 2016-06-02 18:05:11 +10:00
0bd8d6d194 Add extra validation checks to array-store 2016-06-02 16:41:41 +10:00
d931e958a1 Minor changes to help text
D2040 by @Blendify, also move 'Experimental Features' above more general help text.
2016-06-02 15:29:53 +10:00
1e9b222322 ShapeKey was missing lattice-flag
missed from 7a8bd2eae
2016-06-02 15:12:29 +10:00
c4b23a57a9 Fix T48566: Render-border minor offset issue 2016-06-02 12:53:04 +10:00
d48c71b3b1 Decklink: fix output on some DeckLink cards.
Opening a DeckLink card for output with the DeckLink object
sometimes failed because some types of card report no support for BGRA pixel
format, yet it works. The test is maintained but a warning is printed
instead of throwing an exception.

Optional cache size suffix added in Decklink output format string: may be
needed for some card that needs more than the default 8 frames.
2016-06-01 22:06:27 +02:00
a7ff4bb5e5 Decklink: Fix bug: Decklink.right attribute was not unitialized. 2016-06-01 22:01:11 +02:00
24712b1c0b Usual UI/i18n message cleanup (get rid of last remaining 'addon' too). 2016-06-01 20:38:30 +02:00
57d5ddc251 Revert "BLI_ghash: Fix initial over-allocation of mempool chunks."
Useless change in fact, sorry for the noise.

This reverts commit b08473680e.
2016-06-01 17:38:50 +02:00
6befc76265 Fix T48466: Multiple passes starting with 'Diffuse' in EXR file breaks its loading in Blender.
Issue here is that for Blender, any pass which name starts with 'Diffuse' is considered
a diffuse pass - and it does not really support several passes of the same type in renderresult.

So for now, passtype_from_name() is now checking whether a pass of same type already exists
in render layers, and return 0 (uknown passtype) in this case.
2016-06-01 17:31:42 +02:00
2c5dc66d5e Optimize mempool iteration
Around ~10% improvement in own tests.
2016-06-02 00:07:18 +10:00
b1704d18a1 Fix T48415: Segfault on opening .blend in which a 'surface' force object was saved in Edit mode.
In that case, surface modifier won't run (until surface object goes back to Object mode),
and its bvhtree remains NULL.
2016-06-01 15:29:19 +02:00
8cf8679b53 Revert "Correct invalid pointer-pair compare check"
This reverts commit d5e0e681ce.

Tsk, these functions return false on a match.
2016-06-01 23:08:40 +10:00
543c64ef74 Fix bug where corner boundary was straight when it should curve.
Some adjustments to how bevel edge 'profiles' are adjusted in some
cases. For the bug fix, wanted to handle cases of middle of three
coplanar beveled cases to make profile curve rather than linear
interpolate.
Also undid an earlier decision to make profile plane be perpendicular
to beveled edge i the non-coplanar case.
2016-06-01 08:51:08 -04:00
b08473680e BLI_ghash: Fix initial over-allocation of mempool chunks.
Code intended to create only one pool by default here, but code in `mempool_maxchunks()` would make it two.
2016-06-01 12:58:59 +02:00
9ed4233d9d Fix wrong vertex colors in edit mode 2016-06-01 11:53:28 +02:00
d0de2733d5 BI: fix counting of tangents, that was reset during recursion of init_render_nodetree 2016-06-01 12:28:48 +03:00
0e8570b415 GLSL: Attempt to fix errors in setting UV attributes 2016-06-01 10:26:18 +02:00
334d823b2b Depsgraph: Fix missing updates when modifying armature 2016-06-01 10:10:39 +02:00
1c292c9730 Fix/Workaround T48560: Color picker V fail w/ user defined RNA
Set the maximum soft-max to 1.0 when its left at FLT_MAX.
Since this causes problems using the slider.
2016-06-01 16:11:47 +10:00
Dalai Felinto
d85271572b Increase range of Font object textboxs
The current values were arbitrary. I'm keeping them as ui_range, but
internally there is no reason we can't use larger values.
2016-05-31 19:11:16 -03:00
aedeca7d1c BLI_mempool: Use an 'odd' FREEWORD for big/little endian
This also changes freeword to an intptr_t to ensure
not only the first 4 bits of a pointer are tested on 64bit systems.
2016-06-01 02:54:47 +10:00
d2bb0e660b Fix T46207: Slow OpenCL GPU bake and blown out baking Cycles render 2016-05-31 17:48:42 +02:00
Dalai Felinto
ad1c3bef8b Small API typo found while reading the API 2016-05-31 12:39:58 -03:00
a430c688ee Cleanup: unused defines 2016-06-01 00:26:14 +10:00
3df30c1a6e Cleanup: parenthesize defines 2016-06-01 00:19:01 +10:00
a0e91ef040 Fix T48554: Absolute grid snap fails w/ cursor pivot
Use center of selection when using absolute grid snapping and cursor pivot.
2016-06-01 00:01:17 +10:00
d5220d23f9 Cycles: Fixes for recent refactor
- add_vertex() can be called from split_vertex() which does not guarantee
  to have properly pre-allocate arrays.

- Need to check whether Cycles is compiled with OSL in XML reader.
2016-05-31 15:32:31 +02:00
230cf2e46d Buildbot: Attempt to fix buildbot after recent change 2016-05-31 15:28:32 +02:00
9e77a03f63 Buildbot: Use proper list management function
Spotted by Campbell, thanks!
2016-05-31 15:20:14 +02:00
f1f7f6d4b1 Buildbot: Pass proper generator for MSVC 2015 builder 2016-05-31 14:42:18 +02:00
e9c8917e10 Properly handle vertex color color space for Cycles GLSL
A bit tricky, need to pass additional information about what the attribute
is and how to deal with it.

BI path stays unchanged, just to make things simplier for now.

Fixes T48555: Cycles GLSL- Incorrect Vertex Color results from Attribute node
2016-05-31 14:41:51 +02:00
19cfc84328 CMake/ Visual Studio 14 2015, Use one library name for openal for both 2013 and 2015 2016-05-31 14:16:29 +02:00
9725661c60 Cycles GLSL: Make it work with software opengl mode 2016-05-31 12:31:16 +02:00
4388b29e98 Cycles: Add human readable sizes to debug output
Some of these values can get quite large and are hard to read, adding this
makes it easy to read them at a glance.

Reviewed By: sergey

Differential Revision: https://developer.blender.org/D2039
2016-05-31 06:13:54 -04:00
a2aa44370b Fix T48556: Missing transparent shadows on AMD OpenCL
We had transparent shadows disabled for some time because they were causing
drivers to crash. Can't reproduce that issue anymore with current drivers,
so will enable them and see how it goes.
2016-05-31 11:48:07 +02:00
ea8a7397e4 Fix T48553: Cycles GLSL Box projection produces strong artifacts 2016-05-31 09:50:24 +02:00
4f730b4708 Fix T48552: Ctrl-D to add drivers shows disabled menu items 2016-05-31 16:30:44 +10:00
5186143d2c Theme: 2.4x disabled menu text wasn't greyed out 2016-05-31 14:55:55 +10:00
3ed5da0479 Fix T48547: Shrinkwrap fails w/ auxiliary target
Error in 0b5a0d84
2016-05-31 14:37:06 +10:00
0d4a7d50c6 Fix broken Cycles curve motion radius after recent refactor, and fix warnings. 2016-05-31 00:21:33 +02:00
1482826075 Add 'multi small' testcase to performance Ghash tests.
This new test simply inserts and lookup a lot of time on very small ghashes
(most are < 17 items).
2016-05-30 20:04:43 +02:00
7e120f3a74 Shrinkwrap: OMP->BLI_task.
Gives little to no speedup (a few percents at best).
2016-05-30 17:30:55 +02:00
06969fdf1b Depsgraph: Small optimization to update flushing
Gives about 5% speedup in scene with lots of nodes (army_of_clones.blend)
2016-05-30 16:56:05 +02:00
1e7e183787 Fix T48527: Maya keymap fails w/ knife snap 2016-05-30 22:45:46 +10:00
c9799b68f1 Depsgraph: Fix compilation with new depsgraph disabled 2016-05-30 14:44:56 +02:00
f0ee7f9544 CMake: Workaround to get Libmv compiled with latest Gcc 2016-05-30 14:37:33 +02:00
ce13a7b609 Fix: Add a hard upper limit for fontsize of Text Strip's text
Although there is a "UI limit", it's necessary to have the hard limit on the
property too. I noticed this bug first hand just now, when, after accidentally
setting the size to 8188 (due to a combination of typos and sluggish UI refresh)
my machine locked up completely when trying to jump to that frame. It got so bad
that I had to do a hard reset to fix it - so, it's possible that even 1000 or 2000
as used now are actually way too large still.
2016-05-30 23:45:58 +12:00
da975c59c2 GLSL: Fix voronoi texture giving different results form rendered 2016-05-30 13:07:11 +02:00
673fabbb64 Depsgraph: Fix wrong layers flush form children to parent
It was possible to have issues in cases when several child dependencies
goes to IDs with different layers. In this case order of flushing was not
really well defined, which could lead to cases when indirect dependency
via invisible object wouldn't work.

Need some sort of barrier to prevent scheduling of parent nodes for until
all children are done, but that's becoming quite nasty thing to implement.

Added a temp field to component for now. maybe it's not so crazy actually
and we might use it for evaluation as well, so we wouldn't flush updates
to components which does not affect visible stuff.
2016-05-30 12:35:03 +02:00
Ralf Hölzemer
4aaf7b0c7a Support all Cycles image texture projections in the GLSL viewport
This patch enables Tube, Sphere and Box projections in GLSL for the image texture node.

Reviewers: sergey

Projects: #nodes, #opengl_gfx

Differential Revision: https://developer.blender.org/D2036
2016-05-30 10:29:46 +02:00
0f86a545e7 GLSL: Fix magic colors being off 2016-05-30 10:22:18 +02:00
163e46bbea GLSL: Brick texture uses bit operations, which seems to be a failure on some Intel cards 2016-05-30 10:22:18 +02:00
665cb1b291 Change the hash-table to be 3x total items to hash 2016-05-30 18:00:03 +10:00
bd6a64ced7 Remove accidental static var 2016-05-30 17:27:06 +10:00
91bfdacde2 Editmesh undo memory optimization
Previously a whole mesh was stored between undo steps,
This commit uses BLI_array_store to de-duplicate memory use between undo steps.

Memory saving depends entirely on kinds of edits performed,
in own tests 5x-15x less memory use is common.

Compacting the memory does give some overhead however its done in a background thread
so its not blocking in most cases.

New behavior and threading can be ifdef'd out to check for regressions.

See D2026 for details.
2016-05-30 16:27:15 +10:00
8a7d1f3b3c BLI_array_store tests
Ensure the data is valid once expanded,
and that de-duplication is working as expected.
2016-05-30 16:27:12 +10:00
53b60eed45 Add BLI_array_store copy-on-write API
This supported in-memory de-duplication,
useful to avoid in-efficient memory use when storing multiple, similar arrays.
2016-05-30 16:18:24 +10:00
11b0874db0 Code refactor: store ShaderNode enums as enum rather than ustring. 2016-05-29 20:30:16 +02:00
a70a435f28 Code refactor: centralize OSL node creation in shader manager. 2016-05-29 20:30:16 +02:00
af073e149b Code refactor: pass ShaderInput to constant_fold, so it supports arbitrary types. 2016-05-29 20:30:16 +02:00
9bd2820aaf Code refactor: add separate RGB to BW node and rename some sockets. 2016-05-29 20:30:16 +02:00
eac7ed8d04 Code refactor: minor node and node type utility functions and changes. 2016-05-29 20:30:16 +02:00
7cd18dda7d Fix debug mode assert in subd code after recent refactoring. 2016-05-29 20:30:16 +02:00
e1003c2ead BKE's DerivedMesh: get rid of last OMP usage.
Not replacing with some BLI_task_stuff here, tests show this is pointless
(in absolute best case - i.e. single huge mesh in scene - parallelizing here switches
from 0.8ms to 0.5ms for that piece of code - with something like 750ms per frame update...).
2016-05-29 20:14:42 +02:00
3ed2b11a4d Fix T48507: Symmetrize doesn't work properly on Bendy Bones 2016-05-29 19:37:40 +12:00
df76d60267 Fix: Flip logic order for autokeying checking to cope with files where the flags have been set incorrectly
Sometimes the autokeying flags don't get set correctly (i.e. the "mode" flags
used for 'Add + Replace' vs 'Replace Only' aren't set), meaning that the old logic
would always fall through to the "replace only" case. When this happens, the resulting
behaviour can be quite strange and hard to debug. This fix prevents problems like
this from continuing to be an issue...
2016-05-29 19:08:45 +12:00
cd4d80fac6 added missing include 2016-05-29 01:38:14 +02:00
af185e1154 fixed some incompatible definitions (to make this work also on linux) 2016-05-29 01:30:20 +02:00
5366900ace Added support for non numeric bone layer labels (could happen when importing from other tools)
Differential Revision: https://developer.blender.org/D2037
2016-05-29 00:37:46 +02:00
8b2c67c3c3 collada exporter: fixed wrong check for bone roll value 2016-05-28 20:52:32 +02:00
362bd116d9 Fix T48529: NLA : viewport not updated after Track muted/unmuted.
Not sure why, but ANIM_animdata_update() totally ignored NLAStrip type of bAnimListElem.

For now only added support for ANIM_UPDATE_DEPS type of update, don't know whether
others are needed in this case or not... time will say.
2016-05-28 19:52:31 +02:00
8e26111020 Collada: Adding support for bone roll and bone layers
Differential Revision: https://developer.blender.org/D2034
2016-05-28 19:22:06 +02:00
001ba5bdf5 Code refactor: nodify object and mesh, but not used for XML yet.
Differential Revision: https://developer.blender.org/D2016
2016-05-28 18:40:09 +02:00
c96a4c8a2a Code refactor: modify mesh storage to use arrays rather than vectors, separate some arrays.
Differential Revision: https://developer.blender.org/D2016
2016-05-28 18:31:00 +02:00
b94bfe4cd8 Code refactor: make ShaderNode match Node a bit more, reusing types and enums.
Differential Revision: https://developer.blender.org/D2016
2016-05-28 15:49:15 +02:00
a9f7bbc9f8 PyRNA: Fix repr used /w arrays
RNA arrays now display their index, with support for multi-dimensional arrays.
2016-05-28 22:30:25 +10:00
98ad473324 Code refactor: nodify Cycles camera and fix some mistakes in XML node read.
Differential Revision: https://developer.blender.org/D2016
2016-05-28 14:07:19 +02:00
9d5aead88f Fix T48534: color picker hex #RRGGBB input allows typing one character too many.
Fix suggested by Daniel Rivera.
2016-05-28 12:38:21 +02:00
4ae507180e Fix T48498: stereo camera interocular distance should not have a hard max limit. 2016-05-28 12:22:34 +02:00
62f85add48 Fix T48526: Cycles viewport render incorrectly influenced by pixel aspect ratio.
This reverts 72592cfb, needs more refactoring to do that cleanup.
2016-05-28 11:57:27 +02:00
Ralf Hölzemer
739bf147a9 Fix T48533: camera node view vector wrong for Cycles GLSL.
Reviewed By: brecht

Differential Revision: https://developer.blender.org/D2033
2016-05-28 11:38:10 +02:00
94e18c59f8 Add missing include 2016-05-28 10:25:46 +10:00
dc07a5561f Cleanup: Further tweaks for consistency and simplifications.
Now I can start adding half float without adding even bigger mess to all these functions. ;)
2016-05-27 23:35:29 +02:00
2f457b7649 Cleanup: Simplify and de-duplicate assignements in the ImageManager constructor. 2016-05-27 23:12:13 +02:00
2ee063868d Cleanup: Shorten texture variables, tex and image was kinda redundant.
Also make prefix consistent, so it starts with either TEX_NUM or TEX_START, followed by texture type and architecture.
2016-05-27 22:58:33 +02:00
bd678f179b ndof: detect SpaceMouse Enterprise
New device! Lots of buttons!
2016-05-27 15:34:40 -04:00
9449126d7a Depsgraph: Accidentally removed one line too much 2016-05-27 18:30:01 +02:00
55b24bef55 Depsgraph: Cleanup and code simplification
This is mainly a maintenance commit which was aimed to make work with
this module more pleasant and solve such issues as:

- Annoyance with looong files, which had craftload in them
- Usage of STL for the data structures we've got in BLI
- Possible symbol conflicts
- Not real clear layout of what is located where

So in this commit the following changes are done:

- STL is prohibited, it's not really predictable on various compilers,
  with our BLI algorithms we can predict things much better.

  There are still few usages of std::vector, but that we'll be
  solving later once we've got similar thing in BLI.

- Simplify foreach loops, avoid using const_iterator all over the place.

- New directory layout, which is hopefully easier to follow.

- Some files were split, some of them will be split soon.

  The idea of this is to split huge functions into own files with
  good documentation and everything.

- Removed stuff which was planned for use in the future but was never
  finished, tested or anything.

  Let's wipe it out for now, and bring back once we really start using
  it, so it'll be more clear if it solves our needs.

- All the internal routines were moved to DEG namespace to separate
  them better from rest of blender.

  Some places now annoyingly using DEG::foo, but that we can olve by
  moving some utility functions inside of the namespace.

While working on this we've found some hotspot in updates flush, so
now playback of blenrig is few percent faster (something like 96fps
with previous master and around 99-100fps after this change).

Not saying it's something final, there is still room for cleanup and
API simplification, but those might happen as a regular development
now without doing any global changes.
2016-05-27 18:01:18 +02:00
3d86a5bc72 more correct Normal Map node behavior for tangent mapping in Cycles Viewport 2016-05-27 14:45:13 +03:00
108b36f1ce Add upstream information to libraries 2016-05-27 20:03:27 +10:00
7dae62cde0 Cycles: Simplify code around debug stats in BVH traversing 2016-05-27 10:55:48 +02:00
c3eb7c4e9d Add some more information about extern libraries 2016-05-27 09:27:44 +02:00
1e32951477 OpenGL: use EXT version of FBOs
Blender 2.7x supports OpenGL 2.1 which has FBO only as an extension.

It was working fine, but this is more correct.
2016-05-27 00:19:32 -04:00
ab4aa2e3fb fixed collada api call for blenderplayer 2016-05-26 19:16:18 +02:00
1346482d23 moved is_leaf_bone() to collada utils for reuse in exporter and importer 2016-05-26 18:22:36 +02:00
29aa13cfa2 fix: Import of meshes with holes is now reported as WARNING (unsupported)
improved: add support for bone tail export/import using Blender Collada profile

Differential Revision: https://developer.blender.org/D2031
2016-05-26 17:53:25 +02:00
6a7ce064ad fix: Import of meshes with holes is now reported as WARNING (unsupported) 2016-05-26 17:41:41 +02:00
f87842a73a Image viewer scopes update: OMP->BLI_task.
Gives over 50% faster scope update (from 4.5ms to 2.2ms here with SD shot)!
Probably mostly due to more clever usage of thread-local data (which avoids any lock,
when OMP code had a rather stupid critical section for minmax)...
2016-05-26 14:33:26 +02:00
d5e0e681ce Correct invalid pointer-pair compare check 2016-05-26 22:20:12 +10:00
7424ded9c7 Cleanup: glsl style 2016-05-26 18:53:09 +10:00
fe766d9c7a BMesh: don't alloc zero sized select elem array 2016-05-26 15:56:12 +10:00
f2ba13964d Fix T48514: Cycles toon glossy BSDF not respecting reflective caustics option. 2016-05-25 21:13:24 +02:00
b49185df99 Cycles CUDA: reduce branched path stack memory by sharing indirect ShaderData.
Saves about 15% for the branched path kernel.
2016-05-25 21:13:24 +02:00
7928030eff Fix T47257: bevel crash when there are internal faces.
Bevel had assumed that when rebuilding a face that touches
a vertex with beveled edges, the edges of the face at that vertex
would be adjacent in internal order. That is not necessarily true
if there are edges with more than two faces attached.
We could just prohibit beveling any edges that touch a vertex
where this happens (we already don't bevel non-manifold edges)
but the use case in the model of T47257 seems reasonable.
Also had to fix the edge-ordering code, and the face reconstruction
code to take care of cases where the face normal may not be as expected.
2016-05-25 08:48:46 -04:00
cb2b776332 dd upstream information to libraries 2016-05-25 22:27:53 +10:00
cec629ae42 Depsgraph: Simplify some loops using foreach() 2016-05-25 13:52:02 +02:00
f83f7bb988 Add warning to Mesh.from_pydata 2016-05-25 21:35:45 +10:00
dcd2136f95 Depsgraph: Solve wrong datamask calculated by depsgraph
This is a weak concept, but nice t support it for now, so we can enable
new depsgraph by default earlier.
2016-05-25 13:00:30 +02:00
84c7f427f2 Cycles: Yet another fix for textures limit 2016-05-25 12:49:02 +02:00
15911eebda Move editmesh undo into its own file 2016-05-25 19:12:43 +10:00
18b418e8e0 Cycles: Fix wrong cuda textures limits 2016-05-24 17:02:19 +02:00
dc5a6a0aed Cycles: Fix wrong render results when using multiple OpenCL devices 2016-05-24 16:57:57 +02:00
5494ea1d08 Fix own mistake in D1120: wrong indexing of UV maps during tangent calculation 2016-05-24 17:43:57 +03:00
42b26206c6 Fix T48508: Cycles Regression / Crash 2016-05-24 14:53:34 +02:00
2e190abf70 Fix T48496: Viewer function in NodeWrangler addon don't work in Material Shading mode 2016-05-24 14:39:28 +02:00
800de8bffd Cleanup: indentation 2016-05-24 20:34:53 +10:00
e1dd83b399 Fix T48486: Not enough precision in Volume Sampling Step Size input
Volumes might be small, makes sense to use more precision here.
2016-05-24 12:17:06 +02:00
a7c3ec4feb GHOST cleanup (null check before delete, and 0 -> NULL for pointers).
Based on patch from Lawrence D'Oliveiro (ldo) in T48499.
2016-05-24 11:49:30 +02:00
0b588f0905 Forgot this in previous commit 2016-05-24 11:48:19 +02:00
8f04a228f7 Add upstream information to libraries 2016-05-24 11:46:53 +02:00
93b3f1c856 Sequencer's histogram view: OMP -> BLI_task.
New code using loop/finalize model is about 45% faster (from 4.4ms tp 2.4ms per frame,
overall playback of single shot in sequencer in this preview mode goes from 40 to 45fps).
2016-05-24 09:34:55 +02:00
886349fd98 ndof: build system cleanup
Only Linux needs a lib linked in (libspnav).

ghostndof3dconnexion refers to an obsolete Mac driver shim.
2016-05-24 01:57:17 -04:00
84e0839537 ndof: enable Linux support by default, unless libs missing 2016-05-24 00:35:17 -04:00
999d5a6785 Cycles CUDA: reduce stack memory by reusing ShaderData.
57% less for path and 48% less for branched path.
2016-05-23 22:29:24 +02:00
af4a04eae0 Fix T48487: Physics cache names allow (back)slashes, which breaks its handling.
For now, just validate new pointcache names as if they were filnames.

Ideal solution would be rather to validate names in `ptcache_filename()`, but it would
likely break some existing caches - and we'd also have to ensure we still have
uniqueness of name after it has been cleaned up, wich would not be trivial at this stage.

So let's go for simple solution for now, especially since this part of code is to be
fully rewritten in 2.8...
2016-05-23 17:45:44 +02:00
Ralf Hölzemer
a6b218af2e Enable correct GLSL output for cycles normalmap node
See T48453 for details and test scenes

Reviewers: a.romanov, sergey

Reviewed By: a.romanov, sergey

Projects: #opengl_gfx, #nodes

Differential Revision: https://developer.blender.org/D2011
2016-05-23 16:25:44 +03:00
66dceb2bed Add TODO about vertex color linearization to GLSL code
It's not really clear at this moment how we can detect cases
when attribute needs linearization. For now added a comment
so we don't forget about this, hopefully.
2016-05-23 14:43:03 +02:00
12f86a4e48 Fix wrong scale of vertex color values when doing border render of Cycles viewport 2016-05-23 14:40:04 +02:00
6d84a4ecfd Fix wrong vertex color in BI GLSL mode
The issue was caused by recent normalization added to the GLSL attributes.
2016-05-23 14:29:08 +02:00
2aa4b6045a Cycles: Fix wrong closure counter in feature adaptive kernel
Some closures were missing from calculation, leading to an array
under-allocation, presumable causing memory corruption issues with
emission shaders on OpenCL and was causing issues with Volume 3D
textures with CUDA.

The issue was identified by Thomas Dinges, the patch is different
from the original D2006. See the brief discussion there. Current
approach is similar (or the same) as Brecht suggested.
2016-05-23 14:09:27 +02:00
6894bb0555 Fix T48334: Cycles standalone xml import of uv coordinates
In Cycle standalone, the xml import of uv's is done in a way that
a vertex could only have one unique uv coordinate. In practice it
is most of the time not the case.

Patch by Laurent Boiron, thanks!
2016-05-23 13:38:15 +02:00
Stefan Werner
7a35a0f419 Fixed a rare case of NaN in Cycles
This fixes a rare case where NaNs could exist inside Cycles.

When certain invalid meshes were passed in, Cycles would try too normalize
a zero length normal during its setup stage. While it does check against
division by zero, it still returns a zero length normal and passes it on to
the path tracing kernel. The kernel then operates under the assumption that
normals are valid, and in the case of such a zero length normal, would
eventually create NaNs that propagate through and result in black pixels.

Reviewers: #cycles

Subscribers: brecht, sergey

Projects: #cycles

Differential Revision: https://developer.blender.org/D2008
2016-05-23 13:34:14 +02:00
cdcb0826ee B-Bones improve handle calculation
This changes the bezier handles b-bones to fit to a circle more closely.
2016-05-23 21:35:54 +10:00
a17cba339c BLI_math: Add function to calculate circular cubic curve tangents 2016-05-23 21:35:54 +10:00
abe98de63c Cycles: Fix missing feature reported by the Volume node 2016-05-23 12:58:25 +02:00
065c052cfb Cycles: Fix missing volumes support for feature-adaptive viewport render 2016-05-23 12:36:31 +02:00
cbbb021596 Fix for all OpenGL lights affecting Cycles viewport, regardless of their Enabled state
Was a regression since e1b8a5d.

Probably not very optimal fix, but better than a regression anyway.
2016-05-23 12:10:53 +02:00
de8494b54e Cleanup: glsl indentation, line length 2016-05-23 19:56:50 +10:00
3fd88e6843 Decklink: support display mode/pixel format combination that use padding.
Previously, the VideoDeckLink module was rejecting combinations of
video modes and pixel formats that cause padding. For example HD720
(1280 pixels per line) and 10BitYUV (encodes by blocks of 48 pixels) =>
16 padding pixels at the end of each line.
This format is now accepted and the padding pixels are sent to the BGE.
It is sufficient to edit the UV map so that these pixels are not displayed.
2016-05-23 11:04:56 +02:00
caec6f3d41 Code cleanup, stick closer to a blender code style in GLSL shader 2016-05-23 10:31:36 +02:00
a830280688 Support Vertex Color in GLSL viewport for Cycles
The title says it all actually.

Added special custom data type, because we don't know in advance
whether we're referencing UV or Color layer. Also made it so vertex
attributes are normalized.

TODO: Border render in viewport ignores the normalization of the
attribute array for some reason, will be looked into still.

Reviewers: mont29, brecht, campbellbarton

Reviewed By: brecht, campbellbarton

Differential Revision: https://developer.blender.org/D2022
2016-05-23 10:23:43 +02:00
a2669b0cbf Cleanup: Deduplicate image loading functions using templates. 2016-05-22 23:24:26 +02:00
6fdcc8c52d Merge remote-tracking branch 'origin/master' into decklink 2016-05-22 23:22:21 +02:00
a088f81295 Optimize ImageRender->Decklink output
Use loadImage() method whenever possible to transfer video frame
directly from GL driver to Decklink frame. This is possible when
alpha is true on ImageRender and render size matches exactly video size.
Best results with offscreen render.
2016-05-22 23:12:32 +02:00
84a9d171da Cleanup: Use short condition style. 2016-05-22 22:47:37 +02:00
27e4ce0cf6 Fix Cycles warning in release builds. 2016-05-22 19:42:45 +02:00
f7c28a66e2 Fix Cycles compile errors with GCC due to double promotion as errors. 2016-05-22 19:17:22 +02:00
2f978656ab Support Musgrave texture for Cycles GLSL viewport
Only for non-OSX viewport!
2016-05-22 19:10:15 +02:00
22ff9c5568 Fix T48497: Stupid typo in recent own BLI_task forloop work that broke non-parallelized case. 2016-05-22 18:35:44 +02:00
ca03eddfcc Cleanup: remove Cycles layer bits checking in the kernel.
At some point the idea was that we could have an optimization where we could
render multiple render layers without re-exporting the scene, by just updating
the layer bits. We are not doing this now and in practice with the available
render layer control like exclude layers it's not always possible anyway.

This makes it easier to support an arbitrary number of layers in the future
(hopefully this summer), and frees up some useful bits in the kernel.

Reviewed By: sergey, dingto

Differential Revision: https://developer.blender.org/D2020
2016-05-22 17:36:38 +02:00
9b9921b765 Code refactor: nodify Cycles shader and lights.
Differential Revision: https://developer.blender.org/D2016
2016-05-22 17:29:25 +02:00
e7d13b8a1d Code refactor: nodify Cycles background and film.
Differential Revision: https://developer.blender.org/D2016
2016-05-22 17:29:25 +02:00
0062d9f58c Code refactor: nodify Cycles integrator.
Differential Revision: https://developer.blender.org/D2016
2016-05-22 17:29:25 +02:00
226dc75e77 Code refactor: add generic Cycles XML node read and write functions.
Differential Revision: https://developer.blender.org/D2016
2016-05-22 17:29:25 +02:00
ec51175f1f Code refactor: add generic Cycles node infrastructure.
Differential Revision: https://developer.blender.org/D2016
2016-05-22 17:29:24 +02:00
841d008b98 Fix missing Ignore option for GLSL bump 2016-05-22 16:47:06 +02:00
309f26014b Use previous shading mode for border render in viewport
This way we can have border rendered part in the viewport and have
everything else material/texture shaded.
2016-05-22 16:23:26 +02:00
0cc514ec84 Make Shift-Z in viewprot a toggle between current shading mode and rendered one
This way it is now possible to toggle between material and rendered shading
while previously rendered viewport will always go back to solid shading.
2016-05-22 15:44:18 +02:00
120492ace9 Cycles: Support bump mapping in GLSL viewport
This commit implements Bump node in GLSL, making it possible to
see previews of bump mapping in viewport without need to render.
Nothing really fancy going on here, just uses internal dFdx/dFdy
functions to get derivatives of the surface and map itself.
Quite basic but seems to behave correct-ish.

This commit also makes Displacement material output to affect
viewport shading by re-linking unconnected Normal input to a
node which was used for displacement output (via Bump node).

Intention of all this is to make it really easy to do bump map
painting with Cycles as an active render engine.

Reviewers: campbellbarton, mont29, brecht, psy-fi

Reviewed By: brecht

Subscribers: Blendify, eyecandy

Differential Revision: https://developer.blender.org/D2014
2016-05-22 15:12:14 +02:00
6115267a84 CMake: Solve compilation error with pre-compiled libraries and new GCC-6
Since version 6 G++ switched to C++11 by default, which breaks some logic
around WITH_CXX11 checks in out CMake files, leading to compilation errors.
This is easy to solve by explicitly enabling older C++ standard when C++11
was not explicitly enabled by CMake options.

However, G++-6 will also use new ABI by default even if older standard was
specified in the compiler options. This is being addressed by a special
define flag.

This tricks made it possible to use new G++-6 without need to recompile
any of pre-compiled libraries.

However, this might break compilation with existing system libraries, which
might already be using new ABI. We can't address this automatically, so
now we simply default WITH_C11 and WITH_CXX11 options to whatever defaults
of the current compiler are. This means, for G++-6 we'll set WITH_CXX11 to
truth. This should make linking with system libraries working just fine,
but to make pre-compiled libraries we still might need to disable CXX11.

This should work fine work for a new environments with G++-6 and install_deps
script run from scratch there, because C++ standard will be the same for
both Blender dependencies and Blender itself.
2016-05-22 13:48:52 +02:00
e21af38f69 Fix T48476: 'Recalculate Bone to Cursor' fails 2016-05-22 17:47:39 +10:00
24a3a9e8a3 Cleanup: remove unused doxy config 2016-05-22 17:15:08 +10:00
9bf09200d2 ndof: simplify Mac build
We don’t require the 3Dconnexion driver framework at build time.

No special link flags or include paths needed.
2016-05-21 18:29:55 -04:00
Sebastian Ullrich
6bd248cd65 Python API: add material to uniforms from gpu.export_shader.
Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1457
2016-05-21 16:46:42 +02:00
4bbc0731a0 Forgot to remove omp header include... 2016-05-21 16:12:30 +02:00
951db20862 Dynamicpaint: fix (unreported) missing progress bar in early baking stage.
Nothing was shown in UI during pre-bake step, while it can take several minutes
to complete with heavy geometry.
2016-05-21 16:09:35 +02:00
c1b7acda4c DynamicPaint: massive refactor, replace all OpenMP usage by BLI_task and other optimizations.
This commit makes Dynamicpaint modifier evaluation (during playback) a few percents quicker.
However, it makes dynapaint's 'image sequence' baking about 33% quicker (from 119 to 77 seconds
in own heavy test), partly due to switch to BLI_task itself (about 20%), and partly due to
optimizations (remaining ~13%).

As usual, did a lot of tests here to ensure nothing is broken, but a lot more users' testing would definitively
be welcome too! ;)

Note that some quite meaningless omp forloops have been removed (parallelizing thousands of vec copy does
make it two or three times quicker, but the few hundreds of microseconds gained do not make any difference
in a hundreds millisecond process).

Also, this code could still use a lot more cleanup (naming etc.), the way it (tries to) handle malloc faults
is also totally flacky and makes the code horribly verbose and convoluted in some places - without actually
catching all possible faults (memarena could make it more easy to handle here), etc.
2016-05-21 16:01:09 +02:00
3a73d31c56 BKE Mesh mapping: add 'vert to looptri' mapping generator. 2016-05-21 15:20:06 +02:00
92a3ac4dd2 GPencil: Add hotkeys for the "Delete Active Frame" operator
Usage:
* D+X     - Works anytime, anywhere
* Shift-X - Works in EditMode only
* Via Delete Menu - EditMode only

Often doing video tutorials or perhaps during dailies/shot review you want to
quickly get rid of a quick scribble you made for making a point, without having
to undo (i.e. maybe you edited some objects in between) and/or without having
to use the eraser (i.e. it'd take too long to cover the entire area).
2016-05-21 18:34:06 +12:00
b730238e6d GP Sculpt: Make the cursor more visible on light backgrounds
On light coloured backgrounds (especially on white), it was impossible to see
where the cursor was. This commit adds a second ring (black) to the cursor so
that on light backgrounds, even if the light ring isn't visible the black one
will be.
2016-05-21 18:34:05 +12:00
2203444f3f Hopefully fix OMP/MSVC crap... 2016-05-21 00:54:37 +02:00
a055395487 Dynapaint: Serious cleanup and optimization of dynamicPaint_createUVSurface (mostly).
Gives 3-4% speedup in pre-bake step (from 112 to 108 seconds with own heavy test file).

Note that here we have a huge potential performance boost if we replace the flat
`Bounds2D *faceBB` array of UV tris bounding boxes by a real 2D AABB tree (right now,
we can loop over all UV triangles times the number of pixels of the surface times 5...).
2016-05-20 23:18:15 +02:00
f5a4beffdd Fix GLSL shader failing to compile on OSX
Bit operations are not supported on legacy profile of OSX.
2016-05-20 22:54:27 +02:00
79d69bb9e3 Makefile: Use hidden FORCE target 2016-05-21 05:48:10 +10:00
ecf534e4c5 Support Cycles wave texture in GLSL viewport. 2016-05-20 21:21:57 +02:00
d5b843ba9d Support Cycles noise texture in GLSL viewport 2016-05-20 18:58:56 +02:00
bff095184a Cleanup: Don't use f suffix for values in GLSL
Was giving an issues in the past, will avoid it for now.
2016-05-20 18:14:04 +02:00
c6ea288bcf Support voronoi texture in GLSL shading
It gives some slight differences on the plane corners, but can't
really figure out source of the issue here yet.

It's still better than fully white texture for the previews anyway.

At this point we should perhaps ifdef chunks of the code in order
to have faster GLSL compilation and probably even faster compiled
code. Will look into this shortly.
2016-05-20 18:05:29 +02:00
ca8419ed6e Support Cycles magic texture in GLSL viewport 2016-05-20 16:58:56 +02:00
a5a05fc291 Cycles: Fix long compile time with MSVC.
Compile time per kernel increased alot after recent image commits, re-shuffle some code to fix this.

Patch by "LazyDodo".

Differential Revision: https://developer.blender.org/D2012
2016-05-20 16:50:29 +02:00
7ab55d8947 Support gradient Cycles texture in GLSL viewport 2016-05-20 16:39:45 +02:00
b79214bbc5 Support Cycles brick texture in GLSL viewport 2016-05-20 16:13:44 +02:00
0405bbeae2 Support Cycles's checker texture in GLSL shading 2016-05-20 15:18:40 +02:00
9d19533117 Fix T48472: issue in array refactor, causing performance regression in BVH build. 2016-05-20 10:58:11 +02:00
6e416b6bdf Fix T48470: Bendy Bones: Custom Handle References not being cleared when bone deleted
In addition to the original bug report, I've gone through cleaning up a range of
related bugs which only became clear when hunting around the code...

* Custom Handle References weren't getting cleared when the bones they used got
  deleted.  But, neither was the custom bone shape location/transform reference.

* Various places where posebone settings are copied around were also missing code
  to handle the new Bendy Bone properties.

  (WHY DO WE HAVE SO MANY VARIATIONS OF COPYING POSE DATA!?!?)

* If duplicating a Bendy Bone with custom references, and the custom references
  are also selected/duplicated, the new Bendy Bones will use the corresponding
  duplicated bones
2016-05-20 19:09:27 +12:00
75a31c3670 Add Peak Memory as render stamp option
This commit adds Peak Memory to the stamp options, the value is the same one that is already shown in the image viewer.

Requested by @nutel.

Reviewers: campbellbarton

Subscribers: campbellbarton, nutel

Differential Revision: https://developer.blender.org/D1989
2016-05-19 22:57:38 +02:00
ad14c471eb Cycles: Add XML parsing of MappingNodes to Cycles Standalone
Reviewers: dingto, sergey

Differential Revision: https://developer.blender.org/D2009
2016-05-19 21:28:57 +02:00
01e86b2c7d Cleanup: warnings 2016-05-20 05:14:17 +10:00
07c58d5218 Merge remote-tracking branch 'origin/master' into decklink 2016-05-19 20:57:34 +02:00
5fea6ca52f Fix MSVC compilation error after merge 2016-05-19 20:56:51 +02:00
38f65c500c Fix T48204: Generic Tablet on Linux - Erratic strokes with pressure sensitivity enabled.
Once and for all - I hope!

So, for the records: Xinput1 events' valuators have a first_axis and axis_count defining the 'range'
of valid axes for that event - but valid data in the valuator's array **always** start at zero
(which means that, if event reports first axis as being axis 2, axis 2's value is in axis_data[0]).
2016-05-19 20:30:48 +02:00
dedc995018 Cycles / CUDA: Don't use bundled kernel if Adaptive is enforced by the user. 2016-05-19 16:32:57 +02:00
c5893db5cc Cleanup: misleading indentation 2016-05-19 23:37:23 +10:00
a4a968fd99 Dynapaint: parallelize drip effect.
Was not so far, because this effect is not modifying its 'own' PaintPoint, which means
it's not threadsafe. Since a global lock (mutex or spinlock) would not be much efficient
(we need to lock a given point pretty much all the computaion cycle), and since locking
a same PaintPOint from different threads at the same time is *very* unlikely,
solution here is to use an 'array of locks', one for each PaintPoint (same thing as BLI_bitmap,
using atomic ops to set/clear bits).

Here in own test (complex dynapaint over a huge sphere combining all dynapaint types), it gives
20% speedup of the whole dynapaint simulation!

Note: maybe we'd want to move that kind of bitlock into BLI lib some day - not totally sure how,
so let's keep it local for now...
2016-05-19 14:44:37 +02:00
4b810127ba Dynapaint: fix use of normal normalization in dynamicPaint_generateBakeData().
Vertex's normal is always normalized - and its conversion from short to float should not change that!
On the other hand, linear interpolation of three normals **does not give a normalized vector**
(unless all three inputs are exactly the same).

Also, minor optimization, avoid recomputing that interpolated normal twice for each PaintUVPoint.
2016-05-19 14:44:37 +02:00
c9f1ed1e4c Cycles: Add support for bindless textures.
This adds support for CUDA Texture objects (also known as Bindless textures) for Kepler GPUs (Geforce 6xx and above).
This is used for all 2D/3D textures, data still uses arrays as before.

User benefits:
* No more limits of image textures on Kepler.
 We had 5 float4 and 145 byte4 slots there before, now we have 1024 float4 and 1024 byte4.
 This can be extended further if we need to (just change the define).

* Single channel textures slots (byte and float) are now supported on Kepler as well (1024 slots for each type).

ToDo / Issues:
* 3D textures don't work yet, at least don't show up during render. I have no idea whats wrong yet.
* Dynamically allocate bindless_mapping array?

I hope Fermi still works fine, but that should be tested on a Fermi card before pushing to master.

Part of my GSoC 2016.

Reviewers: sergey, #cycles, brecht

Subscribers: swerner, jtheninja, brecht, sergey

Differential Revision: https://developer.blender.org/D1999
2016-05-19 13:14:37 +02:00
a7c8327c8a Merge remote-tracking branch 'origin/master' into decklink 2016-05-19 11:56:08 +02:00
31976ca624 Try to fix atomic_ops on buildbot by moving include to top 2016-05-19 11:54:16 +02:00
03f846ea12 Ignore vertex color when doing texture paint
It was totally useless to multiply diffuse color with the vertex color
when doing texture painting. It was masking actual texture and only was
forcing artists to create an empty vertex color layer to work this around.
2016-05-19 11:11:21 +02:00
89df6720be CMake: use signed char for recastnavigation
External libraries may need char to be signed.
2016-05-19 07:36:32 +10:00
20678138f7 Cleanup: CMake indentation
Also remove outdated comment
2016-05-19 07:12:14 +10:00
55a38402ca Fix again assembler version of atomic_add_uint32 and atomic_sub_uint32
The assembler version returns the previous value of the variable while
all the other versions return the new value.
This was fixed before but somehow it came back when the atomic module
was refactored.
2016-05-18 22:57:47 +02:00
ad2bf24a19 Merge remote-tracking branch 'origin/master' into decklink
Conflicts:
	intern/atomic/atomic_ops.h
2016-05-18 22:56:31 +02:00
b8435f48f0 VideoDeclink: change default cache size to 4 frames.
Previously, cache size was only 3 frames, which caused problems with older
types of Decklink cards (was working with the 4K Extreme).
The default is now 4 frames and it is possible to specify a different cache
size when opening the card:
VideoDecklink("<mode>/<pixel>[/3D][:<cachesize>]", cardIdx)

Ex with 8 frames in cache:

VideoDecklink("pal/2vuy:8", 0)
2016-05-18 22:30:41 +02:00
6988061bf1 Cuda wrangler: Fix very nasty bug with multiple scalar type qualifiers 2016-05-18 18:01:37 +02:00
3289f174ee Fix missing modifiers for mesh objects
All modifiers for all non-lattice objects were disabled after recent commit.
2016-05-18 17:36:52 +02:00
e34e5ce332 Theme Color Sets - Dynamically generated icons
The theme color set selector (for Bone Groups) will now show previews of
what each color set looks like. It does so using a 3-color band icon.
2016-05-19 03:25:38 +12:00
f74c7fcca2 Fix T47727: Weird bake results with non integer color values 2016-05-18 15:11:05 +02:00
7a8bd2eaea Fix T47737: Lattice crashes w/ smooth modifier
Add flag for modifiers that support lattice
2016-05-18 22:46:29 +10:00
cade8e25c6 Revert string splitting
Caused error on OSX
2016-05-18 22:05:53 +10:00
1283c66146 Revert part of 4adffde02c to get Windows (MSVC2013) compiling again 2016-05-18 23:42:53 +12:00
41a6829021 Depsgraph: Fix rest pose still using bone constraints 2016-05-18 11:38:52 +02:00
792e147e2c Cycles: Fix compilation error of CUDA kernels after recent volume commit
Apparently the code path with malloc() was enabled for CUDA.
2016-05-18 11:15:28 +02:00
cbe7f9dd03 Cycles: Pole merging for spherical stereo
The idea of pole merge is to fade interocular distance after a certain
altitude to zero when altitude goes closer to a pole. This should prevent
annoyances looking up in the sky or down to the bottom.

Works for both panorama and perspective cameras when Spherical Stereo
is enabled.

Reviewers: dfelinto, brecht

Reviewed By: brecht

Subscribers: sebastian_k

Differential Revision: https://developer.blender.org/D1998
2016-05-18 10:56:57 +02:00
7b356a8565 Cycles: Reduce amount of malloc() calls from the kernel
This commit makes it so malloc() is only happening once per volume and
once per transparent shadow query (per thread), improving scalability of
the code to multiple CPU cores.

Hard to measure this with a low-bottom i7 here currently, but from quick
tests seems volume sampling gave about 3-5% speedup.

The idea is to store allocated memory in kernel globals, which are per
thread on CPU already.

Reviewers: dingto, juicyfruit, lukasstockner97, maiself, brecht

Reviewed By: brecht

Subscribers: Blendify, nutel

Differential Revision: https://developer.blender.org/D1996
2016-05-18 10:14:24 +02:00
2433a537fa Cycles: Explicitly mark arguments as unused 2016-05-18 09:12:47 +02:00
e3218ded41 Fix T48395: Grease Pencil, pressing Ekey to sculpt don't work for left click configurations
When using Left Click select, it wasn't possible to sculpt using E+LMB.

I've changed the order of things in the keymap so that the select operator won't
end up catching and blocking all these events.
2016-05-18 17:23:16 +12:00
1139e51be6 Fix: "Whole Character" Keying Set should not include Location on bones with "connected" joint 2016-05-18 16:29:18 +12:00
4adffde02c Cleanup: cmake, indentation, line length 2016-05-18 11:58:08 +10:00
6f29dbd045 Fix issue in with multiple importance sampling in recent code refactor. 2016-05-18 01:51:30 +02:00
9dc5367c89 Cleanup code style inconsistency in last commits. 2016-05-17 23:41:45 +02:00
2630207ada Fix GCC/Linux build error after finite/isfinite changes. 2016-05-17 23:40:25 +02:00
21fddf7d1c C99/C++11: replace deprecated finite() by isfinite(). 2016-05-17 21:39:16 +02:00
2b73402547 Fix C++11 build issues on OS X, remove references to outdated libs. 2016-05-17 21:39:16 +02:00
0e8cd14dfe Code refactor: use shader pointers rather than shader indexes. 2016-05-17 21:39:16 +02:00
08670d3b81 Code refactor: use dynamic shader node array lengths now that OSL supports them. 2016-05-17 21:39:16 +02:00
93e4ae84ad Code refactor: add some array utility methods, fix leak in assignment operator. 2016-05-17 21:39:16 +02:00
df8097ea2a Bendy Bones: Small ui tweak
Change the order of the bending controls ("Curve XY Offsets") so the user can activate both InX and OutX by holding down the left mouse button. This way, it's easy to bend symmetrically on X or Y.
2016-05-17 18:08:04 +02:00
6cf7cc3393 Fix T48434: Missing meta support in new depsgraph 2016-05-17 17:52:23 +02:00
49aeee5a3d Bendy Bones: Advanced B-Bones for Easier + Simple Rigging
This commit/patch/branch brings a bunch of powerful new options for B-Bones and
for working with B-Bones, making it easier for animators to create their own
rigs, using fewer bones (which also means hopefully lighter + faster rigs ;)
This functionality was first demoed by Daniel at BConf15

Some highlights from this patch include:
* You can now directly control the shape of B-Bones using a series of properties
  instead of being restricted to trying to indirectly control them through the
  neighbouring bones.  See the "Bendy Bones" panel...

* B-Bones can be shaped in EditMode to define a "curved rest pose" for the bone.
  This is useful for things like eyebrows and mouths/eyelids

* You can now make B-Bones use custom bones as their reference bone handles,
  instead of only using the parent/child bones. To do so, enable the
  "Use Custom Reference Handles" toggle. If none are specified, then the BBone will
  only use the Bendy Bone properties.

* Constraints Head/Tail option can now slide along the B-Bone shape, instead of
  just linearly interpolating between the endpoints of the bone.

For more details, see:
* http://aligorith.blogspot.co.nz/2016/05/bendy-bones-dev-update.html
* http://aligorith.blogspot.co.nz/2016/05/an-in-depth-look-at-how-b-bones-work.html



-- Credits --
Original Idea: Daniel M Lara (pepeland)
Original Patch/Research: Jose Molina
Additional Development + Polish: Joshua Leung (aligorith)
Testing/Feedback: Daniel M Lara (pepeland), Juan Pablo Bouza (jpbouza)
2016-05-18 03:19:06 +12:00
29a17d54da Fix CUDA MEMCPY condition, it should only copy 3D, 2D or 1D.
Found by Brecht, thanks!
2016-05-17 00:37:34 +02:00
99d861169f Cycles / Requested Features: Volume was missing in logging print. 2016-05-17 00:36:22 +02:00
b90cc984f7 Usual i18n/UI messgaes fixes... 2016-05-16 21:46:55 +02:00
886ff72301 Remove strict header, gives issues with gcc5x 2016-05-17 05:26:09 +10:00
0096bae8c4 Cleanup: use const args 2016-05-17 03:07:40 +10:00
42f8232046 CustomData: Support for >2gig layers 2016-05-17 03:02:55 +10:00
2b02e03973 Cleanup: simplify checks calculating tangents 2016-05-17 02:18:11 +10:00
688858d3a8 BLI_task: Add new 'BLI_task_parallel_range_finalize()'.
Together with the extended loop callback and userdata_chunk, this allows to perform
cumulative tasks (like aggregation) in a lockfree way using local userdata_chunk to store temp data,
and once all workers have finished, to merge those userdata_chunks in the finalize callback
(from calling thread, so no need to lock here either).

Note that this changes how userdata_chunk is handled (now fully from 'main' thread,
which means a given worker thread will always get the same userdata_chunk, without
being re-initialized anymore to init value at start of each iter chunk).
2016-05-16 17:15:18 +02:00
5a7429c363 BLI_task: Add back lost 'push_from_thread' change to BLI_task_parallel_range() & co. 2016-05-16 17:00:15 +02:00
19955bd152 Fix T48447: Inactive menu items don't grey-out icons 2016-05-17 00:17:26 +10:00
575d7a9666 BLI_task: make foreach loop index hleper lockfree, take II.
New code is actually much, much better than first version, using 'fetch_and_add' atomic op
here allows us to get rid of the loop etc.

The broken CAS issue remains on windows, to be investigated...
2016-05-16 15:57:19 +02:00
75a96f8325 Atomic ops: add 'fetch_and_add_uint32' op.
Needed for next commit.
2016-05-16 15:56:39 +02:00
460d944493 Cleanup rna_Brush_direction_itemf()
Some variants of gcc compilation were reporting 'control reaching end of non-void function' error
in this switch/case maze. Either use break everywhere or not at all (which is simpler, since we
only always return anyway...).
2016-05-16 15:54:18 +02:00
22d53e558d Cycles: Cleanup after recent refactor
Wrong indentation, wrong spacing.
2016-05-16 10:55:50 +02:00
f70b548630 Revert "Docs: smoke typo corrections"
This reverts commit b13bc48932.

Wasn't only typo fixes, broke compiling
2016-05-16 09:28:49 +10:00
b13bc48932 Docs: smoke typo corrections
patch by @Blendify
2016-05-16 07:52:56 +10:00
a1a640f614 Curve Fitting: correct circular tangent length calculation
Method for scaling is still not perfect but quite close.
2016-05-16 07:45:50 +10:00
bb7da630ba Fix T48422: Revert "BLI_task: nano-optimizations to BLI_task_parallel_range feature."
There are some serious issues under windows, causing deadlocks somehow (not reproducible under linux so far).

Until further investigation over why this happens, better to revert to previous
spin-locked behavior.

This reverts commits a83bc4f597 and 98123ae916.
2016-05-15 21:14:40 +02:00
23bdcfe560 BGE: Fix KX_LightObject python API documentation.
Replace "..attribute::" by ".. attribute::".
2016-05-15 14:56:40 +00:00
20714889bf Fix T48425: Armature Symmetrize is flipping Custom Shape parameter.
In case not all bones are selected, not all possible mirrors are set in editbone->temp.ebone,
so we need to search them...
2016-05-15 12:35:01 +02:00
a83bc4f597 Fix an error in new lockfree parallel_range_next_iter_get() helper.
Reading the shared state->iter value after storing it in the 'reference' var could in theory
lead to a race condition setting state->iter value above state->stop, which would be 'deadly'.

This **may** be the cause of T48422, though I was not able to reproduce that issue so far.
2016-05-14 18:06:05 +02:00
b9996a3cc3 Fix Cube generated UV's rotated incorrectly 2016-05-14 23:01:59 +10:00
b1e2f8be23 Fix T48426: Use same length for all header message strings.
Some languages like Chinese or Japanese take three or four bytes per char...

Also fixed some missing translation markers for UI header messages.
2016-05-14 10:00:52 +02:00
ede742917a Correct BM_iter_mesh_bitmap_from_filter return 2016-05-14 04:49:42 +10:00
eeca6372d0 Correct asserts 2016-05-14 04:05:18 +10:00
24e887cd93 Fix script_paths(check_all=True) missing script paths
BLENDER_SYSTEM_SCRIPTS wasn't included in bpy.utils.script_paths()
2016-05-14 03:27:35 +10:00
89c6b58ef5 Fix compilation with strict compiler flags
Some const qualifier was discarding.
2016-05-13 17:37:39 +02:00
8b92d728ae Fix T48421: AO pass broken, only works when AO in cycles is enabled 2016-05-13 17:33:40 +02:00
141c0f8ad1 Cleanup: rna naming, indentation 2016-05-14 01:33:27 +10:00
a91a49ba8e Fix T48416: Impossible to copy a linked object from a file to another one mantaining the linked library.
When writing temp blenbuffer file, libraries of linked datablocks where not tagged correctly, which
means they were not put in the temp Main used to write the buffer, resulting in implicit localization
of linked data.
2016-05-13 14:12:10 +02:00
5e0ec49570 Fix T48416: Impossible to append from another file without localizing also all indirectly linked data.
Previous to 2.77, this used to be default behavior, was changed in rB591f4549c958b.

However, in most append cases, you do want a full localization of your data, so this new behavior
is kept by default, but there is now an option in append operator to only localize the 'first level'
of data (i.e. datablocks from linked library itself, and not those from other 'sub-libraries').
2016-05-13 14:12:10 +02:00
6276726bc4 Fix T47652: Texture shading mode fails to update material colors 2016-05-13 22:16:14 +10:00
029ccca0fe Armature meshdeform evaluation: parallelize computation of bbones deform matrices.
On big and complex rigs like blendrig or koro, it can give up to ~10% more FPS in best cases.
Hard to tackle all cases in tests though, so please report any unexpected slowdown
in armature animation playback!
2016-05-13 12:06:15 +02:00
868cfc5a4a BLI_task: add support for listbase parallelized for loops.
Code by @sergey, with small edits and doc by @mont29.
2016-05-13 12:06:15 +02:00
990fab73ea Cleanup: fix inconsitency in dynamicPaint_outputLayerExists()
Dyna WPaint indeed only uses first output layer, but better be consistent in those cases...
2016-05-13 12:06:15 +02:00
d4b8aa476b Dynapaint: cleanup of BKE code.
Line lengths, monolined 'if' statements, int -> bool, etc.

Also, replaced some internal cooked stuff by BLI helpers (most notably, the
'is inside UV triangle' code in `dynamicPaint_createUVSurface()`), and some
other minor optimizations.
2016-05-13 12:06:15 +02:00
ba6519f0a7 BLI_math: add 'equals_m4m4' (and 'm3' variant) helpers. 2016-05-13 12:06:15 +02:00
0903ee6ce2 Cycles: Scale debug pass with number of samples
This way it's easier to compare different renders together without
worrying about scale too much.
2016-05-13 11:22:18 +02:00
958d613f66 Image editor: Show actual value of single-channel buffer in sample info
Previously if image only had single channel only z buffer value was displaying.
This isn't handy for cases when you've got single channel buffer which is not
a z buffer.

Also fixed possible read past the array.
2016-05-13 11:22:18 +02:00
b72aef92c4 install_deps: Avoid conflicts on Arch-based systems when gcc-multilib is installed
install_deps can fail due to conflict between gcc (referenced by base-devel) and
gcc-multilib if the latter is installed. This avoids the conflict by filtering
the contents of base-devel when needed.

Reviewers: mont29

Differential Revision: https://developer.blender.org/D1944
2016-05-12 18:17:14 -04:00
3c85e1ca1a Cycles: Add support for single channel byte textures.
This way, we also save 3/4th of memory for single channel byte textures (e.g. Bump Maps).

Note: In order for this to work, the texture *must* have 1 channel only.
In Gimp you can e.g. do that via the menu: Image -> Mode -> Grayscale
2016-05-12 14:51:42 +02:00
cde10e774c Fix array bounds compile warning. 2016-05-12 14:20:12 +02:00
86b509229f Fix T48413: editmesh intersect tool crash
Its important to add tri-edge intersections from both sides.
2016-05-12 21:00:08 +10:00
8d3f367c01 Correct debug prints 2016-05-12 20:59:48 +10:00
ea41207c3b Fix depsgraph tagging during the relations build pass.
Followup commit to 18e5e2fa1a. Needs the same
treatment in the second pass when ID tags are reset again.
2016-05-12 09:55:48 +02:00
80b1adf8c2 BMesh: avoid calling delete operator w/ face dissolve
In nearly all cases this isn't needed.
2016-05-12 16:47:30 +10:00
031715f743 Fix missing piece in recent rBce65fae8f32c (support for '+' key).
Thanks to Daniel Rivera (Dr2d4) for the headup!
2016-05-12 08:15:59 +02:00
689e45284b Recent bmesh face-join caused regression (T48407) 2016-05-12 16:11:42 +10:00
8de3303a03 Cleanup: Fix typo. 2016-05-12 02:11:36 +02:00
c5ddbf181e Armature outline drawing used single width line
Only set line width in pose-mode
2016-05-12 07:14:44 +10:00
d3ed8233ff BMesh: use active face fallback w/ select-path
From user perspective, last selected face is the same as the active face,
use this as a fallback.
2016-05-12 07:11:19 +10:00
16ce1b78b0 Cleanup: Remove outdated comment and add new one about slot IDs. 2016-05-11 22:25:48 +02:00
4a4f043bc4 Cycles: Add support for single channel float textures on CPU.
Until now, single channel textures were packed into a float4, wasting 3 floats per pixel. Memory usage of such textures is now reduced by 3/4.
Voxel Attributes such as density, flame and heat benefit from this, but also Bumpmaps with one channel.
This commit also includes some cleanup and code deduplication for image loading.

Example Smoke render from Cosmos Laundromat: http://www.pasteall.org/pic/show.php?id=102972
Memory here went down from ~600MB to ~300MB.

Reviewers: #cycles, brecht

Differential Revision: https://developer.blender.org/D1981
2016-05-11 21:58:34 +02:00
544b76ac9c BMesh: ignore non-manifold face connections
Was showing an error message,
now dissolve the faces that and delimit at non-manifold boundaries.
2016-05-12 06:00:05 +10:00
a46d930d8b BMesh: add BMW_ISLAND_MANIFOLD
An island walker that only walks over manifold edges.
2016-05-12 05:59:59 +10:00
f6948083e9 BMesh Island Walker: use direct loop access 2016-05-12 05:30:20 +10:00
135064c45e BMesh: remove exception from face-join function
Callers need to check for NULL, if we need to know exact cause it could be a return arg.
2016-05-12 04:42:45 +10:00
1b003511be BMesh: boundary walker, skip non-manifold loops
Instead of setting an exception, treat non-manifold edges as boundaries.
2016-05-12 04:39:01 +10:00
674bf2fe58 BMesh: add check for manifold loop 2016-05-12 04:37:36 +10:00
5d93836a61 Cleanup: only use r_ prefix for return args 2016-05-12 04:36:16 +10:00
fbbac6807a Cleanup: unused win32 headers 2016-05-12 04:35:40 +10:00
8dea74bb4f error in last commit 2016-05-12 01:43:56 +10:00
725a088ef9 Correct check for tree being in BVH cache 2016-05-12 01:40:50 +10:00
79d01de6b0 Remove pointer typedef from BVHCache
Used ** arguments unnecessarily,
also replace BLI_linklist_apply with while loop.
2016-05-12 01:40:46 +10:00
63432f1424 Fix crash snapping to mesh with no geometry 2016-05-12 01:00:43 +10:00
92774ff792 Cycles: Use explicit qualifier for single-argument constructors
Almost in all cases we want such constructors to be explicit, there are
exceptions but only in few places.
2016-05-11 16:51:14 +02:00
d57f416e47 Fix incorrect FLT_MIN use 2016-05-11 21:36:42 +10:00
67d2de8828 Transform Volume rewrite/refactor
Take advantage of the efficiency provided by the snap_context.

Also fixes errors:
- volume snap fails based on view angle (T48394).
- multiple instances of dupli-objects break volume calculation.
2016-05-11 20:20:25 +10:00
4a135ad2b7 BMesh: correct fix for face-join removing attached faces 2016-05-11 20:12:52 +10:00
de72dcadbb Fix for inline documentation of FOREACH_NODETREE.
Was missing id macro variable.
2016-05-11 10:53:11 +02:00
18e5e2fa1a Fix for node tree ID tagging in new depsgraph.
Nested node trees are not handled in BKE_main_id_tag_all.
2016-05-11 10:53:11 +02:00
b4b269f38e Depsgraph: Add some missing relations
Those cases requires not only geometry component, but also a transform one
to be ready before evaluation can start.
2016-05-11 09:24:16 +02:00
35531657e5 BLI_kdopbvh: Use distance for BLI_bvhtree_ray_cast_all
Pass distance argument so its possible to limit the range we get all hits from.

Other changes:

- Use boundbox test before calling callback, avoids redundant calls.
- Remove meaningless return value.
- Add doc string, explaining purpose of this function.
2016-05-11 15:01:27 +10:00
a18f4d2bc6 CMake: optional date/time overrides for reproducible builds 2016-05-11 02:47:38 +10:00
c1e4aaa289 Fix T48387: Mirror weights keeps groups assigned
Swapping the weights kept zero weight verts assigned.
2016-05-11 02:47:38 +10:00
e525a06800 BMesh: only remove loose geometry when joining faces
Joining faces could remove faces that happened to share an edge that would normally be removed.
2016-05-11 02:47:38 +10:00
98123ae916 BLI_task: nano-optimizations to BLI_task_parallel_range feature.
This commit makes use of new taskpool feature (instead of allocating own tasks),
and removes the spinlock used to generate chunks (using atomic ops instead).

In best cases (dynamic scheduled loop with light processing func callback), we
get a few percents of speedup, in most cases there is no sensible enhancement.
2016-05-10 17:57:53 +02:00
fdd999042b Depsgraph: A bit of experiment with skipping where_is_bone if channels is taged as done
This is what old dependency graph was doing and apparently this avoids some updates,
however it's not really clear why those nodes are considering done. Maybe just because
of the way how relations are working. But needs a closer investigation.
2016-05-10 17:30:19 +02:00
e343e4a5ba Avoid per-constraint-target call of strlen
It's enough to do one single comparison to see if the string is empty or not.
2016-05-10 17:15:16 +02:00
2786b0bc9d Optimize action constraint by avoid memory allocation 2016-05-10 16:45:27 +02:00
e1a254d8de Attempt to fix blenplayer after recent changes 2016-05-10 16:14:24 +02:00
335274192e Revert "Task scheduler: Avoid mutex lock in number manipulation functions"
Appears mutex was guarateeing number of tasks is not modified at moments
when it's not expected. Removing those mutexes resulted in some hard-to-catch
locks where worker thread were waiting for work by all the tasks were already
done.

This reverts commit a1d8fe052c.
2016-05-10 15:43:03 +02:00
f501dfb085 Depsgraph: Use some more threading when tagging and finalizing evaluation
Also don't reset values there which were re-set on the next evaluation anyway.
2016-05-10 15:42:44 +02:00
a1d8fe052c Task scheduler: Avoid mutex lock in number manipulation functions
It seems using atomic operations here we can avoid having mute without
breaking anything.

Thanks Bastien for double-checking the changes!
2016-05-10 14:59:19 +02:00
9239257806 Fix T48393: Blender player doesn't start on files saved with with cyrillic letters in path 2016-05-10 14:31:00 +02:00
fcc2175710 Fix own mistake in rBd617de965ea20e5d5 from late December 2015.
Brain melt here, intention was to reduce number of tasks in case we have not much chunks of data to loop over,
not to increase it!

Note that this only affected dynamic scheduling.
2016-05-10 13:10:21 +02:00
898d040b0c Depsgraph: For big graphs update pending parents in threads
Gives additional speedup from ~88 to ~91 fps with a test rig.
2016-05-10 13:02:54 +02:00
288bbee5b1 Depsgraph: Comment evaluation priority out for now
It uses some additional compute power and the evaluation priority is
not even used.

This brings fps 88.2 with blenrig_for_debugging.blend on this desktop.
2016-05-10 12:05:09 +02:00
ce2c15deaf Depsgraph: Avoid multipel editors update per same ID
Simple thing, and apparently fps goes up to 80 with the demo file from jpbouza.

Not sure why at this point fps is so much higher than the old dependency graph
here now. And it's definitely something what others should verify as well.
2016-05-10 11:25:57 +02:00
12a20b78d3 Depsgraph: Don't leave active thread if there's only one children node
This reduces stress on the task scheduler and avoids some unwanted overhead
caused by all the threading business in the cases when there's only one
children node. We try to immediately switch to it's evaluation now, keeping
active thread up and running.

This bumps FPS from 58 to 64 on the blenrig test file from jpbouza.
2016-05-10 10:39:38 +02:00
7efa34d078 Task scheduler: Add thread-aware task push routines
This commit implements new function BLI_task_pool_push_from_thread()
who's main goal is to have less parasitic load on the CPU bu avoiding
memory allocations as much as possible, making taks pushing cheaper.

This function expects thread ID, which must be 0 for the thread from
which pool is created from (and from which wait_work() is called) and
for other threads it mush be the ID which was sent to the thread working
function.

This reduces allocations quite a bit in the new dependency graph,
hopefully gaining some visible speedup on a fewzillion core machines
(on my own machine can only see benefit in profiler, which shows
significant reduce of time wasted in the memory allocation).
2016-05-10 10:01:24 +02:00
401e710807 Correct armature-sketch snap context use
Use scene snap mode.
Also allow passing NULL ray-depth which falls back to BVH_RAYCAST_DIST_MAX.
2016-05-10 16:47:57 +10:00
ce65fae8f3 Fix T48369: Missing suport for main '+' key.
Many keyboard layouts (italian, spanish, german...) have direct access to '+' key on main
keyboard area (not the numpad one), ans x11 has own define for this key, so use it instead
of generating an unkown key event.

Note that we most likely have much more missing 'specific' keycodes for non-US keyboard layout,
but think since we already had a 'minus' keyevent, supporting 'plus' one is totally consistent.
And we had a spare space in our defined values just for it even!

This keyevent is only supported/generated by x11 and cocoa Ghost backends for now,
neither SDL nor win32 seem to have matching key events...
2016-05-10 08:29:03 +02:00
76481eaeff Cycles: Add support for float4 textures on OpenCL.
Title says it all, this adds OpenCL float4 texture support.

There is a bug in the code still, I get a "Out of ressources error" on nvidia hardware here, not sure whats wrong yet.
Will investigate further, but maybe someone else has an idea. :)

Reviewers: #cycles, brecht

Subscribers: brecht, candreacchio

Differential Revision: https://developer.blender.org/D1983
2016-05-10 02:53:50 +02:00
dc82c2cd48 View selected support for grease-pencil 2016-05-10 04:37:00 +10:00
119230b565 Cleanup: header, style 2016-05-10 03:03:34 +10:00
d8cf14fa67 Fix T48388: Undo history sculpt mode not visible 2016-05-10 02:42:14 +10:00
9513bdcaea Buildbot: Attempt to make sure install folder is always clean for Win and OSX 2016-05-09 17:34:02 +02:00
ba3ae9ea27 Cleanup and refactor our atomic library.
This commit:
* Removes most of all dirty internal details from public atomi_ops.h file, and move them into /intern private subdir.
* Removes unused 'architectures' (__apple__ and jemalloc).
* Split each implementation into its own file.
* Makes use of C99's limits.h system header to determine pointer and int size, instead of using fix hardcoded list of architectures.
* Introduces new 'faked' atomics ops for floats.

Note that we may add a lot more real and 'faked' atomic operations over integers and floats
(multiplication, division, bitshift, bitwise booleans, etc.), as needs arise.

Reviewers: sergey, campbellbarton

Differential Revision: https://developer.blender.org/D1982
2016-05-09 17:03:08 +02:00
299a25cb35 Fix weight-mirror reporting invalid failed mirror verts
Use vertex tagging instead of clearing mirror index.
2016-05-10 00:57:00 +10:00
f616caa315 CMake: Fix compilation error when toolkit gives empty result
Should we also check whether toolkit exist perhaps?
2016-05-09 16:05:02 +02:00
df07303fbb Depsgraph: Avoid unneeded relations update when canceling transform
This was originally done for T46320 in order to re-store depsgraph state
after all the constraint modifications.

However, it relations were updated if there's any IK chain the the pose,
which is a bit too annoying.
2016-05-09 16:04:26 +02:00
5ae4487351 Missed last commit 2016-05-09 23:51:42 +10:00
6172bdbde8 Remove redundant error checks in grease-pencil tessellation 2016-05-09 23:47:57 +10:00
8b13555b24 Docs: comment polyfill2d functions 2016-05-09 23:47:57 +10:00
9ac35be63a Task scheduler: Don't calloc in performance-critical areas
Majority of the fields are being overwritten anyway, so calloc it
kinda waste of CPU ticks.
2016-05-09 14:54:24 +02:00
86a57b04bf Depsgraph: Store node input/output links in a vector rather than in set
Set is much slower to iterate through (due to cache misses and such) and
the only advantage of using set is faster removal of link. However, we are
iterating links much much more often than removing them, and even when we
are removing links we don't really need to remove link from nodes which it
connects -- we don't support partial depsgraph updates, so removing links
from nodes on destruction is a waste of time.

If we ever want to support partial updates we can have dedicated function
to remove link from nodes it connects.

This gives a surprising increase of fps from 42 to 56 with test file from
Mr. J.P.Bouza (blenrig_for_debugging.blend). Surprising because old DEG is
actually slower here (52 fps). Didn't see any regressions (and don't see
why they will happen), so let's ask our riggers and animators to perform
further speed tests ;)
2016-05-09 12:42:53 +02:00
5dbeea95d0 Depsgraph: Avoid having per-node lock when scheduling children
Use atomic operations instead, should in theory improve timing of
scheduling. However, probably not so visible yet because actual
task scheduling still have some locks and memory allocations.

Baby steps, what would i say.
2016-05-09 11:58:36 +02:00
dc5e02c42c Atomics: Add atomic_fetch_and_or_uint8() function
Hopefully it compiles on all platforms still..
2016-05-09 11:45:43 +02:00
a27772cd66 Fix makesdna not checking alignment for a non-native platform
This was causing alignment issues which were only visible on a platform
of particular bitness, so it was easy to break stuff for 32bit when
working on 64bit platform and vice versa.
2016-05-09 09:54:51 +02:00
3ce3163379 Fixes for GPencil Copy and Paste
* Fix "Attempt to free NULL pointer" when copying strokes for the first time

* Fix poll callback on "paste" operator, so that it is possible to paste
  strokes when there are no editable strokes visible.
2016-05-09 19:42:34 +12:00
d6555d936c Cleanup: Avoid duplicative defines for CPU textures, use the ones from util_texture.h
Also includes some further byte -> byte4 renaming, missed that in last commit.
2016-05-09 09:16:41 +02:00
e0e7d94f79 Fix error introduced by removing faces before executing bridge
Commit 86abddc9, caused an error when the face-region included boundary edges.
Since removing the faces first, caused the edges along the boundaries to be removed.

Add support for deleting faces and internal edges, that keeps boundaries.
2016-05-09 16:21:00 +10:00
69be8d7cbd Fix error in recent snap refactor
Crash in edge snapping
2016-05-09 15:46:34 +10:00
73fab5bb3f Fix crash introduced w/ snap refactor
Create snapping context when in the 3d view,
transforming pose bones and grease-pencil crashed.
2016-05-09 15:46:34 +10:00
dc4c3ce592 GPencil: Added operators to select first and last points of strokes
These are useful for removing overshoots at the end of closed strokes (for fills)
2016-05-09 17:23:36 +12:00
0578d3ef3e Graph Editor: Ctrl-Click keyframing now deselects all existing keyframes by default
Now, when creating new keyframes in the graph editor by ctrl-clicking, only
the newly created keyframes will be selected. This is a little workflow tweak
to make it faster to work, as you no longer have to deselect all, and then
re-select the newly added keys in order to manipulate them.

The old behaviour (not modifying the selection status of the old keys) has been
kept, but is now available via Shift-Ctrl-Click.

Feature request from @Shhlife
2016-05-09 17:23:35 +12:00
9a1e11260c Cleanup: More byte -> byte4 renaming for consistency. 2016-05-09 02:22:01 +02:00
5fe1bea2da Info Header / URLs: Fix community link + https'ification. 2016-05-08 23:38:41 +02:00
98e2135a2d Fix T48380: fix for recent image manager code cleanup. 2016-05-08 21:41:25 +02:00
a815e10211 Code cleanup: use special type instead of node names. 2016-05-08 20:21:04 +02:00
dfe9aa25c3 Code cleanup: tweaks to image manager code found while looking into previous bug. 2016-05-08 20:20:53 +02:00
e362b04c43 Fix T48377: Cycles crash removing float image texture node during viewport render. 2016-05-08 19:48:22 +02:00
5fde5616e0 Fix T48372: missing OS X trackpad scroll support for increasing loop cut / bevel segments. 2016-05-08 19:06:48 +02:00
2d8db0de79 Docs: explain some details of RNA enums 2016-05-09 02:37:34 +10:00
cbaa25eb88 Cycles: Fix two small memory leaks and deduplicate table freeing
This commit makes remove_table skip the freeing if the offset is
already set to invalid - or, if it wasn't, set it to invalid after freeing.

That's what the current code was already doing in the Manager classes,
this change allows them to just call remove without the additional code.

Also, two potential memory leaks where new tables were always allocated
without freeing the old ones are fixed.

Reviewers: sergey, dingto, brecht

Differential Revision: https://developer.blender.org/D1974
2016-05-08 17:44:03 +02:00
6100c2d262 Cleanup: warnings 2016-05-09 01:16:58 +10:00
e2b79a0a24 GPencil Onion Skinning: Setting before/after to -1 will turn off onionskinning in that direction
This is an experimental option that I found would have been useful to have,
when making my earlier anim test. The only contentious point is whether it's
better to use a separate boolean flag (perhaps bound to the labels) instead
of overloading this setting (and describing the usage in the tooltip).
2016-05-09 03:03:40 +12:00
d6fd6d18d7 Fix: Toggling "lock layer" for GPencil layers in the dopesheet didn't update the layers UI 2016-05-09 02:49:32 +12:00
c4a5c26a59 Fix: Lasso select for Grease Pencil doesn't work in the Nodes Editor
In the nodes editor, Ctrl-LMB-drag is taken by "Cut", and it seems impossible
for any other keymap to override that. Instead, the default lasso select hotkey
there is Ctrl-Alt-LMB-drag instead.

To get Grease Pencil lasso select (in GP Editmode) to work in the Nodes Editor too,
this commit adds the Ctrl-Alt-LMB-drag binding here too. However, to make things easier,
this extra binding will be part of the Grease Pencil keymap everywhere. There doesn't
seem to be any conflicts with having this in place - until we find them, this should
be ok to have.
2016-05-09 02:44:21 +12:00
491ad6664e Tweak to GPencil layers UI layout
I'm still not happy with this layout as it is now, but it seems a bit less unbalanced
than what I'd been trying before. So, let's leave this as-is for now.
2016-05-09 02:04:28 +12:00
3f934b06a6 Tweaks for a tooltip I missed during earlier review for D1886 2016-05-09 02:00:23 +12:00
d4ed5c398e A "better" (?) fix for msvc silliness - used in one other place in all of Blender 2016-05-09 01:46:18 +12:00
e43ee5563b Fix compiling on MSVC - M_PI undefined 2016-05-09 01:31:13 +12:00
81c302bbff Action Editor: Initial support for a Properties Region
This commit adds some of the initial support for a properties region in the
Action Editor. There are currently no panels to display, as there is still
a lot of work required to port over the required internal architecture to
support the panels seen in the Graph Editor.
2016-05-09 00:53:52 +12:00
9dbe7bbe9a D1886: GPencil - Add smooth iterations parameter to get better quality
After some test, a new iteration parameter has been added in order to
apply repetitive smoothing to the stroke. By default 1 iteration is applied,
but can used any number between 1 and 3.

The repetition uses different levels of intensity from 100% of the defined smooth
factor for the first loop, 50% for the second and 25% for the third. We use in each
loop a smaller value in order to avoid deform too much the stroke.
2016-05-09 00:53:51 +12:00
dc78e47b77 Fix for D1705: Update to fix the bug with extra triangles that produces glitches in some situations 2016-05-09 00:53:51 +12:00
011786a3f8 GPencil Fills: Small reshuffle of UI buttons
Now, stroke-related things (thickness, volumetric, points) and fill-related things
(HQ fill) are in the relevant columns, instead of having some in each column.
2016-05-09 00:53:50 +12:00
b88535ed28 Code Cleanup: Just a bit more tidying up comments/whitespace/etc.
There is still some instability in how the triangulations are happening,
where the triangle count of the resulting triangulation fluctuates resulting
in weird artifacts sometimes.

To reproduce, try drawing some U-shapes, and keep reloading the file.
2016-05-09 00:53:49 +12:00
af8a54bd8d Fix for potential bug with new GP Fill
While trying to track down why I still keep getting some random "extra" triangles
showing up when reloading files with fills, I noticed that there's an index mismatch
here that may cause problems in some rare cases:

There are "gps->totpoints" items in tmp_triangles, but there should only be
"gps->tot_triangles" triangles in the gps->triangles array. If for whatever reason
some of the triangles in tmp_triangles are invalid, this could have meant that
while a tmp_triangles candidate was skipped, a corresponding slot for a valid
triangle also got skipped.
2016-05-09 00:53:49 +12:00
f5ddcfeb03 Code Cleanups: A bunch of tweaks to tidy up things from the GPencil Fill patch 2016-05-09 00:53:48 +12:00
1d5c71bca7 D1705: Fix Grease Pencil Fill for Concave Shapes
Improve filling for concave shapes using a triangulation of the stroke.
The triangulation information is saved in an internal cache and only is
recalculated if the stroke changes.

The triangulation is not saved in .blend file.

Reviewers: aligorith

Maniphest Tasks: T47102

Differential Revision: https://developer.blender.org/D1705
2016-05-09 00:53:47 +12:00
0411cfea9d Fix T48373: Crash when using dynamic paint with brush material.
`dynamicPaint_doMaterialTex` was called from inside an omp parallel section with brush->dm
itself, and not the local dm copy. Generating looptri data is not thread safe at all...
2016-05-08 11:39:45 +02:00
1955754934 Cycles: Cleanup: Swap order of the RNG-state-initializing for-loops
Swap the for-loops in the RenderBuffer reset code to follow the convention
of looping over y in the outer loop.
The improved cache performance won't really be noticable here, but it's nicer
if it follows the usual style.
2016-05-08 01:22:28 +02:00
e5b4e6b0a3 Clamp dot-product to avoid precision error
Would only happen in degenerate cases.
2016-05-08 00:04:05 +10:00
1c46ecd86b Cleanup: Remove unneded (void) line, we don't have ifdefs here anymore. 2016-05-07 15:55:28 +02:00
a3b42d638b Cleanup: whicespace 2016-05-07 23:58:04 +10:00
b132f3ac7b Correct render-border line width 2016-05-07 23:53:35 +10:00
6d402610c1 Correct error in wrapped array-span-iteration 2016-05-07 23:48:53 +10:00
f5930759a6 Fix T48368: Cycles mix RGB constant folding bug after recent refactor. 2016-05-07 14:21:15 +02:00
68e856da03 Curve Fitting: better fallback when least-square solution fails
Take curvature into account when calculating handle length.

Gives significantly better results for curve dissolve and 10-20% more efficient freehand drawing.
2016-05-07 21:48:00 +10:00
d2296cd5ec Fix error copying cubic data 2016-05-07 21:38:48 +10:00
65dd1d7d08 Fix T48362: Spin tool broken after recent commit.
Typo in rBrBa48d74079, spin tool was now using the wrong view axis.
2016-05-07 11:58:33 +02:00
Martijn Berger
0a277f7428 Fix cycles-xml with OSL support after changes inroduced in 1422f0dd16 2016-05-07 10:50:21 +02:00
4422b3f919 Some fixes for CUDA runtime compile:
* When Baking wasn't used we got an error.
* On top of Volume Nodes (NODES_FEATURE_VOLUME), we now also check if we need volume sampling code,
so we can disable that as well and save some further compilation time.
2016-05-06 23:13:33 +02:00
734d1aec3f Cycles: Make CUDA adaptive feature compile a Debug flag.
If the CUDA Toolkit is installed and the user is on Linux,
adaptive, feature based CUDA runtime compile is now possible to enable via:

* Environment flag CYCLES_CUDA_ADAPTIVE_COMPILE or
* Debug menu (Debug value 256) in the Cycles UI.
2016-05-06 23:13:33 +02:00
bd335f13fe Fix T47657: Using template_list() with invoke_props_dialog()
popups have no wm_region in context, using wm_menu here.

Not working perfect, but at least it prevents crash.
2016-05-06 21:56:54 +02:00
8c2cec937b Fix T48262: Crash when trying to render a scene without camera. 2016-05-06 21:41:56 +02:00
e074554f8f Image Editor: Add border zoom
Use Shift-B, UV border-select-pinned is now Ctrl-B.

Patch from @rav66
2016-05-07 04:32:08 +10:00
ddbc351dd3 Fix recent issue in recent BVH snap/cache
The derivedMesh could free a tree stored by the cache.
Now check the cached tree is valid.
2016-05-07 02:59:19 +10:00
9c6f33c405 Correct in-range assert (zero is valid) 2016-05-07 02:16:21 +10:00
9f96976e59 DerivedMesh: don't allocate a new material array each draw 2016-05-07 02:16:21 +10:00
bd309603c5 Clip invisible parts of image when drawing in 2D textures and GLSL Modes
This commit avoids draw of invisible parts of image in image editor,
making it faster to re-draw the image.

Especially handy when painting on a high-res image when zoomed-in.
2016-05-06 16:54:07 +02:00
dd52bf8fb9 Cleanup: Move full SVM statistics to VLOG(2) verbosity level. 2016-05-06 14:39:41 +02:00
3807bcb3a8 Cleanup: Rename texture slots to float4 and byte, to distinguish from future float (single channel) and half_float slots.
Should be no functional changes, tested CPU and CUDA.
2016-05-06 14:37:35 +02:00
36d8a70b00 Code refactor: Change Cycles ImageManager arrays.
This commit simplifies the code for the image arrays. Instead of having 2 arrays for float and byte textures,
we now use an array here. This simplifies the code (avoids code duplication), and makes it possible to easily extend it
with float1 and half-float types in the future.

Only tested with CPU yet, plus some cleanup / code de-duplication is still possible here.

Reviewers: #cycles, sergey

Reviewed By: #cycles, sergey

Subscribers: jesterking, sergey

Differential Revision: https://developer.blender.org/D1969
2016-05-06 13:20:09 +02:00
8aa3bac7af Tweak precision for interocular distance and convergence plane
Previous number of digits after point was not really useful, especially
for the interocular distance where it's quite common to go sub-cm precision.
2016-05-06 12:32:23 +02:00
ef0c02cb4d Speedup of regular 2D painting
Yet another commit which makes painting aware of multi-threaded systems.
2016-05-06 11:49:09 +02:00
204f55c189 Cloth: Fix shrinking to properly respond to animated min/max and weight.
Enable dynamic restlen recomputation based on sew flag and update the
shrink factor math within it to call the new utility function.
2016-05-06 11:40:20 +03:00
2a9ddc808d Cloth: Change ClothVertex::xrest to actually store the rest position.
Originally the value was only needed when building the springs,
so a pointer to the input data was somewhat ok. However, recalculating
spring length dynamically requires keeping the actual value around.
2016-05-06 11:40:19 +03:00
Luca Rood
fcfbe27826 Part of D1903: Dynamic base mesh for cloth simulation
A function that recalculates cloth spring lengths.
2016-05-06 11:40:19 +03:00
8e1ab9b137 Cloth: Ignore zero-restlen sewing springs in average length computation.
The average length is used to adjust self-collision and stiffness
to match mesh density, and in either case considering the always zero
restlen sewing springs doesn't actually make much sense.

The struct_springs variable is also used for other things like total
spring count, so a new one needed for the true struct springs.
2016-05-06 11:40:19 +03:00
b481e886e5 Cloth: Use Geometrical Mean for averaging cloth shrink factor.
This comes out of considering a one-dimensional transition in weight
on a rectangular cloth grid. At the transition face loop, one side
of each rectangular face would be scaled by k1, and the opposite one
by k2, thus turning the rectangle into a trapezoid. Averaging would
be used to choose the scale factor for the remaining two sides.

If Geometrical Mean, i.e. sqrt(k1*k2) is used, it so happens that the
diagonals of the trapezoid also end up scaled by sqrt(k1*k2) compared
to the original rectangle. This means that the same scale factor is
correct for both structural and shear springs, which is not the case
with simple average.
2016-05-06 11:40:19 +03:00
8d22a8afa0 Cloth: Fix the shrink feature to be controlled by the sewing spring flag.
Previously it was all over the place: without a vertex group it was
always enabled, and with it it depended on the Self Collision option
due to a likely editing mistake. Now it should be in sync with what
disables the fields in the UI.

The verts->shrink_factor field is changed to just cache the vertex
weight, with the shrink_min/shrink_max interpolation done later.
This is because cloth_apply_vgroup only runs if there are vertex
groups, and thus the factor may not update after property changes.

In addition, bending springs are now also affected by the shrink
factor to avoid visible distortion in object shape at high shrink.
2016-05-06 11:40:19 +03:00
ae3f68109d Cloth: Invalidate cache when sewing springs are toggled on or off. 2016-05-06 11:40:19 +03:00
7ecc159f37 Force Fields: Fix Texture with both Use Coordinates and 2D enabled.
From description, Use Coordinates evaluates the texture using
target coordinates in the local space of the force field object.
2D is supposed to ignore the Z coordinate. Thus one would assume
that if both are enabled, the force field effect would move with
the force field object, and Z would be 0.

However, instead first the 2D option projects points onto a plane
passing through the global zero and orthogonal to the local Z,
and only then the resulting point is transformed into local space.
Z is not locked at 0, so procedural textures like Spherical Blend
don't work as expected.

To fix this, apply local transform first, and then just clear Z if 2D.
2016-05-06 11:40:18 +03:00
8cc4f3f52a Implement threaded partial display buffer update
This speeds up update of display buffer when affected area is big enough.

Mainly helpful for cases when doing long fast strokes when painting.
2016-05-06 10:04:29 +02:00
bc1a7d9283 Cleanup: warnings
Values set but not used
2016-05-06 16:49:25 +10:00
304501193b Fix T48356: Bridge tool creates self-intersecting loop
When loops are planar to eachother, initialize their winding based on surrounding geometry.
2016-05-06 10:22:02 +10:00
86abddc96a Fix error bridging edge loops flipping
Calculating the winding failed when faces exist on both sides of the edge.
2016-05-06 08:53:51 +10:00
37ad451b8e Cycles: Comment out unused function arguments 2016-05-05 23:47:22 +02:00
9b89071c9c Multi-thread generated image creation
Gives about 2x speedup on laptop when creating new hires generated image,
regardless of it's type (color, color grid, uv grid).
2016-05-05 23:47:22 +02:00
3064270e13 Correct snap checks for edges & faces
Snap targets can't contain vertices which are being transformed
2016-05-06 07:44:07 +10:00
5e72ea4397 Don't overwrite existing snap context
Re-activating transform would overwrite previous context, leaking memory.
2016-05-06 06:47:21 +10:00
d12378da11 Cleanup: style 2016-05-06 06:34:25 +10:00
ee5eb2a26a Missed last commit 2016-05-06 06:28:36 +10:00
55c4889864 bvhutils: remove bitmap counting
All callers pass in valid number
2016-05-06 06:14:36 +10:00
c5a26bef5d Cleanup: rename getepsilon -> get_epsilon 2016-05-06 06:14:36 +10:00
cc650c3d07 Add asserts to check bvhutils args are correct
Would have prevented previous error going unnoticed.
2016-05-06 06:14:36 +10:00
7efdee7517 Fix crash adding byte color grid images 2016-05-05 22:05:09 +02:00
7b7e7ac4c1 Code cleanup: simplify SVM stack assignment. 2016-05-05 21:43:46 +02:00
0f943337bc Code cleanup: remove some unused functions. 2016-05-05 21:43:46 +02:00
dd8bfa0929 Code refactor: reduce special node types, use generic constant folding. 2016-05-05 21:43:46 +02:00
2cfadecf97 Fix Cycles emission node being unnecessarily tagged as spatially varying. 2016-05-05 21:43:46 +02:00
9a20ff2b52 Fix OS X build error after SSE changes, BLI_math_base.h conflicts with EXR headers. 2016-05-05 21:43:46 +02:00
4aaafcbc45 Fix for fix, sorry for the noise 2016-05-06 05:46:07 +10:00
2812a8f7eb Missed last commit 2016-05-06 05:42:33 +10:00
7122b05ac3 Correct own mistake int recent transform API edits
Need to return number of enabled elements.
2016-05-06 05:40:07 +10:00
46ccc54faf Fix error not using the cached BVH tree 2016-05-06 05:17:34 +10:00
0b5a0d8412 Transform/Snap: EditMesh/BKE_bvhutils API improvements
Separate the creation of trees from EditMesh from the creation of trees from DerivedMesh.
This was meant to simplify the API, but didn't work out so well.

`bvhtree_from_mesh_*` actually is working as `bvhtree_from_derivedmesh_*`.
This is inconsistent with the trees created from EditMesh. Since for create them does not use the DerivedMesh.

In such cases the dm is being used only to cache the tree in the struct DerivedMesh. What is immediately released once
bvhtree is being used in functions that change(tag) the DM cleaning the cache.

- Use a filter function so users of SnapObjectContext can define how edit-mesh elements are handled.
- Remove em_evil.
- bvhtree of EditMesh is now really cached in the snap functions.
- Code becomes organized and easier to maintain.

This is an important patch for future improvements in snapping functions.
2016-05-06 05:01:51 +10:00
88b72925d0 Optimize linear<->sRGB conversion for SSE2 processors
Using SSE2 intrinsics when available for this kind of conversions.

It's not totally accurate, but accurate enough for the purposes where
we're using direct colorspace conversion by-passing OCIO.

Partially based on code from Cycles, partially based on other online
articles:

  https://stackoverflow.com/questions/6475373/optimizations-for-pow-with-const-non-integer-exponent

Makes projection painting on hi-res float textures smoother.

This commit also enables global SSE2 in Blender. It shouldn't
bring any regressions in supported hardware (we require SSE2 since
2.64 now), but should keep an eye on because compilers might have
some bugs with that (unlikely, but possible).
2016-05-05 19:46:06 +02:00
bb6fbc64ae Docs: scanfill.c purpose 2016-05-06 00:45:38 +10:00
c8e9832be3 Fix T48320: Freestyle renders wrong edges of objects which in the other RenderLayer.
FSAA sample files in EXR format are no longer always updated (after some
changes between 2.73 and 2.74 releases), and the reported bug was caused
by old samples from a previous frame that were being merged by mistake.

The present revision addresses the documented issue by entirely skipping
the rendering of auto-generated scenes when there are no Freestyle strokes
to render, which suppresses sample merging of the render layers that were
not rendered.
2016-05-05 23:15:52 +09:00
6f83710af9 Optimize projection painting with big brushes
Multi-threaded partial buffer update, gives about 2x speedup with
big brushes.

Thanks Campbell for testing and benchmarking!
2016-05-05 14:45:00 +02:00
c81d9fda46 Optimize threaded scanline processor
Avoid memory allocation for task data.
2016-05-05 14:18:11 +02:00
c795d31a1f Simplify scanline threaded processor used by GPU_verify_image
Just avoid some unneeded initialization functions when the threaded
processor is simple enough to only depend on current chunk start
scanline and number of scanlines.
2016-05-05 13:16:56 +02:00
f5dcb137f1 Fix project paint using uninitialized edit-region
First stroke always had the minimum rectangle set to 0,0 which could cause a largre region of pixels to be
unnecessarily updated.
2016-05-05 20:57:54 +10:00
9b8bf57361 Curve Fitting: avoid clamping fallback handles. 2016-05-05 20:31:13 +10:00
d0818dbae1 Optimize Blank and Color Grid generated images
Avoid unnecessary pixels linearization gives nice speedup.
2016-05-05 12:04:42 +02:00
dd73d9c54e Correct error in recent smoothview edits 2016-05-05 19:58:45 +10:00
043486e2bc Fix typo in previous commit
Thanks Julian Eisel (Severin) for the heads up!
2016-05-05 11:33:13 +02:00
9aff51661c Optimization for initial display of high res textures in viewport
Multi-thread all the color space conversion operations.

Gives speedup from 0.8 to 0.1 seconds on a model with 4k etxture on it.
2016-05-05 11:28:50 +02:00
8c3c669c2d Image Paint: fix for calls to GPU_free_image while painting
The width and height of of the region to update are often zero,
skip calling GPU_paint_update_image in this case.
2016-05-05 18:52:11 +10:00
08be000637 Fix T48210: Editing all selected buttons fails to auto-key 2016-05-05 02:37:46 +10:00
10bbce30a9 UI: avoid getting the active button when its already known 2016-05-05 02:22:23 +10:00
6601680e8d View3D: apply smoothview before modal view operations 2016-05-05 02:01:18 +10:00
bd1378b56b Cleanup: rename ED_view3d_smooth_view_finish (to force_finish) 2016-05-05 01:51:25 +10:00
e30f0427a5 Fix error in BM_face_exists_overlap_subset
Was re-using loop index, thanks to @bzztploink for spotting!
2016-05-05 01:35:09 +10:00
875df1e2b9 Cycles: Fix hair minimal size doesn't work on GPU and SSE2 only CPUs 2016-05-04 17:14:43 +02:00
ddd6be1834 Compositor: negative color support for ASC-CDL offset
Since the color wheel can't handle negative colors usefully, use a basis value for the initial RGB.
2016-05-05 00:06:55 +10:00
980f3c3693 Fix T48346: Transparent shadows do not work for instanced objects 2016-05-04 14:46:30 +02:00
6f2797b50b Curve Draw: option to apply absolute offset
Offset used curve radius, which isn't useful drawing without any bevel radius.
2016-05-04 15:45:55 +10:00
568514c875 Fix T48340: Smooth view cancels previous view action
Previously users needed to wait for view orbit to finished,
so quickly pressing keys would gave different result.
2016-05-04 03:38:20 +10:00
Julian Eisel
9d3d9ac0b9 Fix 3D View panel header color wrong after theme reset
Caused by wrong alpha value in rB34b30f847429ac (used 0.01, should've been 0.1). Also made sure all editors initialize same default theme values for panels and cleaned up code a bit.
Works fine with old userpref.blend files.
2016-05-03 18:31:37 +02:00
645047708d Fix broken build without IME and/or I18N (caused by rBcb6307162b4c12). 2016-05-03 16:56:52 +02:00
9151095dbe Fix T48328: Outliner: Armature EditMode: crash when selecting bone of a shared amrature in another object's bone list.
Basically, issue is that outliner stores editbones for an edited armature, which are only valid during EditMode.

When more than one object use the same armature, selecting ebones from same armature but under non-edited object
would first select that object (and hence switch out of editmode), and then try to select editbone while editdata
no more exist.

Solution for now is to not change active object in this case - it's not totally ideal (not consistent),
but other solutions (like switching edited object without leaving editmode, or rebuilding (part of)
outliner tree in-between) are horribly hackish and most likely prone to epic failure anyway.
2016-05-03 15:11:42 +02:00
cb6307162b Cache whether current translation language supports IME or not
Solves the weak point mentionedi n previous commit.
2016-05-03 12:38:21 +02:00
b34f177a39 Fix T47841: Shift-space doesn't type space in type-in fields on Windows
Shift-space was reserved for IME support, however IME will only
be enabled on certain languages. We can avoid any IME-related
exceptions form other languages without too much trouble.

There's one weak point around ui_ime_is_lang_supported() tho,
which is it might be doing string comparison a bit too much
often now, this we can avoid by handling those checks from BLT.
2016-05-03 12:20:40 +02:00
bff15770a9 Fix T47424: Blender Internal material node 'mapping' not showing results of animation
Not very efficient solution -- it'll update mapping node on init ntree exec and will
not work for viewport GLSL shading perhaps, but it's as good as it could be within
current dependency graph.

The issue here is that manual edit of values will cause cached matrix re-evaluation.
but using animation does not use rna update callbacks hence no matrix update was
happening.
2016-05-03 11:44:17 +02:00
3dcc05c591 Cleanup: no need to cast for pointer comparison 2016-05-03 18:20:33 +10:00
c2f28864d6 Fix T48169: 1 pixel offset painting 2D textures
Painting at negative locations was using int-rounding.
2016-05-03 17:49:18 +10:00
ead2496e67 Cleanup: use offset macro 2016-05-03 16:40:14 +10:00
1fb17fcf23 UI: limit listview arrow/wheel bindings
Allow Ctrl-Up for eg to be used when in a list view.
2016-05-03 16:17:14 +10:00
e2a6fb1f0b UI: don't show tips when navigating ui-list 2016-05-03 14:59:45 +10:00
9953eeb012 Cleanup: use const for units API
Also make return args explicit.
2016-05-03 13:52:07 +10:00
48d3a8b54b Math Lib: inline project_plane_v3_v3v3 2016-05-03 13:48:00 +10:00
a58a8ebea7 Missed setting handles in curve dissolve 2016-05-03 00:06:12 +10:00
122496dda1 Correct header (can't use uint here) 2016-05-02 21:08:02 +10:00
f28c626574 Fix bl_load_py_modules test
- scripts that execute directly need to include their basedir in the sys.path
- modules which are in a directory without an __init__.py weren't importing.
2016-05-02 21:06:15 +10:00
143f6c4bb2 Curve: new dissolve tool
removes vertices, re-fitting the surrounding handles.
2016-05-02 18:50:12 +10:00
ec9cb57b01 Curve Fitting: expose function for fitting a single curve 2016-05-02 18:50:04 +10:00
915e9eeff1 BLI_array_utils: helper for stepping over contiguous ranges 2016-05-02 18:49:22 +10:00
c1ca667d4a Fix compilation error on Armel architecture
__GCC_HAVE_SYNC_COMPARE_AND_SWAP_n are not defined on this architecture
for some reason, however those functions are available.

Adding a workaround for newly used __sync_fetch_and_and() function.
2016-05-02 09:55:08 +02:00
4e4ff72d13 Fix T48325: Data transfer modifier vertex group selector doesn't work with freestyle data.
Freestyle edge/face marks are (afaik) our only actual customdata bitflags... Original work
kinda assumed we had no such things. :P
2016-05-01 15:36:09 +02:00
1422f0dd16 Fix Cycles external OSL shader not working with relative file paths. 2016-05-01 01:44:52 +02:00
abf6f9f6cf Fix T48118: Vertex Groups not masking particle hair emission correctly
Own regression from rB019ce363b01bba0af, not totally sure why removing the heading
zero value in element_sum broke binary search distribution in random branch, but...

New code makes thing sooo much simpler, by simply getting rid of all zero-weight
items in element_sum (at the cost of adding a temporary extra index mapping array),
that way neither random nor 'even ordered' distribution code has to wory anymore
about skipping zero-weighted items!
2016-04-30 16:56:19 +02:00
b1f6cd5a6a Slight adjustment to curve fitting tangents
Don't let the point spacing give bias to a side.
2016-04-30 16:27:43 +10:00
6ab22064c2 Fix for typo comparing double events
Also remove doubles when filling the final array.
2016-04-30 16:21:06 +10:00
ac163447f8 Cleanup: warnings. spelling 2016-04-30 04:10:34 +10:00
461604c0d5 Fix (unreported) bad 'NULL freeing' with placeholder images.
Looks like code expects some initialized Image data after all, so do it
for placeholders as well (using default generated UV grid).
2016-04-29 18:05:49 +02:00
57eb8539fc Fix crash (segfault) in node editor.
In some cases, we can have nodegroups without attached nodetree, this case is checked
in top `node_group_has_output()` entry point, but not in recursive `node_group_has_output_dfs()`.

Issue appeared after rB42824f4403db3a35, presumably because check on node flag itself
was skipping that case, which is no more possible when using ID tags.

Reported by sebastian_k over IRC, thanks.
2016-04-29 17:37:00 +02:00
467e12514e Fix broken Collada from rBrB6d0cae56e84306ed. 2016-04-29 16:56:20 +02:00
2ba7b3ea1a install_deps: add support for OpenVDB.
Note that recent DEB-based distro have packages for this, even simpler!

Differential Revision: https://developer.blender.org/D1933
2016-04-29 16:45:09 +02:00
de0b480629 install_deps: add check for glew version, too old ones are not compatible with OSD.
In case too old system glew is detected, use the one shipped with blender.

Part of D1933.
2016-04-29 16:43:28 +02:00
3ccc61c03a install_deps: bunch of cleanups, tweaks and micro-fixes.
This commit mostly:
* removes some (very) old messages or hacks (like those for ubuntu 10.4...).
* Moves lib-specific dependencies installations to upper level
  (simpler to manage, and those are small enough packages).
* Uses new dnf package manager for fedora (sigh, we now have tree different commands for fed/suse/rehl).
* fixes or enhances some options for commandline tools.
* Force anew building of oiio package, due to insane dependencies of this one in recent distro.

Part of D1933.
2016-04-29 16:35:37 +02:00
6d0cae56e8 Fix T48290: Hook fails after deleting geometry
Now CD_SHAPEKEY_INDEX customdata is stored in edit-mode when hooks and vertex parents are used.

This also fixes a bug where undo would loose key-index data.

Move to structs for BM_mesh_bm_to/from_me to avoid passing many argument, which mostly aren't used.
2016-04-29 23:39:50 +10:00
b5ce2bbef7 BMesh: when multiple vertices have the same key-index, use the first
Simple error case where many vertices share an original index,
now use the first match instead of the last.
2016-04-29 21:52:09 +10:00
3e32f8e601 Fix T48298: Cycles World environment Texture node, movie doesn't update frame 2016-04-29 10:54:40 +02:00
9e1a9fa5bb Remove redundant selection flush call 2016-04-29 17:29:23 +10:00
d3344ca7b1 Minor optimization to bmesh shape key conversion
Avoid linked linked loop and custom-data lookups per vertex,
use a table of shape-keys with array offsets instead.
2016-04-29 15:02:04 +10:00
636195e402 Fix T48301: Cycles incorrect render with CMJ and viewport samples 0.
Max samples 2147483647 was causing integer overflow.
2016-04-28 23:57:20 +02:00
a48d740798 Fix T48300: 3D view tools outside the 3d view crash 2016-04-29 00:00:43 +10:00
6976be7723 Python: install pyconfig.h on OSX, needed for PIP 2016-04-28 20:46:58 +10:00
94a6019a7b Fix T47715: EXCEPTION_ACCESS_VIOLATION crash when removing modifiers or rendering
The issue was caused by missing indirect dependencies from other scenes in the
current scene depsgraph, which was causing some threading conflicts.

Not sure what would be ideal solution here, for now use stupid but rather robust
approach to solve that. Maybe there's something better to do here tho.
2016-04-28 12:32:59 +02:00
c01c47f79d Depsgraph optimization: Don't schedule tasks for empty "NOOP" nodes.
Currently a lot of the nodes in the new dependency graph are empty placeholders
for organizational purposes. These nodes would, however, still be assigned a task
which gets scheduled and takes up some time for worker threads to pop from the
queue and run. This can be avoided by skipping these nodes during depsgraph
scheduling, and scheduling their childrent right away. Gives a few percent speedup
in BlenRig.
2016-04-28 12:10:58 +02:00
aaf5ee73f0 Fix for O(N^2) runtime tagging in the new depsgraph.
Some of the tagging functions would be called for every operation, and then
in turn tag their ID nodes with all their operations again. With extensive rigs
we get ID nodes with a lot (10,000+) operation nodes, which leads to millions
of unnecessary tagging calls.
2016-04-28 12:03:26 +02:00
8a379e3460 3D Text: avoid checking null character's text on path
Redundant and causes complications when improving text code.
2016-04-28 15:56:41 +10:00
42e6477129 Image view selected didn't account for region size
Now fit the selection with a 1.4x margin (matching 3d view).

Also move border fitting into own function.
2016-04-28 13:46:51 +10:00
6e94ec623d BMesh: limited-dissolve, add check for wire edges
Recent degenerate check crashed on chains of wire edges
2016-04-28 12:50:12 +10:00
2b485e21f4 Minor code simplification in previous commit. 2016-04-27 22:58:00 +02:00
cc692c0924 Fix compiler warning on OS X / clang. 2016-04-27 21:41:40 +02:00
dd8a7342bc Nodes: sort builtin compositor/shader/texture nodes alphabetically in menus
Reviewed By: lukastoenne, dingto, Severin, carter2422

Differential Revision: https://developer.blender.org/D1957
2016-04-27 21:37:14 +02:00
c0ae38f656 Fix artifacts w/ low near clear in bglPolygonOffset 2016-04-27 19:53:24 +10:00
7f0cf3ab38 Sequencer: skip text-effect rendering w/ no alpha 2016-04-27 15:55:50 +10:00
0912bffb84 Sequencer text strip color options
D1930 by @NiKoZLaB
2016-04-27 15:49:13 +10:00
01cdd22a52 Fix alpha blending w/ font drawing & byte buffer 2016-04-27 15:47:49 +10:00
d74957d38c Fix mask active-point being lost on load/undo 2016-04-27 14:34:54 +10:00
ed0db62a3d Mask: always add a new spline when adding a new vert
Previously, adding a new vertex with Ctrl-LMB would move an existing
when there was an active spline but no active point.

This function is used as a fallback, extending an existing active point is already handled.
2016-04-27 14:11:07 +10:00
32e20369a5 New mask points now compensate parent offset 2016-04-27 13:54:48 +10:00
6483b9cb07 Fix T48282: Newly added mask points don't follow parent 2016-04-27 13:12:55 +10:00
9bd51735a1 Cleanup: use const, duplicate header 2016-04-27 13:12:55 +10:00
c2cdc67375 Fix Cycles GLSL image texture node not respecting color space property. 2016-04-27 00:26:06 +02:00
2b3657a838 Code cleanup: minor cleanups for GPU_link return values, normal map node. 2016-04-27 00:09:44 +02:00
1da0d0042a Fix Font filebrowser not showing thumbnails when those are enabled by default in userpref.
Reported by Leon Cheung over IRC, thanks.
2016-04-26 17:18:37 +02:00
bb74e0774c Fix T47992: Stereo 3D Anaglyph rendered Images saved too light 2016-04-26 17:15:33 +02:00
f172f2b146 Cycles: Improve logging about motion blur a bit 2016-04-26 16:17:11 +02:00
ab500eb3f3 Hair edit: Add operator to uniform length of selected hairs
Request by Andy, should help him a lot doing weird and wonderful hair styles.

A bit experimental yet, details of behavior might be changed after some real
usage feedback.
2016-04-26 16:08:06 +02:00
96392c33ef Correct error in recent snap-context commit
Edges currently don't use a BVH-tree,
but would still create and attempt to free the tree.
2016-04-26 23:02:44 +10:00
680b135ec1 Fix T48176: Shrinkwrap crashes when multiple objects uses same target
Annoying bug caused by temp nature of looptri layer for CCGDM.

Fixed in a similar to CCG loops by using lock when allocating and
filling looptri arrays.

Real fix would be to make sure this array is allocated on object
evaluation using DAG's eval_flag, but that's more involved change
which we'll work on later.
2016-04-26 14:44:49 +02:00
86b8c8a042 Fix (unreported) possible freed memory usage when reloading a .blend file.
Operator would call `WM_file_read()` directly whith G.main->name as filepath, which
gets freed whith main during new reading of file... Now use a local copy instead.
2016-04-26 14:27:32 +02:00
2a63ef03f0 Fix missing pose bone hash table in stub poses of action constraints.
This is a follow-up fix for rBa10b2fe. The Action constraint uses a hackish
stub object and pose, which doesn't have a hash table for fast lookups.
This doesn't seem to be a big issue with the old depsgraph, but in the new
depsgraph it creates a large number of cache misses and significant slowdown,
possibly because of additional threading and less simple bone loops.
2016-04-26 14:16:28 +02:00
5abae51a6e Support multiple tangents for BI render & viewport
Normal Map node support for GLSL mode and the internal render (multiple tangents support).

The Normal Map node is a useful node which is present in the Cycles render.
It makes it possible to use normal mapping without additional material node in a node tree.
This patch implements Normal Map node for GLSL mode and the internal render.

Previously only the active UV layer was used to calculate tangents.
2016-04-26 20:43:29 +10:00
98babfa2b8 Fix T48211: Modifying an F-Curve modifier property is not updating the 3D window 2016-04-26 12:15:05 +02:00
2942a492f4 Fix T48259: Vertex painting doesn't trigger refresh of cycles rendered viewport 2016-04-26 11:15:28 +02:00
0f8290ad0e Fix UI message typo. 2016-04-26 10:13:02 +02:00
7b9743261d Minor cleanup in object select code
- break when object in hit-buffer.
- don't measure distance to object centers that can't be projected.
- take pixelsize into account for distance pixel distance limit.
2016-04-26 14:33:31 +10:00
bd40ded9f6 Fix T48203: Pose-Mode overrides Alt-RMB menu select
Now always use menu-select when using Alt-RMB
2016-04-26 14:24:52 +10:00
5b28fdb635 Cleanup: use const for outliner args
Also c99 edits for outliner_find_id
2016-04-26 13:09:42 +10:00
27cc015581 Outliner: "Show Active" support for active bone
Resolves T48229
2016-04-26 12:56:47 +10:00
45d9c9de35 UI messages fixes - no final point ;) 2016-04-25 20:16:34 +02:00
6a7378f50f Cycles: Proper pack of leaves which are bigger than single float4 2016-04-25 18:57:37 +02:00
a10b2fefab Fix for missing pose bone hash in the new dependency graph.
The hash table is used to look up bone poses, particularly during constraint
evaluation. Without this the default BLI_findstring method on a plain ListBase
is used, which is really slow for extensive rigs.
2016-04-25 15:41:03 +02:00
3ac2028df0 Fix T48202: Project paint hangs on UV's w/ sharp corners
Using 'shell-thickness' to offset UV's meant very sharp corners would offset far outside the image
causing project-paint to hang while collecting all pixels for each UV face.

Clamp the maximum offset to prevent this.
2016-04-25 22:21:30 +10:00
42fd1b9abe Cycles: Fix issues with stack allocator in MSVC
Couple of issues here:

- Was a bug in heap memory allocation when run out
  of allowed stack memory.

- Debug MSVC was failing because it uses separate
  allocator for some sort of internal proxy thing,
  which seems to be unable to be using stack memory
  because allocator is being created in non-persistent
  stack location.
2016-04-25 13:50:27 +02:00
34f4c31692 Cycles: Move vector re-allocation out of loops 2016-04-25 12:25:30 +02:00
beaa57d269 Refactor BKE_blender into separate headers
- BKE_blender_version.h (only version defines & versionstr).
- BKE_blender_copybuffer.h (currently only used for view3d copy/paste).
- BKE_blender_undo.h (global undo functions).
- BKE_blendfile.h (high level blend file read/write API).
2016-04-25 19:27:45 +10:00
935998312c Fix T48085: Select linked w/ seam delimit gives random results
This changes behavior so seams aren't used for the bmesh walker.
2016-04-25 18:44:11 +10:00
975a224f12 Cycles: Don't pass RNA pointers by vlaue 2016-04-25 10:04:06 +02:00
fc5a37b94e Recent pydriver update missed setting 'curval'
Using PyObject's for drivers (82b0a9e36) still needs to set the 'current value'
for debug info to display in the UI.

Resolves T48251
2016-04-25 15:27:51 +10:00
45835e227e Cleanup: use bool 2016-04-25 14:57:25 +10:00
e76f94e0fb Fix T48263: Armature modifier crash w/ non-armature objects 2016-04-25 14:41:11 +10:00
727f15f7d8 Docs: note that BMesh loops are accessed via faces
Resolves T48258
2016-04-25 11:57:52 +10:00
Julian Eisel
26564ff343 Event system: Let event pass through after menu poll fails
Part 2 of Fix for T48200. Without this, it's not possible to exit GPencil edit mode using tab key with pies enabled.

Menus are somehow similar to operators, which let the event pass through too after operator poll returns 0. So think we should handle them similar here.
Can't guarantee this is totally safe though ;)
2016-04-23 17:24:00 +02:00
35be6d87e8 Cleanup: cmake 2016-04-24 00:16:44 +10:00
39873891bf Fix T48250: suppress CMake ranlib warnings to avoid issue with Qt Creator
Reviewed By: campbellbarton, brecht

Differential Revision: https://developer.blender.org/D1942
2016-04-23 15:52:38 +02:00
Julian Eisel
16316115da Fix weird wording in driver operator tooltip 2016-04-23 15:12:20 +02:00
57d98a8048 PyAPI: support writing compressed library blends 2016-04-23 22:08:42 +10:00
a3d67456cd GHOST/X11: print description of error event 2016-04-23 18:44:17 +10:00
ab3c1de56d Fix T48173: event.mouse_prev_x/y unreliable. 2016-04-23 03:05:48 +02:00
23a9fede69 Fix T48216: Cycles light fallof node gives black emission in baking. 2016-04-23 02:59:40 +02:00
c41b2bd7c6 Fix T48223: 3D View not refresh after changing Blending mode in NLA.
This fixes a lot of things in NLA RNA update handling (which basically did not update anything previously).

There are more update issues with this editor though...
2016-04-22 16:48:57 +02:00
f69b364b88 Fix (unreported) crash when listing available fmodifier types.
Some types are defined but not yet implemented...
2016-04-22 15:23:59 +02:00
a2779a4606 Fix T48230: Home key when only one keyframe makes the DopeSheet acting weird.
Simply apply same minimal range as in graph editor when we get a zero one from keyframes.
2016-04-22 14:39:37 +02:00
f4ecd24f96 Fix curve snap to surface w/ offset & taper
Adjusting the pressure wasn't re-adjusting the offset.
2016-04-22 21:34:04 +10:00
c12e1a09ec BLF: use float vector passing color args 2016-04-22 20:02:41 +10:00
a9729e6d75 Fix T48236: OpenVDB smoke cache glitches out with smokeless flames.
Issue was that before writing to disk grids are clipped against the
density field's tree to optimize for memory/disk space, which in the
case of simulations with no density field results in all grids having
empty trees.

For now avoid clipping against empty grids, but perhaps in the future it
can be interresting to have some UI parameters to let the user choose
the grid used for clipping.
2016-04-22 11:46:02 +02:00
87dcee0c0c Silence some annoying warnings when doing full build with strict flags
This mainly touches extern libraries and few debug-only places in intern.

Some summary:

- External libraries are not strict at all about missing declarations,
  so we can rather safely remove such warning together with other strict
  flags.

- Bullet has some static functions which are not used.
  Those were commented out.

- Carve now has some unused debug-only functions commented out as well.
  While we're on the way of getting rid of Carve, it makes sense to make
  things a bit cleaner for the time being.

- In LZMA we have some parts disabled which gives some set but unused
  variables which is rather correct.

- Elbeem had quite some variables set and never used because their usage
  is inside of debug-only code which is commented out.

Note about patching upstream libraries: surely one might say that we
have to make local patchset against this, but own experience says it
only gives extra work trying to merge such tweaks to a new upstream
version and usually it's just faster to re-apply such fixes again after
bundling new upstream library.
2016-04-22 10:59:15 +02:00
d2cb0f955b Cycles: Reduce verbosity of logging
Mainly makes logging less verbose when doing progressive sampling in viewport.

Such kind of verbosity is not really possible to be filtered out with `grep`
so let's reshuffle few lines of code.
2016-04-22 10:55:26 +02:00
31632e7f74 NDof device: Check for socket exists before connecting to spnavd
This allows us to get rid of annoying and misleading error printed to the console
about being unable to connect to something.
2016-04-22 10:14:30 +02:00
599b7ad13b Transform Snap: optionally cache the BVH tree
Use the SnapObjectContext to store the bvh tree for reuse.
2016-04-22 16:38:49 +10:00
19e5540ff7 Transform Snap: initial snap context refactor
This introduces a snap-context that can be re-used for casting rays into the scene
(by operators such as walk-mode, ruler and transform code).

This can be used to cache data between calls too.
2016-04-22 16:36:53 +10:00
8dcdde52b1 Cleanup: warnings (double promote, string format) 2016-04-22 12:22:58 +10:00
0b349871d8 Fix T48212: Typos in bpy enum props examples. 2016-04-21 12:16:32 +02:00
7205bac989 Update install_deps.sh for ArchLinux.
The script is updated for ArchLinux, since all dependencies are included in Arch's official repositories.

I've made a few changes, such as enabling OCIO and OSD without requiring locally installed lib-path, and a fix to ''get_package_version_ARCH()' so it ignores package epoch (as in the case of ffmpeg).

I intend to look at OpenVDB next.

Reviewers: mont29

Differential Revision: https://developer.blender.org/D1901
2016-04-21 10:44:46 +02:00
c0943babdf Cleanup: math lib use w/ walk mode 2016-04-21 12:43:35 +10:00
22f2405d1b Mesh Deform Modifier - leave bind settings visible after binding
The 'precision' and 'dynamic' settings for binding are now always visible.
The settings that can not be edited after binding are disabled (not inactive).

I find it useful to see with what settings a mesh was bound, in case
the file is not mine or if I simply lost track of it.
2016-04-20 19:51:59 +01:00
9bd1c8caf7 Cycles: Multi-thread object transform update
Simple idea, use threads when dealing with "Copying Transformations to device"
scene update step. Only do it if there's enough objects in the scene.

Hopefully only brings less synchronization time and doesn't break anything.

From tests on my desktop this brings down transform update time from 58sec to
11sec on victor_cpu.blend scene from out benchmark.
2016-04-20 18:17:24 +02:00
02213b867e Cycles: Stop rendering when bad_alloc happens
This is an attempt to gracefully handle out-of-memory events
and stop rendering with an error message instead of a crash.

It uses bad_alloc exception, and usually i'm not really fond
of exceptions, but for such limited use for errors from which
we can't recover it should be fine.

Ideally we'll need to stop full Cycles Session, so viewport
render and persistent images frees all the memory, but that
we can support later, since it'll mainly related on telling
Blender what to do.

General rules are:

- Use as less exception handles as possible, try to find a
  most geenric pace where to handle those.

  For example, ccl::Session.

- Threads needs own handling, exception trap from one thread
  will not catch exceptions from other threads.

  That's why BVH build needs own thing.

Reviewers: brecht, juicyfruit, dingto, lukasstockner97

Differential Revision: https://developer.blender.org/D1898
2016-04-20 16:19:49 +02:00
e3544c9e28 Cycles: Throw bad_alloc exception when custom allocators failed to allocate memory
This mimics behavior of default allocators in STL and allows all the routines
to catch out-of-memory exceptions and hopefully recover from that situation/
2016-04-20 15:49:52 +02:00
d7e4f920fd Cycles: Use threads to sort reference arrays when searching for split
This commits implements threaded sorting of references when looking for
object spatial split. It mainly useful when doing initial binning, which
happens from main thread.

Gives nice speedup of BVH build for Bunny.blend: 36sec vs. 55sec for
the Rabbit mesh BVH build.

On more complex scenes the speedup is probably minimal, but still nice
to have more instant rendering for simplier scenes.

Some further tests with production scenes would be interesting.

Reviewers: juicyfruit, dingto, lukasstockner97, brecht

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1928
2016-04-20 15:21:44 +02:00
96dc96f0a5 Cycles: Avoid reference copy 2016-04-20 15:03:39 +02:00
48c9208d56 Fix T46903: Missing Render Border Menu items
While other borders are more like a toggle, it is an intrinsic behavior
of those operators. Render Border is intrinsicly split into two operators
and trying to expose it as a toggle will end up with rather confusing
situation when shortcut listed in the menu changes depending on the
context.
2016-04-20 15:02:03 +02:00
e50d229273 Fix T47794: Point density sometime seems stretched when rendered on GPU 2016-04-20 14:42:19 +02:00
b9d9d93ff9 Fix T48162: GPU render gives wrong results in certain volume setups
ideally this part of code should be de-duplicated across __VOLUME_INTERSECT_ALL
and regular code.
2016-04-20 13:49:54 +02:00
4cdd6b9bdd Fix T47812: GPU renders have warmer colors than CPU renders
Seems was a mistake in f2c54df, volume attributes are not supposed to
have repeated texture type.
2016-04-20 12:29:08 +02:00
75c9fe428f Update bundled openjpeg from 1.5.0 to 1.5.2
Solves following issues:

- Quite reasonable amount of paranoid warnings were solved by an upstream
- Upstream seems to have all fixes needed for FreeBSD and OSX already
- Brings all fixes and such from upstream
2016-04-20 10:36:58 +02:00
81a477f4dc Fix T47891: Edges throw shadow in edit mode 2016-04-20 12:59:00 +10:00
4ee5ba41bb Fix T48086: Smart UV Project fails w/ small faces
Epsilon for small faces was too large.

Also suppress exception when all faces area are below the epsilon.
2016-04-20 11:51:03 +10:00
dbf1257b14 Minor optimization for scanfill
Replace angle with with cosine calculation.
2016-04-20 09:53:40 +10:00
38442ae2dc Fix image-space mask-transform crash w/o an image 2016-04-20 09:37:51 +10:00
2ca4d21976 Cleanup: rename cos-angle to match BLI_math 2016-04-20 07:50:48 +10:00
bde7439816 Minor optimization for limited-dissolve
Use dot product instead of angle.
2016-04-20 07:50:48 +10:00
ccbfbeba74 Fix crash in rB37493fb9f - there is no guaranty CTX_wm_foo() will return a valid pointer! 2016-04-19 22:53:18 +02:00
11c9ff1edd Cleanup unused header includes from previous commit. 2016-04-19 22:53:18 +02:00
52e09ed4f9 Cleanup: move operators & related code of files & append/link to relevant dedicated source files.
This commit adds a new `wm_files_link.c` which contains everything related to append/link code,
moved from `wm_operators.c` (rather small currently, but will expand quite a bit with future reload & asset works).

It also moves all load/save .bland files (and related userpref/startup stuff) from `wm_operators.c`
to `wm_files.c` (some helper funcs were already there).

This also makes `wm_operators.c` significantly lighter.
2016-04-19 22:53:18 +02:00
Julian Eisel
dd423a6818 Fix T48198: Missing plus sign to open the tool shelf in text editor
Did not happen when using screen layout saved in default startup.blend
2016-04-19 21:01:55 +02:00
Julian Eisel
37493fb9fe Toggle to standard cursor when opening menus/popups
Cursor is now set to standard arrow-cursor when opening menu, and reset to previous one when closing it. Previously it just stayed as it was before, e.g. the edit mode cross-cursor stayed active even if a menu was opened.

Fixes T48192.
2016-04-19 16:17:34 +02:00
9b48f2b27c Cycles: Improvements and fixes for the resumable render
- Fix wrong current sample reported in the log
- Also includes fix for progressive refine log
- Explicitly print to the stdout that resumable render is enabled
- Print error message and abort when passing wrong values for the
  resumable render. Never waste someone's compute power for wrong
  render!

Fixes T48185: Cycles resumable num chunks breaks sample counter
2016-04-19 12:56:33 +02:00
376c8dd95e Fix T48193: Incorrect keyframe_insert docs 2016-04-19 18:25:56 +10:00
7cc9f6b6f8 Minor edits to last commit
Avoid redundant tests
2016-04-19 13:07:01 +10:00
12b0c03e49 Fix T47998: Limited dissolve fails /w holes
Holes with flat surfaces could have their edges dissolved causing degenerate faces.
Now check that collapsing a vertices isn't creating self-overlapping faces.
2016-04-19 12:18:19 +10:00
74b0591d42 Cleanup: pass event args as const 2016-04-19 12:18:19 +10:00
3068ea34e4 Cycles microdisplacement: add max subdivision setting
This is to prevent situations such as when the camera gets very close to a mesh
and causes it to be tessellated into an excessive amount of micropolygons. In
REYES this is known as the eye-splits problem.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1922
2016-04-18 22:47:24 +02:00
71588300d2 Cycles microdisplacement: fix handling of triangles in DiagSplit
Theres still more room for improvement but this makes things useable.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1921
2016-04-18 22:31:12 +02:00
c42a796e9f Fix: Make it easier to tell if Color Swatches are greyed out or not
This commit makes disabled/inactive color swatches look more obviously disabled
by halving their alpha values. It is necessary because the results of
ui_widget_color_disabled() (which is usually used when disabling widgets)
get overwritten by the color filling code here.

To avoid confusion, the checkerboard background (when the color genuinely has
alpha) will still only show in those cases. That is, when disabled, color swatches
won't show the checkerboard unless the color actually has an alpha component if it
wasn't disabled.
2016-04-19 00:42:59 +12:00
2aafadd4ac Fix T48186: Grease Pencil Smooth brush doesn't work properly - "erase" the stroke thickness
As soon as you started trying to smooth a stroke, the thickness of the stroke
would quickly drop right down to near zero, if "affect pressure" was enabled.

This step got accidentally missed when restoring the affect pressure functionality to
the stroke smoothing brush code, following cleanups from the stroke quality patch.
2016-04-19 00:18:46 +12:00
9f39619dda Cycles microdisplacement: scene level render and preview dicing rates
This makes it easier to control overall dicing rate without having to tweak
every object. The preview rate makes viewport editing more interactive. The
default preview rate of 8 is roughly 64 times faster for some operations.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1919
2016-04-17 20:38:50 +02:00
facc127e72 "View Frame" now works in the sequencer too 2016-04-17 12:27:12 +12:00
1dfbcd88d5 Fix a few compiler warnings with OS X / clang. 2016-04-17 01:05:50 +02:00
667a5ef48e Fix T48171: activating spacebar search menu over text button activates it or shows tooltip. 2016-04-17 00:40:01 +02:00
557544f2c4 Cycles: Refactor Image Texture limits.
Instead of treating Fermi GPU limits as default,
and overriding them for other devices,
we now nicely set them for each platform.

* Due to setting values for all platforms,
we don't have to offset the slot id for OpenCL anymore,
as the image manager wont add float images for OpenCL now.

* Bugfix: TEX_NUM_FLOAT_IMAGES was always 5, even for CPU,
so the code in svm_image.h clamped float textures with alpha on CPU after the 5th slot.

Reviewers: #cycles, brecht

Reviewed By: #cycles, brecht

Subscribers: brecht

Differential Revision: https://developer.blender.org/D1925
2016-04-16 20:49:59 +02:00
b973911fee Anim Editors: "View Frame" Operator - Code Cleanups/Reshuffling + NLA/Timeline Support
* Reshuffled code for existing "View Frame" implementations, and removed leftover
  comment from some of the the copy-and-paste used to build it.
* Added support for this operator in the NLA and Timeline
2016-04-17 03:44:10 +12:00
5d6b695f00 Assorted enum tweaks
* Knock out "Python" FModifier entry - It really hasn't been coded yet!
* Add icon for "Match Indices" driver eyedropper mode. It should help provide
  a bit more of a hint of what it does, but it also doesn't look quite as nice now.
2016-04-17 03:29:29 +12:00
b49fd60060 Experimental Drivers UI Tweak: Use icons for variable types
This commit aims to streamline the driver variables layout a bit
* Each variable type now has an icon. (The loc diff and rot diff ones are placeholders,
  which could deserve something better/dedicated if we continue to use this)
* Instead of taking up an entire row, the variable type dropdown now only shows
  an icon, and is located before the variable name field.

Feedback wanted: Is this more/less confusing than it was?
2016-04-17 03:29:28 +12:00
4572d4d861 Tweaks to Streamline Drivers UI - Don't use uiTemplateAnyID for properties where only objects can be used 2016-04-17 03:29:28 +12:00
64c7306cdb Cycles: Insert util_texture.h in CMakeLists to make Cycles compile again after recent refactory. 2016-04-16 11:58:38 +02:00
9c916b0172 Cleanup: Move texture definitions to util, to avoid bad level include. 2016-04-15 23:02:44 +02:00
34c99fa30a Curve draw fix w/ surface offset + only-first enabled
In this case the initial offset needs to be applied to the rest of the stroke.
2016-04-16 06:47:37 +10:00
6bc2ba2111 Fix T48157: 3D view's depth of field isn't displayed correctly with scene units scale.
focus distance is given in BU, no need to scale it at all.
2016-04-15 16:24:19 +02:00
3165e8740b Fix T48139: Checker texture strange behavior in cycles
Seems particular CUDA implementations has some precision issues,
which made integer coordinate (which was expected to always be
positive) to go negative.
2016-04-15 15:30:30 +02:00
177d051126 UI: copy to selected: add 'single'/'all' options to buttons' menu when relevant.
Same as reset or anim keyframe/driver operators... Inconsistency reported by Leon Cheung
through IRC, thanks.
2016-04-15 15:19:19 +02:00
bce4b7c868 Code Cleanup: Fix up various odds and ends 2016-04-16 01:12:50 +12:00
88c071fbb5 Code Cleanup: Remove unused define left over from earlier versions of this code 2016-04-16 01:12:50 +12:00
209cd5db96 Remove a leftover from older code 2016-04-15 15:06:08 +02:00
3130f4167d Cycles: Optimization to spatial BVH build
Simple fix: release lock earlier.

Reduces spatial split build time from 96 to 53sec on the Bunny.blend
(using studio Intel for benchmark).

NOTE: Timing difference is not that spectacular when comparing numbers
with builds before memory optimization, but even then it's about 20%
faster build.
2016-04-15 14:35:42 +02:00
10320891f0 Fix T48151: Brush texture overlay won't refresh automatically in UV editor when changed in buttons window.
Simple solution is to get rid of this stupid `rna_TextureSlot_brush_update` func, and do what it was doing directly
in BR case of `rna_TextureSlot_update`. That way, all updates to brush texture will invalidate correctly the overlay.

Note that this double definition of texture pointer for brushes looks rather fishy, am really not convinced this helps
keeping things simple and clear at all (what happened here is that texture selector in image paint editor was using
'texture' member of brush itself, which was performing correct RNA update, while context-based brush texture selector
from buttons space was using 'texture' member of the TextureSlot struct, which had default texture update callback
which was not invalidating overlay).
2016-04-15 13:19:41 +02:00
8ac662c77a New freehand curve drawing tool
- Access with Shift-LMB or from the 'Create' toolbar tab.
- Uses curve fitting for bezier curves, with error and corner angle options.
- Optional tablet pressure to curve radius mapping.
- Depth can use the cursor or optionally draw onto the surface,
  for the entire stroke or using the stroke start.
- Stroke plane can optionally be perpendicular to, or aligned to the surface normal.
- Optional radius tapering and for start/end points.
- Supports operator redo and calling from Python.
2016-04-15 20:36:38 +10:00
e56e7bd1ec Add lib for n-dimensional cubic curve fitting
This will be used for calculating bezier curves from freehand drawing,
may be used for other areas too.

Original code from GraphicsGems, 1990 (FitCurve.c),
with updates from OpenToonz, under 3 clause BSD license.
with own minor modifications for integration with Blender:
- support adding extra custom-data.
- improved handle clamping.
2016-04-15 20:33:58 +10:00
f951cc36e2 Cycles: Support heat volume attribute
Similar to velocity, it was kind of supported by the mesh manager but
was missing a code in BlenderSession to get actual values.

In Cycles Heat is an attribute which goes from -1 to 1, where -1 is
the coldest ever temperature, 1 is the hottest ever one.
2016-04-15 12:02:31 +02:00
a52b4378b2 Cycles: Improve error print a bit 2016-04-15 11:24:59 +02:00
3fcbb2bb58 Tests: Fix wrong hash after "no redundant zeroes" commit 2016-04-15 10:37:57 +02:00
69ee6c9866 Drivers Editing: Added "Copy/Paste" buttons beside "Add Variable" for copying all variables from one driver to another
This was a feature request from a few years back (IIRC from ZanQdo?) to make it
easier to reuse one set of driver variables across several different drivers.

Dev Notes:
* Finally it's done! All that trouble for two little buttons.
* Grr... cmake... grrr!
2016-04-15 20:05:09 +12:00
c97b0b14e3 NLA Copy/Paste Modifiers: Apply similar fixes as those done in Graph Editor 2016-04-15 20:05:08 +12:00
344c17f439 Fix T42148: Copying/Pasting FModifiers copies to all selected FCurves, not just active one 2016-04-15 20:05:08 +12:00
26e8798561 FModifiers: Various tweaks for consistency + improved behaviour
* Use an RNA enum callback for NLA FModifier types too
* Cleaned up tooltips for these operators in Graph and NLA editors
* Fix update notifiers after adding FModifiers in the Graph Editor
2016-04-15 20:05:07 +12:00
35a089d960 FModifiers: "Add Modifiers" in Graph/NLA Editor buttons now uses a dropdown instead of a button
This brings the UI here more in line with the Constraints and Modifiers UI's.

TODO:
* The tooltips/descriptions on the operators now need fixing, as we can no longer
  use custom tooltips when defining these buttons.
* The operators need to be fixed to only operate on the active data
2016-04-15 20:05:06 +12:00
6bddad2c4e Code Cleanup: Add proper defines (with ANIM_* prefix) for animation-related copy-paste buffer free callbacks 2016-04-15 20:05:06 +12:00
6401730697 Graph Editor: Move "View" panel to be the last
This change means that when going from having no FCurves active to having
an active FCurve, the properties panels will not get stuck with only showing
the "View" tab, which is not that useful a lot of the time.
2016-04-15 20:05:05 +12:00
b8892cac19 Cycles: Yet another fix for camera in volume
Was an embarrassing glitch in original optimization policy,
the for-loops can't be de-duplicated here.
2016-04-14 17:20:17 +02:00
78c3a5d00f Compositor: Fix image and render layer always extending edges
It was no more possible to translate two images, put one on top of
another in order to do things like mapping VR views.
2016-04-14 11:20:00 +02:00
8ed746683a Remove redundant abs ray/line point functions 2016-04-14 13:04:35 +10:00
416064cd5b Math Lib: ray_point_factor_v3 functions
Gives a bit better precision than creating a line in some cases,
use for ED_view3d_win_to_3d.
2016-04-14 12:00:16 +10:00
bbcb9c68c9 Cycles: Resolve ridiculous amount of memory used by spatial split builder
This was only visible on systems with lots of threads and root of the issue
was that we've been pre-allocating too much memory for all the threads.

Now we only pre-allocate data for the main thread and rest of the threads
does allocation on-demand.

This brings down memory usage from 36Gig to 6.9Gig when building spatial
split for the Bunny.blend file on our Intel beast.

Originally regression was happened by the threaded spacial split builder
commit.
2016-04-13 14:25:21 +02:00
9604db7650 Fix T47813: Cycles Standalone not respecting integrator sample_clamp_direct 2016-04-13 10:39:21 +02:00
c8e2cc21ab Cleanup string includes after versioning commits 2016-04-13 09:45:32 +02:00
3156055e27 Show version number in UI as well 2016-04-13 09:45:30 +02:00
bd7e4d2a3d Tweaks to the version string formation
Couple of things:

- No need to use string streams to format the version string,
  we can do it at compile time and don't bother with anything
  at runtime.

- Function declaration was wring and would have caused linking
  conflicts in cases when util_version.h was included from
  multiple places.

We should have an utility function to get Cycles version so
applications which are linked to Cycles dynamically can query
the version, but that can't be done as an inlined function in
header and would need to be a function properly exported to a
global symbol table (aka, be implemented in a .cpp file).
2016-04-13 09:45:26 +02:00
ed050753ce Add a version number to Cycles standalone
Now Cycles has its own versioning, that is mainly interesting for external projects, which integrate the engine.

We start with version 1.7.0. Reasons for that:

* The engine is too mature for a 1.0 release.
* We assume that Cycles inside of Blender 2.61 was version 0.1. We count upwards in 0.1 steps, therefore Cycles inside of Blender 2.77 would be 1.7.

We use a common versioning scheme here, with 3 decimals for the major, minor and patch level.

At the moment cycles --version can be used to display the version, easy to parse for external projects. The info will be added to the UI later aswell.
2016-04-13 09:45:23 +02:00
84c68dcb3f Cycles: Minor cleanup, whitespace around keyword and preprocessor indent 2016-04-13 08:58:52 +02:00
c1a27a76cf Cycles microdisplacement: preserve smooth normals for linear subdivison
This way we prevent cracks in the model due to discontinuous normals, by using
smooth normals for displacement instead of always getting flat normals after
linear subdivision.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1916
2016-04-13 01:37:33 +02:00
068ee2cd98 Fix T47754: Meshes glitch on cycling Viewport Shading mode with Linked Groups
This is a regression since 4310128 which is cased by really bad logic:
there might be dependencies between dupli-objects, which means _if_ we
really want to ensure derived mesh on dupli creation we have to do it
before any matrix is overwritten.

I'm not sure if such derived mesh trick is really the only way to go
without major refactor, but seems simple fix for now will do it.
2016-04-12 17:16:36 +02:00
3a977ff502 Missed last commit 2016-04-13 00:49:47 +10:00
6cc953fb74 Correct UI messages: hyphenate 'add-ons' 2016-04-13 00:30:38 +10:00
951fad2baa Cycles: Add missing velocity attribute to builtin image loader
For some reason other parts of blender importer were assuming velocity
is supported, but actual loader was not aware of that.

Fixes T48064: Adding velocity attribute crashes render
2016-04-12 13:26:21 +02:00
19539c50c9 Cycles: Avoid crash when accessing non-existing volume attribute 2016-04-12 13:26:21 +02:00
f636b8bfc0 CMake: consistency check now reports stale ignores
Also update ignore list.
2016-04-12 20:12:29 +10:00
d4979f1d66 Remove exception for file which no longer exists 2016-04-12 11:55:44 +02:00
5231b049d7 Fix T47443: Circle & UV Sphere aren't aligned
D1912 by @samb96

Change the starting point of the UV sphere so that it is aligned with the circle, cylinder, and cone primitives.
2016-04-12 19:47:29 +10:00
dc7d6643e1 Remove any wrangler utility scripts 2016-04-12 11:07:23 +02:00
4fae162bce CMake: ignore header 2016-04-12 18:50:08 +10:00
b1ef786a73 CMake: Partially revert recent missing headers commit
The header which was put to the CMake project is not by any means used
during compilation, it is only used when manually updating CUDA wrangler
from CUDA headers.
2016-04-12 08:54:34 +02:00
4a64b36029 Cleanup: use bool 2016-04-12 11:26:06 +10:00
a2db16ba58 CMake: add missing headers 2016-04-12 11:22:30 +10:00
d032c5e46c Cycles microdisplacement: UI tweak to use split column
Reviewed By: brecht, dingto

Differential Revision: https://developer.blender.org/D1917
2016-04-12 00:08:28 +02:00
665467e51e Cycles microdisplacement: refactor to move some tesselation code from SubdMesh to Mesh
Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1915
2016-04-11 23:50:15 +02:00
d456458e06 Cycles microdisplacement: change use subdivision bool to subdivision type enum
This is only the UI change, there is no underlying code change in this commit.

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D1910
2016-04-11 23:13:51 +02:00
ebfdd7da83 Cycles microdisplacement: perform subdivision dicing in raster space
NOTE: this is only the first of many patches towards completing the subdivison
and displacement system in Cycles. These patches will be reviewed and committed
one by one over the coming weeks.

Reviewed By: brecht, sergey

Differential Revision: https://developer.blender.org/D1909
2016-04-11 23:12:11 +02:00
4a507a7653 Merge remote-tracking branch 'origin/master' into decklink 2016-04-11 23:04:58 +02:00
7d033717ad Cycles: Cleanup, make some comments easier to read on split editors 2016-04-11 18:00:42 +02:00
ac00c17900 Cycles: Remove hair support from volume BVH traversal
There are couple of reasons:

- Volume shader on hair does behave really weird anyway and it's
  not something considered a bug really.

- Volume BVH traversal were only used by camera-in-volume check,
  which doesn't really make sense to take hair into account since
  it'll be rendered wrong anyway.

Such a removal makes both code easier to extend further (as in,
no need to worry about those traversal for hair bvh) and also
reduces stress on GPU compilers.
2016-04-11 17:18:14 +02:00
e4cdda548a Cycles: Remove unused SAH from BVH pack 2016-04-11 17:18:14 +02:00
6cd13a221f Cycles: Rename tri_woop to tri_storage
It's no longer a pre-computed data and just a storage of triangle
coordinates which are faster to access to.
2016-04-11 17:18:14 +02:00
e5a2790ecb Fix T48084: Solidify uses alternate quad-direction
This prevents twisted quads from self-intersecting.

This change makes the duplicate surface match the first vertex in the face,
so the diagonal indices match in the face copy.
2016-04-11 23:04:11 +10:00
90271e7ff1 Fix T48082: Unwrap overwrites face selection
Sync selection option made adding a new UV layer select all edit-mesh faces.
Now just select the UV's, ignoring sync-select option.
2016-04-11 20:27:10 +10:00
45a089c138 Fix T48103: Wrong renders on AMD OpenCL when Light Falloff node is used 2016-04-11 10:54:41 +02:00
2050ecc307 BGE: Fix T48071: Global logic manager
Previously the logic manager was used as a global variable for SCA_ILogicBrick::m_sCurrentLogicManager,
this request to always update it before run any python script and allow call function like
ConvertPythonTo[GameObject/Mesh]. The bug showed in T48071 is that as exepted the global
m_sCurrentLogicManager is not updated with the proper scene logic manager.
Instead of trying to fix it by updating the logic manager everywhere and wait next bug report to add
a similar line. The following patch propose a different way:
- Every logic brick now contain its logic manager to SCA_ILogicBrick::m_logicManager, this value is
  set and get by SCA_ILogicBrick::[Set/Get]LogicManager, It's initialized from blender conversion and
  scene merging.
- Function ConvertPythonTo[GameObject/mesh] now take as first argument the logic manager to find name
  coresponding object or mesh. Only ConvertPythonToCamera doesn't do that because it uses the
  KX_Scene::FindCamera function.

Reviewers: moguri

Differential Revision: https://developer.blender.org/D1913
2016-04-10 23:57:43 +02:00
3a80d5e1d0 Cycles: Fix rare dead-locks on TaskScheduler::exit()
When the Moon is full it was possible to have a dead-lock in task
scheduler's  exit() method.

Similar problem was fixed in Blender's task scheduler 3 years ago
in bae2a2c.
2016-04-10 21:18:54 +02:00
50f9681e15 Docs: comment on line-sphere intersection 2016-04-10 22:46:12 +10:00
019ce363b0 Cleanup a bit particle distribution code.
Also do proper intial/final checks to avoid adding particle on zero-weight extreme items,
instead of using cheap tricks like 'small offset'...
2016-04-09 22:46:27 +02:00
950acb0ced Fix T47983, Take II: Particles - Emit from Verts emits double on one vert.
Previous fix made another issue even more visible, leading to +1 particle on first vert
and none on last one. This commit should fix both original and new issues.
2016-04-09 18:59:05 +02:00
d09a372acb Fix T48078: incorrect OS X command for retrieving number of CPUs on in Makefile. 2016-04-09 00:25:18 +02:00
c1d1c1dc6b Fix T48088: Reproducible crash: Edges + Array Mod + Hair Particles.
Code did not consider the possibility to have no face at all! :P
2016-04-08 16:26:42 +02:00
a5dcda8ad3 Fix broken by D1880 line stipple deactivation 2016-04-08 12:20:43 +03:00
d969192fbe Wide lines + line stipple deprecated API replacement
The patch contains an implementation of the wide lines and the line stipple that is necessary for OpenGL upgrade.

For the implementation I have chosen the geometry shader because it required minimum changes for the wrapper calls and such implementation is the best for the "basic shader" architecture.

There are few shortcomings that can be corrected in future. They all are related to the fact that the lines in one strip are not connected with each other. So the stipple pattern is not continuous on the common vertex of two lines. There is also no continuity of form (each line is an independent rectangular).
But the advantage is that even outdated glBegin, glVertex work! Though with the above restrictions.
Continuity of form and stipple can be implemented with additional attributes, and it will require more changes in calls.

At the moment, the patch replaces calls for some "gestures". It works satisfactorily for "cross" or "rectangular" and not so good for "lasso" and "circle" due to the above-mentioned shortcomings.

Don't forget to set USE_GLSL to true for testing.

Alexander Romanov (Blend4Web Team)

Reviewers: merwin, brecht

Reviewed By: merwin, brecht

Subscribers: aligorith, Evgeny_Rodygin, AlexKowel, yurikovelenov

Differential Revision: https://developer.blender.org/D1880
2016-04-08 10:58:40 +03:00
a51e9ece53 Cycles: Fix misleading remaining time report when using infinite number of samples in viewport 2016-04-06 16:30:52 +02:00
d6ae94b988 Cycles: Fix compilation error of Hair BSDF GLSL shader 2016-04-06 15:40:55 +02:00
42824f4403 Fix missing viewport update when tree output is in a node
There was already an attempt to do it, but it worked incorrect because
of wrong recursion check.
2016-04-06 15:23:26 +02:00
e10ec6ee9a Cycles: Avoid possibly uninitialized variable 2016-04-06 10:51:04 +02:00
5ddf6ca87a Quiet warning for release build 2016-04-06 18:26:39 +10:00
9e3b0350f5 Fix leak w/ missing external mesh customdata 2016-04-06 16:14:30 +10:00
78d39cad8b Tweak fill-region method to produce fewer 'gaps' 2016-04-06 15:07:37 +10:00
16597b691a Fix camera view-border line width 2016-04-06 14:27:37 +10:00
28dad2ec12 Correct error checking for wrong frame range 2016-04-06 09:41:30 +10:00
f5fb4361d2 Cleanup: indentation 2016-04-06 09:30:20 +10:00
cc970dc08a Cleanup: arg docstrings 2016-04-06 09:28:22 +10:00
16f919ea58 Render frame arg parsing, list and range support
Support a comma separated list of frames, as well as frame ranges using the '..' separator.

eg: `blender my.blend --render-frame 1,2,10..40,100..200`
2016-04-06 09:23:15 +10:00
Reinier de Blois
c084520b03 Expose new Recast partitioning methods for navmesh generation
This patch depends on D1747, which upgrades the Recast version.  It exposes the new Recast partitioning methods in the navmesh generation.

Reviewers: campbellbarton, moguri

Reviewed By: moguri

Projects: #bf_blender

Differential Revision: https://developer.blender.org/D1748
2016-04-05 21:39:04 +02:00
Reinier de Blois
176538f613 Update Recast version to 1.5.0
The version of Recast that Blender ships with is from 2009.  This patch updates the Recast version to the latest version, 1.5.0.  The Detour version remains untouched.

Reviewers: campbellbarton, moguri

Reviewed By: moguri

Projects: #bf_blender

Differential Revision: https://developer.blender.org/D1747
2016-04-05 21:38:52 +02:00
214e384fc4 Fix UV-Editor crashes w/ over SHRT_MAX UV's 2016-04-05 22:16:09 +10:00
b8ca4819b2 Revert "Cycles: Remove the Preetham Sky model."
This reverts commit d91316dc67.
2016-04-05 12:25:54 +02:00
46aaa53998 Fix T48054: Blender 2.77 doesn't import blenders fbx, due to recent changes in anim RNA API.
Please do not break API when not absolutely needed, here it was a mere parameter order issue...
2016-04-05 11:51:54 +02:00
db28ff54d6 Fix T47705: Freestyle line glitch.
The addressed issue is a regression from Blender 2.75, after the internal
switch from double to single precision floating-point numbers in the
Freestyle code base.  Face normal calculations require the higher
precision during the computations, even though the results can be stored
as single precision numbers.
2016-04-05 16:15:09 +09:00
9c952bbe85 Cleanup: Typo fixes after BVH commits. 2016-04-05 01:20:45 +02:00
82b0a9e369 PyDriver support for all RNA property types
Support for driver variables that don't resolve to numbers, eg:
objects, bones, curves... etc.

Without this, Python expressions to access this data needed to use an absolute path from `bpy.data`,
however this is inconvenient, breaks easily (based on naming) and wouldn't set the dependencies correctly.
2016-04-05 07:38:57 +10:00
65f279b770 Cycles: Fix wrong camera in volume check when domain is only visible to camera rays 2016-04-04 19:30:38 +02:00
ac8f4ba530 Cycles: Fix regression caused by recent camera-in-volume commit
Stupid me forgot that we don't have stop-element in the stack yet.
2016-04-04 18:24:40 +02:00
a3d6552514 Cycles: Fix regular BVH not having proper visibility flags
This was caused by recent threading commit. Now because of all children
are set when they're ready need to explicitly update all parent's visibility.
2016-04-04 18:11:34 +02:00
d82d9e14e8 Fix T48045: Freestyle ID user decrement error.
This fixes reported issue, but there could be more of those hidden in Freestyle code,
it did not handle user refcount at all (and the fact it by-passes BKE in some places
for efficiency does not help here).

Note that this should be relatively harmless, since freestyle uses own Main during
render, so everything is cleaned up in the end in any case... But better try to
handle IDs correctly here too. :)
2016-04-04 15:49:30 +02:00
f76dec9238 Update hash for an OBJ unit test 2016-04-04 15:22:31 +02:00
bf55afbf26 Cycles: Make spatial split BVH multi-threaded
The title actually covers it all, This commit exploits all the work
being done in previous changes to make it possible to build spatial
splits in threads.

Works quite nicely, but has a downside of some extra memory usage.
In practice it doesn't seem to be a huge problem and that we can
always look into later if it becomes a real showstopper.

In practice it shows some nice speedup:

- BMW27 scene takes 3 now (used to be 4)
- Agent shot takes 5 sec (used to be 80)

Such non-linear speedup is most likely coming from much less amount
of heap re-allocations. A a downside, there's a bit of extra memory
used by BVH arrays. From the tests amount of extra memory is below
0.001% so far, so it's not that bad at all.

Reviewers: brecht, juicyfruit, dingto, lukasstockner97

Differential Revision: https://developer.blender.org/D1820
2016-04-04 14:43:21 +02:00
be2186ad62 Cycles: Solve possible issues with running out of stack memory allocator
Policy here is a bit more complicated, if tree becomes too deep we're
forced to create a leaf node and size of that leaf wouldn't be so well
predicted, which means it's quite tricky to use single stack array for
that.

Made it more official feature that StackAllocator will fall-back to
heap when running out of stack memory.

It's still much better than always using heap allocator.
2016-04-04 14:13:19 +02:00
5ab3a97dbb Cycles: Log overall time spent on building object's BVH
We had per-tree statistics already, but it's a bit tricky to see overall
time because trees could be building in parallel.

In fact, we can now print statistics for any TaskPool.
2016-04-04 13:43:19 +02:00
ba7c2b7b73 Cycles: Log allocation slop factor for BVH arrays
Currently they're staying at 1 (actual size over capacity), but we
will be changing it quite soon in order to avoid having too much
memory re-allocation happening at a BVH build time and will be
playing with different policies for that.
2016-04-04 12:56:56 +02:00
5d25579602 Fix missing ID_SO sound type in outliner's ID types.
Note that we may want to review that some day, we have quite a bit of ID types here that are
'blend file' view only, might be worth splitting the check based on this.
2016-04-04 12:35:59 +02:00
61a8d12ccd Cycles: Tweak to stack allocator used by BVH builder
In some files stack memory was overruning the pre-allocated stack.

Perhaps we should fall-back to a hep-allocated stack so release builds
don't crash in works case but just becoming slower.
2016-04-04 12:23:23 +02:00
8cc7460495 Smoke: Don't use min as an uniform name
This is an attempt to fix report T47991.
2016-04-04 11:58:27 +02:00
673ddd48da Cycles: Make curves modified by a taper object with modifier considered a deform modified
That might consider a bit more objects to be considered deform modified,
but it covers common case of using taper object without require of doing
recursive checks.

In worst case it'll be just some extra synchronization time, no render
time difference will happen for false-positive because of extra checks
happening in Cycles.
2016-04-04 11:39:04 +02:00
2f08d5f761 Fix T48002: Wrong behavior with "RGB to Intensity" in Image textures
There was some extra linearization happening in such cases.
2016-04-04 11:30:35 +02:00
f4875bed89 Fix curve editmode adding 3D primitives w/ 2D curves 2016-04-04 18:36:38 +10:00
0a7ed17099 Fix curve adding 3D nurbs when 2D is set
Ctrl-LMB ignored 2D constraint
2016-04-04 18:36:37 +10:00
097b895c2c Fix curve hide keeping spline active 2016-04-04 18:36:37 +10:00
c868945a43 Fix curve, missing update on Ctrl-LMB 2016-04-04 18:36:37 +10:00
3de9b2ca74 Fix curve add-vertex w/ 2D curves
Project the point onto the 2d place where possible.
2016-04-04 18:36:37 +10:00
8f1223b636 Move some debug print under G.debug
It's not like every debug build is benefiting from this print..
2016-04-04 09:58:14 +02:00
c63398e55a Fix uninitialized variable use w/ VSE transform 2016-04-04 12:44:03 +10:00
d91316dc67 Cycles: Remove the Preetham Sky model.
The improved Hosek / Wilkie model was added during my GSoC 2013 and the default since then.

The older model was kinda kept for compatibility, but after more than 2 years it's time to remove it.
The Hosek / Wilkie model is more realistic anyway, and people who really want a day / night transition can mix the Sky Shader with another one (e.g. color) and fade between the two.
2016-04-02 23:36:14 +02:00
74e40663da Fix T47971: rigid body baking crash due to thread race condition. 2016-04-02 13:04:26 +02:00
b03ff0bbf8 Fix T48030: Can't zoom VSE properties panel 2016-04-02 18:52:52 +11:00
e02d0de36e Fix T47505: Cycles OpenCL rendering crash on Windows.
Restore the boost bug workaround, but without changing the locale.
2016-04-01 20:39:07 +02:00
ce44ffd74f Cycles: Fix wrong camera-in-volume stack when camera ray hits volume domain twice 2016-04-01 18:03:58 +02:00
0f6f921898 Cycles: Temporarily revert index sort commit for spatial split
There are in fact some missing parts to it (Split BVH builder should
be creating bins from result of Object Split constructor).

Doable, but need to quickly fix issue for the studio here, easier to
revert for now.
2016-04-01 17:45:59 +02:00
8e6d6cc4dc Fix T48001: Highlighting selected item in filtered lists.
active index was not reset to 'nothing' in case actual active item was filtered out.
2016-04-01 16:55:34 +02:00
a9cd97673d Knife Project: revert fix for T43896
For now leave precision at half a pixel until we have real fix.
Resolves T48023.
2016-04-02 01:33:10 +11:00
9ca9256693 Cycles: Support deformation motion blur for curves deformed by taper 2016-04-01 15:53:40 +02:00
f318e8322f Cycles: Report thread ID from worker thread to callbacks
Main use case of this ID will be to emulate TLS which otherwise
would require having some platform-specific implementations which
is not always really optimal.

See notes about the argument in util_task.h.
2016-04-01 15:25:35 +02:00
c6b27dd4fa BMesh: improve path-select fill region w/ ngons
Rewrote to work with ngons and and more complex topology, now uses separate function.
Fixes T48009.
2016-04-01 23:36:06 +11:00
Philipp Oeser
ae49f2ed99 Fix T48013: UV Sculpt Brush Does not appear in UV window - but does show up in uv panels (t, n)
Epic fail in recent rB2c3985 :/

To be backported to 2.77a!
2016-04-01 14:22:54 +02:00
f185effa15 Buildbot: Explicitly disable tests on all platforms
They were never running anyway since there's no checkout of
tests folder. We should either make tweaks to buildbot master
to make it to send cloning commands for tests folder and keep
tests working (currently some of them are broken).
2016-04-01 10:33:44 +02:00
42a9f334c8 Update stub for recent BPY API 2016-04-01 18:56:48 +11:00
4738ae085d Cycles: Fix for missing pthread's spin on OSX 2016-04-01 09:16:46 +02:00
314aa17678 Fix When using keying sets, the toggling "all items" in the array target only goes from the index value down, instead of keying all 2016-04-01 12:52:26 +13:00
ee324aacdd Hide layers from UI in template 2016-04-01 10:23:39 +11:00
743739f9dc Cleanup: style/spelling 2016-04-01 10:02:59 +11:00
de21f07f6c Generic check for string being a Py keyword
Driver code used incomplete list of Py keywords
2016-04-01 09:49:16 +11:00
bc318fc470 Use STRPREFIX macro for testing property name 2016-04-01 09:24:50 +11:00
83b5f0268e Fix T48012: Knife Project crash 2016-04-01 06:27:35 +11:00
553ea6de8b Fix NULL check before free 2016-04-01 06:23:35 +11:00
9431fc6764 Cycles: Fix wrong initialization order of mesh flags and object transform 2016-03-31 17:54:03 +02:00
185d002586 Cycles: Fix too many objects being considered an instance 2016-03-31 17:46:22 +02:00
6cc04b408c Cycles: Fix compilation on Win32 after bitscan commit
Need to revisit utility headers a bit more carefully and perhaps
move such utilities outside of simd-related headers.
2016-03-31 16:47:57 +02:00
Julian Eisel
90c19c61d4 Fix memory leak when assigning driver
Also added NULL-checks for RNA paths, though they might be a bit paranoid.
2016-03-31 16:41:50 +02:00
Julian Eisel
60534ee56b Fix memory leak when calling new driver eyedropper
Would return OPERATOR_RUNNING_MODAL for non-modal operator.
2016-03-31 16:27:16 +02:00
de6af2f02a Remove the obsolete windows launcher 2016-03-31 14:07:57 +02:00
c0cb9d75d6 CMAKE disable building the windows launcher, fix type in delayloading of debug dll 2016-03-31 14:05:46 +02:00
791a0852e8 Cycles: Name cleanup and some comments in BVH code 2016-03-31 13:52:38 +02:00
4ec95d621a CMAKE / msvc openmp, delay loading of openmp dll so we can set environment
variable before it is loaded
2016-03-31 13:46:14 +02:00
e2059380de Cycles: Add easy to use spin lock primitive
Currently unused, but will be handy for an upcoming changes.

It'll also be nice to be able to do scoped_lock() for both
Mutex and Spin, but currently it's not really easy to do,
need some changes in typedefs and such, will happen as a
separate commit.
2016-03-31 10:22:11 +02:00
7fd71338f9 Cycles: Expose array's capacity via getter function
This way it's possible to query capacity of an array, which then
could be used for some smart re-allocation and reserve policies.
2016-03-31 10:06:21 +02:00
63d017be90 Cycles: Avoid per-split memory allocation for the new references list 2016-03-31 10:06:21 +02:00
e69a0ab5fc Cycles: Pass BVH builder by const reference to spatial splitters 2016-03-31 10:06:21 +02:00
d9b729e342 Cycles: Only sort indices when finding a best dimension to split
This reduces amount of data being moved back and forth, which should
have positive effect on the performance.
2016-03-31 10:06:21 +02:00
bbbbe68473 Cycles: Wrap spatial split storage into own structure
This has following advantages:

- Localizes all the run-time storage into a single structure,
  which could easily be extended further.

- Storage could be created per-thread, so once builder is
  threaded we wouldn't have any conflicts between threads.

- Global nature of the storage avoids memory re-allocation
  on the runtime, keeping builder as fast as possible.

Currently it's just API changes, which don't affect user at all.
2016-03-31 10:06:21 +02:00
9c420e5e48 Cycles: Use stack storage for temporary data on leaf creation
Uses new StackAllocator from util_stack_allocator. Some tweaks to the stack
storage size are possible, read notes in the code about this.

At this point we might want to rename allocator files to util_allocator_foo.c,
so the stay nicely grouped in the folder.
2016-03-31 10:06:21 +02:00
ffe59c54cb Cycles: Add STL allocator which uses stack memory
At this point we might want to rename allocator files to
util_allocator_foo.c so the stay nicely grouped in the folder.
2016-03-31 10:06:21 +02:00
65b375e798 Cycles: Move non-vectorized bitscan() to util
This way we can use bitscan() from both vectorized and non-vectorized
code, which applies to both kernel and host code.
2016-03-31 10:06:21 +02:00
0b6b094a8c Cycles: Aligned vector was not covered by guarded stat
This was making stats printed by the logging being wrong: they did not
include such memory as BVH storage.
2016-03-31 10:06:21 +02:00
bd68a25505 cmake fix full debug builds on msvc 2016-03-31 08:12:53 +02:00
ec28fe2e6b Fix T47985: VSE GL-render scene strip hangs
Regression in d5f1b9c22,
threading deadlock rendering a scene from the OpenGL preview.
2016-03-31 15:49:24 +11:00
01ce8d80d0 Usual ui messages fixes/tweaks. 2016-03-30 23:39:54 +02:00
f7fc55867a libquery foreach looper: in recursive case, do not bother with NULL id pointers! 2016-03-30 21:36:09 +02:00
cb19948053 Fix T47983: Particles - Emit from Verts emits double on one vert.
When non-random, particle distribution used a small start offset (to avoid
zero-weight faces), which is fine with "continuous" entities like faces, but not
for discrete ones like vertices - in that case it was generating some undesired
"jump" over a few verts in case step was small enough
(i.e. total number of verts/particles was big enough).
2016-03-30 21:04:54 +02:00
756ab5ee2c Use Ctrl-Shift-RMB for to enable 'Fill Region' 2016-03-31 04:30:33 +11:00
a55477d32a Shortest Path Select: option to select all paths between 2 elements
This option selects all paths between source/destination which are no longer than the path found.

Handy for selecting meshes with a grid-topology.
2016-03-31 04:25:19 +11:00
26132eaf1f Partly fix (unreported) particles not updating correctly when changing settings.
Point-cached particles (those using simulations) would not update at all outside of
first frame, due to PSYS_RECALC_RESET flag being ingnored in `system_step()`...

For some mysterious reasons, udate is still non-fully functional outside of startframe
(e.g. changing face distribution between random and jittered), but at least when choosing
'Vertices' you get particles from verts and not faces!
2016-03-30 17:10:54 +02:00
53e85a159a Particles: Fix broken grid distribution in some case from own recent rB201d3938622. 2016-03-30 16:56:32 +02:00
f8b9f4e9bb Cycles: Resumable render implementation for Cycles
This feature is also known by the name Samples Offset, which allows
artists to render animation with given amount of samples N, but then
render more samples, starting from N and ending with M (where M > N)
and merge renders together as if they rendered exactly M samples.

Surely such effect could be achieved by changing Seed variable, but
that has possible issues with correlation artifacts and requiring to
manually deal with per render layer samples and such.

While we can't support all possible renderfarm-related features in
Cycles it's nice to support really commonly used stuff.

Here's a command how to run Blender with the new feature enabled:

  blender -- --cycles-resumable-num-chunks 24 --cycles-resumable-current-chunk 2

This command will divide samples range in 24 parts and render
range #2 (chunk number is 1-based).

This feature might be changed a bit after we'll do some tests here
in the studio with it.
2016-03-30 16:02:27 +02:00
ee364b6358 Fix T47940: Custom bone shapes, select error w/ Open NVidia drivers
Latest nouveau drivers have a bug here, use occlusion queries.
2016-03-31 00:59:04 +11:00
74d3f3746c CMake cleanup target_link_libraries_decoupled 2016-03-30 15:15:17 +02:00
119ce13a41 Fix T46623: OSX bpy.app.binary_path_python incorrect
CMake's PYTHON_EXECUTABLE wasn't set.
2016-03-30 22:50:29 +11:00
722d586257 Fix T47993: noise_vector ignores random seed
Replace hard coded values with offsets derived from the random seed.
2016-03-30 20:43:43 +11:00
93f107729c Fix T48000: Eyedropper sample-merged ignored at first 2016-03-30 17:28:01 +11:00
29bb10ee96 Fix transform center2d for 2d views
While this didn't show up as a bug, the center2d was being calculated with a zero aspect,
causing TransInfo.center2d to be NAN.
2016-03-30 07:15:33 +11:00
37e1e2695c Fix T47814: VSE Scene 'Use Sequence' fails
Conflict with flags between depsgraph and sequencer caused error.
Now pass state of sequencer parents to avoid recursion.
2016-03-30 06:59:36 +11:00
e5e8d67028 Fix T47961: Wipe effects should have 2 inputs 2016-03-30 06:33:35 +11:00
c3ed6010af Fix T47967: Select next active fails in some cases
For cases when there are multiple matches,
find the closest match (with increasingly fuzzy tests) instead of failing.
2016-03-30 05:01:57 +11:00
3a24e6320f Buildbot: Attempt to work-around unsupported clang on OSX machine
Ideally this would need to be fixed by nvcc itself. but they didn't
do that for a long time.
2016-03-29 19:46:10 +02:00
de81607efc Fix error in ghash/gset_ensure_p_ex
The key is needed in the case the ghash resizes.
Caused regression T47984.
2016-03-30 03:04:47 +11:00
201d393862 Fix T47902: Particle grid not using modifier stack, Take II.
Now only fix correct handling of use_modifier_stack for grid distribution,
fixing it globally breaks all existing edited hair systems. :/
2016-03-29 17:45:56 +02:00
a959771626 Revert "Fix T47902: Particle grid not using modifier stack."
This reverts commit 2bd3acf7cd.

Commit is valid in theory - but in practice, it means nearly all edited hair systems
would need to be re-created from scratch... Not nice, so better revert and note in code
that particle distribution is ugly and does not respect 'use modifier stack' option in most cases.
2016-03-29 17:33:08 +02:00
24d931ea58 GPencil New Stroke Smoothing: Don't perform smoothing on pressure values
As noted by Antonio and Daniel, performing smoothing on the pressure values
for new strokes doesn't work that great. From an artist POV, it is apparently
"very strange that line thickness shrink suddenly after drawing it".
2016-03-30 03:21:59 +13:00
3bdd7ba34f Driver Mapping Types: Added temporary icons to break up the two types of mapping behaviours (modal vs manual) 2016-03-30 03:21:58 +13:00
d29b32ae36 RMB Menu: Add icons for delineating each cluster of options in this menu
From T33052 by Harley Acheson (harley)
2016-03-30 03:21:58 +13:00
deffd4352b Drivers Setup: Expose all mapping types for creating drivers
* This includes the "manually create" modes, which correspond to the previous behaviour
  for setting up drivers. This is necessary when the current screen layout is not
  well suited to having multiple property editors open (e.g. small screen or heavily
  subdivided screen).

* Only the modes relevant for the current property type (i.e. array vs single)
  will be shown

* The "Add Driver" entries in the RMB context menu have now been replaced by a
  submenu which will list all the available mapping types.

* NOTE: The code for the ANIM_OT_button_driver_add() operator is perhaps a bit hairy.
  However, it currently allows us to have the desired behaviour. It can always get
  cleaned up later though.
2016-03-30 03:21:57 +13:00
3237ae2855 Add license text for OCIO configuration 2016-03-29 12:54:29 +02:00
003f908f0d Fix T47987: Blender Cycles standalone does not properly read UV coordinates from XML 2016-03-29 10:02:17 +02:00
2fae1719f8 Fix T47986: OBJ Import fails w/ imagepath encoding 2016-03-29 18:30:08 +11:00
b1f918bcc5 Fix T47958: Crash in Walk or Fly Navigation in Camera mode when invoking from non-3DView region 2016-03-28 18:19:43 +02:00
Julian Eisel
37b7b3a935 T47532: Pop-ups drop fast mouse clicks
Caused by rBc24be7ec6e5.

Before rBc24be7ec6e5,  wm_handlers_do always called handlers a second time with event value KM_PRESS in case of a double click. After it, this was only the case for non-LEFTMOUSE events.
Since ui_popup_handler (almost) always returned WM_UI_HANDLER_BREAK, the second handler iteration with KM_PRESS wouldn't run. This fix just makes sure we return WM_UI_HANDLER_CONTINUE for double click events instead (causing second iteration to run).
2016-03-28 16:45:12 +02:00
28ca3ebc5f Fix T47969: Select Random always uses same seed
Increment the seed on each use,
otherwise calling again selects the same order, unless you manually adjust the seed.
2016-03-29 01:24:57 +11:00
d336bb0765 Fix T47972: Blender crash showing particle system.
Do same as with faces - if no orcodata is available, fill orco with current location...
2016-03-28 15:52:59 +02:00
240adb90a5 Fix T47973: Render stamp ignores font alpha 2016-03-29 00:26:55 +11:00
6a099b0c45 BLF: alpha support for drawing to buffer 2016-03-29 00:26:55 +11:00
e2e72a20ec Fix T47931: Missed world shader update when having object dependency 2016-03-28 10:45:29 +02:00
8a9dd6f6fb Fix T47898: Error adding mask node with "Add Mask Node" operator
This operator is intended to be used by drag-n-drop, no user invocation
is expected to happen here. Use Add->Search to quickly add nodes instead.
2016-03-28 10:09:11 +02:00
b7dfef325d Cleanup: Unused variable 2016-03-28 09:36:41 +02:00
ca935abc18 Graph Editor UI: Experimental Tweak - Use tabs for properties region, to make it easier to navigate 2016-03-28 14:46:29 +13:00
96f8bfec2d GPencil: Note that clicking outside the active area also exits draw mode 2016-03-28 14:46:28 +13:00
211b539644 Fix T47959: make tip for 'individual origins' pivot point in UV editor more accurate.
Based on D1877 from Philipp Oeser (lichtwerk), thanks.
2016-03-27 17:18:17 +02:00
c65950dbb4 GPencil: Remove the old UserPrefs-based On/Off Stroke Smoothing method
This never really worked that well, and often ended up being far too strong
to be of practical use. The new options do similar things, but with greater
control, so removing this old method now.
2016-03-28 03:39:26 +13:00
2bb956f6c9 GPencil: Smooth and Subdivision variable/setting naming
On second thought, these might be better names for these... I'm still not 100%
happy with these, but they will do for now.

(Best results currently seem to be with smooth 0.7, and subdivision steps 1 or 2)
2016-03-28 03:21:31 +13:00
fd8f51da08 GPencil: Removed the restriction of not subdividing strokes further if it exceeds GP_STROKE_BUFFER_MAX
Assuming that this subdivision + smoothing mostly only happens at the end of a stroke
anyway, enforcing this max-points limit in some cases was resulting in strokes that
weren't quite getting subdivided properly as the others.
2016-03-28 03:21:30 +13:00
e78a929d68 GPencil: Code Cleanup - Simplify and clarify the code for subdividing a stroke 2016-03-28 03:21:29 +13:00
a7538b19c6 GPencil: Restore ability for Smooth brush to affect pressure values of strokes 2016-03-28 03:21:29 +13:00
00cfbeef11 Code Cleanup - Style tweaks 2016-03-28 03:21:28 +13:00
bfbbc8ec40 Improve grease pencil stroke quality
Improve the quality of current grease pencil strokes adding a new dynamic smooth and subdivision. The level of smooth and subdivide can be adjusted using UI parameters. These options are disabled by default in order to keep the grease pencil stroke compatible with any existing add-on.

Both parameters are defined at layer level.

Reviewers: aligorith

Differential Revision: https://developer.blender.org/D1866
2016-03-28 03:21:28 +13:00
71107208dd More tooltip tweaks
The "UI_OT_eyedropper_id" operator only actually works in the 3D view,
so change the tooltip to match that
2016-03-28 03:21:27 +13:00
Julian Eisel
9adf4cba7d Fix T45075: "Error, region type 2 missing in - name:"File", id:5"
Unexpectedly found out what was going wrong here. If a file was saved with a filebrowser open, we searched for the channel region in the wrong list (see 'ListBase *regionbase = (sl == sa->spacedata.first) ? &sa->regionbase : &sl->regionbase;').

Minor annoyance is that I had to move the loookup to the 2.77.1 version patch now.
2016-03-27 13:45:10 +02:00
7bce3dd3ad Fix T47697: Smoke simulation doesn't work in viewport
Seems to be a division by zero error.

Should be safe for an upcoming 'a' release.
2016-03-27 13:21:33 +02:00
Julian Eisel
9c2704c169 Fix changing view in default video editing layout broken
Own mistake in 802bb42267
Apparently we only store one preview region for all views, didn't know that (makes sense though).
2016-03-27 13:20:30 +02:00
ce71e2e789 Fix T47962: It's possible to set a Sound strip as a modifier Mask. 2016-03-27 13:02:43 +02:00
fb9315ce2a Cleanup: Silence some compiler warnings 2016-03-27 12:36:49 +02:00
e12650bdd1 Driver Eyedropper: Auto detection/correction magic for rotation properties
When linking a rotation property to a non-rotation property (going in either
direction - i.e. rot -> normal, normal -> rot), the driver expression will
now be set so that the new drivers behave as expected (i.e. you get the values
you see, instead of "weird" values that seem several orders of magnitude off).

This may not be that great for everyone (i.e. the rare users out there who
actually like to look at their rotations in radians), but they usually know
what they're doing anyway, so this will be easy to correct.
2016-03-27 18:05:35 +13:00
4b279815d5 Drivers: Add a "none" mode for use when adding drivers
Although it isn't currently exposed, this allows for the old behaviour,
where an "empty" driver was added (without any target assigned yet).
For this reason, it's also referred to as the "Manual" mode.

There are also some attempts at improving the tooltips + names for the
other modes (again, not shown anywhere yet)
2016-03-27 18:05:35 +13:00
6caad32c12 Code Cleanup - Split out the property-button-finding code so that it can be used for other eyedroppers 2016-03-27 18:05:34 +13:00
52f3f6ffa4 Fix crash opening some .blend files after recent fix for hidden preview regions. 2016-03-27 01:55:51 +01:00
e14324daa7 Fix T47758: rigidbody bug with constraint breaking and disable collisions.
This is a regression in Bullet, reverted the problematic change for now with
a custom patch.
2016-03-27 01:32:28 +01:00
273740006e Fix T47668: Cycles OpenCL glass not rendering correctly on AMD.
Work around what appears to be a compiler bug.
2016-03-26 23:45:18 +01:00
9317f9c055 Fix T47939, take II: Check clang package version, not llvm-devel one.
Looks like some distro still provide llvm-3.4-devel, while no more clang-3.4.
Since clang depends on llvm of same version, check clang only should ensure
us we also have matvhing llvm... *sigh*
2016-03-26 21:07:04 +01:00
8fcf774167 Fix T47935: Hair particles; The display percentage parameter breaks after a render is done.
Follow same logic in `psys_render_restore` as in `psys_render_set` - if hair and
display percentage is not 100%, we have to recompute particles...

With regular 'emitter' particles just hiding some is fine (though using random here
will not give a precise proportion...).
2016-03-26 17:41:56 +01:00
112f431c3b Fix T47951: UserId problem on reload.
readfile.c would increment object usercount in three places, where it should not.
Remember kids: Objects are **only** refcounted by Scene's bases, and Object->proxy!
2016-03-26 16:22:17 +01:00
6483c3c280 Fix own regression in rBc08924bf94f2dff - foreach ID looper was broken due to missing initialization.
Quite unbelievable this could slip in... tons of shame on me :/
2016-03-26 16:11:12 +01:00
6a0c187653 Revert "Fix T47896: Scripted Expression string length limit is too short for some autogenerated expressions"
This reverts commit 322f86d6b3.
2016-03-26 23:00:20 +13:00
5759e335c3 Driver Variable Name Validation: Added missing check for zero-length (i.e. "blank") names 2016-03-26 18:02:02 +13:00
0512e20ae9 Driver Setup Workflow Improvement: Property Eyedropper
This commit brings some long requested improvements to the workflow for setting up
drivers, which should make it easier and faster to set up new drivers in a more
interactive fashion.

The new workflow is as follows:
1) Hover over the property (e.g. "Lamp Energy" or "Y Location") or properties ("Rotation")
   you wish to add drivers to. We'll refer to this as the "destination"
2) Ctrl-D to active the new "Add Drivers" eyedropper
3) Click on the property you want to use as the source/target. The property under the
   mouse will be used to drive the property you invoked Ctrl-D on.

For example, to drive the X, Y, and Z location of the Cube using the Y Location of the Lamp,
hover over any of the X/Y/Z location buttons, hit Ctrl-D, then click on the Y-Location
button of the Lamp object. Drivers will be added to the X, Y, and Z Location properties
of the Cube; each driver will have a single variable, which uses the Y-Location Transform
Channel of the Lamp.


Tips:
- Transform properties will automatically create "Transform Channel" driver variables.
  Everything else will use "Single Property" ones

- Due to the way that Blender's UI Context works, you'll need two Properties Panel instances
  open (and to have pinned one of the two to show the properties for the unselected
  object). It's slightly clunky, but necessary for implementing a workflow like this,
  as the UI cannot be manipulated while using eyedroppers to pick data.

- The eyedropper operator implemented here actually has three modes of operation.
  1) The "1-N" (one to many) mode is the default used for Ctrl-D, and "Add Driver to All"
     in the RMB Menu. This is the behaviour described above.
  2) There's also a "1-1" (one to one) mode that is used for the "Add Single Driver" in the
     RMB Menu.
  3) Finally, there's the "N-N" mode (many to many), which isn't currently exposed.
     The point of this is to allow mapping XYZ to XYZ elementwise (i.e. direct copying)
     which is useful for things like locations, rotations, scaling, and colours.


Implementation Notes:
- The bulk of the driver adding logic is in editors/animation/drivers.c, where most of
  the Driver UI operators and tools are defined

- The property eyedropper code is in interface_eyedropper.c along with all the other
  eyedroppers (even though they don't share much actual code in common). However, this
  turns out to be necessary, as we can't get access to many of the low-level buttons API's
  otherwise.

Todo:
- It may be necessary to restore a way to access the old behaviour (i.e. "manual setup")
  in case it is not practical to immediately pick a property.

- Other things to investigate here include extra hotkeys (e.g. Ctrl-Shift-D for Add Single?),
  and to expose the N-N mode.

- Other things we could try include interactively applying scaling factors, picking
  multiple targets (e.g. for location difference and rotation difference drivers),
  and/or other ways of using these property picking methods.
2016-03-26 18:02:02 +13:00
ee9898e0fa Drivers Workflow: Change hotkey for "Add Drivers" to Ctrl-D (it was previously just DKEY)
Just using DKEY for this was resulting in too many drivers being accidentally created
by users drawing using Grease Pencil. This change also works better with the following
workflow changes to the driver setup process.
2016-03-26 18:02:01 +13:00
eac770a33a Fix T47939: Install Deps OSL 1.7.1 and clang-3.5
Until we officially support llvm3.5 or more, only allow for 3.4 llvm packages,
and build own stuff otherwise...
2016-03-26 00:31:41 +01:00
2bd3acf7cd Fix T47902: Particle grid not using modifier stack.
Disclaimer: this is tentative fix, seems to be working but you never know with particles.
If issue arise, we'll just revert this commit and hide 'use modifier stack' option
for grid distribution instead.

This commit also try to make choice of which dm to use during distribution more generic
(deduplication of code), again hopping not to break anything. :P
2016-03-26 00:18:00 +01:00
Julian Eisel
802bb42267 Fix sequencer view in video editing layout containing hidden preview region
Steps to reproduce were:
* Open default video editing layout
* Drag down or click '+' icon in upper right corner of sequencer view
* A preview region appears, even though the view type is not set to sequencer-preview split mode

Another bug that has been there since ages :/ Reported by @Blendify via IRC, thanks!
2016-03-26 00:09:34 +01:00
7607d064d6 Fix Cycles debug panel, being shown in BI as well. 2016-03-25 19:59:18 +01:00
e4a265f058 Cycles: Add an option to build single kernel only which fits current CPU
This seems quite useful for the development, so you don't need to wait
all the kernels to be re-compiled when working on a new feature, which
speeds up re-iteration.

Marked as an advanced option, so if it doesn't work so well in practice
it's safe to revert anyway.
2016-03-25 16:09:05 +01:00
700722f686 Cycles: Cleanup, indent nested preprocessor directives
Quite straightforward, main trick is happening in path_source_replace_includes().

Reviewers: brecht, dingto, lukasstockner97, juicyfruit

Differential Revision: https://developer.blender.org/D1794
2016-03-25 13:55:42 +01:00
0e47e0cc9e Cycles: Use dedicated BVH for subsurface ray casting
This commit makes it so casting subsurface rays will totally ignore all
the BVH nodes and primitives which do not belong to a current object,
making it much simpler traversal code and reduces number of intersection
tests.

Reviewers: brecht, juicyfruit, dingto, lukasstockner97

Differential Revision: https://developer.blender.org/D1823
2016-03-25 13:42:13 +01:00
712a257994 Fix T47928: Crashing save corruption with dynamic paint drip effector groups.
Dynapaint's `foreachIDLink` was mnot handling effector_weights->group pointer...
2016-03-25 13:17:04 +01:00
Julian Eisel
4509559c13 Fix modal bevel OP immediately stopping when called using enter key from search menu
Steps to reproduce were:
* Go to edit mode, select geometry
* Spacebar -> search for bevel OP
* Activate *using enter key*
* Immediately stops when releasing enter key

To fix we simply make sure the initial release event is ignored. For mouse events that wasn't an issue since activating an element is done on key release in menus. An alternative fix would be to do the same for enter key, but that's more risky. Also, checking event value is highly recommended anyway.
2016-03-25 12:31:46 +01:00
7219988258 Revert "Fix T47263: numpad4/6 rotates around worl Z axis and not view Y axis."
This reverts commit fe0ca82b23.

This is a design issue, needs more thinking, for now just revert back to old behavior.
2016-03-25 12:09:59 +01:00
a0a7d823e0 CMake: Disable Cycles OSL for the light configuration
While it was indirectly disabled already, it's handy to use the config
as template and enable certain features. In case of Cycles enabling it
would also enable OSL which is not very expected.
2016-03-25 11:27:08 +01:00
7f3da8f5c9 UI: Presets for scene units
This adds simple preset menu for unit scale scene property.

D1799 by @alm
2016-03-25 05:03:25 +11:00
9dc5e1dbc2 Make IDPreview handling code use new recursive libquery looper. 2016-03-24 16:10:39 +01:00
c08924bf94 Rework library_query foreach looper - add optional recursivity.
This commit:
* Fixes bad handling of 'stop iteration' (by adding a status flag, so that we can actually
  stop in helper functions too, and jumping to a finalize label instead of raw return, to
  allow propper clean up).
* Adds optional recursion into 'ID tree' - callback can also decide to exclude current id_pp
  from recursion. Note that this implies 'readonly', modifying IDs while recursing is not
  something we want to support!
* Changes callback signature/expected behavior: return behavior is now handled through flags,
  and 'parent' ID of id_pp is also passed (since it may not always be root id anymore).

Reviewers: sergey, campbellbarton

Differential Revision: https://developer.blender.org/D1869
2016-03-24 16:10:39 +01:00
60cf62ff4b Cycles: Minor optimization of equirectangular projection
Don't calculate sine twice, store this in a variable instead.

Perhaps compilers can optimize this out, but helping them a but wouldn't hurt.
2016-03-24 15:01:39 +01:00
8249046b82 UI: search operator's by word prefix
Would match middle of words which wasn't very useful in most cases.
2016-03-24 23:30:51 +11:00
70fcecc1f7 Fix BLI_strncasestr use with a single character 2016-03-24 23:30:51 +11:00
bdae647670 Color sources for point density textures based on mesh vertices
This patch adds support for coloring point density textures based on several mesh vertex attributes.

* Vertex Color: Use a vertex color layer for coloring the point density texture
* Vertex Weight: Use a weights from a vertex group as intensity values. (for Blender Render engine the additional color band is used)
* Vertex Normals: Use object-space vertex normals as RGB values.

The vertex color source enum is stored separately from the particle color source, to avoid invalid values when switching.

Note that vertex colors are technically "corner colors" (MLoop), so each vertex can have as many colors as faces it is part of.
For the purpose of point density the mloop colors are simply averaged, which is physically plausible because corners can be viewed
as multiple points in the same location.
2016-03-24 12:07:03 +01:00
8e9a55f1e5 Fix some typos and incorrect tooltips/descriptions 2016-03-24 23:31:06 +13:00
f209529c3d Fix T47910: Knife project fails
Regression in fix for T43896, using screen-space precision here is very problematic,
using lower precision here works for both reports.
2016-03-24 18:27:39 +11:00
7e65b02fb6 Cleanup: use prefix for return args 2016-03-24 18:05:10 +11:00
2a9e3c2bdb Fix incorrect arg type 2016-03-24 17:56:30 +11:00
75849b099f Fix T47838: Walk gravity fails w/ intersecting objects
Regression in 3ad0344, fix from @mano-wii.

More comprehensive fix can be done after 2.77a.
2016-03-24 17:52:31 +11:00
17d0c10096 Driver Keyframing: Some tweaks to make inserting keyframes on Driver F-Curves easier
Now, when trying to insert a keyframe on a driven property (using IKEY, or with
autokeying enabled), the keyframes will get created on the Driver's F-Curve
(instead of creating a new FCurve that goes into the active action, but will never
do anything). Furthermore, the x-value of the new keyframe will be the current
result of the driver expression.

Why/Motivations:
This way, it becomes easier to create corrective drivers, as you can position all
the targets the driver depends on, then adjust the driver value until it does what
you need, and then you keyframe that value to bake it into the Driver F-Curve
(in effect, "training" the computer how to behave in that case).

Usage Notes:
* In practice, that particular workflow is still quite clunky to achieve, due to some
  quirks of how the driver system and the UI widgets interact. Specifically, you'll
  need to disable/mute the driver before trying to edit the setting (to prevent the
  driver from immediately resetting the value - before even autokey fires!). However,
  if you're using the Graph Editor to preview/monitor/manage the keying process, you'll
  then want to re-enable the driver before changing the targets, so that you can see
  how much of a change you'll want to be applying!

* The warning about editing driver values may need to be disabled or selectively
  knocked out. I had it disabled while testing this functionality, but it's actually
  harmless in its current state (if just a bit annoying).
2016-03-24 19:34:52 +13:00
0a3792a65b Fix T47900: VSE adjustment crashes on blank frame
Regression, should have been included in previous fix.
2016-03-24 17:13:25 +11:00
d2244b59d8 Fix dodgy indentation 2016-03-24 15:20:56 +13:00
c4956faf99 Drivers UI: Added name validation/linting for Driver Variables
When attempting to change a driver variable name to an "invalid" name,
an indicator will now be shown beside the offending variable name.
Clicking on this icon will show a popup which provides more information
about why the variable name cannot be used.

Reasons that it knows about are:
1) Starts with number
2) Has a dot
3) Has a space
4) Starts with or contains a special character
5) Starts with an underscore (Python does allow this, but it's bad practice,
   and makes checking security of drivers harder)
6) Is a reserved Python keyword
2016-03-24 15:15:04 +13:00
322f86d6b3 Fix T47896: Scripted Expression string length limit is too short for some autogenerated expressions
While most scripted expressions are quite short (e.g. "var" or "frame + 1"),
those that are autogenerated by scripts (to take into account a wide range of factors)
may require a bit more headroom to operate in.

By doubling the maximum length here, we now make it possible to combine up to 38
3-letter variables in some linear combination (with all factors expressed to 4 dp).
That should be more than enough for anyone or anything for quite a while!

Unfortunately, this does increase memory consumption for drivers across the board.
2016-03-24 13:02:22 +13:00
c1095c7a9f Revert "Fix T47869: OpenColorIO Error with unicode path to config file under Windows"
White the config itself could be loaded this way, lookup tables can not. Additionally,
that's not really clear how to solve the issue with search path which is multi-byte
only in the API.

Reverting for further investigation.

This reverts commit ab4307aa08.
2016-03-23 19:28:16 +01:00
376eb77fd7 Fix T47900: VSE adjustment crashes on blank frame 2016-03-24 05:23:37 +11:00
2103e2112c Fix T47870: Missing viewport update when material output is inside of the group 2016-03-23 15:42:38 +01:00
c87e65542c Fix T47833: View-aligned GPencil strokes move in crazyspace when grabbed
These fixes "seem" to do the right thing now...
2016-03-24 03:32:28 +13:00
ab4307aa08 Fix T47869: OpenColorIO Error with unicode path to config file under Windows 2016-03-23 15:09:36 +01:00
6a4967ca6e AnimEditors: Fuzzy/Multi-Word Name Filtering
Thanks to D1080 by @rockets, I've now been able to easily implement the
ability to type multiple word snippets/partial words into the text filter
field (in the Animation Editors), and have it filter the channels which
contain just some of those parts (instead of having to match everything).

For example, the following search strings will now work:
* "loc rot" or "lo ro" will now filter all location and rotation FCurves
* "col loc" will filter all location and color FCurves
* "scale" will also work as before to filter all scale FCurves

But, the following will not work:
* "lc rt" will NOT filter all location and rotation, as the fuzzy search only
  breaks down the search string based on whitespace placement

By default, this is not enabled when using name filtering (i.e. magnifying glass is checked,
and some filtering text is specified). Instead, you need to enable the "AZ" toggle beside
the name field. This fuzzy matching is not enabled by default as it could end up being
quite a bit slower on really heavy scenes. (There are probably some optimisation
opportunities, but that's only a future option if someone really needs it)
2016-03-24 02:45:14 +13:00
21f31e6054 Fix T47856: Cycles problem when running from multi-byte path
This is a mix of regression and old unsupported configuration.

Regression was caused by some checks added on Blender side which was
checking whether python function returned error or not. This made it
impossible to enable Cycles when running from a file path which can't
be encoded with MBCS codepage.

Non-regression issue was that it wasn't possible to use pre-compiled
CUDA kernels when running from a path with non-ascii multi-byte
characters.

This commit fixes regression and CUDA parts, but OSL still can't be
used from a non-ascii location because it uses non-widechar API to
work with file paths by the looks of it. Not sure we can solve this
just from our side by using some codepage trick (UTF-16?) since even
oslc fails to compile shader when there are non-ascii characters in
the path.
2016-03-23 13:58:31 +01:00
6e31f4f090 Fix T47893: BGE crashes w/ generated mesh data 2016-03-23 23:40:30 +11:00
74399e0a18 Radial Operator: Tweak number of digits displayed for the different property types
* As requested by venomgfx, rotations now only display to 2 decimal places (more than
  enough for rotations in degrees)
* Also, made it so that the "factor" types now show 3 dp (previously only 2, which isn't
  really enough when dealing with values from 0.0 - 1.0)
2016-03-24 01:00:13 +13:00
9815262444 Radial Control Operator: Always show the property name + value on the header
The radial control operator is commonly used for setting sculpt brush Size and Strength
settings. However, when using it, it can often be difficult to remember which hotkey
is responsible for which setting, meaning that you can often accidentally modify the
wrong setting without knowing it (or even what new value you've set it to).

This commit makes it so that the property name and the current value are always shown
on the header. Previously this info was only shown when the doing numeric input.
(It also fixes a bug where the numeric input print would hang around even after it
wasn't being used).
2016-03-24 01:00:12 +13:00
0f501a73ab Fix T47890: Vertex mask w/ subsurf select fails
Regression in GL refactor
2016-03-23 21:02:44 +11:00
80a7efdc1d UI: multi word filtering in search menu
D1080 by @rockets, with own improvements to tests
2016-03-23 18:51:29 +11:00
b0a7e77700 Cleanup: style 2016-03-23 04:47:16 +11:00
c31c53983e Cleanup: style (80-width) 2016-03-23 04:25:08 +11:00
46dd04faed Fix incorrect strncat use 2016-03-23 03:54:04 +11:00
0f1d711681 Fix T47830: Multi-edit w/ ui-list wont highlight
Regression from 4d6b892.
2016-03-23 03:37:23 +11:00
84d8b35d6c Weight Paint: support accumulate for blur brush
This re-applies smoothing based on the previous update.

Can smooth more but harder to get such even distribution.
2016-03-23 01:25:56 +11:00
e2181c2ef2 Fix for crash of point density textures due to undefined point_data on loading. 2016-03-22 15:07:56 +01:00
220a7a4fb1 Weight Paint: blur now smooths connected weights
Previously it would average all points under the brush, giving an off feedback loop that often depended on the
direction of the brush stroke, giving not-very-useful smearing effect.

Now blend brush smooths between connected edges.
2016-03-22 22:37:30 +11:00
29acdb4889 Mesh API: add BKE_mesh_vert_edge_vert_map_create
Handy when you need to reference connected verts directly.
2016-03-22 22:07:45 +11:00
3b5dec4afc Fix T47882: startup camera not upright 2016-03-22 17:22:41 +11:00
121e273bb3 Cleanup: reduce scope for versioning vars 2016-03-22 17:20:17 +11:00
0f63ce61c5 Fix add mesh template 2016-03-22 14:26:48 +11:00
4acd218c02 GPU compositing:
Minor optimization: Store the uniform interface of shaders instead of
re-querying every frame.
2016-03-21 22:43:03 +01:00
Philipp Oeser
2c3985d9e6 Fix T47842: UV sculpt brush widgets are available when not in uv sculpt mode.
rB5b3af3dd made the poll function here slightly too laxist.

To be backported to 2.77 should we make an 'a' release.

Reviewed By: mont29

Differential Revision: https://developer.blender.org/D1861
2016-03-21 15:45:16 +01:00
da2dfaad1a Mirror influence of environment texture in Blender viewport
This patch implements Mirror influence for environment textures. Approach matches the one from BI.
{F281871}
See the video https://youtu.be/BskgCv6dcIE
Example: {F281876}
Alexander (Blend4Web Team)

Reviewers: campbellbarton, merwin, brecht

Reviewed By: brecht

Subscribers: TwisterGE, blueprintrandom, youle, Evgeny_Rodygin, AlexKowel, yurikovelenov

Differential Revision: https://developer.blender.org/D1786
2016-03-21 14:36:33 +03:00
112300a982 Fix T47862: VSE hard cut fails
Regression caused by changing how video length is calculated,
however similar problems could be caused by strip length changing on-disk.
2016-03-21 19:40:41 +11:00
f4840e878b Fix T47848: Fix regression in sequencer GL render
Own changes in 2.77 broke off-screen render with scene render size doesn't match output.
2016-03-21 16:36:20 +11:00
fb5c6333f9 GPU: avoid redundant logic for non-spot lamps 2016-03-21 16:06:04 +11:00
72bf5d13e6 Fix for non spot lamps calculating spot values
Logical error in D1378, also incorrectly used lamp type as a flag.
2016-03-21 16:02:37 +11:00
a0a66e0418 Correct strange icon scaling in preferences 2016-03-21 15:34:34 +11:00
8238f5b33b Fix T47868: Check Box shape doesn't scale 2016-03-21 15:16:43 +11:00
2683dd8b93 Docs: add missing bmesh.ops descriptions 2016-03-20 19:40:03 +11:00
7f03e7cc3c Fix T47837: Filtering UIList broken with recent master.
Using 32nd bit of integer with our int RNA prop is not a good idea, it does not
really support unsigned int even with PROP_UNSIGNED type...

Most likely this has been unveiled by recent work over property clamping in RNA.

Not critical, but should be backported should we make an 'a' release.
2016-03-19 17:06:32 +01:00
26f2fe9528 mathutils.bvhtree: Add find_nearest_range API call
Returns all elements within a radius.
Similar to kdtree.find_range
2016-03-19 18:31:56 +11:00
1a7596951a BLI_kdopbvh: Pass center to to range callback
Useful when BLI_bvhtree_range_query callback calculates a new position to measure from.
2016-03-19 18:31:56 +11:00
6aeb1f7f56 Fix: "pchan_name" field in SDNA for names of bone targets for drivers was too short
When all the names in Blender were updated to go from having 32 characters to 64,
the "pchan_name" field in the DriverTarget struct was missed. This meant that if you
had a bone with a suitably long name, it would have been impossible to use values from this
bone in a driver.

The only reason this probably hasn't been discovered yet is because the standard/old depsgraph
doesn't work that well for bones in the same armatures, so setups where this may have
occurred are not that common.

To prevent this problem from happening in future, I've added the standard "MAX_ID_NAME-2"
comment to the comments on each line likely to be impacted by such changes, making it
easier for whoever does a search and replace in future :)
2016-03-19 17:48:29 +13:00
3d59be3001 Sequencer: expose GL preview alpha in scene UI
While this isn't essential, accessing this setting required navigating to each scene and using render menu.
Expose in sequencer UI for more convenient access.
2016-03-18 20:05:08 +11:00
cc12fc1f11 Fix T47806: Blender animation player stop working correctly with XVID codec
Something weird, seems some buffers _might_ be shared between codec context
and frame, which is quite weird. Could be a bug in FFmpeg or could be wrong
API usage somewhere else..
2016-03-18 11:50:06 +05:00
9777c5b0ca Fix T47827: Single Channel Preview Error
Fix by @sergey with own fix for big endian.
2016-03-17 23:52:49 +11:00
49182111fb ImBuf: Some tweaks to FFmpeg frame free policy
Th intention is to make sure we don't free buffers which were not allocated
by FFmpeg.

This is a possible fix for T47806.
2016-03-17 14:45:10 +05:00
eb32aa827a Sequencer: add frame-jump to menu 2016-03-17 11:02:14 +11:00
6952d75e3b Fix missing 'anim_data' in RNA API of Freestyle's linestyle.
Reported by Manuel Rais on ML, thanks.
2016-03-16 20:21:02 +01:00
3274dbceb1 Sequencer: Alt-RMB select handle now always selects strip
Was possible to do Alt-RMB on a strips handle - which only make the strip active (but didn't select).
This isn't really useful, so just select the strip and its handles in this case.
2016-03-17 00:26:50 +11:00
23e608b6fb Fix T47818: GPencil Sculpt Brush settings update when adjusted using scrollwheel while sculpting 2016-03-17 01:12:30 +13:00
Julian Eisel
386872b98b Fix text on collapsed node not positioned correctly with high DPI
Reported by @JacquesLucke via IRC, thx!
2016-03-16 12:53:57 +01:00
bd5bfad723 Fix T47807: Toggle header shortcut doesn't work 2016-03-16 11:33:32 +11:00
2f4ea47566 CMake: only show py module install options when used 2016-03-15 23:52:34 +11:00
31731bc834 Fix T47734: Rest Position is not working with new Deps 2016-03-15 16:13:25 +05:00
b7deea029a Fix T47780: Icons don't update in floating panels 2016-03-15 21:13:41 +11:00
12bb5bdabf Merge remote-tracking branch 'origin/master' into decklink
Conflicts:
	source/gameengine/Ketsji/KX_KetsjiEngine.cpp
2016-02-20 23:22:29 +01:00
e1963ddc30 BGE: undo view matrix scaling but keep axis inverting.
Previous commit 9d18fd11 introduced the possibility to scale the modelview
matrix by setting a scale on the camera but this caused undesirable lighting
and dynamic side effects.
This commit reverts the scaling effect but keeps the axis inversion effect,
which was the purpose of the first commit anyway.
A negative/positive scale on the camera is applied respectively as -1/+1 scale
on the modelview matrix.
2016-02-20 21:17:50 +01:00
7fe43f020c Decklink: patch cleanup before merge. 2016-02-20 21:15:33 +01:00
3c85accf84 Decklink: OSX is not supported, add an error message just in case. 2016-02-16 21:34:18 +01:00
8f97a72a41 Decklink: revert unncessary change to cmake macros. 2016-02-16 21:09:48 +01:00
3d01d6b620 Decklink: fix documentation to reflect the new texture transfer method in the Decklink module. 2016-02-16 21:07:51 +01:00
79e274f1f2 VideoDecklink: fix compilation warning in Windows. 2016-01-10 23:59:09 +01:00
40edd86c77 VideoDecklink: accept mode index, test dvp.dll presence, enable audio just in case.
mode index instead of mode name can be used when opening the card:
VideoDecklink("1/2vuy",0)
The list of video mode is specific to each board and this method is
therefore not generic. Only use it for debugging purposes.

VideoDecklink will not throw if dvp.dll is not found when opening a Decklink
card on Windows with a nVideo Quadro GPU; instead it will fallback on
standard OpenGL transfer. It is preferable to use dvp.dll when possible as it
provides faster image transfer to Quadro GPU.

Audio Input is now enable by default with 48KHz sampling, 16bit samples and
2 channels. This is normally not necessary because audio is not used in
VideoTexture; it is just in case it is necessary on certain Decklink card.
2016-01-10 23:44:39 +01:00
9a750eadcf Merge remote-tracking branch 'origin/master' into decklink
Just to be sure before using experimental-build
2016-01-09 10:44:33 +01:00
18affe39a5 Merge remote-tracking branch 'origin/master' into decklink 2016-01-09 09:47:33 +01:00
18829ee54a Decklink: fix framerate calculation.
For some reason the framerate attribute of the VideoDeclink object was
was wrong by 1.
framerate now returns the correct value.
2015-12-20 12:11:37 +01:00
0ff79c87a4 Decklink: use floating point texture format when possible.
Previous implementation was using GL_RED_INTEGER texture format for
all non-RGBA pixel format. This isn't supported by intel GPU (although
the GL_texture_rg extension is declared supported).
Floating RGBA texture are now used for the following pixel formats:
8BitYUV: Cb->B, Y0->G, Cr->R, Y1->A
10BitYUV: no fixed mapping between CbCrY and RGB, a shader is required
8BitARGB: direct mapping
8BitBGRA: direct mapping
10BitRGBXLE: direct mapping (A is undefined)
Other pixel formats are mapped to GL_RED_INTEGER (GL_R32UI internal
format, usampler2D must be used in the shader).
Note: the 10BitYUV, 10BitRGBXLE and 8BitARGB mapping only works on little-
endian host CPU. For big endian CPU, other formats must be used (not yet
implemented).

The texture MIN/MAX_FILTER is now set to NEAREST. Previously it was set to
LINEAR, which was detremental on multibytes pixel format.

The sample shader in the documentation for the above formats will be
changed to reflect the new mapping.
2015-12-20 11:32:27 +01:00
054d871ac1 BGE: Add GL synchronization on ImageRender.refresh() without buffer.
Calling ImageRender.refresh() without passing a buffer object will
now perform the render (if not already started earlier with
ImageRender.render()) and wait for the render to complete.
This is done internally with a GLSync object to synchronize with the GPU.
This is only useful when doing offscreen render on texture target:
when refresh() returns, you are guaranteed that the texture is ready for use.

fbo = bge.render.offScreenCreate(width,height,samples,bge.render.RAS_OFS_RENDER_TEXTURE)
tex = fbo.color
ir = bge.texture.ImageRender(scene,camera,fbo)
ir.refresh()
--> tex is now ready for use
2015-12-06 12:33:08 +01:00
803e658d63 BGE: Display shadow when default render is off.
There was a bug with logic.setRender(False): the shadow buffers
were not computed, which was visible in the bge.texture.ImageRender()
custom renders.
This is now fixed: the shadow buffers will be computed at most once per
frame by the first ImageRender() or by the default render.
2015-12-05 14:26:12 +01:00
f5161c3137 BGE: Fix offscreen render on texture.
Previously using RAS_OFS_RENDER_TEXTURE was not producing usable
textures (although the render was ok); this was due to missing
mipmap levels in the texture.
This is now fixed: the mipmap levels are explicitly created at the end of
the render as it appears that FBO do not generate them automatically.
2015-11-29 23:44:14 +01:00
9a31389aed BGE: Set render flag true on game start.
Fixes this bug:
1. add `logic.setRender(False)`
2. run game, exit game
3. remove the `logic.setRender` line
4. run game ... the render is still off

Now the render flag will be on by default on game start.

Note: during the game, the render flag stays unchanged across
      game restart/load. It's only on initial game start that it is
      initialized on.
2015-11-24 22:48:45 +01:00
74757522ba BGE: bge.render.offScreenCreate() target argument to select Texture or RenderBuffer as render target.
fbo = bge.render.offScreenCreate(w,h,samples,target)
target = bge.render.RAS_OFS_RENDER_BUFFER: send render to RenderBuffers (compatible with MSAA on Intel GPU)
target = bge.render.RAS_OFS_RENDER_TEXTURE: send render to Texture (not compatible with MSAA on Intel GPU)

The default (RAS_OFS_RENDER_BUFFER) is preferable in all cases expect
if you need to access directly the texture for some applications.

The texture bind code is accessible with the new attribute color (fbo.color).
The attribute value is 0 if target is RAS_OFS_RENDER_BUFFER.
2015-11-21 18:26:17 +01:00
2f1f59cde1 DeckLink: clean GPL statement in new files. 2015-11-21 18:26:17 +01:00
d7f0c33b3d Merge remote-tracking branch 'origin' into decklink
Conflicts:
	source/gameengine/Ketsji/BL_Shader.cpp
	source/gameengine/Ketsji/BL_Shader.h
2015-11-13 18:32:08 +01:00
e5c461285f BGE: Add documentation for bge.types.BL_Shader.setUniformEyef() 2015-11-13 00:46:05 +01:00
a90ee7828e BGE: Add documentation for decklink support in VideoTexture. 2015-11-11 18:40:03 +01:00
47b0327de1 BGE: RASOffScreen object reimplemented with Renderbuffers.
RASOffScreen was previously using GPUOffScreen object from the gpu library,
which in turn uses textures as render destinations, also when multisample is
requested. This is a problem for Intel integrated as they generally don't
support multisample textures.

ImageRender doesn't need textures as render destination: Renderbuffers are
sufficient because it only read pixels from the render with glReadPixels and
glCopyTexSubImage, both of which work with Renderbuffers.

Therefore, RASOffScreen is reimplemented with Renderbuffers and multisample
offscreen renders are now supported on Intel GMA. The gpu library is no
longer used. There is no API change.
2015-11-05 18:32:37 +01:00
a2bebb0880 BGE: asynchronous render with ImageRender new render() method
usage:
ir = bge.texture.ImageRender(..)
ir.render()
ir.refresh(buffer)
2015-11-03 17:37:50 +01:00
ef40f9164c Fix warnings when compiling WITH_DECKLINK=OFF and WITH_X11_ALPHA=OFF 2015-11-02 14:28:14 +01:00
309b4ad840 BGE: multisample FBO supported in bge.render.offscreenCreate()
3rd optional argument to offScreenCreate() to specify the number of
multi-sample. If the GPU does not support MSAA on FBO, this is ignored.
No other change in the API.
2015-11-02 13:15:50 +01:00
5b8f560e46 BGE: fix call to GPU_offscreen_create after merge. 2015-10-20 22:36:22 +02:00
aefd3e5551 Merge remote-tracking branch 'origin/master' into decklink 2015-10-20 22:03:07 +02:00
7455298f8c BGE: Image source refresh() accepts pixel format argument.
All image source objects now accept a pixel format argument in addition to
the buffer argument in the refresh() method. This can be used to change the
format of the image copied in the buffer. The only allowed values are "RGBA"
and "BGRA". This is useful when transferring images to external application
that do not support the RGBA format.
Ex:
   im = bge.texture.ImageRender(...)
   im.refresh(buffer, "BGRA")

Note: the transfer is optimal (i.e. no intermediate copy) for ImageRender and
ImageViewport objects when no processing of the image is needed in VideoTexture.
This is the case if no filter is set and the attributes are set as follow:
flip=False, alpha=True, scale=False, depth=False, zbuff=False.
2015-10-20 00:23:23 +02:00
1be95bb0f4 BGE: fix a bug in ImageRender.refresh(buffer): the scene was rendered twice.
This bug had no visible effect other than consuming CPU time because of the
double render.
2015-10-12 23:44:17 +02:00
9d18fd1188 BGE: support camera scale, can be negative.
Camera scale was previously ignored in the BGE.
It is now injected in the modelview matrix as a scale of the scene
coordinates in the camera local reference. This is equivalent to a zoom:
A scale of 2 multiplies the coordinates by 2 => only the points with
coordinates less then 0.5 before the scale will fall in the frustrum =>
equivalent to a zoom.

Anisotropic scale is supported (different scale in x, y, z)
Negative scale is also supported. As an odd number of negative scale flips the
normals of the objects, the OGL front face setting is also flipped to compensate.

A Y negative scale of -1 produces a vertical flip at OGL level.
2015-10-12 23:18:18 +02:00
c36f08d573 Remove auto-generated doc file. 2015-10-09 10:11:56 +02:00
656733ab2a Merge remote-tracking branch 'origin/master' into decklink 2015-10-08 22:32:09 +02:00
c6248cce73 BGE: new bge.logic.setRender() to enable/disable render.
The render pass is enabled by default but it can be disabled with
bge.logic.setRender(False).
Once disabled, the render pass is skipped and a new logic frame starts
immediately. Note that VSync no longer limits the fps when render is off
but the 'Use Frame Rate' option in the Render Properties still limits it.
2015-10-08 22:26:23 +02:00
622cbd9d7f BGE: API documentation for FBO creation and use in VideoTexture. 2015-10-06 17:49:27 +02:00
c56384944d BGE: new rasterizer method to create FBO for custom render in VideoTexture.
New raterizer method:

fbo = bge.render.offScreenCreate(width,height)
  width, height: size of the FBO, need not be power of two
  Returns a PyRASOffScreen object that encapsulates the FBO.
  It has just 2 attributes: width and height to return the size of the FBO.
  Currently, this object can only be used in the ImageRender constructor.

New optional argument on ImageRender constructor:

ir = bge.texture.ImageRender(scene, camera, fbo)
  If present, fbo is an object of type PyRASOffScreen.
  The returned ImageRender object holds a reference to it, which ensures
  that the FBO livespan is at least as long as the ImageRender object.
  One PyRASOffScreen object can be shared by multiple ImageRender objects.
  The FBO is automatically destroyed when all refences to the PyRASOffScreen
  object are released.
  Note: the whole and capSize attributes of the ImageRender object have no
        effect when an FBO is used: the render and the capture is automatically
        done on the full size of the FBO.
2015-10-06 14:46:00 +02:00
Dalai Felinto
c750ef6cf4 BGL: GL 3.0 methods (Framebuffer related) 2015-09-29 11:45:29 +02:00
2658c67165 Merge remote-tracking branch 'origin/master' into decklink
ce/blender/python/generic/bgl.c

Conflicts:
	build_files/cmake/macros.cmake
	intern/atomic/atomic_ops.h
	intern/ghost/GHOST_ISystem.h
	intern/ghost/GHOST_Types.h
	intern/ghost/intern/GHOST_ContextGLX.cpp
	intern/ghost/intern/GHOST_ContextWGL.cpp
	intern/ghost/intern/GHOST_ContextWGL.h
	intern/ghost/intern/GHOST_SystemX11.cpp
	intern/ghost/intern/GHOST_WindowX11.cpp
	intern/ghost/intern/GHOST_WindowX11.h
	source/blenderplayer/CMakeLists.txt
2015-09-29 11:42:12 +02:00
26b730b180 Remove duplicate call to glColorMask() in ImageRender::Render(). 2015-08-30 23:06:34 +02:00
02c618fb94 VideoTexture: Add an optional parameter to the refresh method of image sources.
If provided, the parameter must be an object that supports the buffer protocol
(bytearray, memoryview, etc) otherwise a runtime error is generated. If the
buffer is sufficiently large, the image is copied in the buffer before being
refreshed (i.e. invalidated). If the image was not already available, it will
be updated first. In the later case, it is possible that the image is loaded
directly in the user's buffer wihtout an intermediate copy in the internal
image buffer. This is currently the case for ImageViewport and ImageRender
sources when the OGL format matches the buffer format (alpha, no filter,
no flip, no scaling). Note that the image format in the buffer is always RGBA.
If no parameter is provided, the method works as before: the image is
invalidated without any attempt to updated it first.

The function returns False if a buffer was provided but could not be updated
for any reason (source not ready, buffer too small). It returns True in all
other situations.

The purpose of this function is to efficiently retrieve the OGL frame buffer
directly into a user buffer by skiping an extra copy to the internal image
buffer if it's not needed.
2015-08-30 22:37:13 +02:00
6c7358a7e9 BGE: ImageRender for other types of stereo.
Stereo mode disturbs ImageRender by changing some OGL state.
It was already fixed for Quadbuffer mode, but not yet for anaglyph and
interlaced mode. This fix simply clears the color mask and stipple mode
that are specific to these stereo mode. In any case, the correct state
is restored prior the render of each eye.
2015-07-13 21:51:39 +02:00
521edaaf75 Merge remote-tracking branch 'origin/master' into decklink 2015-06-23 22:58:09 +02:00
b3df9f4407 WGL: fix minor error in previous patch. 2015-06-20 14:07:57 +02:00
cccb8f0b14 WGL: give precedence to AA over Swap copy.
Certain GPU (intel) will not allow MSAA together with swap copy.
Previously, swap copy had priority over MSAA: fewer AA samples would be
chosen if it was the condition to get swap copy. This patch reverse the
logic: swap copy will be abandonned if another swap method (undefined or
exchange) will provide the number of AA samples requested. If no AA
samples is requested, swap copy still has the priority of course.
2015-06-20 13:02:48 +02:00
e936abdb3f BGE VideoDeckLink: Implement memory locking in Linux.
Use mlock() to lock memory in case of pinned memory extension.
Use get/setrlimit to set limit so thqt locking will work.
However, only privilege process can increase the limit, so ignore error.
2015-05-01 20:31:02 +02:00
cb21edde3e BGE VideoLinck: add AMD pinned memory, fix OGL capture method.
AMD_pinned_memory method implemented according to BMD sample file but
not tested (would need an ATI card).
Fix OGL method: needed to allocate texture data first.
2015-05-01 18:36:25 +02:00
91db6eca47 BGE VideoDeckLink: forgot one cleanup in last commit. 2015-04-22 16:39:40 +02:00
2a41ec616f BGE VideoDeckLink: Minor cleanup in Windows implementation. 2015-04-22 16:36:44 +02:00
c1bfbcbbb5 Atomic ops: return value of *add* and *sub* consistent across OSes.
The Windows and asm variant were returning the value, of the variable
before the add or sub operation. All the other variants were returning
the value after the operation. Now all variants return the new value.
2015-04-16 23:56:23 +02:00
0b7337ed19 BGE DeckLink: support capture in Linux - part I.
Capture works: I can see the frame coming in but passing them to the GPU
doesn't work yet. I'm using standard OGL function though.. TBC.
them to the GPU.
2015-04-16 23:53:04 +02:00
c507e157c4 BGE Decklink: upgrade to Desktop Video 10.4 2015-04-16 17:28:42 +02:00
b64d76d8a2 BGE DeckLink: Upgrade to Decklink version 10.4. 2015-04-13 23:45:39 +02:00
fbc379b5cf BGE DeckLink: fix extend mode.
The algorithm copied from VideoTexture's fast scaling was working only for
shrinking but we also need expanding here. Fixed that.
2015-04-11 20:24:31 +02:00
edd8c874d8 BGE DeckLink: small linux compilation fix. 2015-04-10 23:00:36 +02:00
94e1a67383 BGE VideoTexture: 3D support+performance boost on DeckLink.
ImageViewport will now skip the unnecessary RGBA32 filtering if the capture
is already in the RGBA format. This will be the case if alpha=True and no
filter is set. This saves a great deal of CPU.
Add swap attribute to DeckLink to skip pixel format conversion between
VideoTexture internal (RGBA) and DeckLink (BGRA). This is to test the
benefit of passing the image directly to the board without intermediate
copy => great boost of performance.
However, it will be necessary to change the VideoTexture internal pixel
format from RGBA to BGRA.

3D stream is now fully supported on DeckLink, the right eye image is
passed via a new 'right' attribute (name not definitive). To generate this
image one can simply put a second camera to figure the right eye and
capture its view with ImageRende.
2015-04-10 21:07:51 +02:00
bd9904615b Player: new -a option to enable alpha on frame buffer.
A new option '-a' can be passed to the blenderplayer. It forces the
framebuffer to have an alpha channel. As the background color is applied
with 0 alpha, ImageViewport will return an image with transparent
background (provided alpha is set to True on the ImageViewport object).
This is useful in combination with DeckLink to generate a key frame
with transparent background.
Without the -a option, the frame buffer has no alpha channel and
ImageViewport always returns an opaque image, no matter what.
This should be working in Windows and Linux, but only Windows is tested at
present.
Note that although the frame buffer has alpha, the player window is still
rendered opaque. Transparency of the window is possible using the
'compositing' functions of Windows and the code is already there for that
(look for WIN32_COMPOSITING) but is not enabled because 1) it doesn't work
so well 2) it requires a DLL that is only available on Vista and up.
2015-04-09 09:41:52 +02:00
80f1ab3b62 BGE: VideoTexture.DeckLink: add level attribute.
Allows to control the keying level once keying is enabled.
2015-04-08 20:59:29 +02:00
50a139cf49 BGE: Support VideoDeckLink in Linux, compiling but not yet working. 2015-04-08 20:51:25 +02:00
3dabaa5982 nVidia's DVP library is now linked at runtime.
The DVP library allows direct memory transfer with the GPU to send or
receive textures. It's used in bge.Texture.VideoDeckLink to sent a
captured video stream efficiently to the GPU, only for Windows.
The user will need to download the SDK version 10.3.1 from BlackMagicDesign
and copy dvp.dll where blender can find it (e.g. next to blender.exe)
2015-04-07 11:00:13 +02:00
889573ba21 Merge remote-tracking branch 'origin/master' into decklink 2015-04-06 23:18:10 +02:00
598854da76 Merge remote-tracking branch 'origin/master' into decklink 2015-04-06 18:08:33 +02:00
d36f57c6ea BGE: ImageViewport no texture to load when used with DeckLink. 2015-04-06 16:49:36 +02:00
3f02a17bba BGE: Fill-in DeckLink object.
Implement the DeckLink object to output on DeckLink card. It takes a
source like the Texture object and gets the image the same way.

API:
dl = bge.texture.DeckLink(0, "HD1080p24")  # card nb, mode
dl.source = bge.texture.ImageViewport()
dl.source.whole = True
dl.refresh(True)

Known issue: using ImageViewport as source will not set the alpha channel
right. This is because the framebuffer by default will not have an alpha
channel. This can be solved either by inserting a 'green' filter that will
convert the background color to alpha, or enable the alpha channel on the
framebuffer (require change in Ghost).
2015-04-06 16:18:06 +02:00
edc169d63e BGE: New VideoTexture.DeckLink object.
This object is analoguous to Texture and is used to send frames out to a
DeckLink card. It is primarly intended to mix computed frames with a video
stream looping through the card for real-time compositing. This is known
as 'keying'.
Currently the implementation is only a stub.
2015-04-04 15:56:13 +02:00
56283d0af8 BGE: setUniformEyef need automatic refresh on every frame.
Fix a bug in setUniformEyef implementation where the caching system for
uniform was getting in the way: a 'eye' uniform needs to be updated on
every frame and for each eye in stereo mode.
2015-03-30 23:02:34 +02:00
f01f394982 BGE: BL_Shader.setUniformEyef(): new uniform type to pass stereo eye value.
BL_Shader.setUniformEyef() python method to define a uniform that will
receive the eye value as a float: 0.0 when rendering the left eye, 0.5
when rendering the right eye.
This can be used in a shader to split a 3D texture sent to the GPU by
VideoDeckLink as the left+right eye frame is sent as a single texture in
bottom/top order.

Work around a bug in VideoDeckLink with the the DVP library: the call to
dvpBindToGLCtx() fails for the first frame. This needs to be investigated
but for now catch the exception thrown by this condition and release the
decklink frame anyway as otherwise it corrupts the reference count of the
decklink device.
2015-03-29 13:59:39 +02:00
ad75477f1c First working implementation of VideoDeckLink.
Doc: TBD
BL_Shader: allows to pass partially defined shader (e.g fragment without
vertex)
2015-03-25 08:53:36 +01:00
a2df27ff89 VideoDeckLink: wip, card opening done, GPUdirect tbd. 2015-03-23 23:27:09 +01:00
430b754f9a Add Windows DeckLink API, put Linux aside for now.
The VideoDeckLink object is still a stub but now it compiles and links
with DeckLink COM API and nVidia DVP library.
Only Windows & CMake working at the moment.
The nVidia DVP library is added in SVN win64_vc12 repo.
2015-03-21 23:15:59 +01:00
3b38dc96af This branch adds support for Decklink capture card in the BGE.
Decklink capture cards from BlackMagicDesign are capable of capturing
high speed video stream such as FullHD on HDMI, also 3D. It will
be available in the VideoTexture module as a new type of texture source.
The capture data will be sent to the GPU using GPUDirect for best
performance.
It will be available for Linux and Windows.
This first commit is only a stub for Linux. Windows to be added.
2015-03-21 14:50:30 +01:00
1158 changed files with 76359 additions and 27834 deletions

View File

@@ -166,13 +166,12 @@ option_defaults_init(
)
# customize...
if (UNIX AND NOT APPLE)
if(UNIX AND NOT APPLE)
# some of these libraries are problematic on Linux
# disable less important dependencies by default
set(_init_CODEC_FFMPEG OFF)
set(_init_CYCLES_OSL OFF)
set(_init_IMAGE_OPENEXR OFF)
set(_init_INPUT_NDOF OFF)
set(_init_JACK OFF)
set(_init_OPENCOLLADA OFF)
set(_init_OPENCOLORIO OFF)
@@ -218,6 +217,10 @@ if(${CMAKE_VERSION} VERSION_LESS 2.8.8)
# add_library OBJECT arg unsupported
set(WITH_BUILDINFO OFF)
endif()
set(BUILDINFO_OVERRIDE_DATE "" CACHE STRING "Use instead of the current date for reproducable builds (empty string disables this option)")
set(BUILDINFO_OVERRIDE_TIME "" CACHE STRING "Use instead of the current time for reproducable builds (empty string disables this option)")
mark_as_advanced(BUILDINFO_OVERRIDE_DATE)
mark_as_advanced(BUILDINFO_OVERRIDE_TIME)
option(WITH_IK_ITASC "Enable ITASC IK solver (only disable for development & for incompatible C++ compilers)" ON)
option(WITH_IK_SOLVER "Enable Legacy IK solver (only disable for development)" ON)
@@ -227,6 +230,7 @@ option(WITH_SYSTEM_BULLET "Use the systems bullet library (currently unsupported
mark_as_advanced(WITH_SYSTEM_BULLET)
option(WITH_GAMEENGINE "Enable Game Engine" ${_init_GAMEENGINE})
option(WITH_PLAYER "Build Player" OFF)
option(WITH_DECKLINK "Support BlackMagicDesign DeckLink cards in the BGE" ON)
option(WITH_OPENCOLORIO "Enable OpenColorIO color management" ${_init_OPENCOLORIO})
# Compositor
@@ -270,6 +274,7 @@ endif()
if(WITH_X11)
option(WITH_X11_XINPUT "Enable X11 Xinput (tablet support and unicode input)" ON)
option(WITH_X11_XF86VMODE "Enable X11 video mode switching" ON)
option(WITH_X11_ALPHA "Enable X11 transparent background" ON)
endif()
if(UNIX AND NOT APPLE)
@@ -362,19 +367,23 @@ if(UNIX AND NOT APPLE)
mark_as_advanced(WITH_BOOST_ICU)
endif()
endif()
option(WITH_PYTHON_INSTALL "Copy system python into the blender install folder" ON)
option(WITH_PYTHON_INSTALL_NUMPY "Copy system numpy into the blender install folder" ON)
set(PYTHON_NUMPY_PATH "" CACHE PATH "Path to python site-packages or dist-packages containing 'numpy' module")
mark_as_advanced(PYTHON_NUMPY_PATH)
if(WITH_PYTHON_INSTALL)
option(WITH_PYTHON_INSTALL_NUMPY "Copy system numpy into the blender install folder" ON)
set(PYTHON_NUMPY_PATH "" CACHE PATH "Path to python site-packages or dist-packages containing 'numpy' module")
mark_as_advanced(PYTHON_NUMPY_PATH)
if(UNIX AND NOT APPLE)
option(WITH_PYTHON_INSTALL_REQUESTS "Copy system requests into the blender install folder" ON)
set(PYTHON_REQUESTS_PATH "" CACHE PATH "Path to python site-packages or dist-packages containing 'requests' module")
mark_as_advanced(PYTHON_REQUESTS_PATH)
endif()
endif()
option(WITH_CPU_SSE "Enable SIMD instruction if they're detected on the host machine" ON)
mark_as_advanced(WITH_CPU_SSE)
if(UNIX AND NOT APPLE)
option(WITH_PYTHON_INSTALL_REQUESTS "Copy system requests into the blender install folder" ON)
set(PYTHON_REQUESTS_PATH "" CACHE PATH "Path to python site-packages or dist-packages containing 'requests' module")
mark_as_advanced(PYTHON_REQUESTS_PATH)
endif()
# Cycles
option(WITH_CYCLES "Enable Cycles Render Engine" ON)
option(WITH_CYCLES_STANDALONE "Build Cycles standalone application" OFF)
@@ -386,8 +395,10 @@ mark_as_advanced(CYCLES_CUDA_BINARIES_ARCH)
unset(PLATFORM_DEFAULT)
option(WITH_CYCLES_LOGGING "Build Cycles with logging support" ON)
option(WITH_CYCLES_DEBUG "Build Cycles with extra debug capabilities" OFF)
option(WITH_CYCLES_NATIVE_ONLY "Build Cycles with native kernel only (which fits current CPU, use for development only)" OFF)
mark_as_advanced(WITH_CYCLES_LOGGING)
mark_as_advanced(WITH_CYCLES_DEBUG)
mark_as_advanced(WITH_CYCLES_NATIVE_ONLY)
option(WITH_CUDA_DYNLOAD "Dynamically load CUDA libraries at runtime" ON)
mark_as_advanced(WITH_CUDA_DYNLOAD)
@@ -468,9 +479,19 @@ if(WIN32)
endif()
# Experimental support of C11 and C++11
option(WITH_C11 "Build with C11 standard enabled, for development use only!" OFF)
#
# We default options to whatever default standard in the current compiler.
if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "6.0") AND (NOT WITH_CXX11))
set(_c11_init ON)
set(_cxx11_init ON)
else()
set(_c11_init OFF)
set(_cxx11_init OFF)
endif()
option(WITH_C11 "Build with C11 standard enabled, for development use only!" ${_c11_init})
mark_as_advanced(WITH_C11)
option(WITH_CXX11 "Build with C++11 standard enabled, for development use only!" OFF)
option(WITH_CXX11 "Build with C++11 standard enabled, for development use only!" ${_cxx11_init})
mark_as_advanced(WITH_CXX11)
# Dependency graph
@@ -509,8 +530,8 @@ if(APPLE)
if(NOT CMAKE_OSX_ARCHITECTURES)
set(CMAKE_OSX_ARCHITECTURES x86_64 CACHE STRING
"Choose the architecture you want to build Blender for: i386, x86_64 or ppc"
FORCE)
"Choose the architecture you want to build Blender for: i386, x86_64 or ppc"
FORCE)
endif()
if(NOT DEFINED OSX_SYSTEM)
@@ -520,15 +541,20 @@ if(APPLE)
OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
# workaround for incorrect cmake xcode lookup for developer previews - XCODE_VERSION does not take xcode-select path into accout
# but would always look into /Applications/Xcode.app while dev versions are named Xcode<version>-DP<preview_number>
execute_process(COMMAND xcode-select --print-path OUTPUT_VARIABLE XCODE_CHECK OUTPUT_STRIP_TRAILING_WHITESPACE)
# workaround for incorrect cmake xcode lookup for developer previews - XCODE_VERSION does not
# take xcode-select path into account but would always look into /Applications/Xcode.app
# while dev versions are named Xcode<version>-DP<preview_number>
execute_process(
COMMAND xcode-select --print-path
OUTPUT_VARIABLE XCODE_CHECK OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE "/Contents/Developer" "" XCODE_BUNDLE ${XCODE_CHECK}) # truncate to bundlepath in any case
if(${CMAKE_GENERATOR} MATCHES "Xcode")
if(${XCODE_VERSION} VERSION_GREATER 4.2) # earlier xcode has no bundled developer dir, no sense in getting xcode path from
string(SUBSTRING "${XCODE_CHECK}" 14 6 DP_NAME) # reduce to XCode name without dp extension
# earlier xcode has no bundled developer dir, no sense in getting xcode path from
if(${XCODE_VERSION} VERSION_GREATER 4.2)
# reduce to XCode name without dp extension
string(SUBSTRING "${XCODE_CHECK}" 14 6 DP_NAME)
if(${DP_NAME} MATCHES Xcode5)
set(XCODE_VERSION 5)
endif()
@@ -555,25 +581,30 @@ if(APPLE)
message(STATUS "Detected OS X ${OSX_SYSTEM} and Xcode ${XCODE_VERSION} at ${XCODE_BUNDLE}")
if(${XCODE_VERSION} VERSION_LESS 4.3)
set(CMAKE_OSX_SYSROOT /Developer/SDKs/MacOSX${OSX_SYSTEM}.sdk CACHE PATH "" FORCE) # use guaranteed existing sdk
# use guaranteed existing sdk
set(CMAKE_OSX_SYSROOT /Developer/SDKs/MacOSX${OSX_SYSTEM}.sdk CACHE PATH "" FORCE)
else()
# note: xcode-select path could be ambigous, cause /Applications/Xcode.app/Contents/Developer or /Applications/Xcode.app would be allowed
# note: xcode-select path could be ambigous,
# cause /Applications/Xcode.app/Contents/Developer or /Applications/Xcode.app would be allowed
# so i use a selfcomposed bundlepath here
set(OSX_SYSROOT_PREFIX ${XCODE_BUNDLE}/Contents/Developer/Platforms/MacOSX.platform)
message(STATUS "OSX_SYSROOT_PREFIX: " ${OSX_SYSROOT_PREFIX})
set(OSX_DEVELOPER_PREFIX /Developer/SDKs/MacOSX${OSX_SYSTEM}.sdk) # use guaranteed existing sdk
set(CMAKE_OSX_SYSROOT ${OSX_SYSROOT_PREFIX}/${OSX_DEVELOPER_PREFIX} CACHE PATH "" FORCE)
if(${CMAKE_GENERATOR} MATCHES "Xcode")
set(CMAKE_XCODE_ATTRIBUTE_SDKROOT macosx${OSX_SYSTEM}) # to silence sdk not found warning, just overrides CMAKE_OSX_SYSROOT
# to silence sdk not found warning, just overrides CMAKE_OSX_SYSROOT
set(CMAKE_XCODE_ATTRIBUTE_SDKROOT macosx${OSX_SYSTEM})
endif()
endif()
if(OSX_SYSTEM MATCHES 10.9)
set(CMAKE_FIND_ROOT_PATH ${CMAKE_OSX_SYSROOT}) # make sure syslibs and headers are looked up in sdk ( expecially for 10.9 openGL atm. )
# make sure syslibs and headers are looked up in sdk ( expecially for 10.9 openGL atm. )
set(CMAKE_FIND_ROOT_PATH ${CMAKE_OSX_SYSROOT})
endif()
if(NOT CMAKE_OSX_DEPLOYMENT_TARGET)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.6" CACHE STRING "" FORCE) # 10.6 is our min. target, if you use higher sdk, weak linking happens
# 10.6 is our min. target, if you use higher sdk, weak linking happens
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.6" CACHE STRING "" FORCE)
endif()
if(NOT ${CMAKE_GENERATOR} MATCHES "Xcode")
@@ -582,8 +613,6 @@ if(APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
add_definitions("-DMACOSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET}")
endif()
option(WITH_LIBS10.5 "Use 10.5 libs (needed for 64bit builds)" OFF)
endif()
@@ -591,7 +620,10 @@ endif()
# Check for conflicting/unsupported configurations
if(NOT WITH_BLENDER AND NOT WITH_PLAYER AND NOT WITH_CYCLES_STANDALONE)
message(FATAL_ERROR "At least one of WITH_BLENDER or WITH_PLAYER or WITH_CYCLES_STANDALONE must be enabled, nothing to do!")
message(FATAL_ERROR
"At least one of WITH_BLENDER or WITH_PLAYER or "
"WITH_CYCLES_STANDALONE must be enabled, nothing to do!"
)
endif()
if(NOT WITH_GAMEENGINE AND WITH_PLAYER)
@@ -655,7 +687,8 @@ if(NOT WITH_BOOST)
set_and_warn(WITH_OPENAL OFF) # depends on AUDASPACE
set_and_warn(WITH_GAMEENGINE OFF) # depends on AUDASPACE
set_and_warn(WITH_PLAYER OFF) # depends on GAMEENGINE
elseif(WITH_CYCLES OR WITH_OPENIMAGEIO OR WITH_AUDASPACE OR WITH_INTERNATIONAL OR WITH_OPENVDB OR WITH_OPENCOLORIO OR WITH_MOD_BOOLEAN)
elseif(WITH_CYCLES OR WITH_OPENIMAGEIO OR WITH_AUDASPACE OR WITH_INTERNATIONAL OR
WITH_OPENVDB OR WITH_OPENCOLORIO OR WITH_MOD_BOOLEAN)
# Keep enabled
else()
# New dependency graph needs either Boost or C++11 for function bindings.
@@ -692,6 +725,7 @@ if(WITH_GHOST_SDL OR WITH_HEADLESS)
set(WITH_X11 OFF)
set(WITH_X11_XINPUT OFF)
set(WITH_X11_XF86VMODE OFF)
set(WITH_X11_ALPHA OFF)
set(WITH_GHOST_XDND OFF)
set(WITH_INPUT_IME OFF)
endif()
@@ -752,18 +786,22 @@ endif()
if(WITH_INTERNATIONAL)
if(NOT EXISTS "${CMAKE_SOURCE_DIR}/release/datafiles/locale/languages")
message(WARNING "Translation path '${CMAKE_SOURCE_DIR}/release/datafiles/locale' is missing, "
"This is a 'git submodule', which are known not to work with bridges to other version "
"control systems, disabling 'WITH_INTERNATIONAL'.")
message(WARNING
"Translation path '${CMAKE_SOURCE_DIR}/release/datafiles/locale' is missing, "
"This is a 'git submodule', which are known not to work with bridges to other version "
"control systems, disabling 'WITH_INTERNATIONAL'."
)
set(WITH_INTERNATIONAL OFF)
endif()
endif()
if(WITH_PYTHON)
if(NOT EXISTS "${CMAKE_SOURCE_DIR}/release/scripts/addons/modules")
message(WARNING "Addons path '${CMAKE_SOURCE_DIR}/release/scripts/addons' is missing, "
"This is a 'git submodule', which are known not to work with bridges to other version "
"control systems: * CONTINUING WITHOUT ADDONS *")
message(WARNING
"Addons path '${CMAKE_SOURCE_DIR}/release/scripts/addons' is missing, "
"This is a 'git submodule', which are known not to work with bridges to other version "
"control systems: * CONTINUING WITHOUT ADDONS *"
)
endif()
endif()
@@ -797,21 +835,6 @@ set(PLATFORM_LINKFLAGS "")
set(PLATFORM_LINKFLAGS_DEBUG "")
# For alternate Python locations the commandline can be used to override detected/default cache settings, e.g:
# On Unix:
# cmake ../blender \
# -D PYTHON_VERSION=3.5 \
# -D PYTHON_INCLUDE_DIR=/opt/py35/include/python3.5d \
# -D PYTHON_LIBRARY=/opt/py35/lib/libpython3.5d.so
#
# On Macs:
# cmake ../blender \
# -D PYTHON_INCLUDE_DIR=/System/Library/Frameworks/Python.framework/Versions/3.5/include/python3.5 \
# -D PYTHON_LIBPATH=/System/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/config \
# -G Xcode
#
# When changing any of this remember to update the notes in doc/build_systems/cmake.txt
#-----------------------------------------------------------------------------
#Platform specifics
@@ -842,6 +865,16 @@ if(WITH_X11)
endif()
endif()
if(WITH_X11_ALPHA)
find_library(X11_Xrender_LIB Xrender ${X11_LIB_SEARCH_PATH})
mark_as_advanced(X11_Xrender_LIB)
if (X11_Xrender_LIB)
list(APPEND PLATFORM_LINKLIBS ${X11_Xrender_LIB})
else()
set(WITH_X11_ALPHA OFF)
endif()
endif()
endif()
@@ -1013,14 +1046,12 @@ if(UNIX AND NOT APPLE)
if(WITH_INPUT_NDOF)
find_package_wrapper(Spacenav)
if(NOT SPACENAV_FOUND)
set(WITH_INPUT_NDOF OFF)
endif()
# use generic names within blenders buildsystem.
if(SPACENAV_FOUND)
# use generic names within blenders buildsystem.
set(NDOF_INCLUDE_DIRS ${SPACENAV_INCLUDE_DIRS})
set(NDOF_LIBRARIES ${SPACENAV_LIBRARIES})
else()
set(WITH_INPUT_NDOF OFF)
endif()
endif()
@@ -1034,7 +1065,11 @@ if(UNIX AND NOT APPLE)
if(${OSL_LIBRARY_VERSION_MAJOR} EQUAL "1" AND ${OSL_LIBRARY_VERSION_MINOR} LESS "6")
# Note: --whole-archive is needed to force loading of all symbols in liboslexec,
# otherwise LLVM is missing the osl_allocate_closure_component function
set(OSL_LIBRARIES ${OSL_OSLCOMP_LIBRARY} -Wl,--whole-archive ${OSL_OSLEXEC_LIBRARY} -Wl,--no-whole-archive ${OSL_OSLQUERY_LIBRARY})
set(OSL_LIBRARIES
${OSL_OSLCOMP_LIBRARY}
-Wl,--whole-archive ${OSL_OSLEXEC_LIBRARY}
-Wl,--no-whole-archive ${OSL_OSLQUERY_LIBRARY}
)
endif()
else()
message(STATUS "OSL not found, disabling it from Cycles")
@@ -1105,7 +1140,13 @@ if(UNIX AND NOT APPLE)
set(PUGIXML_LIBRARIES "")
endif()
set(OPENIMAGEIO_LIBRARIES ${OPENIMAGEIO_LIBRARIES} ${PNG_LIBRARIES} ${JPEG_LIBRARIES} ${ZLIB_LIBRARIES} ${BOOST_LIBRARIES})
set(OPENIMAGEIO_LIBRARIES
${OPENIMAGEIO_LIBRARIES}
${PNG_LIBRARIES}
${JPEG_LIBRARIES}
${ZLIB_LIBRARIES}
${BOOST_LIBRARIES}
)
set(OPENIMAGEIO_LIBPATH) # TODO, remove and reference the absolute path everywhere
set(OPENIMAGEIO_DEFINITIONS "")
@@ -1146,7 +1187,9 @@ if(UNIX AND NOT APPLE)
if(WITH_LLVM OR WITH_SDL_DYNLOAD)
# Fix for conflict with Mesa llvmpipe
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -Wl,--version-script='${CMAKE_SOURCE_DIR}/source/creator/blender.map'")
set(PLATFORM_LINKFLAGS
"${PLATFORM_LINKFLAGS} -Wl,--version-script='${CMAKE_SOURCE_DIR}/source/creator/blender.map'"
)
endif()
if(WITH_OPENSUBDIV)
@@ -1249,7 +1292,10 @@ elseif(WIN32)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /SAFESEH:NO")
set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} /SAFESEH:NO")
list(APPEND PLATFORM_LINKLIBS ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32 advapi32 shfolder shell32 ole32 oleaut32 uuid psapi Dbghelp)
list(APPEND PLATFORM_LINKLIBS
ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32
advapi32 shfolder shell32 ole32 oleaut32 uuid psapi Dbghelp
)
if(WITH_INPUT_IME)
list(APPEND PLATFORM_LINKLIBS imm32)
@@ -1287,7 +1333,8 @@ elseif(WIN32)
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /MT")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO} /MT")
set(PLATFORM_LINKFLAGS "/SUBSYSTEM:CONSOLE /STACK:2097152 /INCREMENTAL:NO /NODEFAULTLIB:msvcrt.lib /NODEFAULTLIB:msvcmrt.lib /NODEFAULTLIB:msvcurt.lib /NODEFAULTLIB:msvcrtd.lib")
set(PLATFORM_LINKFLAGS "/SUBSYSTEM:CONSOLE /STACK:2097152 /INCREMENTAL:NO ")
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /NODEFAULTLIB:msvcrt.lib /NODEFAULTLIB:msvcmrt.lib /NODEFAULTLIB:msvcurt.lib /NODEFAULTLIB:msvcrtd.lib ")
# Ignore meaningless for us linker warnings.
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /ignore:4049 /ignore:4217 /ignore:4221")
@@ -1302,6 +1349,17 @@ elseif(WIN32)
set(PLATFORM_LINKFLAGS_DEBUG "/IGNORE:4099 /NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:libc.lib")
# Use dynamic loading for OpenMP
if(WITH_OPENMP)
if(MSVC_VERSION EQUAL 1800)
set(OPENMP_DLL_NAME "vcomp120")
else()
set(OPENMP_DLL_NAME "vcomp140")
endif()
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /DELAYLOAD:${OPENMP_DLL_NAME}.dll delayimp.lib")
set(PLATFORM_LINKFLAGS_DEBUG "${PLATFORM_LINKFLAGS_DEBUG} /DELAYLOAD:${OPENMP_DLL_NAME}d.dll delayimp.lib")
endif()
if(NOT DEFINED LIBDIR)
# Setup 64bit and 64bit windows systems
@@ -1330,9 +1388,9 @@ elseif(WIN32)
# Add each of our libraries to our cmake_prefix_path so find_package() could work
file(GLOB children RELATIVE ${LIBDIR} ${LIBDIR}/*)
foreach(child ${children})
if(IS_DIRECTORY ${LIBDIR}/${child})
list(APPEND CMAKE_PREFIX_PATH ${LIBDIR}/${child})
endif()
if(IS_DIRECTORY ${LIBDIR}/${child})
list(APPEND CMAKE_PREFIX_PATH ${LIBDIR}/${child})
endif()
endforeach()
set(ZLIB_INCLUDE_DIRS ${LIBDIR}/zlib/include)
@@ -1437,23 +1495,28 @@ elseif(WIN32)
set(OPENEXR_INCLUDE_DIRS ${OPENEXR_INCLUDE_DIR} ${OPENEXR}/include/OpenEXR)
set(OPENEXR_LIBPATH ${OPENEXR}/lib)
set(OPENEXR_LIBRARIES
${OPENEXR_LIBPATH}/Iex-2_2.lib
${OPENEXR_LIBPATH}/Half.lib
${OPENEXR_LIBPATH}/IlmImf-2_2.lib
${OPENEXR_LIBPATH}/Imath-2_2.lib
${OPENEXR_LIBPATH}/IlmThread-2_2.lib
optimized ${OPENEXR_LIBPATH}/Iex-2_2.lib
optimized ${OPENEXR_LIBPATH}/Half.lib
optimized ${OPENEXR_LIBPATH}/IlmImf-2_2.lib
optimized ${OPENEXR_LIBPATH}/Imath-2_2.lib
optimized ${OPENEXR_LIBPATH}/IlmThread-2_2.lib
debug ${OPENEXR_LIBPATH}/Iex-2_2_d.lib
debug ${OPENEXR_LIBPATH}/Half_d.lib
debug ${OPENEXR_LIBPATH}/IlmImf-2_2_d.lib
debug ${OPENEXR_LIBPATH}/Imath-2_2_d.lib
debug ${OPENEXR_LIBPATH}/IlmThread-2_2_d.lib
)
endif()
endif()
if(WITH_IMAGE_TIFF)
# Try to find tiff first then complain and set static and maybe wrong paths
find_package(TIFF)
if(NOT TIFF_FOUND)
message(WARNING "Using HARDCODED libtiff locations")
set(TIFF_LIBRARY ${LIBDIR}/tiff/lib/libtiff.lib)
set(TIFF_INCLUDE_DIR ${LIBDIR}/tiff/include)
endif()
# Try to find tiff first then complain and set static and maybe wrong paths
find_package(TIFF)
if(NOT TIFF_FOUND)
message(WARNING "Using HARDCODED libtiff locations")
set(TIFF_LIBRARY ${LIBDIR}/tiff/lib/libtiff.lib)
set(TIFF_INCLUDE_DIR ${LIBDIR}/tiff/include)
endif()
endif()
if(WITH_JACK)
@@ -1508,12 +1571,17 @@ elseif(WIN32)
set(BOOST_DEBUG_POSTFIX "vc140-mt-sgd-1_60.lib")
endif()
set(BOOST_LIBRARIES
optimized libboost_date_time-${BOOST_POSTFIX} optimized libboost_filesystem-${BOOST_POSTFIX}
optimized libboost_date_time-${BOOST_POSTFIX}
optimized libboost_filesystem-${BOOST_POSTFIX}
optimized libboost_regex-${BOOST_POSTFIX}
optimized libboost_system-${BOOST_POSTFIX} optimized libboost_thread-${BOOST_POSTFIX}
debug libboost_date_time-${BOOST_DEBUG_POSTFIX} debug libboost_filesystem-${BOOST_DEBUG_POSTFIX}
optimized libboost_system-${BOOST_POSTFIX}
optimized libboost_thread-${BOOST_POSTFIX}
debug libboost_date_time-${BOOST_DEBUG_POSTFIX}
debug libboost_filesystem-${BOOST_DEBUG_POSTFIX}
debug libboost_regex-${BOOST_DEBUG_POSTFIX}
debug libboost_system-${BOOST_DEBUG_POSTFIX} debug libboost_thread-${BOOST_DEBUG_POSTFIX})
debug libboost_system-${BOOST_DEBUG_POSTFIX}
debug libboost_thread-${BOOST_DEBUG_POSTFIX}
)
if(WITH_CYCLES_OSL)
set(BOOST_LIBRARIES ${BOOST_LIBRARIES}
optimized libboost_wave-${BOOST_POSTFIX}
@@ -1580,12 +1648,12 @@ elseif(WIN32)
endif()
if(WITH_OPENVDB)
set(BLOSC_LIBRARIES ${LIBDIR}/blosc/lib/libblosc.lib)
set(TBB_LIBRARIES ${LIBDIR}/tbb/lib/tbb.lib)
set(BLOSC_LIBRARIES optimized ${LIBDIR}/blosc/lib/libblosc.lib debug ${LIBDIR}/blosc/lib/libblosc_d.lib)
set(TBB_LIBRARIES optimized ${LIBDIR}/tbb/lib/tbb.lib debug ${LIBDIR}/tbb/lib/tbb_debug.lib)
set(TBB_INCLUDE_DIR ${LIBDIR}/tbb/include)
set(OPENVDB ${LIBDIR}/openvdb)
set(OPENVDB_INCLUDE_DIRS ${OPENVDB}/include ${TBB_INCLUDE_DIR})
set(OPENVDB_LIBRARIES openvdb ${TBB_LIBRARIES} ${BLOSC_LIBRARIES})
set(OPENVDB_LIBRARIES optimized openvdb debug openvdb_d ${TBB_LIBRARIES} ${BLOSC_LIBRARIES})
set(OPENVDB_LIBPATH ${LIBDIR}/openvdb/lib)
endif()
@@ -1642,7 +1710,8 @@ elseif(WIN32)
#endif
int main(void) { return 0; }
"
WITH_MINGW64)
WITH_MINGW64
)
if(NOT DEFINED LIBDIR)
if(WITH_MINGW64)
@@ -1663,7 +1732,10 @@ elseif(WIN32)
message(FATAL_ERROR "Windows requires pre-compiled libs at: '${LIBDIR}'")
endif()
list(APPEND PLATFORM_LINKLIBS -lshell32 -lshfolder -lgdi32 -lmsvcrt -lwinmm -lmingw32 -lm -lws2_32 -lz -lstdc++ -lole32 -luuid -lwsock32 -lpsapi -ldbghelp)
list(APPEND PLATFORM_LINKLIBS
-lshell32 -lshfolder -lgdi32 -lmsvcrt -lwinmm -lmingw32 -lm -lws2_32
-lz -lstdc++ -lole32 -luuid -lwsock32 -lpsapi -ldbghelp
)
if(WITH_INPUT_IME)
list(APPEND PLATFORM_LINKLIBS -limm32)
@@ -1732,7 +1804,14 @@ elseif(WIN32)
${OPENCOLLADA}/include/opencollada/GeneratedSaxParser
)
set(OPENCOLLADA_LIBPATH ${OPENCOLLADA}/lib/opencollada)
set(OPENCOLLADA_LIBRARIES OpenCOLLADAStreamWriter OpenCOLLADASaxFrameworkLoader OpenCOLLADAFramework OpenCOLLADABaseUtils GeneratedSaxParser UTF MathMLSolver buffer ftoa xml)
set(OPENCOLLADA_LIBRARIES
OpenCOLLADAStreamWriter
OpenCOLLADASaxFrameworkLoader
OpenCOLLADAFramework
OpenCOLLADABaseUtils
GeneratedSaxParser
UTF MathMLSolver buffer ftoa xml
)
set(PCRE_LIBRARIES pcre)
endif()
@@ -1805,12 +1884,14 @@ elseif(WIN32)
if(WITH_INTERNATIONAL)
set(BOOST_LIBRARIES ${BOOST_LIBRARIES}
optimized boost_locale-${BOOST_POSTFIX}
debug boost_locale-${BOOST_DEBUG_POSTFIX})
debug boost_locale-${BOOST_DEBUG_POSTFIX}
)
endif()
if(WITH_CYCLES_OSL)
set(BOOST_LIBRARIES ${BOOST_LIBRARIES}
optimized boost_wave-${BOOST_POSTFIX}
debug boost_wave-${BOOST_DEBUG_POSTFIX})
debug boost_wave-${BOOST_DEBUG_POSTFIX}
)
endif()
set(BOOST_LIBPATH ${BOOST}/lib)
set(BOOST_DEFINITIONS "-DBOOST_ALL_NO_LIB -DBOOST_THREAD_USE_LIB ")
@@ -1891,7 +1972,7 @@ elseif(WIN32)
set(OPENAL ${LIBDIR}/openal)
set(OPENALDIR ${LIBDIR}/openal)
set(OPENAL_INCLUDE_DIR ${OPENAL}/include)
if(MSVC12)
if(MSVC)
set(OPENAL_LIBRARY openal32)
else()
set(OPENAL_LIBRARY wrap_oal)
@@ -1919,7 +2000,14 @@ elseif(WIN32)
find_library(OSL_LIB_EXEC_DEBUG NAMES oslexec_d PATHS ${CYCLES_OSL}/lib)
find_library(OSL_LIB_COMP_DEBUG NAMES oslcomp_d PATHS ${CYCLES_OSL}/lib)
find_library(OSL_LIB_QUERY_DEBUG NAMES oslquery_d PATHS ${CYCLES_OSL}/lib)
list(APPEND OSL_LIBRARIES optimized ${OSL_LIB_COMP} optimized ${OSL_LIB_EXEC} optimized ${OSL_LIB_QUERY} debug ${OSL_LIB_EXEC_DEBUG} debug ${OSL_LIB_COMP_DEBUG} debug ${OSL_LIB_QUERY_DEBUG})
list(APPEND OSL_LIBRARIES
optimized ${OSL_LIB_COMP}
optimized ${OSL_LIB_EXEC}
optimized ${OSL_LIB_QUERY}
debug ${OSL_LIB_EXEC_DEBUG}
debug ${OSL_LIB_COMP_DEBUG}
debug ${OSL_LIB_QUERY_DEBUG}
)
find_path(OSL_INCLUDE_DIR OSL/oslclosure.h PATHS ${CYCLES_OSL}/include)
find_program(OSL_COMPILER NAMES oslc PATHS ${CYCLES_OSL}/bin)
@@ -1933,20 +2021,8 @@ elseif(WIN32)
elseif(APPLE)
if(${CMAKE_OSX_DEPLOYMENT_TARGET} STREQUAL "10.5" OR ${CMAKE_OSX_DEPLOYMENT_TARGET} STRGREATER "10.5")
set(WITH_LIBS10.5 ON CACHE BOOL "Use 10.5 libs" FORCE) # valid also for 10.6/7/8/9
endif()
if(NOT DEFINED LIBDIR)
if(WITH_LIBS10.5)
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin-9.x.universal)
else()
if(CMAKE_OSX_ARCHITECTURES MATCHES i386)
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin-8.x.i386)
else()
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin-8.0.0-powerpc)
endif()
endif()
set(LIBDIR ${CMAKE_SOURCE_DIR}/../lib/darwin-9.x.universal)
else()
message(STATUS "Using pre-compiled LIBDIR: ${LIBDIR}")
endif()
@@ -1998,22 +2074,30 @@ elseif(APPLE)
if(NOT WITH_PYTHON_MODULE AND NOT WITH_PYTHON_FRAMEWORK)
# normally cached but not since we include them with blender
set(PYTHON_INCLUDE_DIR "${LIBDIR}/python/include/python${PYTHON_VERSION}m")
# set(PYTHON_EXECUTABLE "${LIBDIR}/python/bin/python${PYTHON_VERSION}") # not used yet
set(PYTHON_EXECUTABLE "${LIBDIR}/python/bin/python${PYTHON_VERSION}m")
set(PYTHON_LIBRARY python${PYTHON_VERSION}m)
set(PYTHON_LIBPATH "${LIBDIR}/python/lib/python${PYTHON_VERSION}")
# set(PYTHON_LINKFLAGS "-u _PyMac_Error") # won't build with this enabled
else()
# module must be compiled against Python framework
set(PYTHON_INCLUDE_DIR "/Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/include/python${PYTHON_VERSION}m")
set(PYTHON_EXECUTABLE "/Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/bin/python${PYTHON_VERSION}")
set(_py_framework "/Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}")
set(PYTHON_INCLUDE_DIR "${_py_framework}/include/python${PYTHON_VERSION}m")
set(PYTHON_EXECUTABLE "${_py_framework}/bin/python${PYTHON_VERSION}m")
set(PYTHON_LIBPATH "${_py_framework}/lib/python${PYTHON_VERSION}/config-${PYTHON_VERSION}m")
#set(PYTHON_LIBRARY python${PYTHON_VERSION})
set(PYTHON_LIBPATH "/Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/lib/python${PYTHON_VERSION}/config-${PYTHON_VERSION}m")
#set(PYTHON_LINKFLAGS "-u _PyMac_Error -framework Python") # won't build with this enabled
unset(_py_framework)
endif()
# uncached vars
set(PYTHON_INCLUDE_DIRS "${PYTHON_INCLUDE_DIR}")
set(PYTHON_LIBRARIES "${PYTHON_LIBRARY}")
if(NOT EXISTS "${PYTHON_EXECUTABLE}")
message(FATAL_ERROR "Python executable missing: ${PYTHON_EXECUTABLE}")
endif()
endif()
if(WITH_FFTW3)
@@ -2046,7 +2130,10 @@ elseif(APPLE)
if(WITH_CODEC_FFMPEG)
set(FFMPEG ${LIBDIR}/ffmpeg)
set(FFMPEG_INCLUDE_DIRS ${FFMPEG}/include)
set(FFMPEG_LIBRARIES avcodec avdevice avformat avutil mp3lame swscale x264 xvidcore theora theoradec theoraenc vorbis vorbisenc vorbisfile ogg)
set(FFMPEG_LIBRARIES
avcodec avdevice avformat avutil
mp3lame swscale x264 xvidcore theora theoradec theoraenc vorbis vorbisenc vorbisfile ogg
)
set(FFMPEG_LIBPATH ${FFMPEG}/lib)
endif()
@@ -2057,13 +2144,13 @@ elseif(APPLE)
)
mark_as_advanced(SYSTEMSTUBS_LIBRARY)
if(SYSTEMSTUBS_LIBRARY)
list(APPEND PLATFORM_LINKLIBS stdc++ SystemStubs)
else()
list(APPEND PLATFORM_LINKLIBS stdc++)
list(APPEND PLATFORM_LINKLIBS SystemStubs)
endif()
set(PLATFORM_CFLAGS "-pipe -funsigned-char")
set(PLATFORM_LINKFLAGS "-fexceptions -framework CoreServices -framework Foundation -framework IOKit -framework AppKit -framework Cocoa -framework Carbon -framework AudioUnit -framework AudioToolbox -framework CoreAudio")
set(PLATFORM_LINKFLAGS
"-fexceptions -framework CoreServices -framework Foundation -framework IOKit -framework AppKit -framework Cocoa -framework Carbon -framework AudioUnit -framework AudioToolbox -framework CoreAudio"
)
if(WITH_CODEC_QUICKTIME)
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -framework QTKit")
if(CMAKE_OSX_ARCHITECTURES MATCHES i386)
@@ -2072,22 +2159,10 @@ elseif(APPLE)
endif()
endif()
# XXX - SOME MAC DEV PLEASE TEST WITH THE SDK INSTALLED!
# ALSO SHOULD BE MOVED INTO OWN MODULE WHEN FUNCTIONAL
if(WITH_INPUT_NDOF)
# This thread it *should* work and check the framework - campbell
# http://www.cmake.org/pipermail/cmake/2005-December/007740.html
find_library(3DCONNEXION_CLIENT_FRAMEWORK
NAMES 3DconnexionClient
)
if(NOT 3DCONNEXION_CLIENT_FRAMEWORK)
set(WITH_INPUT_NDOF OFF)
endif()
if(WITH_INPUT_NDOF)
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -F/Library/Frameworks -weak_framework 3DconnexionClient")
set(NDOF_INCLUDE_DIRS /Library/Frameworks/3DconnexionClient.framework/Headers )
endif()
if(WITH_CXX11)
list(APPEND PLATFORM_LINKLIBS c++)
else()
list(APPEND PLATFORM_LINKLIBS stdc++)
endif()
if(WITH_JACK)
@@ -2095,7 +2170,8 @@ elseif(APPLE)
endif()
if(WITH_PYTHON_MODULE OR WITH_PYTHON_FRAMEWORK)
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/Python")# force cmake to link right framework
# force cmake to link right framework
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} /Library/Frameworks/Python.framework/Versions/${PYTHON_VERSION}/Python")
endif()
if(WITH_OPENCOLLADA)
@@ -2110,10 +2186,18 @@ elseif(APPLE)
)
set(OPENCOLLADA_LIBPATH ${OPENCOLLADA}/lib)
set(OPENCOLLADA_LIBRARIES "OpenCOLLADASaxFrameworkLoader -lOpenCOLLADAFramework -lOpenCOLLADABaseUtils -lOpenCOLLADAStreamWriter -lMathMLSolver -lGeneratedSaxParser -lxml2 -lbuffer -lftoa")
set(OPENCOLLADA_LIBRARIES
OpenCOLLADASaxFrameworkLoader
-lOpenCOLLADAFramework
-lOpenCOLLADABaseUtils
-lOpenCOLLADAStreamWriter
-lMathMLSolver
-lGeneratedSaxParser
-lxml2 -lbuffer -lftoa
)
# Use UTF functions from collada if LLVM is not enabled
if(NOT WITH_LLVM)
set(OPENCOLLADA_LIBRARIES "${OPENCOLLADA_LIBRARIES} -lUTF")
list(APPEND OPENCOLLADA_LIBRARIES -lUTF)
endif()
# pcre is bundled with openCollada
#set(PCRE ${LIBDIR}/pcre)
@@ -2148,14 +2232,17 @@ elseif(APPLE)
set(TIFF_LIBPATH ${TIFF}/lib)
endif()
if(WITH_INPUT_NDOF)
# linker needs "-weak_framework 3DconnexionClient"
endif()
if(WITH_BOOST)
set(BOOST ${LIBDIR}/boost)
set(BOOST_INCLUDE_DIR ${BOOST}/include)
set(BOOST_LIBRARIES boost_date_time-mt boost_filesystem-mt boost_regex-mt boost_system-mt boost_thread-mt boost_wave-mt)
set(BOOST_LIBRARIES
boost_date_time-mt
boost_filesystem-mt
boost_regex-mt
boost_system-mt
boost_thread-mt
boost_wave-mt
)
if(WITH_INTERNATIONAL)
list(APPEND BOOST_LIBRARIES boost_locale-mt)
endif()
@@ -2176,8 +2263,22 @@ elseif(APPLE)
if(WITH_OPENIMAGEIO)
set(OPENIMAGEIO ${LIBDIR}/openimageio)
set(OPENIMAGEIO_INCLUDE_DIRS ${OPENIMAGEIO}/include)
set(OPENIMAGEIO_LIBRARIES ${OPENIMAGEIO}/lib/libOpenImageIO.a ${PNG_LIBRARIES} ${JPEG_LIBRARIES} ${TIFF_LIBRARY} ${OPENEXR_LIBRARIES} ${ZLIB_LIBRARIES})
set(OPENIMAGEIO_LIBPATH ${OPENIMAGEIO}/lib ${JPEG_LIBPATH} ${PNG_LIBPATH} ${TIFF_LIBPATH} ${OPENEXR_LIBPATH} ${ZLIB_LIBPATH})
set(OPENIMAGEIO_LIBRARIES
${OPENIMAGEIO}/lib/libOpenImageIO.a
${PNG_LIBRARIES}
${JPEG_LIBRARIES}
${TIFF_LIBRARY}
${OPENEXR_LIBRARIES}
${ZLIB_LIBRARIES}
)
set(OPENIMAGEIO_LIBPATH
${OPENIMAGEIO}/lib
${JPEG_LIBPATH}
${PNG_LIBPATH}
${TIFF_LIBPATH}
${OPENEXR_LIBPATH}
${ZLIB_LIBPATH}
)
set(OPENIMAGEIO_DEFINITIONS "-DOIIO_STATIC_BUILD")
set(OPENIMAGEIO_IDIFF "${LIBDIR}/openimageio/bin/idiff")
endif()
@@ -2270,8 +2371,14 @@ elseif(APPLE)
include_directories(${LIBDIR}/openmp/include)
link_directories(${LIBDIR}/openmp/lib)
# This is a workaround for our helperbinaries ( datatoc, masgfmt, ... ),
# They are linked also to omp lib, so we need it in builddir for runtime exexcution, TODO: remove all unneeded dependencies from these
execute_process(COMMAND ditto -arch ${CMAKE_OSX_ARCHITECTURES} ${LIBDIR}/openmp/lib/libiomp5.dylib ${CMAKE_BINARY_DIR}/Resources/lib/libiomp5.dylib) # for intermediate binaries, in respect to lib ID
# They are linked also to omp lib, so we need it in builddir for runtime exexcution,
# TODO: remove all unneeded dependencies from these
# for intermediate binaries, in respect to lib ID
execute_process(
COMMAND ditto -arch ${CMAKE_OSX_ARCHITECTURES}
${LIBDIR}/openmp/lib/libiomp5.dylib
${CMAKE_BINARY_DIR}/Resources/lib/libiomp5.dylib)
endif()
endif()
endif()
@@ -2297,7 +2404,20 @@ elseif(APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftemplate-depth=1024")
endif()
# Get rid of eventually clashes, we export some symbols explicite as local
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -Xlinker -unexported_symbols_list -Xlinker ${CMAKE_SOURCE_DIR}/source/creator/osx_locals.map")
set(PLATFORM_LINKFLAGS
"${PLATFORM_LINKFLAGS} -Xlinker -unexported_symbols_list -Xlinker ${CMAKE_SOURCE_DIR}/source/creator/osx_locals.map"
)
if(WITH_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
set(PLATFORM_LINKFLAGS "${PLATFORM_LINKFLAGS} -stdlib=libc++")
endif()
# Suppress ranlib "has no symbols" warnings (workaround for T48250)
set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> Scr <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> Scr <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_C_ARCHIVE_FINISH "<CMAKE_RANLIB> -no_warning_for_no_symbols -c <TARGET>")
set(CMAKE_CXX_ARCHIVE_FINISH "<CMAKE_RANLIB> -no_warning_for_no_symbols -c <TARGET>")
endif()
#-----------------------------------------------------------------------------
@@ -2309,38 +2429,50 @@ endif()
if(WITH_CYCLES)
if(NOT WITH_OPENIMAGEIO)
message(FATAL_ERROR "Cycles requires WITH_OPENIMAGEIO, the library may not have been found. Configure OIIO or disable WITH_CYCLES")
message(FATAL_ERROR
"Cycles requires WITH_OPENIMAGEIO, the library may not have been found. "
"Configure OIIO or disable WITH_CYCLES"
)
endif()
if(NOT WITH_BOOST)
message(FATAL_ERROR "Cycles requires WITH_BOOST, the library may not have been found. Configure BOOST or disable WITH_CYCLES")
message(FATAL_ERROR
"Cycles requires WITH_BOOST, the library may not have been found. "
"Configure BOOST or disable WITH_CYCLES"
)
endif()
if(WITH_CYCLES_OSL)
if(NOT WITH_LLVM)
message(FATAL_ERROR "Cycles OSL requires WITH_LLVM, the library may not have been found. Configure LLVM or disable WITH_CYCLES_OSL")
message(FATAL_ERROR
"Cycles OSL requires WITH_LLVM, the library may not have been found. "
"Configure LLVM or disable WITH_CYCLES_OSL"
)
endif()
endif()
endif()
if(WITH_INTERNATIONAL)
if(NOT WITH_BOOST)
message(FATAL_ERROR "Internationalization requires WITH_BOOST, the library may not have been found. Configure BOOST or disable WITH_INTERNATIONAL")
message(FATAL_ERROR
"Internationalization requires WITH_BOOST, the library may not have been found. "
"Configure BOOST or disable WITH_INTERNATIONAL"
)
endif()
endif()
# See TEST_SSE_SUPPORT() for how this is defined.
if(WITH_RAYOPTIMIZATION)
if(SUPPORT_SSE_BUILD)
set(PLATFORM_CFLAGS " ${COMPILER_SSE_FLAG} ${PLATFORM_CFLAGS}")
add_definitions(-D__SSE__ -D__MMX__)
endif()
if(SUPPORT_SSE2_BUILD)
set(PLATFORM_CFLAGS " ${COMPILER_SSE2_FLAG} ${PLATFORM_CFLAGS}")
add_definitions(-D__SSE2__)
if(NOT SUPPORT_SSE_BUILD) # dont double up
add_definitions(-D__MMX__)
endif()
# Do it globally, SSE2 is required for quite some time now.
# Doing it now allows to use SSE/SSE2 in inline headers.
if(SUPPORT_SSE_BUILD)
set(PLATFORM_CFLAGS " ${COMPILER_SSE_FLAG} ${PLATFORM_CFLAGS}")
add_definitions(-D__SSE__ -D__MMX__)
endif()
if(SUPPORT_SSE2_BUILD)
set(PLATFORM_CFLAGS " ${COMPILER_SSE2_FLAG} ${PLATFORM_CFLAGS}")
add_definitions(-D__SSE2__)
if(NOT SUPPORT_SSE_BUILD) # dont double up
add_definitions(-D__MMX__)
endif()
endif()
@@ -2410,7 +2542,10 @@ if(WITH_GL_PROFILE_COMPAT OR WITH_GL_PROFILE_CORE)
elseif(WITH_GL_PROFILE_ES20)
if(WITH_SYSTEM_GLES)
if(NOT OPENGLES_LIBRARY)
message(FATAL_ERROR "Unable to find OpenGL ES libraries. Install them or disable WITH_SYSTEM_GLES.")
message(FATAL_ERROR
"Unable to find OpenGL ES libraries. "
"Install them or disable WITH_SYSTEM_GLES."
)
endif()
list(APPEND BLENDER_GL_LIBRARIES OPENGLES_LIBRARY)
@@ -2422,7 +2557,10 @@ elseif(WITH_GL_PROFILE_ES20)
list(APPEND BLENDER_GL_LIBRARIES "${OPENGLES_LIBRARY}")
if(NOT OPENGLES_LIBRARY)
message(FATAL_ERROR "To compile WITH_GL_EGL you need to set OPENGLES_LIBRARY to the file path of an OpenGL ES 2.0 library.")
message(FATAL_ERROR
"To compile WITH_GL_EGL you need to set OPENGLES_LIBRARY "
"to the file path of an OpenGL ES 2.0 library."
)
endif()
endif()
@@ -2434,7 +2572,10 @@ elseif(WITH_GL_PROFILE_ES20)
mark_as_advanced(OPENGLES_DLL)
if(NOT OPENGLES_DLL)
message(FATAL_ERROR "To compile WITH_GL_PROFILE_ES20 you need to set OPENGLES_DLL to the file path of an OpenGL ES 2.0 runtime dynamic link library (DLL).")
message(FATAL_ERROR
"To compile WITH_GL_PROFILE_ES20 you need to set OPENGLES_DLL to the file "
"path of an OpenGL ES 2.0 runtime dynamic link library (DLL)."
)
endif()
if(WITH_GL_ANGLE)
@@ -2448,7 +2589,10 @@ elseif(WITH_GL_PROFILE_ES20)
mark_as_advanced(D3DCOMPILER_DLL)
if(D3DCOMPILER_DLL STREQUAL "")
message(FATAL_ERROR "To compile WITH_GL_ANGLE you need to set D3DCOMPILER_DLL to the file path of a copy of the DirectX redistributable DLL file: D3DCompiler_46.dll")
message(FATAL_ERROR
"To compile WITH_GL_ANGLE you need to set D3DCOMPILER_DLL to the file "
"path of a copy of the DirectX redistributable DLL file: D3DCompiler_46.dll"
)
endif()
endif()
@@ -2462,7 +2606,10 @@ if(WITH_GL_EGL)
if(WITH_SYSTEM_GLES)
if(NOT OPENGLES_EGL_LIBRARY)
message(FATAL_ERROR "Unable to find OpenGL ES libraries. Install them or disable WITH_SYSTEM_GLES.")
message(FATAL_ERROR
"Unable to find OpenGL ES libraries. "
"Install them or disable WITH_SYSTEM_GLES."
)
endif()
list(APPEND BLENDER_GL_LIBRARIES OPENGLES_EGL_LIBRARY)
@@ -2474,7 +2621,10 @@ if(WITH_GL_EGL)
list(APPEND BLENDER_GL_LIBRARIES "${OPENGLES_LIBRARY}" "${OPENGLES_EGL_LIBRARY}")
if(NOT OPENGLES_EGL_LIBRARY)
message(FATAL_ERROR "To compile WITH_GL_EGL you need to set OPENGLES_EGL_LIBRARY to the file path of an EGL library.")
message(FATAL_ERROR
"To compile WITH_GL_EGL you need to set OPENGLES_EGL_LIBRARY "
"to the file path of an EGL library."
)
endif()
endif()
@@ -2486,7 +2636,10 @@ if(WITH_GL_EGL)
mark_as_advanced(OPENGLES_EGL_DLL)
if(NOT OPENGLES_EGL_DLL)
message(FATAL_ERROR "To compile WITH_GL_EGL you need to set OPENGLES_EGL_DLL to the file path of an EGL runtime dynamic link library (DLL).")
message(FATAL_ERROR
"To compile WITH_GL_EGL you need to set OPENGLES_EGL_DLL "
"to the file path of an EGL runtime dynamic link library (DLL)."
)
endif()
endif()
@@ -2651,7 +2804,9 @@ endif()
if(WITH_LIBMV)
set(CERES_DEFINES)
if(SHARED_PTR_FOUND)
if(WITH_CXX11)
# nothing to be done
elseif(SHARED_PTR_FOUND)
if(SHARED_PTR_TR1_MEMORY_HEADER)
list(APPEND CERES_DEFINES -DCERES_TR1_MEMORY_HEADER)
endif()
@@ -2662,7 +2817,9 @@ if(WITH_LIBMV)
message(FATAL_ERROR "Ceres: Unable to find shared_ptr.")
endif()
if(HAVE_STD_UNORDERED_MAP_HEADER)
if(WITH_CXX11)
list(APPEND CERES_DEFINES -DCERES_STD_UNORDERED_MAP)
elseif(HAVE_STD_UNORDERED_MAP_HEADER)
if(HAVE_UNORDERED_MAP_IN_STD_NAMESPACE)
list(APPEND CERES_DEFINES -DCERES_STD_UNORDERED_MAP)
else()
@@ -2864,10 +3021,12 @@ endif()
# be most problematic.
if(WITH_PYTHON)
if(NOT EXISTS "${PYTHON_INCLUDE_DIR}/Python.h")
message(FATAL_ERROR "Missing: \"${PYTHON_INCLUDE_DIR}/Python.h\",\n"
"Set the cache entry 'PYTHON_INCLUDE_DIR' to point "
"to a valid python include path. Containing "
"Python.h for python version \"${PYTHON_VERSION}\"")
message(FATAL_ERROR
"Missing: \"${PYTHON_INCLUDE_DIR}/Python.h\",\n"
"Set the cache entry 'PYTHON_INCLUDE_DIR' to point "
"to a valid python include path. Containing "
"Python.h for python version \"${PYTHON_VERSION}\""
)
endif()
if(WIN32 OR APPLE)
@@ -2885,12 +3044,22 @@ endif()
if(WITH_CXX11)
if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Clang")
# TODO(sergey): Do we want c++11 or gnu-c++11 here?
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(MSVC12)
# Nothing special is needed, C++11 features are available by default.
else()
message(FATAL_ERROR "Compiler ${CMAKE_C_COMPILER_ID} is not supported for C++11 build yet")
endif()
else()
# GCC-6 switched to C++11 by default, which would break linking with existing libraries
# by default. So we explicitly disable C++11 for a new GCC so no linking issues happens.
if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "6.0"))
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++98")
# We also disable any of C++11 ABI from usage, so we wouldn't even try to
# link to stuff from std::__cxx11 namespace.
add_definitions("-D_GLIBCXX_USE_CXX11_ABI=0")
endif()
endif()
# Visual Studio has all standards it supports available by default
@@ -3005,7 +3174,7 @@ if(FIRST_RUN)
string(LENGTH "${_msg}" _len)
while("32" GREATER "${_len}")
set(_msg "${_msg} ")
math(EXPR _len "${_len} + 1")
math(EXPR _len "${_len} + 1")
endwhile()
set(_config_msg "${_config_msg}\n${_msg}${${_setting}}" PARENT_SCOPE)
@@ -3043,6 +3212,7 @@ if(FIRST_RUN)
info_cfg_text("System Options:")
info_cfg_option(WITH_INSTALL_PORTABLE)
info_cfg_option(WITH_X11_ALPHA)
info_cfg_option(WITH_X11_XF86VMODE)
info_cfg_option(WITH_X11_XINPUT)
info_cfg_option(WITH_MEM_JEMALLOC)

View File

@@ -87,13 +87,13 @@ ifndef NPROCS
NPROCS:=$(shell nproc)
endif
ifeq ($(OS), Darwin)
NPROCS:=$(shell sysctl -a | grep "hw.ncpu" | cut -d" " -f3)
NPROCS:=$(shell sysctl -n hw.ncpu)
endif
ifeq ($(OS), FreeBSD)
NPROCS:=$(shell sysctl -a | grep "hw.ncpu" | cut -d" " -f2 )
NPROCS:=$(shell sysctl -n hw.ncpu)
endif
ifeq ($(OS), NetBSD)
NPROCS:=$(shell sysctl -a | grep "hw.ncpu" | cut -d" " -f2 )
NPROCS:=$(shell sysctl -n hw.ncpu)
endif
endif
@@ -120,7 +120,7 @@ endif
# -----------------------------------------------------------------------------
# Build Blender
all: FORCE
all: .FORCE
@echo
@echo Configuring Blender in \"$(BUILD_DIR)\" ...
@@ -149,13 +149,13 @@ bpy: all
# -----------------------------------------------------------------------------
# Configuration (save some cd'ing around)
config: FORCE
config: .FORCE
$(CMAKE_CONFIG_TOOL) "$(BUILD_DIR)"
# -----------------------------------------------------------------------------
# Help for build targets
help: FORCE
help: .FORCE
@echo ""
@echo "Convenience targets provided for building blender, (multiple at once can be used)"
@echo " * debug - build a debug binary"
@@ -228,13 +228,13 @@ help: FORCE
# -----------------------------------------------------------------------------
# Packages
#
package_debian: FORCE
package_debian: .FORCE
cd build_files/package_spec ; DEB_BUILD_OPTIONS="parallel=$(NPROCS)" sh ./build_debian.sh
package_pacman: FORCE
package_pacman: .FORCE
cd build_files/package_spec/pacman ; MAKEFLAGS="-j$(NPROCS)" makepkg
package_archive: FORCE
package_archive: .FORCE
make -C "$(BUILD_DIR)" -s package_archive
@echo archive in "$(BUILD_DIR)/release"
@@ -242,24 +242,24 @@ package_archive: FORCE
# -----------------------------------------------------------------------------
# Tests
#
test: FORCE
test: .FORCE
cd $(BUILD_DIR) ; ctest . --output-on-failure
# run pep8 check check on scripts we distribute.
test_pep8: FORCE
test_pep8: .FORCE
$(PYTHON) tests/python/pep8.py > test_pep8.log 2>&1
@echo "written: test_pep8.log"
# run some checks on our cmakefiles.
test_cmake: FORCE
test_cmake: .FORCE
$(PYTHON) build_files/cmake/cmake_consistency_check.py > test_cmake_consistency.log 2>&1
@echo "written: test_cmake_consistency.log"
# run deprecation tests, see if we have anything to remove.
test_deprecated: FORCE
test_deprecated: .FORCE
$(PYTHON) tests/check_deprecated.py
test_style_c: FORCE
test_style_c: .FORCE
# run our own checks on C/C++ style
PYTHONIOENCODING=utf_8 $(PYTHON) \
"$(BLENDER_DIR)/source/tools/check_source/check_style_c.py" \
@@ -267,7 +267,7 @@ test_style_c: FORCE
"$(BLENDER_DIR)/source/creator" \
--no-length-check
test_style_c_qtc: FORCE
test_style_c_qtc: .FORCE
# run our own checks on C/C++ style
USE_QTC_TASK=1 \
PYTHONIOENCODING=utf_8 $(PYTHON) \
@@ -280,7 +280,7 @@ test_style_c_qtc: FORCE
@echo "written: test_style.tasks"
test_style_osl: FORCE
test_style_osl: .FORCE
# run our own checks on C/C++ style
PYTHONIOENCODING=utf_8 $(PYTHON) \
"$(BLENDER_DIR)/source/tools/check_source/check_style_c.py" \
@@ -288,7 +288,7 @@ test_style_osl: FORCE
"$(BLENDER_DIR)/release/scripts/templates_osl"
test_style_osl_qtc: FORCE
test_style_osl_qtc: .FORCE
# run our own checks on C/C++ style
USE_QTC_TASK=1 \
PYTHONIOENCODING=utf_8 $(PYTHON) \
@@ -303,13 +303,13 @@ test_style_osl_qtc: FORCE
# Project Files
#
project_qtcreator: FORCE
project_qtcreator: .FORCE
$(PYTHON) build_files/cmake/cmake_qtcreator_project.py "$(BUILD_DIR)"
project_netbeans: FORCE
project_netbeans: .FORCE
$(PYTHON) build_files/cmake/cmake_netbeans_project.py "$(BUILD_DIR)"
project_eclipse: FORCE
project_eclipse: .FORCE
cmake -G"Eclipse CDT4 - Unix Makefiles" -H"$(BLENDER_DIR)" -B"$(BUILD_DIR)"
@@ -317,40 +317,40 @@ project_eclipse: FORCE
# Static Checking
#
check_cppcheck: FORCE
check_cppcheck: .FORCE
$(CMAKE_CONFIG)
cd "$(BUILD_DIR)" ; \
$(PYTHON) "$(BLENDER_DIR)/build_files/cmake/cmake_static_check_cppcheck.py" 2> \
"$(BLENDER_DIR)/check_cppcheck.txt"
@echo "written: check_cppcheck.txt"
check_clang_array: FORCE
check_clang_array: .FORCE
$(CMAKE_CONFIG)
cd "$(BUILD_DIR)" ; \
$(PYTHON) "$(BLENDER_DIR)/build_files/cmake/cmake_static_check_clang_array.py"
check_splint: FORCE
check_splint: .FORCE
$(CMAKE_CONFIG)
cd "$(BUILD_DIR)" ; \
$(PYTHON) "$(BLENDER_DIR)/build_files/cmake/cmake_static_check_splint.py"
check_sparse: FORCE
check_sparse: .FORCE
$(CMAKE_CONFIG)
cd "$(BUILD_DIR)" ; \
$(PYTHON) "$(BLENDER_DIR)/build_files/cmake/cmake_static_check_sparse.py"
check_smatch: FORCE
check_smatch: .FORCE
$(CMAKE_CONFIG)
cd "$(BUILD_DIR)" ; \
$(PYTHON) "$(BLENDER_DIR)/build_files/cmake/cmake_static_check_smatch.py"
check_spelling_py: FORCE
check_spelling_py: .FORCE
cd "$(BUILD_DIR)" ; \
PYTHONIOENCODING=utf_8 $(PYTHON) \
"$(BLENDER_DIR)/source/tools/check_source/check_spelling.py" \
"$(BLENDER_DIR)/release/scripts"
check_spelling_c: FORCE
check_spelling_c: .FORCE
cd "$(BUILD_DIR)" ; \
PYTHONIOENCODING=utf_8 $(PYTHON) \
"$(BLENDER_DIR)/source/tools/check_source/check_spelling.py" \
@@ -359,7 +359,7 @@ check_spelling_c: FORCE
"$(BLENDER_DIR)/intern/guardedalloc" \
"$(BLENDER_DIR)/intern/ghost" \
check_spelling_c_qtc: FORCE
check_spelling_c_qtc: .FORCE
cd "$(BUILD_DIR)" ; USE_QTC_TASK=1 \
PYTHONIOENCODING=utf_8 $(PYTHON) \
"$(BLENDER_DIR)/source/tools/check_source/check_spelling.py" \
@@ -370,13 +370,13 @@ check_spelling_c_qtc: FORCE
> \
"$(BLENDER_DIR)/check_spelling_c.tasks"
check_spelling_osl: FORCE
check_spelling_osl: .FORCE
cd "$(BUILD_DIR)" ;\
PYTHONIOENCODING=utf_8 $(PYTHON) \
"$(BLENDER_DIR)/source/tools/check_source/check_spelling.py" \
"$(BLENDER_DIR)/intern/cycles/kernel/shaders"
check_descriptions: FORCE
check_descriptions: .FORCE
"$(BUILD_DIR)/bin/blender" --background -noaudio --factory-startup --python \
"$(BLENDER_DIR)/source/tools/check_source/check_descriptions.py"
@@ -384,14 +384,14 @@ check_descriptions: FORCE
# Utilities
#
tgz: FORCE
tgz: .FORCE
./build_files/utils/build_tgz.sh
icons: FORCE
icons: .FORCE
"$(BLENDER_DIR)/release/datafiles/blender_icons_update.py"
"$(BLENDER_DIR)/release/datafiles/prvicons_update.py"
update: FORCE
update: .FORCE
if [ -d "../lib" ]; then \
svn update ../lib/* ; \
fi
@@ -404,23 +404,23 @@ update: FORCE
#
# Simple version of ./doc/python_api/sphinx_doc_gen.sh with no PDF generation.
doc_py: FORCE
doc_py: .FORCE
"$(BUILD_DIR)/bin/blender" --background -noaudio --factory-startup --python doc/python_api/sphinx_doc_gen.py
cd doc/python_api ; sphinx-build -b html sphinx-in sphinx-out
@echo "docs written into: '$(BLENDER_DIR)/doc/python_api/sphinx-out/contents.html'"
doc_doxy: FORCE
doc_doxy: .FORCE
cd doc/doxygen; doxygen Doxyfile
@echo "docs written into: '$(BLENDER_DIR)/doc/doxygen/html/index.html'"
doc_dna: FORCE
doc_dna: .FORCE
"$(BUILD_DIR)/bin/blender" --background -noaudio --factory-startup --python doc/blender_file_format/BlendFileDnaExporter_25.py
@echo "docs written into: '$(BLENDER_DIR)/doc/blender_file_format/dna.html'"
doc_man: FORCE
doc_man: .FORCE
$(PYTHON) doc/manpage/blender.1.py "$(BUILD_DIR)/bin/blender"
help_features: FORCE
help_features: .FORCE
@$(PYTHON) -c \
"import re; \
print('\n'.join([ \
@@ -431,9 +431,9 @@ help_features: FORCE
if w.startswith('WITH_')]))" | uniq
clean: FORCE
clean: .FORCE
$(MAKE) -C "$(BUILD_DIR)" clean
.PHONY: all
FORCE:
.FORCE:

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,11 @@
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -13,7 +13,7 @@
set(LLVM_VERSION_MAJOR 3)
set(LLVM_VERSION_MINOR 1)
@@ -14,7 +14,7 @@
set(LLVM_VERSION_MINOR 4)
-set(PACKAGE_VERSION "\${LLVM_VERSION_MAJOR}.\${LLVM_VERSION_MINOR}svn")
+set(PACKAGE_VERSION "\${LLVM_VERSION_MAJOR}.\${LLVM_VERSION_MINOR}")
if (NOT PACKAGE_VERSION)
- set(PACKAGE_VERSION "${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}svn")
+ set(PACKAGE_VERSION "${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}")
endif()
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
option(LLVM_INSTALL_TOOLCHAIN_ONLY "Only include toolchain files in the 'install' target." OFF)

View File

@@ -87,7 +87,7 @@ c['change_source'] = GitPoller(
# CODEBASES
#
# Allow to controll separately things like branches for each repo and submodules.
# Allow to control separately things like branches for each repo and submodules.
all_repositories = {
r'git://git.blender.org/blender.git': 'blender',

View File

@@ -56,7 +56,6 @@ if 'cmake' in builder:
chroot_name = None # If not None command will be delegated to that chroot
cuda_chroot_name = None # If not None cuda compilationcommand will be delegated to that chroot
build_cubins = True # Whether to build Cycles CUDA kernels
remove_install_dir = False # Remove installation folder before building
bits = 64
# Config file to be used (relative to blender's sources root)
@@ -70,18 +69,24 @@ if 'cmake' in builder:
cuda_cmake_options = []
if builder.startswith('mac'):
install_dir = None
# Set up OSX architecture
if builder.endswith('x86_64_10_6_cmake'):
cmake_extra_options.append('-DCMAKE_OSX_ARCHITECTURES:STRING=x86_64')
cmake_extra_options.append('-DCUDA_NVCC_EXECUTABLE=/usr/local/cuda-hack/bin/nvcc')
elif builder.startswith('win'):
install_dir = None
if builder.endswith('_vc2015'):
if builder.startswith('win64'):
cmake_options.append(['-G', '"Visual Studio 12 2013 Win64"'])
cmake_options.extend(['-G', 'Visual Studio 14 2015 Win64', '-DWITH_CYCLES_CUDA_BINARIES=0'])
elif builder.startswith('win32'):
bits = 32
cmake_options.append(['-G', '"Visual Studio 12 2013"'])
cmake_options.extend(['-G', 'Visual Studio 14 2015', '-DWITH_CYCLES_CUDA_BINARIES=0'])
else:
if builder.startswith('win64'):
cmake_options.extend(['-G', 'Visual Studio 12 2013 Win64'])
elif builder.startswith('win32'):
bits = 32
cmake_options.extend(['-G', 'Visual Studio 12 2013'])
elif builder.startswith('linux'):
tokens = builder.split("_")
@@ -90,7 +95,6 @@ if 'cmake' in builder:
deb_name = "jessie"
elif glibc == 'glibc211':
deb_name = "squeeze"
remove_install_dir = True
cmake_config_file = "build_files/buildbot/config/blender_linux.cmake"
cmake_player_config_file = "build_files/buildbot/config/blender_linux_player.cmake"
if builder.endswith('x86_64_cmake'):
@@ -116,8 +120,7 @@ if 'cmake' in builder:
if 'cuda' not in targets:
cmake_options += cuda_cmake_options
if install_dir:
cmake_options.append("-DCMAKE_INSTALL_PREFIX=%s" % (install_dir))
cmake_options.append("-DCMAKE_INSTALL_PREFIX=%s" % (install_dir))
cmake_options += cmake_extra_options
@@ -132,10 +135,8 @@ if 'cmake' in builder:
cuda_chroot_prefix = chroot_prefix[:]
# Make sure no garbage remained from the previous run
# (only do it if builder requested this)
if remove_install_dir:
if os.path.isdir(install_dir):
shutil.rmtree(install_dir)
if os.path.isdir(install_dir):
shutil.rmtree(install_dir)
for target in targets:
print("Building target %s" % (target))
@@ -187,7 +188,7 @@ if 'cmake' in builder:
sys.exit(retcode)
if builder.startswith('linux') and target == 'cuda':
blender_h = os.path.join(blender_dir, "source", "blender", "blenkernel", "BKE_blender.h")
blender_h = os.path.join(blender_dir, "source", "blender", "blenkernel", "BKE_blender_version.h")
blender_version = int(parse_header_file(blender_h, 'BLENDER_VERSION'))
blender_version = "%d.%d" % (blender_version // 100, blender_version % 100)
kernels = os.path.join(target_build_dir, 'intern', 'cycles', 'kernel')

View File

@@ -130,7 +130,7 @@ if builder.find('cmake') != -1:
blenderplayer = os.path.join(install_dir, 'blenderplayer')
buildinfo_h = os.path.join(build_dir, "source", "creator", "buildinfo.h")
blender_h = os.path.join(blender_dir, "source", "blender", "blenkernel", "BKE_blender.h")
blender_h = os.path.join(blender_dir, "source", "blender", "blenkernel", "BKE_blender_version.h")
# Get version information
blender_version = int(parse_header_file(blender_h, 'BLENDER_VERSION'))

View File

@@ -35,9 +35,8 @@ blender_dir = '../blender.git'
if "cmake" in builder:
# cmake
if "linux" in builder or 'mac' in builder:
print("Automated tests are still DISABLED!")
sys.exit(0)
print("Automated tests are still DISABLED!")
sys.exit(0)
build_dir = os.path.abspath(os.path.join('..', 'build', builder))
chroot_name = None

View File

@@ -1,5 +1,10 @@
# This is called by cmake as an extermal process from
# This is called by cmake as an external process from
# ./source/creator/CMakeLists.txt to write ./source/creator/buildinfo.h
# Caller must define:
# SOURCE_DIR
# Optional overrides:
# BUILD_DATE
# BUILD_TIME
# Extract working copy information for SOURCE_DIR into MY_XXX variables
# with a default in case anything fails, for example when using git-svn
@@ -128,12 +133,19 @@ endif()
# BUILD_PLATFORM and BUILD_PLATFORM are taken from CMake
# but BUILD_DATE and BUILD_TIME are platform dependent
if(UNIX)
execute_process(COMMAND date "+%Y-%m-%d" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND date "+%H:%M:%S" OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
if(WIN32)
execute_process(COMMAND cmd /c date /t OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND cmd /c time /t OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT BUILD_DATE)
execute_process(COMMAND date "+%Y-%m-%d" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
if(NOT BUILD_TIME)
execute_process(COMMAND date "+%H:%M:%S" OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
elseif(WIN32)
if(NOT BUILD_DATE)
execute_process(COMMAND cmd /c date /t OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
if(NOT BUILD_TIME)
execute_process(COMMAND cmd /c time /t OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
endif()
# Write a file with the BUILD_HASH define

View File

@@ -240,9 +240,10 @@ def cmake_get_src(f):
filen.close()
def is_ignore(f):
for ig in IGNORE:
def is_ignore(f, ignore_used):
for index, ig in enumerate(IGNORE):
if ig in f:
ignore_used[index] = True
return True
return False
@@ -283,10 +284,12 @@ def main():
del is_err
del errs
ignore_used = [False] * len(IGNORE)
# now check on files not accounted for.
print("\nC/C++ Files CMake doesnt know about...")
for cf in sorted(source_list(SOURCE_DIR, is_c)):
if not is_ignore(cf):
if not is_ignore(cf, ignore_used):
if cf not in global_c:
print("missing_c: ", cf)
@@ -303,7 +306,7 @@ def main():
print("\nC/C++ Headers CMake doesnt know about...")
for hf in sorted(source_list(SOURCE_DIR, is_c_header)):
if not is_ignore(hf):
if not is_ignore(hf, ignore_used):
if hf not in global_h:
print("missing_h: ", hf)
@@ -324,5 +327,12 @@ def main():
if i > 1:
traceback.print_exc()
# Check ignores aren't stale
print("\nCheck for unused 'IGNORE' paths...")
for index, ig in enumerate(IGNORE):
if not ignore_used[index]:
print("unused ignore: %r" % ig)
if __name__ == "__main__":
main()

View File

@@ -3,11 +3,7 @@ import os
IGNORE = (
"/test/",
"/tests/gtests/",
"/BSP_GhostTest/",
"/release/",
"/xembed/",
"/TerraplayNetwork/",
"/ik_glut_test/",
# specific source files
"extern/bullet2/src/BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.cpp",
@@ -18,31 +14,8 @@ IGNORE = (
"extern/bullet2/src/BulletDynamics/Character/btKinematicCharacterController.cpp",
"extern/bullet2/src/BulletDynamics/ConstraintSolver/btHinge2Constraint.cpp",
"extern/bullet2/src/BulletDynamics/ConstraintSolver/btUniversalConstraint.cpp",
"extern/eltopo/common/meshes/ObjLoader.cpp",
"extern/eltopo/common/meshes/meshloader.cpp",
"extern/eltopo/common/openglutils.cpp",
"extern/eltopo/eltopo3d/broadphase_blenderbvh.cpp",
"source/blender/imbuf/intern/imbuf_cocoa.m",
"extern/recastnavigation/Recast/Source/RecastLog.cpp",
"extern/recastnavigation/Recast/Source/RecastTimer.cpp",
"intern/audaspace/SRC/AUD_SRCResampleFactory.cpp",
"intern/audaspace/SRC/AUD_SRCResampleReader.cpp",
"intern/cycles/render/film_response.cpp",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_2_2.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_2_3.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_2_4.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_2_d.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_3_3.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_3_4.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_3_9.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_3_d.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_4_3.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_4_4.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_2_4_d.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_4_4_2.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_4_4_3.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_4_4_4.cc",
"extern/libmv/third_party/ceres/internal/ceres/generated/schur_eliminator_4_4_d.cc",
"extern/bullet2/src/BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.h",
"extern/bullet2/src/BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.h",
@@ -52,20 +25,12 @@ IGNORE = (
"extern/bullet2/src/BulletDynamics/Character/btKinematicCharacterController.h",
"extern/bullet2/src/BulletDynamics/ConstraintSolver/btHinge2Constraint.h",
"extern/bullet2/src/BulletDynamics/ConstraintSolver/btUniversalConstraint.h",
"extern/eltopo/common/meshes/Edge.hpp",
"extern/eltopo/common/meshes/ObjLoader.hpp",
"extern/eltopo/common/meshes/TriangleIndex.hpp",
"extern/eltopo/common/meshes/meshloader.h",
"extern/eltopo/eltopo3d/broadphase_blenderbvh.h",
"extern/recastnavigation/Recast/Include/RecastLog.h",
"extern/recastnavigation/Recast/Include/RecastTimer.h",
"extern/carve/include/carve/config.h",
"extern/carve/include/carve/random/random.h",
"extern/carve/patches/files/config.h",
"extern/carve/patches/files/random.h",
"intern/audaspace/SRC/AUD_SRCResampleFactory.h",
"intern/audaspace/SRC/AUD_SRCResampleReader.h",
"intern/cycles/render/film_response.h",
"extern/carve/include/carve/config.h",
"extern/carve/include/carve/external/boost/random.hpp",
"extern/carve/patches/files/config.h",
"extern/carve/patches/files/random.hpp",
)
UTF8_CHECK = True

View File

@@ -54,7 +54,7 @@ set(WITH_PLAYER ON CACHE BOOL "" FORCE)
set(WITH_MEM_JEMALLOC ON CACHE BOOL "" FORCE)
# platform dependant options
# platform dependent options
if(UNIX AND NOT APPLE)
set(WITH_JACK ON CACHE BOOL "" FORCE)
set(WITH_DOC_MANPAGE ON CACHE BOOL "" FORCE)
@@ -69,7 +69,7 @@ elseif(WIN32)
set(WITH_CODEC_SNDFILE OFF CACHE BOOL "" FORCE)
set(WITH_CYCLES_OSL OFF CACHE BOOL "" FORCE)
endif()
elseif (APPLE)
elseif(APPLE)
set(WITH_JACK ON CACHE BOOL "" FORCE)
set(WITH_CODEC_QUICKTIME ON CACHE BOOL "" FORCE)
set(WITH_OPENSUBDIV OFF CACHE BOOL "" FORCE)

View File

@@ -14,6 +14,7 @@ set(WITH_CODEC_AVI OFF CACHE BOOL "" FORCE)
set(WITH_CODEC_FFMPEG OFF CACHE BOOL "" FORCE)
set(WITH_CODEC_SNDFILE OFF CACHE BOOL "" FORCE)
set(WITH_CYCLES OFF CACHE BOOL "" FORCE)
set(WITH_CYCLES_OSL OFF CACHE BOOL "" FORCE)
set(WITH_FFTW3 OFF CACHE BOOL "" FORCE)
set(WITH_LIBMV OFF CACHE BOOL "" FORCE)
set(WITH_LLVM OFF CACHE BOOL "" FORCE)

View File

@@ -141,22 +141,6 @@ function(target_link_libraries_debug
endforeach()
endfunction()
function(target_link_libraries_decoupled
target
libraries_var
)
if(NOT MSVC)
target_link_libraries(${target} ${${libraries_var}})
else()
# For MSVC we link to different libraries depending whether
# release or debug target is being built.
file_list_suffix(_libraries_debug "${${libraries_var}}" "_d")
target_link_libraries_debug(${target} "${_libraries_debug}")
target_link_libraries_optimized(${target} "${${libraries_var}}")
endif()
endfunction()
# Nicer makefiles with -I/1/foo/ instead of -I/1/2/3/../../foo/
# use it instead of include_directories()
function(blender_include_dirs
@@ -412,14 +396,7 @@ function(setup_liblinks
endif()
target_link_libraries(${target} ${JPEG_LIBRARIES})
if(WITH_IMAGE_OPENEXR)
if(WIN32 AND NOT UNIX AND NOT CMAKE_COMPILER_IS_GNUCC)
file_list_suffix(OPENEXR_LIBRARIES_DEBUG "${OPENEXR_LIBRARIES}" "_d")
target_link_libraries_debug(${target} "${OPENEXR_LIBRARIES_DEBUG}")
target_link_libraries_optimized(${target} "${OPENEXR_LIBRARIES}")
unset(OPENEXR_LIBRARIES_DEBUG)
else()
target_link_libraries(${target} ${OPENEXR_LIBRARIES})
endif()
target_link_libraries(${target} ${OPENEXR_LIBRARIES})
endif()
if(WITH_IMAGE_OPENJPEG AND WITH_SYSTEM_OPENJPEG)
target_link_libraries(${target} ${OPENJPEG_LIBRARIES})
@@ -458,9 +435,6 @@ function(setup_liblinks
if(WITH_MEM_JEMALLOC)
target_link_libraries(${target} ${JEMALLOC_LIBRARIES})
endif()
if(WITH_INPUT_NDOF)
target_link_libraries(${target} ${NDOF_LIBRARIES})
endif()
if(WITH_MOD_CLOTH_ELTOPO)
target_link_libraries(${target} ${LAPACK_LIBRARIES})
endif()
@@ -474,6 +448,9 @@ function(setup_liblinks
if(WITH_OPENMP_STATIC)
target_link_libraries(${target} ${OpenMP_LIBRARIES})
endif()
if(WITH_INPUT_NDOF)
target_link_libraries(${target} ${NDOF_LIBRARIES})
endif()
endif()
# We put CLEW and CUEW here because OPENSUBDIV_LIBRARIES dpeends on them..
@@ -510,6 +487,7 @@ function(SETUP_BLENDER_SORTED_LIBS)
if(WITH_CYCLES)
list(APPEND BLENDER_LINK_LIBS
cycles_render
cycles_graph
cycles_bvh
cycles_device
cycles_kernel
@@ -574,11 +552,11 @@ function(SETUP_BLENDER_SORTED_LIBS)
bf_modifiers
bf_bmesh
bf_gpu
bf_blenloader
bf_blenkernel
bf_physics
bf_nodes
bf_rna
bf_blenloader
bf_imbuf
bf_blenlib
bf_depsgraph
@@ -601,6 +579,7 @@ function(SETUP_BLENDER_SORTED_LIBS)
ge_phys_bullet
bf_intern_smoke
extern_lzma
extern_curve_fit_nd
ge_logic_ketsji
extern_recastnavigation
ge_logic
@@ -622,6 +601,7 @@ function(SETUP_BLENDER_SORTED_LIBS)
bf_intern_dualcon
bf_intern_cycles
cycles_render
cycles_graph
cycles_bvh
cycles_device
cycles_kernel
@@ -681,10 +661,6 @@ function(SETUP_BLENDER_SORTED_LIBS)
list(APPEND BLENDER_SORTED_LIBS bf_quicktime)
endif()
if(WITH_INPUT_NDOF)
list(APPEND BLENDER_SORTED_LIBS bf_intern_ghostndof3dconnexion)
endif()
if(WITH_MOD_BOOLEAN)
list(APPEND BLENDER_SORTED_LIBS extern_carve)
endif()
@@ -709,6 +685,14 @@ function(SETUP_BLENDER_SORTED_LIBS)
list_insert_after(BLENDER_SORTED_LIBS "ge_logic_ngnetwork" "extern_bullet")
endif()
if(WITH_DECKLINK)
list(APPEND BLENDER_SORTED_LIBS bf_intern_decklink)
endif()
if(WIN32)
list(APPEND BLENDER_SORTED_LIBS bf_intern_gpudirect)
endif()
if(WITH_OPENSUBDIV)
list(APPEND BLENDER_SORTED_LIBS bf_intern_opensubdiv)
endif()
@@ -825,7 +809,15 @@ macro(TEST_UNORDERED_MAP_SUPPORT)
# UNORDERED_MAP_NAMESPACE, namespace for unordered_map, if found
include(CheckIncludeFileCXX)
CHECK_INCLUDE_FILE_CXX("unordered_map" HAVE_STD_UNORDERED_MAP_HEADER)
# Workaround for newer GCC (6.x+) where C++11 was enabled by default, which lead us
# to a situation when there is <unordered_map> include but which can't be used uless
# C++11 is enabled.
if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "6.0") AND (NOT WITH_CXX11))
set(HAVE_STD_UNORDERED_MAP_HEADER False)
else()
CHECK_INCLUDE_FILE_CXX("unordered_map" HAVE_STD_UNORDERED_MAP_HEADER)
endif()
if(HAVE_STD_UNORDERED_MAP_HEADER)
# Even so we've found unordered_map header file it doesn't
# mean unordered_map and unordered_set will be declared in
@@ -895,8 +887,16 @@ macro(TEST_SHARED_PTR_SUPPORT)
# otherwise it's assumed to be defined in std namespace.
include(CheckIncludeFileCXX)
include(CheckCXXSourceCompiles)
set(SHARED_PTR_FOUND FALSE)
CHECK_INCLUDE_FILE_CXX(memory HAVE_STD_MEMORY_HEADER)
# Workaround for newer GCC (6.x+) where C++11 was enabled by default, which lead us
# to a situation when there is <unordered_map> include but which can't be used uless
# C++11 is enabled.
if(CMAKE_COMPILER_IS_GNUCC AND (NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS "6.0") AND (NOT WITH_CXX11))
set(HAVE_STD_MEMORY_HEADER False)
else()
CHECK_INCLUDE_FILE_CXX(memory HAVE_STD_MEMORY_HEADER)
endif()
if(HAVE_STD_MEMORY_HEADER)
# Finding the memory header doesn't mean that shared_ptr is in std
# namespace.
@@ -904,7 +904,6 @@ macro(TEST_SHARED_PTR_SUPPORT)
# In particular, MSVC 2008 has shared_ptr declared in std::tr1. In
# order to support this, we do an extra check to see which namespace
# should be used.
include(CheckCXXSourceCompiles)
CHECK_CXX_SOURCE_COMPILES("#include <memory>
int main() {
std::shared_ptr<int> int_ptr;
@@ -990,6 +989,7 @@ macro(remove_strict_flags)
remove_cc_flag(
"-Wstrict-prototypes"
"-Wmissing-prototypes"
"-Wmissing-declarations"
"-Wmissing-format-attribute"
"-Wunused-local-typedefs"
"-Wunused-macros"
@@ -1071,6 +1071,19 @@ macro(remove_strict_flags_file
endmacro()
# External libs may need 'signed char' to be default.
macro(remove_cc_flag_unsigned_char)
if(CMAKE_C_COMPILER_ID MATCHES "^(GNU|Clang|Intel)$")
remove_cc_flag("-funsigned-char")
elseif(MSVC)
remove_cc_flag("/J")
else()
message(WARNING
"Compiler '${CMAKE_C_COMPILER_ID}' failed to disable 'unsigned char' flag."
"Build files need updating."
)
endif()
endmacro()
function(ADD_CHECK_C_COMPILER_FLAG
_CFLAGS
@@ -1117,10 +1130,10 @@ function(get_blender_version)
# - BLENDER_VERSION_CYCLE (alpha, beta, rc, release)
# So cmake depends on BKE_blender.h, beware of inf-loops!
CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/source/blender/blenkernel/BKE_blender.h
${CMAKE_BINARY_DIR}/source/blender/blenkernel/BKE_blender.h.done)
CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/source/blender/blenkernel/BKE_blender_version.h
${CMAKE_BINARY_DIR}/source/blender/blenkernel/BKE_blender_version.h.done)
file(STRINGS ${CMAKE_SOURCE_DIR}/source/blender/blenkernel/BKE_blender.h _contents REGEX "^#define[ \t]+BLENDER_.*$")
file(STRINGS ${CMAKE_SOURCE_DIR}/source/blender/blenkernel/BKE_blender_version.h _contents REGEX "^#define[ \t]+BLENDER_.*$")
string(REGEX REPLACE ".*#define[ \t]+BLENDER_VERSION[ \t]+([0-9]+).*" "\\1" _out_version "${_contents}")
string(REGEX REPLACE ".*#define[ \t]+BLENDER_SUBVERSION[ \t]+([0-9]+).*" "\\1" _out_subversion "${_contents}")

View File

@@ -11,6 +11,10 @@
*
*/
/** \defgroup curve_fit Curve Fitting Library
* \ingroup extern
*/
/** \defgroup bullet Bullet Physics Library
* \ingroup extern
* \see \ref bulletdoc

View File

@@ -0,0 +1,239 @@
"""
Video Capture with DeckLink
+++++++++++++++++++++++++++
Video frames captured with DeckLink cards have pixel formats that are generally not directly
usable by OpenGL, they must be processed by a shader. The three shaders presented here should
cover all common video capture cases.
This file reflects the current video transfer method implemented in the Decklink module:
whenever possible the video images are transferred as float texture because this is more
compatible with GPUs. Of course, only the pixel formats that have a correspondant GL format
can be transferred as float. Look for fg_shaders in this file for an exhaustive list.
Other pixel formats will be transferred as 32 bits integer red-channel texture but this
won't work with certain GPU (Intel GMA); the corresponding shaders are not shown here.
However, it should not be necessary to use any of them as the list below covers all practical
cases of video capture with all types of Decklink product.
In other words, only use one of the pixel format below and you will be fine. Note that depending
on the video stream, only certain pixel formats will be allowed (others will throw an exception).
For example, to capture a PAL video stream, you must use one of the YUV formats.
To find which pixel format is suitable for a particular video stream, use the 'Media Express'
utility that comes with the Decklink software : if you see the video in the 'Log and Capture'
Window, you have selected the right pixel format and you can use the same in Blender.
Notes: * these shaders only decode the RGB channel and set the alpha channel to a fixed
value (look for color.a = ). It's up to you to add postprocessing to the color.
* these shaders are compatible with 2D and 3D video stream
"""
import bge
from bge import logic
from bge import texture as vt
# The default vertex shader, because we need one
#
VertexShader = """
#version 130
void main()
{
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
gl_TexCoord[0] = gl_MultiTexCoord0;
}
"""
# For use with RGB video stream: the pixel is directly usable
#
FragmentShader_R10l = """
#version 130
uniform sampler2D tex;
// stereo = 1.0 if 2D image, =0.5 if 3D (left eye below, right eye above)
uniform float stereo;
// eye = 0.0 for the left eye, 0.5 for the right eye
uniform float eye;
void main(void)
{
vec4 color;
float tx, ty;
tx = gl_TexCoord[0].x;
ty = eye+gl_TexCoord[0].y*stereo;
color = texture(tex, vec2(tx,ty));
color.a = 0.7;
gl_FragColor = color;
}
"""
# For use with YUV video stream
#
FragmentShader_2vuy = """
#version 130
uniform sampler2D tex;
// stereo = 1.0 if 2D image, =0.5 if 3D (left eye below, right eye above)
uniform float stereo;
// eye = 0.0 for the left eye, 0.5 for the right eye
uniform float eye;
void main(void)
{
vec4 color;
float tx, ty, width, Y, Cb, Cr;
int px;
tx = gl_TexCoord[0].x;
ty = eye+gl_TexCoord[0].y*stereo;
width = float(textureSize(tex, 0).x);
color = texture(tex, vec2(tx, ty));
px = int(floor(fract(tx*width)*2.0));
switch (px) {
case 0:
Y = color.g;
break;
case 1:
Y = color.a;
break;
}
Y = (Y - 0.0625) * 1.168949772;
Cb = (color.b - 0.0625) * 1.142857143 - 0.5;
Cr = (color.r - 0.0625) * 1.142857143 - 0.5;
color.r = Y + 1.5748 * Cr;
color.g = Y - 0.1873 * Cb - 0.4681 * Cr;
color.b = Y + 1.8556 * Cb;
color.a = 0.7;
gl_FragColor = color;
}
"""
# For use with high resolution YUV
#
FragmentShader_v210 = """
#version 130
uniform sampler2D tex;
// stereo = 1.0 if 2D image, =0.5 if 3D (left eye below, right eye above)
uniform float stereo;
// eye = 0.0 for the left eye, 0.5 for the right eye
uniform float eye;
void main(void)
{
vec4 color, color1, color2, color3;
int px;
float tx, ty, width, sx, dx, bx, Y, Cb, Cr;
tx = gl_TexCoord[0].x;
ty = eye+gl_TexCoord[0].y*stereo;
width = float(textureSize(tex, 0).x);
// to sample macro pixels (6 pixels in 4 words)
sx = tx*width*0.25+0.01;
// index of display pixel in the macro pixel 0..5
px = int(floor(fract(sx)*6.0));
// increment as we sample the macro pixel
dx = 1.0/width;
// base x coord of macro pixel
bx = (floor(sx)+0.01)*dx*4.0;
color = texture(tex, vec2(bx, ty));
color1 = texture(tex, vec2(bx+dx, ty));
color2 = texture(tex, vec2(bx+dx*2.0, ty));
color3 = texture(tex, vec2(bx+dx*3.0, ty));
switch (px) {
case 0:
case 1:
Cb = color.b;
Cr = color.r;
break;
case 2:
case 3:
Cb = color1.g;
Cr = color2.b;
break;
default:
Cb = color2.r;
Cr = color3.g;
break;
}
switch (px) {
case 0:
Y = color.g;
break;
case 1:
Y = color1.b;
break;
case 2:
Y = color1.r;
break;
case 3:
Y = color2.g;
break;
case 4:
Y = color3.b;
break;
default:
Y = color3.r;
break;
}
Y = (Y - 0.0625) * 1.168949772;
Cb = (Cb - 0.0625) * 1.142857143 - 0.5;
Cr = (Cr - 0.0625) * 1.142857143 - 0.5;
color.r = Y + 1.5748 * Cr;
color.g = Y - 0.1873 * Cb - 0.4681 * Cr;
color.b = Y + 1.8556 * Cb;
color.a = 0.7;
gl_FragColor = color;
}
"""
# The exhausitve list of pixel formats that are transferred as float texture
# Only use those for greater efficiency and compatiblity.
#
fg_shaders = {
'2vuy' :FragmentShader_2vuy,
'8BitYUV' :FragmentShader_2vuy,
'v210' :FragmentShader_v210,
'10BitYUV' :FragmentShader_v210,
'8BitBGRA' :FragmentShader_R10l,
'BGRA' :FragmentShader_R10l,
'8BitARGB' :FragmentShader_R10l,
'10BitRGBXLE':FragmentShader_R10l,
'R10l' :FragmentShader_R10l
}
#
# Helper function to attach a pixel shader to the material that receives the video frame.
#
def config_video(obj, format, pixel, is3D=False, mat=0, card=0):
if not pixel in fg_shaders:
raise('Unsuported shader')
shader = obj.meshes[0].materials[mat].getShader()
if shader != None and not shader.isValid():
shader.setSource(VertexShader, fg_shaders[pixel], True)
shader.setSampler('tex', 0)
shader.setUniformEyef("eye")
shader.setUniform1f("stereo", 0.5 if is3D else 1.0)
tex = vt.Texture(obj, mat)
tex.source = vt.VideoDeckLink(format + "/" + pixel + ("/3D" if is3D else ""), card)
print("frame rate: ", tex.source.framerate)
tex.source.play()
obj["video"] = tex
#
# Attach this function to an object that has a material with texture
# and call it once to initialize the object
#
def init(cont):
#config_video(cont.owner, 'HD720p5994', '8BitBGRA')
#config_video(cont.owner, 'HD720p5994', '8BitYUV')
#config_video(cont.owner, 'pal ', '10BitYUV')
config_video(cont.owner, 'pal ', '8BitYUV')
#
# To be called on every frame
#
def play(cont):
obj = cont.owner
if hasattr(obj, "video"):
obj["video"].refresh(True)

View File

@@ -20,7 +20,7 @@ bpy.types.Scene.my_settings = \
bpy.props.CollectionProperty(type=SceneSettingItem)
# Assume an armature object selected
print("Adding 3 values!")
print("Adding 2 values!")
my_item = bpy.context.scene.my_settings.add()
my_item.name = "Spam"

View File

@@ -48,9 +48,9 @@ bpy.types.Scene.test_array = bpy.props.BoolVectorProperty(size=2, get=get_array,
# Note: the getter/setter callback must use integer identifiers!
test_items = [
("RED", "Red", "", 1),
("GREEN", "Red", "", 2),
("BLUE", "Red", "", 3),
("YELLOW", "Red", "", 4),
("GREEN", "Green", "", 2),
("BLUE", "Blue", "", 3),
("YELLOW", "Yellow", "", 4),
]

View File

@@ -378,6 +378,27 @@ General functions
Render next frame (if Python has control)
.. function:: setRender(render)
Sets the global flag that controls the render of the scene.
If True, the render is done after the logic frame.
If False, the render is skipped and another logic frame starts immediately.
.. note::
GPU VSync no longer limits the number of frame per second when render is off,
but the 'Use Frame Rate' option still regulates the fps. To run as many frames
as possible, untick this option (Render Properties, System panel)
:arg render: the render flag
:type render: bool
.. function:: getRender()
Get the current value of the global render flag
:return: The flag value
:rtype: bool
**********************
Time related functions
**********************

View File

@@ -90,6 +90,43 @@ Constants
Right eye being used during stereoscopic rendering.
.. data:: RAS_OFS_RENDER_BUFFER
The pixel buffer for offscreen render is a RenderBuffer. Argument to :func:`offScreenCreate`
.. data:: RAS_OFS_RENDER_TEXTURE
The pixel buffer for offscreen render is a Texture. Argument to :func:`offScreenCreate`
*****
Types
*****
.. class:: RASOffScreen
An off-screen render buffer object.
Use :func:`offScreenCreate` to create it.
Currently it can only be used in the :class:`bge.texture.ImageRender` constructor to render on a FBO rather than the
default viewport.
.. attribute:: width
The width in pixel of the FBO
:type: integer
.. attribute:: height
The height in pixel of the FBO
:type: integer
.. attribute:: color
The underlying OpenGL bind code of the texture object that holds the rendered image, 0 if the FBO is using RenderBuffer. The choice between RenderBuffer and Texture is determined by the target argument of :func:`offScreenCreate`.
:type: integer
*********
Functions
@@ -362,3 +399,18 @@ Functions
Get the current vsync value
:rtype: One of VSYNC_OFF, VSYNC_ON, VSYNC_ADAPTIVE
.. function:: offScreenCreate(width,height[,samples=0][,target=bge.render.RAS_OFS_RENDER_BUFFER])
Create a Off-screen render buffer object.
:arg width: the width of the buffer in pixels
:type width: integer
:arg height: the height of the buffer in pixels
:type height: integer
:arg samples: the number of multisample for anti-aliasing (MSAA), 0 to disable MSAA
:type samples: integer
:arg target: the pixel storage: :data:`RAS_OFS_RENDER_BUFFER` to render on RenderBuffers (the default), :data:`RAS_OFS_RENDER_TEXTURE` to render on texture. The later is interesting if you want to access the texture directly (see :attr:`RASOffScreen.color`). Otherwise the default is preferable as it's more widely supported by GPUs and more efficient. If the GPU does not support MSAA+Texture (e.g. Intel HD GPU), MSAA will be disabled.
:type target: integer
:rtype: :class:`RASOffScreen`

View File

@@ -51,6 +51,13 @@ When the texture object is deleted, the new texture is deleted and the old textu
:lines: 8-
.. include:: ../examples/bge.texture.2.py
:start-line: 1
:end-line: 6
.. literalinclude:: ../examples/bge.texture.2.py
:lines: 8-
*************
Video classes
*************
@@ -173,12 +180,17 @@ Video classes
:return: Whether the video was playing.
:rtype: bool
.. method:: refresh()
.. method:: refresh(buffer=None, format="RGBA", ts=-1.0)
Refresh video - get its status.
:value: see `FFmpeg Video and Image Status`_.
Refresh video - get its status and optionally copy the frame to an external buffer.
:arg buffer: An optional object that implements the buffer protocol. If specified, the image is copied to the buffer, which must be big enough or an exception is thrown.
:type buffer: any buffer type
:arg format: An optional image format specifier for the image that will be copied to the buffer. Only valid values are "RGBA" or "BGRA"
:type format: str
:arg ts: An optional timestamp (in seconds from the start of the movie) of the frame to be copied to the buffer.
:type ts: float
:return: see `FFmpeg Video and Image Status`_.
:rtype: int
*************
@@ -244,12 +256,15 @@ Image classes
* :class:`FilterRGB24`
* :class:`FilterRGBA32`
.. method:: refresh()
.. method:: refresh(buffer=None, format="RGBA")
Refresh image, i.e. load it.
Refresh image, get its status and optionally copy the frame to an external buffer.
:value: see `FFmpeg Video and Image Status`_.
:arg buffer: An optional object that implements the buffer protocol. If specified, the image is copied to the buffer, which must be big enough or an exception is thrown.
:type buffer: any buffer type
:arg format: An optional image format specifier for the image that will be copied to the buffer. Only valid values are "RGBA" or "BGRA"
:type format: str
:return: see `FFmpeg Video and Image Status`_.
:rtype: int
.. method:: reload(newname=None)
@@ -411,9 +426,14 @@ Image classes
:type: :class:`~bgl.Buffer` or None
.. method:: refresh()
.. method:: refresh(buffer=None, format="RGBA")
Refresh image - invalidate its current content.
Refresh image - render and copy the image to an external buffer (optional) then invalidate its current content.
:arg buffer: An optional object that implements the buffer protocol. If specified, the image is rendered and copied to the buffer, which must be big enough or an exception is thrown.
:type buffer: any buffer type
:arg format: An optional image format specifier for the image that will be copied to the buffer. Only valid values are "RGBA" or "BGRA"
:type format: str
.. attribute:: scale
@@ -498,9 +518,14 @@ Image classes
:type: :class:`~bgl.Buffer` or None
.. method:: refresh()
.. method:: refresh(buffer=None, format="RGBA")
Refresh image - invalidate its current content.
Refresh image - calculate and copy the image to an external buffer (optional) then invalidate its current content.
:arg buffer: An optional object that implements the buffer protocol. If specified, the image is calculated and copied to the buffer, which must be big enough or an exception is thrown.
:type buffer: any buffer type
:arg format: An optional image format specifier for the image that will be copied to the buffer. Only valid values are "RGBA" or "BGRA"
:type format: str
.. attribute:: scale
@@ -545,14 +570,17 @@ Image classes
:type: bool
.. class:: ImageRender(scene, camera)
.. class:: ImageRender(scene, camera, fbo=None)
Image source from render.
Image source from render. The render is done on a custom framebuffer object if fbo is specified, otherwise on
the default framebuffer.
:arg scene: Scene in which the image has to be taken.
:type scene: :class:`~bge.types.KX_Scene`
:arg camera: Camera from which the image has to be taken.
:type camera: :class:`~bge.types.KX_Camera`
:arg fbo: Off-screen render buffer object (optional)
:type fbo: :class:`~bge.render.RASOffScreen`
.. attribute:: alpha
@@ -599,10 +627,6 @@ Image classes
:type: :class:`~bgl.Buffer` or None
.. method:: refresh()
Refresh image - invalidate its current content.
.. attribute:: scale
Fast scale of image (near neighbour).
@@ -640,6 +664,25 @@ Image classes
:type: bool
.. method:: render()
Render the scene but do not extract the pixels yet. The function returns as soon as the render commands have been send to the GPU. The render will proceed asynchronously in the GPU while the host can perform other tasks. To complete the render, you can either call :func:`refresh` directly of refresh the texture of which this object is the source. This method is useful to implement asynchronous render for optimal performance: call render() on frame n and refresh() on frame n+1 to give as much as time as possible to the GPU to render the frame while the game engine can perform other tasks.
:return: True if the render was initiated, False if the render cannot be performed (e.g. the camera is active)
:rtype: bool
.. method:: refresh()
.. method:: refresh(buffer, format="RGBA")
Refresh video - render and optionally copy the image to an external buffer then invalidate its current content. The render may have been started earlier with the :func:`render` method, in which case this function simply waits for the render operations to complete. When called without argument, the pixels are not extracted but the render is guaranteed to be completed when the function returns. This only makes sense with offscreen render on texture target (see :func:`~bge.render.offScreenCreate`).
:arg buffer: An object that implements the buffer protocol. If specified, the image is copied to the buffer, which must be big enough or an exception is thrown. The transfer to the buffer is optimal if no processing of the image is needed. This is the case if flip=False, alpha=True, scale=False, whole=True, depth=False, zbuff=False and no filter is set.
:type buffer: any buffer type of sufficient size
:arg format: An optional image format specifier for the image that will be copied to the buffer. Only valid values are "RGBA" or "BGRA"
:type format: str
:return: True if the render is complete, False if the render cannot be performed (e.g. the camera is active)
:rtype: bool
.. class:: ImageViewport
Image source from viewport.
@@ -689,9 +732,14 @@ Image classes
:type: sequence of two ints
.. method:: refresh()
.. method:: refresh(buffer=None, format="RGBA")
Refresh image - invalidate its current content.
Refresh video - copy the viewport to an external buffer (optional) then invalidate its current content.
:arg buffer: An optional object that implements the buffer protocol. If specified, the image is copied to the buffer, which must be big enough or an exception is thrown. The transfer to the buffer is optimal if no processing of the image is needed. This is the case if flip=False, alpha=True, scale=False, whole=True, depth=False, zbuff=False and no filter is set.
:type buffer: any buffer type
:arg format: An optional image format specifier for the image that will be copied to the buffer. Only valid values are "RGBA" or "BGRA"
:type format: str
.. attribute:: scale
@@ -730,7 +778,174 @@ Image classes
:type: bool
.. class:: VideoDeckLink(format, capture=0)
Image source from an external video stream captured with a DeckLink video card from
Black Magic Design.
Before this source can be used, a DeckLink hardware device must be installed, it can be a PCIe card
or a USB device, and the 'Desktop Video' software package (version 10.4 or above must be installed)
on the host as described in the DeckLink documentation.
If in addition you have a recent nVideo Quadro card, you can benefit from the 'GPUDirect' technology
to push the captured video frame very efficiently to the GPU. For this you need to install the
'DeckLink SDK' version 10.4 or above and copy the 'dvp.dll' runtime library to Blender's
installation directory or to any other place where Blender can load a DLL from.
:arg format: string describing the video format to be captured.
:type format: str
:arg capture: Card number from which the input video must be captured.
:type capture: int
The format argument must be written as “<displayMode>/<pixelFormat>[/3D][:<cacheSize>]” where <displayMode>
describes the frame size and rate and <pixelFormat> the encoding of the pixels.
The optional /3D suffix is to be used if the video stream is stereo with a left and right eye feed.
The optional :<cacheSize> suffix determines the number of the video frames kept in cache, by default 8.
Some DeckLink cards won't work below a certain cache size. The default value 8 should be sufficient for all cards.
You may try to reduce the cache size to reduce the memory footprint. For example the The 4K Extreme is known
to work with 3 frames only, the Extreme 2 needs 4 frames and the Intensity Shuttle needs 6 frames, etc.
Reducing the cache size may be useful when Decklink is used in conjunction with GPUDirect: all frames must be locked
in memory in that case and that puts a lot of pressure on memory. If you reduce the cache size too much,
you'll get no error but no video feed either.
The valid <displayMode> values are copied from the 'BMDDisplayMode' enum in the DeckLink API
without the 'bmdMode' prefix. In case a mode that is not in this list is added in a later version
of the SDK, it is also possible to specify the 4 letters of the internal code for that mode.
You will find the internal code in the DeckLinkAPIModes.h file that is part of the SDK.
Here is for reference the full list of supported display modes with their equivalent internal code:
* NTSC 'ntsc'
* NTSC2398 'nt23'
* PAL 'pal '
* NTSCp 'ntsp'
* PALp 'palp'
HD 1080 Modes:
* HD1080p2398 '23ps'
* HD1080p24 '24ps'
* HD1080p25 'Hp25'
* HD1080p2997 'Hp29'
* HD1080p30 'Hp30'
* HD1080i50 'Hi50'
* HD1080i5994 'Hi59'
* HD1080i6000 'Hi60'
* HD1080p50 'Hp50'
* HD1080p5994 'Hp59'
* HD1080p6000 'Hp60'
HD 720 Modes:
* HD720p50 'hp50'
* HD720p5994 'hp59'
* HD720p60 'hp60'
2k Modes
* 2k2398 '2k23'
* 2k24 '2k24'
* 2k25 '2k25'
4k Modes
* 4K2160p2398 '4k23'
* 4K2160p24 '4k24'
* 4K2160p25 '4k25'
* 4K2160p2997 '4k29'
* 4K2160p30 '4k30'
* 4K2160p50 '4k50'
* 4K2160p5994 '4k59'
* 4K2160p60 '4k60'
Most of names are self explanatory. If necessary refer to the DeckLink API documentation for more information.
Similarly, <pixelFormat> is copied from the BMDPixelFormat enum.
Here is for reference the full list of supported pixel format and their equivalent internal code:
* 8BitYUV '2vuy'
* 10BitYUV 'v210'
* 8BitARGB * no equivalent code *
* 8BitBGRA 'BGRA'
* 10BitRGB 'r210'
* 12BitRGB 'R12B'
* 12BitRGBLE 'R12L'
* 10BitRGBXLE 'R10l'
* 10BitRGBX 'R10b'
Refer to the DeckLink SDK documentation for a full description of these pixel format.
It is important to understand them as the decoding of the pixels is NOT done in VideoTexture
for performance reason. Instead a specific shader must be used to decode the pixel in the GPU.
Only the '8BitARGB', '8BitBGRA' and '10BitRGBXLE' pixel formats are mapped directly to OpenGL RGB float textures.
The '8BitYUV' and '10BitYUV' pixel formats are mapped to openGL RGB float texture but require a shader to decode.
The other pixel formats are sent as a 'GL_RED_INTEGER' texture (i.e. a texture with only the
red channel coded as an unsigned 32 bit integer) and are not recommended for use.
Example: “HD1080p24/10BitYUV/3D:4” is equivalent to “24ps/v210/3D:4” and represents a full HD stereo feed at 24 frame per second and 4 frames cache size.
Although video format auto detection is possible with certain DeckLink devices, the corresponding
API is NOT implemented in the BGE. Therefore it is important to specify the format string that
matches exactly the video feed. If the format is wrong, no frame will be captured.
It should be noted that the pixel format that you need to specify is not necessarily the actual
format in the video feed. For example, the 4K Extreme card delivers 8bit RGBs pixels in the
'10BitRGBXLE' format. Use the 'Media Express' application included in 'Desktop Video' to discover
which pixel format works for a particular video stream.
.. attribute:: status
Status of the capture: 1=ready to use, 2=capturing, 3=stopped
:type: int
.. attribute:: framerate
Capture frame rate as computed from the video format.
:type: float
.. attribute:: valid
Tells if the image attribute can be used to retrieve the image.
Always False in this implementation (the image is not available at python level)
:type: bool
.. attribute:: image
The image data. Always None in this implementation.
:type: :class:`~bgl.Buffer` or None
.. attribute:: size
The size of the frame in pixel.
Stereo frames have double the height of the video frame, i.e. 3D is delivered to the GPU
as a single image in top-bottom order, left eye on top.
:type: (int,int)
.. attribute:: scale
Not used in this object.
:type: bool
.. attribute:: flip
Not used in this object.
:type: bool
.. attribute:: filter
Not used in this object.
.. method:: play()
Kick-off the capture after creation of the object.
:return: True if the capture could be started, False otherwise.
:rtype: bool
.. method:: pause()
Temporary stops the capture. Use play() to restart it.
:return: True if the capture could be paused, False otherwise.
:rtype: bool
.. method:: stop()
Stops the capture.
:return: True if the capture could be stopped, False otherwise.
:rtype: bool
***************
Texture classes
***************
@@ -782,6 +997,7 @@ Texture classes
:type: one of...
* :class:`VideoFFmpeg`
* :class:`VideoDeckLink`
* :class:`ImageFFmpeg`
* :class:`ImageBuff`
* :class:`ImageMirror`
@@ -789,7 +1005,125 @@ Texture classes
* :class:`ImageRender`
* :class:`ImageViewport`
.. class:: DeckLink(cardIdx=0, format="")
Certain DeckLink devices can be used to playback video: the host sends video frames regularly
for immediate or scheduled playback. The video feed is outputted on HDMI or SDI interfaces.
This class supports the immediate playback mode: it has a source attribute that is assigned
one of the source object in the bge.texture module. Refreshing the DeckLink object causes
the image source to be computed and sent to the DeckLink device for immediate transmission
on the output interfaces. Keying is supported: it allows to composite the frame with an
input video feed that transits through the DeckLink card.
:arg cardIdx: Number of the card to be used for output (0=first card). It should be noted that DeckLink devices are usually half duplex: they can either be used for capture or playback but not both at the same time.
:type cardIdx: int
:arg format: String representing the display mode of the output feed.
:type format: str
The default value of the format argument is reserved for auto detection but it is currently
not supported (it will generate a runtime error) and thus the video format must be explicitly
specified. If keying is the goal (see keying attributes), the format must match exactly the
input video feed, otherwise it can be any format supported by the device (there will be a
runtime error if not).
The format of the string is “<displayMode>[/3D]”.
Refer to :class:`VideoDeckLink` to get the list of acceptable <displayMode>.
The optional “/3D” suffix is used to create a stereo 3D feed. In that case the 'right' attribute
must also be set to specify the image source for the right eye.
Note: The pixel format is not specified here because it is always BGRA. The alpha channel is
used in keying to mix the source with the input video feed, otherwise it is not used.
If a conversion is needed to match the native video format, it is done inside the DeckLink driver
or device.
.. attribute:: source
This attribute must be set to one of the image source. If the image size does not fit exactly
the frame size, the extend attribute determines what to do.
For best performance, the source image should match exactly the size of the output frame.
A further optimization is achieved if the image source object is ImageViewport or ImageRender
set for whole viewport, flip disabled and no filter: the GL frame buffer is copied directly
to the image buffer and directly from there to the DeckLink card (hence no buffer to buffer
copy inside VideoTexture).
:type: one of...
* :class:`VideoFFmpeg`
* :class:`VideoDeckLink`
* :class:`ImageFFmpeg`
* :class:`ImageBuff`
* :class:`ImageMirror`
* :class:`ImageMix`
* :class:`ImageRender`
* :class:`ImageViewport`
.. attribute:: right
If the video format is stereo 3D, this attribute should be set to an image source object
that will produce the right eye images. If the goal is to render the BGE scene in 3D,
it can be achieved with 2 cameras, one for each eye, used by 2 ImageRender with an offscreen
render buffer that is just the size of the video frame.
:type: one of...
* :class:`VideoFFmpeg`
* :class:`VideoDeckLink`
* :class:`ImageFFmpeg`
* :class:`ImageBuff`
* :class:`ImageMirror`
* :class:`ImageMix`
* :class:`ImageRender`
* :class:`ImageViewport`
.. attribute:: keying
Specify if keying is enabled. False (default): the output frame is sent unmodified on
the output interface (in that case no input video is required). True: the output frame
is mixed with the input video, using the alpha channel to blend the two images and the
combination is sent on the output interface.
:type: bool
.. attribute:: level
If keying is enabled, sets the keying level from 0 to 255. This value is a global alpha value
that multiplies the alpha channel of the image source. Use 255 (the default) to keep the alpha
channel unmodified, 0 to make the output frame totally transparent.
:type: int
.. attribute:: extend
Determines how the image source should be mapped if the size does not fit the video frame size.
* False (the default): map the image pixel by pixel.
If the image size is smaller than the frame size, extra space around the image is filled with
0-alpha black. If it is larger, the image is cropped to fit the frame size.
* True: the image is scaled by the nearest neighbor algorithm to fit the frame size.
The scaling is fast but poor quality. For best results, always adjust the image source to
match the size of the output video.
:type: bool
.. method:: close()
Close the DeckLink device and release all resources. After calling this method,
the object cannot be reactivated, it must be destroyed and a new DeckLink object
created from fresh to restart the output.
.. method:: refresh(refresh_source,ts)
This method must be called frequently to update the output frame in the DeckLink device.
:arg refresh_source: True if the source objects image buffer should be invalidated after being
used to compute the output frame. This triggers the recomputing of the
source image on next refresh, which is normally the desired effect.
False if the image source buffer should stay valid and reused on next refresh.
Note that the DeckLink device stores the output frame and replays until a
new frame is sent from the host. Thus, it is not necessary to refresh the
DeckLink object if it is known that the image source has not changed.
:type refresh_source: bool
:arg ts: The timestamp value passed to the image source object to compute the image. If unspecified, the BGE clock is used.
:type ts: float
**************
Filter classes
**************

View File

@@ -214,6 +214,16 @@ base class --- :class:`PyObjectPlus`
:arg iList: a list (2, 3 or 4 elements) of integer values
:type iList: list[integer]
.. method:: setUniformEyef(name)
Set a uniform with a float value that reflects the eye being render in stereo mode:
0.0 for the left eye, 0.5 for the right eye. In non stereo mode, the value of the uniform
is fixed to 0.0. The typical use of this uniform is in stereo mode to sample stereo textures
containing the left and right eye images in a top-bottom order.
:arg name: the uniform name
:type name: string
.. method:: validate()
Validate the shader object.

View File

@@ -60,37 +60,37 @@ base class --- :class:`KX_GameObject`
:type: float (read only)
..attribute:: shadowFrustumSize
.. attribute:: shadowFrustumSize
Size of the frustum used for creating the shadowmap.
:type: float (read only)
..attribute:: shadowBindId
.. attribute:: shadowBindId
The OpenGL shadow texture bind number/id.
:type: int (read only)
..attribute:: shadowMapType
.. attribute:: shadowMapType
The shadow shadow map type (0 -> Simple; 1 -> Variance)
:type: int (read only)
..attribute:: shadowBias
.. attribute:: shadowBias
The shadow buffer sampling bias.
:type: float (read only)
..attribute:: shadowBleedBias
.. attribute:: shadowBleedBias
The bias for reducing light-bleed on variance shadow maps.
:type: float (read only)
..attribute:: useShadow
.. attribute:: useShadow
Returns True if the light has Shadow option activated, else returns False.

View File

@@ -33,10 +33,10 @@ SSH_UPLOAD="/data/www/vhosts/www.blender.org/api" # blender_python_api_VERSION,
# "_".join(str(v) for v in bpy.app.version)
# custom blender vars
blender_srcdir=$(dirname -- $0)/../..
blender_version=$(grep "BLENDER_VERSION\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender.h" | awk '{print $3}')
blender_version_char=$(grep "BLENDER_VERSION_CHAR\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender.h" | awk '{print $3}')
blender_version_cycle=$(grep "BLENDER_VERSION_CYCLE\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender.h" | awk '{print $3}')
blender_subversion=$(grep "BLENDER_SUBVERSION\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender.h" | awk '{print $3}')
blender_version=$(grep "BLENDER_VERSION\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender_version.h" | awk '{print $3}')
blender_version_char=$(grep "BLENDER_VERSION_CHAR\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender_version.h" | awk '{print $3}')
blender_version_cycle=$(grep "BLENDER_VERSION_CYCLE\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender_version.h" | awk '{print $3}')
blender_subversion=$(grep "BLENDER_SUBVERSION\s" "$blender_srcdir/source/blender/blenkernel/BKE_blender_version.h" | awk '{print $3}')
if [ "$blender_version_cycle" = "release" ] ; then
BLENDER_VERSION=$(expr $blender_version / 100)_$(expr $blender_version % 100)$blender_version_char"_release"
@@ -61,7 +61,7 @@ if $DO_EXE_BLENDER ; then
--python-exit-code 1 \
--python $SPHINXBASE/sphinx_doc_gen.py
if (($? == 1)) ; then
if (($? != 0)) ; then
echo "Generating documentation failed, aborting"
exit 1
fi

View File

@@ -23,6 +23,9 @@
#
# ***** END GPL LICENSE BLOCK *****
# Libs that adhere to strict flags
add_subdirectory(curve_fit_nd)
# Otherwise we get warnings here that we cant fix in external projects
remove_strict_flags()

6
extern/Eigen3/README.blender vendored Normal file
View File

@@ -0,0 +1,6 @@
Project: Eigen, template library for linear algebra: matrices, vectors, numerical solvers, and related algorithms
URL: http://eigen.tuxfamily.org/index.php?title=Main_Page
License: GPLv3+
Upstream version: 3.2.7
Local modifications:
- OpenMP fix for MSVC2015, see http://eigen.tuxfamily.org/bz/show_bug.cgi?id=1131

6
extern/binreloc/README.blender vendored Normal file
View File

@@ -0,0 +1,6 @@
Project: AutoPackage
URL: http://autopackage.org/docs/binreloc (original, defunct)
http://alien.cern.ch/cache/autopackage-1.0/site/docs/binreloc/ (cache)
License: Public Domain
Upstream version: Unknown (Last Release)
Local modifications: None

View File

@@ -233,3 +233,92 @@ index e05bdcc..dbcf2b6 100644
#include "btVector3.h"
diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp
index e0e8bc7..a788268 100644
--- a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp
+++ b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp
@@ -425,50 +425,38 @@ void btRigidBody::setCenterOfMassTransform(const btTransform& xform)
}
+bool btRigidBody::checkCollideWithOverride(const btCollisionObject* co) const
+{
+ const btRigidBody* otherRb = btRigidBody::upcast(co);
+ if (!otherRb)
+ return true;
+
+ for (int i = 0; i < m_constraintRefs.size(); ++i)
+ {
+ const btTypedConstraint* c = m_constraintRefs[i];
+ if (c->isEnabled())
+ if (&c->getRigidBodyA() == otherRb || &c->getRigidBodyB() == otherRb)
+ return false;
+ }
+
+ return true;
+}
void btRigidBody::addConstraintRef(btTypedConstraint* c)
{
- ///disable collision with the 'other' body
-
int index = m_constraintRefs.findLinearSearch(c);
- //don't add constraints that are already referenced
- //btAssert(index == m_constraintRefs.size());
if (index == m_constraintRefs.size())
- {
- m_constraintRefs.push_back(c);
- btCollisionObject* colObjA = &c->getRigidBodyA();
- btCollisionObject* colObjB = &c->getRigidBodyB();
- if (colObjA == this)
- {
- colObjA->setIgnoreCollisionCheck(colObjB, true);
- }
- else
- {
- colObjB->setIgnoreCollisionCheck(colObjA, true);
- }
- }
+ m_constraintRefs.push_back(c);
+
+ m_checkCollideWith = true;
}
void btRigidBody::removeConstraintRef(btTypedConstraint* c)
{
- int index = m_constraintRefs.findLinearSearch(c);
- //don't remove constraints that are not referenced
- if(index < m_constraintRefs.size())
- {
- m_constraintRefs.remove(c);
- btCollisionObject* colObjA = &c->getRigidBodyA();
- btCollisionObject* colObjB = &c->getRigidBodyB();
- if (colObjA == this)
- {
- colObjA->setIgnoreCollisionCheck(colObjB, false);
- }
- else
- {
- colObjB->setIgnoreCollisionCheck(colObjA, false);
- }
- }
+ m_constraintRefs.remove(c);
+ m_checkCollideWith = m_constraintRefs.size() > 0;
}
int btRigidBody::calculateSerializeBufferSize() const
diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h
index 1d177db..c2f8c5d 100644
--- a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h
+++ b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h
@@ -509,6 +509,8 @@ public:
return (getBroadphaseProxy() != 0);
}
+ virtual bool checkCollideWithOverride(const btCollisionObject* co) const;
+
void addConstraintRef(btTypedConstraint* c);
void removeConstraintRef(btTypedConstraint* c);

View File

@@ -425,50 +425,38 @@ void btRigidBody::setCenterOfMassTransform(const btTransform& xform)
}
bool btRigidBody::checkCollideWithOverride(const btCollisionObject* co) const
{
const btRigidBody* otherRb = btRigidBody::upcast(co);
if (!otherRb)
return true;
for (int i = 0; i < m_constraintRefs.size(); ++i)
{
const btTypedConstraint* c = m_constraintRefs[i];
if (c->isEnabled())
if (&c->getRigidBodyA() == otherRb || &c->getRigidBodyB() == otherRb)
return false;
}
return true;
}
void btRigidBody::addConstraintRef(btTypedConstraint* c)
{
///disable collision with the 'other' body
int index = m_constraintRefs.findLinearSearch(c);
//don't add constraints that are already referenced
//btAssert(index == m_constraintRefs.size());
if (index == m_constraintRefs.size())
{
m_constraintRefs.push_back(c);
btCollisionObject* colObjA = &c->getRigidBodyA();
btCollisionObject* colObjB = &c->getRigidBodyB();
if (colObjA == this)
{
colObjA->setIgnoreCollisionCheck(colObjB, true);
}
else
{
colObjB->setIgnoreCollisionCheck(colObjA, true);
}
}
m_constraintRefs.push_back(c);
m_checkCollideWith = true;
}
void btRigidBody::removeConstraintRef(btTypedConstraint* c)
{
int index = m_constraintRefs.findLinearSearch(c);
//don't remove constraints that are not referenced
if(index < m_constraintRefs.size())
{
m_constraintRefs.remove(c);
btCollisionObject* colObjA = &c->getRigidBodyA();
btCollisionObject* colObjB = &c->getRigidBodyB();
if (colObjA == this)
{
colObjA->setIgnoreCollisionCheck(colObjB, false);
}
else
{
colObjB->setIgnoreCollisionCheck(colObjA, false);
}
}
m_constraintRefs.remove(c);
m_checkCollideWith = m_constraintRefs.size() > 0;
}
int btRigidBody::calculateSerializeBufferSize() const

View File

@@ -509,6 +509,8 @@ public:
return (getBroadphaseProxy() != 0);
}
virtual bool checkCollideWithOverride(const btCollisionObject* co) const;
void addConstraintRef(btTypedConstraint* c);
void removeConstraintRef(btTypedConstraint* c);

View File

@@ -51,6 +51,7 @@ namespace {
bottom_out = -displacement.cross(top_out) + rotation_matrix * bottom_in;
}
/*
void InverseSpatialTransform(const btMatrix3x3 &rotation_matrix,
const btVector3 &displacement,
const btVector3 &top_in,
@@ -80,6 +81,7 @@ namespace {
top_out = a_top.cross(b_top);
bottom_out = a_bottom.cross(b_top) + a_top.cross(b_bottom);
}
*/
}

View File

@@ -1127,6 +1127,7 @@ int nattrb=0;
int hasbounds=0;
int result = sscanf(node,"%d %d %d %d",&nnode,&ndims,&nattrb,&hasbounds);
result = sscanf(node,"%d %d %d %d",&nnode,&ndims,&nattrb,&hasbounds);
(void)result;
node += nextLine(node);
pos.resize(nnode);
@@ -1208,10 +1209,10 @@ if(ele&&ele[0])
}
}
}
printf("Nodes: %u\r\n",psb->m_nodes.size());
printf("Links: %u\r\n",psb->m_links.size());
printf("Faces: %u\r\n",psb->m_faces.size());
printf("Tetras: %u\r\n",psb->m_tetras.size());
printf("Nodes: %d\r\n",psb->m_nodes.size());
printf("Links: %d\r\n",psb->m_links.size());
printf("Faces: %d\r\n",psb->m_faces.size());
printf("Tetras: %d\r\n",psb->m_tetras.size());
return(psb);
}

View File

@@ -422,7 +422,7 @@ static inline btVector3 BaryCoord( const btVector3& a,
}
//
static btScalar ImplicitSolve( btSoftBody::ImplicitFn* fn,
static inline btScalar ImplicitSolve( btSoftBody::ImplicitFn* fn,
const btVector3& a,
const btVector3& b,
const btScalar accuracy,
@@ -504,7 +504,7 @@ static inline btScalar VolumeOf( const btVector3& x0,
}
//
static void EvaluateMedium( const btSoftBodyWorldInfo* wfi,
static inline void EvaluateMedium( const btSoftBodyWorldInfo* wfi,
const btVector3& x,
btSoftBody::sMedium& medium)
{

4
extern/carve/README.blender vendored Normal file
View File

@@ -0,0 +1,4 @@
Project: Carve, CSG library
URL: https://code.google.com/archive/p/carve/
Upstream version 9a85d733a43d
Local modifications: See patches/ folder

View File

@@ -157,6 +157,7 @@ namespace carve {
return pointInPoly(points, p2_adapt_ident(), p);
}
#if 0
static int lineSegmentPolyIntersections(const P2Vector &points,
LineSegment2 line,
std::vector<PolyIntersectionInfo> &out) {
@@ -224,6 +225,7 @@ namespace carve {
}
return count;
}
#endif
struct FwdSort {
bool operator()(const PolyIntersectionInfo &a,
@@ -239,6 +241,7 @@ namespace carve {
}
};
#if 0
static int sortedLineSegmentPolyIntersections(const P2Vector &points,
LineSegment2 line,
std::vector<PolyIntersectionInfo> &out) {
@@ -253,6 +256,7 @@ namespace carve {
}
return count;
}
#endif
bool pickContainedPoint(const std::vector<P2> &poly, P2 &result) {
return pickContainedPoint(poly, p2_adapt_ident(), result);

View File

@@ -28,6 +28,7 @@ namespace carve {
namespace geom3d {
namespace {
#if 0
int is_same(const std::vector<const Vector *> &a,
const std::vector<const Vector *> &b) {
if (a.size() != b.size()) return false;
@@ -52,6 +53,7 @@ not_fwd:
not_rev:
return 0;
}
#endif
}
bool planeIntersection(const Plane &a, const Plane &b, Ray &r) {

View File

@@ -236,6 +236,7 @@ namespace {
#if 0
void dump_intersections(std::ostream &out, carve::csg::Intersections &csg_intersections) {
std::vector<dump_data> temp;
@@ -284,13 +285,14 @@ namespace {
vertices.push_back(i_pt->v);
}
}
#endif
carve::point::PointSet points(vertices);
std::string outf("/tmp/intersection-points.ply");
::writePLY(outf, &points, true);
#endif
}
#endif
@@ -481,6 +483,7 @@ void carve::csg::CSG::makeVertexIntersections() {
#if 0
static carve::mesh::MeshSet<3>::vertex_t *chooseWeldPoint(
const carve::csg::detail::VSet &equivalent,
carve::csg::VertexPool &vertex_pool) {
@@ -537,7 +540,7 @@ static const carve::mesh::MeshSet<3>::vertex_t *weld(
}
return weld_point;
}
#endif
void carve::csg::CSG::groupIntersections() {
@@ -1219,6 +1222,7 @@ void carve::csg::CSG::makeFaceEdges(carve::csg::EdgeClassification &eclass,
*
* @param fll
*/
#if 0
static void checkFaceLoopIntegrity(carve::csg::FaceLoopList &fll) {
static carve::TimingName FUNC_NAME("CSG::checkFaceLoopIntegrity()");
carve::TimingBlock block(FUNC_NAME);
@@ -1245,7 +1249,7 @@ static void checkFaceLoopIntegrity(carve::csg::FaceLoopList &fll) {
}
}
}
#endif
/**

View File

@@ -139,6 +139,7 @@ namespace carve {
#if 0
static void walkGraphSegment(carve::csg::detail::VVSMap &shared_edge_graph,
const carve::csg::detail::VSet &branch_points,
V2 initial,
@@ -215,7 +216,7 @@ namespace carve {
#endif
#endif
}
#endif
static carve::geom3d::Vector perpendicular(const carve::geom3d::Vector &v) {
@@ -383,6 +384,7 @@ namespace carve {
#if 0
static void traceIntersectionGraph(const V2Set &shared_edges,
const FLGroupList & /* a_loops_grouped */,
const FLGroupList & /* b_loops_grouped */,
@@ -416,6 +418,7 @@ namespace carve {
walkGraphSegment(shared_edge_graph, branch_points, V2(v1, v2), a_edge_map, b_edge_map, out);
}
}
#endif
void hashByPerimeter(FLGroupList &grp, PerimMap &perim_map) {
for (FLGroupList::iterator i = grp.begin(); i != grp.end(); ++i) {

View File

@@ -1409,6 +1409,7 @@ namespace {
return s.str().substr(1);
}
#if 0
void dumpAsGraph(carve::mesh::MeshSet<3>::face_t *face,
const std::vector<carve::mesh::MeshSet<3>::vertex_t *> &base_loop,
const carve::csg::V2Set &face_edges,
@@ -1450,6 +1451,7 @@ namespace {
}
std::cerr << "};\n";
}
#endif
void generateOneFaceLoop(carve::mesh::MeshSet<3>::face_t *face,
const carve::csg::detail::Data &data,

View File

@@ -43,6 +43,7 @@ namespace carve {
};
namespace {
#if 0
void cplx_sqrt(double re, double im,
double &re_1, double &im_1,
double &re_2, double &im_2) {
@@ -57,7 +58,9 @@ namespace carve {
im_2 = -im_1;
}
}
#endif
#if 0
void cplx_cbrt(double re, double im,
double &re_1, double &im_1,
double &re_2, double &im_2,
@@ -76,6 +79,7 @@ namespace carve {
im_3 = r * sin(t + M_TWOPI * 2.0 / 3.0);
}
}
#endif
void add_root(std::vector<Root> &roots, double root) {
for (size_t i = 0; i < roots.size(); ++i) {
@@ -250,6 +254,7 @@ namespace carve {
e2.normalize();
}
#if 0
static void eig3(const Matrix3 &m,
double l,
carve::geom::vector<3> &e1,
@@ -259,6 +264,7 @@ namespace carve {
e2.x = 0.0; e2.y = 1.0; e2.z = 0.0;
e3.x = 0.0; e3.y = 0.0; e3.z = 1.0;
}
#endif
void eigSolveSymmetric(const Matrix3 &m,
double &l1, carve::geom::vector<3> &e1,

View File

@@ -774,7 +774,6 @@ namespace carve {
// connectivity information in the Polyhedron.
mesh::MeshSet<3> *meshFromPolyhedron(const poly::Polyhedron *poly, int manifold_id) {
typedef mesh::Vertex<3> vertex_t;
typedef mesh::Vertex<3>::vector_t vector_t;
typedef mesh::Edge<3> edge_t;
typedef mesh::Face<3> face_t;
typedef mesh::Mesh<3> mesh_t;
@@ -884,7 +883,6 @@ namespace carve {
// construct a Polyhedron from a MeshSet
poly::Polyhedron *polyhedronFromMesh(const mesh::MeshSet<3> *mesh, int manifold_id) {
typedef poly::Polyhedron poly_t;
typedef poly::Polyhedron::vertex_t vertex_t;
typedef poly::Polyhedron::edge_t edge_t;
typedef poly::Polyhedron::face_t face_t;

4
extern/ceres/README.blender vendored Normal file
View File

@@ -0,0 +1,4 @@
Project: Ceres Solver
URL: http://ceres-solver.org/
Upstream version 1.11 (aef9c9563b08d5f39eee1576af133a84749d1b48)
Local modifications: None

5
extern/clew/README.blender vendored Normal file
View File

@@ -0,0 +1,5 @@
Project: OpenCL Wrangler
URL: https://github.com/OpenCLWrangler/clew
License: Apache 2.0
Upstream version: 277db43
Local modifications: None

View File

@@ -33,8 +33,9 @@ set(INC_SYS
)
set(SRC
include/cuew.h
src/cuew.c
include/cuew.h
)
blender_add_lib(extern_cuew "${SRC}" "${INC}" "${INC_SYS}")

5
extern/cuew/README.blender vendored Normal file
View File

@@ -0,0 +1,5 @@
Project: Cuda Wrangler
URL: https://github.com/CudaWrangler/cuew
License: Apache 2.0
Upstream version: e2e0315
Local modifications: None

View File

@@ -1,35 +0,0 @@
CUDA_ERRORS={
'CUDA_SUCCESS': "No errors",
'CUDA_ERROR_INVALID_VALUE': "Invalid value",
'CUDA_ERROR_OUT_OF_MEMORY': "Out of memory",
'CUDA_ERROR_NOT_INITIALIZED': "Driver not initialized",
'CUDA_ERROR_DEINITIALIZED': "Driver deinitialized",
'CUDA_ERROR_NO_DEVICE': "No CUDA-capable device available",
'CUDA_ERROR_INVALID_DEVICE': "Invalid device",
'CUDA_ERROR_INVALID_IMAGE': "Invalid kernel image",
'CUDA_ERROR_INVALID_CONTEXT': "Invalid context",
'CUDA_ERROR_CONTEXT_ALREADY_CURRENT': "Context already current",
'CUDA_ERROR_MAP_FAILED': "Map failed",
'CUDA_ERROR_UNMAP_FAILED': "Unmap failed",
'CUDA_ERROR_ARRAY_IS_MAPPED': "Array is mapped",
'CUDA_ERROR_ALREADY_MAPPED': "Already mapped",
'CUDA_ERROR_NO_BINARY_FOR_GPU': "No binary for GPU",
'CUDA_ERROR_ALREADY_ACQUIRED': "Already acquired",
'CUDA_ERROR_NOT_MAPPED': "Not mapped",
'CUDA_ERROR_NOT_MAPPED_AS_ARRAY': "Mapped resource not available for access as an array",
'CUDA_ERROR_NOT_MAPPED_AS_POINTER': "Mapped resource not available for access as a pointer",
'CUDA_ERROR_ECC_UNCORRECTABLE': "Uncorrectable ECC error detected",
'CUDA_ERROR_UNSUPPORTED_LIMIT': "CUlimit not supported by device",
'CUDA_ERROR_INVALID_SOURCE': "Invalid source",
'CUDA_ERROR_FILE_NOT_FOUND': "File not found",
'CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND': "Link to a shared object failed to resolve",
'CUDA_ERROR_SHARED_OBJECT_INIT_FAILED': "Shared object initialization failed",
'CUDA_ERROR_INVALID_HANDLE': "Invalid handle",
'CUDA_ERROR_NOT_FOUND': "Not found",
'CUDA_ERROR_NOT_READY': "CUDA not ready",
'CUDA_ERROR_LAUNCH_FAILED': "Launch failed",
'CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES': "Launch exceeded resources",
'CUDA_ERROR_LAUNCH_TIMEOUT': "Launch exceeded timeout",
'CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING': "Launch with incompatible texturing",
'CUDA_ERROR_UNKNOWN': "Unknown error",
}

View File

@@ -1,125 +0,0 @@
extra_code = """
static void path_join(const char *path1,
const char *path2,
int maxlen,
char *result) {
#if defined(WIN32) || defined(_WIN32)
const char separator = '\\\\';
#else
const char separator = '/';
#endif
int n = snprintf(result, maxlen, "%s%c%s", path1, separator, path2);
if (n != -1 && n < maxlen) {
result[n] = '\\0';
}
else {
result[maxlen - 1] = '\\0';
}
}
static int path_exists(const char *path) {
struct stat st;
if (stat(path, &st)) {
return 0;
}
return 1;
}
const char *cuewCompilerPath(void) {
#ifdef _WIN32
const char *defaultpaths[] = {"C:/CUDA/bin", NULL};
const char *executable = "nvcc.exe";
#else
const char *defaultpaths[] = {
"/Developer/NVIDIA/CUDA-5.0/bin",
"/usr/local/cuda-5.0/bin",
"/usr/local/cuda/bin",
"/Developer/NVIDIA/CUDA-6.0/bin",
"/usr/local/cuda-6.0/bin",
"/Developer/NVIDIA/CUDA-5.5/bin",
"/usr/local/cuda-5.5/bin",
NULL};
const char *executable = "nvcc";
#endif
int i;
const char *binpath = getenv("CUDA_BIN_PATH");
static char nvcc[65536];
if (binpath) {
path_join(binpath, executable, sizeof(nvcc), nvcc);
if (path_exists(nvcc))
return nvcc;
}
for (i = 0; defaultpaths[i]; ++i) {
path_join(defaultpaths[i], executable, sizeof(nvcc), nvcc);
if (path_exists(nvcc))
return nvcc;
}
#ifndef _WIN32
{
FILE *handle = popen("which nvcc", "r");
if (handle) {
char buffer[4096] = {0};
int len = fread(buffer, 1, sizeof(buffer) - 1, handle);
buffer[len] = '\\0';
pclose(handle);
if (buffer[0])
return "nvcc";
}
}
#endif
return NULL;
}
int cuewCompilerVersion(void) {
const char *path = cuewCompilerPath();
const char *marker = "Cuda compilation tools, release ";
FILE *pipe;
int major, minor;
char *versionstr;
char buf[128];
char output[65536] = "\\0";
char command[65536] = "\\0";
if (path == NULL)
return 0;
/* get --version output */
strncpy(command, path, sizeof(command));
strncat(command, " --version", sizeof(command) - strlen(path));
pipe = popen(command, "r");
if (!pipe) {
fprintf(stderr, "CUDA: failed to run compiler to retrieve version");
return 0;
}
while (!feof(pipe)) {
if (fgets(buf, sizeof(buf), pipe) != NULL) {
strncat(output, buf, sizeof(output) - strlen(output) - 1);
}
}
pclose(pipe);
/* parse version number */
versionstr = strstr(output, marker);
if (versionstr == NULL) {
fprintf(stderr, "CUDA: failed to find version number in:\\n\\n%s\\n", output);
return 0;
}
versionstr += strlen(marker);
if (sscanf(versionstr, "%d.%d", &major, &minor) < 2) {
fprintf(stderr, "CUDA: failed to parse version number from:\\n\\n%s\\n", output);
return 0;
}
return 10 * major + minor;
}
"""

View File

@@ -1,640 +0,0 @@
#!/usr/bin/env python3
#
# Copyright 2014 Blender Foundation
#
# Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License
# This script generates either header or implementation file from
# a CUDA header files.
#
# Usage: cuew hdr|impl [/path/to/cuda/includes]
# - hdr means header file will be generated and printed to stdout.
# - impl means implementation file will be generated and printed to stdout.
# - /path/to/cuda/includes is a path to a folder with cuda.h and cudaGL.h
# for which wrangler will be generated.
import os
import sys
from cuda_errors import CUDA_ERRORS
from pycparser import c_parser, c_ast, parse_file
from subprocess import Popen, PIPE
INCLUDE_DIR = "/usr/include"
LIB = "CUEW"
REAL_LIB = "CUDA"
VERSION_MAJOR = "1"
VERSION_MINOR = "2"
COPYRIGHT = """/*
* Copyright 2011-2014 Blender Foundation
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/"""
FILES = ["cuda.h", "cudaGL.h", 'nvrtc.h']
TYPEDEFS = []
FUNC_TYPEDEFS = []
SYMBOLS = []
DEFINES = []
DEFINES_V2 = []
ERRORS = []
class FuncDefVisitor(c_ast.NodeVisitor):
indent = 0
prev_complex = False
dummy_typedefs = ['size_t', 'CUdeviceptr']
def _get_quals_string(self, node):
if node.quals:
return ' '.join(node.quals) + ' '
return ''
def _get_ident_type(self, node):
if isinstance(node, c_ast.PtrDecl):
return self._get_ident_type(node.type.type) + '*'
if isinstance(node, c_ast.ArrayDecl):
return self._get_ident_type(node.type)
elif isinstance(node, c_ast.Struct):
if node.name:
return 'struct ' + node.name
else:
self.indent += 1
struct = self._stringify_struct(node)
self.indent -= 1
return "struct {\n" + \
struct + (" " * self.indent) + "}"
elif isinstance(node, c_ast.Union):
self.indent += 1
union = self._stringify_struct(node)
self.indent -= 1
return "union {\n" + union + (" " * self.indent) + "}"
elif isinstance(node, c_ast.Enum):
if node.name is not None:
return 'enum ' + node.name
else:
return 'enum '
elif isinstance(node, c_ast.TypeDecl):
return self._get_ident_type(node.type)
else:
return node.names[0]
def _stringify_param(self, param):
param_type = param.type
result = self._get_quals_string(param)
result += self._get_ident_type(param_type)
if param.name:
result += ' ' + param.name
if isinstance(param_type, c_ast.ArrayDecl):
# TODO(sergey): Workaround to deal with the
# preprocessed file where array size got
# substituded.
dim = param_type.dim.value
if param.name == "reserved" and dim == "64":
dim = "CU_IPC_HANDLE_SIZE"
result += '[' + dim + ']'
return result
def _stringify_params(self, params):
result = []
for param in params:
result.append(self._stringify_param(param))
return ', '.join(result)
def _stringify_struct(self, node):
result = ""
children = node.children()
for child in children:
member = self._stringify_param(child[1])
result += (" " * self.indent) + member + ";\n"
return result
def _stringify_enum(self, node):
result = ""
children = node.children()
for child in children:
if isinstance(child[1], c_ast.EnumeratorList):
enumerators = child[1].enumerators
for enumerator in enumerators:
result += (" " * self.indent) + enumerator.name
if enumerator.value:
result += " = " + enumerator.value.value
result += ",\n"
if enumerator.name.startswith("CUDA_ERROR_"):
ERRORS.append(enumerator.name)
return result
def visit_Decl(self, node):
if node.type.__class__.__name__ == 'FuncDecl':
if isinstance(node.type, c_ast.FuncDecl):
func_decl = node.type
func_decl_type = func_decl.type
typedef = 'typedef '
symbol_name = None
if isinstance(func_decl_type, c_ast.TypeDecl):
symbol_name = func_decl_type.declname
typedef += self._get_quals_string(func_decl_type)
typedef += self._get_ident_type(func_decl_type.type)
typedef += ' CUDAAPI'
typedef += ' t' + symbol_name
elif isinstance(func_decl_type, c_ast.PtrDecl):
ptr_type = func_decl_type.type
symbol_name = ptr_type.declname
typedef += self._get_quals_string(ptr_type)
typedef += self._get_ident_type(func_decl_type)
typedef += ' CUDAAPI'
typedef += ' t' + symbol_name
typedef += '(' + \
self._stringify_params(func_decl.args.params) + \
');'
SYMBOLS.append(symbol_name)
FUNC_TYPEDEFS.append(typedef)
def visit_Typedef(self, node):
if node.name in self.dummy_typedefs:
return
complex = False
type = self._get_ident_type(node.type)
quals = self._get_quals_string(node)
if isinstance(node.type.type, c_ast.Struct):
self.indent += 1
struct = self._stringify_struct(node.type.type)
self.indent -= 1
typedef = quals + type + " {\n" + struct + "} " + node.name
complex = True
elif isinstance(node.type.type, c_ast.Enum):
self.indent += 1
enum = self._stringify_enum(node.type.type)
self.indent -= 1
typedef = quals + type + " {\n" + enum + "} " + node.name
complex = True
else:
typedef = quals + type + " " + node.name
if complex or self.prev_complex:
typedef = "\ntypedef " + typedef + ";"
else:
typedef = "typedef " + typedef + ";"
TYPEDEFS.append(typedef)
self.prev_complex = complex
def get_latest_cpp():
path_prefix = "/usr/bin"
for cpp_version in ["9", "8", "7", "6", "5", "4"]:
test_cpp = os.path.join(path_prefix, "cpp-4." + cpp_version)
if os.path.exists(test_cpp):
return test_cpp
return None
def preprocess_file(filename, cpp_path):
args = [cpp_path, "-I./"]
if filename.endswith("GL.h"):
args.append("-DCUDAAPI= ")
args.append(filename)
try:
pipe = Popen(args,
stdout=PIPE,
universal_newlines=True)
text = pipe.communicate()[0]
except OSError as e:
raise RuntimeError("Unable to invoke 'cpp'. " +
'Make sure its path was passed correctly\n' +
('Original error: %s' % e))
return text
def parse_files():
parser = c_parser.CParser()
cpp_path = get_latest_cpp()
for filename in FILES:
filepath = os.path.join(INCLUDE_DIR, filename)
dummy_typedefs = {}
text = preprocess_file(filepath, cpp_path)
if filepath.endswith("GL.h"):
dummy_typedefs = {
"CUresult": "int",
"CUgraphicsResource": "void *",
"CUdevice": "void *",
"CUcontext": "void *",
"CUdeviceptr": "void *",
"CUstream": "void *"
}
text = "typedef int GLint;\n" + text
text = "typedef unsigned int GLuint;\n" + text
text = "typedef unsigned int GLenum;\n" + text
text = "typedef long size_t;\n" + text
for typedef in sorted(dummy_typedefs):
text = "typedef " + dummy_typedefs[typedef] + " " + \
typedef + ";\n" + text
ast = parser.parse(text, filepath)
with open(filepath) as f:
lines = f.readlines()
for line in lines:
if line.startswith("#define"):
line = line[8:-1]
token = line.split()
if token[0] not in ("__cuda_cuda_h__",
"CUDA_CB",
"CUDAAPI",
"CUDAGL_H",
"__NVRTC_H__"):
DEFINES.append(token)
for line in lines:
# TODO(sergey): Use better matching rule for _v2 symbols.
if line[0].isspace() and line.lstrip().startswith("#define"):
line = line[12:-1]
token = line.split()
if len(token) == 2 and (token[1].endswith("_v2") or
token[1].endswith("_v2)")):
if token[1].startswith('__CUDA_API_PTDS') or \
token[1].startswith('__CUDA_API_PTSZ'):
token[1] = token[1][16:-1]
DEFINES_V2.append(token)
v = FuncDefVisitor()
for typedef in dummy_typedefs:
v.dummy_typedefs.append(typedef)
v.visit(ast)
FUNC_TYPEDEFS.append('')
SYMBOLS.append('')
def print_copyright():
print(COPYRIGHT)
print("")
def open_header_guard():
print("#ifndef __%s_H__" % (LIB))
print("#define __%s_H__" % (LIB))
print("")
print("#ifdef __cplusplus")
print("extern \"C\" {")
print("#endif")
print("")
def close_header_guard():
print("")
print("#ifdef __cplusplus")
print("}")
print("#endif")
print("")
print("#endif /* __%s_H__ */" % (LIB))
def print_header():
print_copyright()
open_header_guard()
# Fot size_t.
print("#include <stdlib.h>")
print("")
print("/* Defines. */")
print("#define %s_VERSION_MAJOR %s" % (LIB, VERSION_MAJOR))
print("#define %s_VERSION_MINOR %s" % (LIB, VERSION_MINOR))
print("")
for define in DEFINES:
print('#define %s' % (' '.join(define)))
print("")
print("""/* Functions which changed 3.1 -> 3.2 for 64 bit stuff,
* the cuda library has both the old ones for compatibility and new
* ones with _v2 postfix,
*/""")
for define in DEFINES_V2:
print('#define %s' % (' '.join(define)))
print("")
print("/* Types. */")
# We handle this specially because of the file is
# getting preprocessed.
print("""#if defined(__x86_64) || defined(AMD64) || defined(_M_AMD64)
typedef unsigned long long CUdeviceptr;
#else
typedef unsigned int CUdeviceptr;
#endif
""")
for typedef in TYPEDEFS:
print('%s' % (typedef))
# TDO(sergey): This is only specific to CUDA wrapper.
print("""
#ifdef _WIN32
# define CUDAAPI __stdcall
# define CUDA_CB __stdcall
#else
# define CUDAAPI
# define CUDA_CB
#endif
""")
print("/* Function types. */")
for func_typedef in FUNC_TYPEDEFS:
print('%s' % (func_typedef))
print("")
print("/* Function declarations. */")
for symbol in SYMBOLS:
if symbol:
print('extern t%s *%s;' % (symbol, symbol))
else:
print("")
print("")
print("enum {")
print(" CUEW_SUCCESS = 0,")
print(" CUEW_ERROR_OPEN_FAILED = -1,")
print(" CUEW_ERROR_ATEXIT_FAILED = -2,")
print("};")
print("")
print("int %sInit(void);" % (LIB.lower()))
# TODO(sergey): Get rid of hardcoded CUresult.
print("const char *%sErrorString(CUresult result);" % (LIB.lower()))
print("const char *cuewCompilerPath(void);")
print("int cuewCompilerVersion(void);")
close_header_guard()
def print_dl_wrapper():
print("""#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# define VC_EXTRALEAN
# include <windows.h>
/* Utility macros. */
typedef HMODULE DynamicLibrary;
# define dynamic_library_open(path) LoadLibraryA(path)
# define dynamic_library_close(lib) FreeLibrary(lib)
# define dynamic_library_find(lib, symbol) GetProcAddress(lib, symbol)
#else
# include <dlfcn.h>
typedef void* DynamicLibrary;
# define dynamic_library_open(path) dlopen(path, RTLD_NOW)
# define dynamic_library_close(lib) dlclose(lib)
# define dynamic_library_find(lib, symbol) dlsym(lib, symbol)
#endif
""")
def print_dl_helper_macro():
print("""#define _LIBRARY_FIND_CHECKED(lib, name) \\
name = (t##name *)dynamic_library_find(lib, #name); \\
assert(name);
#define _LIBRARY_FIND(lib, name) \\
name = (t##name *)dynamic_library_find(lib, #name);
#define %s_LIBRARY_FIND_CHECKED(name) \\
_LIBRARY_FIND_CHECKED(cuda_lib, name)
#define %s_LIBRARY_FIND(name) _LIBRARY_FIND(cuda_lib, name)
#define NVRTC_LIBRARY_FIND_CHECKED(name) \\
_LIBRARY_FIND_CHECKED(nvrtc_lib, name)
#define NVRTC_LIBRARY_FIND(name) _LIBRARY_FIND(nvrtc_lib, name)
static DynamicLibrary cuda_lib;
static DynamicLibrary nvrtc_lib;""" % (REAL_LIB, REAL_LIB))
print("")
def print_dl_helpers():
print("""static DynamicLibrary dynamic_library_open_find(const char **paths) {
int i = 0;
while (paths[i] != NULL) {
DynamicLibrary lib = dynamic_library_open(paths[i]);
if (lib != NULL) {
return lib;
}
++i;
}
return NULL;
}
static void %sExit(void) {
if(cuda_lib != NULL) {
/* Ignore errors. */
dynamic_library_close(cuda_lib);
cuda_lib = NULL;
}
}""" % (LIB.lower()))
print("")
def print_lib_path():
# TODO(sergey): get rid of hardcoded libraries.
print("""#ifdef _WIN32
/* Expected in c:/windows/system or similar, no path needed. */
const char *cuda_paths[] = {"nvcuda.dll", NULL};
const char *nvrtc_paths[] = {"nvrtc.dll", NULL};
#elif defined(__APPLE__)
/* Default installation path. */
const char *cuda_paths[] = {"/usr/local/cuda/lib/libcuda.dylib", NULL};
const char *nvrtc_paths[] = {"/usr/local/cuda/lib/libnvrtc.dylib", NULL};
#else
const char *cuda_paths[] = {"libcuda.so", NULL};
const char *nvrtc_paths[] = {"libnvrtc.so",
# if defined(__x86_64__) || defined(_M_X64)
"/usr/local/cuda/lib64/libnvrtc.so",
#else
"/usr/local/cuda/lib/libnvrtc.so",
#endif
NULL};
#endif""")
def print_init_guard():
print(""" static int initialized = 0;
static int result = 0;
int error, driver_version;
if (initialized) {
return result;
}
initialized = 1;
error = atexit(cuewExit);
if (error) {
result = CUEW_ERROR_ATEXIT_FAILED;
return result;
}
/* Load library. */
cuda_lib = dynamic_library_open_find(cuda_paths);
nvrtc_lib = dynamic_library_open_find(nvrtc_paths);
/* CUDA library is mandatory to have, while nvrtc might be missing. */
if (cuda_lib == NULL) {
result = CUEW_ERROR_OPEN_FAILED;
return result;
}""")
print("")
def print_driver_version_guard():
# TODO(sergey): Currently it's hardcoded for CUDA only.
print(""" /* Detect driver version. */
driver_version = 1000;
%s_LIBRARY_FIND_CHECKED(cuDriverGetVersion);
if (cuDriverGetVersion) {
cuDriverGetVersion(&driver_version);
}
/* We require version 4.0. */
if (driver_version < 4000) {
result = CUEW_ERROR_OPEN_FAILED;
return result;
}""" % (REAL_LIB))
def print_dl_init():
print("int %sInit(void) {" % (LIB.lower()))
print(" /* Library paths. */")
print_lib_path()
print_init_guard()
print_driver_version_guard()
print(" /* Fetch all function pointers. */")
for symbol in SYMBOLS:
if symbol:
if not symbol.startswith('nvrtc'):
print(" %s_LIBRARY_FIND(%s);" % (REAL_LIB, symbol))
else:
print("")
print(" if (nvrtc_lib != NULL) {")
for symbol in SYMBOLS:
if symbol and symbol.startswith('nvrtc'):
print(" NVRTC_LIBRARY_FIND(%s);" % (symbol))
print(" }")
print("")
print(" result = CUEW_SUCCESS;")
print(" return result;")
print("}")
def print_implementation():
print_copyright()
# TODO(sergey): Get rid of hardcoded header.
print("""#ifdef _MSC_VER
# define snprintf _snprintf
# define popen _popen
# define pclose _pclose
# define _CRT_SECURE_NO_WARNINGS
#endif
""")
print("#include <cuew.h>")
print("#include <assert.h>")
print("#include <stdio.h>")
print("#include <string.h>")
print("#include <sys/stat.h>")
print("")
print_dl_wrapper()
print_dl_helper_macro()
print("/* Function definitions. */")
for symbol in SYMBOLS:
if symbol:
print('t%s *%s;' % (symbol, symbol))
else:
print("")
print("")
print_dl_helpers()
print("/* Implementation function. */")
print_dl_init()
print("")
# TODO(sergey): Get rid of hardcoded CUresult.
print("const char *%sErrorString(CUresult result) {" % (LIB.lower()))
print(" switch(result) {")
print(" case CUDA_SUCCESS: return \"No errors\";")
for error in ERRORS:
if error in CUDA_ERRORS:
str = CUDA_ERRORS[error]
else:
temp = error[11:].replace('_', ' ')
str = temp[0] + temp[1:].lower()
print(" case %s: return \"%s\";" % (error, str))
print(" default: return \"Unknown CUDA error value\";")
print(" }")
print("}")
from cuda_extra import extra_code
print(extra_code)
if __name__ == "__main__":
if len(sys.argv) != 2 and len(sys.argv) != 3:
print("Usage: %s hdr|impl [/path/to/cuda/toolkit/include]" %
(sys.argv[0]))
exit(1)
if len(sys.argv) == 3:
INCLUDE_DIR = sys.argv[2]
parse_files()
if sys.argv[1] == "hdr":
print_header()
elif sys.argv[1] == "impl":
print_implementation()
else:
print("Unknown command %s" % (sys.argv[1]))
exit(1)

View File

@@ -1,10 +0,0 @@
#!/bin/sh
# This script invokes cuew_gen.py and updates the
# header and source files in the repository.
SCRIPT=`realpath -s $0`
DIR=`dirname $SCRIPT`
python ${DIR}/cuew_gen.py hdr $@ > $DIR/../include/cuew.h
python ${DIR}/cuew_gen.py impl $@ > $DIR/../src/cuew.c

View File

@@ -1,3 +0,0 @@
/* This file is needed to workaround issue with parsing system headers. */
typedef long size_t;

View File

@@ -131,8 +131,8 @@ typedef struct CUsurfref_st* CUsurfref;
typedef struct CUevent_st* CUevent;
typedef struct CUstream_st* CUstream;
typedef struct CUgraphicsResource_st* CUgraphicsResource;
typedef unsigned CUtexObject;
typedef unsigned CUsurfObject;
typedef unsigned long long CUtexObject;
typedef unsigned long long CUsurfObject;
typedef struct CUuuid_st {
char bytes[16];
@@ -603,7 +603,7 @@ typedef struct CUDA_ARRAY_DESCRIPTOR_st {
size_t Width;
size_t Height;
CUarray_format Format;
unsigned NumChannels;
unsigned int NumChannels;
} CUDA_ARRAY_DESCRIPTOR;
typedef struct CUDA_ARRAY3D_DESCRIPTOR_st {
@@ -611,8 +611,8 @@ typedef struct CUDA_ARRAY3D_DESCRIPTOR_st {
size_t Height;
size_t Depth;
CUarray_format Format;
unsigned NumChannels;
unsigned Flags;
unsigned int NumChannels;
unsigned int Flags;
} CUDA_ARRAY3D_DESCRIPTOR;
typedef struct CUDA_RESOURCE_DESC_st {
@@ -627,13 +627,13 @@ typedef struct CUDA_RESOURCE_DESC_st {
struct {
CUdeviceptr devPtr;
CUarray_format format;
unsigned numChannels;
unsigned int numChannels;
size_t sizeInBytes;
} linear;
struct {
CUdeviceptr devPtr;
CUarray_format format;
unsigned numChannels;
unsigned int numChannels;
size_t width;
size_t height;
size_t pitchInBytes;
@@ -642,14 +642,14 @@ typedef struct CUDA_RESOURCE_DESC_st {
int reserved[32];
} reserved;
} res;
unsigned flags;
unsigned int flags;
} CUDA_RESOURCE_DESC;
typedef struct CUDA_TEXTURE_DESC_st {
CUaddress_mode addressMode[3];
CUfilter_mode filterMode;
unsigned flags;
unsigned maxAnisotropy;
unsigned int flags;
unsigned int maxAnisotropy;
CUfilter_mode mipmapFilterMode;
float mipmapLevelBias;
float minMipmapLevelClamp;
@@ -700,19 +700,19 @@ typedef struct CUDA_RESOURCE_VIEW_DESC_st {
size_t width;
size_t height;
size_t depth;
unsigned firstMipmapLevel;
unsigned lastMipmapLevel;
unsigned firstLayer;
unsigned lastLayer;
unsigned reserved[16];
unsigned int firstMipmapLevel;
unsigned int lastMipmapLevel;
unsigned int firstLayer;
unsigned int lastLayer;
unsigned int reserved[16];
} CUDA_RESOURCE_VIEW_DESC;
typedef struct CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_st {
unsigned p2pToken;
unsigned vaSpaceToken;
unsigned long long p2pToken;
unsigned int vaSpaceToken;
} CUDA_POINTER_ATTRIBUTE_P2P_TOKENS;
typedef unsigned GLenum;
typedef unsigned GLuint;
typedef unsigned int GLenum;
typedef unsigned int GLuint;
typedef int GLint;
typedef enum CUGLDeviceList_enum {
@@ -751,7 +751,7 @@ typedef struct _nvrtcProgram* nvrtcProgram;
/* Function types. */
typedef CUresult CUDAAPI tcuGetErrorString(CUresult error, const char* pStr);
typedef CUresult CUDAAPI tcuGetErrorName(CUresult error, const char* pStr);
typedef CUresult CUDAAPI tcuInit(unsigned Flags);
typedef CUresult CUDAAPI tcuInit(unsigned int Flags);
typedef CUresult CUDAAPI tcuDriverGetVersion(int* driverVersion);
typedef CUresult CUDAAPI tcuDeviceGet(CUdevice* device, int ordinal);
typedef CUresult CUDAAPI tcuDeviceGetCount(int* count);
@@ -762,17 +762,17 @@ typedef CUresult CUDAAPI tcuDeviceGetProperties(CUdevprop* prop, CUdevice dev);
typedef CUresult CUDAAPI tcuDeviceComputeCapability(int* major, int* minor, CUdevice dev);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxRetain(CUcontext* pctx, CUdevice dev);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxRelease(CUdevice dev);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxSetFlags(CUdevice dev, unsigned flags);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxGetState(CUdevice dev, unsigned* flags, int* active);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxSetFlags(CUdevice dev, unsigned int flags);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxGetState(CUdevice dev, unsigned int* flags, int* active);
typedef CUresult CUDAAPI tcuDevicePrimaryCtxReset(CUdevice dev);
typedef CUresult CUDAAPI tcuCtxCreate_v2(CUcontext* pctx, unsigned flags, CUdevice dev);
typedef CUresult CUDAAPI tcuCtxCreate_v2(CUcontext* pctx, unsigned int flags, CUdevice dev);
typedef CUresult CUDAAPI tcuCtxDestroy_v2(CUcontext ctx);
typedef CUresult CUDAAPI tcuCtxPushCurrent_v2(CUcontext ctx);
typedef CUresult CUDAAPI tcuCtxPopCurrent_v2(CUcontext* pctx);
typedef CUresult CUDAAPI tcuCtxSetCurrent(CUcontext ctx);
typedef CUresult CUDAAPI tcuCtxGetCurrent(CUcontext* pctx);
typedef CUresult CUDAAPI tcuCtxGetDevice(CUdevice* device);
typedef CUresult CUDAAPI tcuCtxGetFlags(unsigned* flags);
typedef CUresult CUDAAPI tcuCtxGetFlags(unsigned int* flags);
typedef CUresult CUDAAPI tcuCtxSynchronize(void);
typedef CUresult CUDAAPI tcuCtxSetLimit(CUlimit limit, size_t value);
typedef CUresult CUDAAPI tcuCtxGetLimit(size_t* pvalue, CUlimit limit);
@@ -780,43 +780,43 @@ typedef CUresult CUDAAPI tcuCtxGetCacheConfig(CUfunc_cache* pconfig);
typedef CUresult CUDAAPI tcuCtxSetCacheConfig(CUfunc_cache config);
typedef CUresult CUDAAPI tcuCtxGetSharedMemConfig(CUsharedconfig* pConfig);
typedef CUresult CUDAAPI tcuCtxSetSharedMemConfig(CUsharedconfig config);
typedef CUresult CUDAAPI tcuCtxGetApiVersion(CUcontext ctx, unsigned* version);
typedef CUresult CUDAAPI tcuCtxGetApiVersion(CUcontext ctx, unsigned int* version);
typedef CUresult CUDAAPI tcuCtxGetStreamPriorityRange(int* leastPriority, int* greatestPriority);
typedef CUresult CUDAAPI tcuCtxAttach(CUcontext* pctx, unsigned flags);
typedef CUresult CUDAAPI tcuCtxAttach(CUcontext* pctx, unsigned int flags);
typedef CUresult CUDAAPI tcuCtxDetach(CUcontext ctx);
typedef CUresult CUDAAPI tcuModuleLoad(CUmodule* module, const char* fname);
typedef CUresult CUDAAPI tcuModuleLoadData(CUmodule* module, const void* image);
typedef CUresult CUDAAPI tcuModuleLoadDataEx(CUmodule* module, const void* image, unsigned numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuModuleLoadDataEx(CUmodule* module, const void* image, unsigned int numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuModuleLoadFatBinary(CUmodule* module, const void* fatCubin);
typedef CUresult CUDAAPI tcuModuleUnload(CUmodule hmod);
typedef CUresult CUDAAPI tcuModuleGetFunction(CUfunction* hfunc, CUmodule hmod, const char* name);
typedef CUresult CUDAAPI tcuModuleGetGlobal_v2(CUdeviceptr* dptr, size_t* bytes, CUmodule hmod, const char* name);
typedef CUresult CUDAAPI tcuModuleGetTexRef(CUtexref* pTexRef, CUmodule hmod, const char* name);
typedef CUresult CUDAAPI tcuModuleGetSurfRef(CUsurfref* pSurfRef, CUmodule hmod, const char* name);
typedef CUresult CUDAAPI tcuLinkCreate_v2(unsigned numOptions, CUjit_option* options, void* optionValues, CUlinkState* stateOut);
typedef CUresult CUDAAPI tcuLinkAddData_v2(CUlinkState state, CUjitInputType type, void* data, size_t size, const char* name, unsigned numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuLinkAddFile_v2(CUlinkState state, CUjitInputType type, const char* path, unsigned numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuLinkCreate_v2(unsigned int numOptions, CUjit_option* options, void* optionValues, CUlinkState* stateOut);
typedef CUresult CUDAAPI tcuLinkAddData_v2(CUlinkState state, CUjitInputType type, void* data, size_t size, const char* name, unsigned int numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuLinkAddFile_v2(CUlinkState state, CUjitInputType type, const char* path, unsigned int numOptions, CUjit_option* options, void* optionValues);
typedef CUresult CUDAAPI tcuLinkComplete(CUlinkState state, void* cubinOut, size_t* sizeOut);
typedef CUresult CUDAAPI tcuLinkDestroy(CUlinkState state);
typedef CUresult CUDAAPI tcuMemGetInfo_v2(size_t* free, size_t* total);
typedef CUresult CUDAAPI tcuMemAlloc_v2(CUdeviceptr* dptr, size_t bytesize);
typedef CUresult CUDAAPI tcuMemAllocPitch_v2(CUdeviceptr* dptr, size_t* pPitch, size_t WidthInBytes, size_t Height, unsigned ElementSizeBytes);
typedef CUresult CUDAAPI tcuMemAllocPitch_v2(CUdeviceptr* dptr, size_t* pPitch, size_t WidthInBytes, size_t Height, unsigned int ElementSizeBytes);
typedef CUresult CUDAAPI tcuMemFree_v2(CUdeviceptr dptr);
typedef CUresult CUDAAPI tcuMemGetAddressRange_v2(CUdeviceptr* pbase, size_t* psize, CUdeviceptr dptr);
typedef CUresult CUDAAPI tcuMemAllocHost_v2(void* pp, size_t bytesize);
typedef CUresult CUDAAPI tcuMemFreeHost(void* p);
typedef CUresult CUDAAPI tcuMemHostAlloc(void* pp, size_t bytesize, unsigned Flags);
typedef CUresult CUDAAPI tcuMemHostGetDevicePointer_v2(CUdeviceptr* pdptr, void* p, unsigned Flags);
typedef CUresult CUDAAPI tcuMemHostGetFlags(unsigned* pFlags, void* p);
typedef CUresult CUDAAPI tcuMemAllocManaged(CUdeviceptr* dptr, size_t bytesize, unsigned flags);
typedef CUresult CUDAAPI tcuMemHostAlloc(void* pp, size_t bytesize, unsigned int Flags);
typedef CUresult CUDAAPI tcuMemHostGetDevicePointer_v2(CUdeviceptr* pdptr, void* p, unsigned int Flags);
typedef CUresult CUDAAPI tcuMemHostGetFlags(unsigned int* pFlags, void* p);
typedef CUresult CUDAAPI tcuMemAllocManaged(CUdeviceptr* dptr, size_t bytesize, unsigned int flags);
typedef CUresult CUDAAPI tcuDeviceGetByPCIBusId(CUdevice* dev, const char* pciBusId);
typedef CUresult CUDAAPI tcuDeviceGetPCIBusId(char* pciBusId, int len, CUdevice dev);
typedef CUresult CUDAAPI tcuIpcGetEventHandle(CUipcEventHandle* pHandle, CUevent event);
typedef CUresult CUDAAPI tcuIpcOpenEventHandle(CUevent* phEvent, CUipcEventHandle handle);
typedef CUresult CUDAAPI tcuIpcGetMemHandle(CUipcMemHandle* pHandle, CUdeviceptr dptr);
typedef CUresult CUDAAPI tcuIpcOpenMemHandle(CUdeviceptr* pdptr, CUipcMemHandle handle, unsigned Flags);
typedef CUresult CUDAAPI tcuIpcOpenMemHandle(CUdeviceptr* pdptr, CUipcMemHandle handle, unsigned int Flags);
typedef CUresult CUDAAPI tcuIpcCloseMemHandle(CUdeviceptr dptr);
typedef CUresult CUDAAPI tcuMemHostRegister_v2(void* p, size_t bytesize, unsigned Flags);
typedef CUresult CUDAAPI tcuMemHostRegister_v2(void* p, size_t bytesize, unsigned int Flags);
typedef CUresult CUDAAPI tcuMemHostUnregister(void* p);
typedef CUresult CUDAAPI tcuMemcpy(CUdeviceptr dst, CUdeviceptr src, size_t ByteCount);
typedef CUresult CUDAAPI tcuMemcpyPeer(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount);
@@ -842,40 +842,40 @@ typedef CUresult CUDAAPI tcuMemcpyAtoHAsync_v2(void* dstHost, CUarray srcArray,
typedef CUresult CUDAAPI tcuMemcpy2DAsync_v2(const CUDA_MEMCPY2D* pCopy, CUstream hStream);
typedef CUresult CUDAAPI tcuMemcpy3DAsync_v2(const CUDA_MEMCPY3D* pCopy, CUstream hStream);
typedef CUresult CUDAAPI tcuMemcpy3DPeerAsync(const CUDA_MEMCPY3D_PEER* pCopy, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD8_v2(CUdeviceptr dstDevice, unsigned uc, size_t N);
typedef CUresult CUDAAPI tcuMemsetD16_v2(CUdeviceptr dstDevice, unsigned us, size_t N);
typedef CUresult CUDAAPI tcuMemsetD32_v2(CUdeviceptr dstDevice, unsigned ui, size_t N);
typedef CUresult CUDAAPI tcuMemsetD2D8_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned uc, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD2D16_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned us, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD2D32_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned ui, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD8Async(CUdeviceptr dstDevice, unsigned uc, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD16Async(CUdeviceptr dstDevice, unsigned us, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD32Async(CUdeviceptr dstDevice, unsigned ui, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D8Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned uc, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D16Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned us, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D32Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned ui, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD8_v2(CUdeviceptr dstDevice, unsigned char uc, size_t N);
typedef CUresult CUDAAPI tcuMemsetD16_v2(CUdeviceptr dstDevice, unsigned short us, size_t N);
typedef CUresult CUDAAPI tcuMemsetD32_v2(CUdeviceptr dstDevice, unsigned int ui, size_t N);
typedef CUresult CUDAAPI tcuMemsetD2D8_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD2D16_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD2D32_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height);
typedef CUresult CUDAAPI tcuMemsetD8Async(CUdeviceptr dstDevice, unsigned char uc, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD16Async(CUdeviceptr dstDevice, unsigned short us, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD32Async(CUdeviceptr dstDevice, unsigned int ui, size_t N, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D8Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D16Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuMemsetD2D32Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height, CUstream hStream);
typedef CUresult CUDAAPI tcuArrayCreate_v2(CUarray* pHandle, const CUDA_ARRAY_DESCRIPTOR* pAllocateArray);
typedef CUresult CUDAAPI tcuArrayGetDescriptor_v2(CUDA_ARRAY_DESCRIPTOR* pArrayDescriptor, CUarray hArray);
typedef CUresult CUDAAPI tcuArrayDestroy(CUarray hArray);
typedef CUresult CUDAAPI tcuArray3DCreate_v2(CUarray* pHandle, const CUDA_ARRAY3D_DESCRIPTOR* pAllocateArray);
typedef CUresult CUDAAPI tcuArray3DGetDescriptor_v2(CUDA_ARRAY3D_DESCRIPTOR* pArrayDescriptor, CUarray hArray);
typedef CUresult CUDAAPI tcuMipmappedArrayCreate(CUmipmappedArray* pHandle, const CUDA_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc, unsigned numMipmapLevels);
typedef CUresult CUDAAPI tcuMipmappedArrayGetLevel(CUarray* pLevelArray, CUmipmappedArray hMipmappedArray, unsigned level);
typedef CUresult CUDAAPI tcuMipmappedArrayCreate(CUmipmappedArray* pHandle, const CUDA_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc, unsigned int numMipmapLevels);
typedef CUresult CUDAAPI tcuMipmappedArrayGetLevel(CUarray* pLevelArray, CUmipmappedArray hMipmappedArray, unsigned int level);
typedef CUresult CUDAAPI tcuMipmappedArrayDestroy(CUmipmappedArray hMipmappedArray);
typedef CUresult CUDAAPI tcuPointerGetAttribute(void* data, CUpointer_attribute attribute, CUdeviceptr ptr);
typedef CUresult CUDAAPI tcuPointerSetAttribute(const void* value, CUpointer_attribute attribute, CUdeviceptr ptr);
typedef CUresult CUDAAPI tcuPointerGetAttributes(unsigned numAttributes, CUpointer_attribute* attributes, void* data, CUdeviceptr ptr);
typedef CUresult CUDAAPI tcuStreamCreate(CUstream* phStream, unsigned Flags);
typedef CUresult CUDAAPI tcuStreamCreateWithPriority(CUstream* phStream, unsigned flags, int priority);
typedef CUresult CUDAAPI tcuPointerGetAttributes(unsigned int numAttributes, CUpointer_attribute* attributes, void* data, CUdeviceptr ptr);
typedef CUresult CUDAAPI tcuStreamCreate(CUstream* phStream, unsigned int Flags);
typedef CUresult CUDAAPI tcuStreamCreateWithPriority(CUstream* phStream, unsigned int flags, int priority);
typedef CUresult CUDAAPI tcuStreamGetPriority(CUstream hStream, int* priority);
typedef CUresult CUDAAPI tcuStreamGetFlags(CUstream hStream, unsigned* flags);
typedef CUresult CUDAAPI tcuStreamWaitEvent(CUstream hStream, CUevent hEvent, unsigned Flags);
typedef CUresult CUDAAPI tcuStreamAddCallback(CUstream hStream, CUstreamCallback callback, void* userData, unsigned flags);
typedef CUresult CUDAAPI tcuStreamAttachMemAsync(CUstream hStream, CUdeviceptr dptr, size_t length, unsigned flags);
typedef CUresult CUDAAPI tcuStreamGetFlags(CUstream hStream, unsigned int* flags);
typedef CUresult CUDAAPI tcuStreamWaitEvent(CUstream hStream, CUevent hEvent, unsigned int Flags);
typedef CUresult CUDAAPI tcuStreamAddCallback(CUstream hStream, CUstreamCallback callback, void* userData, unsigned int flags);
typedef CUresult CUDAAPI tcuStreamAttachMemAsync(CUstream hStream, CUdeviceptr dptr, size_t length, unsigned int flags);
typedef CUresult CUDAAPI tcuStreamQuery(CUstream hStream);
typedef CUresult CUDAAPI tcuStreamSynchronize(CUstream hStream);
typedef CUresult CUDAAPI tcuStreamDestroy_v2(CUstream hStream);
typedef CUresult CUDAAPI tcuEventCreate(CUevent* phEvent, unsigned Flags);
typedef CUresult CUDAAPI tcuEventCreate(CUevent* phEvent, unsigned int Flags);
typedef CUresult CUDAAPI tcuEventRecord(CUevent hEvent, CUstream hStream);
typedef CUresult CUDAAPI tcuEventQuery(CUevent hEvent);
typedef CUresult CUDAAPI tcuEventSynchronize(CUevent hEvent);
@@ -884,23 +884,23 @@ typedef CUresult CUDAAPI tcuEventElapsedTime(float* pMilliseconds, CUevent hStar
typedef CUresult CUDAAPI tcuFuncGetAttribute(int* pi, CUfunction_attribute attrib, CUfunction hfunc);
typedef CUresult CUDAAPI tcuFuncSetCacheConfig(CUfunction hfunc, CUfunc_cache config);
typedef CUresult CUDAAPI tcuFuncSetSharedMemConfig(CUfunction hfunc, CUsharedconfig config);
typedef CUresult CUDAAPI tcuLaunchKernel(CUfunction f, unsigned gridDimX, unsigned gridDimY, unsigned gridDimZ, unsigned blockDimX, unsigned blockDimY, unsigned blockDimZ, unsigned sharedMemBytes, CUstream hStream, void* kernelParams, void* extra);
typedef CUresult CUDAAPI tcuLaunchKernel(CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hStream, void* kernelParams, void* extra);
typedef CUresult CUDAAPI tcuFuncSetBlockShape(CUfunction hfunc, int x, int y, int z);
typedef CUresult CUDAAPI tcuFuncSetSharedSize(CUfunction hfunc, unsigned bytes);
typedef CUresult CUDAAPI tcuParamSetSize(CUfunction hfunc, unsigned numbytes);
typedef CUresult CUDAAPI tcuParamSeti(CUfunction hfunc, int offset, unsigned value);
typedef CUresult CUDAAPI tcuFuncSetSharedSize(CUfunction hfunc, unsigned int bytes);
typedef CUresult CUDAAPI tcuParamSetSize(CUfunction hfunc, unsigned int numbytes);
typedef CUresult CUDAAPI tcuParamSeti(CUfunction hfunc, int offset, unsigned int value);
typedef CUresult CUDAAPI tcuParamSetf(CUfunction hfunc, int offset, float value);
typedef CUresult CUDAAPI tcuParamSetv(CUfunction hfunc, int offset, void* ptr, unsigned numbytes);
typedef CUresult CUDAAPI tcuParamSetv(CUfunction hfunc, int offset, void* ptr, unsigned int numbytes);
typedef CUresult CUDAAPI tcuLaunch(CUfunction f);
typedef CUresult CUDAAPI tcuLaunchGrid(CUfunction f, int grid_width, int grid_height);
typedef CUresult CUDAAPI tcuLaunchGridAsync(CUfunction f, int grid_width, int grid_height, CUstream hStream);
typedef CUresult CUDAAPI tcuParamSetTexRef(CUfunction hfunc, int texunit, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuOccupancyMaxActiveBlocksPerMultiprocessor(int* numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize);
typedef CUresult CUDAAPI tcuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(int* numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize, unsigned flags);
typedef CUresult CUDAAPI tcuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(int* numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize, unsigned int flags);
typedef CUresult CUDAAPI tcuOccupancyMaxPotentialBlockSize(int* minGridSize, int* blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit);
typedef CUresult CUDAAPI tcuOccupancyMaxPotentialBlockSizeWithFlags(int* minGridSize, int* blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit, unsigned flags);
typedef CUresult CUDAAPI tcuTexRefSetArray(CUtexref hTexRef, CUarray hArray, unsigned Flags);
typedef CUresult CUDAAPI tcuTexRefSetMipmappedArray(CUtexref hTexRef, CUmipmappedArray hMipmappedArray, unsigned Flags);
typedef CUresult CUDAAPI tcuOccupancyMaxPotentialBlockSizeWithFlags(int* minGridSize, int* blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit, unsigned int flags);
typedef CUresult CUDAAPI tcuTexRefSetArray(CUtexref hTexRef, CUarray hArray, unsigned int Flags);
typedef CUresult CUDAAPI tcuTexRefSetMipmappedArray(CUtexref hTexRef, CUmipmappedArray hMipmappedArray, unsigned int Flags);
typedef CUresult CUDAAPI tcuTexRefSetAddress_v2(size_t* ByteOffset, CUtexref hTexRef, CUdeviceptr dptr, size_t bytes);
typedef CUresult CUDAAPI tcuTexRefSetAddress2D_v3(CUtexref hTexRef, const CUDA_ARRAY_DESCRIPTOR* desc, CUdeviceptr dptr, size_t Pitch);
typedef CUresult CUDAAPI tcuTexRefSetFormat(CUtexref hTexRef, CUarray_format fmt, int NumPackedComponents);
@@ -909,8 +909,8 @@ typedef CUresult CUDAAPI tcuTexRefSetFilterMode(CUtexref hTexRef, CUfilter_mode
typedef CUresult CUDAAPI tcuTexRefSetMipmapFilterMode(CUtexref hTexRef, CUfilter_mode fm);
typedef CUresult CUDAAPI tcuTexRefSetMipmapLevelBias(CUtexref hTexRef, float bias);
typedef CUresult CUDAAPI tcuTexRefSetMipmapLevelClamp(CUtexref hTexRef, float minMipmapLevelClamp, float maxMipmapLevelClamp);
typedef CUresult CUDAAPI tcuTexRefSetMaxAnisotropy(CUtexref hTexRef, unsigned maxAniso);
typedef CUresult CUDAAPI tcuTexRefSetFlags(CUtexref hTexRef, unsigned Flags);
typedef CUresult CUDAAPI tcuTexRefSetMaxAnisotropy(CUtexref hTexRef, unsigned int maxAniso);
typedef CUresult CUDAAPI tcuTexRefSetFlags(CUtexref hTexRef, unsigned int Flags);
typedef CUresult CUDAAPI tcuTexRefGetAddress_v2(CUdeviceptr* pdptr, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetArray(CUarray* phArray, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetMipmappedArray(CUmipmappedArray* phMipmappedArray, CUtexref hTexRef);
@@ -921,10 +921,10 @@ typedef CUresult CUDAAPI tcuTexRefGetMipmapFilterMode(CUfilter_mode* pfm, CUtexr
typedef CUresult CUDAAPI tcuTexRefGetMipmapLevelBias(float* pbias, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetMipmapLevelClamp(float* pminMipmapLevelClamp, float* pmaxMipmapLevelClamp, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetMaxAnisotropy(int* pmaxAniso, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetFlags(unsigned* pFlags, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefGetFlags(unsigned int* pFlags, CUtexref hTexRef);
typedef CUresult CUDAAPI tcuTexRefCreate(CUtexref* pTexRef);
typedef CUresult CUDAAPI tcuTexRefDestroy(CUtexref hTexRef);
typedef CUresult CUDAAPI tcuSurfRefSetArray(CUsurfref hSurfRef, CUarray hArray, unsigned Flags);
typedef CUresult CUDAAPI tcuSurfRefSetArray(CUsurfref hSurfRef, CUarray hArray, unsigned int Flags);
typedef CUresult CUDAAPI tcuSurfRefGetArray(CUarray* phArray, CUsurfref hSurfRef);
typedef CUresult CUDAAPI tcuTexObjectCreate(CUtexObject* pTexObject, const CUDA_RESOURCE_DESC* pResDesc, const CUDA_TEXTURE_DESC* pTexDesc, const CUDA_RESOURCE_VIEW_DESC* pResViewDesc);
typedef CUresult CUDAAPI tcuTexObjectDestroy(CUtexObject texObject);
@@ -935,27 +935,27 @@ typedef CUresult CUDAAPI tcuSurfObjectCreate(CUsurfObject* pSurfObject, const CU
typedef CUresult CUDAAPI tcuSurfObjectDestroy(CUsurfObject surfObject);
typedef CUresult CUDAAPI tcuSurfObjectGetResourceDesc(CUDA_RESOURCE_DESC* pResDesc, CUsurfObject surfObject);
typedef CUresult CUDAAPI tcuDeviceCanAccessPeer(int* canAccessPeer, CUdevice dev, CUdevice peerDev);
typedef CUresult CUDAAPI tcuCtxEnablePeerAccess(CUcontext peerContext, unsigned Flags);
typedef CUresult CUDAAPI tcuCtxEnablePeerAccess(CUcontext peerContext, unsigned int Flags);
typedef CUresult CUDAAPI tcuCtxDisablePeerAccess(CUcontext peerContext);
typedef CUresult CUDAAPI tcuGraphicsUnregisterResource(CUgraphicsResource resource);
typedef CUresult CUDAAPI tcuGraphicsSubResourceGetMappedArray(CUarray* pArray, CUgraphicsResource resource, unsigned arrayIndex, unsigned mipLevel);
typedef CUresult CUDAAPI tcuGraphicsSubResourceGetMappedArray(CUarray* pArray, CUgraphicsResource resource, unsigned int arrayIndex, unsigned int mipLevel);
typedef CUresult CUDAAPI tcuGraphicsResourceGetMappedMipmappedArray(CUmipmappedArray* pMipmappedArray, CUgraphicsResource resource);
typedef CUresult CUDAAPI tcuGraphicsResourceGetMappedPointer_v2(CUdeviceptr* pDevPtr, size_t* pSize, CUgraphicsResource resource);
typedef CUresult CUDAAPI tcuGraphicsResourceSetMapFlags_v2(CUgraphicsResource resource, unsigned flags);
typedef CUresult CUDAAPI tcuGraphicsMapResources(unsigned count, CUgraphicsResource* resources, CUstream hStream);
typedef CUresult CUDAAPI tcuGraphicsUnmapResources(unsigned count, CUgraphicsResource* resources, CUstream hStream);
typedef CUresult CUDAAPI tcuGraphicsResourceSetMapFlags_v2(CUgraphicsResource resource, unsigned int flags);
typedef CUresult CUDAAPI tcuGraphicsMapResources(unsigned int count, CUgraphicsResource* resources, CUstream hStream);
typedef CUresult CUDAAPI tcuGraphicsUnmapResources(unsigned int count, CUgraphicsResource* resources, CUstream hStream);
typedef CUresult CUDAAPI tcuGetExportTable(const void* ppExportTable, const CUuuid* pExportTableId);
typedef CUresult CUDAAPI tcuGraphicsGLRegisterBuffer(CUgraphicsResource* pCudaResource, GLuint buffer, unsigned Flags);
typedef CUresult CUDAAPI tcuGraphicsGLRegisterImage(CUgraphicsResource* pCudaResource, GLuint image, GLenum target, unsigned Flags);
typedef CUresult CUDAAPI tcuGLGetDevices_v2(unsigned* pCudaDeviceCount, CUdevice* pCudaDevices, unsigned cudaDeviceCount, CUGLDeviceList deviceList);
typedef CUresult CUDAAPI tcuGLCtxCreate_v2(CUcontext* pCtx, unsigned Flags, CUdevice device);
typedef CUresult CUDAAPI tcuGraphicsGLRegisterBuffer(CUgraphicsResource* pCudaResource, GLuint buffer, unsigned int Flags);
typedef CUresult CUDAAPI tcuGraphicsGLRegisterImage(CUgraphicsResource* pCudaResource, GLuint image, GLenum target, unsigned int Flags);
typedef CUresult CUDAAPI tcuGLGetDevices_v2(unsigned int* pCudaDeviceCount, CUdevice* pCudaDevices, unsigned int cudaDeviceCount, CUGLDeviceList deviceList);
typedef CUresult CUDAAPI tcuGLCtxCreate_v2(CUcontext* pCtx, unsigned int Flags, CUdevice device);
typedef CUresult CUDAAPI tcuGLInit(void);
typedef CUresult CUDAAPI tcuGLRegisterBufferObject(GLuint buffer);
typedef CUresult CUDAAPI tcuGLMapBufferObject_v2(CUdeviceptr* dptr, size_t* size, GLuint buffer);
typedef CUresult CUDAAPI tcuGLUnmapBufferObject(GLuint buffer);
typedef CUresult CUDAAPI tcuGLUnregisterBufferObject(GLuint buffer);
typedef CUresult CUDAAPI tcuGLSetBufferObjectMapFlags(GLuint buffer, unsigned Flags);
typedef CUresult CUDAAPI tcuGLSetBufferObjectMapFlags(GLuint buffer, unsigned int Flags);
typedef CUresult CUDAAPI tcuGLMapBufferObjectAsync_v2(CUdeviceptr* dptr, size_t* size, GLuint buffer, CUstream hStream);
typedef CUresult CUDAAPI tcuGLUnmapBufferObjectAsync(GLuint buffer, CUstream hStream);

35
extern/curve_fit_nd/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,35 @@
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program 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 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.
#
# ***** END GPL LICENSE BLOCK *****
set(INC
.
)
set(INC_SYS
)
set(SRC
intern/curve_fit_cubic.c
intern/curve_fit_corners_detect.c
intern/curve_fit_inline.h
curve_fit_nd.h
)
blender_add_lib(extern_curve_fit_nd "${SRC}" "${INC}" "${INC_SYS}")

162
extern/curve_fit_nd/curve_fit_nd.h vendored Normal file
View File

@@ -0,0 +1,162 @@
/*
* Copyright (c) 2016, DWANGO Co., Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __CURVE_FIT_ND_H__
#define __CURVE_FIT_ND_H__
/** \file curve_fit_nd.h
* \ingroup curve_fit
*/
/* curve_fit_cubic.c */
/**
* Takes a flat array of points and evalues that to calculate a bezier spline.
*
* \param points, points_len: The array of points to calculate a cubics from.
* \param dims: The number of dimensions for for each element in \a points.
* \param error_threshold: the error threshold to allow for,
* the curve will be within this distance from \a points.
* \param corners, corners_len: indices for points which will not have aligned tangents (optional).
* This can use the output of #curve_fit_corners_detect_db which has been included
* to evaluate a line to detect corner indices.
*
* \param r_cubic_array, r_cubic_array_len: Resulting array of tangents and knots, formatted as follows:
* ``r_cubic_array[r_cubic_array_len][3][dims]``,
* where each point has 0 and 2 for the tangents and the middle index 1 for the knot.
* The size of the *flat* array will be ``r_cubic_array_len * 3 * dims``.
* \param r_corner_index_array, r_corner_index_len: Corner indices in in \a r_cubic_array (optional).
* This allows you to access corners on the resulting curve.
*
* \returns zero on success, nonzero is reserved for error values.
*/
int curve_fit_cubic_to_points_db(
const double *points,
const unsigned int points_len,
const unsigned int dims,
const double error_threshold,
const unsigned int *corners,
unsigned int corners_len,
double **r_cubic_array, unsigned int *r_cubic_array_len,
unsigned int **r_cubic_orig_index,
unsigned int **r_corner_index_array, unsigned int *r_corner_index_len);
int curve_fit_cubic_to_points_fl(
const float *points,
const unsigned int points_len,
const unsigned int dims,
const float error_threshold,
const unsigned int *corners,
const unsigned int corners_len,
float **r_cubic_array, unsigned int *r_cubic_array_len,
unsigned int **r_cubic_orig_index,
unsigned int **r_corners_index_array, unsigned int *r_corners_index_len);
/**
* Takes a flat array of points and evalues that to calculate handle lengths.
*
* \param points, points_len: The array of points to calculate a cubics from.
* \param dims: The number of dimensions for for each element in \a points.
* \param error_threshold: the error threshold to allow for,
* \param tan_l, tan_r: Normalized tangents the handles will be aligned to.
* Note that tangents must both point along the direction of the \a points,
* so \a tan_l points in the same direction of the resulting handle,
* where \a tan_r will point the opposite direction of its handle.
*
* \param r_handle_l, r_handle_r: Resulting calculated handles.
* \param r_error_sq: The maximum distance (squared) this curve diverges from \a points.
*/
int curve_fit_cubic_to_points_single_db(
const double *points,
const unsigned int points_len,
const unsigned int dims,
const double error_threshold,
const double tan_l[],
const double tan_r[],
double r_handle_l[],
double r_handle_r[],
double *r_error_sq);
int curve_fit_cubic_to_points_single_fl(
const float *points,
const unsigned int points_len,
const unsigned int dims,
const float error_threshold,
const float tan_l[],
const float tan_r[],
float r_handle_l[],
float r_handle_r[],
float *r_error_sq);
/* curve_fit_corners_detect.c */
/**
* A helper function that takes a line and outputs its corner indices.
*
* \param points, points_len: Curve to evaluate.
* \param dims: The number of dimensions for for each element in \a points.
* \param radius_min: Corners on the curve between points below this radius are ignored.
* \param radius_max: Corners on the curve above this radius are ignored.
* \param samples_max: Prevent testing corners beyond this many points
* (prevents a large radius taking excessive time to compute).
* \param angle_threshold: Angles above this value are considered corners
* (higher value for fewer corners).
*
* \param r_corners, r_corners_len: Resulting array of corners.
*
* \returns zero on success, nonzero is reserved for error values.
*/
int curve_fit_corners_detect_db(
const double *points,
const unsigned int points_len,
const unsigned int dims,
const double radius_min,
const double radius_max,
const unsigned int samples_max,
const double angle_threshold,
unsigned int **r_corners,
unsigned int *r_corners_len);
int curve_fit_corners_detect_fl(
const float *points,
const unsigned int points_len,
const unsigned int dims,
const float radius_min,
const float radius_max,
const unsigned int samples_max,
const float angle_threshold,
unsigned int **r_corners,
unsigned int *r_corners_len);
#endif /* __CURVE_FIT_ND_H__ */

View File

@@ -0,0 +1,468 @@
/*
* Copyright (c) 2016, Blender Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file curve_fit_corners_detect.c
* \ingroup curve_fit
*/
#include <math.h>
#include <float.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include "../curve_fit_nd.h"
typedef unsigned int uint;
#include "curve_fit_inline.h"
#ifdef _MSC_VER
# define alloca(size) _alloca(size)
#endif
#if !defined(_MSC_VER)
# define USE_VLA
#endif
#ifdef USE_VLA
# ifdef __GNUC__
# pragma GCC diagnostic ignored "-Wvla"
# endif
#else
# ifdef __GNUC__
# pragma GCC diagnostic error "-Wvla"
# endif
#endif
/* -------------------------------------------------------------------- */
/** \name Simple Vector Math Lib
* \{ */
static double cos_vnvnvn(
const double v0[], const double v1[], const double v2[],
const uint dims)
{
#ifdef USE_VLA
double dvec0[dims];
double dvec1[dims];
#else
double *dvec0 = alloca(sizeof(double) * dims);
double *dvec1 = alloca(sizeof(double) * dims);
#endif
normalize_vn_vnvn(dvec0, v0, v1, dims);
normalize_vn_vnvn(dvec1, v1, v2, dims);
double d = dot_vnvn(dvec0, dvec1, dims);
/* sanity check */
d = max(-1.0, min(1.0, d));
return d;
}
static double angle_vnvnvn(
const double v0[], const double v1[], const double v2[],
const uint dims)
{
return acos(cos_vnvnvn(v0, v1, v2, dims));
}
static bool isect_line_sphere_vn(
const double l1[],
const double l2[],
const double sp[],
const double r,
uint dims,
double r_p1[]
#if 0 /* UNUSED */
double r_p2[]
#endif
)
{
#ifdef USE_VLA
double ldir[dims];
double tvec[dims];
#else
double *ldir = alloca(sizeof(double) * dims);
double *tvec = alloca(sizeof(double) * dims);
#endif
sub_vn_vnvn(ldir, l2, l1, dims);
sub_vn_vnvn(tvec, l1, sp, dims);
const double a = len_squared_vn(ldir, dims);
const double b = 2.0 * dot_vnvn(ldir, tvec, dims);
const double c = len_squared_vn(sp, dims) + len_squared_vn(l1, dims) - (2.0 * dot_vnvn(sp, l1, dims)) - sq(r);
const double i = b * b - 4.0 * a * c;
if ((i < 0.0) || (a == 0.0)) {
return false;
}
else if (i == 0.0) {
/* one intersection */
const double mu = -b / (2.0 * a);
mul_vnvn_fl(r_p1, ldir, mu, dims);
iadd_vnvn(r_p1, l1, dims);
return true;
}
else if (i > 0.0) {
/* # avoid calc twice */
const double i_sqrt = sqrt(i);
double mu;
/* Note: when l1 is inside the sphere and l2 is outside.
* the first intersection point will always be between the pair. */
/* first intersection */
mu = (-b + i_sqrt) / (2.0 * a);
mul_vnvn_fl(r_p1, ldir, mu, dims);
iadd_vnvn(r_p1, l1, dims);
#if 0
/* second intersection */
mu = (-b - i_sqrt) / (2.0 * a);
mul_vnvn_fl(r_p2, ldir, mu, dims);
iadd_vnvn(r_p2, l1, dims);
#endif
return true;
}
else {
return false;
}
}
/** \} */
/* -------------------------------------------------------------------- */
static bool point_corner_measure(
const double *points,
const uint points_len,
const uint i,
const uint i_prev_init,
const uint i_next_init,
const double radius,
const uint samples_max,
const uint dims,
double r_p_prev[], uint *r_i_prev_next,
double r_p_next[], uint *r_i_next_prev)
{
const double *p = &points[i * dims];
uint sample;
uint i_prev = i_prev_init;
uint i_prev_next = i_prev + 1;
sample = 0;
while (true) {
if ((i_prev == -1) || (sample++ > samples_max)) {
return false;
}
else if (len_squared_vnvn(p, &points[i_prev * dims], dims) < radius) {
i_prev -= 1;
}
else {
break;
}
}
uint i_next = i_next_init;
uint i_next_prev = i_next - 1;
sample = 0;
while (true) {
if ((i_next == points_len) || (sample++ > samples_max)) {
return false;
}
else if (len_squared_vnvn(p, &points[i_next * dims], dims) < radius) {
i_next += 1;
}
else {
break;
}
}
/* find points on the sphere */
if (!isect_line_sphere_vn(
&points[i_prev * dims], &points[i_prev_next * dims], p, radius, dims,
r_p_prev))
{
return false;
}
if (!isect_line_sphere_vn(
&points[i_next * dims], &points[i_next_prev * dims], p, radius, dims,
r_p_next))
{
return false;
}
*r_i_prev_next = i_prev_next;
*r_i_next_prev = i_next_prev;
return true;
}
static double point_corner_angle(
const double *points,
const uint points_len,
const uint i,
const double radius_mid,
const double radius_max,
const double angle_threshold,
const double angle_threshold_cos,
/* prevent locking up when for example `radius_min` is very large
* (possibly larger then the curve).
* In this case we would end up checking every point from every other point,
* never reaching one that was outside the `radius_min`. */
/* prevent locking up when for e */
const uint samples_max,
const uint dims)
{
assert(angle_threshold_cos == cos(angle_threshold));
if (i == 0 || i == points_len - 1) {
return 0.0;
}
const double *p = &points[i * dims];
/* initial test */
if (cos_vnvnvn(&points[(i - 1) * dims], p, &points[(i + 1) * dims], dims) > angle_threshold_cos) {
return 0.0;
}
#ifdef USE_VLA
double p_mid_prev[dims];
double p_mid_next[dims];
#else
double *p_mid_prev = alloca(sizeof(double) * dims);
double *p_mid_next = alloca(sizeof(double) * dims);
#endif
uint i_mid_prev_next, i_mid_next_prev;
if (point_corner_measure(
points, points_len,
i, i - 1, i + 1,
radius_mid,
samples_max,
dims,
p_mid_prev, &i_mid_prev_next,
p_mid_next, &i_mid_next_prev))
{
const double angle_mid_cos = cos_vnvnvn(p_mid_prev, p, p_mid_next, dims);
/* compare as cos and flip direction */
/* if (angle_mid > angle_threshold) { */
if (angle_mid_cos < angle_threshold_cos) {
#ifdef USE_VLA
double p_max_prev[dims];
double p_max_next[dims];
#else
double *p_max_prev = alloca(sizeof(double) * dims);
double *p_max_next = alloca(sizeof(double) * dims);
#endif
uint i_max_prev_next, i_max_next_prev;
if (point_corner_measure(
points, points_len,
i, i - 1, i + 1,
radius_max,
samples_max,
dims,
p_max_prev, &i_max_prev_next,
p_max_next, &i_max_next_prev))
{
const double angle_mid = acos(angle_mid_cos);
const double angle_max = angle_vnvnvn(p_max_prev, p, p_max_next, dims) / 2.0;
const double angle_diff = angle_mid - angle_max;
if (angle_diff > angle_threshold) {
return angle_diff;
}
}
}
}
return 0.0;
}
int curve_fit_corners_detect_db(
const double *points,
const uint points_len,
const uint dims,
const double radius_min, /* ignore values below this */
const double radius_max, /* ignore values above this */
const uint samples_max,
const double angle_threshold,
uint **r_corners,
uint *r_corners_len)
{
const double angle_threshold_cos = cos(angle_threshold);
uint corners_len = 0;
/* Use the difference in angle between the mid-max radii
* to detect the difference between a corner and a sharp turn. */
const double radius_mid = (radius_min + radius_max) / 2.0;
/* we could ignore first/last- but simple to keep aligned with the point array */
double *points_angle = malloc(sizeof(double) * points_len);
points_angle[0] = 0.0;
*r_corners = NULL;
*r_corners_len = 0;
for (uint i = 0; i < points_len; i++) {
points_angle[i] = point_corner_angle(
points, points_len, i,
radius_mid, radius_max,
angle_threshold, angle_threshold_cos,
samples_max,
dims);
if (points_angle[i] != 0.0) {
corners_len++;
}
}
if (corners_len == 0) {
free(points_angle);
return 0;
}
/* Clean angle limits!
*
* How this works:
* - Find contiguous 'corners' (where the distance is less or equal to the error threshold).
* - Keep track of the corner with the highest angle
* - Clear every other angle (so they're ignored when setting corners). */
{
const double radius_min_sq = sq(radius_min);
uint i_span_start = 0;
while (i_span_start < points_len) {
uint i_span_end = i_span_start;
if (points_angle[i_span_start] != 0.0) {
uint i_next = i_span_start + 1;
uint i_best = i_span_start;
while (i_next < points_len) {
if ((points_angle[i_next] == 0.0) ||
(len_squared_vnvn(
&points[(i_next - 1) * dims],
&points[i_next * dims], dims) > radius_min_sq))
{
break;
}
else {
if (points_angle[i_best] < points_angle[i_next]) {
i_best = i_next;
}
i_span_end = i_next;
i_next += 1;
}
}
if (i_span_start != i_span_end) {
uint i = i_span_start;
while (i <= i_span_end) {
if (i != i_best) {
/* we could use some other error code */
assert(points_angle[i] != 0.0);
points_angle[i] = 0.0;
corners_len--;
}
i += 1;
}
}
}
i_span_start = i_span_end + 1;
}
}
/* End angle limit cleaning! */
corners_len += 2; /* first and last */
uint *corners = malloc(sizeof(uint) * corners_len);
uint i_corner = 0;
corners[i_corner++] = 0;
for (uint i = 0; i < points_len; i++) {
if (points_angle[i] != 0.0) {
corners[i_corner++] = i;
}
}
corners[i_corner++] = points_len - 1;
assert(i_corner == corners_len);
free(points_angle);
*r_corners = corners;
*r_corners_len = corners_len;
return 0;
}
int curve_fit_corners_detect_fl(
const float *points,
const uint points_len,
const uint dims,
const float radius_min, /* ignore values below this */
const float radius_max, /* ignore values above this */
const uint samples_max,
const float angle_threshold,
uint **r_corners,
uint *r_corners_len)
{
const uint points_flat_len = points_len * dims;
double *points_db = malloc(sizeof(double) * points_flat_len);
for (uint i = 0; i < points_flat_len; i++) {
points_db[i] = (double)points[i];
}
int result = curve_fit_corners_detect_db(
points_db, points_len,
dims,
radius_min, radius_max,
samples_max,
angle_threshold,
r_corners, r_corners_len);
free(points_db);
return result;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,293 @@
/*
* Copyright (c) 2016, Blender Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file curve_fit_inline.h
* \ingroup curve_fit
*/
/** \name Simple Vector Math Lib
* \{ */
#ifdef _MSC_VER
# define MINLINE static __forceinline
#else
# define MINLINE static inline
#endif
MINLINE double sq(const double d)
{
return d * d;
}
#ifndef _MSC_VER
MINLINE double min(const double a, const double b)
{
return b < a ? b : a;
}
MINLINE double max(const double a, const double b)
{
return a < b ? b : a;
}
#endif
MINLINE void zero_vn(
double v0[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] = 0.0;
}
}
MINLINE void flip_vn_vnvn(
double v_out[], const double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] + (v0[j] - v1[j]);
}
}
MINLINE void copy_vnvn(
double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] = v1[j];
}
}
MINLINE void copy_vnfl_vndb(
float v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] = (float)v1[j];
}
}
MINLINE void copy_vndb_vnfl(
double v0[], const float v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] = (double)v1[j];
}
}
MINLINE double dot_vnvn(
const double v0[], const double v1[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
d += v0[j] * v1[j];
}
return d;
}
MINLINE void add_vn_vnvn(
double v_out[], const double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] + v1[j];
}
}
MINLINE void sub_vn_vnvn(
double v_out[], const double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] - v1[j];
}
}
MINLINE void iadd_vnvn(
double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] += v1[j];
}
}
MINLINE void isub_vnvn(
double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] -= v1[j];
}
}
MINLINE void madd_vn_vnvn_fl(
double v_out[],
const double v0[], const double v1[],
const double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] + v1[j] * f;
}
}
MINLINE void msub_vn_vnvn_fl(
double v_out[],
const double v0[], const double v1[],
const double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] - v1[j] * f;
}
}
MINLINE void miadd_vn_vn_fl(
double v_out[], const double v0[], double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] += v0[j] * f;
}
}
#if 0
MINLINE void misub_vn_vn_fl(
double v_out[], const double v0[], double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] -= v0[j] * f;
}
}
#endif
MINLINE void mul_vnvn_fl(
double v_out[],
const double v0[], const double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v_out[j] = v0[j] * f;
}
}
MINLINE void imul_vn_fl(double v0[], const double f, const uint dims)
{
for (uint j = 0; j < dims; j++) {
v0[j] *= f;
}
}
MINLINE double len_squared_vnvn(
const double v0[], const double v1[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
d += sq(v0[j] - v1[j]);
}
return d;
}
MINLINE double len_squared_vn(
const double v0[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
d += sq(v0[j]);
}
return d;
}
MINLINE double len_vnvn(
const double v0[], const double v1[], const uint dims)
{
return sqrt(len_squared_vnvn(v0, v1, dims));
}
MINLINE double len_vn(
const double v0[], const uint dims)
{
return sqrt(len_squared_vn(v0, dims));
}
/* special case, save us negating a copy, then getting the length */
MINLINE double len_squared_negated_vnvn(
const double v0[], const double v1[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
d += sq(v0[j] + v1[j]);
}
return d;
}
MINLINE double len_negated_vnvn(
const double v0[], const double v1[], const uint dims)
{
return sqrt(len_squared_negated_vnvn(v0, v1, dims));
}
MINLINE double normalize_vn(
double v0[], const uint dims)
{
double d = len_squared_vn(v0, dims);
if (d != 0.0 && ((d = sqrt(d)) != 0.0)) {
imul_vn_fl(v0, 1.0 / d, dims);
}
return d;
}
/* v_out = (v0 - v1).normalized() */
MINLINE double normalize_vn_vnvn(
double v_out[],
const double v0[], const double v1[], const uint dims)
{
double d = 0.0;
for (uint j = 0; j < dims; j++) {
double a = v0[j] - v1[j];
d += sq(a);
v_out[j] = a;
}
if (d != 0.0 && ((d = sqrt(d)) != 0.0)) {
imul_vn_fl(v_out, 1.0 / d, dims);
}
return d;
}
MINLINE bool is_almost_zero_ex(double val, double eps)
{
return (-eps < val) && (val < eps);
}
MINLINE bool is_almost_zero(double val)
{
return is_almost_zero_ex(val, 1e-8);
}
MINLINE bool equals_vnvn(
const double v0[], const double v1[], const uint dims)
{
for (uint j = 0; j < dims; j++) {
if (v0[j] != v1[j]) {
return false;
}
}
return true;
}
/** \} */

View File

@@ -1,5 +1,5 @@
Project: Google Flags
URL: http://code.google.com/p/google-gflags/
URL: https://github.com/gflags/gflags
License: New BSD
Upstream version: 2.2.0 (9db82895)
Local modifications:
@@ -17,3 +17,7 @@ Local modifications:
- Applied some modifications from fork https://github.com/Nazg-Gul/gflags.git
(see https://github.com/gflags/gflags/pull/129)
- Avoid attemot of acquiring mutex lock in FlagRegistry::GlobalRegistry when
doing static flags initialization. See d81dd2d in Blender repository.

View File

@@ -1,5 +1,5 @@
Project: Google Logging
URL: http://code.google.com/p/google-glog/
URL: https://github.com/google/glog
License: New BSD
Upstream version: 0.3.4, 4d391fe
Local modifications:

View File

@@ -1,7 +1,5 @@
Project: Google C++ Testing Framework
URL: http://code.google.com/p/googletest
URL: https://github.com/google/googletest
License: New BSD
Upstream version: 1.7.0
Local modifications:
None.
Local modifications:None

5
extern/libopenjpeg/README.blender vendored Normal file
View File

@@ -0,0 +1,5 @@
Project: OpenJPEG
URL: http://www.openjpeg.org
License: BSD 2-Clause
Upstream version: 1.5.2
Local modifications:

View File

@@ -42,7 +42,7 @@ Write a bit
@param bio BIO handle
@param b Bit to write (0 or 1)
*/
static void bio_putbit(opj_bio_t *bio, int b);
static void bio_putbit(opj_bio_t *bio, unsigned int b);
/**
Read a bit
@param bio BIO handle
@@ -78,7 +78,7 @@ static int bio_byteout(opj_bio_t *bio) {
if (bio->bp >= bio->end) {
return 1;
}
*bio->bp++ = bio->buf >> 8;
*bio->bp++ = (unsigned char)(bio->buf >> 8);
return 0;
}
@@ -92,7 +92,7 @@ static int bio_bytein(opj_bio_t *bio) {
return 0;
}
static void bio_putbit(opj_bio_t *bio, int b) {
static void bio_putbit(opj_bio_t *bio, unsigned int b) {
if (bio->ct == 0) {
bio_byteout(bio);
}
@@ -126,7 +126,7 @@ void bio_destroy(opj_bio_t *bio) {
}
int bio_numbytes(opj_bio_t *bio) {
return (bio->bp - bio->start);
return (int)(bio->bp - bio->start);
}
void bio_init_enc(opj_bio_t *bio, unsigned char *bp, int len) {

View File

@@ -29,8 +29,6 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include "opj_includes.h"

View File

@@ -30,6 +30,7 @@
*/
#include "opj_includes.h"
#include <assert.h>
/* ----------------------------------------------------------------------- */
@@ -106,6 +107,7 @@ int OPJ_CALLCONV cio_tell(opj_cio_t *cio) {
* pos : position, in number of bytes, from the beginning of the stream
*/
void OPJ_CALLCONV cio_seek(opj_cio_t *cio, int pos) {
assert((cio->start + pos) <= cio->end);
cio->bp = cio->start + pos;
}
@@ -113,6 +115,7 @@ void OPJ_CALLCONV cio_seek(opj_cio_t *cio, int pos) {
* Number of bytes left before the end of the stream.
*/
int cio_numbytesleft(opj_cio_t *cio) {
assert((cio->end - cio->bp) >= 0);
return cio->end - cio->bp;
}
@@ -139,6 +142,7 @@ opj_bool cio_byteout(opj_cio_t *cio, unsigned char v) {
* Read a byte.
*/
unsigned char cio_bytein(opj_cio_t *cio) {
assert(cio->bp >= cio->start);
if (cio->bp >= cio->end) {
opj_event_msg(cio->cinfo, EVT_ERROR, "read error: passed the end of the codestream (start = %d, current = %d, end = %d\n", cio->start, cio->bp, cio->end);
return 0;
@@ -152,7 +156,7 @@ unsigned char cio_bytein(opj_cio_t *cio) {
* v : value to write
* n : number of bytes to write
*/
unsigned int cio_write(opj_cio_t *cio, unsigned long long int v, int n) {
unsigned int cio_write(opj_cio_t *cio, unsigned int64 v, int n) {
int i;
for (i = n - 1; i >= 0; i--) {
if( !cio_byteout(cio, (unsigned char) ((v >> (i << 3)) & 0xff)) )
@@ -173,7 +177,7 @@ unsigned int cio_read(opj_cio_t *cio, int n) {
unsigned int v;
v = 0;
for (i = n - 1; i >= 0; i--) {
v += cio_bytein(cio) << (i << 3);
v += (unsigned int)cio_bytein(cio) << (i << 3);
}
return v;
}
@@ -184,6 +188,10 @@ unsigned int cio_read(opj_cio_t *cio, int n) {
* n : number of bytes to skip
*/
void cio_skip(opj_cio_t *cio, int n) {
assert((cio->bp + n) >= cio->bp);
if (((cio->bp + n) < cio->start) || ((cio->bp + n) > cio->end)) {
assert(0);
}
cio->bp += n;
}

View File

@@ -31,6 +31,13 @@
#ifndef __CIO_H
#define __CIO_H
#if defined(_MSC_VER) || defined(__BORLANDC__)
#define int64 __int64
#else
#define int64 long long
#endif
/**
@file cio.h
@brief Implementation of a byte input-output process (CIO)
@@ -63,7 +70,7 @@ Write some bytes
@param n Number of bytes to write
@return Returns the number of bytes written or 0 if an error occured
*/
unsigned int cio_write(opj_cio_t *cio, unsigned long long int v, int n);
unsigned int cio_write(opj_cio_t *cio, unsigned int64 v, int n);
/**
Read some bytes
@param cio CIO handle

View File

@@ -103,18 +103,17 @@ opj_bool opj_event_msg(opj_common_ptr cinfo, int event_type, const char *fmt, ..
va_list arg;
int str_length/*, i, j*/; /* UniPG */
char message[MSG_SIZE];
memset(message, 0, MSG_SIZE);
/* initialize the optional parameter list */
va_start(arg, fmt);
/* check the length of the format string */
str_length = (strlen(fmt) > MSG_SIZE) ? MSG_SIZE : strlen(fmt);
/* parse the format string and put the result in 'message' */
vsprintf(message, fmt, arg); /* UniPG */
str_length = vsnprintf(message, MSG_SIZE, fmt, arg); /* UniPG */
/* deinitialize the optional parameter list */
va_end(arg);
/* output the message to the user program */
msg_handler(message, cinfo->client_data);
if( str_length > -1 && str_length < MSG_SIZE )
msg_handler(message, cinfo->client_data);
else return OPJ_FALSE;
}
return OPJ_TRUE;

View File

@@ -40,7 +40,7 @@ opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *c
image->color_space = clrspc;
image->numcomps = numcmpts;
/* allocate memory for the per-component information */
image->comps = (opj_image_comp_t*)opj_malloc(image->numcomps * sizeof(opj_image_comp_t));
image->comps = (opj_image_comp_t*)opj_calloc(1,image->numcomps * sizeof(opj_image_comp_t));
if(!image->comps) {
fprintf(stderr,"Unable to allocate memory for image.\n");
opj_image_destroy(image);
@@ -86,3 +86,4 @@ void OPJ_CALLCONV opj_image_destroy(opj_image_t *image) {
opj_free(image);
}
}

View File

@@ -32,6 +32,7 @@
*/
#include "opj_includes.h"
#include <assert.h>
/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
/*@{*/
@@ -404,6 +405,7 @@ static void j2k_write_siz(opj_j2k_t *j2k) {
static void j2k_read_siz(opj_j2k_t *j2k) {
int len, i;
int n_comps;
opj_cio_t *cio = j2k->cio;
opj_image_t *image = j2k->image;
@@ -422,12 +424,33 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
if ((image->x0<0)||(image->x1<0)||(image->y0<0)||(image->y1<0)) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"%s: invalid image size (x0:%d, x1:%d, y0:%d, y1:%d)\n",
"invalid image size (x0:%d, x1:%d, y0:%d, y1:%d)\n",
image->x0,image->x1,image->y0,image->y1);
return;
}
n_comps = (len - 36 - 2 ) / 3;
assert( (len - 36 - 2 ) % 3 == 0 );
image->numcomps = cio_read(cio, 2); /* Csiz */
assert( n_comps == image->numcomps );
(void)n_comps;
/* testcase 4035.pdf.SIGSEGV.d8b.3375 */
if (image->x0 > image->x1 || image->y0 > image->y1) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Error with SIZ marker: negative image size (%d x %d)\n", image->x1 - image->x0, image->y1 - image->y0);
return;
}
/* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */
if (!(cp->tdx * cp->tdy)) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", cp->tdx, cp->tdy);
return;
}
/* testcase 1610.pdf.SIGSEGV.59c.681 */
if (((int64)image->x1) * ((int64)image->y1) != (image->x1 * image->y1)) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Prevent buffer overflow (x1: %d, y1: %d)\n", image->x1, image->y1);
return;
}
#ifdef USE_JPWL
if (j2k->cp->correct) {
@@ -466,11 +489,19 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
/* update components number in the jpwl_exp_comps filed */
cp->exp_comps = image->numcomps;
}
#else
(void)len;
#endif /* USE_JPWL */
/* prevent division by zero */
if (!(cp->tdx * cp->tdy)) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "invalid tile size (tdx: %d, tdy: %d)\n", cp->tdx, cp->tdy);
return;
}
image->comps = (opj_image_comp_t*) opj_calloc(image->numcomps, sizeof(opj_image_comp_t));
for (i = 0; i < image->numcomps; i++) {
int tmp, w, h;
int tmp;
tmp = cio_read(cio, 1); /* Ssiz_i */
image->comps[i].prec = (tmp & 0x7f) + 1;
image->comps[i].sgnd = tmp >> 7;
@@ -506,9 +537,11 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
}
#endif /* USE_JPWL */
/* TODO: unused ? */
w = int_ceildiv(image->x1 - image->x0, image->comps[i].dx);
h = int_ceildiv(image->y1 - image->y0, image->comps[i].dy);
/* prevent division by zero */
if (!(image->comps[i].dx * image->comps[i].dy)) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: invalid component size (dx: %d, dy: %d)\n", image->comps[i].dx, image->comps[i].dy);
return;
}
image->comps[i].resno_decoded = 0; /* number of resolution decoded */
image->comps[i].factor = cp->reduce; /* reducing factor per component */
@@ -517,6 +550,15 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
/* gdal_fuzzer_check_number_of_tiles.jp2 */
if (cp->tw == 0 || cp->th == 0 || cp->tw > 65535 / cp->th) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n",
cp->tw, cp->th);
return;
}
#ifdef USE_JPWL
if (j2k->cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
@@ -558,7 +600,17 @@ static void j2k_read_siz(opj_j2k_t *j2k) {
#endif /* USE_JPWL */
cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
if (cp->tcps == NULL)
{
opj_event_msg(j2k->cinfo, EVT_ERROR, "Out of memory\n");
return;
}
cp->tileno = (int*) opj_malloc(cp->tw * cp->th * sizeof(int));
if (cp->tileno == NULL)
{
opj_event_msg(j2k->cinfo, EVT_ERROR, "Out of memory\n");
return;
}
cp->tileno_size = 0;
#ifdef USE_JPWL
@@ -684,6 +736,12 @@ static void j2k_read_cox(opj_j2k_t *j2k, int compno) {
"of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno);
j2k->state |= J2K_STATE_ERR;
}
if( tccp->numresolutions > J2K_MAXRLVLS ) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions is too big: %d vs max= %d. Truncating.\n\n",
compno, tccp->numresolutions, J2K_MAXRLVLS);
j2k->state |= J2K_STATE_ERR;
tccp->numresolutions = J2K_MAXRLVLS;
}
tccp->cblkw = cio_read(cio, 1) + 2; /* SPcox (E) */
tccp->cblkh = cio_read(cio, 1) + 2; /* SPcox (F) */
@@ -753,6 +811,7 @@ static void j2k_read_cod(opj_j2k_t *j2k) {
opj_image_t *image = j2k->image;
len = cio_read(cio, 2); /* Lcod */
(void)len;
tcp->csty = cio_read(cio, 1); /* Scod */
tcp->prg = (OPJ_PROG_ORDER)cio_read(cio, 1); /* SGcod (A) */
tcp->numlayers = cio_read(cio, 2); /* SGcod (B) */
@@ -806,7 +865,14 @@ static void j2k_read_coc(opj_j2k_t *j2k) {
opj_cio_t *cio = j2k->cio;
len = cio_read(cio, 2); /* Lcoc */
(void)len;
compno = cio_read(cio, image->numcomps <= 256 ? 1 : 2); /* Ccoc */
if (compno >= image->numcomps) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"bad component number in COC (%d out of a maximum of %d)\n",
compno, image->numcomps);
return;
}
tcp->tccps[compno].csty = cio_read(cio, 1); /* Scoc */
j2k_read_cox(j2k, compno);
}
@@ -877,6 +943,8 @@ static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len) {
opj_event_msg(j2k->cinfo, EVT_WARNING ,
"bad number of subbands in Sqcx (%d) regarding to J2K_MAXBANDS (%d) \n"
"- limiting number of bands to J2K_MAXBANDS and try to move to the next markers\n", numbands, J2K_MAXBANDS);
/* edf_c2_1013627.jp2 */
numbands = 1;
}
#endif /* USE_JPWL */
@@ -988,9 +1056,16 @@ static void j2k_read_qcc(opj_j2k_t *j2k) {
/* keep your private count of tiles */
backup_compno++;
};
}
#endif /* USE_JPWL */
if ((compno < 0) || (compno >= numcomp)) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"bad component number in QCC (%d out of a maximum of %d)\n",
compno, j2k->image->numcomps);
return;
}
j2k_read_qcx(j2k, compno, len - 2 - (numcomp <= 256 ? 1 : 2));
}
@@ -1036,6 +1111,15 @@ static void j2k_read_poc(opj_j2k_t *j2k) {
len = cio_read(cio, 2); /* Lpoc */
numpchgs = (len - 2) / (5 + 2 * (numcomps <= 256 ? 1 : 2));
if( numpchgs >= 32 )
{
/* edf_c2_1103421.jp2 */
opj_event_msg(j2k->cinfo, EVT_ERROR,
"bad number of POCS (%d out of a maximum of %d)\n",
numpchgs, 32);
numpchgs = 0;
}
for (i = old_poc; i < numpchgs + old_poc; i++) {
opj_poc_t *poc;
poc = &tcp->pocs[i];
@@ -1058,9 +1142,12 @@ static void j2k_read_crg(opj_j2k_t *j2k) {
int numcomps = j2k->image->numcomps;
len = cio_read(cio, 2); /* Lcrg */
(void)len;
for (i = 0; i < numcomps; i++) {
Xcrg_i = cio_read(cio, 2); /* Xcrg_i */
(void)Xcrg_i;
Ycrg_i = cio_read(cio, 2); /* Ycrg_i */
(void)Ycrg_i;
}
}
@@ -1072,13 +1159,16 @@ static void j2k_read_tlm(opj_j2k_t *j2k) {
len = cio_read(cio, 2); /* Ltlm */
Ztlm = cio_read(cio, 1); /* Ztlm */
(void)Ztlm;
Stlm = cio_read(cio, 1); /* Stlm */
ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
SP = (Stlm >> 6) & 0x01;
tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);
for (i = 0; i < tile_tlm; i++) {
Ttlm_i = cio_read(cio, ST); /* Ttlm_i */
(void)Ttlm_i;
Ptlm_i = cio_read(cio, SP ? 4 : 2); /* Ptlm_i */
(void)Ptlm_i;
}
}
@@ -1089,6 +1179,7 @@ static void j2k_read_plm(opj_j2k_t *j2k) {
len = cio_read(cio, 2); /* Lplm */
Zplm = cio_read(cio, 1); /* Zplm */
(void)Zplm;
len -= 3;
while (len > 0) {
Nplm = cio_read(cio, 4); /* Nplm */
@@ -1114,6 +1205,7 @@ static void j2k_read_plt(opj_j2k_t *j2k) {
len = cio_read(cio, 2); /* Lplt */
Zplt = cio_read(cio, 1); /* Zplt */
(void)Zplt;
for (i = len - 3; i > 0; i--) {
add = cio_read(cio, 1);
packet_len = (packet_len << 7) + add; /* Iplt_i */
@@ -1261,6 +1353,7 @@ static void j2k_read_sot(opj_j2k_t *j2k) {
opj_cio_t *cio = j2k->cio;
len = cio_read(cio, 2);
(void)len;
tileno = cio_read(cio, 2);
#ifdef USE_JPWL
@@ -1269,7 +1362,7 @@ static void j2k_read_sot(opj_j2k_t *j2k) {
static int backup_tileno = 0;
/* tileno is negative or larger than the number of tiles!!! */
if ((tileno < 0) || (tileno > (cp->tw * cp->th))) {
if ((tileno < 0) || (tileno >= (cp->tw * cp->th))) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"JPWL: bad tile number (%d out of a maximum of %d)\n",
tileno, (cp->tw * cp->th));
@@ -1286,8 +1379,18 @@ static void j2k_read_sot(opj_j2k_t *j2k) {
/* keep your private count of tiles */
backup_tileno++;
};
}
else
#endif /* USE_JPWL */
{
/* tileno is negative or larger than the number of tiles!!! */
if ((tileno < 0) || (tileno >= (cp->tw * cp->th))) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"JPWL: bad tile number (%d out of a maximum of %d)\n",
tileno, (cp->tw * cp->th));
return;
}
}
if (cp->tileno_size == 0) {
cp->tileno[cp->tileno_size] = tileno;
@@ -1325,8 +1428,18 @@ static void j2k_read_sot(opj_j2k_t *j2k) {
totlen);
}
};
}
else
#endif /* USE_JPWL */
{
/* totlen is negative or larger than the bytes left!!! */
if ((totlen < 0) || (totlen > (cio_numbytesleft(cio) + 8))) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
totlen, cio_numbytesleft(cio) + 8);
return;
}
}
if (!totlen)
totlen = cio_numbytesleft(cio) + 8;
@@ -1478,7 +1591,13 @@ static void j2k_read_sod(opj_j2k_t *j2k) {
}
data = j2k->tile_data[curtileno];
data_ptr = data; /* store in case of failure */
data = (unsigned char*) opj_realloc(data, (j2k->tile_len[curtileno] + len) * sizeof(unsigned char));
if( data == NULL ) {
opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not reallocated\n" );
opj_free( data_ptr );
return;
}
data_ptr = data + j2k->tile_len[curtileno];
for (i = 0; i < len; i++) {
@@ -1518,8 +1637,10 @@ static void j2k_read_rgn(opj_j2k_t *j2k) {
int numcomps = j2k->image->numcomps;
len = cio_read(cio, 2); /* Lrgn */
(void)len;
compno = cio_read(cio, numcomps <= 256 ? 1 : 2); /* Crgn */
roisty = cio_read(cio, 1); /* Srgn */
(void)roisty;
#ifdef USE_JPWL
if (j2k->cp->correct) {
@@ -1536,6 +1657,13 @@ static void j2k_read_rgn(opj_j2k_t *j2k) {
};
#endif /* USE_JPWL */
if (compno >= numcomps) {
opj_event_msg(j2k->cinfo, EVT_ERROR,
"bad component number in RGN (%d out of a maximum of %d)\n",
compno, j2k->image->numcomps);
return;
}
tcp->tccps[compno].roishift = cio_read(cio, 1); /* SPrgn */
}
@@ -1554,7 +1682,7 @@ static void j2k_write_eoc(opj_j2k_t *j2k) {
static void j2k_read_eoc(opj_j2k_t *j2k) {
int i, tileno;
opj_bool success;
opj_bool success = OPJ_FALSE;
/* if packets should be decoded */
if (j2k->cp->limit_decoding != DECODE_ALL_BUT_PACKETS) {
@@ -1562,11 +1690,17 @@ static void j2k_read_eoc(opj_j2k_t *j2k) {
tcd_malloc_decode(tcd, j2k->image, j2k->cp);
for (i = 0; i < j2k->cp->tileno_size; i++) {
tcd_malloc_decode_tile(tcd, j2k->image, j2k->cp, i, j2k->cstr_info);
tileno = j2k->cp->tileno[i];
success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info);
opj_free(j2k->tile_data[tileno]);
j2k->tile_data[tileno] = NULL;
tcd_free_decode_tile(tcd, i);
if (j2k->cp->tileno[i] != -1)
{
tileno = j2k->cp->tileno[i];
success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info);
assert( tileno != -1 );
opj_free(j2k->tile_data[tileno]);
j2k->tile_data[tileno] = NULL;
tcd_free_decode_tile(tcd, i);
}
else
success = OPJ_FALSE;
if (success == OPJ_FALSE) {
j2k->state |= J2K_STATE_ERR;
break;
@@ -1737,6 +1871,17 @@ void j2k_destroy_decompress(opj_j2k_t *j2k) {
opj_free(j2k->tile_len);
}
if(j2k->tile_data != NULL) {
if(j2k->cp != NULL) {
for (i = 0; i < j2k->cp->tileno_size; i++) {
int tileno = j2k->cp->tileno[i];
if( tileno != -1 )
{
opj_free(j2k->tile_data[tileno]);
j2k->tile_data[tileno] = NULL;
}
}
}
opj_free(j2k->tile_data);
}
if(j2k->default_tcp != NULL) {
@@ -1856,9 +2001,15 @@ opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *c
#endif /* USE_JPWL */
if (id >> 8 != 0xff) {
opj_image_destroy(image);
opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
return 0;
if(cio_numbytesleft(cio) != 0) /* not end of file reached and no EOC */
{
opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
opj_image_destroy(image);
return 0;
}
opj_event_msg(cinfo, EVT_WARNING, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
j2k->state = J2K_STATE_NEOC;
break;
}
e = j2k_dec_mstab_lookup(id);
/* Check if the marker is known*/
@@ -1877,7 +2028,10 @@ opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *c
(*e->handler)(j2k);
}
if (j2k->state & J2K_STATE_ERR)
{
opj_image_destroy(image);
return NULL;
}
if (j2k->state == J2K_STATE_MT) {
break;
@@ -1888,6 +2042,11 @@ opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *c
}
if (j2k->state == J2K_STATE_NEOC) {
j2k_read_eoc(j2k);
/* Check one last time for errors during decoding before returning */
if (j2k->state & J2K_STATE_ERR) {
opj_image_destroy(image);
return NULL;
}
}
if (j2k->state != J2K_STATE_MT) {
@@ -1949,9 +2108,15 @@ opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestre
id = cio_read(cio, 2);
if (id >> 8 != 0xff) {
opj_image_destroy(image);
opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
return 0;
if(cio_numbytesleft(cio) != 0) /* no end of file reached and no EOC */
{
opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
opj_image_destroy(image);
return 0;
}
opj_event_msg(cinfo, EVT_WARNING, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
j2k->state = J2K_STATE_NEOC;
break;
}
e = j2k_dec_mstab_lookup(id);
if (!(j2k->state & e->states)) {

View File

@@ -30,6 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "opj_includes.h"
#include <assert.h>
/** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
/*@{*/
@@ -172,6 +173,9 @@ static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_bo
}
else if (box->length == 0) {
box->length = cio_numbytesleft(cio) + 8;
} else if (box->length < 0) {
opj_event_msg(cinfo, EVT_ERROR, "Integer overflow in box->length\n");
return OPJ_FALSE; /* TODO: actually check jp2_read_boxhdr's return value */
}
return OPJ_TRUE;
@@ -206,7 +210,10 @@ static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if(jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
if (JP2_IHDR != box.type) {
opj_event_msg(cinfo, EVT_ERROR, "Expected IHDR Marker\n");
return OPJ_FALSE;
@@ -279,7 +286,10 @@ static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
if (JP2_BPCC != box.type) {
opj_event_msg(cinfo, EVT_ERROR, "Expected BPCC Marker\n");
return OPJ_FALSE;
@@ -469,7 +479,7 @@ static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio,
for(i = 0; i < nr_channels; ++i)
{
/* Cji */
*entries++ = cio_read(cio, channel_size[i]>>3);
*entries++ = cio_read(cio, (channel_size[i]+7)>>3);
}
}
@@ -512,10 +522,8 @@ static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio,
static void jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color)
{
opj_jp2_cdef_info_t *info;
int color_space;
unsigned short i, n, cn, typ, asoc, acn;
color_space = image->color_space;
info = color->jp2_cdef->info;
n = color->jp2_cdef->n;
@@ -525,6 +533,7 @@ static void jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color)
if((asoc = info[i].asoc) == 0) continue;
cn = info[i].cn; typ = info[i].typ; acn = asoc - 1;
(void)typ;
if(cn != acn)
{
@@ -639,90 +648,173 @@ opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color)
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
do
{
if (JP2_JP2H != box.type)
{
if (box.type == JP2_JP2C)
{
opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
return OPJ_FALSE;
}
cio_skip(cio, box.length - 8);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
do {
if (JP2_JP2H != box.type)
{
if (box.type == JP2_JP2C)
{
opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
return OPJ_FALSE;
}
if (box.length <= 8) return OPJ_FALSE;
cio_skip(cio, box.length - 8);
if(cio->bp >= cio->end) return OPJ_FALSE;
if(cio->bp >= cio->end) return OPJ_FALSE;
jp2_read_boxhdr(cinfo, cio, &box);
}
} while(JP2_JP2H != box.type);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
}
} while(JP2_JP2H != box.type);
if (!jp2_read_ihdr(jp2, cio))
return OPJ_FALSE;
jp2h_end = box.init_pos + box.length;
if (jp2->bpc == 255)
{
if (!jp2_read_bpcc(jp2, cio))
return OPJ_FALSE;
}
jp2_read_boxhdr(cinfo, cio, &box);
if (jp2->bpc == 255)
{
if (!jp2_read_bpcc(jp2, cio))
return OPJ_FALSE;
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
while(cio_tell(cio) < jp2h_end)
{
if(box.type == JP2_COLR)
{
if( !jp2_read_colr(jp2, cio, &box, color))
{
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
jp2_read_boxhdr(cinfo, cio, &box);
continue;
}
while(cio_tell(cio) < jp2h_end)
{
if(box.type == JP2_COLR)
{
if( !jp2_read_colr(jp2, cio, &box, color))
{
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
continue;
}
if(box.type == JP2_CDEF && !jp2->ignore_pclr_cmap_cdef)
{
if( !jp2_read_cdef(jp2, cio, &box, color))
{
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
jp2_read_boxhdr(cinfo, cio, &box);
continue;
}
{
if( !jp2_read_cdef(jp2, cio, &box, color))
{
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
continue;
}
if(box.type == JP2_PCLR && !jp2->ignore_pclr_cmap_cdef)
{
if( !jp2_read_pclr(jp2, cio, &box, color))
{
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
jp2_read_boxhdr(cinfo, cio, &box);
continue;
}
{
if( !jp2_read_pclr(jp2, cio, &box, color))
{
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
continue;
}
if(box.type == JP2_CMAP && !jp2->ignore_pclr_cmap_cdef)
{
if( !jp2_read_cmap(jp2, cio, &box, color))
{
{
if( !jp2_read_cmap(jp2, cio, &box, color))
{
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
continue;
}
if (box.length <= 8) return OPJ_FALSE;
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
}
jp2_read_boxhdr(cinfo, cio, &box);
continue;
}
cio_seek(cio, box.init_pos + 8);
cio_skip(cio, box.length - 8);
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
}/* while(cio_tell(cio) < box_end) */
}/* while(cio_tell(cio) < box_end) */
cio_seek(cio, jp2h_end);
cio_seek(cio, jp2h_end);
/* Part 1, I.5.3.3 : 'must contain at least one' */
return (color->jp2_has_colr == 1);
/* Part 1, I.5.3.3 : 'must contain at least one' */
return (color->jp2_has_colr == 1);
}/* jp2_read_jp2h() */
static opj_bool opj_jp2_check_color(opj_image_t *image, opj_jp2_color_t *color, opj_common_ptr cinfo)
{
int i;
/* testcase 4149.pdf.SIGSEGV.cf7.3501 */
if (color->jp2_cdef) {
opj_jp2_cdef_info_t *info = color->jp2_cdef->info;
int n = color->jp2_cdef->n;
for (i = 0; i < n; i++) {
if (info[i].cn >= image->numcomps) {
opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].cn, image->numcomps);
return OPJ_FALSE;
}
if (info[i].asoc > 0 && (info[i].asoc - 1) >= image->numcomps) {
opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].asoc - 1, image->numcomps);
return OPJ_FALSE;
}
}
}
/* testcases 451.pdf.SIGSEGV.f4c.3723, 451.pdf.SIGSEGV.5b5.3723 and
66ea31acbb0f23a2bbc91f64d69a03f5_signal_sigsegv_13937c0_7030_5725.pdf */
if (color->jp2_pclr && color->jp2_pclr->cmap) {
int nr_channels = color->jp2_pclr->nr_channels;
opj_jp2_cmap_comp_t *cmap = color->jp2_pclr->cmap;
opj_bool *pcol_usage, is_sane = OPJ_TRUE;
/* verify that all original components match an existing one */
for (i = 0; i < nr_channels; i++) {
if (cmap[i].cmp >= image->numcomps) {
opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", cmap[i].cmp, image->numcomps);
is_sane = OPJ_FALSE;
}
}
pcol_usage = opj_calloc(nr_channels, sizeof(opj_bool));
if (!pcol_usage) {
opj_event_msg(cinfo, EVT_ERROR, "Unexpected OOM.\n");
return OPJ_FALSE;
}
/* verify that no component is targeted more than once */
for (i = 0; i < nr_channels; i++) {
int pcol = cmap[i].pcol;
assert(cmap[i].mtyp == 0 || cmap[i].mtyp == 1);
if (pcol >= nr_channels) {
opj_event_msg(cinfo, EVT_ERROR, "Invalid component/palette index for direct mapping %d.\n", pcol);
is_sane = OPJ_FALSE;
}
else if (pcol_usage[pcol] && cmap[i].mtyp == 1) {
opj_event_msg(cinfo, EVT_ERROR, "Component %d is mapped twice.\n", pcol);
is_sane = OPJ_FALSE;
}
else if (cmap[i].mtyp == 0 && cmap[i].pcol != 0) {
/* I.5.3.5 PCOL: If the value of the MTYP field for this channel is 0, then
* the value of this field shall be 0. */
opj_event_msg(cinfo, EVT_ERROR, "Direct use at #%d however pcol=%d.\n", i, pcol);
is_sane = OPJ_FALSE;
}
else
pcol_usage[pcol] = OPJ_TRUE;
}
/* verify that all components are targeted at least once */
for (i = 0; i < nr_channels; i++) {
if (!pcol_usage[i] && cmap[i].mtyp != 0) {
opj_event_msg(cinfo, EVT_ERROR, "Component %d doesn't have a mapping.\n", i);
is_sane = OPJ_FALSE;
}
}
opj_free(pcol_usage);
if (!is_sane) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio,
opj_codestream_info_t *cstr_info)
{
@@ -756,6 +848,10 @@ opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio,
}
if (!jp2->ignore_pclr_cmap_cdef){
if (!opj_jp2_check_color(image, &color, cinfo)) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to decode PCRL box\n");
return NULL;
}
/* Set Image Color Space */
if (jp2->enumcs == 16)
@@ -839,8 +935,10 @@ static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
if (JP2_FTYP != box.type) {
opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
return OPJ_FALSE;
@@ -849,6 +947,14 @@ static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
jp2->brand = cio_read(cio, 4); /* BR */
jp2->minversion = cio_read(cio, 4); /* MinV */
jp2->numcl = (box.length - 16) / 4;
/* edf_c2_1673169.jp2 */
if (cio_numbytesleft(cio) < ((int)jp2->numcl * 4)) {
opj_event_msg(cinfo, EVT_ERROR, "Not enough bytes in FTYP Box "
"(expected %d, but only %d left)\n",
((int)jp2->numcl * 4), cio_numbytesleft(cio));
return OPJ_FALSE;
}
jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
for (i = 0; i < (int)jp2->numcl; i++) {
@@ -897,15 +1003,20 @@ static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
do {
if(JP2_JP2C != box.type) {
if (box.length <= 8) return OPJ_FALSE;
cio_skip(cio, box.length - 8);
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
}
} while(JP2_JP2C != box.type);
*j2k_codestream_offset = cio_tell(cio);
if (box.length <= 8) return OPJ_FALSE;
*j2k_codestream_length = box.length - 8;
return OPJ_TRUE;
@@ -930,7 +1041,10 @@ static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
opj_common_ptr cinfo = jp2->cinfo;
jp2_read_boxhdr(cinfo, cio, &box);
if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
return OPJ_FALSE;
}
if (JP2_JP != box.type) {
opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
return OPJ_FALSE;
@@ -1070,6 +1184,7 @@ void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
if(jp2) {
memset(jp2, 0, sizeof(opj_jp2_t));
jp2->cinfo = cinfo;
/* create the J2K codec */
jp2->j2k = j2k_create_compress(cinfo);

View File

@@ -135,6 +135,10 @@ typedef enum COLOR_SPACE {
CLRSPC_SYCC = 3 /**< YUV */
} OPJ_COLOR_SPACE;
#define ENUMCS_SRGB 16
#define ENUMCS_GRAY 17
#define ENUMCS_SYCC 18
/**
Supported codec
*/

View File

@@ -3,7 +3,7 @@
* the endian check is a blender define */
/* create config.h for CMake */
#define PACKAGE_VERSION "1.5.0"
#define PACKAGE_VERSION "1.5.2"
#define HAVE_INTTYPES_H
#define HAVE_MEMORY_H
@@ -23,6 +23,7 @@
/* #undef HAVE_LIBLCMS2 */
/* #undef HAVE_LCMS1_H */
/* #undef HAVE_LCMS2_H */
/* #undef USE_SYSTEM_GETOPT */
/* Byte order. */
/* All compilers that support Mac OS X define either __BIG_ENDIAN__ or

View File

@@ -89,18 +89,17 @@ Most compilers implement their own version of this keyword ...
/* MSVC and Borland C do not have lrintf */
#if defined(_MSC_VER) || defined(__BORLANDC__)
static INLINE long lrintf(float f){
#ifdef _M_X64
return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f));
#else
int i;
#ifdef _M_IX86
long int i;
_asm{
fld f
fistp i
};
return i;
#endif
#else
return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f));
#endif /* _M_IX86 */
}
#endif

View File

@@ -83,8 +83,10 @@ Allocate memory aligned to a 16 byte boundry
#else /* Not _WIN32 */
#if defined(__sun)
#define HAVE_MEMALIGN
#elif defined(__FreeBSD__)
#define HAVE_POSIX_MEMALIGN
/* Linux x86_64 and OSX always align allocations to 16 bytes */
#elif !defined(__amd64__) && !defined(__APPLE__)
#elif !defined(__amd64__) && !defined(__APPLE__) && !defined(_AIX)
#define HAVE_MEMALIGN
#include <malloc.h>
#endif

View File

@@ -1,13 +0,0 @@
Index: extern/libopenjpeg/opj_malloc.h
===================================================================
--- extern/libopenjpeg/opj_malloc.h (revision 27736)
+++ extern/libopenjpeg/opj_malloc.h (working copy)
@@ -76,7 +76,7 @@
#if defined(__sun)
#define HAVE_MEMALIGN
#elif defined(__GNUC__)
- #ifndef __APPLE__
+ #if !defined(__APPLE__) && !defined(__FreeBSD__)
#define HAVE_MEMALIGN
#include <malloc.h>
#endif

View File

@@ -1,17 +0,0 @@
Index: opj_malloc.h
===================================================================
--- opj_malloc.h (revision 15089)
+++ opj_malloc.h (working copy)
@@ -76,8 +76,10 @@
#if defined(__sun)
#define HAVE_MEMALIGN
#elif defined(__GNUC__)
- #define HAVE_MEMALIGN
- #include <malloc.h>
+ #ifndef __APPLE__
+ #define HAVE_MEMALIGN
+ #include <malloc.h>
+ #endif
/* Linux x86_64 and OSX always align allocations to 16 bytes */
#elif !defined(__amd64__) && !defined(__APPLE__)
/* FIXME: Yes, this is a big assumption */

View File

@@ -1577,6 +1577,7 @@ void t1_decode_cblks(
opj_free(cblk->segs);
} /* cblkno */
opj_free(precinct->cblks.dec);
precinct->cblks.dec = NULL;
} /* precno */
} /* bandno */
} /* resno */

View File

@@ -30,6 +30,7 @@
*/
#include "opj_includes.h"
#include <assert.h>
/** @defgroup T2 T2 - Implementation of a tier-2 coding */
/*@{*/
@@ -64,7 +65,7 @@ static int t2_encode_packet(opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterato
@param cblksty
@param first
*/
static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first);
static opj_bool t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first);
/**
Decode a packet of a tile from a source buffer
@param t2 T2 handle
@@ -296,9 +297,17 @@ static int t2_encode_packet(opj_tcd_tile_t * tile, opj_tcp_t * tcp, opj_pi_itera
return (c - dest);
}
static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first) {
static opj_bool t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first) {
opj_tcd_seg_t* seg;
cblk->segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, (index + 1) * sizeof(opj_tcd_seg_t));
opj_tcd_seg_t* segs;
segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, (index + 1) * sizeof(opj_tcd_seg_t));
if (segs == NULL)
{
return OPJ_FALSE;
}
cblk->segs = segs;
seg = &cblk->segs[index];
seg->data = NULL;
seg->dataindex = 0;
@@ -316,6 +325,8 @@ static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int fi
} else {
seg->maxpasses = 109;
}
return OPJ_TRUE;
}
static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile,
@@ -330,13 +341,15 @@ static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_t
int precno = pi->precno; /* precinct value */
int layno = pi->layno; /* quality layer value */
opj_tcd_resolution_t* res = &tile->comps[compno].resolutions[resno];
unsigned char *hd = NULL;
int present;
opj_bio_t *bio = NULL; /* BIO component */
opj_tcd_resolution_t* res;
assert(&tile->comps[compno] != NULL);
res = &tile->comps[compno].resolutions[resno];
if (layno == 0) {
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
@@ -462,12 +475,22 @@ static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_t
cblk->numlenbits += increment;
segno = 0;
if (!cblk->numsegs) {
t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 1);
if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 1))
{
opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
bio_destroy(bio);
return -999;
}
} else {
segno = cblk->numsegs - 1;
if (cblk->segs[segno].numpasses == cblk->segs[segno].maxpasses) {
++segno;
t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0);
if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0))
{
opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
bio_destroy(bio);
return -999;
}
}
}
n = cblk->numnewpasses;
@@ -478,7 +501,12 @@ static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_t
n -= cblk->segs[segno].numnewpasses;
if (n > 0) {
++segno;
t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0);
if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0))
{
opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
bio_destroy(bio);
return -999;
}
}
} while (n > 0);
}
@@ -714,7 +742,11 @@ int t2_decode_packets(opj_t2_t *t2, unsigned char *src, int len, int tileno, opj
} else {
e = 0;
}
if(e == -999) return -999;
if(e == -999)
{
pi_destroy(pi, cp, tileno);
return -999;
}
/* progression in resolution */
image->comps[pi[pino].compno].resno_decoded =
(e > 0) ?

View File

@@ -30,7 +30,9 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#define _ISOC99_SOURCE /* lrintf is C99 */
#include "opj_includes.h"
#include <assert.h>
void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img) {
int tileno, compno, resno, bandno, precno;/*, cblkno;*/
@@ -249,7 +251,9 @@ void tcd_malloc_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int c
cbgwidthexpn = pdx - 1;
cbgheightexpn = pdy - 1;
}
(void)brcbgyend;
(void)brcbgxend;
cblkwidthexpn = int_min(tccp->cblkw, cbgwidthexpn);
cblkheightexpn = int_min(tccp->cblkh, cbgheightexpn);
@@ -333,8 +337,10 @@ void tcd_malloc_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int c
cblk->y0 = int_max(cblkystart, prc->y0);
cblk->x1 = int_min(cblkxend, prc->x1);
cblk->y1 = int_min(cblkyend, prc->y1);
cblk->data = (unsigned char*) opj_calloc(8192+2, sizeof(unsigned char));
cblk->data = (unsigned char*) opj_calloc(9728+2, sizeof(unsigned char));
/* FIXME: mqc_init_enc and mqc_byteout underrun the buffer if we don't do this. Why? */
cblk->data[0] = 0;
cblk->data[1] = 0;
cblk->data += 2;
cblk->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t));
cblk->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t));
@@ -509,6 +515,8 @@ void tcd_init_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int cur
cbgwidthexpn = pdx - 1;
cbgheightexpn = pdy - 1;
}
(void)brcbgyend;
(void)brcbgxend;
cblkwidthexpn = int_min(tccp->cblkw, cbgwidthexpn);
cblkheightexpn = int_min(tccp->cblkh, cbgheightexpn);
@@ -594,6 +602,8 @@ void tcd_init_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int cur
cblk->y1 = int_min(cblkyend, prc->y1);
cblk->data = (unsigned char*) opj_calloc(8192+2, sizeof(unsigned char));
/* FIXME: mqc_init_enc and mqc_byteout underrun the buffer if we don't do this. Why? */
cblk->data[0] = 0;
cblk->data[1] = 0;
cblk->data += 2;
cblk->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t));
cblk->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t));
@@ -614,7 +624,7 @@ void tcd_malloc_decode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp) {
tcd->image = image;
tcd->tcd_image->tw = cp->tw;
tcd->tcd_image->th = cp->th;
tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tcd_tile_t));
tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(cp->tw * cp->th, sizeof(opj_tcd_tile_t));
/*
Allocate place to store the decoded data = final image
@@ -690,6 +700,12 @@ void tcd_malloc_decode_tile(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp,
opj_tccp_t *tccp = &tcp->tccps[compno];
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
if (tccp->numresolutions <= 0)
{
cp->tileno[tileno] = -1;
return;
}
/* border of each tile component (global) */
tilec->x0 = int_ceildiv(tile->x0, image->comps[compno].dx);
tilec->y0 = int_ceildiv(tile->y0, image->comps[compno].dy);
@@ -749,6 +765,8 @@ void tcd_malloc_decode_tile(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp,
cbgwidthexpn = pdx - 1;
cbgheightexpn = pdy - 1;
}
(void)brcbgyend;
(void)brcbgxend;
cblkwidthexpn = int_min(tccp->cblkw, cbgwidthexpn);
cblkheightexpn = int_min(tccp->cblkh, cbgheightexpn);
@@ -1370,16 +1388,31 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
if (l == -999) {
eof = 1;
opj_event_msg(tcd->cinfo, EVT_ERROR, "tcd_decode: incomplete bistream\n");
return OPJ_FALSE;
}
/*------------------TIER1-----------------*/
t1_time = opj_clock(); /* time needed to decode a tile */
t1 = t1_create(tcd->cinfo);
if (t1 == NULL)
{
opj_event_msg(tcd->cinfo, EVT_ERROR, "Out of memory\n");
t1_destroy(t1);
return OPJ_FALSE;
}
for (compno = 0; compno < tile->numcomps; ++compno) {
opj_tcd_tilecomp_t* tilec = &tile->comps[compno];
/* The +3 is headroom required by the vectorized DWT */
tilec->data = (int*) opj_aligned_malloc((((tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0))+3) * sizeof(int));
if (tilec->data == NULL)
{
opj_event_msg(tcd->cinfo, EVT_ERROR, "Out of memory\n");
t1_destroy(t1);
return OPJ_FALSE;
}
t1_decode_cblks(t1, tilec, &tcd->tcp->tccps[compno]);
}
t1_destroy(t1);
@@ -1394,13 +1427,15 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
int numres2decode;
if (tcd->cp->reduce != 0) {
tcd->image->comps[compno].resno_decoded =
tile->comps[compno].numresolutions - tcd->cp->reduce - 1;
if (tcd->image->comps[compno].resno_decoded < 0) {
if ( tile->comps[compno].numresolutions < ( tcd->cp->reduce - 1 ) ) {
opj_event_msg(tcd->cinfo, EVT_ERROR, "Error decoding tile. The number of resolutions to remove [%d+1] is higher than the number "
" of resolutions in the original codestream [%d]\nModify the cp_reduce parameter.\n", tcd->cp->reduce, tile->comps[compno].numresolutions);
return OPJ_FALSE;
}
else {
tcd->image->comps[compno].resno_decoded =
tile->comps[compno].numresolutions - tcd->cp->reduce - 1;
}
}
numres2decode = tcd->image->comps[compno].resno_decoded + 1;
@@ -1421,6 +1456,13 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
int n = (tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0);
if (tile->numcomps >= 3 ){
/* testcase 1336.pdf.asan.47.376 */
if ((tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0) < n ||
( tile->comps[1].x1 - tile->comps[1].x0) * (tile->comps[1].y1 - tile->comps[1].y0) < n ||
( tile->comps[2].x1 - tile->comps[2].x0) * (tile->comps[2].y1 - tile->comps[2].y0) < n) {
opj_event_msg(tcd->cinfo, EVT_ERROR, "Tiles don't all have the same dimension. Skip the MCT step.\n");
return OPJ_FALSE;
}
if (tcd->tcp->tccps[0].qmfbid == 1) {
mct_decode(
tile->comps[0].data,
@@ -1452,18 +1494,33 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
int tw = tilec->x1 - tilec->x0;
int w = imagec->w;
int i, j;
int offset_x = int_ceildivpow2(imagec->x0, imagec->factor);
int offset_y = int_ceildivpow2(imagec->y0, imagec->factor);
/* NR-DEC-2977.pdf.asan.67.2198.jp2-52-decode */
if( res->x0 - offset_x < 0 || res->x1 - offset_x < 0
|| res->y0 - offset_y < 0 || res->y1 - offset_y < 0 )
{
opj_event_msg(tcd->cinfo, EVT_ERROR, "Impossible offsets %d / %d\n", offset_x, offset_y);
return OPJ_FALSE;
}
assert( 0 <= res->x0 - offset_x && 0 <= res->x1 - offset_x );
assert( 0 <= res->y0 - offset_y && 0 <= res->y1 - offset_y );
int i, j;
if(!imagec->data){
imagec->data = (int*) opj_malloc(imagec->w * imagec->h * sizeof(int));
}
if (!imagec->data)
{
opj_event_msg(tcd->cinfo, EVT_ERROR, "Out of memory\n");
return OPJ_FALSE;
}
if(tcd->tcp->tccps[compno].qmfbid == 1) {
for(j = res->y0; j < res->y1; ++j) {
for(i = res->x0; i < res->x1; ++i) {
int v = tilec->data[i - res->x0 + (j - res->y0) * tw];
v += adjust;
/*assert( (i - offset_x) + (j - offset_y) * w >= 0 );*/
imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max);
}
}
@@ -1473,6 +1530,7 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
float tmp = ((float*)tilec->data)[i - res->x0 + (j - res->y0) * tw];
int v = lrintf(tmp);
v += adjust;
/*assert( (i - offset_x) + (j - offset_y) * w >= 0 );*/
imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max);
}
}
@@ -1492,32 +1550,51 @@ opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno
void tcd_free_decode(opj_tcd_t *tcd) {
opj_tcd_image_t *tcd_image = tcd->tcd_image;
int i = 0;
for (i = 0; i < tcd_image->tw * tcd_image->th; i++)
{
tcd_free_decode_tile(tcd, i);
}
opj_free(tcd_image->tiles);
}
void tcd_free_decode_tile(opj_tcd_t *tcd, int tileno) {
int compno,resno,bandno,precno;
int compno,resno,bandno,precno,cblkno;
opj_tcd_image_t *tcd_image = tcd->tcd_image;
opj_tcd_tile_t *tile = &tcd_image->tiles[tileno];
for (compno = 0; compno < tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
for (precno = 0; precno < res->ph * res->pw; precno++) {
opj_tcd_precinct_t *prec = &band->precincts[precno];
if (prec->imsbtree != NULL) tgt_destroy(prec->imsbtree);
if (prec->incltree != NULL) tgt_destroy(prec->incltree);
if (tile->comps != NULL) {
for (compno = 0; compno < tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
for (precno = 0; precno < res->ph * res->pw; precno++) {
opj_tcd_precinct_t *prec = &band->precincts[precno];
if (prec->cblks.dec != NULL) {
for (cblkno = 0; cblkno < prec->cw * prec->ch; ++cblkno) {
opj_tcd_cblk_dec_t* cblk = &prec->cblks.dec[cblkno];
opj_free(cblk->data);
opj_free(cblk->segs);
}
opj_free(prec->cblks.dec);
}
if (prec->imsbtree != NULL) tgt_destroy(prec->imsbtree);
if (prec->incltree != NULL) tgt_destroy(prec->incltree);
}
opj_free(band->precincts);
}
opj_free(band->precincts);
}
opj_free(tilec->resolutions);
}
opj_free(tilec->resolutions);
opj_free(tile->comps);
tile->comps = NULL;
}
opj_free(tile->comps);
}

View File

@@ -1919,11 +1919,10 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize
static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
{
UInt32 beforeSize = kNumOpts;
Bool btMode;
if (!RangeEnc_Alloc(&p->rc, alloc))
return SZ_ERROR_MEM;
btMode = (p->matchFinderBase.btMode != 0);
#ifdef COMPRESS_MF_MT
Bool btMode = (p->matchFinderBase.btMode != 0);;
p->mtMode = (p->multiThread && !p->fastMode && btMode);
#endif

5
extern/rangetree/README.blender vendored Normal file
View File

@@ -0,0 +1,5 @@
Project: RangeTree
URL: https://github.com/nicholasbishop/RangeTree
License: GPLv2+
Upstream version: c4ecf6bb7dfd
Local modifications: None

View File

@@ -23,9 +23,11 @@
#
# ***** END GPL LICENSE BLOCK *****
remove_cc_flag_unsigned_char()
set(INC
Recast/Include
Detour/Include
Recast/Include
Detour/Include
)
set(INC_SYS
@@ -33,38 +35,38 @@ set(INC_SYS
)
set(SRC
recast-capi.cpp
recast-capi.h
recast-capi.cpp
recast-capi.h
Detour/Source/DetourCommon.cpp
Detour/Source/DetourNode.cpp
Detour/Source/DetourStatNavMesh.cpp
Detour/Source/DetourStatNavMeshBuilder.cpp
Detour/Source/DetourTileNavMesh.cpp
Detour/Source/DetourTileNavMeshBuilder.cpp
Detour/Source/DetourCommon.cpp
Detour/Source/DetourNode.cpp
Detour/Source/DetourStatNavMesh.cpp
Detour/Source/DetourStatNavMeshBuilder.cpp
Detour/Source/DetourTileNavMesh.cpp
Detour/Source/DetourTileNavMeshBuilder.cpp
Detour/Include/DetourCommon.h
Detour/Include/DetourNode.h
Detour/Include/DetourStatNavMesh.h
Detour/Include/DetourStatNavMeshBuilder.h
Detour/Include/DetourTileNavMesh.h
Detour/Include/DetourTileNavMeshBuilder.h
Detour/Include/DetourCommon.h
Detour/Include/DetourNode.h
Detour/Include/DetourStatNavMesh.h
Detour/Include/DetourStatNavMeshBuilder.h
Detour/Include/DetourTileNavMesh.h
Detour/Include/DetourTileNavMeshBuilder.h
Recast/Source/Recast.cpp
Recast/Source/RecastAlloc.cpp
Recast/Source/RecastArea.cpp
Recast/Source/RecastContour.cpp
Recast/Source/RecastFilter.cpp
Recast/Source/RecastLayers.cpp
Recast/Source/RecastMesh.cpp
Recast/Source/RecastMeshDetail.cpp
Recast/Source/RecastRasterization.cpp
Recast/Source/RecastRegion.cpp
Recast/Source/Recast.cpp
Recast/Source/RecastAlloc.cpp
Recast/Source/RecastArea.cpp
Recast/Source/RecastContour.cpp
Recast/Source/RecastFilter.cpp
Recast/Source/RecastLayers.cpp
Recast/Source/RecastMesh.cpp
Recast/Source/RecastMeshDetail.cpp
Recast/Source/RecastRasterization.cpp
Recast/Source/RecastRegion.cpp
Recast/Include/Recast.h
Recast/Include/RecastAlloc.h
Recast/Include/RecastAssert.h
Recast/Include/Recast.h
Recast/Include/RecastAlloc.h
Recast/Include/RecastAssert.h
)
blender_add_lib(extern_recastnavigation "${SRC}" "${INC}" "${INC_SYS}")

File diff suppressed because it is too large Load Diff

View File

@@ -19,6 +19,8 @@
#ifndef RECASTALLOC_H
#define RECASTALLOC_H
#include <stddef.h>
/// Provides hint values to the memory allocator on how long the
/// memory is expected to be used.
enum rcAllocHint
@@ -28,30 +30,32 @@ enum rcAllocHint
};
/// A memory allocation function.
// @param[in] size The size, in bytes of memory, to allocate.
// @param[in] rcAllocHint A hint to the allocator on how long the memory is expected to be in use.
// @param[in] size The size, in bytes of memory, to allocate.
// @param[in] rcAllocHint A hint to the allocator on how long the memory is expected to be in use.
// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
/// @see rcAllocSetCustom
typedef void* (rcAllocFunc)(int size, rcAllocHint hint);
typedef void* (rcAllocFunc)(size_t size, rcAllocHint hint);
/// A memory deallocation function.
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAllocFunc.
/// @see rcAllocSetCustom
// @param[in] ptr
typedef void (rcFreeFunc)(void* ptr);
/// Sets the base custom allocation functions to be used by Recast.
/// @param[in] allocFunc The memory allocation function to be used by #rcAlloc
/// @param[in] freeFunc The memory de-allocation function to be used by #rcFree
/// @param[in] allocFunc The memory allocation function to be used by #rcAlloc
/// @param[in] freeFunc The memory de-allocation function to be used by #rcFree
void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc);
/// Allocates a memory block.
/// @param[in] size The size, in bytes of memory, to allocate.
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
/// @param[in] size The size, in bytes of memory, to allocate.
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
void* rcAlloc(int size, rcAllocHint hint);
/// @see rcFree
void* rcAlloc(size_t size, rcAllocHint hint);
/// Deallocates a memory block.
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAlloc.
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAlloc.
/// @see rcAlloc
void rcFree(void* ptr);
@@ -60,42 +64,58 @@ class rcIntArray
{
int* m_data;
int m_size, m_cap;
inline rcIntArray(const rcIntArray&);
inline rcIntArray& operator=(const rcIntArray&);
public:
void doResize(int n);
// Explicitly disabled copy constructor and copy assignment operator.
rcIntArray(const rcIntArray&);
rcIntArray& operator=(const rcIntArray&);
public:
/// Constructs an instance with an initial array size of zero.
inline rcIntArray() : m_data(0), m_size(0), m_cap(0) {}
rcIntArray() : m_data(0), m_size(0), m_cap(0) {}
/// Constructs an instance initialized to the specified size.
/// @param[in] n The initial size of the integer array.
inline rcIntArray(int n) : m_data(0), m_size(0), m_cap(0) { resize(n); }
inline ~rcIntArray() { rcFree(m_data); }
/// @param[in] n The initial size of the integer array.
rcIntArray(int n) : m_data(0), m_size(0), m_cap(0) { resize(n); }
~rcIntArray() { rcFree(m_data); }
/// Specifies the new size of the integer array.
/// @param[in] n The new size of the integer array.
void resize(int n);
/// @param[in] n The new size of the integer array.
void resize(int n)
{
if (n > m_cap)
doResize(n);
m_size = n;
}
/// Push the specified integer onto the end of the array and increases the size by one.
/// @param[in] item The new value.
inline void push(int item) { resize(m_size+1); m_data[m_size-1] = item; }
/// @param[in] item The new value.
void push(int item) { resize(m_size+1); m_data[m_size-1] = item; }
/// Returns the value at the end of the array and reduces the size by one.
/// @return The value at the end of the array.
inline int pop() { if (m_size > 0) m_size--; return m_data[m_size]; }
int pop()
{
if (m_size > 0)
m_size--;
return m_data[m_size];
}
/// The value at the specified array index.
/// @warning Does not provide overflow protection.
/// @param[in] i The index of the value.
inline const int& operator[](int i) const { return m_data[i]; }
/// @param[in] i The index of the value.
const int& operator[](int i) const { return m_data[i]; }
/// The value at the specified array index.
/// @warning Does not provide overflow protection.
/// @param[in] i The index of the value.
inline int& operator[](int i) { return m_data[i]; }
/// @param[in] i The index of the value.
int& operator[](int i) { return m_data[i]; }
/// The current size of the integer array.
inline int size() const { return m_size; }
int size() const { return m_size; }
};
/// A simple helper class used to delete an array when it goes out of scope.
@@ -110,13 +130,18 @@ public:
inline rcScopedDelete() : ptr(0) {}
/// Constructs an instance with the specified pointer.
/// @param[in] p An pointer to an allocated array.
/// @param[in] p An pointer to an allocated array.
inline rcScopedDelete(T* p) : ptr(p) {}
inline ~rcScopedDelete() { rcFree(ptr); }
/// The root array pointer.
/// @return The root array pointer.
inline operator T*() { return ptr; }
private:
// Explicitly disabled copy constructor and copy assignment operator.
rcScopedDelete(const rcScopedDelete&);
rcScopedDelete& operator=(const rcScopedDelete&);
};
#endif

View File

@@ -24,7 +24,7 @@
#ifdef NDEBUG
// From http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
# define rcAssert(x) do { (void)sizeof(x); } while((void)(__LINE__ == -1), false)
# define rcAssert(x) do { (void)sizeof(x); } while((void)(__LINE__==-1),false)
#else
# include <assert.h>
# define rcAssert assert

View File

@@ -1,80 +0,0 @@
//
// Copyright (c) 2009 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef RECAST_LOG_H
#define RECAST_LOG_H
enum rcLogCategory
{
RC_LOG_PROGRESS = 1,
RC_LOG_WARNING,
RC_LOG_ERROR,
};
class rcLog
{
public:
rcLog();
~rcLog();
void log(rcLogCategory category, const char* format, ...);
inline void clear() { m_messageCount = 0; m_textPoolSize = 0; }
inline int getMessageCount() const { return m_messageCount; }
inline char getMessageType(int i) const { return *m_messages[i]; }
inline const char* getMessageText(int i) const { return m_messages[i]+1; }
private:
static const int MAX_MESSAGES = 1000;
const char* m_messages[MAX_MESSAGES];
int m_messageCount;
static const int TEXT_POOL_SIZE = 8000;
char m_textPool[TEXT_POOL_SIZE];
int m_textPoolSize;
};
struct rcBuildTimes
{
int rasterizeTriangles;
int buildCompact;
int buildContours;
int buildContoursTrace;
int buildContoursSimplify;
int filterBorder;
int filterWalkable;
int filterMarkReachable;
int buildPolymesh;
int buildDistanceField;
int buildDistanceFieldDist;
int buildDistanceFieldBlur;
int buildRegions;
int buildRegionsReg;
int buildRegionsExp;
int buildRegionsFlood;
int buildRegionsFilter;
int buildDetailMesh;
int mergePolyMesh;
int mergePolyMeshDetail;
};
void rcSetLog(rcLog* log);
rcLog* rcGetLog();
void rcSetBuildTimes(rcBuildTimes* btimes);
rcBuildTimes* rcGetBuildTimes();
#endif // RECAST_LOG_H

View File

@@ -1,31 +0,0 @@
//
// Copyright (c) 2009 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef RECAST_TIMER_H
#define RECAST_TIMER_H
#ifdef __GNUC__
#include <stdint.h>
typedef int64_t rcTimeVal;
#else
typedef __int64 rcTimeVal;
#endif
rcTimeVal rcGetPerformanceTimer();
int rcGetDeltaTimeUsec(rcTimeVal start, rcTimeVal end);
#endif // RECAST_TIMER_H

View File

@@ -208,12 +208,11 @@ void rcCalcGridSize(const float* bmin, const float* bmax, float cs, int* w, int*
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcAllocHeightfield, rcHeightfield
bool rcCreateHeightfield(rcContext* /*ctx*/, rcHeightfield& hf, int width, int height,
bool rcCreateHeightfield(rcContext* ctx, rcHeightfield& hf, int width, int height,
const float* bmin, const float* bmax,
float cs, float ch)
{
// TODO: VC complains about unref formal variable, figure out a way to handle this better.
// rcAssert(ctx);
rcIgnoreUnused(ctx);
hf.width = width;
hf.height = height;
@@ -239,19 +238,18 @@ static void calcTriNormal(const float* v0, const float* v1, const float* v2, flo
/// @par
///
/// Only sets the aread id's for the walkable triangles. Does not alter the
/// Only sets the area id's for the walkable triangles. Does not alter the
/// area id's for unwalkable triangles.
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
void rcMarkWalkableTriangles(rcContext* /*ctx*/, const float walkableSlopeAngle,
void rcMarkWalkableTriangles(rcContext* ctx, const float walkableSlopeAngle,
const float* verts, int /*nv*/,
const int* tris, int nt,
unsigned char* areas)
{
// TODO: VC complains about unref formal variable, figure out a way to handle this better.
// rcAssert(ctx);
rcIgnoreUnused(ctx);
const float walkableThr = cosf(walkableSlopeAngle/180.0f*RC_PI);
@@ -269,19 +267,18 @@ void rcMarkWalkableTriangles(rcContext* /*ctx*/, const float walkableSlopeAngle,
/// @par
///
/// Only sets the aread id's for the unwalkable triangles. Does not alter the
/// Only sets the area id's for the unwalkable triangles. Does not alter the
/// area id's for walkable triangles.
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
void rcClearUnwalkableTriangles(rcContext* /*ctx*/, const float walkableSlopeAngle,
void rcClearUnwalkableTriangles(rcContext* ctx, const float walkableSlopeAngle,
const float* verts, int /*nv*/,
const int* tris, int nt,
unsigned char* areas)
{
// TODO: VC complains about unref formal variable, figure out a way to handle this better.
// rcAssert(ctx);
rcIgnoreUnused(ctx);
const float walkableThr = cosf(walkableSlopeAngle/180.0f*RC_PI);
@@ -297,10 +294,9 @@ void rcClearUnwalkableTriangles(rcContext* /*ctx*/, const float walkableSlopeAng
}
}
int rcGetHeightFieldSpanCount(rcContext* /*ctx*/, rcHeightfield& hf)
int rcGetHeightFieldSpanCount(rcContext* ctx, rcHeightfield& hf)
{
// TODO: VC complains about unref formal variable, figure out a way to handle this better.
// rcAssert(ctx);
rcIgnoreUnused(ctx);
const int w = hf.width;
const int h = hf.height;
@@ -322,7 +318,7 @@ int rcGetHeightFieldSpanCount(rcContext* /*ctx*/, rcHeightfield& hf)
/// @par
///
/// This is just the beginning of the process of fully building a compact heightfield.
/// Various filters may be applied applied, then the distance field and regions built.
/// Various filters may be applied, then the distance field and regions built.
/// E.g: #rcBuildDistanceField and #rcBuildRegions
///
/// See the #rcConfig documentation for more information on the configuration parameters.
@@ -333,7 +329,7 @@ bool rcBuildCompactHeightfield(rcContext* ctx, const int walkableHeight, const i
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
const int w = hf.width;
const int h = hf.height;
@@ -439,13 +435,13 @@ bool rcBuildCompactHeightfield(rcContext* ctx, const int walkableHeight, const i
if ((top - bot) >= walkableHeight && rcAbs((int)ns.y - (int)s.y) <= walkableClimb)
{
// Mark direction as walkable.
const int idx = k - (int)nc.index;
if (idx < 0 || idx > MAX_LAYERS)
const int lidx = k - (int)nc.index;
if (lidx < 0 || lidx > MAX_LAYERS)
{
tooHighNeighbour = rcMax(tooHighNeighbour, idx);
tooHighNeighbour = rcMax(tooHighNeighbour, lidx);
continue;
}
rcSetCon(s, dir, idx);
rcSetCon(s, dir, lidx);
break;
}
}
@@ -460,8 +456,6 @@ bool rcBuildCompactHeightfield(rcContext* ctx, const int walkableHeight, const i
ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Heightfield has too many layers %d (max: %d)",
tooHighNeighbour, MAX_LAYERS);
}
ctx->stopTimer(RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
return true;
}
@@ -490,4 +484,4 @@ static int getCompactHeightFieldMemoryusage(const rcCompactHeightfield& chf)
size += sizeof(rcCompactCell) * chf.width * chf.height;
return size;
}
*/
*/

View File

@@ -20,7 +20,7 @@
#include <string.h>
#include "RecastAlloc.h"
static void *rcAllocDefault(int size, rcAllocHint)
static void *rcAllocDefault(size_t size, rcAllocHint)
{
return malloc(size);
}
@@ -41,7 +41,7 @@ void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc)
}
/// @see rcAllocSetCustom
void* rcAlloc(int size, rcAllocHint hint)
void* rcAlloc(size_t size, rcAllocHint hint)
{
return sRecastAllocFunc(size, hint);
}
@@ -72,17 +72,13 @@ void rcFree(void* ptr)
/// Using this method ensures the array is at least large enough to hold
/// the specified number of elements. This can improve performance by
/// avoiding auto-resizing during use.
void rcIntArray::resize(int n)
void rcIntArray::doResize(int n)
{
if (n > m_cap)
{
if (!m_cap) m_cap = n;
while (m_cap < n) m_cap *= 2;
int* newData = (int*)rcAlloc(m_cap*sizeof(int), RC_ALLOC_TEMP);
if (m_size && newData) memcpy(newData, m_data, m_size*sizeof(int));
rcFree(m_data);
m_data = newData;
}
m_size = n;
if (!m_cap) m_cap = n;
while (m_cap < n) m_cap *= 2;
int* newData = (int*)rcAlloc(m_cap*sizeof(int), RC_ALLOC_TEMP);
if (m_size && newData) memcpy(newData, m_data, m_size*sizeof(int));
rcFree(m_data);
m_data = newData;
}

View File

@@ -41,7 +41,7 @@ bool rcErodeWalkableArea(rcContext* ctx, int radius, rcCompactHeightfield& chf)
const int w = chf.width;
const int h = chf.height;
ctx->startTimer(RC_TIMER_ERODE_AREA);
rcScopedTimer timer(ctx, RC_TIMER_ERODE_AREA);
unsigned char* dist = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
if (!dist)
@@ -75,8 +75,8 @@ bool rcErodeWalkableArea(rcContext* ctx, int radius, rcCompactHeightfield& chf)
{
const int nx = x + rcGetDirOffsetX(dir);
const int ny = y + rcGetDirOffsetY(dir);
const int ni = (int)chf.cells[nx+ny*w].index + rcGetCon(s, dir);
if (chf.areas[ni] != RC_NULL_AREA)
const int nidx = (int)chf.cells[nx+ny*w].index + rcGetCon(s, dir);
if (chf.areas[nidx] != RC_NULL_AREA)
{
nc++;
}
@@ -215,8 +215,6 @@ bool rcErodeWalkableArea(rcContext* ctx, int radius, rcCompactHeightfield& chf)
rcFree(dist);
ctx->stopTimer(RC_TIMER_ERODE_AREA);
return true;
}
@@ -245,7 +243,7 @@ bool rcMedianFilterWalkableArea(rcContext* ctx, rcCompactHeightfield& chf)
const int w = chf.width;
const int h = chf.height;
ctx->startTimer(RC_TIMER_MEDIAN_AREA);
rcScopedTimer timer(ctx, RC_TIMER_MEDIAN_AREA);
unsigned char* areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
if (!areas)
@@ -306,8 +304,6 @@ bool rcMedianFilterWalkableArea(rcContext* ctx, rcCompactHeightfield& chf)
memcpy(chf.areas, areas, sizeof(unsigned char)*chf.spanCount);
rcFree(areas);
ctx->stopTimer(RC_TIMER_MEDIAN_AREA);
return true;
}
@@ -322,7 +318,7 @@ void rcMarkBoxArea(rcContext* ctx, const float* bmin, const float* bmax, unsigne
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_BOX_AREA);
rcScopedTimer timer(ctx, RC_TIMER_MARK_BOX_AREA);
int minx = (int)((bmin[0]-chf.bmin[0])/chf.cs);
int miny = (int)((bmin[1]-chf.bmin[1])/chf.ch);
@@ -357,9 +353,6 @@ void rcMarkBoxArea(rcContext* ctx, const float* bmin, const float* bmax, unsigne
}
}
}
ctx->stopTimer(RC_TIMER_MARK_BOX_AREA);
}
@@ -391,7 +384,7 @@ void rcMarkConvexPolyArea(rcContext* ctx, const float* verts, const int nverts,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_CONVEXPOLY_AREA);
rcScopedTimer timer(ctx, RC_TIMER_MARK_CONVEXPOLY_AREA);
float bmin[3], bmax[3];
rcVcopy(bmin, verts);
@@ -448,10 +441,86 @@ void rcMarkConvexPolyArea(rcContext* ctx, const float* verts, const int nverts,
}
}
}
ctx->stopTimer(RC_TIMER_MARK_CONVEXPOLY_AREA);
}
int rcOffsetPoly(const float* verts, const int nverts, const float offset,
float* outVerts, const int maxOutVerts)
{
const float MITER_LIMIT = 1.20f;
int n = 0;
for (int i = 0; i < nverts; i++)
{
const int a = (i+nverts-1) % nverts;
const int b = i;
const int c = (i+1) % nverts;
const float* va = &verts[a*3];
const float* vb = &verts[b*3];
const float* vc = &verts[c*3];
float dx0 = vb[0] - va[0];
float dy0 = vb[2] - va[2];
float d0 = dx0*dx0 + dy0*dy0;
if (d0 > 1e-6f)
{
d0 = 1.0f/rcSqrt(d0);
dx0 *= d0;
dy0 *= d0;
}
float dx1 = vc[0] - vb[0];
float dy1 = vc[2] - vb[2];
float d1 = dx1*dx1 + dy1*dy1;
if (d1 > 1e-6f)
{
d1 = 1.0f/rcSqrt(d1);
dx1 *= d1;
dy1 *= d1;
}
const float dlx0 = -dy0;
const float dly0 = dx0;
const float dlx1 = -dy1;
const float dly1 = dx1;
float cross = dx1*dy0 - dx0*dy1;
float dmx = (dlx0 + dlx1) * 0.5f;
float dmy = (dly0 + dly1) * 0.5f;
float dmr2 = dmx*dmx + dmy*dmy;
bool bevel = dmr2 * MITER_LIMIT*MITER_LIMIT < 1.0f;
if (dmr2 > 1e-6f)
{
const float scale = 1.0f / dmr2;
dmx *= scale;
dmy *= scale;
}
if (bevel && cross < 0.0f)
{
if (n+2 >= maxOutVerts)
return 0;
float d = (1.0f - (dx0*dx1 + dy0*dy1))*0.5f;
outVerts[n*3+0] = vb[0] + (-dlx0+dx0*d)*offset;
outVerts[n*3+1] = vb[1];
outVerts[n*3+2] = vb[2] + (-dly0+dy0*d)*offset;
n++;
outVerts[n*3+0] = vb[0] + (-dlx1-dx1*d)*offset;
outVerts[n*3+1] = vb[1];
outVerts[n*3+2] = vb[2] + (-dly1-dy1*d)*offset;
n++;
}
else
{
if (n+1 >= maxOutVerts)
return 0;
outVerts[n*3+0] = vb[0] - dmx*offset;
outVerts[n*3+1] = vb[1];
outVerts[n*3+2] = vb[2] - dmy*offset;
n++;
}
}
return n;
}
/// @par
///
/// The value of spacial parameters are in world units.
@@ -463,7 +532,7 @@ void rcMarkCylinderArea(rcContext* ctx, const float* pos,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_CYLINDER_AREA);
rcScopedTimer timer(ctx, RC_TIMER_MARK_CYLINDER_AREA);
float bmin[3], bmax[3];
bmin[0] = pos[0] - r;
@@ -519,6 +588,4 @@ void rcMarkCylinderArea(rcContext* ctx, const float* pos,
}
}
}
ctx->stopTimer(RC_TIMER_MARK_CYLINDER_AREA);
}

View File

@@ -20,6 +20,7 @@
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "Recast.h"
#include "RecastAlloc.h"
#include "RecastAssert.h"
@@ -36,7 +37,7 @@ static int getCornerHeight(int x, int y, int i, int dir,
unsigned int regs[4] = {0,0,0,0};
// Combine region and area codes in order to prevent
// border vertices which are in between two areas to be removed.
// border vertices which are in between two areas to be removed.
regs[0] = chf.spans[i].reg | (chf.areas[i] << 16);
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
@@ -187,27 +188,6 @@ static float distancePtSeg(const int x, const int z,
const int px, const int pz,
const int qx, const int qz)
{
/* float pqx = (float)(qx - px);
float pqy = (float)(qy - py);
float pqz = (float)(qz - pz);
float dx = (float)(x - px);
float dy = (float)(y - py);
float dz = (float)(z - pz);
float d = pqx*pqx + pqy*pqy + pqz*pqz;
float t = pqx*dx + pqy*dy + pqz*dz;
if (d > 0)
t /= d;
if (t < 0)
t = 0;
else if (t > 1)
t = 1;
dx = px + t*pqx - x;
dy = py + t*pqy - y;
dz = pz + t*pqz - z;
return dx*dx + dy*dy + dz*dz;*/
float pqx = (float)(qx - px);
float pqz = (float)(qz - pz);
float dx = (float)(x - px);
@@ -257,13 +237,13 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
simplified.push(points[i*4+2]);
simplified.push(i);
}
}
}
}
if (simplified.size() == 0)
{
// If there is no connections at all,
// create some initial points for the simplification process.
// create some initial points for the simplification process.
// Find lower-left and upper-right vertices of the contour.
int llx = points[0];
int lly = points[1];
@@ -311,19 +291,19 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
{
int ii = (i+1) % (simplified.size()/4);
const int ax = simplified[i*4+0];
const int az = simplified[i*4+2];
const int ai = simplified[i*4+3];
const int bx = simplified[ii*4+0];
const int bz = simplified[ii*4+2];
const int bi = simplified[ii*4+3];
int ax = simplified[i*4+0];
int az = simplified[i*4+2];
int ai = simplified[i*4+3];
int bx = simplified[ii*4+0];
int bz = simplified[ii*4+2];
int bi = simplified[ii*4+3];
// Find maximum deviation from the segment.
float maxd = 0;
int i_max = -1;
int maxi = -1;
int ci, cinc, endi;
// Traverse the segment in lexilogical order so that the
// max deviation is calculated similarly when traversing
// opposite segments.
@@ -338,6 +318,8 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
cinc = pn-1;
ci = (bi+cinc) % pn;
endi = ai;
rcSwap(ax, bx);
rcSwap(az, bz);
}
// Tessellate only outer edges or edges between areas.
@@ -350,7 +332,7 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
if (d > maxd)
{
maxd = d;
i_max = ci;
maxi = ci;
}
ci = (ci+cinc) % pn;
}
@@ -359,7 +341,7 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
// If the max deviation is larger than accepted error,
// add new point, else continue to next segment.
if (i_max != -1 && maxd > (maxError*maxError))
if (maxi != -1 && maxd > (maxError*maxError))
{
// Add space for the new point.
simplified.resize(simplified.size()+4);
@@ -372,10 +354,10 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
simplified[j*4+3] = simplified[(j-1)*4+3];
}
// Add the point.
simplified[(i+1)*4+0] = points[i_max*4+0];
simplified[(i+1)*4+1] = points[i_max*4+1];
simplified[(i+1)*4+2] = points[i_max*4+2];
simplified[(i+1)*4+3] = i_max;
simplified[(i+1)*4+0] = points[maxi*4+0];
simplified[(i+1)*4+1] = points[maxi*4+1];
simplified[(i+1)*4+2] = points[maxi*4+2];
simplified[(i+1)*4+3] = maxi;
}
else
{
@@ -397,11 +379,11 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
const int bx = simplified[ii*4+0];
const int bz = simplified[ii*4+2];
const int bi = simplified[ii*4+3];
// Find maximum deviation from the segment.
int i_max = -1;
int maxi = -1;
int ci = (ai+1) % pn;
// Tessellate only outer edges or edges between areas.
bool tess = false;
// Wall edges.
@@ -420,22 +402,20 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
// Round based on the segments in lexilogical order so that the
// max tesselation is consistent regardles in which direction
// segments are traversed.
if (bx > ax || (bx == ax && bz > az))
const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
if (n > 1)
{
const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
i_max = (ai + n/2) % pn;
}
else
{
const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
i_max = (ai + (n+1)/2) % pn;
if (bx > ax || (bx == ax && bz > az))
maxi = (ai + n/2) % pn;
else
maxi = (ai + (n+1)/2) % pn;
}
}
}
// If the max deviation is larger than accepted error,
// add new point, else continue to next segment.
if (i_max != -1)
if (maxi != -1)
{
// Add space for the new point.
simplified.resize(simplified.size()+4);
@@ -448,10 +428,10 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
simplified[j*4+3] = simplified[(j-1)*4+3];
}
// Add the point.
simplified[(i+1)*4+0] = points[i_max*4+0];
simplified[(i+1)*4+1] = points[i_max*4+1];
simplified[(i+1)*4+2] = points[i_max*4+2];
simplified[(i+1)*4+3] = i_max;
simplified[(i+1)*4+0] = points[maxi*4+0];
simplified[(i+1)*4+1] = points[maxi*4+1];
simplified[(i+1)*4+2] = points[maxi*4+2];
simplified[(i+1)*4+3] = maxi;
}
else
{
@@ -466,37 +446,11 @@ static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
// and the neighbour region is take from the next raw point.
const int ai = (simplified[i*4+3]+1) % pn;
const int bi = simplified[i*4+3];
simplified[i*4+3] = (points[ai*4+3] & RC_CONTOUR_REG_MASK) | (points[bi*4+3] & RC_BORDER_VERTEX);
simplified[i*4+3] = (points[ai*4+3] & (RC_CONTOUR_REG_MASK|RC_AREA_BORDER)) | (points[bi*4+3] & RC_BORDER_VERTEX);
}
}
static void removeDegenerateSegments(rcIntArray& simplified)
{
// Remove adjacent vertices which are equal on xz-plane,
// or else the triangulator will get confused.
for (int i = 0; i < simplified.size()/4; ++i)
{
int ni = i+1;
if (ni >= (simplified.size()/4))
ni = 0;
if (simplified[i*4+0] == simplified[ni*4+0] &&
simplified[i*4+2] == simplified[ni*4+2])
{
// Degenerate segment, remove.
for (int j = i; j < simplified.size()/4-1; ++j)
{
simplified[j*4+0] = simplified[(j+1)*4+0];
simplified[j*4+1] = simplified[(j+1)*4+1];
simplified[j*4+2] = simplified[(j+1)*4+2];
simplified[j*4+3] = simplified[(j+1)*4+3];
}
simplified.resize(simplified.size()-4);
}
}
}
static int calcAreaOfPolygon2D(const int* verts, const int nverts)
{
int area = 0;
@@ -509,54 +463,155 @@ static int calcAreaOfPolygon2D(const int* verts, const int nverts)
return (area+1) / 2;
}
inline bool ileft(const int* a, const int* b, const int* c)
// TODO: these are the same as in RecastMesh.cpp, consider using the same.
// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
inline int area2(const int* a, const int* b, const int* c)
{
return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]) <= 0;
return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);
}
static void getClosestIndices(const int* vertsa, const int nvertsa,
const int* vertsb, const int nvertsb,
int& ia, int& ib)
// Exclusive or: true iff exactly one argument is true.
// The arguments are negated to ensure that they are 0/1
// values. Then the bitwise Xor operator may apply.
// (This idea is due to Michael Baldwin.)
inline bool xorb(bool x, bool y)
{
int closestDist = 0xfffffff;
ia = -1, ib = -1;
for (int i = 0; i < nvertsa; ++i)
return !x ^ !y;
}
// Returns true iff c is strictly to the left of the directed
// line through a to b.
inline bool left(const int* a, const int* b, const int* c)
{
return area2(a, b, c) < 0;
}
inline bool leftOn(const int* a, const int* b, const int* c)
{
return area2(a, b, c) <= 0;
}
inline bool collinear(const int* a, const int* b, const int* c)
{
return area2(a, b, c) == 0;
}
// Returns true iff ab properly intersects cd: they share
// a point interior to both segments. The properness of the
// intersection is ensured by using strict leftness.
static bool intersectProp(const int* a, const int* b, const int* c, const int* d)
{
// Eliminate improper cases.
if (collinear(a,b,c) || collinear(a,b,d) ||
collinear(c,d,a) || collinear(c,d,b))
return false;
return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));
}
// Returns T iff (a,b,c) are collinear and point c lies
// on the closed segement ab.
static bool between(const int* a, const int* b, const int* c)
{
if (!collinear(a, b, c))
return false;
// If ab not vertical, check betweenness on x; else on y.
if (a[0] != b[0])
return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
else
return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
}
// Returns true iff segments ab and cd intersect, properly or improperly.
static bool intersect(const int* a, const int* b, const int* c, const int* d)
{
if (intersectProp(a, b, c, d))
return true;
else if (between(a, b, c) || between(a, b, d) ||
between(c, d, a) || between(c, d, b))
return true;
else
return false;
}
static bool vequal(const int* a, const int* b)
{
return a[0] == b[0] && a[2] == b[2];
}
static bool intersectSegCountour(const int* d0, const int* d1, int i, int n, const int* verts)
{
// For each edge (k,k+1) of P
for (int k = 0; k < n; k++)
{
const int in = (i+1) % nvertsa;
const int ip = (i+nvertsa-1) % nvertsa;
const int* va = &vertsa[i*4];
const int* van = &vertsa[in*4];
const int* vap = &vertsa[ip*4];
int k1 = next(k, n);
// Skip edges incident to i.
if (i == k || i == k1)
continue;
const int* p0 = &verts[k * 4];
const int* p1 = &verts[k1 * 4];
if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
continue;
for (int j = 0; j < nvertsb; ++j)
if (intersect(d0, d1, p0, p1))
return true;
}
return false;
}
static bool inCone(int i, int n, const int* verts, const int* pj)
{
const int* pi = &verts[i * 4];
const int* pi1 = &verts[next(i, n) * 4];
const int* pin1 = &verts[prev(i, n) * 4];
// If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
if (leftOn(pin1, pi, pi1))
return left(pi, pj, pin1) && left(pj, pi, pi1);
// Assume (i-1,i,i+1) not collinear.
// else P[i] is reflex.
return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
}
static void removeDegenerateSegments(rcIntArray& simplified)
{
// Remove adjacent vertices which are equal on xz-plane,
// or else the triangulator will get confused.
int npts = simplified.size()/4;
for (int i = 0; i < npts; ++i)
{
int ni = next(i, npts);
if (vequal(&simplified[i*4], &simplified[ni*4]))
{
const int* vb = &vertsb[j*4];
// vb must be "infront" of va.
if (ileft(vap,va,vb) && ileft(va,van,vb))
// Degenerate segment, remove.
for (int j = i; j < simplified.size()/4-1; ++j)
{
const int dx = vb[0] - va[0];
const int dz = vb[2] - va[2];
const int d = dx*dx + dz*dz;
if (d < closestDist)
{
ia = i;
ib = j;
closestDist = d;
}
simplified[j*4+0] = simplified[(j+1)*4+0];
simplified[j*4+1] = simplified[(j+1)*4+1];
simplified[j*4+2] = simplified[(j+1)*4+2];
simplified[j*4+3] = simplified[(j+1)*4+3];
}
simplified.resize(simplified.size()-4);
npts--;
}
}
}
static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
{
const int maxVerts = ca.nverts + cb.nverts + 2;
int* verts = (int*)rcAlloc(sizeof(int)*maxVerts*4, RC_ALLOC_PERM);
if (!verts)
return false;
int nv = 0;
// Copy contour A.
for (int i = 0; i <= ca.nverts; ++i)
{
@@ -584,7 +639,7 @@ static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
rcFree(ca.verts);
ca.verts = verts;
ca.nverts = nv;
rcFree(cb.verts);
cb.verts = 0;
cb.nverts = 0;
@@ -592,18 +647,179 @@ static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
return true;
}
struct rcContourHole
{
rcContour* contour;
int minx, minz, leftmost;
};
struct rcContourRegion
{
rcContour* outline;
rcContourHole* holes;
int nholes;
};
struct rcPotentialDiagonal
{
int vert;
int dist;
};
// Finds the lowest leftmost vertex of a contour.
static void findLeftMostVertex(rcContour* contour, int* minx, int* minz, int* leftmost)
{
*minx = contour->verts[0];
*minz = contour->verts[2];
*leftmost = 0;
for (int i = 1; i < contour->nverts; i++)
{
const int x = contour->verts[i*4+0];
const int z = contour->verts[i*4+2];
if (x < *minx || (x == *minx && z < *minz))
{
*minx = x;
*minz = z;
*leftmost = i;
}
}
}
static int compareHoles(const void* va, const void* vb)
{
const rcContourHole* a = (const rcContourHole*)va;
const rcContourHole* b = (const rcContourHole*)vb;
if (a->minx == b->minx)
{
if (a->minz < b->minz)
return -1;
if (a->minz > b->minz)
return 1;
}
else
{
if (a->minx < b->minx)
return -1;
if (a->minx > b->minx)
return 1;
}
return 0;
}
static int compareDiagDist(const void* va, const void* vb)
{
const rcPotentialDiagonal* a = (const rcPotentialDiagonal*)va;
const rcPotentialDiagonal* b = (const rcPotentialDiagonal*)vb;
if (a->dist < b->dist)
return -1;
if (a->dist > b->dist)
return 1;
return 0;
}
static void mergeRegionHoles(rcContext* ctx, rcContourRegion& region)
{
// Sort holes from left to right.
for (int i = 0; i < region.nholes; i++)
findLeftMostVertex(region.holes[i].contour, &region.holes[i].minx, &region.holes[i].minz, &region.holes[i].leftmost);
qsort(region.holes, region.nholes, sizeof(rcContourHole), compareHoles);
int maxVerts = region.outline->nverts;
for (int i = 0; i < region.nholes; i++)
maxVerts += region.holes[i].contour->nverts;
rcScopedDelete<rcPotentialDiagonal> diags((rcPotentialDiagonal*)rcAlloc(sizeof(rcPotentialDiagonal)*maxVerts, RC_ALLOC_TEMP));
if (!diags)
{
ctx->log(RC_LOG_WARNING, "mergeRegionHoles: Failed to allocated diags %d.", maxVerts);
return;
}
rcContour* outline = region.outline;
// Merge holes into the outline one by one.
for (int i = 0; i < region.nholes; i++)
{
rcContour* hole = region.holes[i].contour;
int index = -1;
int bestVertex = region.holes[i].leftmost;
for (int iter = 0; iter < hole->nverts; iter++)
{
// Find potential diagonals.
// The 'best' vertex must be in the cone described by 3 cosequtive vertices of the outline.
// ..o j-1
// |
// | * best
// |
// j o-----o j+1
// :
int ndiags = 0;
const int* corner = &hole->verts[bestVertex*4];
for (int j = 0; j < outline->nverts; j++)
{
if (inCone(j, outline->nverts, outline->verts, corner))
{
int dx = outline->verts[j*4+0] - corner[0];
int dz = outline->verts[j*4+2] - corner[2];
diags[ndiags].vert = j;
diags[ndiags].dist = dx*dx + dz*dz;
ndiags++;
}
}
// Sort potential diagonals by distance, we want to make the connection as short as possible.
qsort(diags, ndiags, sizeof(rcPotentialDiagonal), compareDiagDist);
// Find a diagonal that is not intersecting the outline not the remaining holes.
index = -1;
for (int j = 0; j < ndiags; j++)
{
const int* pt = &outline->verts[diags[j].vert*4];
bool intersect = intersectSegCountour(pt, corner, diags[i].vert, outline->nverts, outline->verts);
for (int k = i; k < region.nholes && !intersect; k++)
intersect |= intersectSegCountour(pt, corner, -1, region.holes[k].contour->nverts, region.holes[k].contour->verts);
if (!intersect)
{
index = diags[j].vert;
break;
}
}
// If found non-intersecting diagonal, stop looking.
if (index != -1)
break;
// All the potential diagonals for the current vertex were intersecting, try next vertex.
bestVertex = (bestVertex + 1) % hole->nverts;
}
if (index == -1)
{
ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to find merge points for %p and %p.", region.outline, hole);
continue;
}
if (!mergeContours(*region.outline, *hole, index, bestVertex))
{
ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to merge contours %p and %p.", region.outline, hole);
continue;
}
}
}
/// @par
///
/// The raw contours will match the region outlines exactly. The @p maxError and @p maxEdgeLen
/// parameters control how closely the simplified contours will match the raw contours.
///
/// Simplified contours are generated such that the vertices for portals between areas match up.
/// Simplified contours are generated such that the vertices for portals between areas match up.
/// (They are considered mandatory vertices.)
///
/// Setting @p maxEdgeLength to zero will disabled the edge length feature.
///
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
///
/// @see rcAllocContourSet, rcCompactHeightfield, rcContourSet, rcConfig
bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
const float maxError, const int maxEdgeLen,
@@ -615,7 +831,7 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
const int h = chf.height;
const int borderSize = chf.borderSize;
ctx->startTimer(RC_TIMER_BUILD_CONTOURS);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_CONTOURS);
rcVcopy(cset.bmin, chf.bmin);
rcVcopy(cset.bmax, chf.bmax);
@@ -633,6 +849,7 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
cset.width = chf.width - chf.borderSize*2;
cset.height = chf.height - chf.borderSize*2;
cset.borderSize = chf.borderSize;
cset.maxError = maxError;
int maxContours = rcMax((int)chf.maxRegions, 8);
cset.conts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
@@ -640,7 +857,7 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
return false;
cset.nconts = 0;
rcScopedDelete<unsigned char> flags = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
rcScopedDelete<unsigned char> flags((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP));
if (!flags)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'flags' (%d).", chf.spanCount);
@@ -706,17 +923,17 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
verts.resize(0);
simplified.resize(0);
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
walkContour(x, y, i, chf, flags, verts);
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
simplifyContour(verts, simplified, maxError, maxEdgeLen, buildFlags);
removeDegenerateSegments(simplified);
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
// Store region->contour remap info.
// Create contour.
if (simplified.size()/4 >= 3)
@@ -724,7 +941,7 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
if (cset.nconts >= maxContours)
{
// Allocate more contours.
// This can happen when there are tiny holes in the heightfield.
// This happens when a region has holes.
const int oldMax = maxContours;
maxContours *= 2;
rcContour* newConts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
@@ -737,10 +954,10 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
}
rcFree(cset.conts);
cset.conts = newConts;
ctx->log(RC_LOG_WARNING, "rcBuildContours: Expanding max contours from %d to %d.", oldMax, maxContours);
}
rcContour* cont = &cset.conts[cset.nconts++];
cont->nverts = simplified.size()/4;
@@ -754,9 +971,9 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
if (borderSize > 0)
{
// If the heightfield was build with bordersize, remove the offset.
for (int i = 0; i < cont->nverts; ++i)
for (int j = 0; j < cont->nverts; ++j)
{
int* v = &cont->verts[i*4];
int* v = &cont->verts[j*4];
v[0] -= borderSize;
v[2] -= borderSize;
}
@@ -773,25 +990,14 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
if (borderSize > 0)
{
// If the heightfield was build with bordersize, remove the offset.
for (int i = 0; i < cont->nrverts; ++i)
for (int j = 0; j < cont->nrverts; ++j)
{
int* v = &cont->rverts[i*4];
int* v = &cont->rverts[j*4];
v[0] -= borderSize;
v[2] -= borderSize;
}
}
/* cont->cx = cont->cy = cont->cz = 0;
for (int i = 0; i < cont->nverts; ++i)
{
cont->cx += cont->verts[i*4+0];
cont->cy += cont->verts[i*4+1];
cont->cz += cont->verts[i*4+2];
}
cont->cx /= cont->nverts;
cont->cy /= cont->nverts;
cont->cz /= cont->nverts;*/
cont->reg = reg;
cont->area = area;
}
@@ -799,55 +1005,101 @@ bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
}
}
// Check and merge droppings.
// Sometimes the previous algorithms can fail and create several contours
// per area. This pass will try to merge the holes into the main region.
for (int i = 0; i < cset.nconts; ++i)
// Merge holes if needed.
if (cset.nconts > 0)
{
rcContour& cont = cset.conts[i];
// Check if the contour is would backwards.
if (calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0)
// Calculate winding of all polygons.
rcScopedDelete<char> winding((char*)rcAlloc(sizeof(char)*cset.nconts, RC_ALLOC_TEMP));
if (!winding)
{
// Find another contour which has the same region ID.
int mergeIdx = -1;
for (int j = 0; j < cset.nconts; ++j)
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'hole' (%d).", cset.nconts);
return false;
}
int nholes = 0;
for (int i = 0; i < cset.nconts; ++i)
{
rcContour& cont = cset.conts[i];
// If the contour is wound backwards, it is a hole.
winding[i] = calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0 ? -1 : 1;
if (winding[i] < 0)
nholes++;
}
if (nholes > 0)
{
// Collect outline contour and holes contours per region.
// We assume that there is one outline and multiple holes.
const int nregions = chf.maxRegions+1;
rcScopedDelete<rcContourRegion> regions((rcContourRegion*)rcAlloc(sizeof(rcContourRegion)*nregions, RC_ALLOC_TEMP));
if (!regions)
{
if (i == j) continue;
if (cset.conts[j].nverts && cset.conts[j].reg == cont.reg)
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'regions' (%d).", nregions);
return false;
}
memset(regions, 0, sizeof(rcContourRegion)*nregions);
rcScopedDelete<rcContourHole> holes((rcContourHole*)rcAlloc(sizeof(rcContourHole)*cset.nconts, RC_ALLOC_TEMP));
if (!holes)
{
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'holes' (%d).", cset.nconts);
return false;
}
memset(holes, 0, sizeof(rcContourHole)*cset.nconts);
for (int i = 0; i < cset.nconts; ++i)
{
rcContour& cont = cset.conts[i];
// Positively would contours are outlines, negative holes.
if (winding[i] > 0)
{
// Make sure the polygon is correctly oriented.
if (calcAreaOfPolygon2D(cset.conts[j].verts, cset.conts[j].nverts))
{
mergeIdx = j;
break;
}
if (regions[cont.reg].outline)
ctx->log(RC_LOG_ERROR, "rcBuildContours: Multiple outlines for region %d.", cont.reg);
regions[cont.reg].outline = &cont;
}
else
{
regions[cont.reg].nholes++;
}
}
if (mergeIdx == -1)
int index = 0;
for (int i = 0; i < nregions; i++)
{
ctx->log(RC_LOG_WARNING, "rcBuildContours: Could not find merge target for bad contour %d.", i);
}
else
{
rcContour& mcont = cset.conts[mergeIdx];
// Merge by closest points.
int ia = 0, ib = 0;
getClosestIndices(mcont.verts, mcont.nverts, cont.verts, cont.nverts, ia, ib);
if (ia == -1 || ib == -1)
if (regions[i].nholes > 0)
{
ctx->log(RC_LOG_WARNING, "rcBuildContours: Failed to find merge points for %d and %d.", i, mergeIdx);
continue;
regions[i].holes = &holes[index];
index += regions[i].nholes;
regions[i].nholes = 0;
}
if (!mergeContours(mcont, cont, ia, ib))
}
for (int i = 0; i < cset.nconts; ++i)
{
rcContour& cont = cset.conts[i];
rcContourRegion& reg = regions[cont.reg];
if (winding[i] < 0)
reg.holes[reg.nholes++].contour = &cont;
}
// Finally merge each regions holes into the outline.
for (int i = 0; i < nregions; i++)
{
rcContourRegion& reg = regions[i];
if (!reg.nholes) continue;
if (reg.outline)
{
ctx->log(RC_LOG_WARNING, "rcBuildContours: Failed to merge contours %d and %d.", i, mergeIdx);
continue;
mergeRegionHoles(ctx, reg);
}
else
{
// The region does not have an outline.
// This can happen if the contour becaomes selfoverlapping because of
// too aggressive simplification settings.
ctx->log(RC_LOG_ERROR, "rcBuildContours: Bad outline for region %d, contour simplification is likely too aggressive.", i);
}
}
}
}
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS);
return true;
}

View File

@@ -37,7 +37,7 @@ void rcFilterLowHangingWalkableObstacles(rcContext* ctx, const int walkableClimb
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_FILTER_LOW_OBSTACLES);
rcScopedTimer timer(ctx, RC_TIMER_FILTER_LOW_OBSTACLES);
const int w = solid.width;
const int h = solid.height;
@@ -67,8 +67,6 @@ void rcFilterLowHangingWalkableObstacles(rcContext* ctx, const int walkableClimb
}
}
}
ctx->stopTimer(RC_TIMER_FILTER_LOW_OBSTACLES);
}
/// @par
@@ -86,7 +84,7 @@ void rcFilterLedgeSpans(rcContext* ctx, const int walkableHeight, const int walk
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_FILTER_BORDER);
rcScopedTimer timer(ctx, RC_TIMER_FILTER_BORDER);
const int w = solid.width;
const int h = solid.height;
@@ -128,7 +126,7 @@ void rcFilterLedgeSpans(rcContext* ctx, const int walkableHeight, const int walk
rcSpan* ns = solid.spans[dx + dy*w];
int nbot = -walkableClimb;
int ntop = ns ? (int)ns->smin : MAX_HEIGHT;
// Skip neighbor if the gap between the spans is too small.
// Skip neightbour if the gap between the spans is too small.
if (rcMin(top,ntop) - rcMax(bot,nbot) > walkableHeight)
minh = rcMin(minh, nbot - bot);
@@ -137,7 +135,7 @@ void rcFilterLedgeSpans(rcContext* ctx, const int walkableHeight, const int walk
{
nbot = (int)ns->smax;
ntop = ns->next ? (int)ns->next->smin : MAX_HEIGHT;
// Skip neighbor if the gap between the spans is too small.
// Skip neightbour if the gap between the spans is too small.
if (rcMin(top,ntop) - rcMax(bot,nbot) > walkableHeight)
{
minh = rcMin(minh, nbot - bot);
@@ -156,20 +154,19 @@ void rcFilterLedgeSpans(rcContext* ctx, const int walkableHeight, const int walk
// The current span is close to a ledge if the drop to any
// neighbour span is less than the walkableClimb.
if (minh < -walkableClimb)
{
s->area = RC_NULL_AREA;
}
// If the difference between all neighbours is too large,
// we are at steep slope, mark the span as ledge.
if ((asmax - asmin) > walkableClimb)
else if ((asmax - asmin) > walkableClimb)
{
s->area = RC_NULL_AREA;
}
}
}
}
ctx->stopTimer(RC_TIMER_FILTER_BORDER);
}
}
/// @par
///
@@ -181,7 +178,7 @@ void rcFilterWalkableLowHeightSpans(rcContext* ctx, int walkableHeight, rcHeight
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_FILTER_WALKABLE);
rcScopedTimer timer(ctx, RC_TIMER_FILTER_WALKABLE);
const int w = solid.width;
const int h = solid.height;
@@ -202,6 +199,4 @@ void rcFilterWalkableLowHeightSpans(rcContext* ctx, int walkableHeight, rcHeight
}
}
}
ctx->stopTimer(RC_TIMER_FILTER_WALKABLE);
}

View File

@@ -38,7 +38,7 @@ struct rcLayerRegion
unsigned char layerId; // Layer ID
unsigned char nlayers; // Layer count
unsigned char nneis; // Neighbour count
unsigned char base; // Flag indicating if the region is hte base of merged regions.
unsigned char base; // Flag indicating if the region is the base of merged regions.
};
@@ -87,12 +87,12 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_LAYERS);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_LAYERS);
const int w = chf.width;
const int h = chf.height;
rcScopedDelete<unsigned char> srcReg = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
rcScopedDelete<unsigned char> srcReg((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP));
if (!srcReg)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'srcReg' (%d).", chf.spanCount);
@@ -101,7 +101,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
memset(srcReg,0xff,sizeof(unsigned char)*chf.spanCount);
const int nsweeps = chf.width;
rcScopedDelete<rcLayerSweepSpan> sweeps = (rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP);
rcScopedDelete<rcLayerSweepSpan> sweeps((rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP));
if (!sweeps)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'sweeps' (%d).", nsweeps);
@@ -212,7 +212,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
// Allocate and init layer regions.
const int nregs = (int)regId;
rcScopedDelete<rcLayerRegion> regs = (rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP);
rcScopedDelete<rcLayerRegion> regs((rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP));
if (!regs)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'regs' (%d).", nregs);
@@ -258,7 +258,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
const int ay = y + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
const unsigned char rai = srcReg[ai];
if (rai != 0xff && rai != ri)
if (rai != 0xff && rai != ri && regs[ri].nneis < RC_MAX_NEIS)
addUnique(regs[ri].neis, regs[ri].nneis, rai);
}
}
@@ -293,7 +293,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
for (int i = 0; i < nregs; ++i)
{
rcLayerRegion& root = regs[i];
// Skip alreadu visited.
// Skip already visited.
if (root.layerId != 0xff)
continue;
@@ -325,7 +325,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
continue;
// Skip if the height range would become too large.
const int ymin = rcMin(root.ymin, regn.ymin);
const int ymax = rcMin(root.ymax, regn.ymax);
const int ymax = rcMax(root.ymax, regn.ymax);
if ((ymax - ymin) >= 255)
continue;
@@ -373,11 +373,11 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
continue;
// Skip if the height range would become too large.
const int ymin = rcMin(ri.ymin, rj.ymin);
const int ymax = rcMin(ri.ymax, rj.ymax);
const int ymax = rcMax(ri.ymax, rj.ymax);
if ((ymax - ymin) >= 255)
continue;
// Make sure that there is no overlap when mergin 'ri' and 'rj'.
// Make sure that there is no overlap when merging 'ri' and 'rj'.
bool overlap = false;
// Iterate over all regions which have the same layerId as 'rj'
for (int k = 0; k < nregs; ++k)
@@ -417,7 +417,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
// Add overlaid layers from 'rj' to 'ri'.
for (int k = 0; k < rj.nlayers; ++k)
addUnique(ri.layers, ri.nlayers, rj.layers[k]);
// Update heigh bounds.
// Update height bounds.
ri.ymin = rcMin(ri.ymin, rj.ymin);
ri.ymax = rcMax(ri.ymax, rj.ymax);
}
@@ -446,10 +446,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
// No layers, return empty.
if (layerId == 0)
{
ctx->stopTimer(RC_TIMER_BUILD_LAYERS);
return true;
}
// Create layers.
rcAssert(lset.layers == 0);
@@ -481,10 +478,8 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
for (int i = 0; i < lset.nlayers; ++i)
{
unsigned char curId = (unsigned char)i;
// Allocate memory for the current layer.
rcHeightfieldLayer* layer = &lset.layers[i];
memset(layer, 0, sizeof(rcHeightfieldLayer));
const int gridSize = sizeof(unsigned char)*lw*lh;
@@ -528,7 +523,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
layer->cs = chf.cs;
layer->ch = chf.ch;
// Adjust the bbox to fit the heighfield.
// Adjust the bbox to fit the heightfield.
rcVcopy(layer->bmin, bmin);
rcVcopy(layer->bmax, bmax);
layer->bmin[1] = bmin[1] + hmin*chf.ch;
@@ -542,7 +537,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
layer->miny = layer->height;
layer->maxy = 0;
// Copy height and area from compact heighfield.
// Copy height and area from compact heightfield.
for (int y = 0; y < lh; ++y)
{
for (int x = 0; x < lw; ++x)
@@ -550,14 +545,14 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
const int cx = borderSize+x;
const int cy = borderSize+y;
const rcCompactCell& c = chf.cells[cx+cy*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
for (int j = (int)c.index, nj = (int)(c.index+c.count); j < nj; ++j)
{
const rcCompactSpan& s = chf.spans[i];
const rcCompactSpan& s = chf.spans[j];
// Skip unassigned regions.
if (srcReg[i] == 0xff)
if (srcReg[j] == 0xff)
continue;
// Skip of does nto belong to current layer.
unsigned char lid = regs[srcReg[i]].layerId;
unsigned char lid = regs[srcReg[j]].layerId;
if (lid != curId)
continue;
@@ -570,7 +565,7 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
// Store height and area type.
const int idx = x+y*lw;
layer->heights[idx] = (unsigned char)(s.y - hmin);
layer->areas[idx] = chf.areas[i];
layer->areas[idx] = chf.areas[j];
// Check connection.
unsigned char portal = 0;
@@ -614,7 +609,5 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
layer->miny = layer->maxy = 0;
}
ctx->stopTimer(RC_TIMER_BUILD_LAYERS);
return true;
}

View File

@@ -1,77 +0,0 @@
//
// Copyright (c) 2009 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include "RecastLog.h"
#include <stdio.h>
#include <stdarg.h>
static rcLog* g_log = 0;
static rcBuildTimes* g_btimes = 0;
rcLog::rcLog() :
m_messageCount(0),
m_textPoolSize(0)
{
}
rcLog::~rcLog()
{
if (g_log == this)
g_log = 0;
}
void rcLog::log(rcLogCategory category, const char* format, ...)
{
if (m_messageCount >= MAX_MESSAGES)
return;
char* dst = &m_textPool[m_textPoolSize];
int n = TEXT_POOL_SIZE - m_textPoolSize;
if (n < 2)
return;
// Store category
*dst = (char)category;
n--;
// Store message
va_list ap;
va_start(ap, format);
int ret = vsnprintf(dst+1, n-1, format, ap);
va_end(ap);
if (ret > 0)
m_textPoolSize += ret+2;
m_messages[m_messageCount++] = dst;
}
void rcSetLog(rcLog* log)
{
g_log = log;
}
rcLog* rcGetLog()
{
return g_log;
}
void rcSetBuildTimes(rcBuildTimes* btimes)
{
g_btimes = btimes;
}
rcBuildTimes* rcGetBuildTimes()
{
return g_btimes;
}

View File

@@ -160,6 +160,7 @@ static unsigned short addVertex(unsigned short x, unsigned short y, unsigned sho
return (unsigned short)i;
}
// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
@@ -288,6 +289,53 @@ static bool diagonal(int i, int j, int n, const int* verts, int* indices)
return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices);
}
static bool diagonalieLoose(int i, int j, int n, const int* verts, int* indices)
{
const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];
const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];
// For each edge (k,k+1) of P
for (int k = 0; k < n; k++)
{
int k1 = next(k, n);
// Skip edges incident to i or j
if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
{
const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];
const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];
if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
continue;
if (intersectProp(d0, d1, p0, p1))
return false;
}
}
return true;
}
static bool inConeLoose(int i, int j, int n, const int* verts, int* indices)
{
const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];
const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];
const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];
const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];
// If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
if (leftOn(pin1, pi, pi1))
return leftOn(pi, pj, pin1) && leftOn(pj, pi, pi1);
// Assume (i-1,i,i+1) not collinear.
// else P[i] is reflex.
return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
}
static bool diagonalLoose(int i, int j, int n, const int* verts, int* indices)
{
return inConeLoose(i, j, n, verts, indices) && diagonalieLoose(i, j, n, verts, indices);
}
static int triangulate(int n, const int* verts, int* indices, int* tris)
{
int ntris = 0;
@@ -305,7 +353,7 @@ static int triangulate(int n, const int* verts, int* indices, int* tris)
while (n > 3)
{
int minLen = -1;
int i_min = -1;
int mini = -1;
for (int i = 0; i < n; i++)
{
int i1 = next(i, n);
@@ -321,24 +369,51 @@ static int triangulate(int n, const int* verts, int* indices, int* tris)
if (minLen < 0 || len < minLen)
{
minLen = len;
i_min = i;
mini = i;
}
}
}
if (i_min == -1)
if (mini == -1)
{
// Should not happen.
/* printf("mini == -1 ntris=%d n=%d\n", ntris, n);
// We might get here because the contour has overlapping segments, like this:
//
// A o-o=====o---o B
// / |C D| \
// o o o o
// : : : :
// We'll try to recover by loosing up the inCone test a bit so that a diagonal
// like A-B or C-D can be found and we can continue.
minLen = -1;
mini = -1;
for (int i = 0; i < n; i++)
{
printf("%d ", indices[i] & 0x0fffffff);
int i1 = next(i, n);
int i2 = next(i1, n);
if (diagonalLoose(i, i2, n, verts, indices))
{
const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];
const int* p2 = &verts[(indices[next(i2, n)] & 0x0fffffff) * 4];
int dx = p2[0] - p0[0];
int dy = p2[2] - p0[2];
int len = dx*dx + dy*dy;
if (minLen < 0 || len < minLen)
{
minLen = len;
mini = i;
}
}
}
if (mini == -1)
{
// The contour is messed up. This sometimes happens
// if the contour simplification is too aggressive.
return -ntris;
}
printf("\n");*/
return -ntris;
}
int i = i_min;
int i = mini;
int i1 = next(i, n);
int i2 = next(i1, n);
@@ -453,8 +528,8 @@ static int getPolyMergeValue(unsigned short* pa, unsigned short* pb,
return dx*dx + dy*dy;
}
static void mergePolys(unsigned short* pa, unsigned short* pb, int ea, int eb,
unsigned short* tmp, const int nvp)
static void mergePolyVerts(unsigned short* pa, unsigned short* pb, int ea, int eb,
unsigned short* tmp, const int nvp)
{
const int na = countPolyVerts(pa, nvp);
const int nb = countPolyVerts(pb, nvp);
@@ -526,7 +601,7 @@ static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned sho
// Find edges which share the removed vertex.
const int maxEdges = numTouchedVerts*2;
int nedges = 0;
rcScopedDelete<int> edges = (int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP);
rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP));
if (!edges)
{
ctx->log(RC_LOG_WARNING, "canRemoveVertex: Out of memory 'edges' (%d).", maxEdges*3);
@@ -550,9 +625,9 @@ static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned sho
// Check if the edge exists
bool exists = false;
for (int k = 0; k < nedges; ++k)
for (int m = 0; m < nedges; ++m)
{
int* e = &edges[k*3];
int* e = &edges[m*3];
if (e[1] == b)
{
// Exists, increment vertex share count.
@@ -606,7 +681,7 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
int nedges = 0;
rcScopedDelete<int> edges = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP);
rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP));
if (!edges)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'edges' (%d).", numRemovedVerts*nvp*4);
@@ -614,15 +689,15 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
int nhole = 0;
rcScopedDelete<int> hole = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP);
rcScopedDelete<int> hole((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
if (!hole)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hole' (%d).", numRemovedVerts*nvp);
return false;
}
int nhreg = 0;
rcScopedDelete<int> hreg = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP);
rcScopedDelete<int> hreg((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
if (!hreg)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hreg' (%d).", numRemovedVerts*nvp);
@@ -630,7 +705,7 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
int nharea = 0;
rcScopedDelete<int> harea = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP);
rcScopedDelete<int> harea((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
if (!harea)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'harea' (%d).", numRemovedVerts*nvp);
@@ -661,7 +736,8 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
// Remove the polygon.
unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*nvp*2];
memcpy(p,p2,sizeof(unsigned short)*nvp);
if (p != p2)
memcpy(p,p2,sizeof(unsigned short)*nvp);
memset(p+nvp,0xff,sizeof(unsigned short)*nvp);
mesh.regs[i] = mesh.regs[mesh.npolys-1];
mesh.areas[i] = mesh.areas[mesh.npolys-1];
@@ -671,7 +747,7 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
// Remove vertex.
for (int i = (int)rem; i < mesh.nverts; ++i)
for (int i = (int)rem; i < mesh.nverts - 1; ++i)
{
mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0];
mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1];
@@ -746,22 +822,22 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
break;
}
rcScopedDelete<int> tris = (int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP);
rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP));
if (!tris)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tris' (%d).", nhole*3);
return false;
}
rcScopedDelete<int> tverts = (int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP);
rcScopedDelete<int> tverts((int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP));
if (!tverts)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tverts' (%d).", nhole*4);
return false;
}
rcScopedDelete<int> thole = (int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP);
if (!tverts)
rcScopedDelete<int> thole((int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP));
if (!thole)
{
ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'thole' (%d).", nhole);
return false;
@@ -787,20 +863,20 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
}
// Merge the hole triangles back to polygons.
rcScopedDelete<unsigned short> polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP));
if (!polys)
{
ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'polys' (%d).", (ntris+1)*nvp);
return false;
}
rcScopedDelete<unsigned short> pregs = (unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> pregs((unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP));
if (!pregs)
{
ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pregs' (%d).", ntris);
return false;
}
rcScopedDelete<unsigned char> pareas = (unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP);
if (!pregs)
rcScopedDelete<unsigned char> pareas((unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP));
if (!pareas)
{
ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pareas' (%d).", ntris);
return false;
@@ -819,7 +895,14 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
polys[npolys*nvp+0] = (unsigned short)hole[t[0]];
polys[npolys*nvp+1] = (unsigned short)hole[t[1]];
polys[npolys*nvp+2] = (unsigned short)hole[t[2]];
pregs[npolys] = (unsigned short)hreg[t[0]];
// If this polygon covers multiple region types then
// mark it as such
if (hreg[t[0]] != hreg[t[1]] || hreg[t[1]] != hreg[t[2]])
pregs[npolys] = RC_MULTIPLE_REGS;
else
pregs[npolys] = (unsigned short)hreg[t[0]];
pareas[npolys] = (unsigned char)harea[t[0]];
npolys++;
}
@@ -860,8 +943,13 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
// Found best, merge.
unsigned short* pa = &polys[bestPa*nvp];
unsigned short* pb = &polys[bestPb*nvp];
mergePolys(pa, pb, bestEa, bestEb, tmpPoly, nvp);
memcpy(pb, &polys[(npolys-1)*nvp], sizeof(unsigned short)*nvp);
mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
if (pregs[bestPa] != pregs[bestPb])
pregs[bestPa] = RC_MULTIPLE_REGS;
unsigned short* last = &polys[(npolys-1)*nvp];
if (pb != last)
memcpy(pb, last, sizeof(unsigned short)*nvp);
pregs[bestPb] = pregs[npolys-1];
pareas[bestPb] = pareas[npolys-1];
npolys--;
@@ -905,13 +993,14 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_POLYMESH);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESH);
rcVcopy(mesh.bmin, cset.bmin);
rcVcopy(mesh.bmax, cset.bmax);
mesh.cs = cset.cs;
mesh.ch = cset.ch;
mesh.borderSize = cset.borderSize;
mesh.maxEdgeError = cset.maxError;
int maxVertices = 0;
int maxTris = 0;
@@ -931,10 +1020,10 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
return false;
}
rcScopedDelete<unsigned char> vflags = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP);
rcScopedDelete<unsigned char> vflags((unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP));
if (!vflags)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.verts' (%d).", maxVertices);
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'vflags' (%d).", maxVertices);
return false;
}
memset(vflags, 0, maxVertices);
@@ -974,7 +1063,7 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
memset(mesh.regs, 0, sizeof(unsigned short)*maxTris);
memset(mesh.areas, 0, sizeof(unsigned char)*maxTris);
rcScopedDelete<int> nextVert = (int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP);
rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP));
if (!nextVert)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'nextVert' (%d).", maxVertices);
@@ -982,7 +1071,7 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
}
memset(nextVert, 0, sizeof(int)*maxVertices);
rcScopedDelete<int> firstVert = (int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP);
rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
if (!firstVert)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
@@ -991,19 +1080,19 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
firstVert[i] = -1;
rcScopedDelete<int> indices = (int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP);
rcScopedDelete<int> indices((int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP));
if (!indices)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'indices' (%d).", maxVertsPerCont);
return false;
}
rcScopedDelete<int> tris = (int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP);
rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP));
if (!tris)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'tris' (%d).", maxVertsPerCont*3);
return false;
}
rcScopedDelete<unsigned short> polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP));
if (!polys)
{
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'polys' (%d).", maxVertsPerCont*nvp);
@@ -1053,7 +1142,7 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
vflags[indices[j]] = 1;
}
}
// Build initial polygons.
int npolys = 0;
memset(polys, 0xff, maxVertsPerCont*nvp*sizeof(unsigned short));
@@ -1104,8 +1193,10 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
// Found best, merge.
unsigned short* pa = &polys[bestPa*nvp];
unsigned short* pb = &polys[bestPb*nvp];
mergePolys(pa, pb, bestEa, bestEb, tmpPoly, nvp);
memcpy(pb, &polys[(npolys-1)*nvp], sizeof(unsigned short)*nvp);
mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
unsigned short* lastPoly = &polys[(npolys-1)*nvp];
if (pb != lastPoly)
memcpy(pb, lastPoly, sizeof(unsigned short)*nvp);
npolys--;
}
else
@@ -1150,6 +1241,7 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
}
// Remove vertex
// Note: mesh.nverts is already decremented inside removeVertex()!
// Fixup vertex flags
for (int j = i; j < mesh.nverts; ++j)
vflags[j] = vflags[j+1];
--i;
@@ -1212,8 +1304,6 @@ bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMe
ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
}
ctx->stopTimer(RC_TIMER_BUILD_POLYMESH);
return true;
}
@@ -1225,7 +1315,7 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
if (!nmeshes || !meshes)
return true;
ctx->startTimer(RC_TIMER_MERGE_POLYMESH);
rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESH);
mesh.nvp = meshes[0]->nvp;
mesh.cs = meshes[0]->cs;
@@ -1286,7 +1376,7 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
}
memset(mesh.flags, 0, sizeof(unsigned short)*maxPolys);
rcScopedDelete<int> nextVert = (int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP);
rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP));
if (!nextVert)
{
ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'nextVert' (%d).", maxVerts);
@@ -1294,7 +1384,7 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
}
memset(nextVert, 0, sizeof(int)*maxVerts);
rcScopedDelete<int> firstVert = (int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP);
rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
if (!firstVert)
{
ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
@@ -1303,13 +1393,13 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
firstVert[i] = -1;
rcScopedDelete<unsigned short> vremap = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM);
rcScopedDelete<unsigned short> vremap((unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM));
if (!vremap)
{
ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'vremap' (%d).", maxVertsPerMesh);
return false;
}
memset(nextVert, 0, sizeof(int)*maxVerts);
memset(vremap, 0, sizeof(unsigned short)*maxVertsPerMesh);
for (int i = 0; i < nmeshes; ++i)
{
@@ -1318,6 +1408,12 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
const unsigned short ox = (unsigned short)floorf((pmesh->bmin[0]-mesh.bmin[0])/mesh.cs+0.5f);
const unsigned short oz = (unsigned short)floorf((pmesh->bmin[2]-mesh.bmin[2])/mesh.cs+0.5f);
bool isMinX = (ox == 0);
bool isMinZ = (oz == 0);
bool isMaxX = ((unsigned short)floorf((mesh.bmax[0] - pmesh->bmax[0]) / mesh.cs + 0.5f)) == 0;
bool isMaxZ = ((unsigned short)floorf((mesh.bmax[2] - pmesh->bmax[2]) / mesh.cs + 0.5f)) == 0;
bool isOnBorder = (isMinX || isMinZ || isMaxX || isMaxZ);
for (int j = 0; j < pmesh->nverts; ++j)
{
unsigned short* v = &pmesh->verts[j*3];
@@ -1338,6 +1434,36 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
if (src[k] == RC_MESH_NULL_IDX) break;
tgt[k] = vremap[src[k]];
}
if (isOnBorder)
{
for (int k = mesh.nvp; k < mesh.nvp * 2; ++k)
{
if (src[k] & 0x8000 && src[k] != 0xffff)
{
unsigned short dir = src[k] & 0xf;
switch (dir)
{
case 0: // Portal x-
if (isMinX)
tgt[k] = src[k];
break;
case 1: // Portal z+
if (isMaxZ)
tgt[k] = src[k];
break;
case 2: // Portal x+
if (isMaxX)
tgt[k] = src[k];
break;
case 3: // Portal z-
if (isMinZ)
tgt[k] = src[k];
break;
}
}
}
}
}
}
@@ -1357,7 +1483,70 @@ bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, r
ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
}
ctx->stopTimer(RC_TIMER_MERGE_POLYMESH);
return true;
}
bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst)
{
rcAssert(ctx);
// Destination must be empty.
rcAssert(dst.verts == 0);
rcAssert(dst.polys == 0);
rcAssert(dst.regs == 0);
rcAssert(dst.areas == 0);
rcAssert(dst.flags == 0);
dst.nverts = src.nverts;
dst.npolys = src.npolys;
dst.maxpolys = src.npolys;
dst.nvp = src.nvp;
rcVcopy(dst.bmin, src.bmin);
rcVcopy(dst.bmax, src.bmax);
dst.cs = src.cs;
dst.ch = src.ch;
dst.borderSize = src.borderSize;
dst.maxEdgeError = src.maxEdgeError;
dst.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.nverts*3, RC_ALLOC_PERM);
if (!dst.verts)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.verts' (%d).", src.nverts*3);
return false;
}
memcpy(dst.verts, src.verts, sizeof(unsigned short)*src.nverts*3);
dst.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys*2*src.nvp, RC_ALLOC_PERM);
if (!dst.polys)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.polys' (%d).", src.npolys*2*src.nvp);
return false;
}
memcpy(dst.polys, src.polys, sizeof(unsigned short)*src.npolys*2*src.nvp);
dst.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
if (!dst.regs)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.regs' (%d).", src.npolys);
return false;
}
memcpy(dst.regs, src.regs, sizeof(unsigned short)*src.npolys);
dst.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*src.npolys, RC_ALLOC_PERM);
if (!dst.areas)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.areas' (%d).", src.npolys);
return false;
}
memcpy(dst.areas, src.areas, sizeof(unsigned char)*src.npolys);
dst.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
if (!dst.flags)
{
ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.flags' (%d).", src.npolys);
return false;
}
memcpy(dst.flags, src.flags, sizeof(unsigned short)*src.npolys);
return true;
}

File diff suppressed because it is too large Load Diff

View File

@@ -50,7 +50,7 @@ static rcSpan* allocSpan(rcHeightfield& hf)
// Allocate memory for the new pool.
rcSpanPool* pool = (rcSpanPool*)rcAlloc(sizeof(rcSpanPool), RC_ALLOC_PERM);
if (!pool) return 0;
pool->next = 0;
// Add the pool into the list of pools.
pool->next = hf.pools;
hf.pools = pool;
@@ -82,7 +82,7 @@ static void freeSpan(rcHeightfield& hf, rcSpan* ptr)
hf.freelist = ptr;
}
static void addSpan(rcHeightfield& hf, const int x, const int y,
static bool addSpan(rcHeightfield& hf, const int x, const int y,
const unsigned short smin, const unsigned short smax,
const unsigned char area, const int flagMergeThr)
{
@@ -90,16 +90,18 @@ static void addSpan(rcHeightfield& hf, const int x, const int y,
int idx = x + y*hf.width;
rcSpan* s = allocSpan(hf);
if (!s)
return false;
s->smin = smin;
s->smax = smax;
s->area = area;
s->next = 0;
// Empty cell, add he first span.
// Empty cell, add the first span.
if (!hf.spans[idx])
{
hf.spans[idx] = s;
return;
return true;
}
rcSpan* prev = 0;
rcSpan* cur = hf.spans[idx];
@@ -152,6 +154,8 @@ static void addSpan(rcHeightfield& hf, const int x, const int y,
s->next = hf.spans[idx];
hf.spans[idx] = s;
}
return true;
}
/// @par
@@ -161,45 +165,80 @@ static void addSpan(rcHeightfield& hf, const int x, const int y,
/// from the existing span, the span flags are merged.
///
/// @see rcHeightfield, rcSpan.
void rcAddSpan(rcContext* /*ctx*/, rcHeightfield& hf, const int x, const int y,
bool rcAddSpan(rcContext* ctx, rcHeightfield& hf, const int x, const int y,
const unsigned short smin, const unsigned short smax,
const unsigned char area, const int flagMergeThr)
{
// rcAssert(ctx);
addSpan(hf, x,y, smin, smax, area, flagMergeThr);
rcAssert(ctx);
if (!addSpan(hf, x, y, smin, smax, area, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcAddSpan: Out of memory.");
return false;
}
return true;
}
static int clipPoly(const float* in, int n, float* out, float pnx, float pnz, float pd)
// divides a convex polygons into two convex polygons on both sides of a line
static void dividePoly(const float* in, int nin,
float* out1, int* nout1,
float* out2, int* nout2,
float x, int axis)
{
float d[12];
for (int i = 0; i < n; ++i)
d[i] = pnx*in[i*3+0] + pnz*in[i*3+2] + pd;
int m = 0;
for (int i = 0, j = n-1; i < n; j=i, ++i)
for (int i = 0; i < nin; ++i)
d[i] = x - in[i*3+axis];
int m = 0, n = 0;
for (int i = 0, j = nin-1; i < nin; j=i, ++i)
{
bool ina = d[j] >= 0;
bool inb = d[i] >= 0;
if (ina != inb)
{
float s = d[j] / (d[j] - d[i]);
out[m*3+0] = in[j*3+0] + (in[i*3+0] - in[j*3+0])*s;
out[m*3+1] = in[j*3+1] + (in[i*3+1] - in[j*3+1])*s;
out[m*3+2] = in[j*3+2] + (in[i*3+2] - in[j*3+2])*s;
out1[m*3+0] = in[j*3+0] + (in[i*3+0] - in[j*3+0])*s;
out1[m*3+1] = in[j*3+1] + (in[i*3+1] - in[j*3+1])*s;
out1[m*3+2] = in[j*3+2] + (in[i*3+2] - in[j*3+2])*s;
rcVcopy(out2 + n*3, out1 + m*3);
m++;
n++;
// add the i'th point to the right polygon. Do NOT add points that are on the dividing line
// since these were already added above
if (d[i] > 0)
{
rcVcopy(out1 + m*3, in + i*3);
m++;
}
else if (d[i] < 0)
{
rcVcopy(out2 + n*3, in + i*3);
n++;
}
}
if (inb)
else // same side
{
out[m*3+0] = in[i*3+0];
out[m*3+1] = in[i*3+1];
out[m*3+2] = in[i*3+2];
m++;
// add the i'th point to the right polygon. Addition is done even for points on the dividing line
if (d[i] >= 0)
{
rcVcopy(out1 + m*3, in + i*3);
m++;
if (d[i] != 0)
continue;
}
rcVcopy(out2 + n*3, in + i*3);
n++;
}
}
return m;
*nout1 = m;
*nout2 = n;
}
static void rasterizeTri(const float* v0, const float* v1, const float* v2,
static bool rasterizeTri(const float* v0, const float* v1, const float* v2,
const unsigned char area, rcHeightfield& hf,
const float* bmin, const float* bmax,
const float cs, const float ics, const float ich,
@@ -220,50 +259,59 @@ static void rasterizeTri(const float* v0, const float* v1, const float* v2,
// If the triangle does not touch the bbox of the heightfield, skip the triagle.
if (!overlapBounds(bmin, bmax, tmin, tmax))
return;
return true;
// Calculate the footpring of the triangle on the grid.
int x0 = (int)((tmin[0] - bmin[0])*ics);
// Calculate the footprint of the triangle on the grid's y-axis
int y0 = (int)((tmin[2] - bmin[2])*ics);
int x1 = (int)((tmax[0] - bmin[0])*ics);
int y1 = (int)((tmax[2] - bmin[2])*ics);
x0 = rcClamp(x0, 0, w-1);
y0 = rcClamp(y0, 0, h-1);
x1 = rcClamp(x1, 0, w-1);
y1 = rcClamp(y1, 0, h-1);
// Clip the triangle into all grid cells it touches.
float in[7*3], out[7*3], inrow[7*3];
float buf[7*3*4];
float *in = buf, *inrow = buf+7*3, *p1 = inrow+7*3, *p2 = p1+7*3;
rcVcopy(&in[0], v0);
rcVcopy(&in[1*3], v1);
rcVcopy(&in[2*3], v2);
int nvrow, nvIn = 3;
for (int y = y0; y <= y1; ++y)
{
// Clip polygon to row.
rcVcopy(&in[0], v0);
rcVcopy(&in[1*3], v1);
rcVcopy(&in[2*3], v2);
int nvrow = 3;
// Clip polygon to row. Store the remaining polygon as well
const float cz = bmin[2] + y*cs;
nvrow = clipPoly(in, nvrow, out, 0, 1, -cz);
if (nvrow < 3) continue;
nvrow = clipPoly(out, nvrow, inrow, 0, -1, cz+cs);
dividePoly(in, nvIn, inrow, &nvrow, p1, &nvIn, cz+cs, 2);
rcSwap(in, p1);
if (nvrow < 3) continue;
// find the horizontal bounds in the row
float minX = inrow[0], maxX = inrow[0];
for (int i=1; i<nvrow; ++i)
{
if (minX > inrow[i*3]) minX = inrow[i*3];
if (maxX < inrow[i*3]) maxX = inrow[i*3];
}
int x0 = (int)((minX - bmin[0])*ics);
int x1 = (int)((maxX - bmin[0])*ics);
x0 = rcClamp(x0, 0, w-1);
x1 = rcClamp(x1, 0, w-1);
int nv, nv2 = nvrow;
for (int x = x0; x <= x1; ++x)
{
// Clip polygon to column.
int nv = nvrow;
// Clip polygon to column. store the remaining polygon as well
const float cx = bmin[0] + x*cs;
nv = clipPoly(inrow, nv, out, 1, 0, -cx);
if (nv < 3) continue;
nv = clipPoly(out, nv, in, -1, 0, cx+cs);
dividePoly(inrow, nv2, p1, &nv, p2, &nv2, cx+cs, 0);
rcSwap(inrow, p2);
if (nv < 3) continue;
// Calculate min and max of the span.
float smin = in[1], smax = in[1];
float smin = p1[1], smax = p1[1];
for (int i = 1; i < nv; ++i)
{
smin = rcMin(smin, in[i*3+1]);
smax = rcMax(smax, in[i*3+1]);
smin = rcMin(smin, p1[i*3+1]);
smax = rcMax(smax, p1[i*3+1]);
}
smin -= bmin[1];
smax -= bmin[1];
@@ -278,9 +326,12 @@ static void rasterizeTri(const float* v0, const float* v1, const float* v2,
unsigned short ismin = (unsigned short)rcClamp((int)floorf(smin * ich), 0, RC_SPAN_MAX_HEIGHT);
unsigned short ismax = (unsigned short)rcClamp((int)ceilf(smax * ich), (int)ismin+1, RC_SPAN_MAX_HEIGHT);
addSpan(hf, x, y, ismin, ismax, area, flagMergeThr);
if (!addSpan(hf, x, y, ismin, ismax, area, flagMergeThr))
return false;
}
}
return true;
}
/// @par
@@ -288,19 +339,23 @@ static void rasterizeTri(const float* v0, const float* v1, const float* v2,
/// No spans will be added if the triangle does not overlap the heightfield grid.
///
/// @see rcHeightfield
void rcRasterizeTriangle(rcContext* ctx, const float* v0, const float* v1, const float* v2,
bool rcRasterizeTriangle(rcContext* ctx, const float* v0, const float* v1, const float* v2,
const unsigned char area, rcHeightfield& solid,
const int flagMergeThr)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES);
const float ics = 1.0f/solid.cs;
const float ich = 1.0f/solid.ch;
rasterizeTri(v0, v1, v2, area, solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr);
if (!rasterizeTri(v0, v1, v2, area, solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcRasterizeTriangle: Out of memory.");
return false;
}
ctx->stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
return true;
}
/// @par
@@ -308,13 +363,13 @@ void rcRasterizeTriangle(rcContext* ctx, const float* v0, const float* v1, const
/// Spans will only be added for triangles that overlap the heightfield grid.
///
/// @see rcHeightfield
void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
bool rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
const int* tris, const unsigned char* areas, const int nt,
rcHeightfield& solid, const int flagMergeThr)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES);
const float ics = 1.0f/solid.cs;
const float ich = 1.0f/solid.ch;
@@ -325,10 +380,14 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
const float* v1 = &verts[tris[i*3+1]*3];
const float* v2 = &verts[tris[i*3+2]*3];
// Rasterize.
rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr);
if (!rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
return false;
}
}
ctx->stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
return true;
}
/// @par
@@ -336,13 +395,13 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
/// Spans will only be added for triangles that overlap the heightfield grid.
///
/// @see rcHeightfield
void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
bool rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
const unsigned short* tris, const unsigned char* areas, const int nt,
rcHeightfield& solid, const int flagMergeThr)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES);
const float ics = 1.0f/solid.cs;
const float ich = 1.0f/solid.ch;
@@ -353,10 +412,14 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
const float* v1 = &verts[tris[i*3+1]*3];
const float* v2 = &verts[tris[i*3+2]*3];
// Rasterize.
rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr);
if (!rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
return false;
}
}
ctx->stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
return true;
}
/// @par
@@ -364,12 +427,12 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const int /*nv*/,
/// Spans will only be added for triangles that overlap the heightfield grid.
///
/// @see rcHeightfield
void rcRasterizeTriangles(rcContext* ctx, const float* verts, const unsigned char* areas, const int nt,
bool rcRasterizeTriangles(rcContext* ctx, const float* verts, const unsigned char* areas, const int nt,
rcHeightfield& solid, const int flagMergeThr)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
rcScopedTimer timer(ctx, RC_TIMER_RASTERIZE_TRIANGLES);
const float ics = 1.0f/solid.cs;
const float ich = 1.0f/solid.ch;
@@ -380,8 +443,12 @@ void rcRasterizeTriangles(rcContext* ctx, const float* verts, const unsigned cha
const float* v1 = &verts[(i*3+1)*3];
const float* v2 = &verts[(i*3+2)*3];
// Rasterize.
rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr);
if (!rasterizeTri(v0, v1, v2, areas[i], solid, solid.bmin, solid.bmax, solid.cs, ics, ich, flagMergeThr))
{
ctx->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
return false;
}
}
ctx->stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
return true;
}

View File

@@ -286,7 +286,10 @@ static bool floodRegion(int x, int y, int i,
if (nr & RC_BORDER_REG) // Do not take borders into account.
continue;
if (nr != 0 && nr != r)
{
ar = nr;
break;
}
const rcCompactSpan& as = chf.spans[ai];
@@ -298,9 +301,12 @@ static bool floodRegion(int x, int y, int i,
const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2);
if (chf.areas[ai2] != area)
continue;
unsigned short nr = srcReg[ai2];
if (nr != 0 && nr != r)
ar = nr;
unsigned short nr2 = srcReg[ai2];
if (nr2 != 0 && nr2 != r)
{
ar = nr2;
break;
}
}
}
}
@@ -309,6 +315,7 @@ static bool floodRegion(int x, int y, int i,
srcReg[ci] = 0;
continue;
}
count++;
// Expand neighbours.
@@ -340,30 +347,44 @@ static unsigned short* expandRegions(int maxIter, unsigned short level,
rcCompactHeightfield& chf,
unsigned short* srcReg, unsigned short* srcDist,
unsigned short* dstReg, unsigned short* dstDist,
rcIntArray& stack)
rcIntArray& stack,
bool fillStack)
{
const int w = chf.width;
const int h = chf.height;
// Find cells revealed by the raised level.
stack.resize(0);
for (int y = 0; y < h; ++y)
if (fillStack)
{
for (int x = 0; x < w; ++x)
// Find cells revealed by the raised level.
stack.resize(0);
for (int y = 0; y < h; ++y)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
for (int x = 0; x < w; ++x)
{
if (chf.dist[i] >= level && srcReg[i] == 0 && chf.areas[i] != RC_NULL_AREA)
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
stack.push(x);
stack.push(y);
stack.push(i);
if (chf.dist[i] >= level && srcReg[i] == 0 && chf.areas[i] != RC_NULL_AREA)
{
stack.push(x);
stack.push(y);
stack.push(i);
}
}
}
}
}
else // use cells in the input stack
{
// mark all cells which already have a region
for (int j=0; j<stack.size(); j+=3)
{
int i = stack[j+2];
if (srcReg[i] != 0)
stack[j+2] = -1;
}
}
int iter = 0;
while (stack.size() > 0)
{
@@ -434,6 +455,61 @@ static unsigned short* expandRegions(int maxIter, unsigned short level,
}
static void sortCellsByLevel(unsigned short startLevel,
rcCompactHeightfield& chf,
unsigned short* srcReg,
unsigned int nbStacks, rcIntArray* stacks,
unsigned short loglevelsPerStack) // the levels per stack (2 in our case) as a bit shift
{
const int w = chf.width;
const int h = chf.height;
startLevel = startLevel >> loglevelsPerStack;
for (unsigned int j=0; j<nbStacks; ++j)
stacks[j].resize(0);
// put all cells in the level range into the appropriate stacks
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
if (chf.areas[i] == RC_NULL_AREA || srcReg[i] != 0)
continue;
int level = chf.dist[i] >> loglevelsPerStack;
int sId = startLevel - level;
if (sId >= (int)nbStacks)
continue;
if (sId < 0)
sId = 0;
stacks[sId].push(x);
stacks[sId].push(y);
stacks[sId].push(i);
}
}
}
}
static void appendStacks(rcIntArray& srcStack, rcIntArray& dstStack,
unsigned short* srcReg)
{
for (int j=0; j<srcStack.size(); j+=3)
{
int i = srcStack[j+2];
if ((i < 0) || (srcReg[i] != 0))
continue;
dstStack.push(srcStack[j]);
dstStack.push(srcStack[j+1]);
dstStack.push(srcStack[j+2]);
}
}
struct rcRegion
{
inline rcRegion(unsigned short i) :
@@ -441,7 +517,11 @@ struct rcRegion
id(i),
areaType(0),
remap(false),
visited(false)
visited(false),
overlap(false),
connectsToBorder(false),
ymin(0xffff),
ymax(0)
{}
int spanCount; // Number of spans belonging to this region
@@ -449,6 +529,9 @@ struct rcRegion
unsigned char areaType; // Are type.
bool remap;
bool visited;
bool overlap;
bool connectsToBorder;
unsigned short ymin, ymax;
rcIntArray connections;
rcIntArray floors;
};
@@ -678,25 +761,26 @@ static void walkContour(int x, int y, int i, int dir,
// Remove adjacent duplicates.
if (cont.size() > 1)
{
for (int i = 0; i < cont.size(); )
for (int j = 0; j < cont.size(); )
{
int ni = (i+1) % cont.size();
if (cont[i] == cont[ni])
int nj = (j+1) % cont.size();
if (cont[j] == cont[nj])
{
for (int j = i; j < cont.size()-1; ++j)
cont[j] = cont[j+1];
for (int k = j; k < cont.size()-1; ++k)
cont[k] = cont[k+1];
cont.pop();
}
else
++i;
++j;
}
}
}
static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegionSize,
unsigned short& maxRegionId,
rcCompactHeightfield& chf,
unsigned short* srcReg)
static bool mergeAndFilterRegions(rcContext* ctx, int minRegionArea, int mergeRegionSize,
unsigned short& maxRegionId,
rcCompactHeightfield& chf,
unsigned short* srcReg, rcIntArray& overlaps)
{
const int w = chf.width;
const int h = chf.height;
@@ -705,7 +789,7 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
rcRegion* regions = (rcRegion*)rcAlloc(sizeof(rcRegion)*nreg, RC_ALLOC_TEMP);
if (!regions)
{
ctx->log(RC_LOG_ERROR, "filterSmallRegions: Out of memory 'regions' (%d).", nreg);
ctx->log(RC_LOG_ERROR, "mergeAndFilterRegions: Out of memory 'regions' (%d).", nreg);
return false;
}
@@ -728,7 +812,6 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
rcRegion& reg = regions[r];
reg.spanCount++;
// Update floors.
for (int j = (int)c.index; j < ni; ++j)
{
@@ -736,6 +819,8 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
unsigned short floorId = srcReg[j];
if (floorId == 0 || floorId >= nreg)
continue;
if (floorId == r)
reg.overlap = true;
addUniqueFloorRegion(reg, floorId);
}
@@ -806,14 +891,14 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
connectsToBorder = true;
continue;
}
rcRegion& nreg = regions[creg.connections[j]];
if (nreg.visited)
rcRegion& neireg = regions[creg.connections[j]];
if (neireg.visited)
continue;
if (nreg.id == 0 || (nreg.id & RC_BORDER_REG))
if (neireg.id == 0 || (neireg.id & RC_BORDER_REG))
continue;
// Visit
stack.push(nreg.id);
nreg.visited = true;
stack.push(neireg.id);
neireg.visited = true;
}
}
@@ -831,7 +916,7 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
}
}
}
// Merge too small regions to neighbour regions.
int mergeCount = 0 ;
do
@@ -841,7 +926,9 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
{
rcRegion& reg = regions[i];
if (reg.id == 0 || (reg.id & RC_BORDER_REG))
continue;
continue;
if (reg.overlap)
continue;
if (reg.spanCount == 0)
continue;
@@ -858,7 +945,7 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
{
if (reg.connections[j] & RC_BORDER_REG) continue;
rcRegion& mreg = regions[reg.connections[j]];
if (mreg.id == 0 || (mreg.id & RC_BORDER_REG)) continue;
if (mreg.id == 0 || (mreg.id & RC_BORDER_REG) || mreg.overlap) continue;
if (mreg.spanCount < smallest &&
canMergeWithRegion(reg, mreg) &&
canMergeWithRegion(mreg, reg))
@@ -922,6 +1009,224 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
}
maxRegionId = regIdGen;
// Remap regions.
for (int i = 0; i < chf.spanCount; ++i)
{
if ((srcReg[i] & RC_BORDER_REG) == 0)
srcReg[i] = regions[srcReg[i]].id;
}
// Return regions that we found to be overlapping.
for (int i = 0; i < nreg; ++i)
if (regions[i].overlap)
overlaps.push(regions[i].id);
for (int i = 0; i < nreg; ++i)
regions[i].~rcRegion();
rcFree(regions);
return true;
}
static void addUniqueConnection(rcRegion& reg, int n)
{
for (int i = 0; i < reg.connections.size(); ++i)
if (reg.connections[i] == n)
return;
reg.connections.push(n);
}
static bool mergeAndFilterLayerRegions(rcContext* ctx, int minRegionArea,
unsigned short& maxRegionId,
rcCompactHeightfield& chf,
unsigned short* srcReg, rcIntArray& /*overlaps*/)
{
const int w = chf.width;
const int h = chf.height;
const int nreg = maxRegionId+1;
rcRegion* regions = (rcRegion*)rcAlloc(sizeof(rcRegion)*nreg, RC_ALLOC_TEMP);
if (!regions)
{
ctx->log(RC_LOG_ERROR, "mergeAndFilterLayerRegions: Out of memory 'regions' (%d).", nreg);
return false;
}
// Construct regions
for (int i = 0; i < nreg; ++i)
new(&regions[i]) rcRegion((unsigned short)i);
// Find region neighbours and overlapping regions.
rcIntArray lregs(32);
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
lregs.resize(0);
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
const unsigned short ri = srcReg[i];
if (ri == 0 || ri >= nreg) continue;
rcRegion& reg = regions[ri];
reg.spanCount++;
reg.ymin = rcMin(reg.ymin, s.y);
reg.ymax = rcMax(reg.ymax, s.y);
// Collect all region layers.
lregs.push(ri);
// Update neighbours
for (int dir = 0; dir < 4; ++dir)
{
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(dir);
const int ay = y + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
const unsigned short rai = srcReg[ai];
if (rai > 0 && rai < nreg && rai != ri)
addUniqueConnection(reg, rai);
if (rai & RC_BORDER_REG)
reg.connectsToBorder = true;
}
}
}
// Update overlapping regions.
for (int i = 0; i < lregs.size()-1; ++i)
{
for (int j = i+1; j < lregs.size(); ++j)
{
if (lregs[i] != lregs[j])
{
rcRegion& ri = regions[lregs[i]];
rcRegion& rj = regions[lregs[j]];
addUniqueFloorRegion(ri, lregs[j]);
addUniqueFloorRegion(rj, lregs[i]);
}
}
}
}
}
// Create 2D layers from regions.
unsigned short layerId = 1;
for (int i = 0; i < nreg; ++i)
regions[i].id = 0;
// Merge montone regions to create non-overlapping areas.
rcIntArray stack(32);
for (int i = 1; i < nreg; ++i)
{
rcRegion& root = regions[i];
// Skip already visited.
if (root.id != 0)
continue;
// Start search.
root.id = layerId;
stack.resize(0);
stack.push(i);
while (stack.size() > 0)
{
// Pop front
rcRegion& reg = regions[stack[0]];
for (int j = 0; j < stack.size()-1; ++j)
stack[j] = stack[j+1];
stack.resize(stack.size()-1);
const int ncons = (int)reg.connections.size();
for (int j = 0; j < ncons; ++j)
{
const int nei = reg.connections[j];
rcRegion& regn = regions[nei];
// Skip already visited.
if (regn.id != 0)
continue;
// Skip if the neighbour is overlapping root region.
bool overlap = false;
for (int k = 0; k < root.floors.size(); k++)
{
if (root.floors[k] == nei)
{
overlap = true;
break;
}
}
if (overlap)
continue;
// Deepen
stack.push(nei);
// Mark layer id
regn.id = layerId;
// Merge current layers to root.
for (int k = 0; k < regn.floors.size(); ++k)
addUniqueFloorRegion(root, regn.floors[k]);
root.ymin = rcMin(root.ymin, regn.ymin);
root.ymax = rcMax(root.ymax, regn.ymax);
root.spanCount += regn.spanCount;
regn.spanCount = 0;
root.connectsToBorder = root.connectsToBorder || regn.connectsToBorder;
}
}
layerId++;
}
// Remove small regions
for (int i = 0; i < nreg; ++i)
{
if (regions[i].spanCount > 0 && regions[i].spanCount < minRegionArea && !regions[i].connectsToBorder)
{
unsigned short reg = regions[i].id;
for (int j = 0; j < nreg; ++j)
if (regions[j].id == reg)
regions[j].id = 0;
}
}
// Compress region Ids.
for (int i = 0; i < nreg; ++i)
{
regions[i].remap = false;
if (regions[i].id == 0) continue; // Skip nil regions.
if (regions[i].id & RC_BORDER_REG) continue; // Skip external regions.
regions[i].remap = true;
}
unsigned short regIdGen = 0;
for (int i = 0; i < nreg; ++i)
{
if (!regions[i].remap)
continue;
unsigned short oldId = regions[i].id;
unsigned short newId = ++regIdGen;
for (int j = i; j < nreg; ++j)
{
if (regions[j].id == oldId)
{
regions[j].id = newId;
regions[j].remap = false;
}
}
}
maxRegionId = regIdGen;
// Remap regions.
for (int i = 0; i < chf.spanCount; ++i)
{
@@ -936,6 +1241,8 @@ static bool filterSmallRegions(rcContext* ctx, int minRegionArea, int mergeRegio
return true;
}
/// @par
///
/// This is usually the second to the last step in creating a fully built
@@ -950,7 +1257,7 @@ bool rcBuildDistanceField(rcContext* ctx, rcCompactHeightfield& chf)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_DISTANCEFIELD);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_DISTANCEFIELD);
if (chf.dist)
{
@@ -974,25 +1281,23 @@ bool rcBuildDistanceField(rcContext* ctx, rcCompactHeightfield& chf)
unsigned short maxDist = 0;
ctx->startTimer(RC_TIMER_BUILD_DISTANCEFIELD_DIST);
calculateDistanceField(chf, src, maxDist);
chf.maxDistance = maxDist;
ctx->stopTimer(RC_TIMER_BUILD_DISTANCEFIELD_DIST);
ctx->startTimer(RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
// Blur
if (boxBlur(chf, 1, src, dst) != src)
rcSwap(src, dst);
// Store distance.
chf.dist = src;
ctx->stopTimer(RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
{
rcScopedTimer timerDist(ctx, RC_TIMER_BUILD_DISTANCEFIELD_DIST);
ctx->stopTimer(RC_TIMER_BUILD_DISTANCEFIELD);
calculateDistanceField(chf, src, maxDist);
chf.maxDistance = maxDist;
}
{
rcScopedTimer timerBlur(ctx, RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
// Blur
if (boxBlur(chf, 1, src, dst) != src)
rcSwap(src, dst);
// Store distance.
chf.dist = src;
}
rcFree(dst);
@@ -1052,13 +1357,13 @@ bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_REGIONS);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS);
const int w = chf.width;
const int h = chf.height;
unsigned short id = 1;
rcScopedDelete<unsigned short> srcReg = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> srcReg((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP));
if (!srcReg)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'src' (%d).", chf.spanCount);
@@ -1067,7 +1372,7 @@ bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
const int nsweeps = rcMax(chf.width,chf.height);
rcScopedDelete<rcSweepSpan> sweeps = (rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP);
rcScopedDelete<rcSweepSpan> sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP));
if (!sweeps)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps);
@@ -1181,20 +1486,22 @@ bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
}
}
ctx->startTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Filter out small regions.
chf.maxRegions = id;
if (!filterSmallRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg))
return false;
{
rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER);
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Merge regions and filter out small regions.
rcIntArray overlaps;
chf.maxRegions = id;
if (!mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg, overlaps))
return false;
// Monotone partitioning does not generate overlapping regions.
}
// Store the result out.
for (int i = 0; i < chf.spanCount; ++i)
chf.spans[i].reg = srcReg[i];
ctx->stopTimer(RC_TIMER_BUILD_REGIONS);
return true;
}
@@ -1223,12 +1530,12 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_REGIONS);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS);
const int w = chf.width;
const int h = chf.height;
rcScopedDelete<unsigned short> buf = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount*4, RC_ALLOC_TEMP);
rcScopedDelete<unsigned short> buf((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount*4, RC_ALLOC_TEMP));
if (!buf)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegions: Out of memory 'tmp' (%d).", chf.spanCount*4);
@@ -1236,7 +1543,13 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
}
ctx->startTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
const int LOG_NB_STACKS = 3;
const int NB_STACKS = 1 << LOG_NB_STACKS;
rcIntArray lvlStacks[NB_STACKS];
for (int i=0; i<NB_STACKS; ++i)
lvlStacks[i].resize(1024);
rcIntArray stack(1024);
rcIntArray visited(1024);
@@ -1262,6 +1575,13 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
// Make sure border will not overflow.
const int bw = rcMin(w, borderSize);
const int bh = rcMin(h, borderSize);
if (regionId > 0xFFFB)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegions: Region ID overflow");
return false;
}
// Paint regions
paintRectRegion(0, bw, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
paintRectRegion(w-bw, w, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
@@ -1271,44 +1591,60 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
chf.borderSize = borderSize;
}
int sId = -1;
while (level > 0)
{
level = level >= 2 ? level-2 : 0;
ctx->startTimer(RC_TIMER_BUILD_REGIONS_EXPAND);
// Expand current regions until no empty connected cells found.
if (expandRegions(expandIters, level, chf, srcReg, srcDist, dstReg, dstDist, stack) != srcReg)
sId = (sId+1) & (NB_STACKS-1);
// ctx->startTimer(RC_TIMER_DIVIDE_TO_LEVELS);
if (sId == 0)
sortCellsByLevel(level, chf, srcReg, NB_STACKS, lvlStacks, 1);
else
appendStacks(lvlStacks[sId-1], lvlStacks[sId], srcReg); // copy left overs from last level
// ctx->stopTimer(RC_TIMER_DIVIDE_TO_LEVELS);
{
rcSwap(srcReg, dstReg);
rcSwap(srcDist, dstDist);
}
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_EXPAND);
ctx->startTimer(RC_TIMER_BUILD_REGIONS_FLOOD);
// Mark new regions with IDs.
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
rcScopedTimer timerExpand(ctx, RC_TIMER_BUILD_REGIONS_EXPAND);
// Expand current regions until no empty connected cells found.
if (expandRegions(expandIters, level, chf, srcReg, srcDist, dstReg, dstDist, lvlStacks[sId], false) != srcReg)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
if (chf.dist[i] < level || srcReg[i] != 0 || chf.areas[i] == RC_NULL_AREA)
continue;
if (floodRegion(x, y, i, level, regionId, chf, srcReg, srcDist, stack))
regionId++;
}
rcSwap(srcReg, dstReg);
rcSwap(srcDist, dstDist);
}
}
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FLOOD);
{
rcScopedTimer timerFloor(ctx, RC_TIMER_BUILD_REGIONS_FLOOD);
// Mark new regions with IDs.
for (int j = 0; j<lvlStacks[sId].size(); j += 3)
{
int x = lvlStacks[sId][j];
int y = lvlStacks[sId][j+1];
int i = lvlStacks[sId][j+2];
if (i >= 0 && srcReg[i] == 0)
{
if (floodRegion(x, y, i, level, regionId, chf, srcReg, srcDist, stack))
{
if (regionId == 0xFFFF)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegions: Region ID overflow");
return false;
}
regionId++;
}
}
}
}
}
// Expand current regions until no empty connected cells found.
if (expandRegions(expandIters*8, 0, chf, srcReg, srcDist, dstReg, dstDist, stack) != srcReg)
if (expandRegions(expandIters*8, 0, chf, srcReg, srcDist, dstReg, dstDist, stack, true) != srcReg)
{
rcSwap(srcReg, dstReg);
rcSwap(srcDist, dstDist);
@@ -1316,22 +1652,179 @@ bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
ctx->startTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Filter out small regions.
chf.maxRegions = regionId;
if (!filterSmallRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg))
return false;
ctx->stopTimer(RC_TIMER_BUILD_REGIONS_FILTER);
{
rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER);
// Merge regions and filter out smalle regions.
rcIntArray overlaps;
chf.maxRegions = regionId;
if (!mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg, overlaps))
return false;
// If overlapping regions were found during merging, split those regions.
if (overlaps.size() > 0)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegions: %d overlapping regions.", overlaps.size());
}
}
// Write the result out.
for (int i = 0; i < chf.spanCount; ++i)
chf.spans[i].reg = srcReg[i];
ctx->stopTimer(RC_TIMER_BUILD_REGIONS);
return true;
}
bool rcBuildLayerRegions(rcContext* ctx, rcCompactHeightfield& chf,
const int borderSize, const int minRegionArea)
{
rcAssert(ctx);
rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS);
const int w = chf.width;
const int h = chf.height;
unsigned short id = 1;
rcScopedDelete<unsigned short> srcReg((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP));
if (!srcReg)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'src' (%d).", chf.spanCount);
return false;
}
memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
const int nsweeps = rcMax(chf.width,chf.height);
rcScopedDelete<rcSweepSpan> sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP));
if (!sweeps)
{
ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps);
return false;
}
// Mark border regions.
if (borderSize > 0)
{
// Make sure border will not overflow.
const int bw = rcMin(w, borderSize);
const int bh = rcMin(h, borderSize);
// Paint regions
paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++;
chf.borderSize = borderSize;
}
rcIntArray prev(256);
// Sweep one line at a time.
for (int y = borderSize; y < h-borderSize; ++y)
{
// Collect spans from this row.
prev.resize(id+1);
memset(&prev[0],0,sizeof(int)*id);
unsigned short rid = 1;
for (int x = borderSize; x < w-borderSize; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
if (chf.areas[i] == RC_NULL_AREA) continue;
// -x
unsigned short previd = 0;
if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(0);
const int ay = y + rcGetDirOffsetY(0);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
if ((srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
previd = srcReg[ai];
}
if (!previd)
{
previd = rid++;
sweeps[previd].rid = previd;
sweeps[previd].ns = 0;
sweeps[previd].nei = 0;
}
// -y
if (rcGetCon(s,3) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(3);
const int ay = y + rcGetDirOffsetY(3);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
if (srcReg[ai] && (srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
{
unsigned short nr = srcReg[ai];
if (!sweeps[previd].nei || sweeps[previd].nei == nr)
{
sweeps[previd].nei = nr;
sweeps[previd].ns++;
prev[nr]++;
}
else
{
sweeps[previd].nei = RC_NULL_NEI;
}
}
}
srcReg[i] = previd;
}
}
// Create unique ID.
for (int i = 1; i < rid; ++i)
{
if (sweeps[i].nei != RC_NULL_NEI && sweeps[i].nei != 0 &&
prev[sweeps[i].nei] == (int)sweeps[i].ns)
{
sweeps[i].id = sweeps[i].nei;
}
else
{
sweeps[i].id = id++;
}
}
// Remap IDs
for (int x = borderSize; x < w-borderSize; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
if (srcReg[i] > 0 && srcReg[i] < rid)
srcReg[i] = sweeps[srcReg[i]].id;
}
}
}
{
rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER);
// Merge monotone regions to layers and remove small regions.
rcIntArray overlaps;
chf.maxRegions = id;
if (!mergeAndFilterLayerRegions(ctx, minRegionArea, chf.maxRegions, chf, srcReg, overlaps))
return false;
}
// Store the result out.
for (int i = 0; i < chf.spanCount; ++i)
chf.spans[i].reg = srcReg[i];
return true;
}

View File

@@ -1,58 +0,0 @@
#include "RecastTimer.h"
#if defined(WIN32)
// Win32
#include <windows.h>
rcTimeVal rcGetPerformanceTimer()
{
__int64 count;
QueryPerformanceCounter((LARGE_INTEGER*)&count);
return count;
}
int rcGetDeltaTimeUsec(rcTimeVal start, rcTimeVal end)
{
static __int64 freq = 0;
if (freq == 0)
QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
__int64 elapsed = end - start;
return (int)(elapsed*1000000 / freq);
}
#elif defined(__MACH__)
// OSX
#include <mach/mach_time.h>
rcTimeVal rcGetPerformanceTimer()
{
return mach_absolute_time();
}
int rcGetDeltaTimeUsec(rcTimeVal start, rcTimeVal end)
{
static mach_timebase_info_data_t timebaseInfo;
if (timebaseInfo.denom == 0)
mach_timebase_info(&timebaseInfo);
uint64_t elapsed = end - start;
uint64_t nanosec = elapsed * timebaseInfo.numer / timebaseInfo.denom;
return (int)(nanosec / 1000);
}
#else
// TODO: Linux, etc
rcTimeVal rcGetPerformanceTimer()
{
return 0;
}
int rcGetDeltaTimeUsec(rcTimeVal start, rcTimeVal end)
{
return 0;
}
#endif

View File

@@ -0,0 +1,22 @@
The version of Recast is 1.5.0, from:
https://github.com/recastnavigation/recastnavigation
Changes made:
* Recast/Source/RecastMesh.cpp: made buildMeshAdjacency() non-static so it can be used with recast-capi
* Recast/Include/Recast.h: Added forward declaration for buildMeshAdjacency()
The following additional files were added:
* recast-capi.cpp
* recast-capi.h
These expose a C interface to the Recast library, which has only C++ headers.
The version of Detour is 1.4, from:
https://code.google.com/archive/p/recastnavigation/downloads
Changes made:
* DetourStatNavMesh.h: use more portable definition of DT_STAT_NAVMESH_MAGIC
* DetourStatNavMesh.cpp: comment out some unused variables to avoid compiler warnings
* DetourStatNavMeshBuilder.h: add forward declaration for createBVTree
* DetourStatNavMeshBuilder.cpp: made createBVTree non-static for use with recast-capi
The CMakeLists.txt file has been added, since the original software does not include build files for the libraries.
~rdb

View File

@@ -68,17 +68,41 @@ int recast_createHeightfield(struct recast_heightfield *hf, int width, int heigh
}
void recast_markWalkableTriangles(const float walkableSlopeAngle,const float *verts, int nv,
const int *tris, int nt, unsigned char *flags)
const int *tris, int nt, unsigned char *areas)
{
INIT_SCTX();
rcMarkWalkableTriangles(sctx, walkableSlopeAngle, verts, nv, tris, nt, flags);
rcMarkWalkableTriangles(sctx, walkableSlopeAngle, verts, nv, tris, nt, areas);
}
void recast_rasterizeTriangles(const float *verts, int nv, const int *tris,
const unsigned char *flags, int nt, struct recast_heightfield *solid)
void recast_clearUnwalkableTriangles(const float walkableSlopeAngle, const float* verts, int nv,
const int* tris, int nt, unsigned char* areas)
{
INIT_SCTX();
rcRasterizeTriangles(sctx, verts, nv, tris, flags, nt, *(rcHeightfield *) solid);
rcClearUnwalkableTriangles(sctx, walkableSlopeAngle, verts, nv, tris, nt, areas);
}
int recast_addSpan(struct recast_heightfield *hf, const int x, const int y,
const unsigned short smin, const unsigned short smax,
const unsigned char area, const int flagMergeThr)
{
INIT_SCTX();
return rcAddSpan(sctx, *(rcHeightfield *) hf, x, y, smin, smax, area, flagMergeThr);
}
int recast_rasterizeTriangle(const float *v0, const float *v1, const float *v2,
const unsigned char area, struct recast_heightfield *solid,
const int flagMergeThr)
{
INIT_SCTX();
return rcRasterizeTriangle(sctx, v0, v1, v2, area, *(rcHeightfield *) solid, flagMergeThr);
}
int recast_rasterizeTriangles(const float *verts, const int nv, const int *tris,
const unsigned char *areas, const int nt, struct recast_heightfield *solid,
const int flagMergeThr)
{
INIT_SCTX();
return rcRasterizeTriangles(sctx, verts, nv, tris, areas, nt, *(rcHeightfield *) solid, flagMergeThr);
}
void recast_filterLedgeSpans(const int walkableHeight, const int walkableClimb,
@@ -100,6 +124,22 @@ void recast_filterLowHangingWalkableObstacles(const int walkableClimb, struct re
rcFilterLowHangingWalkableObstacles(sctx, walkableClimb, *(rcHeightfield *) solid);
}
int recast_getHeightFieldSpanCount(struct recast_heightfield *hf)
{
INIT_SCTX();
return rcGetHeightFieldSpanCount(sctx, *(rcHeightfield *) hf);
}
struct recast_heightfieldLayerSet *recast_newHeightfieldLayerSet(void)
{
return (struct recast_heightfieldLayerSet *) rcAllocHeightfieldLayerSet();
}
void recast_destroyHeightfieldLayerSet(struct recast_heightfieldLayerSet *lset)
{
rcFreeHeightfieldLayerSet( (rcHeightfieldLayerSet *) lset);
}
struct recast_compactHeightfield *recast_newCompactHeightfield(void)
{
return (struct recast_compactHeightfield *) rcAllocCompactHeightfield();
@@ -124,18 +164,68 @@ int recast_erodeWalkableArea(int radius, struct recast_compactHeightfield *chf)
return rcErodeWalkableArea(sctx, radius, *(rcCompactHeightfield *) chf);
}
int recast_medianFilterWalkableArea(struct recast_compactHeightfield *chf)
{
INIT_SCTX();
return rcMedianFilterWalkableArea(sctx, *(rcCompactHeightfield *) chf);
}
void recast_markBoxArea(const float *bmin, const float *bmax, unsigned char areaId,
struct recast_compactHeightfield *chf)
{
INIT_SCTX();
rcMarkBoxArea(sctx, bmin, bmax, areaId, *(rcCompactHeightfield *) chf);
}
void recast_markConvexPolyArea(const float* verts, const int nverts,
const float hmin, const float hmax, unsigned char areaId,
struct recast_compactHeightfield *chf)
{
INIT_SCTX();
rcMarkConvexPolyArea(sctx, verts, nverts, hmin, hmax, areaId, *(rcCompactHeightfield *) chf);
}
int recast_offsetPoly(const float* verts, const int nverts,
const float offset, float *outVerts, const int maxOutVerts)
{
return rcOffsetPoly(verts, nverts, offset, outVerts, maxOutVerts);
}
void recast_markCylinderArea(const float* pos, const float r, const float h,
unsigned char areaId, struct recast_compactHeightfield *chf)
{
INIT_SCTX();
rcMarkCylinderArea(sctx, pos, r, h, areaId, *(rcCompactHeightfield *) chf);
}
int recast_buildDistanceField(struct recast_compactHeightfield *chf)
{
INIT_SCTX();
return rcBuildDistanceField(sctx, *(rcCompactHeightfield *) chf);
}
int recast_buildRegions(struct recast_compactHeightfield *chf, int borderSize,
int minRegionSize, int mergeRegionSize)
int recast_buildRegions(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea, const int mergeRegionArea)
{
INIT_SCTX();
return rcBuildRegions(sctx, *(rcCompactHeightfield *) chf, borderSize,
minRegionSize, mergeRegionSize);
minRegionArea, mergeRegionArea);
}
int recast_buildLayerRegions(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea)
{
INIT_SCTX();
return rcBuildLayerRegions(sctx, *(rcCompactHeightfield *) chf, borderSize,
minRegionArea);
}
int recast_buildRegionsMonotone(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea, const int mergeRegionArea)
{
INIT_SCTX();
return rcBuildRegionsMonotone(sctx, *(rcCompactHeightfield *) chf, borderSize,
minRegionArea, mergeRegionArea);
}
struct recast_contourSet *recast_newContourSet(void)
@@ -149,10 +239,11 @@ void recast_destroyContourSet(struct recast_contourSet *contourSet)
}
int recast_buildContours(struct recast_compactHeightfield *chf,
const float maxError, const int maxEdgeLen, struct recast_contourSet *cset)
const float maxError, const int maxEdgeLen, struct recast_contourSet *cset,
const int buildFlags)
{
INIT_SCTX();
return rcBuildContours(sctx, *(rcCompactHeightfield *) chf, maxError, maxEdgeLen, *(rcContourSet *) cset);
return rcBuildContours(sctx, *(rcCompactHeightfield *) chf, maxError, maxEdgeLen, *(rcContourSet *) cset, buildFlags);
}
struct recast_polyMesh *recast_newPolyMesh(void)
@@ -165,10 +256,22 @@ void recast_destroyPolyMesh(struct recast_polyMesh *polyMesh)
rcFreePolyMesh((rcPolyMesh *) polyMesh);
}
int recast_buildPolyMesh(struct recast_contourSet *cset, int nvp, struct recast_polyMesh *mesh)
int recast_buildPolyMesh(struct recast_contourSet *cset, const int nvp, struct recast_polyMesh *mesh)
{
INIT_SCTX();
return rcBuildPolyMesh(sctx, *(rcContourSet *) cset, nvp, * (rcPolyMesh *) mesh);
return rcBuildPolyMesh(sctx, *(rcContourSet *) cset, nvp, *(rcPolyMesh *) mesh);
}
int recast_mergePolyMeshes(struct recast_polyMesh **meshes, const int nmeshes, struct recast_polyMesh *mesh)
{
INIT_SCTX();
return rcMergePolyMeshes(sctx, (rcPolyMesh **) meshes, nmeshes, *(rcPolyMesh *) mesh);
}
int recast_copyPolyMesh(const struct recast_polyMesh *src, struct recast_polyMesh *dst)
{
INIT_SCTX();
return rcCopyPolyMesh(sctx, *(const rcPolyMesh *) src, *(rcPolyMesh *) dst);
}
unsigned short *recast_polyMeshGetVerts(struct recast_polyMesh *mesh, int *nverts)
@@ -240,6 +343,12 @@ int recast_buildPolyMeshDetail(const struct recast_polyMesh *mesh, const struct
sampleDist, sampleMaxError, *(rcPolyMeshDetail *) dmesh);
}
int recast_mergePolyMeshDetails(struct recast_polyMeshDetail **meshes, const int nmeshes, struct recast_polyMeshDetail *mesh)
{
INIT_SCTX();
return rcMergePolyMeshDetails(sctx, (rcPolyMeshDetail **) meshes, nmeshes, *(rcPolyMeshDetail *) mesh);
}
float *recast_polyMeshDetailGetVerts(struct recast_polyMeshDetail *mesh, int *nverts)
{
rcPolyMeshDetail *dmesh = (rcPolyMeshDetail *)mesh;

View File

@@ -38,12 +38,13 @@ struct recast_polyMesh;
struct recast_polyMeshDetail;
struct recast_heightfield;
struct recast_compactHeightfield;
struct recast_heightfieldLayerSet;
struct recast_contourSet;
enum recast_SpanFlags
enum recast_BuildContoursFlags
{
RECAST_WALKABLE = 0x01,
RECAST_REACHABLE = 0x02
RECAST_CONTOUR_TESS_WALL_EDGES = 0x01,
RECAST_CONTOUR_TESS_AREA_EDGES = 0x02,
};
int recast_buildMeshAdjacency(unsigned short* polys, const int npolys,
@@ -61,10 +62,22 @@ int recast_createHeightfield(struct recast_heightfield *hf, int width, int heigh
const float *bmin, const float* bmax, float cs, float ch);
void recast_markWalkableTriangles(const float walkableSlopeAngle,const float *verts, int nv,
const int *tris, int nt, unsigned char *flags);
const int *tris, int nt, unsigned char *areas);
void recast_rasterizeTriangles(const float *verts, int nv, const int *tris,
const unsigned char *flags, int nt, struct recast_heightfield *solid);
void recast_clearUnwalkableTriangles(const float walkableSlopeAngle, const float* verts, int nv,
const int* tris, int nt, unsigned char* areas);
int recast_addSpan(struct recast_heightfield *hf, const int x, const int y,
const unsigned short smin, const unsigned short smax,
const unsigned char area, const int flagMergeThr);
int recast_rasterizeTriangle(const float* v0, const float* v1, const float* v2,
const unsigned char area, struct recast_heightfield *solid,
const int flagMergeThr);
int recast_rasterizeTriangles(const float *verts, const int nv, const int *tris,
const unsigned char *areas, const int nt, struct recast_heightfield *solid,
const int flagMergeThr);
void recast_filterLedgeSpans(const int walkableHeight, const int walkableClimb,
struct recast_heightfield *solid);
@@ -73,6 +86,12 @@ void recast_filterWalkableLowHeightSpans(int walkableHeight, struct recast_heigh
void recast_filterLowHangingWalkableObstacles(const int walkableClimb, struct recast_heightfield *solid);
int recast_getHeightFieldSpanCount(struct recast_heightfield *hf);
struct recast_heightfieldLayerSet *recast_newHeightfieldLayerSet(void);
void recast_destroyHeightfieldLayerSet(struct recast_heightfieldLayerSet *lset);
struct recast_compactHeightfield *recast_newCompactHeightfield(void);
void recast_destroyCompactHeightfield(struct recast_compactHeightfield *compactHeightfield);
@@ -82,10 +101,31 @@ int recast_buildCompactHeightfield(const int walkableHeight, const int walkableC
int recast_erodeWalkableArea(int radius, struct recast_compactHeightfield *chf);
int recast_medianFilterWalkableArea(struct recast_compactHeightfield *chf);
void recast_markBoxArea(const float *bmin, const float *bmax, unsigned char areaId,
struct recast_compactHeightfield *chf);
void recast_markConvexPolyArea(const float* verts, const int nverts,
const float hmin, const float hmax, unsigned char areaId,
struct recast_compactHeightfield *chf);
int recast_offsetPoly(const float* verts, const int nverts,
const float offset, float *outVerts, const int maxOutVerts);
void recast_markCylinderArea(const float* pos, const float r, const float h,
unsigned char areaId, struct recast_compactHeightfield *chf);
int recast_buildDistanceField(struct recast_compactHeightfield *chf);
int recast_buildRegions(struct recast_compactHeightfield *chf, int borderSize,
int minRegionSize, int mergeRegionSize);
int recast_buildRegions(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea, const int mergeRegionArea);
int recast_buildLayerRegions(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea);
int recast_buildRegionsMonotone(struct recast_compactHeightfield *chf,
const int borderSize, const int minRegionArea, const int mergeRegionArea);
/* Contour set */
@@ -94,7 +134,8 @@ struct recast_contourSet *recast_newContourSet(void);
void recast_destroyContourSet(struct recast_contourSet *contourSet);
int recast_buildContours(struct recast_compactHeightfield *chf,
const float maxError, const int maxEdgeLen, struct recast_contourSet *cset);
const float maxError, const int maxEdgeLen, struct recast_contourSet *cset,
const int buildFlags);
/* Poly mesh */
@@ -102,7 +143,11 @@ struct recast_polyMesh *recast_newPolyMesh(void);
void recast_destroyPolyMesh(struct recast_polyMesh *polyMesh);
int recast_buildPolyMesh(struct recast_contourSet *cset, int nvp, struct recast_polyMesh *mesh);
int recast_buildPolyMesh(struct recast_contourSet *cset, const int nvp, struct recast_polyMesh *mesh);
int recast_mergePolyMeshes(struct recast_polyMesh **meshes, const int nmeshes, struct recast_polyMesh *mesh);
int recast_copyPolyMesh(const struct recast_polyMesh *src, struct recast_polyMesh *dst);
unsigned short *recast_polyMeshGetVerts(struct recast_polyMesh *mesh, int *nverts);
@@ -121,6 +166,8 @@ void recast_destroyPolyMeshDetail(struct recast_polyMeshDetail *polyMeshDetail);
int recast_buildPolyMeshDetail(const struct recast_polyMesh *mesh, const struct recast_compactHeightfield *chf,
const float sampleDist, const float sampleMaxError, struct recast_polyMeshDetail *dmesh);
int recast_mergePolyMeshDetails(struct recast_polyMeshDetail **meshes, const int nmeshes, struct recast_polyMeshDetail *mesh);
float *recast_polyMeshDetailGetVerts(struct recast_polyMeshDetail *mesh, int *nverts);
unsigned char *recast_polyMeshDetailGetTris(struct recast_polyMeshDetail *mesh, int *ntris);

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