summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--COPYRIGHT.txt6
-rw-r--r--core/bind/core_bind.cpp3
-rw-r--r--core/class_db.cpp13
-rw-r--r--core/class_db.h1
-rw-r--r--core/image.cpp15
-rw-r--r--core/io/marshalls.cpp11
-rw-r--r--core/io/resource_format_binary.cpp3
-rw-r--r--core/math/audio_frame.h9
-rw-r--r--core/math/basis.cpp4
-rw-r--r--core/math/basis.h4
-rw-r--r--core/math/expression.cpp6
-rw-r--r--core/object.cpp3
-rw-r--r--core/os/file_access.cpp32
-rw-r--r--core/os/file_access.h3
-rw-r--r--core/os/input.cpp1
-rw-r--r--core/os/input.h4
-rw-r--r--core/os/os.cpp10
-rw-r--r--core/os/os.h5
-rw-r--r--core/packed_data_container.cpp3
-rw-r--r--core/project_settings.cpp6
-rw-r--r--core/resource.cpp20
-rw-r--r--core/resource.h10
-rw-r--r--core/ustring.cpp18
-rw-r--r--core/ustring.h8
-rw-r--r--core/variant.cpp38
-rw-r--r--core/variant_call.cpp2
-rw-r--r--core/variant_op.cpp12
-rw-r--r--core/variant_parser.cpp3
-rw-r--r--doc/classes/AnimatedSprite.xml2
-rw-r--r--doc/classes/AudioEffectInstance.xml15
-rw-r--r--doc/classes/AudioEffectSpectrumAnalyzer.xml23
-rw-r--r--doc/classes/AudioEffectSpectrumAnalyzerInstance.xml31
-rw-r--r--doc/classes/AudioServer.xml12
-rw-r--r--doc/classes/AudioStreamGenerator.xml21
-rw-r--r--doc/classes/AudioStreamGeneratorPlayback.xml57
-rw-r--r--doc/classes/AudioStreamPlaybackResampled.xml15
-rw-r--r--doc/classes/AudioStreamPlayer.xml6
-rw-r--r--doc/classes/AudioStreamPlayer2D.xml6
-rw-r--r--doc/classes/AudioStreamPlayer3D.xml6
-rw-r--r--doc/classes/Basis.xml16
-rw-r--r--doc/classes/CanvasItem.xml2
-rw-r--r--doc/classes/CanvasLayer.xml4
-rw-r--r--doc/classes/EditorFeatureProfile.xml131
-rw-r--r--doc/classes/EditorInterface.xml6
-rw-r--r--doc/classes/File.xml10
-rw-r--r--doc/classes/MainLoop.xml24
-rw-r--r--doc/classes/MeshLibrary.xml18
-rw-r--r--doc/classes/Node.xml29
-rw-r--r--doc/classes/ProjectSettings.xml2
-rw-r--r--doc/classes/RandomNumberGenerator.xml10
-rw-r--r--doc/classes/ResourceSaver.xml2
-rw-r--r--doc/classes/SceneTree.xml1
-rw-r--r--doc/classes/Slider.xml4
-rw-r--r--doc/classes/Spatial.xml2
-rw-r--r--doc/classes/String.xml8
-rw-r--r--doc/classes/StyleBoxFlat.xml6
-rw-r--r--doc/classes/TextEdit.xml3
-rw-r--r--doc/classes/TextureRect.xml12
-rw-r--r--doc/classes/Thread.xml2
-rw-r--r--doc/classes/TileMap.xml2
-rw-r--r--doc/classes/Transform.xml4
-rw-r--r--doc/classes/VSlider.xml2
-rw-r--r--doc/classes/VisibilityNotifier.xml1
-rw-r--r--doc/classes/VisibilityNotifier2D.xml1
-rw-r--r--doc/classes/VisualShaderNodeBooleanConstant.xml19
-rw-r--r--doc/classes/VisualShaderNodeBooleanUniform.xml15
-rw-r--r--doc/classes/VisualShaderNodeColorFunc.xml23
-rw-r--r--doc/classes/VisualShaderNodeDeterminant.xml15
-rw-r--r--doc/classes/VisualShaderNodeFaceForward.xml15
-rw-r--r--doc/classes/VisualShaderNodeIf.xml15
-rw-r--r--doc/classes/VisualShaderNodeOuterProduct.xml15
-rw-r--r--doc/classes/VisualShaderNodeScalarClamp.xml15
-rw-r--r--doc/classes/VisualShaderNodeScalarDerivativeFunc.xml25
-rw-r--r--doc/classes/VisualShaderNodeScalarFunc.xml22
-rw-r--r--doc/classes/VisualShaderNodeScalarOp.xml2
-rw-r--r--doc/classes/VisualShaderNodeScalarSmoothStep.xml15
-rw-r--r--doc/classes/VisualShaderNodeSwitch.xml15
-rw-r--r--doc/classes/VisualShaderNodeTransformFunc.xml23
-rw-r--r--doc/classes/VisualShaderNodeTransformMult.xml4
-rw-r--r--doc/classes/VisualShaderNodeVectorClamp.xml15
-rw-r--r--doc/classes/VisualShaderNodeVectorDerivativeFunc.xml25
-rw-r--r--doc/classes/VisualShaderNodeVectorDistance.xml15
-rw-r--r--doc/classes/VisualShaderNodeVectorFunc.xml56
-rw-r--r--doc/classes/VisualShaderNodeVectorOp.xml6
-rw-r--r--doc/classes/VisualShaderNodeVectorRefract.xml15
-rw-r--r--doc/classes/VisualShaderNodeVectorScalarSmoothStep.xml15
-rw-r--r--doc/classes/VisualShaderNodeVectorScalarStep.xml15
-rw-r--r--doc/classes/VisualShaderNodeVectorSmoothStep.xml15
-rw-r--r--drivers/gles2/rasterizer_canvas_gles2.cpp6
-rw-r--r--drivers/gles2/rasterizer_scene_gles2.cpp18
-rw-r--r--drivers/gles2/rasterizer_storage_gles2.cpp10
-rw-r--r--drivers/gles2/shaders/effect_blur.glsl5
-rw-r--r--drivers/gles3/rasterizer_scene_gles3.cpp15
-rw-r--r--drivers/gles3/rasterizer_storage_gles3.cpp21
-rw-r--r--drivers/gles3/shader_gles3.h4
-rw-r--r--drivers/gles3/shaders/effect_blur.glsl5
-rw-r--r--drivers/unix/os_unix.cpp1
-rw-r--r--drivers/windows/semaphore_windows.cpp3
-rw-r--r--editor/animation_track_editor.cpp231
-rw-r--r--editor/animation_track_editor.h11
-rw-r--r--editor/collada/collada.cpp3
-rw-r--r--editor/connections_dialog.cpp131
-rw-r--r--editor/connections_dialog.h12
-rw-r--r--editor/create_dialog.cpp24
-rw-r--r--editor/create_dialog.h2
-rw-r--r--editor/doc/doc_dump.cpp6
-rw-r--r--editor/editor_feature_profile.cpp889
-rw-r--r--editor/editor_feature_profile.h142
-rw-r--r--editor/editor_folding.cpp41
-rw-r--r--editor/editor_folding.h2
-rw-r--r--editor/editor_inspector.cpp36
-rw-r--r--editor/editor_inspector.h4
-rw-r--r--editor/editor_node.cpp146
-rw-r--r--editor/editor_node.h7
-rw-r--r--editor/editor_properties.cpp9
-rw-r--r--editor/editor_properties_array_dict.cpp6
-rw-r--r--editor/editor_settings.cpp12
-rw-r--r--editor/editor_settings.h1
-rw-r--r--editor/editor_themes.cpp4
-rw-r--r--editor/filesystem_dock.cpp51
-rw-r--r--editor/filesystem_dock.h5
-rw-r--r--editor/icons/icon_auto_key.svg56
-rw-r--r--editor/icons/icon_sprite_sheet.svg61
-rw-r--r--editor/import/editor_scene_importer_gltf.cpp7
-rw-r--r--editor/import/resource_importer_scene.cpp275
-rw-r--r--editor/import/resource_importer_scene.h2
-rw-r--r--editor/output_strings.cpp3
-rw-r--r--editor/plugins/animation_player_editor_plugin.cpp5
-rw-r--r--editor/plugins/animation_tree_player_editor_plugin.cpp15
-rw-r--r--editor/plugins/asset_library_editor_plugin.cpp6
-rw-r--r--editor/plugins/baked_lightmap_editor_plugin.cpp3
-rw-r--r--editor/plugins/canvas_item_editor_plugin.cpp168
-rw-r--r--editor/plugins/canvas_item_editor_plugin.h3
-rw-r--r--editor/plugins/item_list_editor_plugin.h2
-rw-r--r--editor/plugins/mesh_instance_editor_plugin.cpp54
-rw-r--r--editor/plugins/mesh_library_editor_plugin.cpp3
-rw-r--r--editor/plugins/polygon_2d_editor_plugin.cpp3
-rw-r--r--editor/plugins/script_editor_plugin.cpp2
-rw-r--r--editor/plugins/script_text_editor.cpp4
-rw-r--r--editor/plugins/spatial_editor_plugin.cpp9
-rw-r--r--editor/plugins/sprite_editor_plugin.cpp287
-rw-r--r--editor/plugins/sprite_editor_plugin.h19
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.cpp230
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.h17
-rw-r--r--editor/plugins/tile_set_editor_plugin.cpp60
-rw-r--r--editor/plugins/visual_shader_editor_plugin.cpp64
-rw-r--r--editor/plugins/visual_shader_editor_plugin.h1
-rw-r--r--editor/project_settings_editor.cpp6
-rw-r--r--editor/property_editor.cpp21
-rw-r--r--editor/scene_tree_dock.cpp283
-rw-r--r--editor/scene_tree_dock.h5
-rw-r--r--editor/scene_tree_editor.cpp63
-rw-r--r--editor/scene_tree_editor.h4
-rwxr-xr-xeditor/translations/extract.py2
-rw-r--r--main/input_default.cpp23
-rw-r--r--main/input_default.h4
-rw-r--r--main/performance.cpp3
-rw-r--r--main/tests/test_gdscript.cpp27
-rw-r--r--modules/assimp/editor_scene_importer_assimp.cpp2439
-rw-r--r--modules/assimp/editor_scene_importer_assimp.h76
-rw-r--r--modules/dds/texture_loader_dds.cpp3
-rw-r--r--modules/enet/networked_multiplayer_enet.cpp7
-rw-r--r--modules/etc/image_etc.cpp3
-rw-r--r--modules/gdnative/gdnative_api.json19
-rw-r--r--modules/gdnative/include/net/godot_net.h29
-rw-r--r--modules/gdnative/net/SCsub8
-rw-r--r--modules/gdnative/net/webrtc_peer_gdnative.cpp45
-rw-r--r--modules/gdscript/gdscript.cpp5
-rw-r--r--modules/gdscript/gdscript.h1
-rw-r--r--modules/gdscript/gdscript_compiler.cpp23
-rw-r--r--modules/gdscript/gdscript_editor.cpp9
-rw-r--r--modules/gdscript/gdscript_parser.cpp70
-rw-r--r--modules/gdscript/gdscript_tokenizer.cpp17
-rw-r--r--modules/mobile_vr/doc_classes/MobileVRInterface.xml11
-rw-r--r--modules/mobile_vr/mobile_vr_interface.cpp13
-rw-r--r--modules/mobile_vr/mobile_vr_interface.h3
-rw-r--r--modules/mono/csharp_script.cpp29
-rw-r--r--modules/mono/csharp_script.h1
-rw-r--r--modules/mono/editor/bindings_generator.cpp5
-rw-r--r--modules/opensimplex/doc_classes/OpenSimplexNoise.xml8
-rw-r--r--modules/squish/image_compress_squish.cpp3
-rw-r--r--modules/vhacd/SCsub38
-rw-r--r--modules/vhacd/config.py6
-rw-r--r--modules/vhacd/register_types.cpp88
-rw-r--r--modules/vhacd/register_types.h32
-rw-r--r--modules/visual_script/visual_script_builtin_funcs.cpp3
-rw-r--r--modules/visual_script/visual_script_expression.cpp3
-rw-r--r--modules/visual_script/visual_script_func_nodes.cpp3
-rw-r--r--modules/webrtc/SCsub16
-rw-r--r--modules/webrtc/config.py13
-rw-r--r--modules/webrtc/register_types.cpp55
-rw-r--r--modules/webrtc/register_types.h32
-rw-r--r--modules/webrtc/webrtc_peer.cpp81
-rw-r--r--modules/webrtc/webrtc_peer.h86
-rw-r--r--modules/webrtc/webrtc_peer_gdnative.cpp114
-rw-r--r--modules/webrtc/webrtc_peer_gdnative.h78
-rw-r--r--modules/webrtc/webrtc_peer_js.cpp455
-rw-r--r--modules/webrtc/webrtc_peer_js.h88
-rw-r--r--modules/websocket/register_types.cpp19
-rw-r--r--platform/android/java/src/org/godotengine/godot/Godot.java10
-rw-r--r--platform/android/java/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java3
-rw-r--r--platform/android/java/src/org/godotengine/godot/GodotDownloaderService.java1
-rw-r--r--platform/android/java/src/org/godotengine/godot/GodotIO.java33
-rw-r--r--platform/android/java/src/org/godotengine/godot/GodotPaymentV3.java8
-rw-r--r--platform/android/java/src/org/godotengine/godot/GodotView.java8
-rw-r--r--platform/android/java/src/org/godotengine/godot/input/GodotEditText.java11
-rw-r--r--platform/android/java/src/org/godotengine/godot/input/InputManagerV16.java1
-rw-r--r--platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java4
-rw-r--r--platform/android/java/src/org/godotengine/godot/payments/HandlePurchaseTask.java12
-rw-r--r--platform/android/java/src/org/godotengine/godot/payments/PaymentsManager.java7
-rw-r--r--platform/android/java/src/org/godotengine/godot/payments/PurchaseTask.java12
-rw-r--r--platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java7
-rw-r--r--platform/android/java/src/org/godotengine/godot/payments/ValidateTask.java21
-rw-r--r--platform/android/java/src/org/godotengine/godot/utils/CustomSSLSocketFactory.java2
-rw-r--r--platform/android/java/src/org/godotengine/godot/utils/HttpRequester.java8
-rw-r--r--platform/android/java/src/org/godotengine/godot/utils/RequestParams.java1
-rw-r--r--platform/android/os_android.cpp8
-rw-r--r--platform/android/os_android.h3
-rw-r--r--platform/haiku/os_haiku.cpp4
-rw-r--r--platform/haiku/os_haiku.h1
-rw-r--r--platform/iphone/os_iphone.cpp6
-rw-r--r--platform/iphone/os_iphone.h3
-rw-r--r--platform/javascript/SCsub7
-rw-r--r--platform/javascript/id_handler.js62
-rw-r--r--platform/osx/os_osx.h1
-rw-r--r--platform/osx/os_osx.mm15
-rw-r--r--platform/server/os_server.cpp6
-rw-r--r--platform/server/os_server.h3
-rw-r--r--platform/uwp/os_uwp.cpp5
-rw-r--r--platform/uwp/os_uwp.h1
-rw-r--r--platform/windows/detect.py2
-rw-r--r--platform/windows/os_windows.cpp13
-rw-r--r--platform/windows/os_windows.h1
-rw-r--r--platform/x11/os_x11.cpp11
-rw-r--r--platform/x11/os_x11.h1
-rw-r--r--scene/2d/area_2d.cpp5
-rw-r--r--scene/2d/audio_stream_player_2d.cpp6
-rw-r--r--scene/2d/audio_stream_player_2d.h2
-rw-r--r--scene/2d/light_occluder_2d.cpp61
-rw-r--r--scene/2d/light_occluder_2d.h9
-rw-r--r--scene/2d/tile_map.cpp6
-rw-r--r--scene/3d/area.cpp4
-rw-r--r--scene/3d/audio_stream_player_3d.cpp6
-rw-r--r--scene/3d/audio_stream_player_3d.h2
-rw-r--r--scene/3d/light.cpp3
-rw-r--r--scene/3d/skeleton.cpp5
-rw-r--r--scene/3d/spatial.cpp3
-rw-r--r--scene/animation/animation_blend_tree.cpp2
-rw-r--r--scene/animation/animation_cache.cpp3
-rw-r--r--scene/animation/animation_tree.cpp17
-rw-r--r--scene/animation/animation_tree_player.cpp15
-rw-r--r--scene/animation/skeleton_ik.cpp2
-rw-r--r--scene/audio/audio_stream_player.cpp6
-rw-r--r--scene/audio/audio_stream_player.h3
-rw-r--r--scene/gui/file_dialog.cpp4
-rw-r--r--scene/gui/rich_text_label.cpp3
-rw-r--r--scene/gui/tab_container.cpp44
-rw-r--r--scene/gui/tab_container.h3
-rw-r--r--scene/gui/text_edit.cpp7
-rw-r--r--scene/gui/text_edit.h1
-rw-r--r--scene/gui/tree.cpp44
-rw-r--r--scene/main/node.cpp8
-rw-r--r--scene/main/viewport.cpp2
-rw-r--r--scene/register_scene_types.cpp2
-rw-r--r--scene/resources/mesh.cpp45
-rw-r--r--scene/resources/mesh.h7
-rw-r--r--scene/resources/resource_format_text.cpp67
-rw-r--r--scene/resources/resource_format_text.h9
-rw-r--r--scene/resources/sky.cpp8
-rw-r--r--scene/resources/sky.h2
-rw-r--r--scene/resources/surface_tool.cpp53
-rw-r--r--scene/resources/surface_tool.h8
-rw-r--r--scene/resources/visual_shader.cpp5
-rw-r--r--scene/resources/visual_shader_nodes.cpp137
-rw-r--r--scene/resources/visual_shader_nodes.h44
-rw-r--r--servers/audio/effects/audio_effect_spectrum_analyzer.cpp249
-rw-r--r--servers/audio/effects/audio_effect_spectrum_analyzer.h76
-rw-r--r--servers/audio/effects/audio_stream_generator.cpp182
-rw-r--r--servers/audio/effects/audio_stream_generator.h66
-rw-r--r--servers/audio_server.cpp10
-rw-r--r--servers/audio_server.h1
-rw-r--r--servers/physics/body_sw.cpp9
-rw-r--r--servers/physics_2d/body_2d_sw.cpp9
-rw-r--r--servers/register_server_types.cpp10
-rw-r--r--servers/visual/shader_language.cpp6
-rw-r--r--servers/visual/visual_server_canvas.cpp22
-rw-r--r--servers/visual/visual_server_scene.cpp21
-rw-r--r--servers/visual/visual_server_viewport.cpp4
-rw-r--r--thirdparty/README.md26
-rw-r--r--thirdparty/vhacd/0001-bullet-namespace.patch213
-rw-r--r--thirdparty/vhacd/0002-fpermissive-fix.patch53
-rw-r--r--thirdparty/vhacd/LICENSE29
-rw-r--r--thirdparty/vhacd/inc/FloatMath.h525
-rw-r--r--thirdparty/vhacd/inc/btAlignedAllocator.h113
-rw-r--r--thirdparty/vhacd/inc/btAlignedObjectArray.h456
-rw-r--r--thirdparty/vhacd/inc/btConvexHullComputer.h105
-rw-r--r--thirdparty/vhacd/inc/btMinMax.h73
-rw-r--r--thirdparty/vhacd/inc/btScalar.h573
-rw-r--r--thirdparty/vhacd/inc/btVector3.h723
-rw-r--r--thirdparty/vhacd/inc/vhacdCircularList.h79
-rw-r--r--thirdparty/vhacd/inc/vhacdCircularList.inl161
-rw-r--r--thirdparty/vhacd/inc/vhacdICHull.h98
-rw-r--r--thirdparty/vhacd/inc/vhacdManifoldMesh.h142
-rw-r--r--thirdparty/vhacd/inc/vhacdMesh.h130
-rw-r--r--thirdparty/vhacd/inc/vhacdMutex.h148
-rw-r--r--thirdparty/vhacd/inc/vhacdRaycastMesh.h39
-rw-r--r--thirdparty/vhacd/inc/vhacdSArray.h158
-rw-r--r--thirdparty/vhacd/inc/vhacdTimer.h121
-rw-r--r--thirdparty/vhacd/inc/vhacdVHACD.h371
-rw-r--r--thirdparty/vhacd/inc/vhacdVector.h168
-rw-r--r--thirdparty/vhacd/inc/vhacdVector.inl362
-rw-r--r--thirdparty/vhacd/inc/vhacdVolume.h430
-rw-r--r--thirdparty/vhacd/public/VHACD.h153
-rw-r--r--thirdparty/vhacd/src/FloatMath.cpp17
-rw-r--r--thirdparty/vhacd/src/FloatMath.inl5276
-rw-r--r--thirdparty/vhacd/src/VHACD-ASYNC.cpp334
-rw-r--r--thirdparty/vhacd/src/VHACD.cpp1589
-rw-r--r--thirdparty/vhacd/src/btAlignedAllocator.cpp192
-rw-r--r--thirdparty/vhacd/src/btConvexHullComputer.cpp2487
-rw-r--r--thirdparty/vhacd/src/vhacdICHull.cpp731
-rw-r--r--thirdparty/vhacd/src/vhacdManifoldMesh.cpp202
-rw-r--r--thirdparty/vhacd/src/vhacdMesh.cpp376
-rw-r--r--thirdparty/vhacd/src/vhacdRaycastMesh.cpp208
-rw-r--r--thirdparty/vhacd/src/vhacdVolume.cpp1626
324 files changed, 26597 insertions, 2384 deletions
diff --git a/COPYRIGHT.txt b/COPYRIGHT.txt
index d28aabd0a6..738a0e62b5 100644
--- a/COPYRIGHT.txt
+++ b/COPYRIGHT.txt
@@ -385,6 +385,12 @@ Copyright: 2014-2018, Syoyo Fujita
2002, Industrial Light & Magic, a division of Lucas Digital Ltd. LLC
License: BSD-3-clause
+Files: ./thirdparty/vhacd/
+Comment: V-HACD
+Copyright: 2011, Khaled Mamou
+ 2003-2009, Erwin Coumans
+License: BSD-3-clause
+
Files: ./thirdparty/zlib/
Comment: zlib
Copyright: 1995-2017, Jean-loup Gailly and Mark Adler
diff --git a/core/bind/core_bind.cpp b/core/bind/core_bind.cpp
index 98d3e77f66..ba595b9627 100644
--- a/core/bind/core_bind.cpp
+++ b/core/bind/core_bind.cpp
@@ -2445,7 +2445,8 @@ void _Thread::_start_func(void *ud) {
reason = "Method Not Found";
} break;
- default: {}
+ default: {
+ }
}
ERR_EXPLAIN("Could not call function '" + t->target_method.operator String() + "'' starting thread ID: " + t->get_id() + " Reason: " + reason);
diff --git a/core/class_db.cpp b/core/class_db.cpp
index f7b446707d..0c844657a4 100644
--- a/core/class_db.cpp
+++ b/core/class_db.cpp
@@ -312,6 +312,19 @@ void ClassDB::get_inheriters_from_class(const StringName &p_class, List<StringNa
}
}
+void ClassDB::get_direct_inheriters_from_class(const StringName &p_class, List<StringName> *p_classes) {
+
+ OBJTYPE_RLOCK;
+
+ const StringName *k = NULL;
+
+ while ((k = classes.next(k))) {
+
+ if (*k != p_class && get_parent_class(*k) == p_class)
+ p_classes->push_back(*k);
+ }
+}
+
StringName ClassDB::get_parent_class_nocheck(const StringName &p_class) {
OBJTYPE_RLOCK;
diff --git a/core/class_db.h b/core/class_db.h
index f18a7113d7..efa1a46866 100644
--- a/core/class_db.h
+++ b/core/class_db.h
@@ -214,6 +214,7 @@ public:
static void get_class_list(List<StringName> *p_classes);
static void get_inheriters_from_class(const StringName &p_class, List<StringName> *p_classes);
+ static void get_direct_inheriters_from_class(const StringName &p_class, List<StringName> *p_classes);
static StringName get_parent_class_nocheck(const StringName &p_class);
static StringName get_parent_class(const StringName &p_class);
static bool class_exists(const StringName &p_class);
diff --git a/core/image.cpp b/core/image.cpp
index f547d7e973..90afd9f35a 100644
--- a/core/image.cpp
+++ b/core/image.cpp
@@ -1266,7 +1266,8 @@ void Image::shrink_x2() {
case FORMAT_RGBAH: _generate_po2_mipmap<uint16_t, 4, false, Image::average_4_half, Image::renormalize_half>(reinterpret_cast<const uint16_t *>(r.ptr()), reinterpret_cast<uint16_t *>(w.ptr()), width, height); break;
case FORMAT_RGBE9995: _generate_po2_mipmap<uint32_t, 1, false, Image::average_4_rgbe9995, Image::renormalize_rgbe9995>(reinterpret_cast<const uint32_t *>(r.ptr()), reinterpret_cast<uint32_t *>(w.ptr()), width, height); break;
- default: {}
+ default: {
+ }
}
}
@@ -1398,7 +1399,8 @@ Error Image::generate_mipmaps(bool p_renormalize) {
_generate_po2_mipmap<uint32_t, 1, false, Image::average_4_rgbe9995, Image::renormalize_rgbe9995>(reinterpret_cast<const uint32_t *>(&wp[prev_ofs]), reinterpret_cast<uint32_t *>(&wp[ofs]), prev_w, prev_h);
break;
- default: {}
+ default: {
+ }
}
prev_ofs = ofs;
@@ -1612,7 +1614,8 @@ void Image::create(const char **p_xpm) {
if (y == (size_height - 1))
status = DONE;
} break;
- default: {}
+ default: {
+ }
}
line++;
@@ -1685,7 +1688,8 @@ bool Image::is_invisible() const {
case FORMAT_DXT5: {
detected = true;
} break;
- default: {}
+ default: {
+ }
}
return !detected;
@@ -1729,7 +1733,8 @@ Image::AlphaMode Image::detect_alpha() const {
case FORMAT_DXT5: {
detected = true;
} break;
- default: {}
+ default: {
+ }
}
if (detected)
diff --git a/core/io/marshalls.cpp b/core/io/marshalls.cpp
index 363460311c..81b3829ffc 100644
--- a/core/io/marshalls.cpp
+++ b/core/io/marshalls.cpp
@@ -768,7 +768,9 @@ Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int
r_variant = carray;
} break;
- default: { ERR_FAIL_V(ERR_BUG); }
+ default: {
+ ERR_FAIL_V(ERR_BUG);
+ }
}
return OK;
@@ -823,7 +825,8 @@ Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len, bo
flags |= ENCODE_FLAG_OBJECT_AS_ID;
}
} break;
- default: {} // nothing to do at this stage
+ default: {
+ } // nothing to do at this stage
}
if (buf) {
@@ -1385,7 +1388,9 @@ Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len, bo
r_len += 4 * 4 * len;
} break;
- default: { ERR_FAIL_V(ERR_BUG); }
+ default: {
+ ERR_FAIL_V(ERR_BUG);
+ }
}
return OK;
diff --git a/core/io/resource_format_binary.cpp b/core/io/resource_format_binary.cpp
index 42070cd132..f25abc4aab 100644
--- a/core/io/resource_format_binary.cpp
+++ b/core/io/resource_format_binary.cpp
@@ -1725,7 +1725,8 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant &p_variant
get_string_index(np.get_subname(i));
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/core/math/audio_frame.h b/core/math/audio_frame.h
index ebe0356c93..98e4e33021 100644
--- a/core/math/audio_frame.h
+++ b/core/math/audio_frame.h
@@ -31,6 +31,7 @@
#ifndef AUDIOFRAME_H
#define AUDIOFRAME_H
+#include "core/math/vector2.h"
#include "core/typedefs.h"
static inline float undenormalise(volatile float f) {
@@ -128,6 +129,14 @@ struct AudioFrame {
return *this;
}
+ _ALWAYS_INLINE_ operator Vector2() const {
+ return Vector2(l, r);
+ }
+
+ _ALWAYS_INLINE_ AudioFrame(const Vector2 &p_v2) {
+ l = p_v2.x;
+ r = p_v2.y;
+ }
_ALWAYS_INLINE_ AudioFrame() {}
};
diff --git a/core/math/basis.cpp b/core/math/basis.cpp
index 82b2f7006d..9fcecd1ba6 100644
--- a/core/math/basis.cpp
+++ b/core/math/basis.cpp
@@ -557,7 +557,7 @@ void Basis::set_euler_yxz(const Vector3 &p_euler) {
*this = ymat * xmat * zmat;
}
-bool Basis::is_equal_approx(const Basis &a, const Basis &b,real_t p_epsilon) const {
+bool Basis::is_equal_approx(const Basis &a, const Basis &b, real_t p_epsilon) const {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
@@ -569,7 +569,7 @@ bool Basis::is_equal_approx(const Basis &a, const Basis &b,real_t p_epsilon) con
return true;
}
-bool Basis::is_equal_approx_ratio(const Basis &a, const Basis &b,real_t p_epsilon) const {
+bool Basis::is_equal_approx_ratio(const Basis &a, const Basis &b, real_t p_epsilon) const {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
diff --git a/core/math/basis.h b/core/math/basis.h
index aa0ddb280f..75037c2c52 100644
--- a/core/math/basis.h
+++ b/core/math/basis.h
@@ -133,8 +133,8 @@ public:
return elements[0][2] * v[0] + elements[1][2] * v[1] + elements[2][2] * v[2];
}
- bool is_equal_approx(const Basis &a, const Basis &b, real_t p_epsilon=CMP_EPSILON) const;
- bool is_equal_approx_ratio(const Basis &a, const Basis &b, real_t p_epsilon=UNIT_EPSILON) const;
+ bool is_equal_approx(const Basis &a, const Basis &b, real_t p_epsilon = CMP_EPSILON) const;
+ bool is_equal_approx_ratio(const Basis &a, const Basis &b, real_t p_epsilon = UNIT_EPSILON) const;
bool operator==(const Basis &p_matrix) const;
bool operator!=(const Basis &p_matrix) const;
diff --git a/core/math/expression.cpp b/core/math/expression.cpp
index 05b49f0815..133dcc7ab9 100644
--- a/core/math/expression.cpp
+++ b/core/math/expression.cpp
@@ -760,7 +760,8 @@ void Expression::exec_func(BuiltinFunc p_func, const Variant **p_inputs, Variant
*r_return = String(color);
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1679,7 +1680,8 @@ Expression::ENode *Expression::_parse_expression() {
case TK_OP_BIT_OR: op = Variant::OP_BIT_OR; break;
case TK_OP_BIT_XOR: op = Variant::OP_BIT_XOR; break;
case TK_OP_BIT_INVERT: op = Variant::OP_BIT_NEGATE; break;
- default: {};
+ default: {
+ };
}
if (op == Variant::OP_MAX) { //stop appending stuff
diff --git a/core/object.cpp b/core/object.cpp
index 8b693f039c..03a11b8ca3 100644
--- a/core/object.cpp
+++ b/core/object.cpp
@@ -1637,7 +1637,8 @@ void Object::_clear_internal_resource_paths(const Variant &p_var) {
_clear_internal_resource_paths(d[E->get()]);
}
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/core/os/file_access.cpp b/core/os/file_access.cpp
index 39d9f45bd7..4be1364278 100644
--- a/core/os/file_access.cpp
+++ b/core/os/file_access.cpp
@@ -571,10 +571,16 @@ void FileAccess::store_buffer(const uint8_t *p_src, int p_length) {
store_8(p_src[i]);
}
-Vector<uint8_t> FileAccess::get_file_as_array(const String &p_path) {
+Vector<uint8_t> FileAccess::get_file_as_array(const String &p_path, Error *r_error) {
- FileAccess *f = FileAccess::open(p_path, READ);
- ERR_FAIL_COND_V(!f, Vector<uint8_t>());
+ FileAccess *f = FileAccess::open(p_path, READ, r_error);
+ if (!f) {
+ if (r_error) { // if error requested, do not throw error
+ return Vector<uint8_t>();
+ } else {
+ ERR_FAIL_COND_V(!f, Vector<uint8_t>());
+ }
+ }
Vector<uint8_t> data;
data.resize(f->get_len());
f->get_buffer(data.ptrw(), data.size());
@@ -582,6 +588,26 @@ Vector<uint8_t> FileAccess::get_file_as_array(const String &p_path) {
return data;
}
+String FileAccess::get_file_as_string(const String &p_path, Error *r_error) {
+
+ Error err;
+ Vector<uint8_t> array = get_file_as_array(p_path, &err);
+ if (r_error) {
+ *r_error = err;
+ }
+ if (err != OK) {
+ if (r_error) {
+ return String();
+ } else {
+ ERR_FAIL_COND_V(err != OK, String());
+ }
+ }
+
+ String ret;
+ ret.parse_utf8((const char *)array.ptr(), array.size());
+ return ret;
+}
+
String FileAccess::get_md5(const String &p_file) {
FileAccess *f = FileAccess::open(p_file, READ);
diff --git a/core/os/file_access.h b/core/os/file_access.h
index c65b75369c..9df2a5cade 100644
--- a/core/os/file_access.h
+++ b/core/os/file_access.h
@@ -164,7 +164,8 @@ public:
static String get_sha256(const String &p_file);
static String get_multiple_md5(const Vector<String> &p_file);
- static Vector<uint8_t> get_file_as_array(const String &p_path);
+ static Vector<uint8_t> get_file_as_array(const String &p_path, Error *r_error = NULL);
+ static String get_file_as_string(const String &p_path, Error *r_error = NULL);
template <class T>
static void make_default(AccessType p_access) {
diff --git a/core/os/input.cpp b/core/os/input.cpp
index caa9fb1493..63bf1db499 100644
--- a/core/os/input.cpp
+++ b/core/os/input.cpp
@@ -89,6 +89,7 @@ void Input::_bind_methods() {
ClassDB::bind_method(D_METHOD("action_press", "action", "strength"), &Input::action_press, DEFVAL(1.f));
ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release);
ClassDB::bind_method(D_METHOD("set_default_cursor_shape", "shape"), &Input::set_default_cursor_shape, DEFVAL(CURSOR_ARROW));
+ ClassDB::bind_method(D_METHOD("get_current_cursor_shape"), &Input::get_current_cursor_shape);
ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image", "shape", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(CURSOR_ARROW), DEFVAL(Vector2()));
ClassDB::bind_method(D_METHOD("parse_input_event", "event"), &Input::parse_input_event);
ClassDB::bind_method(D_METHOD("set_use_accumulated_input", "enable"), &Input::set_use_accumulated_input);
diff --git a/core/os/input.h b/core/os/input.h
index c8b80b28d0..de04f239e6 100644
--- a/core/os/input.h
+++ b/core/os/input.h
@@ -121,10 +121,10 @@ public:
virtual bool is_emulating_touch_from_mouse() const = 0;
virtual bool is_emulating_mouse_from_touch() const = 0;
- virtual CursorShape get_default_cursor_shape() = 0;
+ virtual CursorShape get_default_cursor_shape() const = 0;
virtual void set_default_cursor_shape(CursorShape p_shape) = 0;
+ virtual CursorShape get_current_cursor_shape() const = 0;
virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape = CURSOR_ARROW, const Vector2 &p_hotspot = Vector2()) = 0;
- virtual void set_mouse_in_window(bool p_in_window) = 0;
virtual String get_joy_button_string(int p_button) = 0;
virtual String get_joy_axis_string(int p_axis) = 0;
diff --git a/core/os/os.cpp b/core/os/os.cpp
index 03e63f636e..ea378c9e83 100644
--- a/core/os/os.cpp
+++ b/core/os/os.cpp
@@ -220,6 +220,16 @@ int OS::get_virtual_keyboard_height() const {
return 0;
}
+void OS::set_cursor_shape(CursorShape p_shape) {
+}
+
+OS::CursorShape OS::get_cursor_shape() const {
+ return CURSOR_ARROW;
+}
+
+void OS::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
+}
+
void OS::print_all_resources(String p_to_file) {
ERR_FAIL_COND(p_to_file != "" && _OSPRF);
diff --git a/core/os/os.h b/core/os/os.h
index d02d5a2c84..12012fba80 100644
--- a/core/os/os.h
+++ b/core/os/os.h
@@ -377,8 +377,9 @@ public:
// returns height of the currently shown virtual keyboard (0 if keyboard is hidden)
virtual int get_virtual_keyboard_height() const;
- virtual void set_cursor_shape(CursorShape p_shape) = 0;
- virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) = 0;
+ virtual void set_cursor_shape(CursorShape p_shape);
+ virtual CursorShape get_cursor_shape() const;
+ virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot);
virtual bool get_swap_ok_cancel() { return false; }
virtual void dump_memory_to_file(const char *p_file);
diff --git a/core/packed_data_container.cpp b/core/packed_data_container.cpp
index 99bed829c1..fa60be64a7 100644
--- a/core/packed_data_container.cpp
+++ b/core/packed_data_container.cpp
@@ -319,7 +319,8 @@ uint32_t PackedDataContainer::_pack(const Variant &p_data, Vector<uint8_t> &tmpd
} break;
- default: {}
+ default: {
+ }
}
return OK;
diff --git a/core/project_settings.cpp b/core/project_settings.cpp
index 5752cdca2b..c86d1567dd 100644
--- a/core/project_settings.cpp
+++ b/core/project_settings.cpp
@@ -501,7 +501,7 @@ Error ProjectSettings::_load_settings_binary(const String p_path) {
d.resize(vlen);
f->get_buffer(d.ptrw(), vlen);
Variant value;
- err = decode_variant(value, d.ptr(), d.size(), NULL, false);
+ err = decode_variant(value, d.ptr(), d.size(), NULL, true);
ERR_EXPLAIN("Error decoding property: " + key);
ERR_CONTINUE(err != OK);
set(key, value);
@@ -694,7 +694,7 @@ Error ProjectSettings::_save_settings_binary(const String &p_file, const Map<Str
file->store_string(key);
int len;
- err = encode_variant(value, NULL, len, false);
+ err = encode_variant(value, NULL, len, true);
if (err != OK)
memdelete(file);
ERR_FAIL_COND_V(err != OK, ERR_INVALID_DATA);
@@ -702,7 +702,7 @@ Error ProjectSettings::_save_settings_binary(const String &p_file, const Map<Str
Vector<uint8_t> buff;
buff.resize(len);
- err = encode_variant(value, buff.ptrw(), len, false);
+ err = encode_variant(value, buff.ptrw(), len, true);
if (err != OK)
memdelete(file);
ERR_FAIL_COND_V(err != OK, ERR_INVALID_DATA);
diff --git a/core/resource.cpp b/core/resource.cpp
index 74c93cd790..74e2c1ed6b 100644
--- a/core/resource.cpp
+++ b/core/resource.cpp
@@ -363,6 +363,26 @@ bool Resource::is_translation_remapped() const {
return remapped_list.in_list();
}
+#ifdef TOOLS_ENABLED
+//helps keep IDs same number when loading/saving scenes. -1 clears ID and it Returns -1 when no id stored
+void Resource::set_id_for_path(const String &p_path, int p_id) {
+ if (p_id == -1) {
+ id_for_path.erase(p_path);
+ } else {
+ id_for_path[p_path] = p_id;
+ }
+}
+
+int Resource::get_id_for_path(const String &p_path) const {
+
+ if (id_for_path.has(p_path)) {
+ return id_for_path[p_path];
+ } else {
+ return -1;
+ }
+}
+#endif
+
void Resource::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_path", "path"), &Resource::_set_path);
diff --git a/core/resource.h b/core/resource.h
index a4d9e998ac..853b2859c7 100644
--- a/core/resource.h
+++ b/core/resource.h
@@ -88,7 +88,9 @@ protected:
void _set_path(const String &p_path);
void _take_over_path(const String &p_path);
-
+#ifdef TOOLS_ENABLED
+ Map<String, int> id_for_path;
+#endif
public:
static Node *(*_get_local_scene_func)(); //used by editor
@@ -137,6 +139,12 @@ public:
virtual RID get_rid() const; // some resources may offer conversion to RID
+#ifdef TOOLS_ENABLED
+ //helps keep IDs same number when loading/saving scenes. -1 clears ID and it Returns -1 when no id stored
+ void set_id_for_path(const String &p_path, int p_id);
+ int get_id_for_path(const String &p_path) const;
+#endif
+
Resource();
~Resource();
};
diff --git a/core/ustring.cpp b/core/ustring.cpp
index ff8fcaaaaf..d60bd16921 100644
--- a/core/ustring.cpp
+++ b/core/ustring.cpp
@@ -3748,6 +3748,24 @@ bool String::is_valid_html_color() const {
return Color::html_is_valid(*this);
}
+bool String::is_valid_filename() const {
+
+ String stripped = strip_edges();
+ if (*this != stripped) {
+ return false;
+ }
+
+ if (stripped == String()) {
+ return false;
+ }
+
+ if (find(":") != -1 || find("/") != -1 || find("\\") != -1 || find("?") != -1 || find("*") != -1 || find("\"") != -1 || find("|") != -1 || find("%") != -1 || find("<") != -1 || find(">") != -1) {
+ return false;
+ } else {
+ return true;
+ }
+}
+
bool String::is_valid_ip_address() const {
if (find(":") >= 0) {
diff --git a/core/ustring.h b/core/ustring.h
index 9288c1526e..85103057df 100644
--- a/core/ustring.h
+++ b/core/ustring.h
@@ -335,6 +335,7 @@ public:
bool is_valid_hex_number(bool p_with_prefix) const;
bool is_valid_html_color() const;
bool is_valid_ip_address() const;
+ bool is_valid_filename() const;
/**
* The constructors must not depend on other overloads
@@ -406,11 +407,18 @@ _FORCE_INLINE_ bool is_str_less(const L *l_ptr, const R *r_ptr) {
//tool translate
#ifdef TOOLS_ENABLED
+//gets parsed
String TTR(const String &);
+//use for c strings
+#define TTRC(m_value) m_value
+//use to avoid parsing (for use later with C strings)
+#define TTRGET(m_value) TTR(m_value)
#else
#define TTR(m_val) (String())
+#define TTRCDEF(m_value) (m_value)
+#define TTRC(m_value) (m_value)
#endif
diff --git a/core/variant.cpp b/core/variant.cpp
index 2ee2e8e293..6c54faf233 100644
--- a/core/variant.cpp
+++ b/core/variant.cpp
@@ -179,7 +179,8 @@ String Variant::get_type_name(Variant::Type p_type) {
return "PoolColorArray";
} break;
- default: {}
+ default: {
+ }
}
return "";
@@ -403,7 +404,8 @@ bool Variant::can_convert(Variant::Type p_type_from, Variant::Type p_type_to) {
valid_types = valid;
} break;
- default: {}
+ default: {
+ }
}
if (valid_types) {
@@ -649,7 +651,8 @@ bool Variant::can_convert_strict(Variant::Type p_type_from, Variant::Type p_type
valid_types = valid;
} break;
- default: {}
+ default: {
+ }
}
if (valid_types) {
@@ -841,7 +844,8 @@ bool Variant::is_zero() const {
return reinterpret_cast<const PoolVector<Color> *>(_data._mem)->size() == 0;
} break;
- default: {}
+ default: {
+ }
}
return false;
@@ -896,7 +900,9 @@ bool Variant::is_one() const {
} break;
- default: { return !is_zero(); }
+ default: {
+ return !is_zero();
+ }
}
return false;
@@ -1039,7 +1045,8 @@ void Variant::reference(const Variant &p_variant) {
memnew_placement(_data._mem, PoolVector<Color>(*reinterpret_cast<const PoolVector<Color> *>(p_variant._data._mem)));
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1143,7 +1150,8 @@ void Variant::clear() {
reinterpret_cast<PoolVector<Color> *>(_data._mem)->~PoolVector<Color>();
} break;
- default: {} /* not needed */
+ default: {
+ } /* not needed */
}
type = NIL;
@@ -1823,7 +1831,9 @@ inline DA _convert_array_from_variant(const Variant &p_variant) {
case Variant::POOL_COLOR_ARRAY: {
return _convert_array<DA, PoolVector<Color> >(p_variant.operator PoolVector<Color>());
}
- default: { return DA(); }
+ default: {
+ return DA();
+ }
}
return DA();
@@ -2642,7 +2652,8 @@ void Variant::operator=(const Variant &p_variant) {
*reinterpret_cast<PoolVector<Color> *>(_data._mem) = *reinterpret_cast<const PoolVector<Color> *>(p_variant._data._mem);
} break;
- default: {}
+ default: {
+ }
}
}
@@ -2919,7 +2930,8 @@ uint32_t Variant::hash() const {
return hash;
} break;
- default: {}
+ default: {
+ }
}
return 0;
@@ -3167,7 +3179,8 @@ bool Variant::is_shared() const {
case OBJECT: return true;
case ARRAY: return true;
case DICTIONARY: return true;
- default: {}
+ default: {
+ }
}
return false;
@@ -3204,7 +3217,8 @@ Variant Variant::call(const StringName &p_method, VARIANT_ARG_DECLARE) {
String err = "Too many arguments for method '" + p_method + "'";
ERR_PRINT(err.utf8().get_data());
} break;
- default: {}
+ default: {
+ }
}
return ret;
diff --git a/core/variant_call.cpp b/core/variant_call.cpp
index cbe24d4a63..143b07418e 100644
--- a/core/variant_call.cpp
+++ b/core/variant_call.cpp
@@ -294,6 +294,7 @@ struct _VariantCall {
VCALL_LOCALMEM1R(String, is_valid_hex_number);
VCALL_LOCALMEM0R(String, is_valid_html_color);
VCALL_LOCALMEM0R(String, is_valid_ip_address);
+ VCALL_LOCALMEM0R(String, is_valid_filename);
VCALL_LOCALMEM0R(String, to_int);
VCALL_LOCALMEM0R(String, to_float);
VCALL_LOCALMEM0R(String, hex_to_int);
@@ -1542,6 +1543,7 @@ void register_variant_methods() {
ADDFUNC1R(STRING, BOOL, String, is_valid_hex_number, BOOL, "with_prefix", varray(false));
ADDFUNC0R(STRING, BOOL, String, is_valid_html_color, varray());
ADDFUNC0R(STRING, BOOL, String, is_valid_ip_address, varray());
+ ADDFUNC0R(STRING, BOOL, String, is_valid_filename, varray());
ADDFUNC0R(STRING, INT, String, to_int, varray());
ADDFUNC0R(STRING, REAL, String, to_float, varray());
ADDFUNC0R(STRING, INT, String, hex_to_int, varray());
diff --git a/core/variant_op.cpp b/core/variant_op.cpp
index b40b6ce4a6..f3c9bcaa7e 100644
--- a/core/variant_op.cpp
+++ b/core/variant_op.cpp
@@ -2781,7 +2781,8 @@ bool Variant::in(const Variant &p_index, bool *r_valid) const {
return false;
}
} break;
- default: {}
+ default: {
+ }
}
if (r_valid)
@@ -2912,7 +2913,8 @@ void Variant::get_property_list(List<PropertyInfo> *p_list) const {
//nothing
} break;
- default: {}
+ default: {
+ }
}
}
@@ -3251,7 +3253,8 @@ bool Variant::iter_next(Variant &r_iter, bool &valid) const {
r_iter = idx;
return true;
} break;
- default: {}
+ default: {
+ }
}
valid = false;
@@ -3408,7 +3411,8 @@ Variant Variant::iter_get(const Variant &r_iter, bool &r_valid) const {
#endif
return arr->get(idx);
} break;
- default: {}
+ default: {
+ }
}
r_valid = false;
diff --git a/core/variant_parser.cpp b/core/variant_parser.cpp
index 0056fc75b6..6377197282 100644
--- a/core/variant_parser.cpp
+++ b/core/variant_parser.cpp
@@ -1948,7 +1948,8 @@ Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_str
p_store_string_func(p_store_string_ud, " )");
} break;
- default: {}
+ default: {
+ }
}
return OK;
diff --git a/doc/classes/AnimatedSprite.xml b/doc/classes/AnimatedSprite.xml
index 0ee1c75348..555169545e 100644
--- a/doc/classes/AnimatedSprite.xml
+++ b/doc/classes/AnimatedSprite.xml
@@ -23,6 +23,8 @@
</return>
<argument index="0" name="anim" type="String" default="&quot;&quot;">
</argument>
+ <argument index="1" name="backwards" type="bool" default="false">
+ </argument>
<description>
Play the animation set in parameter. If no parameter is provided, the current animation is played. Property [code]backwards[/code] plays the animation in reverse if set to [code]true[/code].
</description>
diff --git a/doc/classes/AudioEffectInstance.xml b/doc/classes/AudioEffectInstance.xml
new file mode 100644
index 0000000000..ed42928eb1
--- /dev/null
+++ b/doc/classes/AudioEffectInstance.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="AudioEffectInstance" inherits="Reference" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/AudioEffectSpectrumAnalyzer.xml b/doc/classes/AudioEffectSpectrumAnalyzer.xml
new file mode 100644
index 0000000000..5732039467
--- /dev/null
+++ b/doc/classes/AudioEffectSpectrumAnalyzer.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="AudioEffectSpectrumAnalyzer" inherits="AudioEffect" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <members>
+ <member name="buffer_length" type="float" setter="set_buffer_length" getter="get_buffer_length">
+ </member>
+ <member name="fft_size" type="int" setter="set_fft_size" getter="get_fft_size" enum="AudioEffectSpectrumAnalyzer.FFT_Size">
+ </member>
+ <member name="tap_back_pos" type="float" setter="set_tap_back_pos" getter="get_tap_back_pos">
+ </member>
+ </members>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/AudioEffectSpectrumAnalyzerInstance.xml b/doc/classes/AudioEffectSpectrumAnalyzerInstance.xml
new file mode 100644
index 0000000000..0c0061beb4
--- /dev/null
+++ b/doc/classes/AudioEffectSpectrumAnalyzerInstance.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="AudioEffectSpectrumAnalyzerInstance" inherits="AudioEffectInstance" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ <method name="get_magnitude_for_frequency_range" qualifiers="const">
+ <return type="Vector2">
+ </return>
+ <argument index="0" name="from_hz" type="float">
+ </argument>
+ <argument index="1" name="to_hz" type="float">
+ </argument>
+ <argument index="2" name="mode" type="int" enum="AudioEffectSpectrumAnalyzerInstance.MagnitudeMode" default="1">
+ </argument>
+ <description>
+ </description>
+ </method>
+ </methods>
+ <constants>
+ <constant name="MAGNITUDE_AVERAGE" value="0" enum="MagnitudeMode">
+ </constant>
+ <constant name="MAGNITUDE_MAX" value="1" enum="MagnitudeMode">
+ </constant>
+ </constants>
+</class>
diff --git a/doc/classes/AudioServer.xml b/doc/classes/AudioServer.xml
index 82e17e4957..32eed54882 100644
--- a/doc/classes/AudioServer.xml
+++ b/doc/classes/AudioServer.xml
@@ -97,6 +97,18 @@
Returns the number of effects on the bus at [code]bus_idx[/code].
</description>
</method>
+ <method name="get_bus_effect_instance">
+ <return type="AudioEffectInstance">
+ </return>
+ <argument index="0" name="bus_idx" type="int">
+ </argument>
+ <argument index="1" name="effect_idx" type="int">
+ </argument>
+ <argument index="2" name="channel" type="int" default="0">
+ </argument>
+ <description>
+ </description>
+ </method>
<method name="get_bus_index" qualifiers="const">
<return type="int">
</return>
diff --git a/doc/classes/AudioStreamGenerator.xml b/doc/classes/AudioStreamGenerator.xml
new file mode 100644
index 0000000000..e41b5827b1
--- /dev/null
+++ b/doc/classes/AudioStreamGenerator.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="AudioStreamGenerator" inherits="AudioStream" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <members>
+ <member name="buffer_length" type="float" setter="set_buffer_length" getter="get_buffer_length">
+ </member>
+ <member name="mix_rate" type="float" setter="set_mix_rate" getter="get_mix_rate">
+ </member>
+ </members>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/AudioStreamGeneratorPlayback.xml b/doc/classes/AudioStreamGeneratorPlayback.xml
new file mode 100644
index 0000000000..4b4d622741
--- /dev/null
+++ b/doc/classes/AudioStreamGeneratorPlayback.xml
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="AudioStreamGeneratorPlayback" inherits="AudioStreamPlaybackResampled" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ <method name="can_push_buffer" qualifiers="const">
+ <return type="bool">
+ </return>
+ <argument index="0" name="amount" type="int">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="clear_buffer">
+ <return type="void">
+ </return>
+ <description>
+ </description>
+ </method>
+ <method name="get_frames_available" qualifiers="const">
+ <return type="int">
+ </return>
+ <description>
+ </description>
+ </method>
+ <method name="get_skips" qualifiers="const">
+ <return type="int">
+ </return>
+ <description>
+ </description>
+ </method>
+ <method name="push_buffer">
+ <return type="bool">
+ </return>
+ <argument index="0" name="frames" type="PoolVector2Array">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="push_frame">
+ <return type="bool">
+ </return>
+ <argument index="0" name="frame" type="Vector2">
+ </argument>
+ <description>
+ </description>
+ </method>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/AudioStreamPlaybackResampled.xml b/doc/classes/AudioStreamPlaybackResampled.xml
new file mode 100644
index 0000000000..764f966167
--- /dev/null
+++ b/doc/classes/AudioStreamPlaybackResampled.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="AudioStreamPlaybackResampled" inherits="AudioStreamPlayback" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/AudioStreamPlayer.xml b/doc/classes/AudioStreamPlayer.xml
index d8b87a3c19..1681d796ea 100644
--- a/doc/classes/AudioStreamPlayer.xml
+++ b/doc/classes/AudioStreamPlayer.xml
@@ -19,6 +19,12 @@
Returns the position in the [AudioStream] in seconds.
</description>
</method>
+ <method name="get_stream_playback">
+ <return type="AudioStreamPlayback">
+ </return>
+ <description>
+ </description>
+ </method>
<method name="play">
<return type="void">
</return>
diff --git a/doc/classes/AudioStreamPlayer2D.xml b/doc/classes/AudioStreamPlayer2D.xml
index 1cd2bf7645..e001d11727 100644
--- a/doc/classes/AudioStreamPlayer2D.xml
+++ b/doc/classes/AudioStreamPlayer2D.xml
@@ -19,6 +19,12 @@
Returns the position in the [AudioStream].
</description>
</method>
+ <method name="get_stream_playback">
+ <return type="AudioStreamPlayback">
+ </return>
+ <description>
+ </description>
+ </method>
<method name="play">
<return type="void">
</return>
diff --git a/doc/classes/AudioStreamPlayer3D.xml b/doc/classes/AudioStreamPlayer3D.xml
index 8ff5223e4f..0d973a761a 100644
--- a/doc/classes/AudioStreamPlayer3D.xml
+++ b/doc/classes/AudioStreamPlayer3D.xml
@@ -19,6 +19,12 @@
Returns the position in the [AudioStream].
</description>
</method>
+ <method name="get_stream_playback">
+ <return type="AudioStreamPlayback">
+ </return>
+ <description>
+ </description>
+ </method>
<method name="play">
<return type="void">
</return>
diff --git a/doc/classes/Basis.xml b/doc/classes/Basis.xml
index 7b43d58c71..3710bc3de6 100644
--- a/doc/classes/Basis.xml
+++ b/doc/classes/Basis.xml
@@ -76,6 +76,12 @@
This function considers a discretization of rotations into 24 points on unit sphere, lying along the vectors (x,y,z) with each component being either -1,0 or 1, and returns the index of the point best representing the orientation of the object. It is mainly used by the grid map editor. For further details, refer to Godot source code.
</description>
</method>
+ <method name="get_rotation_quat">
+ <return type="Quat">
+ </return>
+ <description>
+ </description>
+ </method>
<method name="get_scale">
<return type="Vector3">
</return>
@@ -90,6 +96,16 @@
Return the inverse of the matrix.
</description>
</method>
+ <method name="is_equal_approx">
+ <return type="bool">
+ </return>
+ <argument index="0" name="b" type="Basis">
+ </argument>
+ <argument index="1" name="epsilon" type="float" default="0.00001">
+ </argument>
+ <description>
+ </description>
+ </method>
<method name="orthonormalized">
<return type="Basis">
</return>
diff --git a/doc/classes/CanvasItem.xml b/doc/classes/CanvasItem.xml
index c1cf7dcabe..61ccc167a5 100644
--- a/doc/classes/CanvasItem.xml
+++ b/doc/classes/CanvasItem.xml
@@ -575,7 +575,7 @@
<constant name="BLEND_MODE_DISABLED" value="5" enum="BlendMode">
Disable blending mode. Colors including alpha are written as is. Only applicable for render targets with a transparent background. No lighting will be applied.
</constant>
- <constant name="NOTIFICATION_TRANSFORM_CHANGED" value="29">
+ <constant name="NOTIFICATION_TRANSFORM_CHANGED" value="2000">
Canvas item transform has changed. Notification is only received if enabled by [method set_notify_transform] or [method set_notify_local_transform].
</constant>
<constant name="NOTIFICATION_DRAW" value="30">
diff --git a/doc/classes/CanvasLayer.xml b/doc/classes/CanvasLayer.xml
index 3d69c92ea3..04aa7fbbf2 100644
--- a/doc/classes/CanvasLayer.xml
+++ b/doc/classes/CanvasLayer.xml
@@ -25,6 +25,10 @@
<member name="custom_viewport" type="Node" setter="set_custom_viewport" getter="get_custom_viewport">
The custom [Viewport] node assigned to the [CanvasLayer]. If null, uses the default viewport instead.
</member>
+ <member name="follow_viewport_enable" type="bool" setter="set_follow_viewport" getter="is_following_viewport">
+ </member>
+ <member name="follow_viewport_scale" type="float" setter="set_follow_viewport_scale" getter="get_follow_viewport_scale">
+ </member>
<member name="layer" type="int" setter="set_layer" getter="get_layer">
Layer index for draw order. Lower values are drawn first. Default value: [code]1[/code].
</member>
diff --git a/doc/classes/EditorFeatureProfile.xml b/doc/classes/EditorFeatureProfile.xml
new file mode 100644
index 0000000000..e0e56dc009
--- /dev/null
+++ b/doc/classes/EditorFeatureProfile.xml
@@ -0,0 +1,131 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="EditorFeatureProfile" inherits="Reference" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ <method name="get_feature_name">
+ <return type="String">
+ </return>
+ <argument index="0" name="feature" type="int" enum="EditorFeatureProfile.Feature">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="is_class_disabled" qualifiers="const">
+ <return type="bool">
+ </return>
+ <argument index="0" name="class_name" type="String">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="is_class_editor_disabled" qualifiers="const">
+ <return type="bool">
+ </return>
+ <argument index="0" name="class_name" type="String">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="is_class_property_disabled" qualifiers="const">
+ <return type="bool">
+ </return>
+ <argument index="0" name="class_name" type="String">
+ </argument>
+ <argument index="1" name="arg1" type="String">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="is_feature_disabled" qualifiers="const">
+ <return type="bool">
+ </return>
+ <argument index="0" name="feature" type="int" enum="EditorFeatureProfile.Feature">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="load_from_file">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="path" type="String">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="save_to_file">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="path" type="String">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="set_disable_class">
+ <return type="void">
+ </return>
+ <argument index="0" name="class_name" type="String">
+ </argument>
+ <argument index="1" name="disable" type="bool">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="set_disable_class_editor">
+ <return type="void">
+ </return>
+ <argument index="0" name="class_name" type="String">
+ </argument>
+ <argument index="1" name="disable" type="bool">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="set_disable_class_property">
+ <return type="void">
+ </return>
+ <argument index="0" name="class_name" type="String">
+ </argument>
+ <argument index="1" name="property" type="String">
+ </argument>
+ <argument index="2" name="arg2" type="bool">
+ </argument>
+ <description>
+ </description>
+ </method>
+ <method name="set_disable_feature">
+ <return type="void">
+ </return>
+ <argument index="0" name="feature" type="int" enum="EditorFeatureProfile.Feature">
+ </argument>
+ <argument index="1" name="disable" type="bool">
+ </argument>
+ <description>
+ </description>
+ </method>
+ </methods>
+ <constants>
+ <constant name="FEATURE_3D" value="0" enum="Feature">
+ </constant>
+ <constant name="FEATURE_SCRIPT" value="1" enum="Feature">
+ </constant>
+ <constant name="FEATURE_ASSET_LIB" value="2" enum="Feature">
+ </constant>
+ <constant name="FEATURE_SCENE_TREE" value="3" enum="Feature">
+ </constant>
+ <constant name="FEATURE_IMPORT_DOCK" value="4" enum="Feature">
+ </constant>
+ <constant name="FEATURE_NODE_DOCK" value="5" enum="Feature">
+ </constant>
+ <constant name="FEATURE_FILESYSTEM_DOCK" value="6" enum="Feature">
+ </constant>
+ <constant name="FEATURE_MAX" value="7" enum="Feature">
+ </constant>
+ </constants>
+</class>
diff --git a/doc/classes/EditorInterface.xml b/doc/classes/EditorInterface.xml
index 30ff609a81..2dc8d716a7 100644
--- a/doc/classes/EditorInterface.xml
+++ b/doc/classes/EditorInterface.xml
@@ -48,6 +48,12 @@
Returns the editor [Viewport].
</description>
</method>
+ <method name="get_inspector" qualifiers="const">
+ <return type="EditorInspector">
+ </return>
+ <description>
+ </description>
+ </method>
<method name="get_open_scenes" qualifiers="const">
<return type="Array">
</return>
diff --git a/doc/classes/File.xml b/doc/classes/File.xml
index 8a785ab263..79462816e3 100644
--- a/doc/classes/File.xml
+++ b/doc/classes/File.xml
@@ -227,7 +227,7 @@
</return>
<argument index="0" name="path" type="String">
</argument>
- <argument index="1" name="flags" type="int">
+ <argument index="1" name="flags" type="int" enum="File.ModeFlags">
</argument>
<description>
Opens the file for writing or reading, depending on the flags.
@@ -238,9 +238,9 @@
</return>
<argument index="0" name="path" type="String">
</argument>
- <argument index="1" name="mode_flags" type="int">
+ <argument index="1" name="mode_flags" type="int" enum="File.ModeFlags">
</argument>
- <argument index="2" name="compression_mode" type="int" default="0">
+ <argument index="2" name="compression_mode" type="int" enum="File.CompressionMode" default="0">
</argument>
<description>
Opens a compressed file for reading or writing. Use COMPRESSION_* constants to set [code]compression_mode[/code].
@@ -251,7 +251,7 @@
</return>
<argument index="0" name="path" type="String">
</argument>
- <argument index="1" name="mode_flags" type="int">
+ <argument index="1" name="mode_flags" type="int" enum="File.ModeFlags">
</argument>
<argument index="2" name="key" type="PoolByteArray">
</argument>
@@ -264,7 +264,7 @@
</return>
<argument index="0" name="path" type="String">
</argument>
- <argument index="1" name="mode_flags" type="int">
+ <argument index="1" name="mode_flags" type="int" enum="File.ModeFlags">
</argument>
<argument index="2" name="pass" type="String">
</argument>
diff --git a/doc/classes/MainLoop.xml b/doc/classes/MainLoop.xml
index 8d8d4c46cc..6b7d9cc834 100644
--- a/doc/classes/MainLoop.xml
+++ b/doc/classes/MainLoop.xml
@@ -114,29 +114,29 @@
</method>
</methods>
<constants>
- <constant name="NOTIFICATION_WM_MOUSE_ENTER" value="2">
+ <constant name="NOTIFICATION_WM_MOUSE_ENTER" value="1002">
</constant>
- <constant name="NOTIFICATION_WM_MOUSE_EXIT" value="3">
+ <constant name="NOTIFICATION_WM_MOUSE_EXIT" value="1003">
</constant>
- <constant name="NOTIFICATION_WM_FOCUS_IN" value="4">
+ <constant name="NOTIFICATION_WM_FOCUS_IN" value="1004">
</constant>
- <constant name="NOTIFICATION_WM_FOCUS_OUT" value="5">
+ <constant name="NOTIFICATION_WM_FOCUS_OUT" value="1005">
</constant>
- <constant name="NOTIFICATION_WM_QUIT_REQUEST" value="6">
+ <constant name="NOTIFICATION_WM_QUIT_REQUEST" value="1006">
</constant>
- <constant name="NOTIFICATION_WM_GO_BACK_REQUEST" value="7">
+ <constant name="NOTIFICATION_WM_GO_BACK_REQUEST" value="1007">
</constant>
- <constant name="NOTIFICATION_WM_UNFOCUS_REQUEST" value="8">
+ <constant name="NOTIFICATION_WM_UNFOCUS_REQUEST" value="1008">
</constant>
- <constant name="NOTIFICATION_OS_MEMORY_WARNING" value="9">
+ <constant name="NOTIFICATION_OS_MEMORY_WARNING" value="1009">
</constant>
- <constant name="NOTIFICATION_TRANSLATION_CHANGED" value="90">
+ <constant name="NOTIFICATION_TRANSLATION_CHANGED" value="1010">
</constant>
- <constant name="NOTIFICATION_WM_ABOUT" value="91">
+ <constant name="NOTIFICATION_WM_ABOUT" value="1011">
</constant>
- <constant name="NOTIFICATION_CRASH" value="92">
+ <constant name="NOTIFICATION_CRASH" value="1012">
</constant>
- <constant name="NOTIFICATION_OS_IME_UPDATE" value="93">
+ <constant name="NOTIFICATION_OS_IME_UPDATE" value="1013">
</constant>
</constants>
</class>
diff --git a/doc/classes/MeshLibrary.xml b/doc/classes/MeshLibrary.xml
index 8fb10696f2..02d87a9c48 100644
--- a/doc/classes/MeshLibrary.xml
+++ b/doc/classes/MeshLibrary.xml
@@ -68,6 +68,14 @@
<description>
</description>
</method>
+ <method name="get_item_navmesh_transform" qualifiers="const">
+ <return type="Transform">
+ </return>
+ <argument index="0" name="id" type="int">
+ </argument>
+ <description>
+ </description>
+ </method>
<method name="get_item_preview" qualifiers="const">
<return type="Texture">
</return>
@@ -132,6 +140,16 @@
<description>
</description>
</method>
+ <method name="set_item_navmesh_transform">
+ <return type="void">
+ </return>
+ <argument index="0" name="id" type="int">
+ </argument>
+ <argument index="1" name="navmesh" type="Transform">
+ </argument>
+ <description>
+ </description>
+ </method>
<method name="set_item_preview">
<return type="void">
</return>
diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml
index e01e3d3a20..646b921743 100644
--- a/doc/classes/Node.xml
+++ b/doc/classes/Node.xml
@@ -146,6 +146,7 @@
</argument>
<description>
Adds the node to a group. Groups are helpers to name and organize a subset of nodes, for example "enemies" or "collectables". A node can be in any number of groups. Nodes can be assigned a group at any time, but will not be added until they are inside the scene tree (see [method is_inside_tree]). See notes in the description, and the group methods in [SceneTree].
+ [code]persistent[/code] option is used when packing node to [PackedScene] and saving to file. Non-persistent groups aren't stored.
</description>
</method>
<method name="can_process" qualifiers="const">
@@ -885,15 +886,37 @@
<constant name="NOTIFICATION_PATH_CHANGED" value="23">
Notification received when the node's [NodePath] changed.
</constant>
- <constant name="NOTIFICATION_TRANSLATION_CHANGED" value="24">
- Notification received when translations may have changed. Can be triggered by the user changing the locale. Can be used to respond to language changes, for example to change the UI strings on the fly. Useful when working with the built-in translation support, like [method Object.tr].
- </constant>
<constant name="NOTIFICATION_INTERNAL_PROCESS" value="25">
Notification received every frame when the internal process flag is set (see [method set_process_internal]).
</constant>
<constant name="NOTIFICATION_INTERNAL_PHYSICS_PROCESS" value="26">
Notification received every frame when the internal physics process flag is set (see [method set_physics_process_internal]).
</constant>
+ <constant name="NOTIFICATION_WM_MOUSE_ENTER" value="1002">
+ </constant>
+ <constant name="NOTIFICATION_WM_MOUSE_EXIT" value="1003">
+ </constant>
+ <constant name="NOTIFICATION_WM_FOCUS_IN" value="1004">
+ </constant>
+ <constant name="NOTIFICATION_WM_FOCUS_OUT" value="1005">
+ </constant>
+ <constant name="NOTIFICATION_WM_QUIT_REQUEST" value="1006">
+ </constant>
+ <constant name="NOTIFICATION_WM_GO_BACK_REQUEST" value="1007">
+ </constant>
+ <constant name="NOTIFICATION_WM_UNFOCUS_REQUEST" value="1008">
+ </constant>
+ <constant name="NOTIFICATION_OS_MEMORY_WARNING" value="1009">
+ </constant>
+ <constant name="NOTIFICATION_TRANSLATION_CHANGED" value="1010">
+ Notification received when translations may have changed. Can be triggered by the user changing the locale. Can be used to respond to language changes, for example to change the UI strings on the fly. Useful when working with the built-in translation support, like [method Object.tr].
+ </constant>
+ <constant name="NOTIFICATION_WM_ABOUT" value="1011">
+ </constant>
+ <constant name="NOTIFICATION_CRASH" value="1012">
+ </constant>
+ <constant name="NOTIFICATION_OS_IME_UPDATE" value="1013">
+ </constant>
<constant name="PAUSE_MODE_INHERIT" value="0" enum="PauseMode">
Inherits pause mode from the node's parent. For the root node, it is equivalent to PAUSE_MODE_STOP. Default.
</constant>
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml
index e67e3c9a03..ee3f3260d7 100644
--- a/doc/classes/ProjectSettings.xml
+++ b/doc/classes/ProjectSettings.xml
@@ -215,6 +215,8 @@
<member name="audio/channel_disable_time" type="float" setter="" getter="">
Audio buses will disable automatically when sound goes below a given DB threshold for a given time. This saves CPU as effects assigned to that bus will no longer do any processing.
</member>
+ <member name="audio/default_bus_layout" type="String" setter="" getter="">
+ </member>
<member name="audio/driver" type="String" setter="" getter="">
</member>
<member name="audio/enable_audio_input" type="bool" setter="" getter="">
diff --git a/doc/classes/RandomNumberGenerator.xml b/doc/classes/RandomNumberGenerator.xml
index 07c9f2a74b..0e4ede50c0 100644
--- a/doc/classes/RandomNumberGenerator.xml
+++ b/doc/classes/RandomNumberGenerator.xml
@@ -1,9 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="RandomNumberGenerator" inherits="Reference" category="Core" version="3.2">
<brief_description>
- A class for generation pseudo-random numbers.
+ A class for generating pseudo-random numbers.
</brief_description>
<description>
+ RandomNumberGenerator is a class for generating pseudo-random numbers. It currently uses PCG32. The underlying algorithm is an implementation detail. As a result, it should not be depended upon for reproducible random streams across Godot versions.
</description>
<tutorials>
</tutorials>
@@ -14,7 +15,7 @@
<return type="float">
</return>
<description>
- Generates pseudo-random float between '0.0' and '1.0'.
+ Generates pseudo-random float between '0.0' and '1.0', inclusive.
</description>
</method>
<method name="randf_range">
@@ -25,7 +26,7 @@
<argument index="1" name="to" type="float">
</argument>
<description>
- Generates pseudo-random float between [code]from[/code] and [code]to[/code].
+ Generates pseudo-random float between [code]from[/code] and [code]to[/code], inclusive.
</description>
</method>
<method name="randfn">
@@ -43,7 +44,7 @@
<return type="int">
</return>
<description>
- Generates pseudo-random 32-bit unsigned integer between '0' and '4294967295'.
+ Generates pseudo-random 32-bit unsigned integer between '0' and '4294967295', inclusive.
</description>
</method>
<method name="randi_range">
@@ -68,6 +69,7 @@
<members>
<member name="seed" type="int" setter="set_seed" getter="get_seed">
The seed used by the random number generator. A given seed will give a reproducible sequence of pseudo-random numbers.
+ [b]Note:[/b] The RNG does not have an avalanche effect, and can output similar random streams given similar seeds. Consider using a hash function to improve your seed quality if they're sourced externally.
</member>
</members>
<constants>
diff --git a/doc/classes/ResourceSaver.xml b/doc/classes/ResourceSaver.xml
index 165ab0dc95..079d1388f0 100644
--- a/doc/classes/ResourceSaver.xml
+++ b/doc/classes/ResourceSaver.xml
@@ -27,7 +27,7 @@
</argument>
<argument index="1" name="resource" type="Resource">
</argument>
- <argument index="2" name="flags" type="int" default="0">
+ <argument index="2" name="flags" type="int" enum="ResourceSaver.SaverFlags" default="0">
</argument>
<description>
Saves a resource to disk.
diff --git a/doc/classes/SceneTree.xml b/doc/classes/SceneTree.xml
index fb23ef0654..30889c385f 100644
--- a/doc/classes/SceneTree.xml
+++ b/doc/classes/SceneTree.xml
@@ -77,6 +77,7 @@
<return type="int">
</return>
<description>
+ Returns the current frame, i.e. number of frames since the application started.
</description>
</method>
<method name="get_network_connected_peers" qualifiers="const">
diff --git a/doc/classes/Slider.xml b/doc/classes/Slider.xml
index 1e665f0236..98be77641d 100644
--- a/doc/classes/Slider.xml
+++ b/doc/classes/Slider.xml
@@ -14,14 +14,18 @@
</methods>
<members>
<member name="editable" type="bool" setter="set_editable" getter="is_editable">
+ If [code]true[/code], the slider can be interacted with. If [code]false[/code], the value can be changed only by code.
</member>
<member name="focus_mode" type="int" setter="set_focus_mode" getter="get_focus_mode" enum="Control.FocusMode">
</member>
<member name="scrollable" type="bool" setter="set_scrollable" getter="is_scrollable">
+ If [code]true[/code], the value can be changed using the mouse wheel.
</member>
<member name="tick_count" type="int" setter="set_ticks" getter="get_ticks">
+ Number of ticks displayed on the slider, including border ticks. Ticks are uniformly-distributed value markers.
</member>
<member name="ticks_on_borders" type="bool" setter="set_ticks_on_borders" getter="get_ticks_on_borders">
+ If [code]true[/code], the slider will display ticks for minimum and maximum values.
</member>
</members>
<constants>
diff --git a/doc/classes/Spatial.xml b/doc/classes/Spatial.xml
index 7e42e06960..f28ddcf351 100644
--- a/doc/classes/Spatial.xml
+++ b/doc/classes/Spatial.xml
@@ -329,7 +329,7 @@
</signal>
</signals>
<constants>
- <constant name="NOTIFICATION_TRANSFORM_CHANGED" value="29">
+ <constant name="NOTIFICATION_TRANSFORM_CHANGED" value="2000">
Spatial nodes receives this notification when their global transform changes. This means that either the current or a parent node changed its transform.
In order for [code]NOTIFICATION_TRANSFORM_CHANGED[/code] to work, users first need to ask for it, with [method set_notify_transform].
</constant>
diff --git a/doc/classes/String.xml b/doc/classes/String.xml
index c3c4b6f938..67a9b80602 100644
--- a/doc/classes/String.xml
+++ b/doc/classes/String.xml
@@ -432,6 +432,14 @@
Returns [code]true[/code] if this string is a subsequence of the given string, without considering case.
</description>
</method>
+ <method name="is_valid_filename">
+ <return type="bool">
+ </return>
+ <description>
+ Returns [code]true[/code] if this string is free from characters that aren't allowed in file names, those being:
+ [code]: / \ ? * " | % &lt; &gt;[/code]
+ </description>
+ </method>
<method name="is_valid_float">
<return type="bool">
</return>
diff --git a/doc/classes/StyleBoxFlat.xml b/doc/classes/StyleBoxFlat.xml
index d74f481f55..34f99755a4 100644
--- a/doc/classes/StyleBoxFlat.xml
+++ b/doc/classes/StyleBoxFlat.xml
@@ -148,12 +148,12 @@
<member name="shadow_color" type="Color" setter="set_shadow_color" getter="get_shadow_color">
The color of the shadow. (This has no effect when shadow_size &lt; 1)
</member>
- <member name="shadow_size" type="int" setter="set_shadow_size" getter="get_shadow_size">
- The shadow size in pixels.
- </member>
<member name="shadow_offset" type="Vector2" setter="set_shadow_offset" getter="get_shadow_offset">
The shadow offset in pixels. Adjusts the position of the shadow relatively to the stylebox.
</member>
+ <member name="shadow_size" type="int" setter="set_shadow_size" getter="get_shadow_size">
+ The shadow size in pixels.
+ </member>
</members>
<constants>
</constants>
diff --git a/doc/classes/TextEdit.xml b/doc/classes/TextEdit.xml
index 0d52245538..c85738609f 100644
--- a/doc/classes/TextEdit.xml
+++ b/doc/classes/TextEdit.xml
@@ -401,9 +401,10 @@
String value of the [TextEdit].
</member>
<member name="v_scroll_speed" type="float" setter="set_v_scroll_speed" getter="get_v_scroll_speed">
- If [code]true[/code], enables text wrapping when it goes beyond he edge of what is visible.
+ Vertical scroll sensitivity.
</member>
<member name="wrap_enabled" type="bool" setter="set_wrap_enabled" getter="is_wrap_enabled">
+ If [code]true[/code], enables text wrapping when it goes beyond the edge of what is visible.
</member>
</members>
<signals>
diff --git a/doc/classes/TextureRect.xml b/doc/classes/TextureRect.xml
index 7f26fe18e5..eb8014bab8 100644
--- a/doc/classes/TextureRect.xml
+++ b/doc/classes/TextureRect.xml
@@ -16,18 +16,18 @@
<member name="expand" type="bool" setter="set_expand" getter="has_expand">
If [code]true[/code], the texture scales to fit its bounding rectangle. Default value: [code]false[/code].
</member>
- <member name="stretch_mode" type="int" setter="set_stretch_mode" getter="get_stretch_mode" enum="TextureRect.StretchMode">
- Controls the texture's behavior when resizing the node's bounding rectangle. See [enum StretchMode].
- </member>
- <member name="texture" type="Texture" setter="set_texture" getter="get_texture">
- The node's [Texture] resource.
- </member>
<member name="flip_h" type="bool" setter="set_flip_h" getter="is_flipped_h">
If [code]true[/code], texture is flipped horizontally. Default value: [code]false[/code].
</member>
<member name="flip_v" type="bool" setter="set_flip_v" getter="is_flipped_v">
If [code]true[/code], texture is flipped vertically. Default value: [code]false[/code].
</member>
+ <member name="stretch_mode" type="int" setter="set_stretch_mode" getter="get_stretch_mode" enum="TextureRect.StretchMode">
+ Controls the texture's behavior when resizing the node's bounding rectangle. See [enum StretchMode].
+ </member>
+ <member name="texture" type="Texture" setter="set_texture" getter="get_texture">
+ The node's [Texture] resource.
+ </member>
</members>
<constants>
<constant name="STRETCH_SCALE_ON_EXPAND" value="0" enum="StretchMode">
diff --git a/doc/classes/Thread.xml b/doc/classes/Thread.xml
index d2aa1a3f03..ea558735aa 100644
--- a/doc/classes/Thread.xml
+++ b/doc/classes/Thread.xml
@@ -34,7 +34,7 @@
</argument>
<argument index="2" name="userdata" type="Variant" default="null">
</argument>
- <argument index="3" name="priority" type="int" default="1">
+ <argument index="3" name="priority" type="int" enum="Thread.Priority" default="1">
</argument>
<description>
Starts a new [Thread] that runs "method" on object "instance" with "userdata" passed as an argument. The "priority" of the [Thread] can be changed by passing a PRIORITY_* enum.
diff --git a/doc/classes/TileMap.xml b/doc/classes/TileMap.xml
index 3c047487e0..54d9e05180 100644
--- a/doc/classes/TileMap.xml
+++ b/doc/classes/TileMap.xml
@@ -171,7 +171,7 @@
# Write your custom logic here.
# To call the default method:
.set_cell(x, y, tile, flip_x, flip_y, transpose, autotile_coord)
- [/codeblock]
+ [/codeblock]
</description>
</method>
<method name="set_cellv">
diff --git a/doc/classes/Transform.xml b/doc/classes/Transform.xml
index e110fa7b40..8c9a1a36b3 100644
--- a/doc/classes/Transform.xml
+++ b/doc/classes/Transform.xml
@@ -172,9 +172,9 @@
</constant>
<constant name="FLIP_X" value="Transform( -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )">
</constant>
- <constant name="FLIP_Y" value="Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )">
+ <constant name="FLIP_Y" value="Transform( 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0 )">
</constant>
- <constant name="FLIP_Z" value="Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )">
+ <constant name="FLIP_Z" value="Transform( 1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0 )">
</constant>
</constants>
</class>
diff --git a/doc/classes/VSlider.xml b/doc/classes/VSlider.xml
index 477c618064..847e5e5272 100644
--- a/doc/classes/VSlider.xml
+++ b/doc/classes/VSlider.xml
@@ -4,7 +4,7 @@
Vertical slider.
</brief_description>
<description>
- Vertical slider. See [Slider]. This one goes from left (min) to right (max).
+ Vertical slider. See [Slider]. This one goes from bottom (min) to top (max).
</description>
<tutorials>
</tutorials>
diff --git a/doc/classes/VisibilityNotifier.xml b/doc/classes/VisibilityNotifier.xml
index e30078d82f..062371ba29 100644
--- a/doc/classes/VisibilityNotifier.xml
+++ b/doc/classes/VisibilityNotifier.xml
@@ -16,6 +16,7 @@
</return>
<description>
If [code]true[/code], the bounding box is on the screen.
+ Note: It takes one frame for the node's visibility to be assessed once added to the scene tree, so this method will return [code]false[/code] right after it is instantiated, even if it will be on screen in the draw pass.
</description>
</method>
</methods>
diff --git a/doc/classes/VisibilityNotifier2D.xml b/doc/classes/VisibilityNotifier2D.xml
index 5689ced4bf..7b553c7518 100644
--- a/doc/classes/VisibilityNotifier2D.xml
+++ b/doc/classes/VisibilityNotifier2D.xml
@@ -16,6 +16,7 @@
</return>
<description>
If [code]true[/code], the bounding rectangle is on the screen.
+ Note: It takes one frame for the node's visibility to be assessed once added to the scene tree, so this method will return [code]false[/code] right after it is instantiated, even if it will be on screen in the draw pass.
</description>
</method>
</methods>
diff --git a/doc/classes/VisualShaderNodeBooleanConstant.xml b/doc/classes/VisualShaderNodeBooleanConstant.xml
new file mode 100644
index 0000000000..dc2abfff25
--- /dev/null
+++ b/doc/classes/VisualShaderNodeBooleanConstant.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeBooleanConstant" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <members>
+ <member name="constant" type="bool" setter="set_constant" getter="get_constant">
+ </member>
+ </members>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeBooleanUniform.xml b/doc/classes/VisualShaderNodeBooleanUniform.xml
new file mode 100644
index 0000000000..06dca13426
--- /dev/null
+++ b/doc/classes/VisualShaderNodeBooleanUniform.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeBooleanUniform" inherits="VisualShaderNodeUniform" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeColorFunc.xml b/doc/classes/VisualShaderNodeColorFunc.xml
new file mode 100644
index 0000000000..e906049cae
--- /dev/null
+++ b/doc/classes/VisualShaderNodeColorFunc.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeColorFunc" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <members>
+ <member name="function" type="int" setter="set_function" getter="get_function" enum="VisualShaderNodeColorFunc.Function">
+ </member>
+ </members>
+ <constants>
+ <constant name="FUNC_GRAYSCALE" value="0" enum="Function">
+ </constant>
+ <constant name="FUNC_SEPIA" value="1" enum="Function">
+ </constant>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeDeterminant.xml b/doc/classes/VisualShaderNodeDeterminant.xml
new file mode 100644
index 0000000000..661894e7b6
--- /dev/null
+++ b/doc/classes/VisualShaderNodeDeterminant.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeDeterminant" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeFaceForward.xml b/doc/classes/VisualShaderNodeFaceForward.xml
new file mode 100644
index 0000000000..823e251203
--- /dev/null
+++ b/doc/classes/VisualShaderNodeFaceForward.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeFaceForward" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeIf.xml b/doc/classes/VisualShaderNodeIf.xml
new file mode 100644
index 0000000000..4e606b95aa
--- /dev/null
+++ b/doc/classes/VisualShaderNodeIf.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeIf" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeOuterProduct.xml b/doc/classes/VisualShaderNodeOuterProduct.xml
new file mode 100644
index 0000000000..4ea4713428
--- /dev/null
+++ b/doc/classes/VisualShaderNodeOuterProduct.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeOuterProduct" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeScalarClamp.xml b/doc/classes/VisualShaderNodeScalarClamp.xml
new file mode 100644
index 0000000000..66401c6bf6
--- /dev/null
+++ b/doc/classes/VisualShaderNodeScalarClamp.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeScalarClamp" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeScalarDerivativeFunc.xml b/doc/classes/VisualShaderNodeScalarDerivativeFunc.xml
new file mode 100644
index 0000000000..c78be81034
--- /dev/null
+++ b/doc/classes/VisualShaderNodeScalarDerivativeFunc.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeScalarDerivativeFunc" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <members>
+ <member name="function" type="int" setter="set_function" getter="get_function" enum="VisualShaderNodeScalarDerivativeFunc.Function">
+ </member>
+ </members>
+ <constants>
+ <constant name="FUNC_SUM" value="0" enum="Function">
+ </constant>
+ <constant name="FUNC_X" value="1" enum="Function">
+ </constant>
+ <constant name="FUNC_Y" value="2" enum="Function">
+ </constant>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeScalarFunc.xml b/doc/classes/VisualShaderNodeScalarFunc.xml
index 67a5d3f5c4..66bdfab5a6 100644
--- a/doc/classes/VisualShaderNodeScalarFunc.xml
+++ b/doc/classes/VisualShaderNodeScalarFunc.xml
@@ -55,5 +55,27 @@
</constant>
<constant name="FUNC_NEGATE" value="19" enum="Function">
</constant>
+ <constant name="FUNC_ACOSH" value="20" enum="Function">
+ </constant>
+ <constant name="FUNC_ASINH" value="21" enum="Function">
+ </constant>
+ <constant name="FUNC_ATANH" value="22" enum="Function">
+ </constant>
+ <constant name="FUNC_DEGREES" value="23" enum="Function">
+ </constant>
+ <constant name="FUNC_EXP2" value="24" enum="Function">
+ </constant>
+ <constant name="FUNC_INVERSE_SQRT" value="25" enum="Function">
+ </constant>
+ <constant name="FUNC_LOG2" value="26" enum="Function">
+ </constant>
+ <constant name="FUNC_RADIANS" value="27" enum="Function">
+ </constant>
+ <constant name="FUNC_RECIPROCAL" value="28" enum="Function">
+ </constant>
+ <constant name="FUNC_ROUNDEVEN" value="29" enum="Function">
+ </constant>
+ <constant name="FUNC_TRUNC" value="30" enum="Function">
+ </constant>
</constants>
</class>
diff --git a/doc/classes/VisualShaderNodeScalarOp.xml b/doc/classes/VisualShaderNodeScalarOp.xml
index 34ec89f8be..c5a331679f 100644
--- a/doc/classes/VisualShaderNodeScalarOp.xml
+++ b/doc/classes/VisualShaderNodeScalarOp.xml
@@ -33,5 +33,7 @@
</constant>
<constant name="OP_ATAN2" value="8" enum="Operator">
</constant>
+ <constant name="OP_STEP" value="9" enum="Operator">
+ </constant>
</constants>
</class>
diff --git a/doc/classes/VisualShaderNodeScalarSmoothStep.xml b/doc/classes/VisualShaderNodeScalarSmoothStep.xml
new file mode 100644
index 0000000000..5be54d0b4f
--- /dev/null
+++ b/doc/classes/VisualShaderNodeScalarSmoothStep.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeScalarSmoothStep" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeSwitch.xml b/doc/classes/VisualShaderNodeSwitch.xml
new file mode 100644
index 0000000000..1c346e7a1f
--- /dev/null
+++ b/doc/classes/VisualShaderNodeSwitch.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeSwitch" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeTransformFunc.xml b/doc/classes/VisualShaderNodeTransformFunc.xml
new file mode 100644
index 0000000000..601e66ca16
--- /dev/null
+++ b/doc/classes/VisualShaderNodeTransformFunc.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeTransformFunc" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <members>
+ <member name="function" type="int" setter="set_function" getter="get_function" enum="VisualShaderNodeTransformFunc.Function">
+ </member>
+ </members>
+ <constants>
+ <constant name="FUNC_INVERSE" value="0" enum="Function">
+ </constant>
+ <constant name="FUNC_TRANSPOSE" value="1" enum="Function">
+ </constant>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeTransformMult.xml b/doc/classes/VisualShaderNodeTransformMult.xml
index 47026b400e..e9c445526d 100644
--- a/doc/classes/VisualShaderNodeTransformMult.xml
+++ b/doc/classes/VisualShaderNodeTransformMult.xml
@@ -19,5 +19,9 @@
</constant>
<constant name="OP_BxA" value="1" enum="Operator">
</constant>
+ <constant name="OP_AxB_COMP" value="2" enum="Operator">
+ </constant>
+ <constant name="OP_BxA_COMP" value="3" enum="Operator">
+ </constant>
</constants>
</class>
diff --git a/doc/classes/VisualShaderNodeVectorClamp.xml b/doc/classes/VisualShaderNodeVectorClamp.xml
new file mode 100644
index 0000000000..677625ebce
--- /dev/null
+++ b/doc/classes/VisualShaderNodeVectorClamp.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeVectorClamp" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeVectorDerivativeFunc.xml b/doc/classes/VisualShaderNodeVectorDerivativeFunc.xml
new file mode 100644
index 0000000000..e382cb0b58
--- /dev/null
+++ b/doc/classes/VisualShaderNodeVectorDerivativeFunc.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeVectorDerivativeFunc" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <members>
+ <member name="function" type="int" setter="set_function" getter="get_function" enum="VisualShaderNodeVectorDerivativeFunc.Function">
+ </member>
+ </members>
+ <constants>
+ <constant name="FUNC_SUM" value="0" enum="Function">
+ </constant>
+ <constant name="FUNC_X" value="1" enum="Function">
+ </constant>
+ <constant name="FUNC_Y" value="2" enum="Function">
+ </constant>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeVectorDistance.xml b/doc/classes/VisualShaderNodeVectorDistance.xml
new file mode 100644
index 0000000000..d83a520a46
--- /dev/null
+++ b/doc/classes/VisualShaderNodeVectorDistance.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeVectorDistance" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeVectorFunc.xml b/doc/classes/VisualShaderNodeVectorFunc.xml
index 968d73d4e1..5e57d85b4c 100644
--- a/doc/classes/VisualShaderNodeVectorFunc.xml
+++ b/doc/classes/VisualShaderNodeVectorFunc.xml
@@ -27,5 +27,61 @@
</constant>
<constant name="FUNC_HSV2RGB" value="5" enum="Function">
</constant>
+ <constant name="FUNC_ABS" value="6" enum="Function">
+ </constant>
+ <constant name="FUNC_ACOS" value="7" enum="Function">
+ </constant>
+ <constant name="FUNC_ACOSH" value="8" enum="Function">
+ </constant>
+ <constant name="FUNC_ASIN" value="9" enum="Function">
+ </constant>
+ <constant name="FUNC_ASINH" value="10" enum="Function">
+ </constant>
+ <constant name="FUNC_ATAN" value="11" enum="Function">
+ </constant>
+ <constant name="FUNC_ATANH" value="12" enum="Function">
+ </constant>
+ <constant name="FUNC_CEIL" value="13" enum="Function">
+ </constant>
+ <constant name="FUNC_COS" value="14" enum="Function">
+ </constant>
+ <constant name="FUNC_COSH" value="15" enum="Function">
+ </constant>
+ <constant name="FUNC_DEGREES" value="16" enum="Function">
+ </constant>
+ <constant name="FUNC_EXP" value="17" enum="Function">
+ </constant>
+ <constant name="FUNC_EXP2" value="18" enum="Function">
+ </constant>
+ <constant name="FUNC_FLOOR" value="19" enum="Function">
+ </constant>
+ <constant name="FUNC_FRAC" value="20" enum="Function">
+ </constant>
+ <constant name="FUNC_INVERSE_SQRT" value="21" enum="Function">
+ </constant>
+ <constant name="FUNC_LOG" value="22" enum="Function">
+ </constant>
+ <constant name="FUNC_LOG2" value="23" enum="Function">
+ </constant>
+ <constant name="FUNC_RADIANS" value="24" enum="Function">
+ </constant>
+ <constant name="FUNC_ROUND" value="25" enum="Function">
+ </constant>
+ <constant name="FUNC_ROUNDEVEN" value="26" enum="Function">
+ </constant>
+ <constant name="FUNC_SIGN" value="27" enum="Function">
+ </constant>
+ <constant name="FUNC_SIN" value="28" enum="Function">
+ </constant>
+ <constant name="FUNC_SINH" value="29" enum="Function">
+ </constant>
+ <constant name="FUNC_SQRT" value="30" enum="Function">
+ </constant>
+ <constant name="FUNC_TAN" value="31" enum="Function">
+ </constant>
+ <constant name="FUNC_TANH" value="32" enum="Function">
+ </constant>
+ <constant name="FUNC_TRUNC" value="33" enum="Function">
+ </constant>
</constants>
</class>
diff --git a/doc/classes/VisualShaderNodeVectorOp.xml b/doc/classes/VisualShaderNodeVectorOp.xml
index 16c1f8f25d..6524f129da 100644
--- a/doc/classes/VisualShaderNodeVectorOp.xml
+++ b/doc/classes/VisualShaderNodeVectorOp.xml
@@ -33,5 +33,11 @@
</constant>
<constant name="OP_CROSS" value="8" enum="Operator">
</constant>
+ <constant name="OP_ATAN2" value="9" enum="Operator">
+ </constant>
+ <constant name="OP_REFLECT" value="10" enum="Operator">
+ </constant>
+ <constant name="OP_STEP" value="11" enum="Operator">
+ </constant>
</constants>
</class>
diff --git a/doc/classes/VisualShaderNodeVectorRefract.xml b/doc/classes/VisualShaderNodeVectorRefract.xml
new file mode 100644
index 0000000000..32bb0692d4
--- /dev/null
+++ b/doc/classes/VisualShaderNodeVectorRefract.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeVectorRefract" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeVectorScalarSmoothStep.xml b/doc/classes/VisualShaderNodeVectorScalarSmoothStep.xml
new file mode 100644
index 0000000000..a158b4731d
--- /dev/null
+++ b/doc/classes/VisualShaderNodeVectorScalarSmoothStep.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeVectorScalarSmoothStep" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeVectorScalarStep.xml b/doc/classes/VisualShaderNodeVectorScalarStep.xml
new file mode 100644
index 0000000000..88c9b006fc
--- /dev/null
+++ b/doc/classes/VisualShaderNodeVectorScalarStep.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeVectorScalarStep" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/VisualShaderNodeVectorSmoothStep.xml b/doc/classes/VisualShaderNodeVectorSmoothStep.xml
new file mode 100644
index 0000000000..1ddd5f26ce
--- /dev/null
+++ b/doc/classes/VisualShaderNodeVectorSmoothStep.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="VisualShaderNodeVectorSmoothStep" inherits="VisualShaderNode" category="Core" version="3.2">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <demos>
+ </demos>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/drivers/gles2/rasterizer_canvas_gles2.cpp b/drivers/gles2/rasterizer_canvas_gles2.cpp
index 9eb159cb31..7232d2d95a 100644
--- a/drivers/gles2/rasterizer_canvas_gles2.cpp
+++ b/drivers/gles2/rasterizer_canvas_gles2.cpp
@@ -943,7 +943,8 @@ void RasterizerCanvasGLES2::_canvas_item_render_commands(Item *p_item, Item *cur
glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
} break;
- default: {}
+ default: {
+ }
}
}
}
@@ -1032,7 +1033,8 @@ void RasterizerCanvasGLES2::_canvas_item_render_commands(Item *p_item, Item *cur
glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
} break;
- default: {}
+ default: {
+ }
}
}
}
diff --git a/drivers/gles2/rasterizer_scene_gles2.cpp b/drivers/gles2/rasterizer_scene_gles2.cpp
index c996078ba6..e790d5b031 100644
--- a/drivers/gles2/rasterizer_scene_gles2.cpp
+++ b/drivers/gles2/rasterizer_scene_gles2.cpp
@@ -1208,7 +1208,8 @@ void RasterizerSceneGLES2::_fill_render_list(InstanceBase **p_cull_result, int p
} break;
- default: {}
+ default: {
+ }
}
}
}
@@ -1369,7 +1370,8 @@ void RasterizerSceneGLES2::_setup_geometry(RenderList::Element *p_element, Raste
glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
} break;
- default: {}
+ default: {
+ }
}
}
}
@@ -1530,7 +1532,8 @@ void RasterizerSceneGLES2::_setup_geometry(RenderList::Element *p_element, Raste
glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
} break;
- default: {}
+ default: {
+ }
}
}
}
@@ -1550,7 +1553,8 @@ void RasterizerSceneGLES2::_setup_geometry(RenderList::Element *p_element, Raste
case VS::INSTANCE_IMMEDIATE: {
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1758,7 +1762,8 @@ void RasterizerSceneGLES2::_render_geometry(RenderList::Element *p_element) {
}
} break;
- default: {}
+ default: {
+ }
}
}
@@ -2074,7 +2079,8 @@ void RasterizerSceneGLES2::_setup_light(LightInstance *light, ShadowAtlas *shado
}
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/drivers/gles2/rasterizer_storage_gles2.cpp b/drivers/gles2/rasterizer_storage_gles2.cpp
index b051c7d811..1e32d8166f 100644
--- a/drivers/gles2/rasterizer_storage_gles2.cpp
+++ b/drivers/gles2/rasterizer_storage_gles2.cpp
@@ -1557,6 +1557,10 @@ void RasterizerStorageGLES2::shader_get_param_list(RID p_shader, List<PropertyIn
case ShaderLanguage::TYPE_FLOAT: {
pi.type = Variant::REAL;
+ if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
+ pi.hint = PROPERTY_HINT_RANGE;
+ pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]);
+ }
} break;
case ShaderLanguage::TYPE_VEC2: {
@@ -3737,7 +3741,8 @@ void RasterizerStorageGLES2::light_set_param(RID p_light, VS::LightParam p_param
light->version++;
light->instance_change_notify(true, false);
} break;
- default: {}
+ default: {
+ }
}
light->param[p_param] = p_value;
@@ -4880,7 +4885,8 @@ void RasterizerStorageGLES2::render_target_set_flag(RID p_render_target, RenderT
_render_target_allocate(rt);
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/drivers/gles2/shaders/effect_blur.glsl b/drivers/gles2/shaders/effect_blur.glsl
index a531802c75..df79e89931 100644
--- a/drivers/gles2/shaders/effect_blur.glsl
+++ b/drivers/gles2/shaders/effect_blur.glsl
@@ -116,12 +116,13 @@ void main() {
#ifdef GAUSSIAN_HORIZONTAL
vec2 pix_size = pixel_size;
pix_size *= 0.5; //reading from larger buffer, so use more samples
+ // sigma 2
vec4 color = textureLod(source_color, uv_interp + vec2(0.0, 0.0) * pix_size, lod) * 0.214607;
color += textureLod(source_color, uv_interp + vec2(1.0, 0.0) * pix_size, lod) * 0.189879;
- color += textureLod(source_color, uv_interp + vec2(2.0, 0.0) * pix_size, lod) * 0.157305;
+ color += textureLod(source_color, uv_interp + vec2(2.0, 0.0) * pix_size, lod) * 0.131514;
color += textureLod(source_color, uv_interp + vec2(3.0, 0.0) * pix_size, lod) * 0.071303;
color += textureLod(source_color, uv_interp + vec2(-1.0, 0.0) * pix_size, lod) * 0.189879;
- color += textureLod(source_color, uv_interp + vec2(-2.0, 0.0) * pix_size, lod) * 0.157305;
+ color += textureLod(source_color, uv_interp + vec2(-2.0, 0.0) * pix_size, lod) * 0.131514;
color += textureLod(source_color, uv_interp + vec2(-3.0, 0.0) * pix_size, lod) * 0.071303;
frag_color = color;
#endif
diff --git a/drivers/gles3/rasterizer_scene_gles3.cpp b/drivers/gles3/rasterizer_scene_gles3.cpp
index d1b704e09a..56a6c51460 100644
--- a/drivers/gles3/rasterizer_scene_gles3.cpp
+++ b/drivers/gles3/rasterizer_scene_gles3.cpp
@@ -1278,7 +1278,8 @@ bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material *p_m
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1525,7 +1526,8 @@ void RasterizerSceneGLES3::_setup_geometry(RenderList::Element *e, const Transfo
}
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1847,7 +1849,8 @@ void RasterizerSceneGLES3::_render_geometry(RenderList::Element *e) {
}
} break;
- default: {}
+ default: {
+ }
}
}
@@ -3248,7 +3251,8 @@ void RasterizerSceneGLES3::_fill_render_list(InstanceBase **p_cull_result, int p
}
} break;
- default: {}
+ default: {
+ }
}
}
}
@@ -4423,7 +4427,8 @@ void RasterizerSceneGLES3::render_scene(const Transform &p_cam_transform, const
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
break;
- default: {}
+ default: {
+ }
}
}
diff --git a/drivers/gles3/rasterizer_storage_gles3.cpp b/drivers/gles3/rasterizer_storage_gles3.cpp
index 6169790163..be44d62efc 100644
--- a/drivers/gles3/rasterizer_storage_gles3.cpp
+++ b/drivers/gles3/rasterizer_storage_gles3.cpp
@@ -642,7 +642,8 @@ void RasterizerStorageGLES3::texture_allocate(RID p_texture, int p_width, int p_
p_flags &= ~VS::TEXTURE_FLAG_FILTER;
}
} break;
- default: {}
+ default: {
+ }
}
#endif
@@ -2751,7 +2752,8 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy
gui[14] = v.origin.z;
gui[15] = 1;
} break;
- default: {}
+ default: {
+ }
}
}
@@ -2919,7 +2921,8 @@ _FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type,
gui[i] = value[i].real;
}
} break;
- default: {}
+ default: {
+ }
}
}
@@ -2962,7 +2965,8 @@ _FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type,
zeromem(data, 64);
} break;
- default: {}
+ default: {
+ }
}
}
@@ -5246,7 +5250,8 @@ void RasterizerStorageGLES3::light_set_param(RID p_light, VS::LightParam p_param
light->version++;
light->instance_change_notify(true, false);
} break;
- default: {}
+ default: {
+ }
}
light->param[p_param] = p_value;
@@ -5448,7 +5453,8 @@ AABB RasterizerStorageGLES3::light_get_aabb(RID p_light) const {
return AABB();
} break;
- default: {}
+ default: {
+ }
}
ERR_FAIL_V(AABB());
@@ -7379,7 +7385,8 @@ void RasterizerStorageGLES3::render_target_set_flag(RID p_render_target, RenderT
_render_target_allocate(rt);
} break;
- default: {}
+ default: {
+ }
}
}
bool RasterizerStorageGLES3::render_target_was_used(RID p_render_target) {
diff --git a/drivers/gles3/shader_gles3.h b/drivers/gles3/shader_gles3.h
index 1ed30986bf..be2c34ba07 100644
--- a/drivers/gles3/shader_gles3.h
+++ b/drivers/gles3/shader_gles3.h
@@ -289,7 +289,9 @@ private:
glUniformMatrix4fv(p_uniform, 1, false, matrix);
} break;
- default: { ERR_FAIL(); } // do nothing
+ default: {
+ ERR_FAIL();
+ } // do nothing
}
}
diff --git a/drivers/gles3/shaders/effect_blur.glsl b/drivers/gles3/shaders/effect_blur.glsl
index fc15ca31b1..ff5a9f326f 100644
--- a/drivers/gles3/shaders/effect_blur.glsl
+++ b/drivers/gles3/shaders/effect_blur.glsl
@@ -117,12 +117,13 @@ void main() {
#ifdef GAUSSIAN_HORIZONTAL
vec2 pix_size = pixel_size;
pix_size *= 0.5; //reading from larger buffer, so use more samples
+ // sigma 2
vec4 color = textureLod(source_color, uv_interp + vec2(0.0, 0.0) * pix_size, lod) * 0.214607;
color += textureLod(source_color, uv_interp + vec2(1.0, 0.0) * pix_size, lod) * 0.189879;
- color += textureLod(source_color, uv_interp + vec2(2.0, 0.0) * pix_size, lod) * 0.157305;
+ color += textureLod(source_color, uv_interp + vec2(2.0, 0.0) * pix_size, lod) * 0.131514;
color += textureLod(source_color, uv_interp + vec2(3.0, 0.0) * pix_size, lod) * 0.071303;
color += textureLod(source_color, uv_interp + vec2(-1.0, 0.0) * pix_size, lod) * 0.189879;
- color += textureLod(source_color, uv_interp + vec2(-2.0, 0.0) * pix_size, lod) * 0.157305;
+ color += textureLod(source_color, uv_interp + vec2(-2.0, 0.0) * pix_size, lod) * 0.131514;
color += textureLod(source_color, uv_interp + vec2(-3.0, 0.0) * pix_size, lod) * 0.071303;
frag_color = color;
#endif
diff --git a/drivers/unix/os_unix.cpp b/drivers/unix/os_unix.cpp
index e7550903a8..2778590658 100644
--- a/drivers/unix/os_unix.cpp
+++ b/drivers/unix/os_unix.cpp
@@ -108,6 +108,7 @@ void OS_Unix::initialize_debugging() {
if (ScriptDebugger::get_singleton() != NULL) {
struct sigaction action;
+ memset(&action, 0, sizeof(action));
action.sa_handler = handle_interrupt;
sigaction(SIGINT, &action, NULL);
}
diff --git a/drivers/windows/semaphore_windows.cpp b/drivers/windows/semaphore_windows.cpp
index 718bb81836..55b47e45eb 100644
--- a/drivers/windows/semaphore_windows.cpp
+++ b/drivers/windows/semaphore_windows.cpp
@@ -54,7 +54,8 @@ int SemaphoreWindows::get() const {
case WAIT_TIMEOUT: {
return 0;
} break;
- default: {}
+ default: {
+ }
}
ERR_FAIL_V(-1);
diff --git a/editor/animation_track_editor.cpp b/editor/animation_track_editor.cpp
index 8807a01f64..39c93fa785 100644
--- a/editor/animation_track_editor.cpp
+++ b/editor/animation_track_editor.cpp
@@ -109,9 +109,17 @@ public:
ERR_FAIL_COND_V(key == -1, false);
String name = p_name;
- if (name == "time") {
+ if (name == "time" || name == "frame") {
float new_time = p_value;
+
+ if (name == "frame") {
+ float fps = animation->get_step();
+ if (fps > 0) {
+ fps = 1.0 / fps;
+ }
+ new_time /= fps;
+ }
if (new_time == key_ofs)
return true;
@@ -413,6 +421,13 @@ public:
if (name == "time") {
r_ret = key_ofs;
return true;
+ } else if (name == "frame") {
+ float fps = animation->get_step();
+ if (fps > 0) {
+ fps = 1.0 / fps;
+ }
+ r_ret = key_ofs * fps;
+ return true;
} else if (name == "easing") {
r_ret = animation->track_get_key_transition(track, key);
return true;
@@ -527,7 +542,12 @@ public:
int key = animation->track_find_key(track, key_ofs, true);
ERR_FAIL_COND(key == -1);
- p_list->push_back(PropertyInfo(Variant::REAL, "time", PROPERTY_HINT_RANGE, "0," + rtos(animation->get_length()) + ",0.01"));
+ if (use_fps && animation->get_step() > 0) {
+ float max_frame = animation->get_length() / animation->get_step();
+ p_list->push_back(PropertyInfo(Variant::REAL, "frame", PROPERTY_HINT_RANGE, "0," + rtos(max_frame) + ",0.01"));
+ } else {
+ p_list->push_back(PropertyInfo(Variant::REAL, "time", PROPERTY_HINT_RANGE, "0," + rtos(animation->get_length()) + ",0.01"));
+ }
switch (animation->track_get_type(track)) {
@@ -648,6 +668,7 @@ public:
PropertyInfo hint;
NodePath base;
+ bool use_fps;
void notify_change() {
@@ -658,7 +679,13 @@ public:
return root_path;
}
+ void set_use_fps(bool p_enable) {
+ use_fps = p_enable;
+ _change_notify();
+ }
+
AnimationTrackKeyEdit() {
+ use_fps = false;
key_ofs = 0;
track = -1;
setting = false;
@@ -690,6 +717,9 @@ void AnimationTimelineEdit::_anim_length_changed(double p_new_len) {
return;
p_new_len = MAX(0.001, p_new_len);
+ if (use_fps && animation->get_step() > 0) {
+ p_new_len *= animation->get_step();
+ }
editing = true;
undo_redo->create_action(TTR("Change Animation Length"));
@@ -887,24 +917,53 @@ void AnimationTimelineEdit::_notification(int p_what) {
decimals = 0;
}
- for (int i = 0; i < zoomw; i++) {
+ if (use_fps) {
+
+ float step_size = animation->get_step();
+ if (step_size > 0) {
+
+ int prev_frame_ofs = -10000000;
- float pos = get_value() + double(i) / scale;
- float prev = get_value() + (double(i) - 1.0) / scale;
+ for (int i = 0; i < zoomw; i++) {
- int sc = int(Math::floor(pos * SC_ADJ));
- int prev_sc = int(Math::floor(prev * SC_ADJ));
- bool sub = (sc % SC_ADJ);
+ float pos = get_value() + double(i) / scale;
+ float prev = get_value() + (double(i) - 1.0) / scale;
- if ((sc / step) != (prev_sc / step) || (prev_sc < 0 && sc >= 0)) {
+ int frame = pos / step_size;
+ int prev_frame = prev / step_size;
- int scd = sc < 0 ? prev_sc : sc;
- draw_line(Point2(get_name_limit() + i, 0), Point2(get_name_limit() + i, h), linecolor);
- draw_string(font, Point2(get_name_limit() + i + 3, (h - font->get_height()) / 2 + font->get_ascent()).floor(), String::num((scd - (scd % step)) / double(SC_ADJ), decimals), sub ? color_time_dec : color_time_sec, zoomw - i);
+ bool sub = Math::floor(prev) == Math::floor(pos);
+
+ if (frame != prev_frame && i >= prev_frame_ofs) {
+
+ draw_line(Point2(get_name_limit() + i, 0), Point2(get_name_limit() + i, h), linecolor, Math::round(EDSCALE));
+
+ draw_string(font, Point2(get_name_limit() + i + 3 * EDSCALE, (h - font->get_height()) / 2 + font->get_ascent()).floor(), itos(frame), sub ? color_time_dec : color_time_sec, zoomw - i);
+ prev_frame_ofs = i + font->get_string_size(itos(frame)).x + 5 * EDSCALE;
+ }
+ }
+ }
+
+ } else {
+ for (int i = 0; i < zoomw; i++) {
+
+ float pos = get_value() + double(i) / scale;
+ float prev = get_value() + (double(i) - 1.0) / scale;
+
+ int sc = int(Math::floor(pos * SC_ADJ));
+ int prev_sc = int(Math::floor(prev * SC_ADJ));
+ bool sub = (sc % SC_ADJ);
+
+ if ((sc / step) != (prev_sc / step) || (prev_sc < 0 && sc >= 0)) {
+
+ int scd = sc < 0 ? prev_sc : sc;
+ draw_line(Point2(get_name_limit() + i, 0), Point2(get_name_limit() + i, h), linecolor, Math::round(EDSCALE));
+ draw_string(font, Point2(get_name_limit() + i + 3, (h - font->get_height()) / 2 + font->get_ascent()).floor(), String::num((scd - (scd % step)) / double(SC_ADJ), decimals), sub ? color_time_dec : color_time_sec, zoomw - i);
+ }
}
}
- draw_line(Vector2(0, get_size().height), get_size(), linecolor);
+ draw_line(Vector2(0, get_size().height), get_size(), linecolor, Math::round(EDSCALE));
}
}
@@ -961,7 +1020,11 @@ void AnimationTimelineEdit::update_values() {
return;
editing = true;
- length->set_value(animation->get_length());
+ if (use_fps && animation->get_step() > 0) {
+ length->set_value(animation->get_length() / animation->get_step());
+ } else {
+ length->set_value(animation->get_length());
+ }
loop->set_pressed(animation->has_loop());
editing = false;
}
@@ -978,7 +1041,7 @@ void AnimationTimelineEdit::_play_position_draw() {
if (px >= get_name_limit() && px < (play_position->get_size().width - get_buttons_width())) {
Color color = get_color("accent_color", "Editor");
- play_position->draw_line(Point2(px, 0), Point2(px, h), color);
+ play_position->draw_line(Point2(px, 0), Point2(px, h), color, Math::round(EDSCALE));
}
}
@@ -1046,6 +1109,15 @@ void AnimationTimelineEdit::_gui_input(const Ref<InputEvent> &p_event) {
}
}
+void AnimationTimelineEdit::set_use_fps(bool p_use_fps) {
+ use_fps = p_use_fps;
+ update_values();
+ update();
+}
+bool AnimationTimelineEdit::is_using_fps() const {
+ return use_fps;
+}
+
void AnimationTimelineEdit::set_hscroll(HScrollBar *p_hscroll) {
hscroll = p_hscroll;
@@ -1072,6 +1144,7 @@ void AnimationTimelineEdit::_bind_methods() {
AnimationTimelineEdit::AnimationTimelineEdit() {
+ use_fps = false;
editing = false;
name_limit = 150;
zoom = NULL;
@@ -1099,7 +1172,7 @@ AnimationTimelineEdit::AnimationTimelineEdit() {
len_hb->add_child(time_icon);
length = memnew(EditorSpinSlider);
length->set_min(0.001);
- length->set_max(3600);
+ length->set_max(36000);
length->set_step(0.01);
length->set_allow_greater(true);
length->set_custom_minimum_size(Vector2(70 * EDSCALE, 0));
@@ -1237,7 +1310,7 @@ void AnimationTrackEdit::_notification(int p_what) {
string_pos = string_pos.floor();
draw_string(font, string_pos, text, text_color, limit - ofs - hsep);
- draw_line(Point2(limit, 0), Point2(limit, get_size().height), linecolor);
+ draw_line(Point2(limit, 0), Point2(limit, get_size().height), linecolor, Math::round(EDSCALE));
}
// KEYFAMES //
@@ -1297,7 +1370,7 @@ void AnimationTrackEdit::_notification(int p_what) {
Ref<Texture> down_icon = get_icon("select_arrow", "Tree");
- draw_line(Point2(ofs, 0), Point2(ofs, get_size().height), linecolor);
+ draw_line(Point2(ofs, 0), Point2(ofs, get_size().height), linecolor, Math::round(EDSCALE));
ofs += hsep;
{
@@ -1344,7 +1417,7 @@ void AnimationTrackEdit::_notification(int p_what) {
}
ofs += down_icon->get_width();
- draw_line(Point2(ofs + hsep * 0.5, 0), Point2(ofs + hsep * 0.5, get_size().height), linecolor);
+ draw_line(Point2(ofs + hsep * 0.5, 0), Point2(ofs + hsep * 0.5, get_size().height), linecolor, Math::round(EDSCALE));
ofs += hsep;
}
@@ -1377,7 +1450,7 @@ void AnimationTrackEdit::_notification(int p_what) {
}
ofs += down_icon->get_width();
- draw_line(Point2(ofs + hsep * 0.5, 0), Point2(ofs + hsep * 0.5, get_size().height), linecolor);
+ draw_line(Point2(ofs + hsep * 0.5, 0), Point2(ofs + hsep * 0.5, get_size().height), linecolor, Math::round(EDSCALE));
ofs += hsep;
}
@@ -1410,7 +1483,7 @@ void AnimationTrackEdit::_notification(int p_what) {
}
ofs += down_icon->get_width();
- draw_line(Point2(ofs + hsep * 0.5, 0), Point2(ofs + hsep * 0.5, get_size().height), linecolor);
+ draw_line(Point2(ofs + hsep * 0.5, 0), Point2(ofs + hsep * 0.5, get_size().height), linecolor, Math::round(EDSCALE));
ofs += hsep;
}
@@ -1428,17 +1501,17 @@ void AnimationTrackEdit::_notification(int p_what) {
}
if (in_group) {
- draw_line(Vector2(timeline->get_name_limit(), get_size().height), get_size(), linecolor);
+ draw_line(Vector2(timeline->get_name_limit(), get_size().height), get_size(), linecolor, Math::round(EDSCALE));
} else {
- draw_line(Vector2(0, get_size().height), get_size(), linecolor);
+ draw_line(Vector2(0, get_size().height), get_size(), linecolor, Math::round(EDSCALE));
}
if (dropping_at != 0) {
Color drop_color = get_color("accent_color", "Editor");
if (dropping_at < 0) {
- draw_line(Vector2(0, 0), Vector2(get_size().width, 0), drop_color);
+ draw_line(Vector2(0, 0), Vector2(get_size().width, 0), drop_color, Math::round(EDSCALE));
} else {
- draw_line(Vector2(0, get_size().height), get_size(), drop_color);
+ draw_line(Vector2(0, get_size().height), get_size(), drop_color, Math::round(EDSCALE));
}
}
}
@@ -1487,7 +1560,7 @@ void AnimationTrackEdit::draw_key_link(int p_index, float p_pixels_sec, int p_x,
int from_x = MAX(p_x, p_clip_left);
int to_x = MIN(p_next_x, p_clip_right);
- draw_line(Point2(from_x + 1, get_size().height / 2), Point2(to_x, get_size().height / 2), color, 2);
+ draw_line(Point2(from_x + 1, get_size().height / 2), Point2(to_x, get_size().height / 2), color, Math::round(2 * EDSCALE));
}
void AnimationTrackEdit::draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right) {
@@ -1667,7 +1740,7 @@ void AnimationTrackEdit::_play_position_draw() {
if (px >= timeline->get_name_limit() && px < (get_size().width - timeline->get_buttons_width())) {
Color color = get_color("accent_color", "Editor");
- play_position->draw_line(Point2(px, 0), Point2(px, h), color);
+ play_position->draw_line(Point2(px, 0), Point2(px, h), color, Math::round(EDSCALE));
}
}
@@ -2370,9 +2443,9 @@ void AnimationTrackEditGroup::_notification(int p_what) {
Color linecolor = color;
linecolor.a = 0.2;
- draw_line(Point2(), Point2(get_size().width, 0), linecolor);
- draw_line(Point2(timeline->get_name_limit(), 0), Point2(timeline->get_name_limit(), get_size().height), linecolor);
- draw_line(Point2(get_size().width - timeline->get_buttons_width(), 0), Point2(get_size().width - timeline->get_buttons_width(), get_size().height), linecolor);
+ draw_line(Point2(), Point2(get_size().width, 0), linecolor, Math::round(EDSCALE));
+ draw_line(Point2(timeline->get_name_limit(), 0), Point2(timeline->get_name_limit(), get_size().height), linecolor, Math::round(EDSCALE));
+ draw_line(Point2(get_size().width - timeline->get_buttons_width(), 0), Point2(get_size().width - timeline->get_buttons_width(), get_size().height), linecolor, Math::round(EDSCALE));
int ofs = 0;
draw_texture(icon, Point2(ofs, int(get_size().height - icon->get_height()) / 2));
@@ -2383,7 +2456,7 @@ void AnimationTrackEditGroup::_notification(int p_what) {
if (px >= timeline->get_name_limit() && px < (get_size().width - timeline->get_buttons_width())) {
Color accent = get_color("accent_color", "Editor");
- draw_line(Point2(px, 0), Point2(px, get_size().height), accent);
+ draw_line(Point2(px, 0), Point2(px, get_size().height), accent, Math::round(EDSCALE));
}
}
}
@@ -2462,10 +2535,12 @@ void AnimationTrackEditor::set_animation(const Ref<Animation> &p_anim) {
hscroll->show();
edit->set_disabled(false);
step->set_block_signals(true);
- step->set_value(animation->get_step());
+
+ _update_step_spinbox();
step->set_block_signals(false);
step->set_read_only(false);
snap->set_disabled(false);
+ snap_mode->set_disabled(true);
} else {
hscroll->hide();
edit->set_disabled(true);
@@ -2474,6 +2549,7 @@ void AnimationTrackEditor::set_animation(const Ref<Animation> &p_anim) {
step->set_block_signals(false);
step->set_read_only(true);
snap->set_disabled(true);
+ snap_mode->set_disabled(false);
}
}
@@ -2518,6 +2594,43 @@ void AnimationTrackEditor::update_keying() {
bool AnimationTrackEditor::has_keying() const {
return keying;
}
+Dictionary AnimationTrackEditor::get_state() const {
+ Dictionary state;
+ state["fps_mode"] = timeline->is_using_fps();
+ state["zoom"] = zoom->get_value();
+ state["offset"] = timeline->get_value();
+ state["v_scroll"] = scroll->get_v_scrollbar()->get_value();
+ return state;
+}
+void AnimationTrackEditor::set_state(const Dictionary &p_state) {
+ if (p_state.has("fps_mode")) {
+ bool fps_mode = p_state["fps_mode"];
+ if (fps_mode) {
+ snap_mode->select(1);
+ } else {
+ snap_mode->select(0);
+ }
+ _snap_mode_changed(snap_mode->get_selected());
+ } else {
+ snap_mode->select(0);
+ _snap_mode_changed(snap_mode->get_selected());
+ }
+ if (p_state.has("zoom")) {
+ zoom->set_value(p_state["zoom"]);
+ } else {
+ zoom->set_value(1.0);
+ }
+ if (p_state.has("offset")) {
+ timeline->set_value(p_state["offset"]);
+ } else {
+ timeline->set_value(0);
+ }
+ if (p_state.has("v_scroll")) {
+ scroll->get_v_scrollbar()->set_value(p_state["v_scroll"]);
+ } else {
+ scroll->get_v_scrollbar()->set_value(0);
+ }
+}
void AnimationTrackEditor::cleanup() {
set_animation(Ref<Animation>());
@@ -3417,6 +3530,34 @@ void AnimationTrackEditor::_animation_changed() {
call_deferred("_animation_update");
}
+void AnimationTrackEditor::_snap_mode_changed(int p_mode) {
+
+ timeline->set_use_fps(p_mode == 1);
+ if (key_edit) {
+ key_edit->set_use_fps(p_mode == 1);
+ }
+ _update_step_spinbox();
+}
+
+void AnimationTrackEditor::_update_step_spinbox() {
+ if (!animation.is_valid()) {
+ return;
+ }
+ step->set_block_signals(true);
+
+ if (timeline->is_using_fps()) {
+ if (animation->get_step() == 0) {
+ step->set_value(0);
+ } else {
+ step->set_value(1.0 / animation->get_step());
+ }
+
+ } else {
+ step->set_value(animation->get_step());
+ }
+
+ step->set_block_signals(false);
+}
void AnimationTrackEditor::_animation_update() {
timeline->update();
@@ -3454,9 +3595,7 @@ void AnimationTrackEditor::_animation_update() {
bezier_edit->update();
- step->set_block_signals(true);
- step->set_value(animation->get_step());
- step->set_block_signals(false);
+ _update_step_spinbox();
animation_changing_awaiting_update = false;
}
@@ -3497,12 +3636,18 @@ void AnimationTrackEditor::_update_scroll(double) {
void AnimationTrackEditor::_update_step(double p_new_step) {
undo_redo->create_action(TTR("Change Animation Step"));
- undo_redo->add_do_method(animation.ptr(), "set_step", p_new_step);
+ float step_value = p_new_step;
+ if (timeline->is_using_fps()) {
+ if (step_value != 0.0) {
+ step_value = 1.0 / step_value;
+ }
+ }
+ undo_redo->add_do_method(animation.ptr(), "set_step", step_value);
undo_redo->add_undo_method(animation.ptr(), "set_step", animation->get_step());
step->set_block_signals(true);
undo_redo->commit_action();
step->set_block_signals(false);
- emit_signal("animation_step_changed", p_new_step);
+ emit_signal("animation_step_changed", step_value);
}
void AnimationTrackEditor::_update_length(double p_new_len) {
@@ -4787,6 +4932,7 @@ void AnimationTrackEditor::_bind_methods() {
ClassDB::bind_method("_edit_menu_pressed", &AnimationTrackEditor::_edit_menu_pressed);
ClassDB::bind_method("_view_group_toggle", &AnimationTrackEditor::_view_group_toggle);
ClassDB::bind_method("_selection_changed", &AnimationTrackEditor::_selection_changed);
+ ClassDB::bind_method("_snap_mode_changed", &AnimationTrackEditor::_snap_mode_changed);
ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::REAL, "position"), PropertyInfo(Variant::BOOL, "drag")));
ADD_SIGNAL(MethodInfo("keying_changed"));
@@ -4875,7 +5021,7 @@ AnimationTrackEditor::AnimationTrackEditor() {
bottom_hb->add_child(memnew(VSeparator));
snap = memnew(ToolButton);
- snap->set_text(TTR("Snap (s): "));
+ snap->set_text(TTR("Snap: "));
bottom_hb->add_child(snap);
snap->set_disabled(true);
snap->set_toggle_mode(true);
@@ -4883,7 +5029,7 @@ AnimationTrackEditor::AnimationTrackEditor() {
step = memnew(EditorSpinSlider);
step->set_min(0);
- step->set_max(1000);
+ step->set_max(1000000);
step->set_step(0.01);
step->set_hide_slider(true);
step->set_custom_minimum_size(Size2(100, 0) * EDSCALE);
@@ -4892,6 +5038,13 @@ AnimationTrackEditor::AnimationTrackEditor() {
step->connect("value_changed", this, "_update_step");
step->set_read_only(true);
+ snap_mode = memnew(OptionButton);
+ snap_mode->add_item(TTR("Seconds"));
+ snap_mode->add_item(TTR("FPS"));
+ bottom_hb->add_child(snap_mode);
+ snap_mode->connect("item_selected", this, "_snap_mode_changed");
+ snap_mode->set_disabled(true);
+
bottom_hb->add_child(memnew(VSeparator));
zoom_icon = memnew(TextureRect);
diff --git a/editor/animation_track_editor.h b/editor/animation_track_editor.h
index 29ce4f189e..5ac5999b68 100644
--- a/editor/animation_track_editor.h
+++ b/editor/animation_track_editor.h
@@ -76,6 +76,7 @@ class AnimationTimelineEdit : public Range {
Rect2 hsize_rect;
bool editing;
+ bool use_fps;
bool panning_timeline;
float panning_timeline_from;
@@ -110,6 +111,9 @@ public:
void update_values();
+ void set_use_fps(bool p_use_fps);
+ bool is_using_fps() const;
+
void set_hscroll(HScrollBar *p_hscroll);
AnimationTimelineEdit();
@@ -303,7 +307,9 @@ class AnimationTrackEditor : public VBoxContainer {
EditorSpinSlider *step;
TextureRect *zoom_icon;
ToolButton *snap;
+ OptionButton *snap_mode;
+ void _snap_mode_changed(int p_mode);
Vector<AnimationTrackEdit *> track_edits;
Vector<AnimationTrackEditGroup *> groups;
@@ -328,6 +334,8 @@ class AnimationTrackEditor : public VBoxContainer {
void _new_track_node_selected(NodePath p_path);
void _new_track_property_selected(String p_name);
+ void _update_step_spinbox();
+
PropertySelector *prop_selector;
PropertySelector *method_selector;
SceneTreeDialog *pick_track;
@@ -484,6 +492,9 @@ public:
void update_keying();
bool has_keying() const;
+ Dictionary get_state() const;
+ void set_state(const Dictionary &p_state);
+
void cleanup();
void set_anim_pos(float p_pos);
diff --git a/editor/collada/collada.cpp b/editor/collada/collada.cpp
index 94e6d4ded0..94a37a3118 100644
--- a/editor/collada/collada.cpp
+++ b/editor/collada/collada.cpp
@@ -166,7 +166,8 @@ Transform Collada::Node::compute_transform(Collada &state) const {
}
} break;
- default: {}
+ default: {
+ }
}
xform = xform * xform_step;
diff --git a/editor/connections_dialog.cpp b/editor/connections_dialog.cpp
index f775a0a14b..685c5de76c 100644
--- a/editor/connections_dialog.cpp
+++ b/editor/connections_dialog.cpp
@@ -37,6 +37,25 @@
#include "scene/gui/label.h"
#include "scene/gui/popup_menu.h"
+static Node *_find_first_script(Node *p_root, Node *p_node) {
+ if (p_node != p_root && p_node->get_owner() != p_root) {
+ return NULL;
+ }
+ if (!p_node->get_script().is_null()) {
+ return p_node;
+ }
+
+ for (int i = 0; i < p_node->get_child_count(); i++) {
+
+ Node *ret = _find_first_script(p_root, p_node->get_child(i));
+ if (ret) {
+ return ret;
+ }
+ }
+
+ return NULL;
+}
+
class ConnectDialogBinds : public Object {
GDCLASS(ConnectDialogBinds, Object);
@@ -122,17 +141,8 @@ void ConnectDialog::_tree_node_selected() {
Node *current = tree->get_selected();
- if (!current) {
- make_callback->hide();
- return;
- }
-
- if (current->get_script().is_null())
- make_callback->hide();
- else
- make_callback->show();
-
- dst_path->set_text(source->get_path_to(current));
+ dst_path = source->get_path_to(current);
+ get_ok()->set_disabled(false);
}
/*
@@ -160,7 +170,9 @@ void ConnectDialog::_add_bind() {
case Variant::BASIS: value = Basis(); break;
case Variant::TRANSFORM: value = Transform(); break;
case Variant::COLOR: value = Color(); break;
- default: { ERR_FAIL(); } break;
+ default: {
+ ERR_FAIL();
+ } break;
}
ERR_FAIL_COND(value.get_type() == Variant::NIL);
@@ -193,6 +205,7 @@ void ConnectDialog::_notification(int p_what) {
void ConnectDialog::_bind_methods() {
+ ClassDB::bind_method("_advanced_pressed", &ConnectDialog::_advanced_pressed);
ClassDB::bind_method("_cancel", &ConnectDialog::_cancel_pressed);
ClassDB::bind_method("_tree_node_selected", &ConnectDialog::_tree_node_selected);
ClassDB::bind_method("_add_bind", &ConnectDialog::_add_bind);
@@ -213,7 +226,7 @@ StringName ConnectDialog::get_signal_name() const {
NodePath ConnectDialog::get_dst_path() const {
- return dst_path->get_text();
+ return dst_path;
}
void ConnectDialog::set_dst_node(Node *p_node) {
@@ -270,8 +283,13 @@ void ConnectDialog::init(Connection c, bool bEdit) {
tree->set_selected(NULL);
tree->set_marked(source, true);
- set_dst_node(static_cast<Node *>(c.target));
- set_dst_method(c.method);
+ if (c.target) {
+ get_ok()->set_disabled(false);
+ set_dst_node(static_cast<Node *>(c.target));
+ set_dst_method(c.method);
+ } else {
+ get_ok()->set_disabled(true);
+ }
bool bDeferred = (c.flags & CONNECT_DEFERRED) == CONNECT_DEFERRED;
bool bOneshot = (c.flags & CONNECT_ONESHOT) == CONNECT_ONESHOT;
@@ -286,6 +304,36 @@ void ConnectDialog::init(Connection c, bool bEdit) {
bEditMode = bEdit;
}
+void ConnectDialog::popup_dialog(const String &p_for_signal, bool p_advanced) {
+
+ advanced->set_pressed(p_advanced);
+ from_signal->set_text(p_for_signal);
+ error_label->add_color_override("font_color", get_color("error_color", "Editor"));
+
+ if (p_advanced) {
+
+ popup_centered(Size2(900, 500) * EDSCALE);
+ connect_to_label->set_text("Connect to Node:");
+ tree->set_connect_to_script_mode(false);
+ error_label->hide();
+ } else {
+ popup_centered(Size2(700, 500) * EDSCALE);
+ connect_to_label->set_text("Connect to Script:");
+ tree->set_connect_to_script_mode(true);
+
+ if (!_find_first_script(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root())) {
+ error_label->show();
+ } else {
+ error_label->hide();
+ }
+ }
+}
+
+void ConnectDialog::_advanced_pressed() {
+ vbc_right->set_visible(advanced->is_pressed());
+ popup_dialog(from_signal->get_text(), advanced->is_pressed());
+}
+
ConnectDialog::ConnectDialog() {
VBoxContainer *vbc = memnew(VBoxContainer);
@@ -299,15 +347,27 @@ ConnectDialog::ConnectDialog() {
main_hb->add_child(vbc_left);
vbc_left->set_h_size_flags(SIZE_EXPAND_FILL);
+ from_signal = memnew(LineEdit);
+ from_signal->set_editable(false);
+ vbc_left->add_margin_child(TTR("From Signal:"), from_signal);
+
tree = memnew(SceneTreeEditor(false));
tree->get_scene_tree()->connect("item_activated", this, "_ok");
tree->connect("node_selected", this, "_tree_node_selected");
+ tree->set_connect_to_script_mode(true);
- vbc_left->add_margin_child(TTR("Connect To Node:"), tree, true);
+ Node *mc = vbc_left->add_margin_child(TTR("Connect To Script:"), tree, true);
+ connect_to_label = Object::cast_to<Label>(vbc_left->get_child(mc->get_index() - 1));
- VBoxContainer *vbc_right = memnew(VBoxContainer);
+ error_label = memnew(Label);
+ error_label->set_text(TTR("Scene does not contain any script."));
+ vbc_left->add_child(error_label);
+ error_label->hide();
+
+ vbc_right = memnew(VBoxContainer);
main_hb->add_child(vbc_right);
vbc_right->set_h_size_flags(SIZE_EXPAND_FILL);
+ vbc_right->hide();
HBoxContainer *add_bind_hb = memnew(HBoxContainer);
@@ -345,16 +405,18 @@ ConnectDialog::ConnectDialog() {
vbc_right->add_margin_child(TTR("Extra Call Arguments:"), bind_editor, true);
- dst_path = memnew(LineEdit);
- vbc->add_margin_child(TTR("Path to Node:"), dst_path);
-
HBoxContainer *dstm_hb = memnew(HBoxContainer);
- vbc->add_margin_child("Method In Node:", dstm_hb);
+ vbc_left->add_margin_child("Method to Create:", dstm_hb);
dst_method = memnew(LineEdit);
dst_method->set_h_size_flags(SIZE_EXPAND_FILL);
dstm_hb->add_child(dst_method);
+ advanced = memnew(CheckBox);
+ dstm_hb->add_child(advanced);
+ advanced->set_text(TTR("Advanced.."));
+ advanced->connect("pressed", this, "_advanced_pressed");
+
/*
dst_method_list = memnew( MenuButton );
dst_method_list->set_text("List...");
@@ -366,19 +428,13 @@ ConnectDialog::ConnectDialog() {
dst_method_list->set_end( Point2( 15,39 ) );
*/
- make_callback = memnew(CheckButton);
- make_callback->set_toggle_mode(true);
- make_callback->set_pressed(EDITOR_DEF("text_editor/tools/create_signal_callbacks", true));
- make_callback->set_text(TTR("Make Function"));
- dstm_hb->add_child(make_callback);
-
deferred = memnew(CheckButton);
deferred->set_text(TTR("Deferred"));
- dstm_hb->add_child(deferred);
+ vbc_right->add_child(deferred);
oneshot = memnew(CheckButton);
oneshot->set_text(TTR("Oneshot"));
- dstm_hb->add_child(oneshot);
+ vbc_right->add_child(oneshot);
set_as_toplevel(true);
@@ -427,7 +483,8 @@ void ConnectionsDock::_make_or_edit_connection() {
bool oshot = connect_dialog->get_oneshot();
cToMake.flags = CONNECT_PERSIST | (defer ? CONNECT_DEFERRED : 0) | (oshot ? CONNECT_ONESHOT : 0);
- bool add_script_function = connect_dialog->get_make_callback();
+ //conditions to add function, must have a script and must have a method
+ bool add_script_function = !target->get_script().is_null() && !ClassDB::has_method(target->get_class(), cToMake.method);
PoolStringArray script_function_args;
if (add_script_function) {
// pick up args here before "it" is deleted by update_tree
@@ -566,6 +623,7 @@ bool ConnectionsDock::_is_item_signal(TreeItem &item) {
/*
Open connection dialog with TreeItem data to CREATE a brand-new connection.
*/
+
void ConnectionsDock::_open_connection_dialog(TreeItem &item) {
String signal = item.get_metadata(0).operator Dictionary()["name"];
@@ -588,6 +646,10 @@ void ConnectionsDock::_open_connection_dialog(TreeItem &item) {
}
Node *dst_node = selectedNode->get_owner() ? selectedNode->get_owner() : selectedNode;
+ if (!dst_node || dst_node->get_script().is_null()) {
+ dst_node = _find_first_script(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root());
+ }
+
StringName dst_method = "_on_" + midname + "_" + signal;
Connection c;
@@ -596,9 +658,10 @@ void ConnectionsDock::_open_connection_dialog(TreeItem &item) {
c.target = dst_node;
c.method = dst_method;
+ //connect_dialog->set_title(TTR("Connect Signal: ") + signalname);
+ connect_dialog->popup_dialog(signalname, false);
connect_dialog->init(c);
- connect_dialog->set_title(TTR("Connect Signal: ") + signalname);
- connect_dialog->popup_centered_ratio();
+ connect_dialog->set_title(TTR("Connect a Signal to a Method"));
}
/*
@@ -610,9 +673,9 @@ void ConnectionsDock::_open_connection_dialog(Connection cToEdit) {
Node *dst = static_cast<Node *>(cToEdit.target);
if (src && dst) {
- connect_dialog->init(cToEdit, true);
- connect_dialog->set_title(TTR("Edit Connection: ") + cToEdit.signal);
+ connect_dialog->set_title(TTR("Edit Connection:") + cToEdit.signal);
connect_dialog->popup_centered_ratio();
+ connect_dialog->init(cToEdit, true);
}
}
diff --git a/editor/connections_dialog.h b/editor/connections_dialog.h
index 0e7e172ebb..59fe6dacfe 100644
--- a/editor/connections_dialog.h
+++ b/editor/connections_dialog.h
@@ -53,12 +53,15 @@ class ConnectDialog : public ConfirmationDialog {
GDCLASS(ConnectDialog, ConfirmationDialog);
+ Label *connect_to_label;
+ LineEdit *from_signal;
Node *source;
StringName signal;
- LineEdit *dst_path;
LineEdit *dst_method;
ConnectDialogBinds *cdbinds;
bool bEditMode;
+ NodePath dst_path;
+ VBoxContainer *vbc_right;
SceneTreeEditor *tree;
ConfirmationDialog *error;
@@ -66,13 +69,16 @@ class ConnectDialog : public ConfirmationDialog {
OptionButton *type_list;
CheckButton *deferred;
CheckButton *oneshot;
- CheckButton *make_callback;
+ CheckBox *advanced;
+
+ Label *error_label;
void ok_pressed();
void _cancel_pressed();
void _tree_node_selected();
void _add_bind();
void _remove_bind();
+ void _advanced_pressed();
protected:
void _notification(int p_what);
@@ -87,13 +93,13 @@ public:
void set_dst_method(const StringName &p_method);
Vector<Variant> get_binds() const;
- bool get_make_callback() { return make_callback->is_visible() && make_callback->is_pressed(); }
bool get_deferred() const;
bool get_oneshot() const;
bool is_editing() const;
void init(Connection c, bool bEdit = false);
+ void popup_dialog(const String &p_for_signal, bool p_advanced);
ConnectDialog();
~ConnectDialog();
};
diff --git a/editor/create_dialog.cpp b/editor/create_dialog.cpp
index 364c5126d7..26bd651c2b 100644
--- a/editor/create_dialog.cpp
+++ b/editor/create_dialog.cpp
@@ -238,6 +238,26 @@ void CreateDialog::add_type(const String &p_type, HashMap<String, TreeItem *> &p
p_types[p_type] = item;
}
+bool CreateDialog::_is_class_disabled_by_feature_profile(const StringName &p_class) {
+
+ Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile();
+ if (profile.is_null()) {
+ return false;
+ }
+
+ StringName class_name = p_class;
+
+ while (class_name != StringName()) {
+
+ if (profile->is_class_disabled(class_name)) {
+ return true;
+ }
+ class_name = ClassDB::get_parent_class(class_name);
+ }
+
+ return false;
+}
+
void CreateDialog::_update_search() {
search_options->clear();
@@ -264,6 +284,10 @@ void CreateDialog::_update_search() {
for (List<StringName>::Element *I = type_list.front(); I; I = I->next()) {
String type = I->get();
+
+ if (_is_class_disabled_by_feature_profile(type)) {
+ continue;
+ }
bool cpp_type = ClassDB::class_exists(type);
if (base_type == "Node" && type.begins_with("Editor"))
diff --git a/editor/create_dialog.h b/editor/create_dialog.h
index 2636e2ddef..d859f7cbe4 100644
--- a/editor/create_dialog.h
+++ b/editor/create_dialog.h
@@ -86,6 +86,8 @@ class CreateDialog : public ConfirmationDialog {
bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
+ bool _is_class_disabled_by_feature_profile(const StringName &p_class);
+
protected:
void _notification(int p_what);
static void _bind_methods();
diff --git a/editor/doc/doc_dump.cpp b/editor/doc/doc_dump.cpp
index 1a68fe5bf2..6ccf0e26ea 100644
--- a/editor/doc/doc_dump.cpp
+++ b/editor/doc/doc_dump.cpp
@@ -199,7 +199,8 @@ void DocDump::dump(const String &p_file) {
case Variant::ARRAY:
case Variant::_RID:
- default: {}
+ default: {
+ }
}
_write_string(f, 3, "<argument index=\"" + itos(i) + "\" name=\"" + _escape_string(arginfo.name) + "\" type=\"" + type_name + "\" default=\"" + _escape_string(default_arg_text) + "\">");
@@ -227,7 +228,8 @@ void DocDump::dump(const String &p_file) {
}
break;
case PROPERTY_HINT_FILE: hint = "A file:"; break;
- default: {}
+ default: {
+ }
//case PROPERTY_HINT_RESOURCE_TYPE: hint="Type: "+arginfo.hint_string; break;
};
if (hint != "")
diff --git a/editor/editor_feature_profile.cpp b/editor/editor_feature_profile.cpp
new file mode 100644
index 0000000000..714df44e25
--- /dev/null
+++ b/editor/editor_feature_profile.cpp
@@ -0,0 +1,889 @@
+#include "editor_feature_profile.h"
+#include "core/io/json.h"
+#include "core/os/dir_access.h"
+#include "editor/editor_settings.h"
+#include "editor_node.h"
+#include "editor_scale.h"
+
+const char *EditorFeatureProfile::feature_names[FEATURE_MAX] = {
+ TTRC("3D Editor"),
+ TTRC("Script Editor"),
+ TTRC("Asset Library"),
+ TTRC("Scene Tree Editing"),
+ TTRC("Import Dock"),
+ TTRC("Node Dock"),
+ TTRC("Filesystem Dock")
+};
+
+const char *EditorFeatureProfile::feature_identifiers[FEATURE_MAX] = {
+ "3d",
+ "script",
+ "asset_lib",
+ "scene_tree",
+ "import_dock",
+ "node_dock",
+ "filesystem_dock"
+};
+
+void EditorFeatureProfile::set_disable_class(const StringName &p_class, bool p_disabled) {
+ if (p_disabled) {
+ disabled_classes.insert(p_class);
+ } else {
+ disabled_classes.erase(p_class);
+ }
+}
+
+bool EditorFeatureProfile::is_class_disabled(const StringName &p_class) const {
+ return disabled_classes.has(p_class);
+}
+
+void EditorFeatureProfile::set_disable_class_editor(const StringName &p_class, bool p_disabled) {
+ if (p_disabled) {
+ disabled_editors.insert(p_class);
+ } else {
+ disabled_editors.erase(p_class);
+ }
+}
+
+bool EditorFeatureProfile::is_class_editor_disabled(const StringName &p_class) const {
+ return disabled_editors.has(p_class);
+}
+
+void EditorFeatureProfile::set_disable_class_property(const StringName &p_class, const StringName &p_property, bool p_disabled) {
+
+ if (p_disabled) {
+ if (!disabled_properties.has(p_class)) {
+ disabled_properties[p_class] = Set<StringName>();
+ }
+
+ disabled_properties[p_class].insert(p_property);
+ } else {
+ ERR_FAIL_COND(!disabled_properties.has(p_class));
+ disabled_properties[p_class].erase(p_property);
+ if (disabled_properties[p_class].empty()) {
+ disabled_properties.erase(p_class);
+ }
+ }
+}
+bool EditorFeatureProfile::is_class_property_disabled(const StringName &p_class, const StringName &p_property) const {
+
+ if (!disabled_properties.has(p_class)) {
+ return false;
+ }
+
+ if (!disabled_properties[p_class].has(p_property)) {
+ return false;
+ }
+
+ return true;
+}
+
+bool EditorFeatureProfile::has_class_properties_disabled(const StringName &p_class) const {
+ return disabled_properties.has(p_class);
+}
+
+void EditorFeatureProfile::set_disable_feature(Feature p_feature, bool p_disable) {
+
+ ERR_FAIL_INDEX(p_feature, FEATURE_MAX);
+ features_disabled[p_feature] = p_disable;
+}
+bool EditorFeatureProfile::is_feature_disabled(Feature p_feature) const {
+ ERR_FAIL_INDEX_V(p_feature, FEATURE_MAX, false);
+ return features_disabled[p_feature];
+}
+
+String EditorFeatureProfile::get_feature_name(Feature p_feature) {
+ ERR_FAIL_INDEX_V(p_feature, FEATURE_MAX, String());
+ return feature_names[p_feature];
+}
+
+Error EditorFeatureProfile::save_to_file(const String &p_path) {
+
+ Dictionary json;
+ json["type"] = "feature_profile";
+ Array dis_classes;
+ for (Set<StringName>::Element *E = disabled_classes.front(); E; E = E->next()) {
+ dis_classes.push_back(String(E->get()));
+ }
+ dis_classes.sort();
+ json["disabled_classes"] = dis_classes;
+
+ Array dis_editors;
+ for (Set<StringName>::Element *E = disabled_editors.front(); E; E = E->next()) {
+ dis_editors.push_back(String(E->get()));
+ }
+ dis_editors.sort();
+ json["disabled_editors"] = dis_editors;
+
+ Array dis_props;
+
+ for (Map<StringName, Set<StringName> >::Element *E = disabled_properties.front(); E; E = E->next()) {
+ for (Set<StringName>::Element *F = E->get().front(); F; F = F->next()) {
+ dis_props.push_back(String(E->key()) + ":" + String(F->get()));
+ }
+ }
+
+ json["disabled_properties"] = dis_props;
+
+ Array dis_features;
+ for (int i = 0; i < FEATURE_MAX; i++) {
+ if (features_disabled[i]) {
+ dis_features.push_back(feature_identifiers[i]);
+ }
+ }
+
+ json["disabled_features"] = dis_features;
+
+ FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE);
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
+
+ String text = JSON::print(json, "\t");
+ f->store_string(text);
+ f->close();
+ return OK;
+}
+
+Error EditorFeatureProfile::load_from_file(const String &p_path) {
+
+ Error err;
+ String text = FileAccess::get_file_as_string(p_path, &err);
+ if (err != OK) {
+ return err;
+ }
+
+ String err_str;
+ int err_line;
+ Variant v;
+ err = JSON::parse(text, v, err_str, err_line);
+ if (err != OK) {
+ ERR_PRINTS("Error parsing '" + p_path + "' on line " + itos(err_line) + ": " + err_str);
+ return ERR_PARSE_ERROR;
+ }
+
+ Dictionary json = v;
+
+ if (!json.has("type") || String(json["type"]) != "feature_profile") {
+ ERR_PRINTS("Error parsing '" + p_path + "', it's not a feature profile.");
+ return ERR_PARSE_ERROR;
+ }
+
+ disabled_classes.clear();
+
+ if (json.has("disabled_classes")) {
+ Array disabled_classes_arr = json["disabled_classes"];
+ for (int i = 0; i < disabled_classes_arr.size(); i++) {
+ disabled_classes.insert(disabled_classes_arr[i]);
+ }
+ }
+
+ disabled_editors.clear();
+
+ if (json.has("disabled_editors")) {
+ Array disabled_editors_arr = json["disabled_editors"];
+ for (int i = 0; i < disabled_editors_arr.size(); i++) {
+ disabled_editors.insert(disabled_editors_arr[i]);
+ }
+ }
+
+ disabled_properties.clear();
+
+ if (json.has("disabled_properties")) {
+ Array disabled_properties_arr = json["disabled_properties"];
+ for (int i = 0; i < disabled_properties_arr.size(); i++) {
+ String s = disabled_properties_arr[i];
+ set_disable_class_property(s.get_slice(":", 0), s.get_slice(":", 1), true);
+ }
+ }
+
+ if (json.has("disabled_features")) {
+
+ Array disabled_features_arr = json["disabled_features"];
+ for (int i = 0; i < FEATURE_MAX; i++) {
+ bool found = false;
+ String f = feature_identifiers[i];
+ for (int j = 0; j < disabled_features_arr.size(); j++) {
+ String fd = disabled_features_arr[j];
+ if (fd == f) {
+ found = true;
+ break;
+ }
+ }
+
+ features_disabled[i] = found;
+ }
+ }
+
+ return OK;
+}
+
+void EditorFeatureProfile::_bind_methods() {
+
+ ClassDB::bind_method(D_METHOD("set_disable_class", "class_name", "disable"), &EditorFeatureProfile::set_disable_class);
+ ClassDB::bind_method(D_METHOD("is_class_disabled", "class_name"), &EditorFeatureProfile::is_class_disabled);
+
+ ClassDB::bind_method(D_METHOD("set_disable_class_editor", "class_name", "disable"), &EditorFeatureProfile::set_disable_class_editor);
+ ClassDB::bind_method(D_METHOD("is_class_editor_disabled", "class_name"), &EditorFeatureProfile::is_class_editor_disabled);
+
+ ClassDB::bind_method(D_METHOD("set_disable_class_property", "class_name", "property"), &EditorFeatureProfile::set_disable_class_property);
+ ClassDB::bind_method(D_METHOD("is_class_property_disabled", "class_name"), &EditorFeatureProfile::is_class_property_disabled);
+
+ ClassDB::bind_method(D_METHOD("set_disable_feature", "feature", "disable"), &EditorFeatureProfile::set_disable_feature);
+ ClassDB::bind_method(D_METHOD("is_feature_disabled", "feature"), &EditorFeatureProfile::is_feature_disabled);
+
+ ClassDB::bind_method(D_METHOD("get_feature_name", "feature"), &EditorFeatureProfile::_get_feature_name);
+
+ ClassDB::bind_method(D_METHOD("save_to_file", "path"), &EditorFeatureProfile::save_to_file);
+ ClassDB::bind_method(D_METHOD("load_from_file", "path"), &EditorFeatureProfile::load_from_file);
+
+ BIND_ENUM_CONSTANT(FEATURE_3D);
+ BIND_ENUM_CONSTANT(FEATURE_SCRIPT);
+ BIND_ENUM_CONSTANT(FEATURE_ASSET_LIB);
+ BIND_ENUM_CONSTANT(FEATURE_SCENE_TREE);
+ BIND_ENUM_CONSTANT(FEATURE_IMPORT_DOCK);
+ BIND_ENUM_CONSTANT(FEATURE_NODE_DOCK);
+ BIND_ENUM_CONSTANT(FEATURE_FILESYSTEM_DOCK);
+ BIND_ENUM_CONSTANT(FEATURE_MAX);
+}
+
+EditorFeatureProfile::EditorFeatureProfile() {
+
+ for (int i = 0; i < FEATURE_MAX; i++) {
+ features_disabled[i] = false;
+ }
+}
+
+//////////////////////////
+
+void EditorFeatureProfileManager::_notification(int p_what) {
+ if (p_what == NOTIFICATION_READY) {
+
+ current_profile = EDITOR_GET("_default_feature_profile");
+ if (current_profile != String()) {
+ current.instance();
+ Error err = current->load_from_file(EditorSettings::get_singleton()->get_feature_profiles_dir().plus_file(current_profile + ".profile"));
+ if (err != OK) {
+ ERR_PRINTS("Error loading default feature profile: " + current_profile);
+ current_profile = String();
+ current.unref();
+ }
+ }
+ _update_profile_list(current_profile);
+ }
+}
+
+String EditorFeatureProfileManager::_get_selected_profile() {
+ int idx = profile_list->get_selected();
+ if (idx < 0) {
+ return String();
+ }
+
+ return profile_list->get_item_metadata(idx);
+}
+
+void EditorFeatureProfileManager::_update_profile_list(const String &p_select_profile) {
+
+ String selected_profile;
+ if (p_select_profile == String()) { //default, keep
+ if (profile_list->get_selected() >= 0) {
+ selected_profile = profile_list->get_item_metadata(profile_list->get_selected());
+ if (!FileAccess::exists(EditorSettings::get_singleton()->get_feature_profiles_dir().plus_file(selected_profile + ".profile"))) {
+ selected_profile = String(); //does not exist
+ }
+ }
+ } else {
+ selected_profile = p_select_profile;
+ }
+
+ Vector<String> profiles;
+ DirAccessRef d = DirAccess::open(EditorSettings::get_singleton()->get_feature_profiles_dir());
+ ERR_FAIL_COND(!d);
+ d->list_dir_begin();
+ while (true) {
+ String f = d->get_next();
+ if (f == String()) {
+ break;
+ }
+
+ if (!d->current_is_dir()) {
+ int last_pos = f.find_last(".profile");
+ if (last_pos != -1) {
+ profiles.push_back(f.substr(0, last_pos));
+ }
+ }
+ }
+
+ profiles.sort();
+
+ profile_list->clear();
+
+ for (int i = 0; i < profiles.size(); i++) {
+ String name = profiles[i];
+
+ if (i == 0 && selected_profile == String()) {
+ selected_profile = name;
+ }
+
+ if (name == current_profile) {
+ name += " (current)";
+ }
+ profile_list->add_item(name);
+ int index = profile_list->get_item_count() - 1;
+ profile_list->set_item_metadata(index, profiles[i]);
+ if (profiles[i] == selected_profile) {
+ profile_list->select(index);
+ }
+ }
+
+ profile_actions[PROFILE_CLEAR]->set_disabled(current_profile == String());
+ profile_actions[PROFILE_ERASE]->set_disabled(selected_profile == String());
+ profile_actions[PROFILE_EXPORT]->set_disabled(selected_profile == String());
+ profile_actions[PROFILE_SET]->set_disabled(selected_profile == String());
+
+ current_profile_name->set_text(current_profile);
+
+ _update_selected_profile();
+}
+
+void EditorFeatureProfileManager::_profile_action(int p_action) {
+
+ switch (p_action) {
+ case PROFILE_CLEAR: {
+ EditorSettings::get_singleton()->set("_default_feature_profile", "");
+ EditorSettings::get_singleton()->save();
+ current_profile = "";
+ current.unref();
+ _update_profile_list();
+ } break;
+ case PROFILE_SET: {
+
+ String selected = _get_selected_profile();
+ ERR_FAIL_COND(selected == String());
+ if (selected == current_profile) {
+ return; //nothing to do here
+ }
+ EditorSettings::get_singleton()->set("_default_feature_profile", selected);
+ EditorSettings::get_singleton()->save();
+ current_profile = selected;
+ current = edited;
+
+ _update_profile_list();
+
+ } break;
+ case PROFILE_IMPORT: {
+
+ import_profiles->popup_centered_ratio();
+ } break;
+ case PROFILE_EXPORT: {
+
+ export_profile->popup_centered_ratio();
+ export_profile->set_current_file(_get_selected_profile() + ".profile");
+ } break;
+ case PROFILE_NEW: {
+
+ new_profile_dialog->popup_centered_minsize();
+ new_profile_name->clear();
+ new_profile_name->grab_focus();
+ } break;
+ case PROFILE_ERASE: {
+ String selected = _get_selected_profile();
+ ERR_FAIL_COND(selected == String());
+
+ erase_profile_dialog->set_text(vformat(TTR("Erase profile '%s'? (no undo)"), selected));
+ erase_profile_dialog->popup_centered_minsize();
+ } break;
+ }
+}
+
+void EditorFeatureProfileManager::_erase_selected_profile() {
+
+ String selected = _get_selected_profile();
+ ERR_FAIL_COND(selected == String());
+ DirAccessRef da = DirAccess::open(EditorSettings::get_singleton()->get_feature_profiles_dir());
+ ERR_FAIL_COND(!da);
+ da->remove(selected + ".profile");
+ if (selected == current_profile) {
+ _profile_action(PROFILE_CLEAR);
+ } else {
+ _update_profile_list();
+ }
+}
+
+void EditorFeatureProfileManager::_create_new_profile() {
+ String name = new_profile_name->get_text().strip_edges();
+ if (!name.is_valid_filename() || name.find(".") != -1) {
+ EditorNode::get_singleton()->show_warning(TTR("Profile must be a valid filename and must not contain '.'"));
+ return;
+ }
+ String file = EditorSettings::get_singleton()->get_feature_profiles_dir().plus_file(name + ".profile");
+ if (FileAccess::exists(file)) {
+ EditorNode::get_singleton()->show_warning(TTR("Profile with this name already exists."));
+ return;
+ }
+
+ Ref<EditorFeatureProfile> new_profile;
+ new_profile.instance();
+ new_profile->save_to_file(file);
+
+ _update_profile_list(name);
+}
+
+void EditorFeatureProfileManager::_profile_selected(int p_what) {
+
+ _update_selected_profile();
+}
+
+void EditorFeatureProfileManager::_fill_classes_from(TreeItem *p_parent, const String &p_class, const String &p_selected) {
+
+ TreeItem *class_item = class_list->create_item(p_parent);
+ class_item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ class_item->set_icon(0, EditorNode::get_singleton()->get_class_icon(p_class, "Node"));
+ String text = p_class;
+
+ bool disabled = edited->is_class_disabled(p_class);
+ bool disabled_editor = edited->is_class_editor_disabled(p_class);
+ bool disabled_properties = edited->has_class_properties_disabled(p_class);
+ if (disabled) {
+ class_item->set_custom_color(0, get_color("disabled_font_color", "Editor"));
+ } else if (disabled_editor && disabled_properties) {
+ text += " " + TTR("(Editor Disabled, Properties Disabled)");
+ } else if (disabled_properties) {
+ text += " " + TTR("(Properties Disabled)");
+ } else if (disabled_editor) {
+ text += " " + TTR("(Editor Disabled)");
+ }
+ class_item->set_text(0, text);
+ class_item->set_editable(0, true);
+ class_item->set_selectable(0, true);
+ class_item->set_metadata(0, p_class);
+
+ if (p_class == p_selected) {
+ class_item->select(0);
+ }
+ if (disabled) {
+ //class disabled, do nothing else (do not show further)
+ return;
+ }
+
+ class_item->set_checked(0, true); // if its not disabled, its checked
+
+ List<StringName> child_classes;
+ ClassDB::get_direct_inheriters_from_class(p_class, &child_classes);
+ child_classes.sort_custom<StringName::AlphCompare>();
+
+ for (List<StringName>::Element *E = child_classes.front(); E; E = E->next()) {
+ String name = E->get();
+ if (name.begins_with("Editor") || ClassDB::get_api_type(name) != ClassDB::API_CORE) {
+ continue;
+ }
+ _fill_classes_from(class_item, name, p_selected);
+ }
+}
+
+void EditorFeatureProfileManager::_class_list_item_selected() {
+
+ if (updating_features)
+ return;
+
+ property_list->clear();
+
+ TreeItem *item = class_list->get_selected();
+ if (!item) {
+ return;
+ }
+
+ Variant md = item->get_metadata(0);
+ if (md.get_type() != Variant::STRING) {
+ return;
+ }
+
+ String class_name = md;
+
+ if (edited->is_class_disabled(class_name)) {
+ return;
+ }
+
+ updating_features = true;
+ TreeItem *root = property_list->create_item();
+ TreeItem *options = property_list->create_item(root);
+ options->set_text(0, TTR("Class Options:"));
+
+ {
+ TreeItem *option = property_list->create_item(options);
+ option->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ option->set_editable(0, true);
+ option->set_selectable(0, true);
+ option->set_checked(0, !edited->is_class_editor_disabled(class_name));
+ option->set_text(0, TTR("Enable Contextual Editor"));
+ option->set_metadata(0, CLASS_OPTION_DISABLE_EDITOR);
+ }
+
+ TreeItem *properties = property_list->create_item(root);
+ properties->set_text(0, TTR("Enabled Properties:"));
+
+ List<PropertyInfo> props;
+
+ ClassDB::get_property_list(class_name, &props, true);
+
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
+
+ String name = E->get().name;
+ if (!(E->get().usage & PROPERTY_USAGE_EDITOR))
+ continue;
+ TreeItem *property = property_list->create_item(properties);
+ property->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ property->set_editable(0, true);
+ property->set_selectable(0, true);
+ property->set_checked(0, !edited->is_class_property_disabled(class_name, name));
+ property->set_text(0, name.capitalize());
+ property->set_metadata(0, name);
+ String icon_type = Variant::get_type_name(E->get().type);
+ property->set_icon(0, EditorNode::get_singleton()->get_class_icon(icon_type));
+ }
+
+ updating_features = false;
+}
+
+void EditorFeatureProfileManager::_class_list_item_edited() {
+
+ if (updating_features)
+ return;
+
+ TreeItem *item = class_list->get_edited();
+ if (!item) {
+ return;
+ }
+
+ bool checked = item->is_checked(0);
+
+ Variant md = item->get_metadata(0);
+ if (md.get_type() == Variant::STRING) {
+ String class_selected = md;
+ edited->set_disable_class(class_selected, !checked);
+ _save_and_update();
+ _update_selected_profile();
+ } else if (md.get_type() == Variant::INT) {
+ int feature_selected = md;
+ edited->set_disable_feature(EditorFeatureProfile::Feature(feature_selected), !checked);
+ _save_and_update();
+ }
+}
+
+void EditorFeatureProfileManager::_property_item_edited() {
+ if (updating_features)
+ return;
+
+ TreeItem *class_item = class_list->get_selected();
+ if (!class_item) {
+ return;
+ }
+
+ Variant md = class_item->get_metadata(0);
+ if (md.get_type() != Variant::STRING) {
+ return;
+ }
+
+ String class_name = md;
+
+ TreeItem *item = property_list->get_edited();
+ if (!item) {
+ return;
+ }
+ bool checked = item->is_checked(0);
+
+ md = item->get_metadata(0);
+ if (md.get_type() == Variant::STRING) {
+ String property_selected = md;
+ edited->set_disable_class_property(class_name, property_selected, !checked);
+ _save_and_update();
+ _update_selected_profile();
+ } else if (md.get_type() == Variant::INT) {
+ int feature_selected = md;
+ switch (feature_selected) {
+ case CLASS_OPTION_DISABLE_EDITOR: {
+ edited->set_disable_class_editor(class_name, !checked);
+ _save_and_update();
+ _update_selected_profile();
+ } break;
+ }
+ }
+}
+
+void EditorFeatureProfileManager::_update_selected_profile() {
+
+ String class_selected;
+ int feature_selected = -1;
+
+ if (class_list->get_selected()) {
+ Variant md = class_list->get_selected()->get_metadata(0);
+ if (md.get_type() == Variant::STRING) {
+ class_selected = md;
+ } else if (md.get_type() == Variant::INT) {
+ feature_selected = md;
+ }
+ }
+
+ class_list->clear();
+
+ String profile = _get_selected_profile();
+ if (profile == String()) { //nothing selected, nothing edited
+ property_list->clear();
+ edited.unref();
+ return;
+ }
+
+ if (profile == current_profile) {
+ edited = current; //reuse current profile (which is what editor uses)
+ ERR_FAIL_COND(current.is_null()); //nothing selected, current should never be null
+ } else {
+ //reload edited, if different from current
+ edited.instance();
+ Error err = edited->load_from_file(EditorSettings::get_singleton()->get_feature_profiles_dir().plus_file(profile + ".profile"));
+ ERR_FAIL_COND(err != OK);
+ }
+
+ updating_features = true;
+
+ TreeItem *root = class_list->create_item();
+
+ TreeItem *features = class_list->create_item(root);
+ features->set_text(0, TTR("Enabled Features:"));
+ for (int i = 0; i < EditorFeatureProfile::FEATURE_MAX; i++) {
+
+ TreeItem *feature = class_list->create_item(features);
+ feature->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ feature->set_text(0, TTRGET(EditorFeatureProfile::get_feature_name(EditorFeatureProfile::Feature(i))));
+ feature->set_selectable(0, true);
+ feature->set_editable(0, true);
+ feature->set_metadata(0, i);
+ if (!edited->is_feature_disabled(EditorFeatureProfile::Feature(i))) {
+ feature->set_checked(0, true);
+ }
+
+ if (i == feature_selected) {
+ feature->select(0);
+ }
+ }
+
+ TreeItem *classes = class_list->create_item(root);
+ classes->set_text(0, TTR("Enabled Classes:"));
+
+ _fill_classes_from(classes, "Node", class_selected);
+ _fill_classes_from(classes, "Resource", class_selected);
+
+ updating_features = false;
+
+ _class_list_item_selected();
+}
+
+void EditorFeatureProfileManager::_import_profiles(const Vector<String> &p_paths) {
+
+ //test it first
+ for (int i = 0; i < p_paths.size(); i++) {
+ Ref<EditorFeatureProfile> profile;
+ profile.instance();
+ Error err = profile->load_from_file(p_paths[i]);
+ String basefile = p_paths[i].get_file();
+ if (err != OK) {
+ EditorNode::get_singleton()->show_warning(vformat(TTR("File '%s' format is invalid, import aborted."), basefile));
+ return;
+ }
+
+ String dst_file = EditorSettings::get_singleton()->get_feature_profiles_dir().plus_file(basefile);
+
+ if (FileAccess::exists(dst_file)) {
+ EditorNode::get_singleton()->show_warning(vformat(TTR("Profile '%s' already exists. Remote it first before importing, import aborted."), basefile.get_basename()));
+ return;
+ }
+ }
+
+ //do it second
+ for (int i = 0; i < p_paths.size(); i++) {
+ Ref<EditorFeatureProfile> profile;
+ profile.instance();
+ Error err = profile->load_from_file(p_paths[i]);
+ ERR_CONTINUE(err != OK);
+ String basefile = p_paths[i].get_file();
+ String dst_file = EditorSettings::get_singleton()->get_feature_profiles_dir().plus_file(basefile);
+ profile->save_to_file(dst_file);
+ }
+
+ _update_profile_list();
+}
+
+void EditorFeatureProfileManager::_export_profile(const String &p_path) {
+
+ ERR_FAIL_COND(edited.is_null());
+ Error err = edited->save_to_file(p_path);
+ if (err != OK) {
+ EditorNode::get_singleton()->show_warning(vformat(TTR("Error saving profile to path: '%s'."), p_path));
+ }
+}
+
+void EditorFeatureProfileManager::_save_and_update() {
+
+ String edited_path = _get_selected_profile();
+ ERR_FAIL_COND(edited_path == String());
+ ERR_FAIL_COND(edited.is_null());
+
+ edited->save_to_file(EditorSettings::get_singleton()->get_feature_profiles_dir().plus_file(edited_path + ".profile"));
+
+ if (edited == current) {
+ update_timer->start();
+ }
+}
+
+void EditorFeatureProfileManager::_emit_current_profile_changed() {
+
+ emit_signal("current_feature_profile_changed");
+}
+
+void EditorFeatureProfileManager::notify_changed() {
+ _emit_current_profile_changed();
+}
+
+Ref<EditorFeatureProfile> EditorFeatureProfileManager::get_current_profile() {
+ return current;
+}
+
+EditorFeatureProfileManager *EditorFeatureProfileManager::singleton = NULL;
+
+void EditorFeatureProfileManager::_bind_methods() {
+
+ ClassDB::bind_method("_update_selected_profile", &EditorFeatureProfileManager::_update_selected_profile);
+ ClassDB::bind_method("_profile_action", &EditorFeatureProfileManager::_profile_action);
+ ClassDB::bind_method("_create_new_profile", &EditorFeatureProfileManager::_create_new_profile);
+ ClassDB::bind_method("_profile_selected", &EditorFeatureProfileManager::_profile_selected);
+ ClassDB::bind_method("_erase_selected_profile", &EditorFeatureProfileManager::_erase_selected_profile);
+ ClassDB::bind_method("_import_profiles", &EditorFeatureProfileManager::_import_profiles);
+ ClassDB::bind_method("_export_profile", &EditorFeatureProfileManager::_export_profile);
+ ClassDB::bind_method("_class_list_item_selected", &EditorFeatureProfileManager::_class_list_item_selected);
+ ClassDB::bind_method("_class_list_item_edited", &EditorFeatureProfileManager::_class_list_item_edited);
+ ClassDB::bind_method("_property_item_edited", &EditorFeatureProfileManager::_property_item_edited);
+ ClassDB::bind_method("_emit_current_profile_changed", &EditorFeatureProfileManager::_emit_current_profile_changed);
+
+ ADD_SIGNAL(MethodInfo("current_feature_profile_changed"));
+}
+
+EditorFeatureProfileManager::EditorFeatureProfileManager() {
+
+ VBoxContainer *main_vbc = memnew(VBoxContainer);
+ add_child(main_vbc);
+
+ HBoxContainer *name_hbc = memnew(HBoxContainer);
+ current_profile_name = memnew(LineEdit);
+ name_hbc->add_child(current_profile_name);
+ current_profile_name->set_editable(false);
+ current_profile_name->set_h_size_flags(SIZE_EXPAND_FILL);
+ profile_actions[PROFILE_CLEAR] = memnew(Button(TTR("Unset")));
+ name_hbc->add_child(profile_actions[PROFILE_CLEAR]);
+ profile_actions[PROFILE_CLEAR]->set_disabled(true);
+ profile_actions[PROFILE_CLEAR]->connect("pressed", this, "_profile_action", varray(PROFILE_CLEAR));
+
+ main_vbc->add_margin_child(TTR("Current Profile"), name_hbc);
+
+ HBoxContainer *profiles_hbc = memnew(HBoxContainer);
+ profile_list = memnew(OptionButton);
+ profile_list->set_h_size_flags(SIZE_EXPAND_FILL);
+ profiles_hbc->add_child(profile_list);
+ profile_list->connect("item_selected", this, "_profile_selected");
+
+ profile_actions[PROFILE_SET] = memnew(Button(TTR("Make Current")));
+ profiles_hbc->add_child(profile_actions[PROFILE_SET]);
+ profile_actions[PROFILE_SET]->set_disabled(true);
+ profile_actions[PROFILE_SET]->connect("pressed", this, "_profile_action", varray(PROFILE_SET));
+
+ profile_actions[PROFILE_ERASE] = memnew(Button(TTR("Remove")));
+ profiles_hbc->add_child(profile_actions[PROFILE_ERASE]);
+ profile_actions[PROFILE_ERASE]->set_disabled(true);
+ profile_actions[PROFILE_ERASE]->connect("pressed", this, "_profile_action", varray(PROFILE_ERASE));
+
+ profiles_hbc->add_child(memnew(VSeparator));
+
+ profile_actions[PROFILE_NEW] = memnew(Button(TTR("New")));
+ profiles_hbc->add_child(profile_actions[PROFILE_NEW]);
+ profile_actions[PROFILE_NEW]->connect("pressed", this, "_profile_action", varray(PROFILE_NEW));
+
+ profiles_hbc->add_child(memnew(VSeparator));
+
+ profile_actions[PROFILE_IMPORT] = memnew(Button(TTR("Import")));
+ profiles_hbc->add_child(profile_actions[PROFILE_IMPORT]);
+ profile_actions[PROFILE_IMPORT]->connect("pressed", this, "_profile_action", varray(PROFILE_IMPORT));
+
+ profile_actions[PROFILE_EXPORT] = memnew(Button(TTR("Export")));
+ profiles_hbc->add_child(profile_actions[PROFILE_EXPORT]);
+ profile_actions[PROFILE_EXPORT]->set_disabled(true);
+ profile_actions[PROFILE_EXPORT]->connect("pressed", this, "_profile_action", varray(PROFILE_EXPORT));
+
+ main_vbc->add_margin_child(TTR("Available Profiles"), profiles_hbc);
+
+ h_split = memnew(HSplitContainer);
+ h_split->set_v_size_flags(SIZE_EXPAND_FILL);
+ main_vbc->add_child(h_split);
+
+ VBoxContainer *class_list_vbc = memnew(VBoxContainer);
+ h_split->add_child(class_list_vbc);
+ class_list_vbc->set_h_size_flags(SIZE_EXPAND_FILL);
+
+ class_list = memnew(Tree);
+ class_list_vbc->add_margin_child(TTR("Enabled Classes"), class_list, true);
+ class_list->set_hide_root(true);
+ class_list->set_hide_folding(true);
+ class_list->set_edit_checkbox_cell_only_when_checkbox_is_pressed(true);
+ class_list->connect("cell_selected", this, "_class_list_item_selected");
+ class_list->connect("item_edited", this, "_class_list_item_edited", varray(), CONNECT_DEFERRED);
+
+ VBoxContainer *property_list_vbc = memnew(VBoxContainer);
+ h_split->add_child(property_list_vbc);
+ property_list_vbc->set_h_size_flags(SIZE_EXPAND_FILL);
+
+ property_list = memnew(Tree);
+ property_list_vbc->add_margin_child(TTR("Class Options"), property_list, true);
+ property_list->set_hide_root(true);
+ property_list->set_hide_folding(true);
+ property_list->set_edit_checkbox_cell_only_when_checkbox_is_pressed(true);
+ property_list->connect("item_edited", this, "_property_item_edited", varray(), CONNECT_DEFERRED);
+
+ new_profile_dialog = memnew(ConfirmationDialog);
+ new_profile_dialog->set_title(TTR("New profile name:"));
+ new_profile_name = memnew(LineEdit);
+ new_profile_dialog->add_child(new_profile_name);
+ new_profile_name->set_custom_minimum_size(Size2(300 * EDSCALE, 1));
+ add_child(new_profile_dialog);
+ new_profile_dialog->connect("confirmed", this, "_create_new_profile");
+ new_profile_dialog->register_text_enter(new_profile_name);
+ new_profile_dialog->get_ok()->set_text(TTR("Create"));
+
+ erase_profile_dialog = memnew(ConfirmationDialog);
+ add_child(erase_profile_dialog);
+ erase_profile_dialog->set_title(TTR("Erase Profile"));
+ erase_profile_dialog->connect("confirmed", this, "_erase_selected_profile");
+
+ import_profiles = memnew(EditorFileDialog);
+ add_child(import_profiles);
+ import_profiles->set_mode(EditorFileDialog::MODE_OPEN_FILES);
+ import_profiles->add_filter("*.profile; Godot Feature Profile");
+ import_profiles->connect("files_selected", this, "_import_profiles");
+ import_profiles->set_title(TTR("Import Profile(s)"));
+ import_profiles->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
+
+ export_profile = memnew(EditorFileDialog);
+ add_child(export_profile);
+ export_profile->set_mode(EditorFileDialog::MODE_SAVE_FILE);
+ export_profile->add_filter("*.profile; Godot Feature Profile");
+ export_profile->connect("file_selected", this, "_export_profile");
+ export_profile->set_title(TTR("Export Profile"));
+ export_profile->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
+
+ set_title(TTR("Manage Editor Feature Profiles"));
+ EDITOR_DEF("_default_feature_profile", "");
+
+ update_timer = memnew(Timer);
+ update_timer->set_wait_time(1); //wait a second before updating editor
+ add_child(update_timer);
+ update_timer->connect("timeout", this, "_emit_current_profile_changed");
+ update_timer->set_one_shot(true);
+
+ updating_features = false;
+
+ singleton = this;
+}
diff --git a/editor/editor_feature_profile.h b/editor/editor_feature_profile.h
new file mode 100644
index 0000000000..b7c2ebc1b2
--- /dev/null
+++ b/editor/editor_feature_profile.h
@@ -0,0 +1,142 @@
+#ifndef EDITOR_FEATURE_PROFILE_H
+#define EDITOR_FEATURE_PROFILE_H
+
+#include "core/os/file_access.h"
+#include "core/reference.h"
+#include "editor/editor_file_dialog.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/option_button.h"
+#include "scene/gui/separator.h"
+#include "scene/gui/split_container.h"
+#include "scene/gui/tree.h"
+
+class EditorFeatureProfile : public Reference {
+ GDCLASS(EditorFeatureProfile, Reference);
+
+public:
+ enum Feature {
+ FEATURE_3D,
+ FEATURE_SCRIPT,
+ FEATURE_ASSET_LIB,
+ FEATURE_SCENE_TREE,
+ FEATURE_IMPORT_DOCK,
+ FEATURE_NODE_DOCK,
+ FEATURE_FILESYSTEM_DOCK,
+ FEATURE_MAX
+ };
+
+private:
+ Set<StringName> disabled_classes;
+ Set<StringName> disabled_editors;
+ Map<StringName, Set<StringName> > disabled_properties;
+
+ bool features_disabled[FEATURE_MAX];
+ static const char *feature_names[FEATURE_MAX];
+ static const char *feature_identifiers[FEATURE_MAX];
+
+ String _get_feature_name(Feature p_feature) { return get_feature_name(p_feature); }
+
+protected:
+ static void _bind_methods();
+
+public:
+ void set_disable_class(const StringName &p_class, bool p_disabled);
+ bool is_class_disabled(const StringName &p_class) const;
+
+ void set_disable_class_editor(const StringName &p_class, bool p_disabled);
+ bool is_class_editor_disabled(const StringName &p_class) const;
+
+ void set_disable_class_property(const StringName &p_class, const StringName &p_property, bool p_disabled);
+ bool is_class_property_disabled(const StringName &p_class, const StringName &p_property) const;
+ bool has_class_properties_disabled(const StringName &p_class) const;
+
+ void set_disable_feature(Feature p_feature, bool p_disable);
+ bool is_feature_disabled(Feature p_feature) const;
+
+ Error save_to_file(const String &p_path);
+ Error load_from_file(const String &p_path);
+
+ static String get_feature_name(Feature p_feature);
+
+ EditorFeatureProfile();
+};
+
+VARIANT_ENUM_CAST(EditorFeatureProfile::Feature)
+
+class EditorFeatureProfileManager : public AcceptDialog {
+
+ GDCLASS(EditorFeatureProfileManager, AcceptDialog);
+
+ enum Action {
+ PROFILE_CLEAR,
+ PROFILE_SET,
+ PROFILE_IMPORT,
+ PROFILE_EXPORT,
+ PROFILE_NEW,
+ PROFILE_ERASE,
+ PROFILE_MAX
+ };
+
+ enum ClassOptions {
+ CLASS_OPTION_DISABLE_EDITOR
+ };
+
+ ConfirmationDialog *erase_profile_dialog;
+ ConfirmationDialog *new_profile_dialog;
+ LineEdit *new_profile_name;
+
+ LineEdit *current_profile_name;
+ OptionButton *profile_list;
+ Button *profile_actions[PROFILE_MAX];
+
+ HSplitContainer *h_split;
+
+ Tree *class_list;
+ Tree *property_list;
+
+ EditorFileDialog *import_profiles;
+ EditorFileDialog *export_profile;
+
+ void _profile_action(int p_action);
+ void _profile_selected(int p_what);
+
+ String current_profile;
+ void _update_profile_list(const String &p_select_profile = String());
+ void _update_selected_profile();
+ void _fill_classes_from(TreeItem *p_parent, const String &p_class, const String &p_selected);
+
+ Ref<EditorFeatureProfile> current;
+ Ref<EditorFeatureProfile> edited;
+
+ void _erase_selected_profile();
+ void _create_new_profile();
+ String _get_selected_profile();
+
+ void _import_profiles(const Vector<String> &p_paths);
+ void _export_profile(const String &p_path);
+
+ bool updating_features;
+
+ void _class_list_item_selected();
+ void _class_list_item_edited();
+ void _property_item_edited();
+ void _save_and_update();
+
+ Timer *update_timer;
+ void _emit_current_profile_changed();
+
+ static EditorFeatureProfileManager *singleton;
+
+protected:
+ static void _bind_methods();
+ void _notification(int p_what);
+
+public:
+ Ref<EditorFeatureProfile> get_current_profile();
+ void notify_changed();
+
+ static EditorFeatureProfileManager *get_singleton() { return singleton; }
+ EditorFeatureProfileManager();
+};
+
+#endif // EDITOR_FEATURE_PROFILE_H
diff --git a/editor/editor_folding.cpp b/editor/editor_folding.cpp
index 77c0f7491e..f6079624de 100644
--- a/editor/editor_folding.cpp
+++ b/editor/editor_folding.cpp
@@ -92,7 +92,7 @@ void EditorFolding::load_resource_folding(RES p_resource, const String &p_path)
_set_unfolds(p_resource.ptr(), unfolds);
}
-void EditorFolding::_fill_folds(const Node *p_root, const Node *p_node, Array &p_folds, Array &resource_folds, Set<RES> &resources) {
+void EditorFolding::_fill_folds(const Node *p_root, const Node *p_node, Array &p_folds, Array &resource_folds, Array& nodes_folded,Set<RES> &resources) {
if (p_root != p_node) {
if (!p_node->get_owner()) {
return; //not owned, bye
@@ -102,6 +102,9 @@ void EditorFolding::_fill_folds(const Node *p_root, const Node *p_node, Array &p
}
}
+ if (p_node->is_displayed_folded()) {
+ nodes_folded.push_back(p_root->get_path_to(p_node));
+ }
PoolVector<String> unfolds = _get_unfolds(p_node);
if (unfolds.size()) {
@@ -112,20 +115,22 @@ void EditorFolding::_fill_folds(const Node *p_root, const Node *p_node, Array &p
List<PropertyInfo> plist;
p_node->get_property_list(&plist);
for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (E->get().type == Variant::OBJECT) {
- RES res = p_node->get(E->get().name);
- if (res.is_valid() && !resources.has(res) && res->get_path() != String() && !res->get_path().is_resource_file()) {
-
- PoolVector<String> res_unfolds = _get_unfolds(res.ptr());
- resource_folds.push_back(res->get_path());
- resource_folds.push_back(res_unfolds);
- resources.insert(res);
+ if (E->get().usage & PROPERTY_USAGE_EDITOR) {
+ if (E->get().type == Variant::OBJECT) {
+ RES res = p_node->get(E->get().name);
+ if (res.is_valid() && !resources.has(res) && res->get_path() != String() && !res->get_path().is_resource_file()) {
+
+ PoolVector<String> res_unfolds = _get_unfolds(res.ptr());
+ resource_folds.push_back(res->get_path());
+ resource_folds.push_back(res_unfolds);
+ resources.insert(res);
+ }
}
}
}
for (int i = 0; i < p_node->get_child_count(); i++) {
- _fill_folds(p_root, p_node->get_child(i), p_folds, resource_folds, resources);
+ _fill_folds(p_root, p_node->get_child(i), p_folds, resource_folds, nodes_folded,resources);
}
}
void EditorFolding::save_scene_folding(const Node *p_scene, const String &p_path) {
@@ -135,10 +140,12 @@ void EditorFolding::save_scene_folding(const Node *p_scene, const String &p_path
Array unfolds, res_unfolds;
Set<RES> resources;
- _fill_folds(p_scene, p_scene, unfolds, res_unfolds, resources);
+ Array nodes_folded;
+ _fill_folds(p_scene, p_scene, unfolds, res_unfolds, nodes_folded, resources);
config->set_value("folding", "node_unfolds", unfolds);
config->set_value("folding", "resource_unfolds", res_unfolds);
+ config->set_value("folding", "nodes_folded", nodes_folded);
String path = EditorSettings::get_singleton()->get_project_settings_dir();
String file = p_path.get_file() + "-folding-" + p_path.md5_text() + ".cfg";
@@ -166,6 +173,10 @@ void EditorFolding::load_scene_folding(Node *p_scene, const String &p_path) {
if (config->has_section_key("folding", "resource_unfolds")) {
res_unfolds = config->get_value("folding", "resource_unfolds");
}
+ Array nodes_folded;
+ if (config->has_section_key("folding", "nodes_folded")) {
+ nodes_folded = config->get_value("folding", "nodes_folded");
+ }
ERR_FAIL_COND(unfolds.size() & 1);
ERR_FAIL_COND(res_unfolds.size() & 1);
@@ -193,6 +204,14 @@ void EditorFolding::load_scene_folding(Node *p_scene, const String &p_path) {
PoolVector<String> unfolds2 = res_unfolds[i + 1];
_set_unfolds(res.ptr(), unfolds2);
}
+
+ for(int i=0;i<nodes_folded.size();i++) {
+ NodePath fold_path = nodes_folded[i];
+ if (p_scene->has_node(fold_path)) {
+ Node *node = p_scene->get_node(fold_path);
+ node->set_display_folded(true);
+ }
+ }
}
bool EditorFolding::has_folding_data(const String &p_path) {
diff --git a/editor/editor_folding.h b/editor/editor_folding.h
index e4f7dbba80..5fc980c4a9 100644
--- a/editor/editor_folding.h
+++ b/editor/editor_folding.h
@@ -38,7 +38,7 @@ class EditorFolding {
PoolVector<String> _get_unfolds(const Object *p_object);
void _set_unfolds(Object *p_object, const PoolVector<String> &p_unfolds);
- void _fill_folds(const Node *p_root, const Node *p_node, Array &p_folds, Array &resource_folds, Set<RES> &resources);
+ void _fill_folds(const Node *p_root, const Node *p_node, Array &p_folds, Array &resource_folds, Array &nodes_folded, Set<RES> &resources);
void _do_object_unfolds(Object *p_object, Set<RES> &resources);
void _do_node_unfolds(Node *p_root, Node *p_node, Set<RES> &resources);
diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp
index 60fa5ff16f..c705f9af2b 100644
--- a/editor/editor_inspector.cpp
+++ b/editor/editor_inspector.cpp
@@ -1370,6 +1370,30 @@ void EditorInspector::_parse_added_editors(VBoxContainer *current_vbox, Ref<Edit
ped->added_editors.clear();
}
+bool EditorInspector::_is_property_disabled_by_feature_profile(const StringName &p_property) {
+
+ Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile();
+ if (profile.is_null()) {
+ return false;
+ }
+
+ StringName class_name = object->get_class();
+
+ while (class_name != StringName()) {
+
+ if (profile->is_class_property_disabled(class_name, p_property)) {
+ return true;
+ }
+ if (profile->is_class_disabled(class_name)) {
+ //won't see properties of a disabled class
+ return true;
+ }
+ class_name = ClassDB::get_parent_class(class_name);
+ }
+
+ return false;
+}
+
void EditorInspector::update_tree() {
//to update properly if all is refreshed
@@ -1513,7 +1537,7 @@ void EditorInspector::update_tree() {
continue;
- } else if (!(p.usage & PROPERTY_USAGE_EDITOR))
+ } else if (!(p.usage & PROPERTY_USAGE_EDITOR) || _is_property_disabled_by_feature_profile(p.name))
continue;
if (p.usage & PROPERTY_USAGE_HIGH_END_GFX && VS::get_singleton()->is_low_end())
@@ -2132,6 +2156,10 @@ void EditorInspector::_node_removed(Node *p_node) {
void EditorInspector::_notification(int p_what) {
+ if (p_what == NOTIFICATION_READY) {
+ EditorFeatureProfileManager::get_singleton()->connect("current_feature_profile_changed", this, "_feature_profile_changed");
+ }
+
if (p_what == NOTIFICATION_ENTER_TREE) {
if (sub_inspector) {
@@ -2238,6 +2266,11 @@ String EditorInspector::get_object_class() const {
return object_class;
}
+void EditorInspector::_feature_profile_changed() {
+
+ update_tree();
+}
+
void EditorInspector::_bind_methods() {
ClassDB::bind_method("_property_changed", &EditorInspector::_property_changed, DEFVAL(""), DEFVAL(false));
@@ -2254,6 +2287,7 @@ void EditorInspector::_bind_methods() {
ClassDB::bind_method("_resource_selected", &EditorInspector::_resource_selected);
ClassDB::bind_method("_object_id_selected", &EditorInspector::_object_id_selected);
ClassDB::bind_method("_vscroll_changed", &EditorInspector::_vscroll_changed);
+ ClassDB::bind_method("_feature_profile_changed", &EditorInspector::_feature_profile_changed);
ClassDB::bind_method("refresh", &EditorInspector::refresh);
diff --git a/editor/editor_inspector.h b/editor/editor_inspector.h
index 3d22cdb9a3..494e8b5833 100644
--- a/editor/editor_inspector.h
+++ b/editor/editor_inspector.h
@@ -323,6 +323,10 @@ class EditorInspector : public ScrollContainer {
void _vscroll_changed(double);
+ void _feature_profile_changed();
+
+ bool _is_property_disabled_by_feature_profile(const StringName &p_property);
+
protected:
static void _bind_methods();
void _notification(int p_what);
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index 91e104667e..851d6a0aa6 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -306,7 +306,14 @@ void EditorNode::_notification(int p_what) {
VisualServer::get_singleton()->viewport_set_hide_canvas(get_scene_root()->get_viewport_rid(), true);
VisualServer::get_singleton()->viewport_set_disable_environment(get_viewport()->get_viewport_rid(), true);
- _editor_select(EDITOR_3D);
+ feature_profile_manager->notify_changed();
+
+ if (!main_editor_buttons[EDITOR_3D]->is_visible()) { //may be hidden due to feature profile
+ _editor_select(EDITOR_2D);
+ } else {
+ _editor_select(EDITOR_3D);
+ }
+
_update_debug_options();
/* DO NOT LOAD SCENES HERE, WAIT FOR FILE SCANNING AND REIMPORT TO COMPLETE */
@@ -558,11 +565,14 @@ void EditorNode::_editor_select_next() {
int editor = _get_current_main_editor();
- if (editor == editor_table.size() - 1) {
- editor = 0;
- } else {
- editor++;
- }
+ do {
+ if (editor == editor_table.size() - 1) {
+ editor = 0;
+ } else {
+ editor++;
+ }
+ } while (main_editor_buttons[editor]->is_visible());
+
_editor_select(editor);
}
@@ -570,11 +580,14 @@ void EditorNode::_editor_select_prev() {
int editor = _get_current_main_editor();
- if (editor == 0) {
- editor = editor_table.size() - 1;
- } else {
- editor--;
- }
+ do {
+ if (editor == 0) {
+ editor = editor_table.size() - 1;
+ } else {
+ editor--;
+ }
+ } while (main_editor_buttons[editor]->is_visible());
+
_editor_select(editor);
}
@@ -911,7 +924,8 @@ bool EditorNode::_find_and_save_edited_subresources(Object *obj, Map<RES, bool>
ret_changed = true;
}
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1292,6 +1306,7 @@ void EditorNode::_dialog_action(String p_file) {
_save_default_environment();
_save_scene_with_preview(p_file, scene_idx);
_add_to_recent_scenes(p_file);
+ save_layout();
if (scene_idx != -1)
_discard_changes();
@@ -1440,17 +1455,48 @@ void EditorNode::_dialog_action(String p_file) {
bool EditorNode::item_has_editor(Object *p_object) {
+ if (_is_class_editor_disabled_by_feature_profile(p_object->get_class())) {
+ return false;
+ }
+
return editor_data.get_subeditors(p_object).size() > 0;
}
void EditorNode::edit_item_resource(RES p_resource) {
edit_item(p_resource.ptr());
}
+
+bool EditorNode::_is_class_editor_disabled_by_feature_profile(const StringName &p_class) {
+
+ Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile();
+ if (profile.is_null()) {
+ return false;
+ }
+
+ StringName class_name = p_class;
+
+ while (class_name != StringName()) {
+
+ if (profile->is_class_disabled(class_name)) {
+ return true;
+ }
+ if (profile->is_class_editor_disabled(class_name)) {
+ return true;
+ }
+ class_name = ClassDB::get_parent_class(class_name);
+ }
+
+ return false;
+}
+
void EditorNode::edit_item(Object *p_object) {
Vector<EditorPlugin *> sub_plugins;
if (p_object) {
+ if (_is_class_editor_disabled_by_feature_profile(p_object->get_class())) {
+ return;
+ }
sub_plugins = editor_data.get_subeditors(p_object);
}
@@ -1640,6 +1686,12 @@ void EditorNode::_edit_current() {
EditorPlugin *main_plugin = editor_data.get_editor(current_obj);
+ for (int i = 0; i < editor_table.size(); i++) {
+ if (editor_table[i] == main_plugin && !main_editor_buttons[i]->is_visible()) {
+ main_plugin = NULL; //if button is not visible, then no plugin active
+ }
+ }
+
if (main_plugin) {
// special case if use of external editor is true
@@ -1677,7 +1729,11 @@ void EditorNode::_edit_current() {
}
}
- Vector<EditorPlugin *> sub_plugins = editor_data.get_subeditors(current_obj);
+ Vector<EditorPlugin *> sub_plugins;
+
+ if (!_is_class_editor_disabled_by_feature_profile(current_obj->get_class())) {
+ sub_plugins = editor_data.get_subeditors(current_obj);
+ }
if (!sub_plugins.empty()) {
_display_top_editors(false);
@@ -1685,7 +1741,6 @@ void EditorNode::_edit_current() {
_set_top_editors(sub_plugins);
_set_editing_top_editors(current_obj);
_display_top_editors(true);
-
} else if (!editor_plugins_over->get_plugins_list().empty()) {
hide_top_editors();
@@ -2359,6 +2414,11 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) {
export_template_manager->popup_manager();
} break;
+ case SETTINGS_MANAGE_FEATURE_PROFILES: {
+
+ feature_profile_manager->popup_centered_ratio();
+
+ } break;
case SETTINGS_TOGGLE_FULLSCREEN: {
OS::get_singleton()->set_window_fullscreen(!OS::get_singleton()->is_window_fullscreen());
@@ -2541,10 +2601,13 @@ void EditorNode::_editor_select(int p_which) {
if (selecting || changing_scene)
return;
- selecting = true;
-
ERR_FAIL_INDEX(p_which, editor_table.size());
+ if (!main_editor_buttons[p_which]->is_visible()) //button hidden, no editor
+ return;
+
+ selecting = true;
+
for (int i = 0; i < main_editor_buttons.size(); i++) {
main_editor_buttons[i]->set_pressed(i == p_which);
}
@@ -3284,6 +3347,7 @@ void EditorNode::register_editor_types() {
ClassDB::register_class<EditorProperty>();
ClassDB::register_class<AnimationTrackEditPlugin>();
ClassDB::register_class<ScriptCreateDialog>();
+ ClassDB::register_class<EditorFeatureProfile>();
// FIXME: Is this stuff obsolete, or should it be ported to new APIs?
ClassDB::register_class<EditorScenePostImport>();
@@ -3821,7 +3885,13 @@ void EditorNode::_update_dock_slots_visibility() {
} else {
for (int i = 0; i < DOCK_SLOT_MAX; i++) {
- if (dock_slot[i]->get_tab_count())
+ int tabs_visible = 0;
+ for (int j = 0; j < dock_slot[i]->get_tab_count(); j++) {
+ if (!dock_slot[i]->get_tab_hidden(j)) {
+ tabs_visible++;
+ }
+ }
+ if (tabs_visible)
dock_slot[i]->show();
else
dock_slot[i]->hide();
@@ -4000,6 +4070,7 @@ void EditorNode::_load_open_scenes_from_config(Ref<ConfigFile> p_layout, const S
for (int i = 0; i < scenes.size(); i++) {
load_scene(scenes[i]);
}
+ save_layout();
restoring_scenes = false;
}
@@ -4806,6 +4877,39 @@ void EditorNode::_resource_loaded(RES p_resource, const String &p_path) {
singleton->editor_folding.load_resource_folding(p_resource, p_path);
}
+void EditorNode::_feature_profile_changed() {
+
+ Ref<EditorFeatureProfile> profile = feature_profile_manager->get_current_profile();
+ TabContainer *import_tabs = cast_to<TabContainer>(import_dock->get_parent());
+ TabContainer *node_tabs = cast_to<TabContainer>(node_dock->get_parent());
+ TabContainer *fs_tabs = cast_to<TabContainer>(filesystem_dock->get_parent());
+ if (profile.is_valid()) {
+
+ import_tabs->set_tab_hidden(import_dock->get_index(), profile->is_feature_disabled(EditorFeatureProfile::FEATURE_IMPORT_DOCK));
+ node_tabs->set_tab_hidden(node_dock->get_index(), profile->is_feature_disabled(EditorFeatureProfile::FEATURE_NODE_DOCK));
+ fs_tabs->set_tab_hidden(filesystem_dock->get_index(), profile->is_feature_disabled(EditorFeatureProfile::FEATURE_FILESYSTEM_DOCK));
+
+ main_editor_buttons[EDITOR_3D]->set_visible(!profile->is_feature_disabled(EditorFeatureProfile::FEATURE_3D));
+ main_editor_buttons[EDITOR_SCRIPT]->set_visible(!profile->is_feature_disabled(EditorFeatureProfile::FEATURE_SCRIPT));
+ main_editor_buttons[EDITOR_ASSETLIB]->set_visible(!profile->is_feature_disabled(EditorFeatureProfile::FEATURE_ASSET_LIB));
+ if (profile->is_feature_disabled(EditorFeatureProfile::FEATURE_3D) || profile->is_feature_disabled(EditorFeatureProfile::FEATURE_ASSET_LIB) || profile->is_feature_disabled(EditorFeatureProfile::FEATURE_ASSET_LIB)) {
+ _editor_select(EDITOR_2D);
+ }
+ } else {
+
+ import_tabs->set_tab_hidden(import_dock->get_index(), false);
+ node_tabs->set_tab_hidden(node_dock->get_index(), false);
+ fs_tabs->set_tab_hidden(filesystem_dock->get_index(), false);
+ import_dock->set_visible(true);
+ node_dock->set_visible(true);
+ filesystem_dock->set_visible(true);
+ main_editor_buttons[EDITOR_3D]->set_visible(true);
+ main_editor_buttons[EDITOR_ASSETLIB]->set_visible(true);
+ }
+
+ _update_dock_slots_visibility();
+}
+
void EditorNode::_bind_methods() {
ClassDB::bind_method("_menu_option", &EditorNode::_menu_option);
@@ -4884,6 +4988,7 @@ void EditorNode::_bind_methods() {
ClassDB::bind_method(D_METHOD("_video_driver_selected"), &EditorNode::_video_driver_selected);
ClassDB::bind_method(D_METHOD("_resources_changed"), &EditorNode::_resources_changed);
+ ClassDB::bind_method(D_METHOD("_feature_profile_changed"), &EditorNode::_feature_profile_changed);
ADD_SIGNAL(MethodInfo("play_pressed"));
ADD_SIGNAL(MethodInfo("pause_pressed"));
@@ -5397,8 +5502,11 @@ EditorNode::EditorNode() {
export_template_manager = memnew(ExportTemplateManager);
gui_base->add_child(export_template_manager);
+ feature_profile_manager = memnew(EditorFeatureProfileManager);
+ gui_base->add_child(feature_profile_manager);
about = memnew(EditorAbout);
gui_base->add_child(about);
+ feature_profile_manager->connect("current_feature_profile_changed", this, "_feature_profile_changed");
warning = memnew(AcceptDialog);
gui_base->add_child(warning);
@@ -5554,6 +5662,10 @@ EditorNode::EditorNode() {
}
p->add_separator();
+ p->add_item(TTR("Manage Editor Features"), SETTINGS_MANAGE_FEATURE_PROFILES);
+
+ p->add_separator();
+
p->add_item(TTR("Manage Export Templates"), SETTINGS_MANAGE_EXPORT_TEMPLATES);
// Help Menu
diff --git a/editor/editor_node.h b/editor/editor_node.h
index 267c70c773..5ed0bd4ac3 100644
--- a/editor/editor_node.h
+++ b/editor/editor_node.h
@@ -38,6 +38,7 @@
#include "editor/editor_about.h"
#include "editor/editor_data.h"
#include "editor/editor_export.h"
+#include "editor/editor_feature_profile.h"
#include "editor/editor_folding.h"
#include "editor/editor_inspector.h"
#include "editor/editor_log.h"
@@ -84,7 +85,6 @@
#include "scene/gui/tool_button.h"
#include "scene/gui/tree.h"
#include "scene/gui/viewport_container.h"
-
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
@@ -175,6 +175,7 @@ private:
SETTINGS_EDITOR_DATA_FOLDER,
SETTINGS_EDITOR_CONFIG_FOLDER,
SETTINGS_MANAGE_EXPORT_TEMPLATES,
+ SETTINGS_MANAGE_FEATURE_PROFILES,
SETTINGS_PICK_MAIN_SCENE,
SETTINGS_TOGGLE_FULLSCREEN,
SETTINGS_HELP,
@@ -294,6 +295,7 @@ private:
ProjectSettingsEditor *project_settings;
EditorFileDialog *file;
ExportTemplateManager *export_template_manager;
+ EditorFeatureProfileManager *feature_profile_manager;
EditorFileDialog *file_templates;
EditorFileDialog *file_export;
EditorFileDialog *file_export_lib;
@@ -610,6 +612,9 @@ private:
void _resources_changed(const PoolVector<String> &p_resources);
+ void _feature_profile_changed();
+ bool _is_class_editor_disabled_by_feature_profile(const StringName &p_class);
+
protected:
void _notification(int p_what);
static void _bind_methods();
diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp
index 0e8cd955b5..31f53305e2 100644
--- a/editor/editor_properties.cpp
+++ b/editor/editor_properties.cpp
@@ -2883,7 +2883,8 @@ bool EditorInspectorDefaultPlugin::parse_property(Object *p_object, Variant::Typ
case PROPERTY_HINT_LAYERS_3D_PHYSICS:
lt = EditorPropertyLayers::LAYER_PHYSICS_3D;
break;
- default: {} //compiler could be smarter here and realize this can't happen
+ default: {
+ } //compiler could be smarter here and realize this can't happen
}
EditorPropertyLayers *editor = memnew(EditorPropertyLayers);
editor->setup(lt);
@@ -3020,7 +3021,8 @@ bool EditorInspectorDefaultPlugin::parse_property(Object *p_object, Variant::Typ
case PROPERTY_HINT_PROPERTY_OF_BASE_TYPE: type = EditorPropertyMember::MEMBER_PROPERTY_OF_BASE_TYPE; break;
case PROPERTY_HINT_PROPERTY_OF_INSTANCE: type = EditorPropertyMember::MEMBER_PROPERTY_OF_INSTANCE; break;
case PROPERTY_HINT_PROPERTY_OF_SCRIPT: type = EditorPropertyMember::MEMBER_PROPERTY_OF_SCRIPT; break;
- default: {}
+ default: {
+ }
}
editor->setup(type, p_hint_text);
add_property_editor(p_path, editor);
@@ -3284,7 +3286,8 @@ bool EditorInspectorDefaultPlugin::parse_property(Object *p_object, Variant::Typ
editor->setup(Variant::POOL_COLOR_ARRAY);
add_property_editor(p_path, editor);
} break;
- default: {}
+ default: {
+ }
}
return false; //can be overridden, although it will most likely be last anyway
diff --git a/editor/editor_properties_array_dict.cpp b/editor/editor_properties_array_dict.cpp
index 0f6c6349ed..e3dc517a39 100644
--- a/editor/editor_properties_array_dict.cpp
+++ b/editor/editor_properties_array_dict.cpp
@@ -251,7 +251,8 @@ void EditorPropertyArray::update_property() {
case Variant::POOL_COLOR_ARRAY: {
arrtype = "PoolColorArray";
} break;
- default: {}
+ default: {
+ }
}
if (array.get_type() == Variant::NIL) {
@@ -862,7 +863,8 @@ void EditorPropertyDictionary::update_property() {
editor->setup(Variant::POOL_COLOR_ARRAY);
prop = editor;
} break;
- default: {}
+ default: {
+ }
}
if (i == amount) {
diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp
index b9ed63c1b6..f54c51940f 100644
--- a/editor/editor_settings.cpp
+++ b/editor/editor_settings.cpp
@@ -832,6 +832,13 @@ void EditorSettings::create() {
} else {
dir->change_dir("..");
}
+
+ if (dir->change_dir("feature_profiles") != OK) {
+ dir->make_dir("feature_profiles");
+ } else {
+ dir->change_dir("..");
+ }
+
_create_script_templates(dir->get_current_dir().plus_file("script_templates"));
if (dir->change_dir("projects") != OK) {
@@ -1157,6 +1164,11 @@ String EditorSettings::get_cache_dir() const {
return cache_dir;
}
+String EditorSettings::get_feature_profiles_dir() const {
+
+ return get_settings_dir().plus_file("feature_profiles");
+}
+
// Metadata
void EditorSettings::set_project_metadata(const String &p_section, const String &p_key, Variant p_data) {
diff --git a/editor/editor_settings.h b/editor/editor_settings.h
index 1b44c15c54..43a8cbf739 100644
--- a/editor/editor_settings.h
+++ b/editor/editor_settings.h
@@ -169,6 +169,7 @@ public:
String get_text_editor_themes_dir() const;
String get_script_templates_dir() const;
String get_cache_dir() const;
+ String get_feature_profiles_dir() const;
void set_project_metadata(const String &p_section, const String &p_key, Variant p_data);
Variant get_project_metadata(const String &p_section, const String &p_key, Variant p_default) const;
diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp
index 335e3fcd29..9641e10114 100644
--- a/editor/editor_themes.cpp
+++ b/editor/editor_themes.cpp
@@ -204,7 +204,7 @@ void editor_register_and_generate_icons(Ref<Theme> p_theme, bool p_dark_theme =
}
// generate thumb files with the given thumb size
- bool force_filter = !(p_thumb_size == 64 && p_thumb_size == 32); // we don't need filter with original resolution
+ bool force_filter = p_thumb_size != 64 && p_thumb_size != 32; // we don't need filter with original resolution
if (p_thumb_size >= 64) {
float scale = (float)p_thumb_size / 64.0 * EDSCALE;
for (int i = 0; i < editor_bg_thumbs_count; i++) {
@@ -687,7 +687,7 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
theme->set_constant("button_margin", "Tree", default_margin_size * EDSCALE);
theme->set_constant("draw_relationship_lines", "Tree", relationship_line_opacity >= 0.01);
theme->set_constant("draw_guides", "Tree", relationship_line_opacity < 0.01);
- theme->set_constant("scroll_border", "Tree", default_margin_size * EDSCALE);
+ theme->set_constant("scroll_border", "Tree", 40 * EDSCALE);
theme->set_constant("scroll_speed", "Tree", 12);
Ref<StyleBoxFlat> style_tree_btn = style_default->duplicate();
diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp
index b637148f2d..c32cd1de50 100644
--- a/editor/filesystem_dock.cpp
+++ b/editor/filesystem_dock.cpp
@@ -86,6 +86,13 @@ bool FileSystemDock::_create_tree(TreeItem *p_parent, EditorFileSystemDirectory
// Create all items for the files in the subdirectory
if (display_mode == DISPLAY_MODE_TREE_ONLY) {
for (int i = 0; i < p_dir->get_file_count(); i++) {
+
+ String file_type = p_dir->get_file_type(i);
+
+ if (_is_file_type_disabled_by_feature_profile(file_type)) {
+ //if type is disabled, file wont be displayed.
+ continue;
+ }
String file_name = p_dir->get_file(i);
if (searched_string.length() > 0) {
@@ -276,6 +283,7 @@ void FileSystemDock::_notification(int p_what) {
if (initialized)
return;
initialized = true;
+ EditorFeatureProfileManager::get_singleton()->connect("current_feature_profile_changed", this, "_feature_profile_changed");
EditorFileSystem::get_singleton()->connect("filesystem_changed", this, "_fs_changed");
EditorResourcePreview::get_singleton()->connect("preview_invalidated", this, "_preview_invalidated");
@@ -520,6 +528,26 @@ void FileSystemDock::_set_file_display(bool p_active) {
_update_file_list(true);
}
+bool FileSystemDock::_is_file_type_disabled_by_feature_profile(const StringName &p_class) {
+
+ Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile();
+ if (profile.is_null()) {
+ return false;
+ }
+
+ StringName class_name = p_class;
+
+ while (class_name != StringName()) {
+
+ if (profile->is_class_disabled(class_name)) {
+ return true;
+ }
+ class_name = ClassDB::get_parent_class(class_name);
+ }
+
+ return false;
+}
+
void FileSystemDock::_search(EditorFileSystemDirectory *p_path, List<FileInfo> *matches, int p_max_items) {
if (matches->size() > p_max_items)
@@ -541,6 +569,11 @@ void FileSystemDock::_search(EditorFileSystemDirectory *p_path, List<FileInfo> *
fi.import_broken = !p_path->get_file_import_is_valid(i);
fi.import_status = 0;
+ if (_is_file_type_disabled_by_feature_profile(fi.type)) {
+ //this type is disabled, will not appear here
+ continue;
+ }
+
matches->push_back(fi);
if (matches->size() > p_max_items)
return;
@@ -988,6 +1021,7 @@ void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_
for (int j = 0; j < ed->get_edited_scene_count(); j++) {
if (ed->get_scene_path(j) == file_changed_paths[i]) {
ed->get_edited_scene_root(j)->set_filename(new_item_path);
+ editor->save_layout();
break;
}
}
@@ -2092,6 +2126,10 @@ void FileSystemDock::_tree_rmb_select(const Vector2 &p_pos) {
}
}
+void FileSystemDock::_tree_empty_selected() {
+ tree->deselect_all();
+}
+
void FileSystemDock::_file_list_rmb_select(int p_item, const Vector2 &p_pos) {
// Right click is pressed in the file list
Vector<String> paths;
@@ -2259,6 +2297,11 @@ void FileSystemDock::_update_import_dock() {
import_dock_needs_update = false;
}
+void FileSystemDock::_feature_profile_changed() {
+
+ _update_display_mode(true);
+}
+
void FileSystemDock::_bind_methods() {
ClassDB::bind_method(D_METHOD("_file_list_gui_input"), &FileSystemDock::_file_list_gui_input);
@@ -2270,9 +2313,10 @@ void FileSystemDock::_bind_methods() {
ClassDB::bind_method(D_METHOD("_toggle_split_mode"), &FileSystemDock::_toggle_split_mode);
ClassDB::bind_method(D_METHOD("_tree_rmb_option", "option"), &FileSystemDock::_tree_rmb_option);
- ClassDB::bind_method(D_METHOD("_file_list_rmb_option", "option"), &FileSystemDock::_file_list_rmb_option);
-
ClassDB::bind_method(D_METHOD("_tree_rmb_select"), &FileSystemDock::_tree_rmb_select);
+ ClassDB::bind_method(D_METHOD("_tree_empty_selected"), &FileSystemDock::_tree_empty_selected);
+
+ ClassDB::bind_method(D_METHOD("_file_list_rmb_option", "option"), &FileSystemDock::_file_list_rmb_option);
ClassDB::bind_method(D_METHOD("_file_list_rmb_select"), &FileSystemDock::_file_list_rmb_select);
ClassDB::bind_method(D_METHOD("_file_list_rmb_pressed"), &FileSystemDock::_file_list_rmb_pressed);
@@ -2308,6 +2352,8 @@ void FileSystemDock::_bind_methods() {
ClassDB::bind_method(D_METHOD("_file_multi_selected"), &FileSystemDock::_file_multi_selected);
ClassDB::bind_method(D_METHOD("_update_import_dock"), &FileSystemDock::_update_import_dock);
+ ClassDB::bind_method(D_METHOD("_feature_profile_changed"), &FileSystemDock::_feature_profile_changed);
+
ADD_SIGNAL(MethodInfo("instance", PropertyInfo(Variant::POOL_STRING_ARRAY, "files")));
ADD_SIGNAL(MethodInfo("open"));
@@ -2405,6 +2451,7 @@ FileSystemDock::FileSystemDock(EditorNode *p_editor) {
tree->connect("item_activated", this, "_tree_activate_file");
tree->connect("multi_selected", this, "_tree_multi_selected");
tree->connect("item_rmb_selected", this, "_tree_rmb_select");
+ tree->connect("nothing_selected", this, "_tree_empty_selected");
tree->connect("gui_input", this, "_tree_gui_input");
file_list_vb = memnew(VBoxContainer);
diff --git a/editor/filesystem_dock.h b/editor/filesystem_dock.h
index cd052f9700..8b27938c8a 100644
--- a/editor/filesystem_dock.h
+++ b/editor/filesystem_dock.h
@@ -237,6 +237,7 @@ private:
void _tree_rmb_select(const Vector2 &p_pos);
void _file_list_rmb_select(int p_item, const Vector2 &p_pos);
void _file_list_rmb_pressed(const Vector2 &p_pos);
+ void _tree_empty_selected();
struct FileInfo {
String name;
@@ -268,6 +269,10 @@ private:
Vector<String> _tree_get_selected(bool remove_self_inclusion = true);
+ bool _is_file_type_disabled_by_feature_profile(const StringName &p_class);
+
+ void _feature_profile_changed();
+
protected:
void _notification(int p_what);
static void _bind_methods();
diff --git a/editor/icons/icon_auto_key.svg b/editor/icons/icon_auto_key.svg
new file mode 100644
index 0000000000..cbafe1ac38
--- /dev/null
+++ b/editor/icons/icon_auto_key.svg
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ width="16"
+ height="16"
+ version="1.1"
+ viewBox="0 0 16 16"
+ id="svg6"
+ sodipodi:docname="icon_auto_key.svg"
+ inkscape:version="0.92.4 (5da689c313, 2019-01-14)">
+ <metadata
+ id="metadata12">
+ <rdf:RDF>
+ <cc:Work
+ rdf:about="">
+ <dc:format>image/svg+xml</dc:format>
+ <dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+ <dc:title></dc:title>
+ </cc:Work>
+ </rdf:RDF>
+ </metadata>
+ <defs
+ id="defs10" />
+ <sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1854"
+ inkscape:window-height="1016"
+ id="namedview8"
+ showgrid="false"
+ inkscape:zoom="10.429825"
+ inkscape:cx="10.199345"
+ inkscape:cy="-4.0344119"
+ inkscape:window-x="66"
+ inkscape:window-y="27"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="svg6" />
+ <path
+ style="fill:#e0e0e0;fill-opacity:1;stroke-width:0.0333107"
+ d="M 3.5469681,13.426786 C 2.7965829,13.263778 2.2774312,12.503915 2.4037297,11.753472 c 0.1081234,-0.642451 0.6006808,-1.135008 1.2431317,-1.243131 0.9667125,-0.162696 1.8555225,0.726112 1.6928259,1.692826 -0.103766,0.616558 -0.5592173,1.098057 -1.1588427,1.225117 -0.2719576,0.05763 -0.3626872,0.05741 -0.6338765,-0.0014 z m 8.0861339,-0.08275 c -0.746862,-0.13829 -1.23937,-0.720718 -1.23937,-1.465649 0,-0.527377 0.244831,-0.978806 0.679757,-1.253362 0.471386,-0.297574 1.114188,-0.297574 1.585574,0 0.682727,0.430986 0.892336,1.362194 0.460575,2.046149 -0.307786,0.487563 -0.940521,0.773963 -1.486536,0.672862 z M 0.60726032,9.8305658 V 7.7161233 L 1.1770842,7.7070075 1.7469079,7.6978939 3.1889882,5.1995916 4.6310686,2.7012893 h 3.1726318 3.1726316 l 1.442755,2.4983023 1.442755,2.4983023 0.651097,0.00903 0.651096,0.00903 v 2.1145264 2.1145257 h -0.566282 -0.566281 v -0.161225 c 0,-0.234927 -0.113135,-0.639704 -0.255664,-0.914727 -0.16895,-0.326004 -0.574198,-0.731251 -0.900202,-0.9002019 -0.656732,-0.3403483 -1.428549,-0.3403483 -2.085281,0 -0.326004,0.1689519 -0.731252,0.5741989 -0.9002019,0.9002029 -0.1425297,0.275023 -0.2556639,0.6798 -0.2556639,0.914727 v 0.161225 H 7.8570969 6.0797346 L 6.0617736,11.686851 C 6.006289,10.889347 5.447548,10.170679 4.6603773,9.884336 4.4466221,9.8065798 4.3737631,9.797427 3.9716406,9.7978134 3.5871254,9.7981885 3.4905638,9.809405 3.3054265,9.8752358 2.5067319,10.159236 1.9362359,10.884501 1.8813215,11.68568 l -0.017772,0.259329 H 1.2354063 0.60726287 Z M 12.399247,7.7466889 c 0,-0.037287 -0.02623,-0.1073444 -0.0583,-0.1556843 -0.03206,-0.04834 -0.561225,-0.958444 -1.17592,-2.0224529 L 10.047407,3.6339894 7.6977565,3.6254406 C 5.4917229,3.6174174 5.3450379,3.6204563 5.2979001,3.6754094 5.1898818,3.8013046 2.9723198,7.6840061 2.9723198,7.7472381 c 0,0.067139 0.00758,0.067247 4.7134636,0.067247 h 4.7134636 z"
+ id="path6243"
+ inkscape:connector-curvature="0" />
+</svg>
diff --git a/editor/icons/icon_sprite_sheet.svg b/editor/icons/icon_sprite_sheet.svg
new file mode 100644
index 0000000000..eeb804f8b9
--- /dev/null
+++ b/editor/icons/icon_sprite_sheet.svg
@@ -0,0 +1,61 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ width="16"
+ height="16"
+ version="1.1"
+ viewBox="0 0 16 16"
+ id="svg6"
+ sodipodi:docname="icon_sprite_sheet.svg"
+ inkscape:version="0.92.3 (2405546, 2018-03-11)">
+ <metadata
+ id="metadata12">
+ <rdf:RDF>
+ <cc:Work
+ rdf:about="">
+ <dc:format>image/svg+xml</dc:format>
+ <dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+ <dc:title></dc:title>
+ </cc:Work>
+ </rdf:RDF>
+ </metadata>
+ <defs
+ id="defs10" />
+ <sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="773"
+ inkscape:window-height="480"
+ id="namedview8"
+ showgrid="false"
+ inkscape:zoom="14.75"
+ inkscape:cx="8"
+ inkscape:cy="8"
+ inkscape:window-x="551"
+ inkscape:window-y="278"
+ inkscape:window-maximized="0"
+ inkscape:current-layer="g4" />
+ <g
+ transform="translate(0 -1036.4)"
+ id="g4">
+ <path
+ transform="translate(0 1036.4)"
+ d="m3 1c-1.1046 0-2 0.89543-2 2v10c0 1.1046 0.89543 2 2 2h10c1.1046 0 2-0.89543 2-2v-10c0-1.1046-0.89543-2-2-2h-10zm0 2h2v2h-2v-2zm4 0h2v2h-2v-2zm4 0h2v2h-2v-2zm-8 4h2v2h-2v-2zm4 0h2v2h-2v-2zm4 0h2v2h-2v-2zm-8 4h2v2h-2v-2zm4 0h2v2h-2v-2zm4 0h2v2h-2v-2z"
+ fill="#a5efac"
+ id="path2"
+ style="fill:#e0e0e0;fill-opacity:1" />
+ </g>
+</svg>
diff --git a/editor/import/editor_scene_importer_gltf.cpp b/editor/import/editor_scene_importer_gltf.cpp
index e6e29df133..daa423e1d9 100644
--- a/editor/import/editor_scene_importer_gltf.cpp
+++ b/editor/import/editor_scene_importer_gltf.cpp
@@ -581,7 +581,9 @@ int EditorSceneImporterGLTF::_get_component_type_size(int component_type) {
case COMPONENT_TYPE_UNSIGNED_SHORT: return 2; break;
case COMPONENT_TYPE_INT: return 4; break;
case COMPONENT_TYPE_FLOAT: return 4; break;
- default: { ERR_FAIL_V(0); }
+ default: {
+ ERR_FAIL_V(0);
+ }
}
return 0;
}
@@ -631,7 +633,8 @@ Vector<double> EditorSceneImporterGLTF::_decode_accessor(GLTFState &state, int p
element_size = 16; //override for this case
}
} break;
- default: {}
+ default: {
+ }
}
Vector<double> dst_buffer;
diff --git a/editor/import/resource_importer_scene.cpp b/editor/import/resource_importer_scene.cpp
index fb2e3c0401..ab515785da 100644
--- a/editor/import/resource_importer_scene.cpp
+++ b/editor/import/resource_importer_scene.cpp
@@ -279,7 +279,24 @@ static String _fixstr(const String &p_what, const String &p_str) {
return what;
}
-Node *ResourceImporterScene::_fix_node(Node *p_node, Node *p_root, Map<Ref<ArrayMesh>, Ref<Shape> > &collision_map, LightBakeMode p_light_bake_mode) {
+static void _gen_shape_list(const Ref<Mesh> &mesh, List<Ref<Shape> > &r_shape_list, bool p_convex) {
+
+ if (!p_convex) {
+
+ Ref<Shape> shape = mesh->create_trimesh_shape();
+ r_shape_list.push_back(shape);
+ } else {
+
+ Vector<Ref<Shape> > cd = mesh->convex_decompose();
+ if (cd.size()) {
+ for (int i = 0; i < cd.size(); i++) {
+ r_shape_list.push_back(cd[i]);
+ }
+ }
+ }
+}
+
+Node *ResourceImporterScene::_fix_node(Node *p_node, Node *p_root, Map<Ref<Mesh>, List<Ref<Shape> > > &collision_map, LightBakeMode p_light_bake_mode) {
// children first
for (int i = 0; i < p_node->get_child_count(); i++) {
@@ -365,37 +382,52 @@ Node *ResourceImporterScene::_fix_node(Node *p_node, Node *p_root, Map<Ref<Array
return p_node;
MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
if (mi) {
- Node *col = NULL;
-
- if (_teststr(name, "colonly")) {
- col = mi->create_trimesh_collision_node();
- if (col == NULL) {
- ERR_PRINTS("Error generating collision for mesh: " + name);
- } else {
-
- col->set_name(_fixstr(name, "colonly"));
+ Ref<Mesh> mesh = mi->get_mesh();
+
+ if (mesh.is_valid()) {
+ List<Ref<Shape> > shapes;
+ String fixed_name;
+ if (collision_map.has(mesh)) {
+ shapes = collision_map[mesh];
+ } else if (_teststr(name, "colonly")) {
+ _gen_shape_list(mesh, shapes, false);
+ collision_map[mesh] = shapes;
+ } else if (_teststr(name, "convcolonly")) {
+ _gen_shape_list(mesh, shapes, true);
+ collision_map[mesh] = shapes;
}
- } else {
- col = mi->create_convex_collision_node();
- if (col == NULL) {
- ERR_PRINTS("Error generating collision for mesh: " + name);
- } else {
- col->set_name(_fixstr(name, "convcolonly"));
+ if (_teststr(name, "colonly")) {
+ fixed_name = _fixstr(name, "colonly");
+ } else if (_teststr(name, "convcolonly")) {
+ fixed_name = _fixstr(name, "convcolonly");
}
- }
- if (col) {
- Object::cast_to<Spatial>(col)->set_transform(mi->get_transform());
- p_node->replace_by(col);
- memdelete(p_node);
- p_node = col;
+ ERR_FAIL_COND_V(fixed_name == String(), NULL);
+
+ if (shapes.size()) {
+
+ StaticBody *col = memnew(StaticBody);
+ col->set_transform(mi->get_transform());
+ col->set_name(fixed_name);
+ p_node->replace_by(col);
+ memdelete(p_node);
+ p_node = col;
+
+ int idx = 0;
+ for (List<Ref<Shape> >::Element *E = shapes.front(); E; E = E->next()) {
+
+ CollisionShape *cshape = memnew(CollisionShape);
+ cshape->set_shape(E->get());
+ col->add_child(cshape);
- StaticBody *sb = Object::cast_to<StaticBody>(col);
- CollisionShape *colshape = Object::cast_to<CollisionShape>(sb->get_child(0));
- colshape->set_name("shape");
- colshape->set_owner(p_node->get_owner());
+ cshape->set_name("shape" + itos(idx));
+ cshape->set_owner(col->get_owner());
+ idx++;
+ }
+ }
}
+
} else if (p_node->has_meta("empty_draw_type")) {
String empty_draw_type = String(p_node->get_meta("empty_draw_type"));
StaticBody *sb = memnew(StaticBody);
@@ -434,77 +466,91 @@ Node *ResourceImporterScene::_fix_node(Node *p_node, Node *p_root, Map<Ref<Array
if (isroot)
return p_node;
- // get mesh instance and bounding box
MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
- AABB aabb = mi->get_aabb();
-
- // create a new rigid body collision node
- RigidBody *rigid_body = memnew(RigidBody);
- Node *col = rigid_body;
- ERR_FAIL_COND_V(!col, NULL);
-
- // remove node name postfix
- col->set_name(_fixstr(name, "rigid"));
- // get mesh instance xform matrix to the rigid body collision node
- Object::cast_to<Spatial>(col)->set_transform(mi->get_transform());
- // save original node by duplicating it into a new instance and correcting the name
- Node *mesh = p_node->duplicate();
- mesh->set_name(_fixstr(name, "rigid"));
- // reset the xform matrix of the duplicated node so it can inherit parent node xform
- Object::cast_to<Spatial>(mesh)->set_transform(Transform(Basis()));
- // reparent the new mesh node to the rigid body collision node
- p_node->add_child(mesh);
- mesh->set_owner(p_node->get_owner());
- // replace the original node with the rigid body collision node
- p_node->replace_by(col);
- memdelete(p_node);
- p_node = col;
-
- // create an alias for the rigid body collision node
- RigidBody *rb = Object::cast_to<RigidBody>(col);
- // create a new Box collision shape and set the right extents
- Ref<BoxShape> shape = memnew(BoxShape);
- shape->set_extents(aabb.get_size() * 0.5);
- CollisionShape *colshape = memnew(CollisionShape);
- colshape->set_name("shape");
- colshape->set_shape(shape);
- // reparent the new collision shape to the rigid body collision node
- rb->add_child(colshape);
- colshape->set_owner(p_node->get_owner());
+ Ref<Mesh> mesh = mi->get_mesh();
+
+ if (mesh.is_valid()) {
+ List<Ref<Shape> > shapes;
+ if (collision_map.has(mesh)) {
+ shapes = collision_map[mesh];
+ } else {
+ _gen_shape_list(mesh, shapes, true);
+ }
+
+ RigidBody *rigid_body = memnew(RigidBody);
+ rigid_body->set_name(_fixstr(name, "rigid"));
+ p_node->replace_by(rigid_body);
+ rigid_body->set_transform(mi->get_transform());
+ p_node = rigid_body;
+ mi->set_name("mesh");
+ mi->set_transform(Transform());
+ rigid_body->add_child(mi);
+ mi->set_owner(rigid_body->get_owner());
+
+ int idx = 0;
+ for (List<Ref<Shape> >::Element *E = shapes.front(); E; E = E->next()) {
+
+ CollisionShape *cshape = memnew(CollisionShape);
+ cshape->set_shape(E->get());
+ rigid_body->add_child(cshape);
+
+ cshape->set_name("shape" + itos(idx));
+ cshape->set_owner(p_node->get_owner());
+ idx++;
+ }
+ }
} else if ((_teststr(name, "col") || (_teststr(name, "convcol"))) && Object::cast_to<MeshInstance>(p_node)) {
MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
- Node *col;
- if (_teststr(name, "col")) {
- String new_name = _fixstr(name, "col");
- if (mi->get_parent() && !mi->get_parent()->has_node(new_name)) {
- mi->set_name(new_name);
+ Ref<Mesh> mesh = mi->get_mesh();
+
+ if (mesh.is_valid()) {
+ List<Ref<Shape> > shapes;
+ String fixed_name;
+ if (collision_map.has(mesh)) {
+ shapes = collision_map[mesh];
+ } else if (_teststr(name, "col")) {
+ _gen_shape_list(mesh, shapes, false);
+ collision_map[mesh] = shapes;
+ } else if (_teststr(name, "convcol")) {
+ _gen_shape_list(mesh, shapes, true);
+ collision_map[mesh] = shapes;
}
- col = mi->create_trimesh_collision_node();
- ERR_FAIL_COND_V(!col, NULL);
- col->set_name("col");
- } else {
- String new_name = _fixstr(name, "convcol");
- if (mi->get_parent() && !mi->get_parent()->has_node(new_name)) {
- mi->set_name(new_name);
+ if (_teststr(name, "col")) {
+ fixed_name = _fixstr(name, "col");
+ } else if (_teststr(name, "convcol")) {
+ fixed_name = _fixstr(name, "convcol");
}
- col = mi->create_convex_collision_node();
- ERR_FAIL_COND_V(!col, NULL);
- col->set_name("convcol");
- }
+ if (fixed_name != String()) {
+ if (mi->get_parent() && !mi->get_parent()->has_node(fixed_name)) {
+ mi->set_name(fixed_name);
+ }
+ }
+
+ if (shapes.size()) {
+ StaticBody *col = memnew(StaticBody);
+ col->set_name("static_collision");
+ mi->add_child(col);
+ col->set_owner(mi->get_owner());
- p_node->add_child(col);
+ int idx = 0;
+ for (List<Ref<Shape> >::Element *E = shapes.front(); E; E = E->next()) {
- StaticBody *sb = Object::cast_to<StaticBody>(col);
- CollisionShape *colshape = Object::cast_to<CollisionShape>(sb->get_child(0));
- colshape->set_name("shape");
- col->add_child(colshape);
- colshape->set_owner(p_node->get_owner());
- sb->set_owner(p_node->get_owner());
+ CollisionShape *cshape = memnew(CollisionShape);
+ cshape->set_shape(E->get());
+ col->add_child(cshape);
+
+ cshape->set_name("shape" + itos(idx));
+ cshape->set_owner(p_node->get_owner());
+
+ idx++;
+ }
+ }
+ }
} else if (_teststr(name, "navmesh") && Object::cast_to<MeshInstance>(p_node)) {
@@ -574,48 +620,35 @@ Node *ResourceImporterScene::_fix_node(Node *p_node, Node *p_root, Map<Ref<Array
Ref<ArrayMesh> mesh = mi->get_mesh();
if (!mesh.is_null()) {
- if (_teststr(mesh->get_name(), "col") || _teststr(mesh->get_name(), "convcol")) {
- Ref<Shape> shape;
- if (_teststr(mesh->get_name(), "col")) {
- mesh->set_name(_fixstr(mesh->get_name(), "col"));
-
- if (collision_map.has(mesh)) {
- shape = collision_map[mesh];
-
- } else {
-
- shape = mesh->create_trimesh_shape();
- if (!shape.is_null())
- collision_map[mesh] = shape;
- }
- } else if (_teststr(mesh->get_name(), "convcol")) {
- mesh->set_name(_fixstr(mesh->get_name(), "convcol"));
+ List<Ref<Shape> > shapes;
+ if (collision_map.has(mesh)) {
+ shapes = collision_map[mesh];
+ } else if (_teststr(mesh->get_name(), "col")) {
+ _gen_shape_list(mesh, shapes, false);
+ collision_map[mesh] = shapes;
+ mesh->set_name(_fixstr(mesh->get_name(), "col"));
+ } else if (_teststr(mesh->get_name(), "convcol")) {
+ _gen_shape_list(mesh, shapes, true);
+ collision_map[mesh] = shapes;
+ mesh->set_name(_fixstr(mesh->get_name(), "convcol"));
+ }
- if (collision_map.has(mesh)) {
- shape = collision_map[mesh];
+ if (shapes.size()) {
+ StaticBody *col = memnew(StaticBody);
+ col->set_name("static_collision");
+ p_node->add_child(col);
+ col->set_owner(p_node->get_owner());
- } else {
+ int idx = 0;
+ for (List<Ref<Shape> >::Element *E = shapes.front(); E; E = E->next()) {
- shape = mesh->create_convex_shape();
- if (!shape.is_null())
- collision_map[mesh] = shape;
- }
- }
-
- if (!shape.is_null()) {
- StaticBody *col = memnew(StaticBody);
CollisionShape *cshape = memnew(CollisionShape);
- cshape->set_shape(shape);
+ cshape->set_shape(E->get());
col->add_child(cshape);
- col->set_transform(mi->get_transform());
- col->set_name(mi->get_name());
- p_node->replace_by(col);
- memdelete(p_node);
- p_node = col;
-
- cshape->set_name("shape");
+ cshape->set_name("shape" + itos(idx));
cshape->set_owner(p_node->get_owner());
+ idx++;
}
}
}
@@ -1269,7 +1302,7 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p
float anim_optimizer_maxang = p_options["animation/optimizer/max_angle"];
int light_bake_mode = p_options["meshes/light_baking"];
- Map<Ref<ArrayMesh>, Ref<Shape> > collision_map;
+ Map<Ref<Mesh>, List<Ref<Shape> > > collision_map;
scene = _fix_node(scene, scene, collision_map, LightBakeMode(light_bake_mode));
diff --git a/editor/import/resource_importer_scene.h b/editor/import/resource_importer_scene.h
index 99f8b1a8e0..b10c4da2e5 100644
--- a/editor/import/resource_importer_scene.h
+++ b/editor/import/resource_importer_scene.h
@@ -146,7 +146,7 @@ public:
void _make_external_resources(Node *p_node, const String &p_base_path, bool p_make_animations, bool p_keep_animations, bool p_make_materials, bool p_keep_materials, bool p_make_meshes, Map<Ref<Animation>, Ref<Animation> > &p_animations, Map<Ref<Material>, Ref<Material> > &p_materials, Map<Ref<ArrayMesh>, Ref<ArrayMesh> > &p_meshes);
- Node *_fix_node(Node *p_node, Node *p_root, Map<Ref<ArrayMesh>, Ref<Shape> > &collision_map, LightBakeMode p_light_bake_mode);
+ Node *_fix_node(Node *p_node, Node *p_root, Map<Ref<Mesh>, List<Ref<Shape> > > &collision_map, LightBakeMode p_light_bake_mode);
void _create_clips(Node *scene, const Array &p_clips, bool p_bake_all);
void _filter_anim_tracks(Ref<Animation> anim, Set<String> &keep);
diff --git a/editor/output_strings.cpp b/editor/output_strings.cpp
index 24b44f078f..baabaff9a8 100644
--- a/editor/output_strings.cpp
+++ b/editor/output_strings.cpp
@@ -105,7 +105,8 @@ void OutputStrings::_notification(int p_what) {
case LINE_LINK: {
} break;
- default: {}
+ default: {
+ }
}
line_ofs.y += font->get_ascent();
diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp
index bbaf41e3cc..41f35c3bed 100644
--- a/editor/plugins/animation_player_editor_plugin.cpp
+++ b/editor/plugins/animation_player_editor_plugin.cpp
@@ -670,6 +670,7 @@ Dictionary AnimationPlayerEditor::get_state() const {
if (EditorNode::get_singleton()->get_edited_scene() && is_visible_in_tree() && player) {
d["player"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(player);
d["animation"] = player->get_assigned_animation();
+ d["track_editor_state"] = track_editor->get_state();
}
return d;
@@ -696,6 +697,10 @@ void AnimationPlayerEditor::set_state(const Dictionary &p_state) {
_animation_edit();
}
}
+
+ if (p_state.has("track_editor_state")) {
+ track_editor->set_state(p_state["track_editor_state"]);
+ }
}
}
diff --git a/editor/plugins/animation_tree_player_editor_plugin.cpp b/editor/plugins/animation_tree_player_editor_plugin.cpp
index e2a44069d9..e21ae4834d 100644
--- a/editor/plugins/animation_tree_player_editor_plugin.cpp
+++ b/editor/plugins/animation_tree_player_editor_plugin.cpp
@@ -200,7 +200,8 @@ void AnimationTreePlayerEditor::_edit_dialog_changed() {
if (anim_tree->transition_node_get_current(edited_node) != edit_option->get_selected())
anim_tree->transition_node_set_current(edited_node, edit_option->get_selected());
} break;
- default: {}
+ default: {
+ }
}
}
@@ -457,7 +458,8 @@ void AnimationTreePlayerEditor::_popup_edit_dialog() {
edit_dialog->set_size(Size2(150, 100));
} break;
- default: {}
+ default: {
+ }
}
}
@@ -555,7 +557,8 @@ void AnimationTreePlayerEditor::_draw_node(const StringName &p_node) {
text += "->";
break;
- default: {}
+ default: {
+ }
}
font->draw(ci, ofs + ascofs + Point2(3, 0), text, font_color);
@@ -740,7 +743,8 @@ void AnimationTreePlayerEditor::_gui_input(Ref<InputEvent> p_event) {
//open editor
//_node_edit_property(click_node);
} break;
- default: {}
+ default: {
+ }
}
}
if (mb->get_button_index() == 2) {
@@ -817,7 +821,8 @@ void AnimationTreePlayerEditor::_gui_input(Ref<InputEvent> p_event) {
anim_tree->node_set_position(click_node, new_pos);
} break;
- default: {}
+ default: {
+ }
}
click_type = CLICK_NONE;
diff --git a/editor/plugins/asset_library_editor_plugin.cpp b/editor/plugins/asset_library_editor_plugin.cpp
index 6d2cdfc583..386bc1738e 100644
--- a/editor/plugins/asset_library_editor_plugin.cpp
+++ b/editor/plugins/asset_library_editor_plugin.cpp
@@ -454,7 +454,8 @@ void EditorAssetLibraryItemDownload::_notification(int p_what) {
progress->set_max(1);
progress->set_value(0);
} break;
- default: {}
+ default: {
+ }
}
prev_status = cstatus;
}
@@ -612,7 +613,8 @@ void EditorAssetLibrary::_notification(int p_what) {
case HTTPClient::STATUS_BODY: {
load_status->set_value(0.4);
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/editor/plugins/baked_lightmap_editor_plugin.cpp b/editor/plugins/baked_lightmap_editor_plugin.cpp
index d90ff95c1f..d75f06de12 100644
--- a/editor/plugins/baked_lightmap_editor_plugin.cpp
+++ b/editor/plugins/baked_lightmap_editor_plugin.cpp
@@ -50,7 +50,8 @@ void BakedLightmapEditorPlugin::_bake() {
case BakedLightmap::BAKE_ERROR_CANT_CREATE_IMAGE:
EditorNode::get_singleton()->show_warning(TTR("Failed creating lightmap images, make sure path is writable."));
break;
- default: {}
+ default: {
+ }
}
}
}
diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp
index c3cac582ad..b2923a1ff2 100644
--- a/editor/plugins/canvas_item_editor_plugin.cpp
+++ b/editor/plugins/canvas_item_editor_plugin.cpp
@@ -1340,6 +1340,10 @@ bool CanvasItemEditor::_gui_input_rotate(const Ref<InputEvent> &p_event) {
// Confirms the node rotation
if (b.is_valid() && b->get_button_index() == BUTTON_LEFT && !b->is_pressed()) {
_commit_canvas_item_state(drag_selection, TTR("Rotate CanvasItem"));
+ if (key_auto_insert_button->is_pressed()) {
+ _insert_animation_keys(false, true, false, true);
+ }
+
drag_type = DRAG_NONE;
return true;
}
@@ -1641,6 +1645,9 @@ bool CanvasItemEditor::_gui_input_resize(const Ref<InputEvent> &p_event) {
// Confirm resize
if (b.is_valid() && b->get_button_index() == BUTTON_LEFT && !b->is_pressed()) {
_commit_canvas_item_state(drag_selection, TTR("Resize CanvasItem"));
+ if (key_auto_insert_button->is_pressed()) {
+ _insert_animation_keys(false, false, true, true);
+ }
drag_type = DRAG_NONE;
viewport->update();
return true;
@@ -1747,6 +1754,10 @@ bool CanvasItemEditor::_gui_input_scale(const Ref<InputEvent> &p_event) {
// Confirm resize
if (b.is_valid() && b->get_button_index() == BUTTON_LEFT && !b->is_pressed()) {
_commit_canvas_item_state(drag_selection, TTR("Scale CanvasItem"));
+ if (key_auto_insert_button->is_pressed()) {
+ _insert_animation_keys(false, false, true, true);
+ }
+
drag_type = DRAG_NONE;
viewport->update();
return true;
@@ -1852,6 +1863,9 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) {
_commit_canvas_item_state(drag_selection, TTR("Move CanvasItem"), true);
}
+ if (key_auto_insert_button->is_pressed()) {
+ _insert_animation_keys(true, false, false, true);
+ }
drag_type = DRAG_NONE;
viewport->update();
return true;
@@ -3384,6 +3398,7 @@ void CanvasItemEditor::_notification(int p_what) {
key_rot_button->set_icon(get_icon("KeyRotation", "EditorIcons"));
key_scale_button->set_icon(get_icon("KeyScale", "EditorIcons"));
key_insert_button->set_icon(get_icon("Key", "EditorIcons"));
+ key_auto_insert_button->set_icon(get_icon("AutoKey", "EditorIcons"));
zoom_minus->set_icon(get_icon("ZoomLess", "EditorIcons"));
zoom_reset->set_icon(get_icon("ZoomReset", "EditorIcons"));
@@ -3716,6 +3731,77 @@ void CanvasItemEditor::_button_tool_select(int p_index) {
tool = (Tool)p_index;
}
+void CanvasItemEditor::_insert_animation_keys(bool p_location, bool p_rotation, bool p_scale, bool p_on_existing) {
+
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
+
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
+
+ CanvasItem *canvas_item = Object::cast_to<CanvasItem>(E->key());
+ if (!canvas_item || !canvas_item->is_visible_in_tree())
+ continue;
+
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
+ continue;
+
+ if (Object::cast_to<Node2D>(canvas_item)) {
+ Node2D *n2d = Object::cast_to<Node2D>(canvas_item);
+
+ if (key_pos && p_location)
+ AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(n2d, "position", n2d->get_position(), p_on_existing);
+ if (key_rot && p_rotation)
+ AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(n2d, "rotation_degrees", Math::rad2deg(n2d->get_rotation()), p_on_existing);
+ if (key_scale && p_scale)
+ AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(n2d, "scale", n2d->get_scale(), p_on_existing);
+
+ if (n2d->has_meta("_edit_bone_") && n2d->get_parent_item()) {
+ //look for an IK chain
+ List<Node2D *> ik_chain;
+
+ Node2D *n = Object::cast_to<Node2D>(n2d->get_parent_item());
+ bool has_chain = false;
+
+ while (n) {
+
+ ik_chain.push_back(n);
+ if (n->has_meta("_edit_ik_")) {
+ has_chain = true;
+ break;
+ }
+
+ if (!n->get_parent_item())
+ break;
+ n = Object::cast_to<Node2D>(n->get_parent_item());
+ }
+
+ if (has_chain && ik_chain.size()) {
+
+ for (List<Node2D *>::Element *F = ik_chain.front(); F; F = F->next()) {
+
+ if (key_pos)
+ AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(F->get(), "position", F->get()->get_position(), p_on_existing);
+ if (key_rot)
+ AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(F->get(), "rotation_degrees", Math::rad2deg(F->get()->get_rotation()), p_on_existing);
+ if (key_scale)
+ AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(F->get(), "scale", F->get()->get_scale(), p_on_existing);
+ }
+ }
+ }
+
+ } else if (Object::cast_to<Control>(canvas_item)) {
+
+ Control *ctrl = Object::cast_to<Control>(canvas_item);
+
+ if (key_pos)
+ AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl, "rect_position", ctrl->get_position(), p_on_existing);
+ if (key_rot)
+ AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl, "rect_rotation", ctrl->get_rotation_degrees(), p_on_existing);
+ if (key_scale)
+ AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl, "rect_size", ctrl->get_size(), p_on_existing);
+ }
+ }
+}
+
void CanvasItemEditor::_popup_callback(int p_op) {
last_option = MenuOption(p_op);
@@ -3983,73 +4069,7 @@ void CanvasItemEditor::_popup_callback(int p_op) {
bool existing = p_op == ANIM_INSERT_KEY_EXISTING;
- Map<Node *, Object *> &selection = editor_selection->get_selection();
-
- for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
-
- CanvasItem *canvas_item = Object::cast_to<CanvasItem>(E->key());
- if (!canvas_item || !canvas_item->is_visible_in_tree())
- continue;
-
- if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
- continue;
-
- if (Object::cast_to<Node2D>(canvas_item)) {
- Node2D *n2d = Object::cast_to<Node2D>(canvas_item);
-
- if (key_pos)
- AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(n2d, "position", n2d->get_position(), existing);
- if (key_rot)
- AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(n2d, "rotation_degrees", Math::rad2deg(n2d->get_rotation()), existing);
- if (key_scale)
- AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(n2d, "scale", n2d->get_scale(), existing);
-
- if (n2d->has_meta("_edit_bone_") && n2d->get_parent_item()) {
- //look for an IK chain
- List<Node2D *> ik_chain;
-
- Node2D *n = Object::cast_to<Node2D>(n2d->get_parent_item());
- bool has_chain = false;
-
- while (n) {
-
- ik_chain.push_back(n);
- if (n->has_meta("_edit_ik_")) {
- has_chain = true;
- break;
- }
-
- if (!n->get_parent_item())
- break;
- n = Object::cast_to<Node2D>(n->get_parent_item());
- }
-
- if (has_chain && ik_chain.size()) {
-
- for (List<Node2D *>::Element *F = ik_chain.front(); F; F = F->next()) {
-
- if (key_pos)
- AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(F->get(), "position", F->get()->get_position(), existing);
- if (key_rot)
- AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(F->get(), "rotation_degrees", Math::rad2deg(F->get()->get_rotation()), existing);
- if (key_scale)
- AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(F->get(), "scale", F->get()->get_scale(), existing);
- }
- }
- }
-
- } else if (Object::cast_to<Control>(canvas_item)) {
-
- Control *ctrl = Object::cast_to<Control>(canvas_item);
-
- if (key_pos)
- AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl, "rect_position", ctrl->get_position(), existing);
- if (key_rot)
- AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl, "rect_rotation", ctrl->get_rotation_degrees(), existing);
- if (key_scale)
- AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl, "rect_size", ctrl->get_size(), existing);
- }
- }
+ _insert_animation_keys(true, true, true, existing);
} break;
case ANIM_INSERT_POS: {
@@ -4866,6 +4886,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
key_loc_button->set_pressed(true);
key_loc_button->set_focus_mode(FOCUS_NONE);
key_loc_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_POS));
+ key_loc_button->set_tooltip(TTR("Translation mask for inserting keys."));
animation_hb->add_child(key_loc_button);
key_rot_button = memnew(Button);
key_rot_button->set_toggle_mode(true);
@@ -4873,21 +4894,30 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
key_rot_button->set_pressed(true);
key_rot_button->set_focus_mode(FOCUS_NONE);
key_rot_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_ROT));
+ key_rot_button->set_tooltip(TTR("Rotation mask for inserting keys."));
animation_hb->add_child(key_rot_button);
key_scale_button = memnew(Button);
key_scale_button->set_toggle_mode(true);
key_scale_button->set_flat(true);
key_scale_button->set_focus_mode(FOCUS_NONE);
key_scale_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_SCALE));
+ key_scale_button->set_tooltip(TTR("Scale mask for inserting keys."));
animation_hb->add_child(key_scale_button);
key_insert_button = memnew(Button);
key_insert_button->set_flat(true);
key_insert_button->set_focus_mode(FOCUS_NONE);
key_insert_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_KEY));
- key_insert_button->set_tooltip(TTR("Insert keys."));
+ key_insert_button->set_tooltip(TTR("Insert keys (based on mask)."));
key_insert_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/anim_insert_key", TTR("Insert Key"), KEY_INSERT));
-
animation_hb->add_child(key_insert_button);
+ key_auto_insert_button = memnew(Button);
+ key_auto_insert_button->set_flat(true);
+ key_auto_insert_button->set_toggle_mode(true);
+ key_auto_insert_button->set_focus_mode(FOCUS_NONE);
+ //key_auto_insert_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_KEY));
+ key_auto_insert_button->set_tooltip(TTR("Auto insert keys when objects are translated, rotated on scaled (based on mask).\nKeys are only added to existing tracks, no new tracks will be created.\nKeys must be inserted manually for the first time."));
+ key_auto_insert_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/anim_auto_insert_key", TTR("Auto Insert Key")));
+ animation_hb->add_child(key_auto_insert_button);
animation_menu = memnew(MenuButton);
animation_menu->set_text(TTR("Animation"));
diff --git a/editor/plugins/canvas_item_editor_plugin.h b/editor/plugins/canvas_item_editor_plugin.h
index 9173c55ae0..14ea81f302 100644
--- a/editor/plugins/canvas_item_editor_plugin.h
+++ b/editor/plugins/canvas_item_editor_plugin.h
@@ -351,6 +351,7 @@ private:
Button *key_rot_button;
Button *key_scale_button;
Button *key_insert_button;
+ Button *key_auto_insert_button;
PopupMenu *selection_menu;
@@ -422,6 +423,8 @@ private:
Object *_get_editor_data(Object *p_what);
+ void _insert_animation_keys(bool p_location, bool p_rotation, bool p_scale, bool p_on_existing);
+
void _keying_changed();
void _unhandled_key_input(const Ref<InputEvent> &p_ev);
diff --git a/editor/plugins/item_list_editor_plugin.h b/editor/plugins/item_list_editor_plugin.h
index 679235e316..701632e576 100644
--- a/editor/plugins/item_list_editor_plugin.h
+++ b/editor/plugins/item_list_editor_plugin.h
@@ -157,7 +157,7 @@ public:
virtual void set_item_enabled(int p_idx, int p_enabled) { pp->set_item_disabled(p_idx, !p_enabled); }
virtual bool is_item_enabled(int p_idx) const { return !pp->is_item_disabled(p_idx); }
- virtual void set_item_id(int p_idx, int p_id) { pp->set_item_id(p_idx, p_idx); }
+ virtual void set_item_id(int p_idx, int p_id) { pp->set_item_id(p_idx, p_id); }
virtual int get_item_id(int p_idx) const { return pp->get_item_id(p_idx); }
virtual void set_item_separator(int p_idx, bool p_separator) { pp->set_item_as_separator(p_idx, p_separator); }
diff --git a/editor/plugins/mesh_instance_editor_plugin.cpp b/editor/plugins/mesh_instance_editor_plugin.cpp
index 3e10cdbbfa..cf111dc4ce 100644
--- a/editor/plugins/mesh_instance_editor_plugin.cpp
+++ b/editor/plugins/mesh_instance_editor_plugin.cpp
@@ -95,10 +95,7 @@ void MeshInstanceEditor::_menu_option(int p_option) {
return;
}
- if (trimesh_shape)
- ur->create_action(TTR("Create Static Trimesh Body"));
- else
- ur->create_action(TTR("Create Static Convex Body"));
+ ur->create_action(TTR("Create Static Trimesh Body"));
for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
@@ -132,8 +129,7 @@ void MeshInstanceEditor::_menu_option(int p_option) {
} break;
- case MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE:
- case MENU_OPTION_CREATE_CONVEX_COLLISION_SHAPE: {
+ case MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE: {
if (node == get_tree()->get_edited_scene_root()) {
err_dialog->set_text(TTR("This doesn't work on scene root!"));
@@ -141,9 +137,7 @@ void MeshInstanceEditor::_menu_option(int p_option) {
return;
}
- bool trimesh_shape = (p_option == MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE);
-
- Ref<Shape> shape = trimesh_shape ? mesh->create_trimesh_shape() : mesh->create_convex_shape();
+ Ref<Shape> shape = mesh->create_trimesh_shape();
if (shape.is_null())
return;
@@ -154,10 +148,7 @@ void MeshInstanceEditor::_menu_option(int p_option) {
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
- if (trimesh_shape)
- ur->create_action(TTR("Create Trimesh Shape"));
- else
- ur->create_action(TTR("Create Convex Shape"));
+ ur->create_action(TTR("Create Trimesh Static Shape"));
ur->add_do_method(node->get_parent(), "add_child", cshape);
ur->add_do_method(node->get_parent(), "move_child", cshape, node->get_index() + 1);
@@ -165,6 +156,40 @@ void MeshInstanceEditor::_menu_option(int p_option) {
ur->add_do_reference(cshape);
ur->add_undo_method(node->get_parent(), "remove_child", cshape);
ur->commit_action();
+ } break;
+ case MENU_OPTION_CREATE_CONVEX_COLLISION_SHAPE: {
+
+ if (node == get_tree()->get_edited_scene_root()) {
+ err_dialog->set_text(TTR("This doesn't work on scene root!"));
+ err_dialog->popup_centered_minsize();
+ return;
+ }
+
+ Vector<Ref<Shape> > shapes = mesh->convex_decompose();
+
+ if (!shapes.size()) {
+ err_dialog->set_text(TTR("Failed creating shapes!"));
+ err_dialog->popup_centered_minsize();
+ return;
+ }
+ UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
+
+ ur->create_action(TTR("Create Convex Shape(s)"));
+
+ for (int i = 0; i < shapes.size(); i++) {
+
+ CollisionShape *cshape = memnew(CollisionShape);
+ cshape->set_shape(shapes[i]);
+
+ Node *owner = node->get_owner();
+
+ ur->add_do_method(node->get_parent(), "add_child", cshape);
+ ur->add_do_method(node->get_parent(), "move_child", cshape, node->get_index() + 1);
+ ur->add_do_method(cshape, "set_owner", owner);
+ ur->add_do_reference(cshape);
+ ur->add_undo_method(node->get_parent(), "remove_child", cshape);
+ }
+ ur->commit_action();
} break;
@@ -393,10 +418,9 @@ MeshInstanceEditor::MeshInstanceEditor() {
options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("MeshInstance", "EditorIcons"));
options->get_popup()->add_item(TTR("Create Trimesh Static Body"), MENU_OPTION_CREATE_STATIC_TRIMESH_BODY);
- options->get_popup()->add_item(TTR("Create Convex Static Body"), MENU_OPTION_CREATE_STATIC_CONVEX_BODY);
options->get_popup()->add_separator();
options->get_popup()->add_item(TTR("Create Trimesh Collision Sibling"), MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE);
- options->get_popup()->add_item(TTR("Create Convex Collision Sibling"), MENU_OPTION_CREATE_CONVEX_COLLISION_SHAPE);
+ options->get_popup()->add_item(TTR("Create Convex Collision Sibling(s)"), MENU_OPTION_CREATE_CONVEX_COLLISION_SHAPE);
options->get_popup()->add_separator();
options->get_popup()->add_item(TTR("Create Navigation Mesh"), MENU_OPTION_CREATE_NAVMESH);
options->get_popup()->add_separator();
diff --git a/editor/plugins/mesh_library_editor_plugin.cpp b/editor/plugins/mesh_library_editor_plugin.cpp
index 89eb253afe..18586b2fe5 100644
--- a/editor/plugins/mesh_library_editor_plugin.cpp
+++ b/editor/plugins/mesh_library_editor_plugin.cpp
@@ -61,7 +61,8 @@ void MeshLibraryEditor::_menu_confirm() {
_import_scene_cbk(existing);
} break;
- default: {};
+ default: {
+ };
}
}
diff --git a/editor/plugins/polygon_2d_editor_plugin.cpp b/editor/plugins/polygon_2d_editor_plugin.cpp
index 0dbbaf4177..af43f679fd 100644
--- a/editor/plugins/polygon_2d_editor_plugin.cpp
+++ b/editor/plugins/polygon_2d_editor_plugin.cpp
@@ -905,7 +905,8 @@ void Polygon2DEditor::_uv_input(const Ref<InputEvent> &p_input) {
bone_paint_pos = Vector2(mm->get_position().x, mm->get_position().y);
} break;
- default: {}
+ default: {
+ }
}
if (bone_painting) {
diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp
index 42aba78e96..d7d4cec07d 100644
--- a/editor/plugins/script_editor_plugin.cpp
+++ b/editor/plugins/script_editor_plugin.cpp
@@ -1735,7 +1735,7 @@ void ScriptEditor::_update_script_names() {
String name = eh->get_class();
Ref<Texture> icon = get_icon("Help", "EditorIcons");
- String tooltip = name + TTR(" Class Reference");
+ String tooltip = vformat(TTR("%s Class Reference"), name);
_ScriptEditorItemData sd;
sd.icon = icon;
diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp
index 9fc42e3862..c586985957 100644
--- a/editor/plugins/script_text_editor.cpp
+++ b/editor/plugins/script_text_editor.cpp
@@ -81,6 +81,8 @@ void ScriptTextEditor::set_edited_resource(const RES &p_res) {
emit_signal("name_changed");
code_editor->update_line_and_column();
+
+ _validate_script();
}
void ScriptTextEditor::_update_member_keywords() {
@@ -286,7 +288,7 @@ void ScriptTextEditor::_warning_clicked(Variant p_line) {
code_editor->get_text_edit()->cursor_set_line(p_line.operator int64_t());
} else if (p_line.get_type() == Variant::DICTIONARY) {
Dictionary meta = p_line.operator Dictionary();
- code_editor->get_text_edit()->insert_at("#warning-ignore:" + meta["code"].operator String(), meta["line"].operator int64_t() - 1);
+ code_editor->get_text_edit()->insert_at("# warning-ignore:" + meta["code"].operator String(), meta["line"].operator int64_t() - 1);
_validate_script();
}
}
diff --git a/editor/plugins/spatial_editor_plugin.cpp b/editor/plugins/spatial_editor_plugin.cpp
index f48887d342..ba297539d3 100644
--- a/editor/plugins/spatial_editor_plugin.cpp
+++ b/editor/plugins/spatial_editor_plugin.cpp
@@ -1637,7 +1637,8 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
surface->update();
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1704,7 +1705,8 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1760,7 +1762,8 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/editor/plugins/sprite_editor_plugin.cpp b/editor/plugins/sprite_editor_plugin.cpp
index 3854d27567..fbc72b1396 100644
--- a/editor/plugins/sprite_editor_plugin.cpp
+++ b/editor/plugins/sprite_editor_plugin.cpp
@@ -31,7 +31,10 @@
#include "sprite_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
+#include "scene/2d/collision_polygon_2d.h"
+#include "scene/2d/light_occluder_2d.h"
#include "scene/2d/mesh_instance_2d.h"
+#include "scene/2d/polygon_2d.h"
#include "scene/gui/box_container.h"
#include "thirdparty/misc/clipper.hpp"
@@ -116,8 +119,42 @@ void SpriteEditor::_menu_option(int p_option) {
return;
}
+ selected_menu_item = (Menu)p_option;
+
switch (p_option) {
- case MENU_OPTION_CREATE_MESH_2D: {
+ case MENU_OPTION_CONVERT_TO_MESH_2D: {
+
+ debug_uv_dialog->get_ok()->set_text(TTR("Create Mesh2D"));
+ debug_uv_dialog->set_title("Mesh2D Preview");
+
+ _update_mesh_data();
+ debug_uv_dialog->popup_centered();
+ debug_uv->update();
+
+ } break;
+ case MENU_OPTION_CONVERT_TO_POLYGON_2D: {
+
+ debug_uv_dialog->get_ok()->set_text(TTR("Create Polygon2D"));
+ debug_uv_dialog->set_title("Polygon2D Preview");
+
+ _update_mesh_data();
+ debug_uv_dialog->popup_centered();
+ debug_uv->update();
+ } break;
+ case MENU_OPTION_CREATE_COLLISION_POLY_2D: {
+
+ debug_uv_dialog->get_ok()->set_text(TTR("Create CollisionPolygon2D"));
+ debug_uv_dialog->set_title("CollisionPolygon2D Preview");
+
+ _update_mesh_data();
+ debug_uv_dialog->popup_centered();
+ debug_uv->update();
+
+ } break;
+ case MENU_OPTION_CREATE_LIGHT_OCCLUDER_2D: {
+
+ debug_uv_dialog->get_ok()->set_text(TTR("Create LightOccluder2D"));
+ debug_uv_dialog->set_title("LightOccluder2D Preview");
_update_mesh_data();
debug_uv_dialog->popup_centered();
@@ -169,47 +206,107 @@ void SpriteEditor::_update_mesh_data() {
computed_indices.clear();
Size2 img_size = Vector2(image->get_width(), image->get_height());
- for (int j = 0; j < lines.size(); j++) {
- lines.write[j] = expand(lines[j], rect, epsilon);
+ for (int i = 0; i < lines.size(); i++) {
+ lines.write[i] = expand(lines[i], rect, epsilon);
+ }
+
+ if (selected_menu_item == MENU_OPTION_CONVERT_TO_MESH_2D) {
+
+ for (int j = 0; j < lines.size(); j++) {
+ int index_ofs = computed_vertices.size();
+
+ for (int i = 0; i < lines[j].size(); i++) {
+ Vector2 vtx = lines[j][i];
+ computed_uv.push_back(vtx / img_size);
- int index_ofs = computed_vertices.size();
+ vtx -= rect.position; //offset by rect position
- for (int i = 0; i < lines[j].size(); i++) {
- Vector2 vtx = lines[j][i];
- computed_uv.push_back(vtx / img_size);
+ //flip if flipped
+ if (node->is_flipped_h())
+ vtx.x = rect.size.x - vtx.x - 1.0;
+ if (node->is_flipped_v())
+ vtx.y = rect.size.y - vtx.y - 1.0;
- vtx -= rect.position; //offset by rect position
+ if (node->is_centered())
+ vtx -= rect.size / 2.0;
- //flip if flipped
- if (node->is_flipped_h())
- vtx.x = rect.size.x - vtx.x - 1.0;
- if (node->is_flipped_v())
- vtx.y = rect.size.y - vtx.y - 1.0;
+ computed_vertices.push_back(vtx);
+ }
+
+ Vector<int> poly = Geometry::triangulate_polygon(lines[j]);
- if (node->is_centered())
- vtx -= rect.size / 2.0;
+ for (int i = 0; i < poly.size(); i += 3) {
+ for (int k = 0; k < 3; k++) {
+ int idx = i + k;
+ int idxn = i + (k + 1) % 3;
+ uv_lines.push_back(lines[j][poly[idx]]);
+ uv_lines.push_back(lines[j][poly[idxn]]);
- computed_vertices.push_back(vtx);
+ computed_indices.push_back(poly[idx] + index_ofs);
+ }
+ }
}
+ }
- Vector<int> poly = Geometry::triangulate_polygon(lines[j]);
+ outline_lines.clear();
+ computed_outline_lines.clear();
- for (int i = 0; i < poly.size(); i += 3) {
- for (int k = 0; k < 3; k++) {
- int idx = i + k;
- int idxn = i + (k + 1) % 3;
- uv_lines.push_back(lines[j][poly[idx]]);
- uv_lines.push_back(lines[j][poly[idxn]]);
+ if (selected_menu_item == MENU_OPTION_CONVERT_TO_POLYGON_2D || selected_menu_item == MENU_OPTION_CREATE_COLLISION_POLY_2D || selected_menu_item == MENU_OPTION_CREATE_LIGHT_OCCLUDER_2D) {
+ outline_lines.resize(lines.size());
+ computed_outline_lines.resize(lines.size());
+ for (int pi = 0; pi < lines.size(); pi++) {
+
+ Vector<Vector2> ol;
+ Vector<Vector2> col;
+
+ ol.resize(lines[pi].size());
+ col.resize(lines[pi].size());
+
+ for (int i = 0; i < lines[pi].size(); i++) {
+ Vector2 vtx = lines[pi][i];
+
+ ol.write[i] = vtx;
+
+ vtx -= rect.position; //offset by rect position
+
+ //flip if flipped
+ if (node->is_flipped_h())
+ vtx.x = rect.size.x - vtx.x - 1.0;
+ if (node->is_flipped_v())
+ vtx.y = rect.size.y - vtx.y - 1.0;
+
+ if (node->is_centered())
+ vtx -= rect.size / 2.0;
- computed_indices.push_back(poly[idx] + index_ofs);
+ col.write[i] = vtx;
}
+
+ outline_lines.write[pi] = ol;
+ computed_outline_lines.write[pi] = col;
}
}
debug_uv->update();
}
-void SpriteEditor::_create_mesh_node() {
+void SpriteEditor::_create_node() {
+ switch (selected_menu_item) {
+ case MENU_OPTION_CONVERT_TO_MESH_2D: {
+ _convert_to_mesh_2d_node();
+ } break;
+ case MENU_OPTION_CONVERT_TO_POLYGON_2D: {
+ _convert_to_polygon_2d_node();
+ } break;
+ case MENU_OPTION_CREATE_COLLISION_POLY_2D: {
+ _create_collision_polygon_2d_node();
+ } break;
+ case MENU_OPTION_CREATE_LIGHT_OCCLUDER_2D: {
+ _create_light_occluder_2d_node();
+ } break;
+ }
+}
+
+void SpriteEditor::_convert_to_mesh_2d_node() {
if (computed_vertices.size() < 3) {
err_dialog->set_text(TTR("Invalid geometry, can't replace by mesh."));
@@ -233,6 +330,117 @@ void SpriteEditor::_create_mesh_node() {
EditorNode::get_singleton()->get_scene_tree_dock()->replace_node(node, mesh_instance);
}
+void SpriteEditor::_convert_to_polygon_2d_node() {
+ Polygon2D *polygon_2d_instance = memnew(Polygon2D);
+
+ int total_point_count = 0;
+ for (int i = 0; i < computed_outline_lines.size(); i++)
+ total_point_count += computed_outline_lines[i].size();
+
+ PoolVector2Array polygon;
+ polygon.resize(total_point_count);
+ PoolVector2Array::Write polygon_write = polygon.write();
+
+ PoolVector2Array uvs;
+ uvs.resize(total_point_count);
+ PoolVector2Array::Write uvs_write = uvs.write();
+
+ int current_point_index = 0;
+
+ Array polys;
+ polys.resize(computed_outline_lines.size());
+
+ for (int i = 0; i < computed_outline_lines.size(); i++) {
+
+ Vector<Vector2> outline = computed_outline_lines[i];
+ Vector<Vector2> uv_outline = outline_lines[i];
+
+ if (outline.size() < 3) {
+ err_dialog->set_text(TTR("Invalid geometry, can't create polygon."));
+ err_dialog->popup_centered_minsize();
+ return;
+ }
+
+ PoolIntArray pia;
+ pia.resize(outline.size());
+ PoolIntArray::Write pia_write = pia.write();
+
+ for (int pi = 0; pi < outline.size(); pi++) {
+ polygon_write[current_point_index] = outline[pi];
+ uvs_write[current_point_index] = uv_outline[pi];
+ pia_write[pi] = current_point_index;
+ current_point_index++;
+ }
+
+ polys[i] = pia;
+ }
+
+ polygon_2d_instance->set_uv(uvs);
+ polygon_2d_instance->set_polygon(polygon);
+ polygon_2d_instance->set_polygons(polys);
+
+ EditorNode::get_singleton()->get_scene_tree_dock()->replace_node(node, polygon_2d_instance);
+}
+
+void SpriteEditor::_create_collision_polygon_2d_node() {
+ for (int i = 0; i < computed_outline_lines.size(); i++) {
+
+ Vector<Vector2> outline = computed_outline_lines[i];
+
+ if (outline.size() < 3) {
+ err_dialog->set_text(TTR("Invalid geometry, can't create collision polygon."));
+ err_dialog->popup_centered_minsize();
+ continue;
+ }
+
+ CollisionPolygon2D *collision_polygon_2d_instance = memnew(CollisionPolygon2D);
+ collision_polygon_2d_instance->set_polygon(outline);
+
+ _add_as_sibling_or_child(node, collision_polygon_2d_instance);
+ }
+}
+
+void SpriteEditor::_create_light_occluder_2d_node() {
+ for (int i = 0; i < computed_outline_lines.size(); i++) {
+
+ Vector<Vector2> outline = computed_outline_lines[i];
+
+ if (outline.size() < 3) {
+ err_dialog->set_text(TTR("Invalid geometry, can't create light occluder."));
+ err_dialog->popup_centered_minsize();
+ continue;
+ }
+
+ Ref<OccluderPolygon2D> polygon;
+ polygon.instance();
+
+ PoolVector2Array a;
+ a.resize(outline.size());
+ PoolVector2Array::Write aw = a.write();
+ for (int io = 0; io < outline.size(); io++) {
+ aw[io] = outline[io];
+ }
+ polygon->set_polygon(a);
+
+ LightOccluder2D *light_occluder_2d_instance = memnew(LightOccluder2D);
+ light_occluder_2d_instance->set_occluder_polygon(polygon);
+
+ _add_as_sibling_or_child(node, light_occluder_2d_instance);
+ }
+}
+
+void SpriteEditor::_add_as_sibling_or_child(Node2D *p_own_node, Node2D *p_new_node) {
+ // Can't make sibling if own node is scene root
+ if (p_own_node != this->get_tree()->get_edited_scene_root()) {
+ p_own_node->get_parent()->add_child(p_new_node, true);
+ p_new_node->set_transform(p_own_node->get_transform());
+ } else {
+ p_own_node->add_child(p_new_node, true);
+ }
+
+ p_new_node->set_owner(this->get_tree()->get_edited_scene_root());
+}
+
#if 0
void SpriteEditor::_create_uv_lines() {
@@ -298,16 +506,26 @@ void SpriteEditor::_create_uv_lines() {
#endif
void SpriteEditor::_debug_uv_draw() {
- if (uv_lines.size() == 0)
- return;
-
Ref<Texture> tex = node->get_texture();
ERR_FAIL_COND(!tex.is_valid());
debug_uv->set_clip_contents(true);
debug_uv->draw_texture(tex, Point2());
debug_uv->set_custom_minimum_size(tex->get_size());
//debug_uv->draw_set_transform(Vector2(), 0, debug_uv->get_size());
- debug_uv->draw_multiline(uv_lines, Color(1.0, 0.8, 0.7));
+
+ Color color = Color(1.0, 0.8, 0.7);
+
+ if (selected_menu_item == MENU_OPTION_CONVERT_TO_MESH_2D && uv_lines.size() > 0) {
+ debug_uv->draw_multiline(uv_lines, color);
+
+ } else if ((selected_menu_item == MENU_OPTION_CONVERT_TO_POLYGON_2D || selected_menu_item == MENU_OPTION_CREATE_COLLISION_POLY_2D || selected_menu_item == MENU_OPTION_CREATE_LIGHT_OCCLUDER_2D) && outline_lines.size() > 0) {
+ for (int i = 0; i < outline_lines.size(); i++) {
+ Vector<Vector2> outline = outline_lines[i];
+
+ debug_uv->draw_polyline(outline, color);
+ debug_uv->draw_line(outline[0], outline[outline.size() - 1], color);
+ }
+ }
}
void SpriteEditor::_bind_methods() {
@@ -315,7 +533,7 @@ void SpriteEditor::_bind_methods() {
ClassDB::bind_method("_menu_option", &SpriteEditor::_menu_option);
ClassDB::bind_method("_debug_uv_draw", &SpriteEditor::_debug_uv_draw);
ClassDB::bind_method("_update_mesh_data", &SpriteEditor::_update_mesh_data);
- ClassDB::bind_method("_create_mesh_node", &SpriteEditor::_create_mesh_node);
+ ClassDB::bind_method("_create_node", &SpriteEditor::_create_node);
}
SpriteEditor::SpriteEditor() {
@@ -327,7 +545,10 @@ SpriteEditor::SpriteEditor() {
options->set_text(TTR("Sprite"));
options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("Sprite", "EditorIcons"));
- options->get_popup()->add_item(TTR("Convert to 2D Mesh"), MENU_OPTION_CREATE_MESH_2D);
+ options->get_popup()->add_item(TTR("Convert to Mesh2D"), MENU_OPTION_CONVERT_TO_MESH_2D);
+ options->get_popup()->add_item(TTR("Convert to Polygon2D"), MENU_OPTION_CONVERT_TO_POLYGON_2D);
+ options->get_popup()->add_item(TTR("Create CollisionPolygon2D Sibling"), MENU_OPTION_CREATE_COLLISION_POLY_2D);
+ options->get_popup()->add_item(TTR("Create LightOccluder2D Sibling"), MENU_OPTION_CREATE_LIGHT_OCCLUDER_2D);
options->get_popup()->connect("id_pressed", this, "_menu_option");
@@ -335,7 +556,7 @@ SpriteEditor::SpriteEditor() {
add_child(err_dialog);
debug_uv_dialog = memnew(ConfirmationDialog);
- debug_uv_dialog->get_ok()->set_text(TTR("Create 2D Mesh"));
+ debug_uv_dialog->get_ok()->set_text(TTR("Create Mesh2D"));
debug_uv_dialog->set_title("Mesh 2D Preview");
VBoxContainer *vb = memnew(VBoxContainer);
debug_uv_dialog->add_child(vb);
@@ -347,7 +568,7 @@ SpriteEditor::SpriteEditor() {
debug_uv = memnew(Control);
debug_uv->connect("draw", this, "_debug_uv_draw");
scroll->add_child(debug_uv);
- debug_uv_dialog->connect("confirmed", this, "_create_mesh_node");
+ debug_uv_dialog->connect("confirmed", this, "_create_node");
HBoxContainer *hb = memnew(HBoxContainer);
hb->add_child(memnew(Label(TTR("Simplification: "))));
diff --git a/editor/plugins/sprite_editor_plugin.h b/editor/plugins/sprite_editor_plugin.h
index 7250e3df59..460f5a5707 100644
--- a/editor/plugins/sprite_editor_plugin.h
+++ b/editor/plugins/sprite_editor_plugin.h
@@ -41,9 +41,14 @@ class SpriteEditor : public Control {
GDCLASS(SpriteEditor, Control);
enum Menu {
- MENU_OPTION_CREATE_MESH_2D,
+ MENU_OPTION_CONVERT_TO_MESH_2D,
+ MENU_OPTION_CONVERT_TO_POLYGON_2D,
+ MENU_OPTION_CREATE_COLLISION_POLY_2D,
+ MENU_OPTION_CREATE_LIGHT_OCCLUDER_2D
};
+ Menu selected_menu_item;
+
Sprite *node;
MenuButton *options;
@@ -55,7 +60,8 @@ class SpriteEditor : public Control {
ConfirmationDialog *debug_uv_dialog;
Control *debug_uv;
Vector<Vector2> uv_lines;
-
+ Vector<Vector<Vector2> > outline_lines;
+ Vector<Vector<Vector2> > computed_outline_lines;
Vector<Vector2> computed_vertices;
Vector<Vector2> computed_uv;
Vector<int> computed_indices;
@@ -71,7 +77,14 @@ class SpriteEditor : public Control {
void _debug_uv_draw();
void _update_mesh_data();
- void _create_mesh_node();
+
+ void _create_node();
+ void _convert_to_mesh_2d_node();
+ void _convert_to_polygon_2d_node();
+ void _create_collision_polygon_2d_node();
+ void _create_light_occluder_2d_node();
+
+ void _add_as_sibling_or_child(Node2D *p_own_node, Node2D *p_new_node);
protected:
void _node_removed(Node *p_node);
diff --git a/editor/plugins/sprite_frames_editor_plugin.cpp b/editor/plugins/sprite_frames_editor_plugin.cpp
index 5ba2fde763..33b8347f94 100644
--- a/editor/plugins/sprite_frames_editor_plugin.cpp
+++ b/editor/plugins/sprite_frames_editor_plugin.cpp
@@ -38,11 +38,167 @@
void SpriteFramesEditor::_gui_input(Ref<InputEvent> p_event) {
}
+void SpriteFramesEditor::_open_sprite_sheet() {
+
+ file_split_sheet->clear_filters();
+ List<String> extensions;
+ ResourceLoader::get_recognized_extensions_for_type("Texture", &extensions);
+ for (int i = 0; i < extensions.size(); i++) {
+ file_split_sheet->add_filter("*." + extensions[i]);
+ }
+
+ file_split_sheet->popup_centered_ratio();
+}
+
+void SpriteFramesEditor::_sheet_preview_draw() {
+ Size2i size = split_sheet_preview->get_size();
+ int h = split_sheet_h->get_value();
+ int v = split_sheet_v->get_value();
+ const float a = 0.3;
+ for (int i = 1; i < h; i++) {
+ for (int j = 1; j < v; j++) {
+
+ int x = i * size.width / h;
+ int y = i * size.height / v;
+
+ split_sheet_preview->draw_line(Point2(x, 0), Point2(x, size.height), Color(1, 1, 1, a));
+ split_sheet_preview->draw_line(Point2(x + 1, 0), Point2(x + 1, size.height), Color(0, 0, 0, a));
+
+ split_sheet_preview->draw_line(Point2(0, y), Point2(size.width, y), Color(1, 1, 1, a));
+ split_sheet_preview->draw_line(Point2(0, y + 1), Point2(size.width, y + 1), Color(0, 0, 0, a));
+ }
+ }
+
+ Color accent = get_color("accent_color", "Editor");
+
+ for (Set<int>::Element *E = frames_selected.front(); E; E = E->next()) {
+ int idx = E->get();
+ int x = (idx % h) * size.width / h;
+ int y = (idx / v) * size.height / v;
+ int width = size.width / h;
+ int height = size.height / v;
+
+ split_sheet_preview->draw_rect(Rect2(x + 5, y + 5, width - 10, height - 10), Color(0, 0, 0, 0.35), true);
+ split_sheet_preview->draw_rect(Rect2(x + 0, y + 0, width - 0, height - 0), Color(0, 0, 0, 1), false);
+ split_sheet_preview->draw_rect(Rect2(x + 1, y + 1, width - 2, height - 2), Color(0, 0, 0, 1), false);
+ split_sheet_preview->draw_rect(Rect2(x + 2, y + 2, width - 4, height - 4), accent, false);
+ split_sheet_preview->draw_rect(Rect2(x + 3, y + 3, width - 6, height - 6), accent, false);
+ split_sheet_preview->draw_rect(Rect2(x + 4, y + 4, width - 8, height - 8), Color(0, 0, 0, 1), false);
+ split_sheet_preview->draw_rect(Rect2(x + 5, y + 5, width - 10, height - 10), Color(0, 0, 0, 1), false);
+ }
+
+ if (frames_selected.size() == 0) {
+ split_sheet_dialog->get_ok()->set_disabled(true);
+ split_sheet_dialog->get_ok()->set_text(TTR("No frames selected"));
+ } else {
+ split_sheet_dialog->get_ok()->set_disabled(false);
+ split_sheet_dialog->get_ok()->set_text(vformat(TTR("Add %d frame(s)"), frames_selected.size()));
+ }
+}
+void SpriteFramesEditor::_sheet_preview_input(const Ref<InputEvent> &p_event) {
+
+ Ref<InputEventMouseButton> mb = p_event;
+
+ if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) {
+ Size2i size = split_sheet_preview->get_size();
+ int h = split_sheet_h->get_value();
+ int v = split_sheet_v->get_value();
+
+ int x = CLAMP(int(mb->get_position().x) * h / size.width, 0, h - 1);
+ int y = CLAMP(int(mb->get_position().y) * v / size.height, 0, v - 1);
+
+ int idx = h * y + x;
+
+ if (mb->get_shift() && last_frame_selected >= 0) {
+ //select multiple
+ int from = idx;
+ int to = last_frame_selected;
+ if (from > to) {
+ SWAP(from, to);
+ }
+
+ for (int i = from; i <= to; i++) {
+ if (mb->get_control()) {
+ frames_selected.erase(i);
+ } else {
+ frames_selected.insert(i);
+ }
+ }
+ } else {
+ if (frames_selected.has(idx)) {
+ frames_selected.erase(idx);
+ } else {
+ frames_selected.insert(idx);
+ }
+ }
+
+ last_frame_selected = idx;
+ split_sheet_preview->update();
+ }
+}
+
+void SpriteFramesEditor::_sheet_add_frames() {
+
+ Size2i size = split_sheet_preview->get_size();
+ int h = split_sheet_h->get_value();
+ int v = split_sheet_v->get_value();
+
+ undo_redo->create_action(TTR("Add Frame"));
+
+ int fc = frames->get_frame_count(edited_anim);
+
+ for (Set<int>::Element *E = frames_selected.front(); E; E = E->next()) {
+ int idx = E->get();
+ int x = (idx % h) * size.width / h;
+ int y = (idx / v) * size.height / v;
+ int width = size.width / h;
+ int height = size.height / v;
+
+ Ref<AtlasTexture> at;
+ at.instance();
+ at->set_atlas(split_sheet_preview->get_texture());
+ at->set_region(Rect2(x, y, width, height));
+
+ undo_redo->add_do_method(frames, "add_frame", edited_anim, at, -1);
+ undo_redo->add_undo_method(frames, "remove_frame", edited_anim, fc);
+ }
+
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
+ undo_redo->commit_action();
+}
+
+void SpriteFramesEditor::_sheet_spin_changed(double) {
+ frames_selected.clear();
+ last_frame_selected = -1;
+ split_sheet_preview->update();
+}
+
+void SpriteFramesEditor::_prepare_sprite_sheet(const String &p_file) {
+
+ Ref<Resource> texture = ResourceLoader::load(p_file);
+ if (!texture.is_valid()) {
+ EditorNode::get_singleton()->show_warning("Unable to load images");
+ ERR_FAIL_COND(!texture.is_valid());
+ }
+ if (texture != split_sheet_preview->get_texture()) {
+ //different texture, reset to 4x4
+ split_sheet_h->set_value(4);
+ split_sheet_v->set_value(4);
+ }
+ frames_selected.clear();
+ last_frame_selected = -1;
+
+ split_sheet_preview->set_texture(texture);
+ split_sheet_dialog->popup_centered_ratio(0.65);
+}
+
void SpriteFramesEditor::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE) {
load->set_icon(get_icon("Load", "EditorIcons"));
+ load_sheet->set_icon(get_icon("SpriteSheet", "EditorIcons"));
copy->set_icon(get_icon("ActionCopy", "EditorIcons"));
paste->set_icon(get_icon("ActionPaste", "EditorIcons"));
empty->set_icon(get_icon("InsertBefore", "EditorIcons"));
@@ -72,6 +228,7 @@ void SpriteFramesEditor::_file_load_request(const PoolVector<String> &p_path, in
if (resource.is_null()) {
dialog->set_text(TTR("ERROR: Couldn't load frame resource!"));
dialog->set_title(TTR("Error!"));
+
//dialog->get_cancel()->set_text("Close");
dialog->get_ok()->set_text(TTR("Close"));
dialog->popup_centered_minsize();
@@ -655,6 +812,12 @@ void SpriteFramesEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &SpriteFramesEditor::get_drag_data_fw);
ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &SpriteFramesEditor::can_drop_data_fw);
ClassDB::bind_method(D_METHOD("drop_data_fw"), &SpriteFramesEditor::drop_data_fw);
+ ClassDB::bind_method(D_METHOD("_prepare_sprite_sheet"), &SpriteFramesEditor::_prepare_sprite_sheet);
+ ClassDB::bind_method(D_METHOD("_open_sprite_sheet"), &SpriteFramesEditor::_open_sprite_sheet);
+ ClassDB::bind_method(D_METHOD("_sheet_preview_draw"), &SpriteFramesEditor::_sheet_preview_draw);
+ ClassDB::bind_method(D_METHOD("_sheet_preview_input"), &SpriteFramesEditor::_sheet_preview_input);
+ ClassDB::bind_method(D_METHOD("_sheet_spin_changed"), &SpriteFramesEditor::_sheet_spin_changed);
+ ClassDB::bind_method(D_METHOD("_sheet_add_frames"), &SpriteFramesEditor::_sheet_add_frames);
}
SpriteFramesEditor::SpriteFramesEditor() {
@@ -712,9 +875,15 @@ SpriteFramesEditor::SpriteFramesEditor() {
sub_vb->add_child(hbc);
load = memnew(ToolButton);
- load->set_tooltip(TTR("Load Resource"));
+ load->set_tooltip(TTR("Add a Texture from File"));
hbc->add_child(load);
+ load_sheet = memnew(ToolButton);
+ load_sheet->set_tooltip(TTR("Add frames from a Sprite Sheet"));
+ hbc->add_child(load_sheet);
+
+ hbc->add_child(memnew(VSeparator));
+
copy = memnew(ToolButton);
copy->set_tooltip(TTR("Copy"));
hbc->add_child(copy);
@@ -723,6 +892,8 @@ SpriteFramesEditor::SpriteFramesEditor() {
paste->set_tooltip(TTR("Paste"));
hbc->add_child(paste);
+ hbc->add_spacer(false);
+
empty = memnew(ToolButton);
empty->set_tooltip(TTR("Insert Empty (Before)"));
hbc->add_child(empty);
@@ -731,7 +902,7 @@ SpriteFramesEditor::SpriteFramesEditor() {
empty2->set_tooltip(TTR("Insert Empty (After)"));
hbc->add_child(empty2);
- hbc->add_spacer(false);
+ hbc->add_child(memnew(VSeparator));
move_up = memnew(ToolButton);
move_up->set_tooltip(TTR("Move (Before)"));
@@ -766,6 +937,7 @@ SpriteFramesEditor::SpriteFramesEditor() {
add_child(dialog);
load->connect("pressed", this, "_load_pressed");
+ load_sheet->connect("pressed", this, "_open_sprite_sheet");
_delete->connect("pressed", this, "_delete_pressed");
copy->connect("pressed", this, "_copy_pressed");
paste->connect("pressed", this, "_paste_pressed");
@@ -780,6 +952,60 @@ SpriteFramesEditor::SpriteFramesEditor() {
updating = false;
edited_anim = "default";
+
+ split_sheet_dialog = memnew(ConfirmationDialog);
+ add_child(split_sheet_dialog);
+ VBoxContainer *split_sheet_vb = memnew(VBoxContainer);
+ split_sheet_dialog->add_child(split_sheet_vb);
+ split_sheet_dialog->set_title(TTR("Select Frames"));
+ split_sheet_dialog->connect("confirmed", this, "_sheet_add_frames");
+
+ ScrollContainer *scroll = memnew(ScrollContainer);
+ split_sheet_preview = memnew(TextureRect);
+ split_sheet_preview->set_expand(false);
+ split_sheet_preview->set_mouse_filter(MOUSE_FILTER_PASS);
+ split_sheet_preview->connect("draw", this, "_sheet_preview_draw");
+ split_sheet_preview->connect("gui_input", this, "_sheet_preview_input");
+
+ scroll->set_enable_h_scroll(true);
+ scroll->set_enable_v_scroll(true);
+ CenterContainer *cc = memnew(CenterContainer);
+ cc->add_child(split_sheet_preview);
+ cc->set_h_size_flags(SIZE_EXPAND_FILL);
+ cc->set_v_size_flags(SIZE_EXPAND_FILL);
+ scroll->add_child(cc);
+
+ split_sheet_vb->add_margin_child(TTR("Base Image:"), scroll, true);
+
+ HBoxContainer *split_sheet_hb = memnew(HBoxContainer);
+ split_sheet_hb->add_spacer();
+ Label *ss_label = memnew(Label(TTR("Horizontal:")));
+ split_sheet_hb->add_child(ss_label);
+ split_sheet_h = memnew(SpinBox);
+ split_sheet_h->set_min(1);
+ split_sheet_h->set_max(128);
+ split_sheet_h->set_step(1);
+ split_sheet_hb->add_child(split_sheet_h);
+ split_sheet_hb->add_spacer();
+ split_sheet_h->connect("value_changed", this, "_sheet_spin_changed");
+
+ ss_label = memnew(Label(TTR("Vertical:")));
+ split_sheet_hb->add_child(ss_label);
+ split_sheet_v = memnew(SpinBox);
+ split_sheet_v->set_min(1);
+ split_sheet_v->set_max(128);
+ split_sheet_v->set_step(1);
+ split_sheet_hb->add_child(split_sheet_v);
+ split_sheet_hb->add_spacer();
+ split_sheet_v->connect("value_changed", this, "_sheet_spin_changed");
+
+ split_sheet_vb->add_margin_child(TTR("Split Settings:"), split_sheet_hb);
+
+ file_split_sheet = memnew(EditorFileDialog);
+ file_split_sheet->set_title(TTR("Create frames from Sprite Sheet"));
+ file_split_sheet->set_mode(EditorFileDialog::MODE_OPEN_FILE);
+ add_child(file_split_sheet);
+ file_split_sheet->connect("file_selected", this, "_prepare_sprite_sheet");
}
void SpriteFramesEditorPlugin::edit(Object *p_object) {
diff --git a/editor/plugins/sprite_frames_editor_plugin.h b/editor/plugins/sprite_frames_editor_plugin.h
index 55dd10074e..383e99f87e 100644
--- a/editor/plugins/sprite_frames_editor_plugin.h
+++ b/editor/plugins/sprite_frames_editor_plugin.h
@@ -37,6 +37,7 @@
#include "scene/gui/dialogs.h"
#include "scene/gui/file_dialog.h"
#include "scene/gui/split_container.h"
+#include "scene/gui/texture_rect.h"
#include "scene/gui/tree.h"
class SpriteFramesEditor : public HSplitContainer {
@@ -44,6 +45,7 @@ class SpriteFramesEditor : public HSplitContainer {
GDCLASS(SpriteFramesEditor, HSplitContainer);
ToolButton *load;
+ ToolButton *load_sheet;
ToolButton *_delete;
ToolButton *copy;
ToolButton *paste;
@@ -71,6 +73,14 @@ class SpriteFramesEditor : public HSplitContainer {
StringName edited_anim;
+ ConfirmationDialog *split_sheet_dialog;
+ TextureRect *split_sheet_preview;
+ SpinBox *split_sheet_h;
+ SpinBox *split_sheet_v;
+ EditorFileDialog *file_split_sheet;
+ Set<int> frames_selected;
+ int last_frame_selected;
+
void _load_pressed();
void _load_scene_pressed();
void _file_load_request(const PoolVector<String> &p_path, int p_at_pos = -1);
@@ -99,6 +109,13 @@ class SpriteFramesEditor : public HSplitContainer {
bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
+ void _open_sprite_sheet();
+ void _prepare_sprite_sheet(const String &p_file);
+ void _sheet_preview_draw();
+ void _sheet_spin_changed(double);
+ void _sheet_preview_input(const Ref<InputEvent> &p_event);
+ void _sheet_add_frames();
+
protected:
void _notification(int p_what);
void _gui_input(Ref<InputEvent> p_event);
diff --git a/editor/plugins/tile_set_editor_plugin.cpp b/editor/plugins/tile_set_editor_plugin.cpp
index 5bc1067718..8cf00cf67d 100644
--- a/editor/plugins/tile_set_editor_plugin.cpp
+++ b/editor/plugins/tile_set_editor_plugin.cpp
@@ -770,7 +770,8 @@ void TileSetEditor::_on_edit_mode_changed(int p_edit_mode) {
spin_z_index->show();
}
} break;
- default: {}
+ default: {
+ }
}
_update_toggle_shape_button();
workspace->update();
@@ -940,7 +941,8 @@ void TileSetEditor::_on_workspace_draw() {
spin_z_index->set_value(tileset->autotile_get_z_index(get_current_tile(), edited_shape_coord));
draw_highlight_subtile(edited_shape_coord);
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1036,25 +1038,26 @@ void TileSetEditor::_on_workspace_overlay_draw() {
tileset->get_tile_list(tiles);
for (List<int>::Element *E = tiles->front(); E; E = E->next()) {
int t_id = E->get();
- if (tileset->tile_get_texture(t_id)->get_rid() == current_texture_rid) {
- Rect2i region = tileset->tile_get_region(t_id);
- region.position += WORKSPACE_MARGIN;
- region.position *= workspace->get_scale().x;
- Color c;
- if (tileset->tile_get_tile_mode(t_id) == TileSet::SINGLE_TILE)
- c = COLOR_SINGLE;
- else if (tileset->tile_get_tile_mode(t_id) == TileSet::AUTO_TILE)
- c = COLOR_AUTOTILE;
- else if (tileset->tile_get_tile_mode(t_id) == TileSet::ATLAS_TILE)
- c = COLOR_ATLAS;
- String tile_id_name = String::num(t_id, 0) + ": " + tileset->tile_get_name(t_id);
- Ref<Font> font = get_font("font", "Label");
- region.set_size(font->get_string_size(tile_id_name));
- workspace_overlay->draw_rect(region, c);
- region.position.y += region.size.y - 2;
- c = Color(0.1, 0.1, 0.1);
- workspace_overlay->draw_string(font, region.position, tile_id_name, c);
- }
+ if (tileset->tile_get_texture(t_id)->get_rid() != current_texture_rid)
+ continue;
+
+ Rect2 region = tileset->tile_get_region(t_id);
+ region.position += WORKSPACE_MARGIN;
+ region.position *= workspace->get_scale().x;
+ Color c;
+ if (tileset->tile_get_tile_mode(t_id) == TileSet::SINGLE_TILE)
+ c = COLOR_SINGLE;
+ else if (tileset->tile_get_tile_mode(t_id) == TileSet::AUTO_TILE)
+ c = COLOR_AUTOTILE;
+ else if (tileset->tile_get_tile_mode(t_id) == TileSet::ATLAS_TILE)
+ c = COLOR_ATLAS;
+ String tile_id_name = String::num(t_id, 0) + ": " + tileset->tile_get_name(t_id);
+ Ref<Font> font = get_font("font", "Label");
+ region.set_size(font->get_string_size(tile_id_name));
+ workspace_overlay->draw_rect(region, c);
+ region.position.y += region.size.y - 2;
+ c = Color(0.1, 0.1, 0.1);
+ workspace_overlay->draw_string(font, region.position, tile_id_name, c);
}
}
@@ -1570,7 +1573,8 @@ void TileSetEditor::_on_workspace_input(const Ref<InputEvent> &p_ie) {
}
}
} break;
- default: {}
+ default: {
+ }
}
}
}
@@ -1724,7 +1728,8 @@ void TileSetEditor::_on_tool_clicked(int p_tool) {
undo_redo->commit_action();
}
} break;
- default: {}
+ default: {
+ }
}
}
} else if (p_tool == TOOL_SELECT) {
@@ -1894,7 +1899,8 @@ void TileSetEditor::_select_next_tile() {
edited_shape_coord = Vector2();
_select_edited_shape_coord();
} break;
- default: {}
+ default: {
+ }
}
}
}
@@ -1931,7 +1937,8 @@ void TileSetEditor::_select_previous_tile() {
edited_shape_coord = cell_count;
_select_edited_shape_coord();
} break;
- default: {}
+ default: {
+ }
}
}
}
@@ -2668,7 +2675,8 @@ void TileSetEditor::draw_polygon_shapes() {
}
}
} break;
- default: {}
+ default: {
+ }
}
if (creating_shape) {
diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp
index f71ff84bbe..0aba7f3d15 100644
--- a/editor/plugins/visual_shader_editor_plugin.cpp
+++ b/editor/plugins/visual_shader_editor_plugin.cpp
@@ -453,7 +453,8 @@ void VisualShaderEditor::_update_graph() {
Vector3 v = default_value;
button->set_text(String::num(v.x, 3) + "," + String::num(v.y, 3) + "," + String::num(v.z, 3));
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1003,6 +1004,58 @@ void VisualShaderEditor::_duplicate_nodes() {
}
}
+void VisualShaderEditor::_on_nodes_delete() {
+
+ VisualShader::Type type = VisualShader::Type(edit_type->get_selected());
+ List<int> to_erase;
+
+ for (int i = 0; i < graph->get_child_count(); i++) {
+ GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
+ if (gn) {
+ if (gn->is_selected() && gn->is_close_button_visible()) {
+ to_erase.push_back(gn->get_name().operator String().to_int());
+ }
+ }
+ }
+
+ if (to_erase.empty())
+ return;
+
+ undo_redo->create_action(TTR("Delete Nodes"));
+
+ for (List<int>::Element *F = to_erase.front(); F; F = F->next()) {
+ undo_redo->add_do_method(visual_shader.ptr(), "remove_node", type, F->get());
+ undo_redo->add_undo_method(visual_shader.ptr(), "add_node", type, visual_shader->get_node(type, F->get()), visual_shader->get_node_position(type, F->get()), F->get());
+ }
+
+ List<VisualShader::Connection> conns;
+ visual_shader->get_node_connections(type, &conns);
+
+ List<VisualShader::Connection> used_conns;
+ for (List<int>::Element *F = to_erase.front(); F; F = F->next()) {
+ for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) {
+ if (E->get().from_node == F->get() || E->get().to_node == F->get()) {
+
+ bool cancel = false;
+ for (List<VisualShader::Connection>::Element *R = used_conns.front(); R; R = R->next()) {
+ if (R->get().from_node == E->get().from_node && R->get().from_port == E->get().from_port && R->get().to_node == E->get().to_node && R->get().to_port == E->get().to_port) {
+ cancel = true; // to avoid ERR_ALREADY_EXISTS warning
+ break;
+ }
+ }
+ if (!cancel) {
+ undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
+ used_conns.push_back(E->get());
+ }
+ }
+ }
+ }
+
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
+ undo_redo->commit_action();
+}
+
void VisualShaderEditor::_mode_selected(int p_id) {
_update_options_menu();
_update_graph();
@@ -1174,6 +1227,7 @@ void VisualShaderEditor::_bind_methods() {
ClassDB::bind_method("_node_selected", &VisualShaderEditor::_node_selected);
ClassDB::bind_method("_scroll_changed", &VisualShaderEditor::_scroll_changed);
ClassDB::bind_method("_delete_request", &VisualShaderEditor::_delete_request);
+ ClassDB::bind_method("_on_nodes_delete", &VisualShaderEditor::_on_nodes_delete);
ClassDB::bind_method("_node_changed", &VisualShaderEditor::_node_changed);
ClassDB::bind_method("_edit_port_default_input", &VisualShaderEditor::_edit_port_default_input);
ClassDB::bind_method("_port_edited", &VisualShaderEditor::_port_edited);
@@ -1223,6 +1277,7 @@ VisualShaderEditor::VisualShaderEditor() {
graph->connect("node_selected", this, "_node_selected");
graph->connect("scroll_offset_changed", this, "_scroll_changed");
graph->connect("duplicate_nodes_request", this, "_duplicate_nodes");
+ graph->connect("delete_nodes_request", this, "_on_nodes_delete");
graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR);
graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_VECTOR);
graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_BOOLEAN);
@@ -1345,9 +1400,10 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("ColorUniform", "Color", "Variables", "VisualShaderNodeColorUniform", TTR("Color uniform."), -1, VisualShaderNode::PORT_TYPE_COLOR));
// BOOLEAN
-
- add_options.push_back(AddOption("BooleanConstant", "Boolean", "Variables", "VisualShaderNodeBooleanConstant", TTR("Boolean constant."), -1, VisualShaderNode::PORT_TYPE_BOOLEAN));
- add_options.push_back(AddOption("BooleanUniform", "Boolean", "Variables", "VisualShaderNodeBooleanUniform", TTR("Boolean uniform."), -1, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("If", "Conditional", "Functions", "VisualShaderNodeIf", TTR("Returns an associated vector if the provided scalars are equal, greater or less."), -1, VisualShaderNode::PORT_TYPE_VECTOR));
+ add_options.push_back(AddOption("Switch", "Conditional", "Functions", "VisualShaderNodeSwitch", TTR("Returns an associated vector if the provided boolean value is true or false."), -1, VisualShaderNode::PORT_TYPE_VECTOR));
+ add_options.push_back(AddOption("BooleanConstant", "Conditional", "Variables", "VisualShaderNodeBooleanConstant", TTR("Boolean constant."), -1, VisualShaderNode::PORT_TYPE_BOOLEAN));
+ add_options.push_back(AddOption("BooleanUniform", "Conditional", "Variables", "VisualShaderNodeBooleanUniform", TTR("Boolean uniform."), -1, VisualShaderNode::PORT_TYPE_BOOLEAN));
// INPUT
diff --git a/editor/plugins/visual_shader_editor_plugin.h b/editor/plugins/visual_shader_editor_plugin.h
index 2709d72931..4b0b48ad92 100644
--- a/editor/plugins/visual_shader_editor_plugin.h
+++ b/editor/plugins/visual_shader_editor_plugin.h
@@ -143,6 +143,7 @@ class VisualShaderEditor : public VBoxContainer {
void _node_selected(Object *p_node);
void _delete_request(int);
+ void _on_nodes_delete();
void _removed_from_graph();
diff --git a/editor/project_settings_editor.cpp b/editor/project_settings_editor.cpp
index bb72c621be..2d7ad8bc04 100644
--- a/editor/project_settings_editor.cpp
+++ b/editor/project_settings_editor.cpp
@@ -294,7 +294,8 @@ void ProjectSettingsEditor::_device_input_add() {
ie = jb;
} break;
- default: {}
+ default: {
+ }
}
if (idx < 0 || idx >= events.size()) {
@@ -519,7 +520,8 @@ void ProjectSettingsEditor::_add_item(int p_item, Ref<InputEvent> p_exiting_even
}
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/editor/property_editor.cpp b/editor/property_editor.cpp
index c45a97800c..4fa1bd74fe 100644
--- a/editor/property_editor.cpp
+++ b/editor/property_editor.cpp
@@ -310,7 +310,8 @@ void CustomPropertyEditor::_menu_option(int p_which) {
}
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1049,7 +1050,8 @@ bool CustomPropertyEditor::edit(Object *p_owner, const String &p_name, Variant::
case Variant::POOL_COLOR_ARRAY: {
} break;
- default: {}
+ default: {
+ }
}
updating = false;
@@ -1091,7 +1093,8 @@ void CustomPropertyEditor::_file_selected(String p_file) {
emit_signal("variant_changed");
hide();
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1432,7 +1435,8 @@ void CustomPropertyEditor::_action_pressed(int p_which) {
} break;
- default: {};
+ default: {
+ };
}
}
@@ -1699,7 +1703,8 @@ void CustomPropertyEditor::_modified(String p_string) {
case Variant::POOL_COLOR_ARRAY: {
} break;
- default: {}
+ default: {
+ }
}
updating = false;
@@ -1753,7 +1758,8 @@ void CustomPropertyEditor::_focus_enter() {
}
}
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1774,7 +1780,8 @@ void CustomPropertyEditor::_focus_exit() {
value_editor[i]->select(0, 0);
}
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp
index 7e4861cd09..bd245d5da9 100644
--- a/editor/scene_tree_dock.cpp
+++ b/editor/scene_tree_dock.cpp
@@ -290,12 +290,18 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
switch (p_tool) {
case TOOL_BATCH_RENAME: {
+ if (!profile_allow_editing) {
+ break;
+ }
Tree *tree = scene_tree->get_scene_tree();
if (tree->is_anything_selected()) {
rename_dialog->popup_centered();
}
} break;
case TOOL_RENAME: {
+ if (!profile_allow_editing) {
+ break;
+ }
Tree *tree = scene_tree->get_scene_tree();
if (tree->is_anything_selected()) {
tree->grab_focus();
@@ -304,6 +310,9 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} break;
case TOOL_NEW: {
+ if (!profile_allow_editing) {
+ break;
+ }
String preferred = "";
Node *current_edited_scene_root = EditorNode::get_singleton()->get_edited_scene();
@@ -319,6 +328,9 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} break;
case TOOL_INSTANCE: {
+ if (!profile_allow_editing) {
+ break;
+ }
Node *scene = edited_scene;
if (!scene) {
@@ -332,10 +344,17 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} break;
case TOOL_REPLACE: {
+ if (!profile_allow_editing) {
+ break;
+ }
create_dialog->popup_create(false, true);
} break;
case TOOL_ATTACH_SCRIPT: {
+ if (!profile_allow_script_editing) {
+ break;
+ }
+
List<Node *> selection = editor_selection->get_selected_node_list();
if (selection.empty())
break;
@@ -377,6 +396,10 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} break;
case TOOL_CLEAR_SCRIPT: {
+ if (!profile_allow_script_editing) {
+ break;
+ }
+
Array selection = editor_selection->get_selected_nodes();
if (selection.empty())
@@ -404,6 +427,10 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
case TOOL_MOVE_UP:
case TOOL_MOVE_DOWN: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
if (!scene_tree->get_selected())
break;
@@ -464,6 +491,10 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} break;
case TOOL_DUPLICATE: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
if (!edited_scene)
break;
@@ -533,6 +564,10 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} break;
case TOOL_REPARENT: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
if (!scene_tree->get_selected())
break;
@@ -559,6 +594,10 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} break;
case TOOL_MAKE_ROOT: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
List<Node *> nodes = editor_selection->get_selected_node_list();
ERR_FAIL_COND(nodes.size() != 1);
@@ -616,6 +655,10 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} break;
case TOOL_MULTI_EDIT: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
Node *root = EditorNode::get_singleton()->get_edited_scene();
if (!root)
break;
@@ -630,6 +673,10 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
case TOOL_ERASE: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
List<Node *> remove_list = editor_selection->get_selected_node_list();
if (remove_list.empty())
@@ -649,10 +696,18 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
} break;
case TOOL_MERGE_FROM_SCENE: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
EditorNode::get_singleton()->merge_from_scene();
} break;
case TOOL_NEW_SCENE_FROM: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
Node *scene = editor_data->get_edited_scene_root();
if (!scene) {
@@ -704,6 +759,7 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
new_scene_from_dialog->set_title(TTR("Save New Scene As..."));
} break;
case TOOL_COPY_NODE_PATH: {
+
List<Node *> selection = editor_selection->get_selected_node_list();
List<Node *>::Element *e = selection.front();
if (e) {
@@ -723,6 +779,11 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT);
} break;
case TOOL_SCENE_EDITABLE_CHILDREN: {
+
+ if (!profile_allow_editing) {
+ break;
+ }
+
List<Node *> selection = editor_selection->get_selected_node_list();
List<Node *>::Element *e = selection.front();
if (e) {
@@ -740,6 +801,11 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
}
} break;
case TOOL_SCENE_USE_PLACEHOLDER: {
+
+ if (!profile_allow_editing) {
+ break;
+ }
+
List<Node *> selection = editor_selection->get_selected_node_list();
List<Node *>::Element *e = selection.front();
if (e) {
@@ -760,6 +826,11 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
}
} break;
case TOOL_SCENE_MAKE_LOCAL: {
+
+ if (!profile_allow_editing) {
+ break;
+ }
+
List<Node *> selection = editor_selection->get_selected_node_list();
List<Node *>::Element *e = selection.front();
if (e) {
@@ -782,6 +853,7 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
}
} break;
case TOOL_SCENE_OPEN: {
+
List<Node *> selection = editor_selection->get_selected_node_list();
List<Node *>::Element *e = selection.front();
if (e) {
@@ -792,9 +864,17 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
}
} break;
case TOOL_SCENE_CLEAR_INHERITANCE: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
clear_inherit_confirm->popup_centered_minsize();
} break;
case TOOL_SCENE_CLEAR_INHERITANCE_CONFIRM: {
+ if (!profile_allow_editing) {
+ break;
+ }
+
List<Node *> selection = editor_selection->get_selected_node_list();
List<Node *>::Element *e = selection.front();
if (e) {
@@ -807,6 +887,7 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
}
} break;
case TOOL_SCENE_OPEN_INHERITED: {
+
List<Node *> selection = editor_selection->get_selected_node_list();
List<Node *>::Element *e = selection.front();
if (e) {
@@ -894,6 +975,8 @@ void SceneTreeDock::_notification(int p_what) {
break;
first_enter = false;
+ EditorFeatureProfileManager::get_singleton()->connect("current_feature_profile_changed", this, "_feature_profile_changed");
+
CanvasItemEditorPlugin *canvas_item_plugin = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor("2D"));
if (canvas_item_plugin) {
canvas_item_plugin->get_canvas_item_editor()->connect("item_lock_status_changed", scene_tree, "_update_tree");
@@ -1640,7 +1723,12 @@ void SceneTreeDock::_delete_confirm() {
}
void SceneTreeDock::_update_script_button() {
- if (EditorNode::get_singleton()->get_editor_selection()->get_selection().size() == 0) {
+
+ if (!profile_allow_script_editing) {
+
+ button_create_script->hide();
+ button_clear_script->hide();
+ } else if (EditorNode::get_singleton()->get_editor_selection()->get_selection().size() == 0) {
button_create_script->hide();
button_clear_script->hide();
} else if (EditorNode::get_singleton()->get_editor_selection()->get_selection().size() == 1) {
@@ -1653,7 +1741,7 @@ void SceneTreeDock::_update_script_button() {
button_clear_script->show();
}
} else {
- button_create_script->show();
+ button_create_script->hide();
Array selection = editor_selection->get_selected_nodes();
for (int i = 0; i < selection.size(); i++) {
Node *n = Object::cast_to<Node>(selection[i]);
@@ -1760,6 +1848,8 @@ void SceneTreeDock::_create() {
replace_node(n, newnode);
}
}
+
+ scene_tree->get_scene_tree()->call_deferred("grab_focus");
}
void SceneTreeDock::replace_node(Node *p_node, Node *p_by_node, bool p_keep_properties) {
@@ -2074,11 +2164,14 @@ void SceneTreeDock::_add_children_to_popup(Object *p_obj, int p_depth) {
}
void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) {
+
if (!EditorNode::get_singleton()->get_edited_scene()) {
menu->clear();
- menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW);
- menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE);
+ if (profile_allow_editing) {
+ menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW);
+ menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE);
+ }
menu->set_size(Size2(1, 1));
menu->set_position(p_menu_pos);
@@ -2098,80 +2191,101 @@ void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) {
Node *selected = selection[0];
- subresources.clear();
- menu_subresources->clear();
- menu_subresources->set_size(Size2(1, 1));
- _add_children_to_popup(selection.front()->get(), 0);
- if (menu->get_item_count() > 0)
- menu->add_separator();
+ if (profile_allow_editing) {
+ subresources.clear();
+ menu_subresources->clear();
+ menu_subresources->set_size(Size2(1, 1));
+ _add_children_to_popup(selection.front()->get(), 0);
+ if (menu->get_item_count() > 0)
+ menu->add_separator();
- menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW);
- menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE);
- menu->add_separator();
+ menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW);
+ menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE);
+ menu->add_separator();
+ }
existing_script = selected->get_script();
}
- if (!existing_script.is_valid()) {
- menu->add_icon_shortcut(get_icon("ScriptCreate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/attach_script"), TOOL_ATTACH_SCRIPT);
- }
- if (selection.size() > 1 || existing_script.is_valid()) {
- menu->add_icon_shortcut(get_icon("ScriptRemove", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/clear_script"), TOOL_CLEAR_SCRIPT);
- menu->add_icon_shortcut(get_icon("ScriptExtend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/extend_script"), TOOL_ATTACH_SCRIPT);
- }
+ if (profile_allow_script_editing) {
- menu->add_separator();
- if (selection.size() == 1) {
- menu->add_icon_shortcut(get_icon("Rename", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/rename"), TOOL_RENAME);
+ if (selection.size() == 1) {
+ if (!existing_script.is_valid()) {
+ menu->add_icon_shortcut(get_icon("ScriptCreate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/attach_script"), TOOL_ATTACH_SCRIPT);
+ } else {
+ menu->add_icon_shortcut(get_icon("ScriptExtend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/extend_script"), TOOL_ATTACH_SCRIPT);
+ }
+ }
+ if (selection.size() > 1 || existing_script.is_valid()) {
+ menu->add_icon_shortcut(get_icon("ScriptRemove", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/clear_script"), TOOL_CLEAR_SCRIPT);
+ }
+ menu->add_separator();
}
- menu->add_icon_shortcut(get_icon("Reload", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/change_node_type"), TOOL_REPLACE);
- if (scene_tree->get_selected() != edited_scene) {
- menu->add_separator();
- menu->add_icon_shortcut(get_icon("MoveUp", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_up"), TOOL_MOVE_UP);
- menu->add_icon_shortcut(get_icon("MoveDown", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_down"), TOOL_MOVE_DOWN);
- menu->add_icon_shortcut(get_icon("Duplicate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/duplicate"), TOOL_DUPLICATE);
- menu->add_icon_shortcut(get_icon("Reparent", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/reparent"), TOOL_REPARENT);
+ if (profile_allow_editing) {
+ if (selection.size() == 1) {
+ menu->add_icon_shortcut(get_icon("Rename", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/rename"), TOOL_RENAME);
+ }
+ menu->add_icon_shortcut(get_icon("Reload", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/change_node_type"), TOOL_REPLACE);
+
+ if (scene_tree->get_selected() != edited_scene) {
+ menu->add_separator();
+ menu->add_icon_shortcut(get_icon("MoveUp", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_up"), TOOL_MOVE_UP);
+ menu->add_icon_shortcut(get_icon("MoveDown", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_down"), TOOL_MOVE_DOWN);
+ menu->add_icon_shortcut(get_icon("Duplicate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/duplicate"), TOOL_DUPLICATE);
+ menu->add_icon_shortcut(get_icon("Reparent", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/reparent"), TOOL_REPARENT);
+ menu->add_icon_shortcut(get_icon("NewRoot", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/make_root"), TOOL_MAKE_ROOT);
+ }
}
if (selection.size() == 1) {
- menu->add_icon_shortcut(get_icon("NewRoot", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/make_root"), TOOL_MAKE_ROOT);
- menu->add_separator();
- menu->add_icon_shortcut(get_icon("Blend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/merge_from_scene"), TOOL_MERGE_FROM_SCENE);
- menu->add_icon_shortcut(get_icon("CreateNewSceneFrom", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/save_branch_as_scene"), TOOL_NEW_SCENE_FROM);
- menu->add_separator();
+ if (profile_allow_editing) {
+ menu->add_separator();
+ menu->add_icon_shortcut(get_icon("Blend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/merge_from_scene"), TOOL_MERGE_FROM_SCENE);
+ menu->add_icon_shortcut(get_icon("CreateNewSceneFrom", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/save_branch_as_scene"), TOOL_NEW_SCENE_FROM);
+ menu->add_separator();
+ }
menu->add_icon_shortcut(get_icon("CopyNodePath", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/copy_node_path"), TOOL_COPY_NODE_PATH);
+
bool is_external = (selection[0]->get_filename() != "");
if (is_external) {
bool is_inherited = selection[0]->get_scene_inherited_state() != NULL;
bool is_top_level = selection[0]->get_owner() == NULL;
if (is_inherited && is_top_level) {
menu->add_separator();
- menu->add_item(TTR("Clear Inheritance"), TOOL_SCENE_CLEAR_INHERITANCE);
+ if (profile_allow_editing) {
+ menu->add_item(TTR("Clear Inheritance"), TOOL_SCENE_CLEAR_INHERITANCE);
+ }
menu->add_icon_item(get_icon("Load", "EditorIcons"), TTR("Open in Editor"), TOOL_SCENE_OPEN_INHERITED);
} else if (!is_top_level) {
menu->add_separator();
bool editable = EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(selection[0]);
bool placeholder = selection[0]->get_scene_instance_load_placeholder();
- menu->add_check_item(TTR("Editable Children"), TOOL_SCENE_EDITABLE_CHILDREN);
- menu->add_check_item(TTR("Load As Placeholder"), TOOL_SCENE_USE_PLACEHOLDER);
- menu->add_item(TTR("Make Local"), TOOL_SCENE_MAKE_LOCAL);
+ if (profile_allow_editing) {
+ menu->add_check_item(TTR("Editable Children"), TOOL_SCENE_EDITABLE_CHILDREN);
+ menu->add_check_item(TTR("Load As Placeholder"), TOOL_SCENE_USE_PLACEHOLDER);
+ menu->add_item(TTR("Make Local"), TOOL_SCENE_MAKE_LOCAL);
+ }
menu->add_icon_item(get_icon("Load", "EditorIcons"), TTR("Open in Editor"), TOOL_SCENE_OPEN);
- menu->set_item_checked(menu->get_item_idx_from_text(TTR("Editable Children")), editable);
- menu->set_item_checked(menu->get_item_idx_from_text(TTR("Load As Placeholder")), placeholder);
+ if (profile_allow_editing) {
+ menu->set_item_checked(menu->get_item_idx_from_text(TTR("Editable Children")), editable);
+ menu->set_item_checked(menu->get_item_idx_from_text(TTR("Load As Placeholder")), placeholder);
+ }
}
}
}
- if (selection.size() > 1) {
+ if (profile_allow_editing && selection.size() > 1) {
//this is not a commonly used action, it makes no sense for it to be where it was nor always present.
menu->add_separator();
menu->add_icon_shortcut(get_icon("Rename", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/batch_rename"), TOOL_BATCH_RENAME);
}
menu->add_separator();
- menu->add_icon_item(get_icon("Help", "EditorIcons"), TTR("Open documentation"), TOOL_OPEN_DOCUMENTATION);
+ menu->add_icon_item(get_icon("Help", "EditorIcons"), TTR("Open Documentation"), TOOL_OPEN_DOCUMENTATION);
- menu->add_separator();
- menu->add_icon_shortcut(get_icon("Remove", "EditorIcons"), ED_SHORTCUT("scene_tree/delete", TTR("Delete Node(s)"), KEY_DELETE), TOOL_ERASE);
+ if (profile_allow_editing) {
+ menu->add_separator();
+ menu->add_icon_shortcut(get_icon("Remove", "EditorIcons"), ED_SHORTCUT("scene_tree/delete", TTR("Delete Node(s)"), KEY_DELETE), TOOL_ERASE);
+ }
menu->set_size(Size2(1, 1));
menu->set_position(p_menu_pos);
menu->popup();
@@ -2321,6 +2435,30 @@ void SceneTreeDock::_favorite_root_selected(const String &p_class) {
_tool_selected(TOOL_CREATE_FAVORITE, false);
}
+void SceneTreeDock::_feature_profile_changed() {
+
+ Ref<EditorFeatureProfile> profile = EditorFeatureProfileManager::get_singleton()->get_current_profile();
+
+ if (profile.is_valid()) {
+
+ profile_allow_editing = !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_SCENE_TREE);
+ profile_allow_script_editing = !profile->is_feature_disabled(EditorFeatureProfile::FEATURE_SCRIPT);
+
+ button_add->set_visible(profile_allow_editing);
+ button_instance->set_visible(profile_allow_editing);
+ scene_tree->set_can_rename(profile_allow_editing);
+
+ } else {
+ button_add->set_visible(true);
+ button_instance->set_visible(true);
+ scene_tree->set_can_rename(true);
+ profile_allow_editing = true;
+ profile_allow_script_editing = true;
+ }
+
+ _update_script_button();
+}
+
void SceneTreeDock::_bind_methods() {
ClassDB::bind_method(D_METHOD("_tool_selected"), &SceneTreeDock::_tool_selected, DEFVAL(false));
@@ -2353,6 +2491,7 @@ void SceneTreeDock::_bind_methods() {
ClassDB::bind_method(D_METHOD("_update_script_button"), &SceneTreeDock::_update_script_button);
ClassDB::bind_method(D_METHOD("_favorite_root_selected"), &SceneTreeDock::_favorite_root_selected);
ClassDB::bind_method(D_METHOD("_update_create_root_dialog"), &SceneTreeDock::_update_create_root_dialog);
+ ClassDB::bind_method(D_METHOD("_feature_profile_changed"), &SceneTreeDock::_feature_profile_changed);
ClassDB::bind_method(D_METHOD("instance"), &SceneTreeDock::instance);
@@ -2372,7 +2511,6 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel
HBoxContainer *filter_hbc = memnew(HBoxContainer);
filter_hbc->add_constant_override("separate", 0);
- ToolButton *tb;
ED_SHORTCUT("scene_tree/rename", TTR("Rename"));
ED_SHORTCUT("scene_tree/batch_rename", TTR("Batch Rename"), KEY_MASK_CMD | KEY_F2);
@@ -2393,19 +2531,17 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel
ED_SHORTCUT("scene_tree/delete_no_confirm", TTR("Delete (No Confirm)"), KEY_MASK_SHIFT | KEY_DELETE);
ED_SHORTCUT("scene_tree/delete", TTR("Delete"), KEY_DELETE);
- tb = memnew(ToolButton);
- tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_NEW, false));
- tb->set_tooltip(TTR("Add/Create a New Node"));
- tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/add_child_node"));
- filter_hbc->add_child(tb);
- button_add = tb;
+ button_add = memnew(ToolButton);
+ button_add->connect("pressed", this, "_tool_selected", make_binds(TOOL_NEW, false));
+ button_add->set_tooltip(TTR("Add/Create a New Node"));
+ button_add->set_shortcut(ED_GET_SHORTCUT("scene_tree/add_child_node"));
+ filter_hbc->add_child(button_add);
- tb = memnew(ToolButton);
- tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_INSTANCE, false));
- tb->set_tooltip(TTR("Instance a scene file as a Node. Creates an inherited scene if no root node exists."));
- tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/instance_scene"));
- filter_hbc->add_child(tb);
- button_instance = tb;
+ button_instance = memnew(ToolButton);
+ button_instance->connect("pressed", this, "_tool_selected", make_binds(TOOL_INSTANCE, false));
+ button_instance->set_tooltip(TTR("Instance a scene file as a Node. Creates an inherited scene if no root node exists."));
+ button_instance->set_shortcut(ED_GET_SHORTCUT("scene_tree/instance_scene"));
+ filter_hbc->add_child(button_instance);
vbc->add_child(filter_hbc);
filter = memnew(LineEdit);
@@ -2415,21 +2551,19 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel
filter->add_constant_override("minimum_spaces", 0);
filter->connect("text_changed", this, "_filter_changed");
- tb = memnew(ToolButton);
- tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_ATTACH_SCRIPT, false));
- tb->set_tooltip(TTR("Attach a new or existing script for the selected node."));
- tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/attach_script"));
- filter_hbc->add_child(tb);
- tb->hide();
- button_create_script = tb;
-
- tb = memnew(ToolButton);
- tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_CLEAR_SCRIPT, false));
- tb->set_tooltip(TTR("Clear a script for the selected node."));
- tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/clear_script"));
- filter_hbc->add_child(tb);
- button_clear_script = tb;
- tb->hide();
+ button_create_script = memnew(ToolButton);
+ button_create_script->connect("pressed", this, "_tool_selected", make_binds(TOOL_ATTACH_SCRIPT, false));
+ button_create_script->set_tooltip(TTR("Attach a new or existing script for the selected node."));
+ button_create_script->set_shortcut(ED_GET_SHORTCUT("scene_tree/attach_script"));
+ filter_hbc->add_child(button_create_script);
+ button_create_script->hide();
+
+ button_clear_script = memnew(ToolButton);
+ button_clear_script->connect("pressed", this, "_tool_selected", make_binds(TOOL_CLEAR_SCRIPT, false));
+ button_clear_script->set_tooltip(TTR("Clear a script for the selected node."));
+ button_clear_script->set_shortcut(ED_GET_SHORTCUT("scene_tree/clear_script"));
+ filter_hbc->add_child(button_clear_script);
+ button_clear_script->hide();
button_hb = memnew(HBoxContainer);
vbc->add_child(button_hb);
@@ -2537,6 +2671,9 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel
set_process_input(true);
set_process(true);
+ profile_allow_editing = true;
+ profile_allow_script_editing = true;
+
EDITOR_DEF("interface/editors/show_scene_tree_root_selection", true);
EDITOR_DEF("_use_favorites_root_selection", false);
}
diff --git a/editor/scene_tree_dock.h b/editor/scene_tree_dock.h
index 653d0a4eca..e66525d721 100644
--- a/editor/scene_tree_dock.h
+++ b/editor/scene_tree_dock.h
@@ -212,6 +212,11 @@ class SceneTreeDock : public VBoxContainer {
void _update_create_root_dialog();
void _favorite_root_selected(const String &p_class);
+ void _feature_profile_changed();
+
+ bool profile_allow_editing;
+ bool profile_allow_script_editing;
+
protected:
void _notification(int p_what);
static void _bind_methods();
diff --git a/editor/scene_tree_editor.cpp b/editor/scene_tree_editor.cpp
index c023c41747..f2d11c2753 100644
--- a/editor/scene_tree_editor.cpp
+++ b/editor/scene_tree_editor.cpp
@@ -48,6 +48,9 @@ Node *SceneTreeEditor::get_scene_node() {
void SceneTreeEditor::_cell_button_pressed(Object *p_item, int p_column, int p_id) {
+ if (connect_to_script_mode) {
+ return; //dont do anything in this mode
+ }
TreeItem *item = Object::cast_to<TreeItem>(p_item);
ERR_FAIL_COND(!item);
@@ -190,7 +193,25 @@ bool SceneTreeEditor::_add_nodes(Node *p_node, TreeItem *p_parent) {
item->set_icon(0, icon);
item->set_metadata(0, p_node->get_path());
- if (part_of_subscene) {
+ if (connect_to_script_mode) {
+ Color accent = get_color("accent_color", "Editor");
+
+ if (!p_node->get_script().is_null()) {
+ //has script
+ item->add_button(0, get_icon("Script", "EditorIcons"), BUTTON_SCRIPT);
+ } else {
+ //has no script
+ item->set_custom_color(0, get_color("disabled_font_color", "Editor"));
+ item->set_selectable(0, false);
+ accent.a *= 0.7;
+ }
+
+ if (marked.has(p_node)) {
+ item->set_text(0, String(p_node->get_name()) + " " + TTR("(Connecting From)"));
+
+ item->set_custom_color(0, accent);
+ }
+ } else if (part_of_subscene) {
//item->set_selectable(0,marked_selectable);
if (valid_types.size() == 0) {
@@ -199,7 +220,9 @@ bool SceneTreeEditor::_add_nodes(Node *p_node, TreeItem *p_parent) {
} else if (marked.has(p_node)) {
- item->set_selectable(0, marked_selectable);
+ if (!connect_to_script_mode) {
+ item->set_selectable(0, marked_selectable);
+ }
item->set_custom_color(0, get_color("error_color", "Editor"));
} else if (!marked_selectable && !marked_children_selectable) {
@@ -620,6 +643,7 @@ void SceneTreeEditor::set_selected(Node *p_node, bool p_emit_selected) {
item->set_as_cursor(0);
selected = p_node;
tree->ensure_cursor_is_visible();
+
} else {
if (!p_node)
selected = NULL;
@@ -974,6 +998,11 @@ void SceneTreeEditor::_warning_changed(Node *p_for_node) {
update_timer->start();
}
+void SceneTreeEditor::set_connect_to_script_mode(bool p_enable) {
+ connect_to_script_mode = p_enable;
+ update_tree();
+}
+
void SceneTreeEditor::_bind_methods() {
ClassDB::bind_method("_tree_changed", &SceneTreeEditor::_tree_changed);
@@ -1016,6 +1045,7 @@ void SceneTreeEditor::_bind_methods() {
SceneTreeEditor::SceneTreeEditor(bool p_label, bool p_can_rename, bool p_can_open_instance) {
+ connect_to_script_mode = false;
undo_redo = NULL;
tree_dirty = true;
selected = NULL;
@@ -1091,22 +1121,17 @@ SceneTreeEditor::~SceneTreeEditor() {
void SceneTreeDialog::_notification(int p_what) {
- if (p_what == NOTIFICATION_ENTER_TREE) {
- connect("confirmed", this, "_select");
- }
-
- if (p_what == NOTIFICATION_EXIT_TREE) {
- disconnect("confirmed", this, "_select");
- }
- if (p_what == NOTIFICATION_DRAW) {
-
- RID ci = get_canvas_item();
- get_stylebox("panel", "PopupMenu")->draw(ci, Rect2(Point2(), get_size()));
- }
-
- if (p_what == NOTIFICATION_VISIBILITY_CHANGED && is_visible_in_tree()) {
-
- tree->update_tree();
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ connect("confirmed", this, "_select");
+ } break;
+ case NOTIFICATION_EXIT_TREE: {
+ disconnect("confirmed", this, "_select");
+ } break;
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ if (is_visible_in_tree())
+ tree->update_tree();
+ } break;
}
}
@@ -1135,8 +1160,6 @@ SceneTreeDialog::SceneTreeDialog() {
tree = memnew(SceneTreeEditor(false, false, true));
add_child(tree);
- //set_child_rect(tree);
-
tree->get_scene_tree()->connect("item_activated", this, "_select");
}
diff --git a/editor/scene_tree_editor.h b/editor/scene_tree_editor.h
index aa4d4dd58a..9158c4aa48 100644
--- a/editor/scene_tree_editor.h
+++ b/editor/scene_tree_editor.h
@@ -67,6 +67,8 @@ class SceneTreeEditor : public Control {
AcceptDialog *error;
AcceptDialog *warning;
+ bool connect_to_script_mode;
+
int blocked;
void _compute_hash(Node *p_node, uint64_t &hash);
@@ -151,6 +153,8 @@ public:
void update_tree() { _update_tree(); }
+ void set_connect_to_script_mode(bool p_enable);
+
Tree *get_scene_tree() { return tree; }
SceneTreeEditor(bool p_label = true, bool p_can_rename = false, bool p_can_open_instance = false);
diff --git a/editor/translations/extract.py b/editor/translations/extract.py
index fd9b1183c4..2075bd5f3c 100755
--- a/editor/translations/extract.py
+++ b/editor/translations/extract.py
@@ -60,7 +60,7 @@ def process_file(f, fname):
lc = 1
while (l):
- patterns = ['RTR(\"', 'TTR(\"']
+ patterns = ['RTR(\"', 'TTR(\"','TTRC(\"']
idx = 0
pos = 0
while (pos >= 0):
diff --git a/main/input_default.cpp b/main/input_default.cpp
index e9f1eeff6a..6c3252ad1a 100644
--- a/main/input_default.cpp
+++ b/main/input_default.cpp
@@ -623,7 +623,8 @@ bool InputDefault::is_emulating_mouse_from_touch() const {
return emulate_mouse_from_touch;
}
-Input::CursorShape InputDefault::get_default_cursor_shape() {
+Input::CursorShape InputDefault::get_default_cursor_shape() const {
+
return default_shape;
}
@@ -638,6 +639,11 @@ void InputDefault::set_default_cursor_shape(CursorShape p_shape) {
parse_input_event(mm);
}
+Input::CursorShape InputDefault::get_current_cursor_shape() const {
+
+ return (Input::CursorShape)OS::get_singleton()->get_cursor_shape();
+}
+
void InputDefault::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
if (Engine::get_singleton()->is_editor_hint())
return;
@@ -645,21 +651,6 @@ void InputDefault::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_sh
OS::get_singleton()->set_custom_mouse_cursor(p_cursor, (OS::CursorShape)p_shape, p_hotspot);
}
-void InputDefault::set_mouse_in_window(bool p_in_window) {
- /* no longer supported, leaving this for reference to anyone who might want to implement hardware cursors
- if (custom_cursor.is_valid()) {
-
- if (p_in_window) {
- set_mouse_mode(MOUSE_MODE_HIDDEN);
- VisualServer::get_singleton()->cursor_set_visible(true);
- } else {
- set_mouse_mode(MOUSE_MODE_VISIBLE);
- VisualServer::get_singleton()->cursor_set_visible(false);
- }
- }
- */
-}
-
void InputDefault::accumulate_input_event(const Ref<InputEvent> &p_event) {
ERR_FAIL_COND(p_event.is_null());
diff --git a/main/input_default.h b/main/input_default.h
index 79a90cc4a4..f9b4cbbd57 100644
--- a/main/input_default.h
+++ b/main/input_default.h
@@ -242,10 +242,10 @@ public:
void set_emulate_mouse_from_touch(bool p_emulate);
virtual bool is_emulating_mouse_from_touch() const;
- virtual CursorShape get_default_cursor_shape();
+ virtual CursorShape get_default_cursor_shape() const;
virtual void set_default_cursor_shape(CursorShape p_shape);
+ virtual CursorShape get_current_cursor_shape() const;
virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape = Input::CURSOR_ARROW, const Vector2 &p_hotspot = Vector2());
- virtual void set_mouse_in_window(bool p_in_window);
void parse_mapping(String p_mapping);
void joy_button(int p_device, int p_button, bool p_pressed);
diff --git a/main/performance.cpp b/main/performance.cpp
index 49a08aa8d1..2f7ebf7656 100644
--- a/main/performance.cpp
+++ b/main/performance.cpp
@@ -154,7 +154,8 @@ float Performance::get_monitor(Monitor p_monitor) const {
case PHYSICS_3D_ISLAND_COUNT: return PhysicsServer::get_singleton()->get_process_info(PhysicsServer::INFO_ISLAND_COUNT);
case AUDIO_OUTPUT_LATENCY: return AudioServer::get_singleton()->get_output_latency();
- default: {}
+ default: {
+ }
}
return 0;
diff --git a/main/tests/test_gdscript.cpp b/main/tests/test_gdscript.cpp
index 7a711e8cc9..87bd640001 100644
--- a/main/tests/test_gdscript.cpp
+++ b/main/tests/test_gdscript.cpp
@@ -284,10 +284,16 @@ static String _parser_expr(const GDScriptParser::Node *p_expr) {
case GDScriptParser::OperatorNode::OP_BIT_XOR: {
txt = _parser_expr(c_node->arguments[0]) + "^" + _parser_expr(c_node->arguments[1]);
} break;
- default: {}
+ default: {
+ }
}
} break;
+ case GDScriptParser::Node::TYPE_CAST: {
+ const GDScriptParser::CastNode *cast_node = static_cast<const GDScriptParser::CastNode *>(p_expr);
+ txt = _parser_expr(cast_node->source_node) + " as " + cast_node->cast_type.to_string();
+
+ } break;
case GDScriptParser::Node::TYPE_NEWLINE: {
//skippie
@@ -668,6 +674,17 @@ static void _disassemble_class(const Ref<GDScript> &p_class, const Vector<String
incr += 2;
} break;
+ case GDScriptFunction::OPCODE_CAST_TO_SCRIPT: {
+
+ txt += " cast ";
+ txt += DADDR(3);
+ txt += "=";
+ txt += DADDR(1);
+ txt += " as ";
+ txt += DADDR(2);
+ incr += 4;
+
+ } break;
case GDScriptFunction::OPCODE_CONSTRUCT: {
Variant::Type t = Variant::Type(code[ip + 1]);
@@ -1017,19 +1034,17 @@ MainLoop *test(TestType p_type) {
return NULL;
}
- GDScript *script = memnew(GDScript);
+ Ref<GDScript> gds;
+ gds.instance();
GDScriptCompiler gdc;
- err = gdc.compile(&parser, script);
+ err = gdc.compile(&parser, gds.ptr());
if (err) {
print_line("Compile Error:\n" + itos(gdc.get_error_line()) + ":" + itos(gdc.get_error_column()) + ":" + gdc.get_error());
- memdelete(script);
return NULL;
}
- Ref<GDScript> gds = Ref<GDScript>(script);
-
Ref<GDScript> current = gds;
while (current.is_valid()) {
diff --git a/modules/assimp/editor_scene_importer_assimp.cpp b/modules/assimp/editor_scene_importer_assimp.cpp
index ee66097ffd..0330ab4604 100644
--- a/modules/assimp/editor_scene_importer_assimp.cpp
+++ b/modules/assimp/editor_scene_importer_assimp.cpp
@@ -113,7 +113,7 @@ Node *EditorSceneImporterAssimp::import_scene(const String &p_path, uint32_t p_f
std::string s_path(w_path.begin(), w_path.end());
importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true);
// Cannot remove pivot points because the static mesh will be in the wrong place
- importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, true);
+ importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false);
int32_t max_bone_weights = 4;
//if (p_flags & IMPORT_ANIMATION_EIGHT_WEIGHTS) {
// const int eight_bones = 8;
@@ -282,673 +282,438 @@ T EditorSceneImporterAssimp::_interpolate_track(const Vector<float> &p_times, co
ERR_FAIL_V(p_values[0]);
}
-Spatial *EditorSceneImporterAssimp::_generate_scene(const String &p_path, const aiScene *scene, const uint32_t p_flags, int p_bake_fps, const int32_t p_max_bone_weights) {
- ERR_FAIL_COND_V(scene == NULL, NULL);
- Spatial *root = memnew(Spatial);
- AnimationPlayer *ap = NULL;
- if (p_flags & IMPORT_ANIMATION) {
- ap = memnew(AnimationPlayer);
- root->add_child(ap);
- ap->set_owner(root);
- ap->set_name(TTR("AnimationPlayer"));
- }
- Set<String> bone_names;
- Set<String> light_names;
- Set<String> camera_names;
- real_t factor = 1.0f;
- String ext = p_path.get_file().get_extension().to_lower();
- if ((ext == "fbx")) {
- if (scene->mMetaData != NULL) {
- scene->mMetaData->Get("UnitScaleFactor", factor);
- factor = factor * 0.01f;
+void EditorSceneImporterAssimp::_generate_bone_groups(ImportState &state, const aiNode *p_assimp_node, Map<String, int> &ownership, Map<String, Transform> &bind_xforms) {
+
+ Transform mesh_offset = _get_global_assimp_node_transform(p_assimp_node);
+ //mesh_offset.basis = Basis();
+ for (uint32_t i = 0; i < p_assimp_node->mNumMeshes; i++) {
+ const aiMesh *mesh = state.assimp_scene->mMeshes[i];
+ int owned_by = -1;
+ for (uint32_t j = 0; j < mesh->mNumBones; j++) {
+ const aiBone *bone = mesh->mBones[j];
+ String name = _assimp_get_string(bone->mName);
+
+ if (ownership.has(name)) {
+ owned_by = ownership[name];
+ break;
+ }
}
- }
- for (size_t l = 0; l < scene->mNumLights; l++) {
- Light *light = NULL;
- aiLight *ai_light = scene->mLights[l];
- ERR_CONTINUE(ai_light == NULL);
- if (ai_light->mType == aiLightSource_DIRECTIONAL) {
- light = memnew(DirectionalLight);
- Vector3 dir = Vector3(ai_light->mDirection.y, ai_light->mDirection.x, ai_light->mDirection.z);
- dir.normalize();
- Transform xform;
- Quat quat;
- quat.set_euler(dir);
- Vector3 pos = Vector3(ai_light->mPosition.x, ai_light->mPosition.y, ai_light->mPosition.z);
- pos = factor * pos;
- xform.origin = pos;
- light->set_transform(xform);
- } else if (ai_light->mType == aiLightSource_POINT) {
- light = memnew(OmniLight);
- Vector3 pos = Vector3(ai_light->mPosition.x, ai_light->mPosition.y, ai_light->mPosition.z);
- Transform xform;
- xform.origin = pos;
- pos = factor * pos;
- light->set_transform(xform);
- // No idea for energy
- light->set_param(Light::PARAM_ATTENUATION, 0.0f);
- } else if (ai_light->mType == aiLightSource_SPOT) {
- light = memnew(SpotLight);
- Vector3 pos = Vector3(ai_light->mPosition.x, ai_light->mPosition.y, ai_light->mPosition.z);
- pos = factor * pos;
- Transform xform;
- xform.origin = pos;
- Vector3 dir = Vector3(ai_light->mDirection.y, ai_light->mDirection.x, ai_light->mDirection.z);
- dir.normalize();
- Quat quat;
- quat.set_euler(dir);
- xform.basis = quat;
- light->set_transform(xform);
- // No idea for energy
- light->set_param(Light::PARAM_ATTENUATION, 0.0f);
+
+ if (owned_by == -1) { //no owned, create new unique id
+ owned_by = 1;
+ for (Map<String, int>::Element *E = ownership.front(); E; E = E->next()) {
+ owned_by = MAX(E->get() + 1, owned_by);
+ }
}
- ERR_CONTINUE(light == NULL);
- light->set_color(Color(ai_light->mColorDiffuse.r, ai_light->mColorDiffuse.g, ai_light->mColorDiffuse.b));
- root->add_child(light);
- light->set_name(_ai_string_to_string(ai_light->mName));
- light->set_owner(root);
- light_names.insert(_ai_string_to_string(scene->mLights[l]->mName));
- }
- for (size_t c = 0; c < scene->mNumCameras; c++) {
- aiCamera *ai_camera = scene->mCameras[c];
- Camera *camera = memnew(Camera);
- float near = ai_camera->mClipPlaneNear;
- if (Math::is_equal_approx(near, 0.0f)) {
- near = 0.1f;
+
+ for (uint32_t j = 0; j < mesh->mNumBones; j++) {
+ const aiBone *bone = mesh->mBones[j];
+ String name = _assimp_get_string(bone->mName);
+ ownership[name] = owned_by;
+ //store the actuall full path for the bone transform
+ //when skeleton finds it's place in the tree, it will be restored
+ bind_xforms[name] = mesh_offset * _assimp_matrix_transform(bone->mOffsetMatrix);
}
- camera->set_perspective(Math::rad2deg(ai_camera->mHorizontalFOV) * 2.0f, near, ai_camera->mClipPlaneFar);
- Vector3 pos = Vector3(ai_camera->mPosition.x, ai_camera->mPosition.y, ai_camera->mPosition.z);
+ }
- Vector3 look_at = Vector3(ai_camera->mLookAt.y, ai_camera->mLookAt.x, ai_camera->mLookAt.z).normalized();
- Quat quat;
- quat.set_euler(look_at);
- Transform xform;
- xform.basis = quat;
- xform.set_origin(pos);
- root->add_child(camera);
- camera->set_transform(xform);
- camera->set_name(_ai_string_to_string(ai_camera->mName));
- camera->set_owner(root);
- camera_names.insert(_ai_string_to_string(scene->mCameras[c]->mName));
- }
- Map<Skeleton *, MeshInstance *> skeletons;
- Map<String, Transform> bone_rests;
- Vector<MeshInstance *> meshes;
- int32_t mesh_count = 0;
- Skeleton *s = memnew(Skeleton);
- Set<String> removed_bones;
- Map<String, Map<uint32_t, String> > path_morph_mesh_names;
- _generate_node(p_path, scene, scene->mRootNode, root, root, bone_names, light_names, camera_names, skeletons, bone_rests, meshes, mesh_count, s, p_max_bone_weights, removed_bones, path_morph_mesh_names);
- for (Map<Skeleton *, MeshInstance *>::Element *E = skeletons.front(); E; E = E->next()) {
- E->key()->localize_rests();
- }
- Set<String> removed_nodes;
- Set<Node *> keep_nodes;
- _keep_node(p_path, root, root, keep_nodes);
- _fill_kept_node(keep_nodes);
- _filter_node(p_path, root, root, keep_nodes, removed_nodes);
- if (p_flags & IMPORT_ANIMATION) {
- for (size_t i = 0; i < scene->mNumAnimations; i++) {
- _import_animation(p_path, meshes, scene, ap, i, p_bake_fps, skeletons, removed_nodes, removed_bones, path_morph_mesh_names);
- }
- List<StringName> animation_names;
- ap->get_animation_list(&animation_names);
- if (animation_names.empty()) {
- root->remove_child(ap);
- memdelete(ap);
- }
- }
- return root;
+ for (size_t i = 0; i < p_assimp_node->mNumChildren; i++) {
+ _generate_bone_groups(state, p_assimp_node->mChildren[i], ownership, bind_xforms);
+ }
}
-void EditorSceneImporterAssimp::_fill_kept_node(Set<Node *> &keep_nodes) {
- for (Set<Node *>::Element *E = keep_nodes.front(); E; E = E->next()) {
- Node *node = E->get();
- while (node != NULL) {
- if (keep_nodes.has(node) == false) {
- keep_nodes.insert(node);
+void EditorSceneImporterAssimp::_fill_node_relationships(ImportState &state, const aiNode *p_assimp_node, Map<String, int> &ownership, Map<int, int> &skeleton_map, int p_skeleton_id, Skeleton *p_skeleton, const String &p_parent_name, int &holecount, const Vector<SkeletonHole> &p_holes, const Map<String, Transform> &bind_xforms) {
+
+ String name = _assimp_get_string(p_assimp_node->mName);
+ if (name == String()) {
+ name = "AuxiliaryBone" + itos(holecount++);
+ }
+
+ Transform pose = _assimp_matrix_transform(p_assimp_node->mTransformation);
+
+ if (!ownership.has(name)) {
+ //not a bone, it's a hole
+ Vector<SkeletonHole> holes = p_holes;
+ SkeletonHole hole; //add a new one
+ hole.name = name;
+ hole.pose = pose;
+ hole.node = p_assimp_node;
+ hole.parent = p_parent_name;
+ holes.push_back(hole);
+
+ for (size_t i = 0; i < p_assimp_node->mNumChildren; i++) {
+ _fill_node_relationships(state, p_assimp_node->mChildren[i], ownership, skeleton_map, p_skeleton_id, p_skeleton, name, holecount, holes, bind_xforms);
+ }
+
+ return;
+ } else if (ownership[name] != p_skeleton_id) {
+ //oh, it's from another skeleton? fine.. reparent all bones to this skeleton.
+ int prev_owner = ownership[name];
+ ERR_EXPLAIN("A previous skeleton exists for bone '" + name + "', this type of skeleton layout is unsupported.");
+ ERR_FAIL_COND(skeleton_map.has(prev_owner));
+ for (Map<String, int>::Element *E = ownership.front(); E; E = E->next()) {
+ if (E->get() == prev_owner) {
+ E->get() = p_skeleton_id;
}
- node = node->get_parent();
}
}
-}
-String EditorSceneImporterAssimp::_find_skeleton_bone_root(Map<Skeleton *, MeshInstance *> &skeletons, Map<MeshInstance *, String> &meshes, Spatial *root) {
- for (Map<Skeleton *, MeshInstance *>::Element *E = skeletons.front(); E; E = E->next()) {
- if (meshes.has(E->get())) {
- String name = meshes[E->get()];
- if (name != "") {
- return name;
- }
+ //valid bone, first fill holes if needed
+ for (int i = 0; i < p_holes.size(); i++) {
+
+ int bone_idx = p_skeleton->get_bone_count();
+ p_skeleton->add_bone(p_holes[i].name);
+ int parent_idx = p_skeleton->find_bone(p_holes[i].parent);
+ if (parent_idx >= 0) {
+ p_skeleton->set_bone_parent(bone_idx, parent_idx);
}
+
+ Transform pose_transform = _get_global_assimp_node_transform(p_holes[i].node);
+ p_skeleton->set_bone_rest(bone_idx, pose_transform);
+
+ state.bone_owners[p_holes[i].name] = skeleton_map[p_skeleton_id];
+ }
+
+ //finally fill bone
+
+ int bone_idx = p_skeleton->get_bone_count();
+ p_skeleton->add_bone(name);
+ int parent_idx = p_skeleton->find_bone(p_parent_name);
+ if (parent_idx >= 0) {
+ p_skeleton->set_bone_parent(bone_idx, parent_idx);
+ }
+ //p_skeleton->set_bone_pose(bone_idx, pose);
+ if (bind_xforms.has(name)) {
+ //for now this is the full path to the bone in rest pose
+ //when skeleton finds it's place in the tree, it will get fixed
+ p_skeleton->set_bone_rest(bone_idx, bind_xforms[name]);
+ }
+ state.bone_owners[name] = skeleton_map[p_skeleton_id];
+ //go to children
+ for (size_t i = 0; i < p_assimp_node->mNumChildren; i++) {
+ _fill_node_relationships(state, p_assimp_node->mChildren[i], ownership, skeleton_map, p_skeleton_id, p_skeleton, name, holecount, Vector<SkeletonHole>(), bind_xforms);
}
- return "";
}
-void EditorSceneImporterAssimp::_set_bone_parent(Skeleton *s, Node *p_owner, aiNode *p_node) {
- for (int32_t j = 0; j < s->get_bone_count(); j++) {
- String bone_name = s->get_bone_name(j);
- const aiNode *ai_bone_node = _ai_find_node(p_node, bone_name);
- if (ai_bone_node == NULL) {
- continue;
- }
- ai_bone_node = ai_bone_node->mParent;
- while (ai_bone_node != NULL) {
- int32_t node_parent_index = -1;
- String parent_bone_name = _ai_string_to_string(ai_bone_node->mName);
- node_parent_index = s->find_bone(parent_bone_name);
- if (node_parent_index != -1) {
- s->set_bone_parent(j, node_parent_index);
- break;
+void EditorSceneImporterAssimp::_generate_skeletons(ImportState &state, const aiNode *p_assimp_node, Map<String, int> &ownership, Map<int, int> &skeleton_map, const Map<String, Transform> &bind_xforms) {
+
+ //find skeletons at this level, there may be multiple root nodes for each
+ Map<int, List<aiNode *> > skeletons_found;
+ for (size_t i = 0; i < p_assimp_node->mNumChildren; i++) {
+ String name = _assimp_get_string(p_assimp_node->mChildren[i]->mName);
+ if (ownership.has(name)) {
+ int skeleton = ownership[name];
+ if (!skeletons_found.has(skeleton)) {
+ skeletons_found[skeleton] = List<aiNode *>();
}
- ai_bone_node = ai_bone_node->mParent;
+ skeletons_found[skeleton].push_back(p_assimp_node->mChildren[i]);
}
}
+
+ //go via the potential skeletons found and generate the actual skeleton
+ for (Map<int, List<aiNode *> >::Element *E = skeletons_found.front(); E; E = E->next()) {
+ ERR_CONTINUE(skeleton_map.has(E->key())); //skeleton already exists? this can't be.. skip
+ Skeleton *skeleton = memnew(Skeleton);
+ //this the only way to reliably use multiple meshes with one skeleton, at the cost of less precision
+ skeleton->set_use_bones_in_world_transform(true);
+ skeleton_map[E->key()] = state.skeletons.size();
+ state.skeletons.push_back(skeleton);
+ int holecount = 1;
+ //fill the bones and their relationships
+ for (List<aiNode *>::Element *F = E->get().front(); F; F = F->next()) {
+ _fill_node_relationships(state, F->get(), ownership, skeleton_map, E->key(), skeleton, "", holecount, Vector<SkeletonHole>(), bind_xforms);
+ }
+ }
+
+ //go to the children
+ for (uint32_t i = 0; i < p_assimp_node->mNumChildren; i++) {
+ String name = _assimp_get_string(p_assimp_node->mChildren[i]->mName);
+ if (ownership.has(name)) {
+ continue; //a bone, so don't bother with this
+ }
+ _generate_skeletons(state, p_assimp_node->mChildren[i], ownership, skeleton_map, bind_xforms);
+ }
}
-void EditorSceneImporterAssimp::_insert_animation_track(const aiScene *p_scene, const String p_path, int p_bake_fps, Ref<Animation> animation, float ticks_per_second, float length, const Skeleton *sk, const aiNodeAnim *track, String node_name, NodePath node_path) {
+Spatial *EditorSceneImporterAssimp::_generate_scene(const String &p_path, const aiScene *scene, const uint32_t p_flags, int p_bake_fps, const int32_t p_max_bone_weights) {
+ ERR_FAIL_COND_V(scene == NULL, NULL);
- if (track->mNumRotationKeys || track->mNumPositionKeys || track->mNumScalingKeys) {
- //make transform track
- int track_idx = animation->get_track_count();
- animation->add_track(Animation::TYPE_TRANSFORM);
- animation->track_set_path(track_idx, node_path);
- //first determine animation length
+ ImportState state;
+ state.path = p_path;
+ state.assimp_scene = scene;
+ state.max_bone_weights = p_max_bone_weights;
+ state.root = memnew(Spatial);
+ state.fbx = false;
+ state.animation_player = NULL;
- for (size_t i = 0; i < track->mNumRotationKeys; i++) {
- length = MAX(length, track->mRotationKeys[i].mTime / ticks_per_second);
- }
- for (size_t i = 0; i < track->mNumPositionKeys; i++) {
- length = MAX(length, track->mPositionKeys[i].mTime / ticks_per_second);
- }
- for (size_t i = 0; i < track->mNumScalingKeys; i++) {
- length = MAX(length, track->mScalingKeys[i].mTime / ticks_per_second);
+ real_t scale_factor = 1.0f;
+ {
+ //handle scale
+ String ext = p_path.get_file().get_extension().to_lower();
+ if (ext == "fbx") {
+ if (scene->mMetaData != NULL) {
+ float factor = 1.0;
+ scene->mMetaData->Get("UnitScaleFactor", factor);
+ scale_factor = factor * 0.01f;
+ }
+ state.fbx = true;
}
+ }
- float increment = 1.0 / float(p_bake_fps);
- float time = 0.0;
+ state.root->set_scale(Vector3(scale_factor, scale_factor, scale_factor));
- Vector3 base_pos;
- Quat base_rot;
- Vector3 base_scale = Vector3(1, 1, 1);
+ //fill light map cache
+ for (size_t l = 0; l < scene->mNumLights; l++) {
- if (track->mNumRotationKeys != 0) {
- aiQuatKey key = track->mRotationKeys[0];
- real_t x = key.mValue.x;
- real_t y = key.mValue.y;
- real_t z = key.mValue.z;
- real_t w = key.mValue.w;
- Quat q(x, y, z, w);
- q = q.normalized();
- base_rot = q;
- }
+ aiLight *ai_light = scene->mLights[l];
+ ERR_CONTINUE(ai_light == NULL);
+ state.light_cache[_assimp_get_string(ai_light->mName)] = l;
+ }
- if (track->mNumPositionKeys != 0) {
- aiVectorKey key = track->mPositionKeys[0];
- real_t x = key.mValue.x;
- real_t y = key.mValue.y;
- real_t z = key.mValue.z;
- base_pos = Vector3(x, y, z);
+ //fill camera cache
+ for (size_t c = 0; c < scene->mNumCameras; c++) {
+ aiCamera *ai_camera = scene->mCameras[c];
+ ERR_CONTINUE(ai_camera == NULL);
+ state.camera_cache[_assimp_get_string(ai_camera->mName)] = c;
+ }
+
+ if (scene->mRootNode) {
+ Map<String, Transform> bind_xforms; //temporary map to store bind transforms
+ //guess the skeletons, since assimp does not really support them directly
+ Map<String, int> ownership; //bone names to groups
+ //fill this map with bone names and which group where they detected to, going mesh by mesh
+ _generate_bone_groups(state, state.assimp_scene->mRootNode, ownership, bind_xforms);
+ Map<int, int> skeleton_map; //maps previously created groups to actual skeletons
+ //generates the skeletons when bones are found in the hierarchy, and follows them (including gaps/holes).
+ _generate_skeletons(state, state.assimp_scene->mRootNode, ownership, skeleton_map, bind_xforms);
+
+ //generate nodes
+ for (uint32_t i = 0; i < scene->mRootNode->mNumChildren; i++) {
+ _generate_node(state, scene->mRootNode->mChildren[i], state.root);
}
- if (track->mNumScalingKeys != 0) {
- aiVectorKey key = track->mScalingKeys[0];
- real_t x = key.mValue.x;
- real_t y = key.mValue.y;
- real_t z = key.mValue.z;
- base_scale = Vector3(x, y, z);
+ //assign skeletons to nodes
+
+ for (Map<MeshInstance *, Skeleton *>::Element *E = state.mesh_skeletons.front(); E; E = E->next()) {
+ MeshInstance *mesh = E->key();
+ Skeleton *skeleton = E->get();
+ NodePath skeleton_path = mesh->get_path_to(skeleton);
+ mesh->set_skeleton_path(skeleton_path);
}
+ }
- bool last = false;
+ if (p_flags & IMPORT_ANIMATION && scene->mNumAnimations) {
- Vector<Vector3> pos_values;
- Vector<float> pos_times;
- Vector<Vector3> scale_values;
- Vector<float> scale_times;
- Vector<Quat> rot_values;
- Vector<float> rot_times;
+ state.animation_player = memnew(AnimationPlayer);
+ state.root->add_child(state.animation_player);
+ state.animation_player->set_owner(state.root);
- for (size_t p = 0; p < track->mNumPositionKeys; p++) {
- aiVector3D pos = track->mPositionKeys[p].mValue;
- pos_values.push_back(Vector3(pos.x, pos.y, pos.z));
- pos_times.push_back(track->mPositionKeys[p].mTime / ticks_per_second);
+ for (uint32_t i = 0; i < scene->mNumAnimations; i++) {
+ _import_animation(state, i, p_bake_fps);
}
+ }
+
+ return state.root;
+}
+
+void EditorSceneImporterAssimp::_insert_animation_track(ImportState &scene, const aiAnimation *assimp_anim, int p_track, int p_bake_fps, Ref<Animation> animation, float ticks_per_second, Skeleton *p_skeleton, const NodePath &p_path, const String &p_name) {
+
+ const aiNodeAnim *assimp_track = assimp_anim->mChannels[p_track];
+ //make transform track
+ int track_idx = animation->get_track_count();
+ animation->add_track(Animation::TYPE_TRANSFORM);
+ animation->track_set_path(track_idx, p_path);
+ //first determine animation length
- for (size_t r = 0; r < track->mNumRotationKeys; r++) {
- aiQuaternion quat = track->mRotationKeys[r].mValue;
- rot_values.push_back(Quat(quat.x, quat.y, quat.z, quat.w).normalized());
- rot_times.push_back(track->mRotationKeys[r].mTime / ticks_per_second);
+ float increment = 1.0 / float(p_bake_fps);
+ float time = 0.0;
+
+ bool last = false;
+
+ int skeleton_bone = -1;
+
+ if (p_skeleton) {
+ skeleton_bone = p_skeleton->find_bone(p_name);
+ }
+
+ Vector<Vector3> pos_values;
+ Vector<float> pos_times;
+ Vector<Vector3> scale_values;
+ Vector<float> scale_times;
+ Vector<Quat> rot_values;
+ Vector<float> rot_times;
+
+ for (size_t p = 0; p < assimp_track->mNumPositionKeys; p++) {
+ aiVector3D pos = assimp_track->mPositionKeys[p].mValue;
+ pos_values.push_back(Vector3(pos.x, pos.y, pos.z));
+ pos_times.push_back(assimp_track->mPositionKeys[p].mTime / ticks_per_second);
+ }
+
+ for (size_t r = 0; r < assimp_track->mNumRotationKeys; r++) {
+ aiQuaternion quat = assimp_track->mRotationKeys[r].mValue;
+ rot_values.push_back(Quat(quat.x, quat.y, quat.z, quat.w).normalized());
+ rot_times.push_back(assimp_track->mRotationKeys[r].mTime / ticks_per_second);
+ }
+
+ for (size_t sc = 0; sc < assimp_track->mNumScalingKeys; sc++) {
+ aiVector3D scale = assimp_track->mScalingKeys[sc].mValue;
+ scale_values.push_back(Vector3(scale.x, scale.y, scale.z));
+ scale_times.push_back(assimp_track->mScalingKeys[sc].mTime / ticks_per_second);
+ }
+ while (true) {
+ Vector3 pos;
+ Quat rot;
+ Vector3 scale(1, 1, 1);
+
+ if (pos_values.size()) {
+ pos = _interpolate_track<Vector3>(pos_times, pos_values, time, AssetImportAnimation::INTERP_LINEAR);
}
- for (size_t sc = 0; sc < track->mNumScalingKeys; sc++) {
- aiVector3D scale = track->mScalingKeys[sc].mValue;
- scale_values.push_back(Vector3(scale.x, scale.y, scale.z));
- scale_times.push_back(track->mScalingKeys[sc].mTime / ticks_per_second);
+ if (rot_values.size()) {
+ rot = _interpolate_track<Quat>(rot_times, rot_values, time, AssetImportAnimation::INTERP_LINEAR).normalized();
}
- while (true) {
- Vector3 pos = base_pos;
- Quat rot = base_rot;
- Vector3 scale = base_scale;
- if (pos_values.size()) {
- pos = _interpolate_track<Vector3>(pos_times, pos_values, time, AssetImportAnimation::INTERP_LINEAR);
- }
+ if (scale_values.size()) {
+ scale = _interpolate_track<Vector3>(scale_times, scale_values, time, AssetImportAnimation::INTERP_LINEAR);
+ }
- if (rot_values.size()) {
- rot = _interpolate_track<Quat>(rot_times, rot_values, time, AssetImportAnimation::INTERP_LINEAR).normalized();
- }
+ if (skeleton_bone >= 0) {
+ Transform xform;
+ xform.basis.set_quat_scale(rot, scale);
+ xform.origin = pos;
- if (scale_values.size()) {
- scale = _interpolate_track<Vector3>(scale_times, scale_values, time, AssetImportAnimation::INTERP_LINEAR);
- }
+ Transform rest_xform = p_skeleton->get_bone_rest(skeleton_bone);
+ xform = rest_xform.affine_inverse() * xform;
+ rot = xform.basis.get_rotation_quat();
+ scale = xform.basis.get_scale();
+ pos = xform.origin;
+ }
- if (sk != NULL && sk->find_bone(node_name) != -1) {
- Transform xform;
- xform.basis.set_quat_scale(rot, scale);
- xform.origin = pos;
-
- int bone = sk->find_bone(node_name);
- Transform rest_xform = sk->get_bone_rest(bone);
- xform = rest_xform.affine_inverse() * xform;
- rot = xform.basis.get_rotation_quat();
- scale = xform.basis.get_scale();
- pos = xform.origin;
- }
- {
- Transform xform;
- xform.basis.set_quat_scale(rot, scale);
- xform.origin = pos;
- Transform anim_xform;
- String ext = p_path.get_file().get_extension().to_lower();
- if (ext == "fbx") {
- real_t factor = 1.0f;
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("UnitScaleFactor", factor);
- }
- anim_xform = anim_xform.scaled(Vector3(factor, factor, factor));
- }
- xform = anim_xform * xform;
- rot = xform.basis.get_rotation_quat();
- scale = xform.basis.get_scale();
- pos = xform.origin;
- }
- rot.normalize();
+ rot.normalize();
- animation->track_set_interpolation_type(track_idx, Animation::INTERPOLATION_LINEAR);
- animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
+ animation->track_set_interpolation_type(track_idx, Animation::INTERPOLATION_LINEAR);
+ animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
- if (last) {
- break;
- }
- time += increment;
- if (time >= length) {
- last = true;
- time = length;
- }
+ if (last) { //done this way so a key is always inserted past the end (for proper interpolation)
+ break;
+ }
+ time += increment;
+ if (time >= animation->get_length()) {
+ last = true;
}
}
}
-void EditorSceneImporterAssimp::_import_animation(const String p_path, const Vector<MeshInstance *> p_meshes, const aiScene *p_scene, AnimationPlayer *ap, int32_t p_index, int p_bake_fps, Map<Skeleton *, MeshInstance *> p_skeletons, const Set<String> p_removed_nodes, const Set<String> removed_bones, const Map<String, Map<uint32_t, String> > p_path_morph_mesh_names) {
- String name = "Animation";
- aiAnimation const *anim = NULL;
- if (p_index != -1) {
- anim = p_scene->mAnimations[p_index];
- if (anim->mName.length > 0) {
- name = _ai_anim_string_to_string(anim->mName);
- }
+void EditorSceneImporterAssimp::_import_animation(ImportState &state, int p_animation_index, int p_bake_fps) {
+
+ ERR_FAIL_INDEX(p_animation_index, (int)state.assimp_scene->mNumAnimations);
+
+ const aiAnimation *anim = state.assimp_scene->mAnimations[p_animation_index];
+ String name = _assimp_anim_string_to_string(anim->mName);
+ if (name == String()) {
+ name = "Animation " + itos(p_animation_index + 1);
}
- Ref<Animation> animation;
- animation.instance();
- float length = 0.0f;
- animation->set_name(name);
- float ticks_per_second = p_scene->mAnimations[p_index]->mTicksPerSecond;
+ float ticks_per_second = anim->mTicksPerSecond;
- if (p_scene->mMetaData != NULL && Math::is_equal_approx(ticks_per_second, 0.0f)) {
+ if (state.assimp_scene->mMetaData != NULL && Math::is_equal_approx(ticks_per_second, 0.0f)) {
int32_t time_mode = 0;
- p_scene->mMetaData->Get("TimeMode", time_mode);
- ticks_per_second = _get_fbx_fps(time_mode, p_scene);
+ state.assimp_scene->mMetaData->Get("TimeMode", time_mode);
+ ticks_per_second = _get_fbx_fps(time_mode, state.assimp_scene);
}
- if ((p_path.get_file().get_extension().to_lower() == "glb" || p_path.get_file().get_extension().to_lower() == "gltf") && Math::is_equal_approx(ticks_per_second, 0.0f)) {
- ticks_per_second = 1000.0f;
- }
+ //?
+ //if ((p_path.get_file().get_extension().to_lower() == "glb" || p_path.get_file().get_extension().to_lower() == "gltf") && Math::is_equal_approx(ticks_per_second, 0.0f)) {
+ // ticks_per_second = 1000.0f;
+ //}
if (Math::is_equal_approx(ticks_per_second, 0.0f)) {
ticks_per_second = 25.0f;
}
- length = anim->mDuration / ticks_per_second;
- if (anim) {
- Map<String, Vector<const aiNodeAnim *> > node_tracks;
- for (size_t i = 0; i < anim->mNumChannels; i++) {
- const aiNodeAnim *track = anim->mChannels[i];
- String node_name = _ai_string_to_string(track->mNodeName);
- NodePath node_path = node_name;
- bool is_bone = false;
- if (node_name.split(ASSIMP_FBX_KEY).size() > 1) {
- String p_track_type = node_name.split(ASSIMP_FBX_KEY)[1];
- if (p_track_type == "_Translation" || p_track_type == "_Rotation" || p_track_type == "_Scaling") {
- continue;
- }
- }
- for (Map<Skeleton *, MeshInstance *>::Element *E = p_skeletons.front(); E; E = E->next()) {
- Skeleton *sk = E->key();
- const String path = ap->get_owner()->get_path_to(sk);
- if (path.empty()) {
- continue;
- }
- if (sk->find_bone(node_name) == -1) {
- continue;
- }
- node_path = path + ":" + node_name;
- ERR_CONTINUE(ap->get_owner()->has_node(node_path) == false);
- _insert_animation_track(p_scene, p_path, p_bake_fps, animation, ticks_per_second, length, sk, track, node_name, node_path);
- is_bone = true;
- }
- if (is_bone) {
- continue;
- }
- Node *node = ap->get_owner()->find_node(node_name);
- if (node == NULL) {
- continue;
- }
- if (p_removed_nodes.has(node_name)) {
- continue;
- }
- const String path = ap->get_owner()->get_path_to(node);
- if (path.empty()) {
- print_verbose("Can't animate path");
- continue;
- }
- node_path = path;
- if (ap->get_owner()->has_node(node_path) == false) {
- continue;
- }
- _insert_animation_track(p_scene, p_path, p_bake_fps, animation, ticks_per_second, length, NULL, track, node_name, node_path);
- }
- for (size_t i = 0; i < anim->mNumChannels; i++) {
- const aiNodeAnim *track = anim->mChannels[i];
- String node_name = _ai_string_to_string(track->mNodeName);
- Vector<String> split_name = node_name.split(ASSIMP_FBX_KEY);
- String bare_name = split_name[0];
- Node *node = ap->get_owner()->find_node(bare_name);
- if (node != NULL && split_name.size() > 1) {
- Map<String, Vector<const aiNodeAnim *> >::Element *E = node_tracks.find(bare_name);
- Vector<const aiNodeAnim *> ai_tracks;
- if (E) {
- ai_tracks = E->get();
- ai_tracks.push_back(anim->mChannels[i]);
- } else {
- ai_tracks.push_back(anim->mChannels[i]);
- }
- node_tracks.insert(bare_name, ai_tracks);
- }
- }
- for (Map<Skeleton *, MeshInstance *>::Element *E = p_skeletons.front(); E; E = E->next()) {
- Skeleton *sk = E->key();
- Map<String, Vector<const aiNodeAnim *> > anim_tracks;
- for (int32_t i = 0; i < sk->get_bone_count(); i++) {
- String _bone_name = sk->get_bone_name(i);
- Vector<const aiNodeAnim *> ai_tracks;
+ Ref<Animation> animation;
+ animation.instance();
+ animation->set_name(name);
+ animation->set_length(anim->mDuration / ticks_per_second);
- if (sk->find_bone(_bone_name) == -1) {
- continue;
- }
- for (size_t j = 0; j < anim->mNumChannels; j++) {
- if (_ai_string_to_string(anim->mChannels[j]->mNodeName).split(ASSIMP_FBX_KEY).size() == 1) {
- continue;
- }
- String track_name = _ai_string_to_string(anim->mChannels[j]->mNodeName).split(ASSIMP_FBX_KEY)[0];
- if (track_name != _bone_name) {
- continue;
- }
- if (sk->find_bone(_bone_name) == -1) {
- continue;
- }
- ai_tracks.push_back(anim->mChannels[j]);
- }
- if (ai_tracks.size() == 0) {
- continue;
- }
- anim_tracks.insert(_bone_name, ai_tracks);
- }
- for (Map<String, Vector<const aiNodeAnim *> >::Element *F = anim_tracks.front(); F; F = F->next()) {
- _insert_pivot_anim_track(p_meshes, F->key(), F->get(), ap, sk, length, ticks_per_second, animation, p_bake_fps, p_path, p_scene);
- }
- }
- for (Map<String, Vector<const aiNodeAnim *> >::Element *E = node_tracks.front(); E; E = E->next()) {
- if (p_removed_nodes.has(E->key())) {
- continue;
- }
- if (removed_bones.find(E->key())) {
+ //regular tracks
+
+ for (size_t i = 0; i < anim->mNumChannels; i++) {
+ const aiNodeAnim *track = anim->mChannels[i];
+ String node_name = _assimp_get_string(track->mNodeName);
+ /*
+ if (node_name.find(ASSIMP_FBX_KEY) != -1) {
+ String p_track_type = node_name.get_slice(ASSIMP_FBX_KEY, 1);
+ if (p_track_type == "_Translation" || p_track_type == "_Rotation" || p_track_type == "_Scaling") {
continue;
}
- _insert_pivot_anim_track(p_meshes, E->key(), E->get(), ap, NULL, length, ticks_per_second, animation, p_bake_fps, p_path, p_scene);
}
- for (size_t i = 0; i < anim->mNumMorphMeshChannels; i++) {
- const aiMeshMorphAnim *anim_mesh = anim->mMorphMeshChannels[i];
- const String prop_name = _ai_string_to_string(anim_mesh->mName);
- const String mesh_name = prop_name.split("*")[0];
- if (p_removed_nodes.has(mesh_name)) {
- continue;
- }
- ERR_CONTINUE(prop_name.split("*").size() != 2);
- const MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(ap->get_owner()->find_node(mesh_name));
- ERR_CONTINUE(mesh_instance == NULL);
- if (ap->get_owner()->find_node(mesh_instance->get_name()) == NULL) {
- print_verbose("Can't find mesh in scene: " + mesh_instance->get_name());
- continue;
- }
- const String path = ap->get_owner()->get_path_to(mesh_instance);
- if (path.empty()) {
- print_verbose("Can't find mesh in scene");
- continue;
- }
- Ref<Mesh> mesh = mesh_instance->get_mesh();
- ERR_CONTINUE(mesh.is_null());
- const Map<String, Map<uint32_t, String> >::Element *E = p_path_morph_mesh_names.find(mesh_name);
- ERR_CONTINUE(E == NULL);
- for (size_t k = 0; k < anim_mesh->mNumKeys; k++) {
- for (size_t j = 0; j < anim_mesh->mKeys[k].mNumValuesAndWeights; j++) {
- const Map<uint32_t, String>::Element *F = E->get().find(anim_mesh->mKeys[k].mValues[j]);
- ERR_CONTINUE(F == NULL);
- const String prop = "blend_shapes/" + F->get();
- const NodePath node_path = String(path) + ":" + prop;
- ERR_CONTINUE(ap->get_owner()->has_node(node_path) == false);
- int32_t blend_track_idx = -1;
- if (animation->find_track(node_path) == -1) {
- blend_track_idx = animation->get_track_count();
- animation->add_track(Animation::TYPE_VALUE);
- animation->track_set_interpolation_type(blend_track_idx, Animation::INTERPOLATION_LINEAR);
- animation->track_set_path(blend_track_idx, node_path);
- } else {
- blend_track_idx = animation->find_track(node_path);
- }
- float t = anim_mesh->mKeys[k].mTime / ticks_per_second;
- float w = anim_mesh->mKeys[k].mWeights[j];
- animation->track_insert_key(blend_track_idx, t, w);
- }
- }
+*/
+ if (track->mNumRotationKeys == 0 && track->mNumPositionKeys == 0 && track->mNumScalingKeys == 0) {
+ continue; //do not bother
}
- }
- animation->set_length(length);
- if (animation->get_track_count()) {
- ap->add_animation(name, animation);
- }
-}
-void EditorSceneImporterAssimp::_insert_pivot_anim_track(const Vector<MeshInstance *> p_meshes, const String p_node_name, Vector<const aiNodeAnim *> F, AnimationPlayer *ap, Skeleton *sk, float &length, float ticks_per_second, Ref<Animation> animation, int p_bake_fps, const String &p_path, const aiScene *p_scene) {
- NodePath node_path;
- if (sk != NULL) {
- const String path = ap->get_owner()->get_path_to(sk);
- if (path.empty()) {
- return;
- }
- if (sk->find_bone(p_node_name) == -1) {
- return;
- }
- node_path = path + ":" + p_node_name;
- } else {
- Node *node = ap->get_owner()->find_node(p_node_name);
- if (node == NULL) {
- return;
- }
- const String path = ap->get_owner()->get_path_to(node);
- node_path = path;
- }
- if (node_path.is_empty()) {
- return;
- }
+ bool is_bone = state.bone_owners.has(node_name);
+ NodePath node_path;
+ Skeleton *skeleton = NULL;
- Vector<Vector3> pos_values;
- Vector<float> pos_times;
- Vector<Vector3> scale_values;
- Vector<float> scale_times;
- Vector<Quat> rot_values;
- Vector<float> rot_times;
- Vector3 base_pos;
- Quat base_rot;
- Vector3 base_scale = Vector3(1, 1, 1);
- bool is_translation = false;
- bool is_rotation = false;
- bool is_scaling = false;
- for (int32_t k = 0; k < F.size(); k++) {
- String p_track_type = _ai_string_to_string(F[k]->mNodeName).split(ASSIMP_FBX_KEY)[1];
- if (p_track_type == "_Translation") {
- is_translation = is_translation || true;
- } else if (p_track_type == "_Rotation") {
- is_rotation = is_rotation || true;
- } else if (p_track_type == "_Scaling") {
- is_scaling = is_scaling || true;
+ if (is_bone) {
+ skeleton = state.skeletons[state.bone_owners[node_name]];
+ String path = state.root->get_path_to(skeleton);
+ path += ":" + node_name;
+ node_path = path;
} else {
- continue;
+
+ ERR_CONTINUE(!state.node_map.has(node_name));
+ Node *node = state.node_map[node_name];
+ node_path = state.root->get_path_to(node);
}
- ERR_CONTINUE(ap->get_owner()->has_node(node_path) == false);
- if (F[k]->mNumRotationKeys || F[k]->mNumPositionKeys || F[k]->mNumScalingKeys) {
+ _insert_animation_track(state, anim, i, p_bake_fps, animation, ticks_per_second, skeleton, node_path, node_name);
+ }
- if (is_rotation) {
- for (size_t i = 0; i < F[k]->mNumRotationKeys; i++) {
- length = MAX(length, F[k]->mRotationKeys[i].mTime / ticks_per_second);
- }
- }
- if (is_translation) {
- for (size_t i = 0; i < F[k]->mNumPositionKeys; i++) {
- length = MAX(length, F[k]->mPositionKeys[i].mTime / ticks_per_second);
- }
- }
- if (is_scaling) {
- for (size_t i = 0; i < F[k]->mNumScalingKeys; i++) {
- length = MAX(length, F[k]->mScalingKeys[i].mTime / ticks_per_second);
- }
- }
+ //blend shape tracks
- if (is_rotation == false && is_translation == false && is_scaling == false) {
- return;
- }
+ for (size_t i = 0; i < anim->mNumMorphMeshChannels; i++) {
- if (is_rotation) {
- if (F[k]->mNumRotationKeys != 0) {
- aiQuatKey key = F[k]->mRotationKeys[0];
- real_t x = key.mValue.x;
- real_t y = key.mValue.y;
- real_t z = key.mValue.z;
- real_t w = key.mValue.w;
- Quat q(x, y, z, w);
- q = q.normalized();
- base_rot = q;
- }
- }
+ const aiMeshMorphAnim *anim_mesh = anim->mMorphMeshChannels[i];
- if (is_translation) {
- if (F[k]->mNumPositionKeys != 0) {
- aiVectorKey key = F[k]->mPositionKeys[0];
- real_t x = key.mValue.x;
- real_t y = key.mValue.y;
- real_t z = key.mValue.z;
- base_pos = Vector3(x, y, z);
- }
- }
+ const String prop_name = _assimp_get_string(anim_mesh->mName);
+ const String mesh_name = prop_name.split("*")[0];
- if (is_scaling) {
- if (F[k]->mNumScalingKeys != 0) {
- aiVectorKey key = F[k]->mScalingKeys[0];
- real_t x = key.mValue.x;
- real_t y = key.mValue.y;
- real_t z = key.mValue.z;
- base_scale = Vector3(x, y, z);
- }
- }
- if (is_translation) {
- for (size_t p = 0; p < F[k]->mNumPositionKeys; p++) {
- aiVector3D pos = F[k]->mPositionKeys[p].mValue;
- pos_values.push_back(Vector3(pos.x, pos.y, pos.z));
- pos_times.push_back(F[k]->mPositionKeys[p].mTime / ticks_per_second);
- }
- }
+ ERR_CONTINUE(prop_name.split("*").size() != 2);
- if (is_rotation) {
- for (size_t r = 0; r < F[k]->mNumRotationKeys; r++) {
- aiQuaternion quat = F[k]->mRotationKeys[r].mValue;
- rot_values.push_back(Quat(quat.x, quat.y, quat.z, quat.w).normalized());
- rot_times.push_back(F[k]->mRotationKeys[r].mTime / ticks_per_second);
- }
- }
+ ERR_CONTINUE(!state.node_map.has(mesh_name));
- if (is_scaling) {
- for (size_t sc = 0; sc < F[k]->mNumScalingKeys; sc++) {
- aiVector3D scale = F[k]->mScalingKeys[sc].mValue;
- scale_values.push_back(Vector3(scale.x, scale.y, scale.z));
- scale_times.push_back(F[k]->mScalingKeys[sc].mTime / ticks_per_second);
- }
- }
+ const MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(state.node_map[mesh_name]);
+
+ ERR_CONTINUE(mesh_instance == NULL);
+
+ String base_path = state.root->get_path_to(mesh_instance);
+
+ Ref<Mesh> mesh = mesh_instance->get_mesh();
+ ERR_CONTINUE(mesh.is_null());
+
+ //add the tracks for this mesh
+ int base_track = animation->get_track_count();
+ for (int j = 0; j < mesh->get_blend_shape_count(); j++) {
+
+ animation->add_track(Animation::TYPE_VALUE);
+ animation->track_set_path(base_track + j, base_path + ":blend_shapes/" + mesh->get_blend_shape_name(j));
}
- }
- int32_t track_idx = animation->get_track_count();
- animation->add_track(Animation::TYPE_TRANSFORM);
- animation->track_set_path(track_idx, node_path);
- float increment = 1.0 / float(p_bake_fps);
- float time = 0.0;
- bool last = false;
- while (true) {
- Vector3 pos = Vector3();
- Quat rot = Quat();
- Vector3 scale = Vector3(1.0f, 1.0f, 1.0f);
- if (is_translation && pos_values.size()) {
- pos = _interpolate_track<Vector3>(pos_times, pos_values, time, AssetImportAnimation::INTERP_LINEAR);
- Transform anim_xform;
- String ext = p_path.get_file().get_extension().to_lower();
- if (ext == "fbx") {
- aiNode *ai_node = _ai_find_node(p_scene->mRootNode, p_node_name);
- Transform mesh_xform = _get_global_ai_node_transform(p_scene, ai_node);
- pos = mesh_xform.origin + pos;
- real_t factor = 1.0f;
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("UnitScaleFactor", factor);
- factor = factor * 0.01f;
- }
- pos = pos * factor;
+
+ for (size_t k = 0; k < anim_mesh->mNumKeys; k++) {
+ for (size_t j = 0; j < anim_mesh->mKeys[k].mNumValuesAndWeights; j++) {
+
+ float t = anim_mesh->mKeys[k].mTime / ticks_per_second;
+ float w = anim_mesh->mKeys[k].mWeights[j];
+
+ animation->track_insert_key(base_track + j, t, w);
}
}
- if (is_rotation && rot_values.size()) {
- rot = _interpolate_track<Quat>(rot_times, rot_values, time, AssetImportAnimation::INTERP_LINEAR).normalized();
- }
- if (is_scaling && scale_values.size()) {
- scale = _interpolate_track<Vector3>(scale_times, scale_values, time, AssetImportAnimation::INTERP_LINEAR);
- }
- animation->track_set_interpolation_type(track_idx, Animation::INTERPOLATION_LINEAR);
- animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
+ }
- if (last) {
- break;
- }
- time += increment;
- if (time >= length) {
- last = true;
- time = length;
- }
+ if (animation->get_track_count()) {
+ state.animation_player->add_animation(name, animation);
}
}
@@ -976,611 +741,320 @@ float EditorSceneImporterAssimp::_get_fbx_fps(int32_t time_mode, const aiScene *
return 0;
}
-Transform EditorSceneImporterAssimp::_get_global_ai_node_transform(const aiScene *p_scene, const aiNode *p_current_node) {
+Transform EditorSceneImporterAssimp::_get_global_assimp_node_transform(const aiNode *p_current_node) {
aiNode const *current_node = p_current_node;
Transform xform;
while (current_node != NULL) {
- xform = _ai_matrix_transform(current_node->mTransformation) * xform;
+ xform = _assimp_matrix_transform(current_node->mTransformation) * xform;
current_node = current_node->mParent;
}
return xform;
}
-void EditorSceneImporterAssimp::_generate_node_bone(const aiScene *p_scene, const aiNode *p_node, Map<String, bool> &p_mesh_bones, Skeleton *p_skeleton, const String p_path, const int32_t p_max_bone_weights) {
- for (size_t i = 0; i < p_node->mNumMeshes; i++) {
- const unsigned int mesh_idx = p_node->mMeshes[i];
- const aiMesh *ai_mesh = p_scene->mMeshes[mesh_idx];
- for (size_t j = 0; j < ai_mesh->mNumBones; j++) {
- String bone_name = _ai_string_to_string(ai_mesh->mBones[j]->mName);
- if (p_skeleton->find_bone(bone_name) != -1) {
- continue;
- }
- p_mesh_bones.insert(bone_name, true);
- p_skeleton->add_bone(bone_name);
- int32_t idx = p_skeleton->find_bone(bone_name);
- Transform xform = _ai_matrix_transform(ai_mesh->mBones[j]->mOffsetMatrix);
- String ext = p_path.get_file().get_extension().to_lower();
- if (ext == "fbx") {
- Transform mesh_xform = _get_global_ai_node_transform(p_scene, p_node);
- mesh_xform.basis = Basis();
- xform = mesh_xform.affine_inverse() * xform;
- }
- p_skeleton->set_bone_rest(idx, xform.affine_inverse());
- }
- }
-}
+Ref<Texture> EditorSceneImporterAssimp::_load_texture(ImportState &state, String p_path) {
+ Vector<String> split_path = p_path.get_basename().split("*");
+ if (split_path.size() == 2) {
+ size_t texture_idx = split_path[1].to_int();
+ ERR_FAIL_COND_V(texture_idx >= state.assimp_scene->mNumTextures, Ref<Texture>());
+ aiTexture *tex = state.assimp_scene->mTextures[texture_idx];
+ String filename = _assimp_raw_string_to_string(tex->mFilename);
+ filename = filename.get_file();
+ print_verbose("Open Asset Import: Loading embedded texture " + filename);
+ if (tex->mHeight == 0) {
+ if (tex->CheckFormat("png")) {
+ Ref<Image> img = Image::_png_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
+ ERR_FAIL_COND_V(img.is_null(), Ref<Texture>());
-void EditorSceneImporterAssimp::_generate_node_bone_parents(const aiScene *p_scene, const aiNode *p_node, Map<String, bool> &p_mesh_bones, Skeleton *p_skeleton, const MeshInstance *p_mi) {
- for (size_t i = 0; i < p_node->mNumMeshes; i++) {
- const unsigned int mesh_idx = p_node->mMeshes[i];
- const aiMesh *ai_mesh = p_scene->mMeshes[mesh_idx];
-
- for (size_t j = 0; j < ai_mesh->mNumBones; j++) {
- aiNode *bone_node = p_scene->mRootNode->FindNode(ai_mesh->mBones[j]->mName);
- ERR_CONTINUE(bone_node == NULL);
- aiNode *bone_node_parent = bone_node->mParent;
- while (bone_node_parent != NULL) {
- String bone_parent_name = _ai_string_to_string(bone_node_parent->mName);
- bone_parent_name = bone_parent_name.split(ASSIMP_FBX_KEY)[0];
- if (bone_parent_name == p_mi->get_name()) {
- break;
- }
- if (p_mi->get_parent() == NULL) {
- break;
- }
- if (bone_parent_name == p_mi->get_parent()->get_name()) {
- break;
- }
- if (bone_node_parent->mParent == p_scene->mRootNode) {
- break;
- }
- if (p_skeleton->find_bone(bone_parent_name) == -1) {
- p_mesh_bones.insert(bone_parent_name, true);
- }
- bone_node_parent = bone_node_parent->mParent;
- }
- }
- }
-}
-void EditorSceneImporterAssimp::_calculate_skeleton_root(Skeleton *s, const aiScene *p_scene, aiNode *&p_ai_skeleton_root, Map<String, bool> &mesh_bones, const aiNode *p_node) {
- if (s->get_bone_count() > 0) {
- String bone_name = s->get_bone_name(0);
- p_ai_skeleton_root = _ai_find_node(p_scene->mRootNode, bone_name);
- for (size_t i = 0; i < p_scene->mRootNode->mNumChildren; i++) {
- if (p_ai_skeleton_root == NULL) {
- break;
+ Ref<ImageTexture> t;
+ t.instance();
+ t->create_from_image(img);
+ t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
+ return t;
+ } else if (tex->CheckFormat("jpg")) {
+ Ref<Image> img = Image::_jpg_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
+ ERR_FAIL_COND_V(img.is_null(), Ref<Texture>());
+ Ref<ImageTexture> t;
+ t.instance();
+ t->create_from_image(img);
+ t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
+ return t;
+ } else if (tex->CheckFormat("dds")) {
+ ERR_EXPLAIN("Open Asset Import: Embedded dds not implemented");
+ ERR_FAIL_COND_V(true, Ref<Texture>());
+ //Ref<Image> img = Image::_dds_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
+ //ERR_FAIL_COND_V(img.is_null(), Ref<Texture>());
+ //Ref<ImageTexture> t;
+ //t.instance();
+ //t->create_from_image(img);
+ //t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
+ //return t;
}
- aiNode *found = p_scene->mRootNode->mChildren[i]->FindNode(p_ai_skeleton_root->mName);
- if (found) {
- p_ai_skeleton_root = p_scene->mRootNode->mChildren[i];
- break;
+ } else {
+ Ref<Image> img;
+ img.instance();
+ PoolByteArray arr;
+ uint32_t size = tex->mWidth * tex->mHeight;
+ arr.resize(size);
+ memcpy(arr.write().ptr(), tex->pcData, size);
+ ERR_FAIL_COND_V(arr.size() % 4 != 0, Ref<Texture>());
+ //ARGB8888 to RGBA8888
+ for (int32_t i = 0; i < arr.size() / 4; i++) {
+ arr.write().ptr()[(4 * i) + 3] = arr[(4 * i) + 0];
+ arr.write().ptr()[(4 * i) + 0] = arr[(4 * i) + 1];
+ arr.write().ptr()[(4 * i) + 1] = arr[(4 * i) + 2];
+ arr.write().ptr()[(4 * i) + 2] = arr[(4 * i) + 3];
}
- }
- }
+ img->create(tex->mWidth, tex->mHeight, true, Image::FORMAT_RGBA8, arr);
+ ERR_FAIL_COND_V(img.is_null(), Ref<Texture>());
- if (p_ai_skeleton_root == NULL) {
- p_ai_skeleton_root = p_scene->mRootNode->FindNode(p_node->mName);
- while (p_ai_skeleton_root && p_ai_skeleton_root->mParent && p_ai_skeleton_root->mParent != p_scene->mRootNode) {
- p_ai_skeleton_root = p_scene->mRootNode->FindNode(p_ai_skeleton_root->mName)->mParent;
+ Ref<ImageTexture> t;
+ t.instance();
+ t->create_from_image(img);
+ t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
+ return t;
}
+ return Ref<Texture>();
}
- p_ai_skeleton_root = _ai_find_node(p_scene->mRootNode, _ai_string_to_string(p_ai_skeleton_root->mName).split(ASSIMP_FBX_KEY)[0]);
-}
-
-void EditorSceneImporterAssimp::_fill_skeleton(const aiScene *p_scene, const aiNode *p_node, Spatial *p_current, Node *p_owner, Skeleton *p_skeleton, const Map<String, bool> p_mesh_bones, const Map<String, Transform> &p_bone_rests, Set<String> p_tracks, const String p_path, Set<String> &r_removed_bones) {
- String node_name = _ai_string_to_string(p_node->mName);
- if (p_mesh_bones.find(node_name) != NULL && p_skeleton->find_bone(node_name) == -1) {
- r_removed_bones.insert(node_name);
- p_skeleton->add_bone(node_name);
- int32_t idx = p_skeleton->find_bone(node_name);
- Transform xform = _get_global_ai_node_transform(p_scene, p_node);
- xform = _format_rot_xform(p_path, p_scene) * xform;
- p_skeleton->set_bone_rest(idx, xform);
- }
-
- for (size_t i = 0; i < p_node->mNumChildren; i++) {
- _fill_skeleton(p_scene, p_node->mChildren[i], p_current, p_owner, p_skeleton, p_mesh_bones, p_bone_rests, p_tracks, p_path, r_removed_bones);
- }
+ Ref<Texture> p_texture = ResourceLoader::load(p_path, "Texture");
+ return p_texture;
}
-void EditorSceneImporterAssimp::_keep_node(const String &p_path, Node *p_current, Node *p_owner, Set<Node *> &r_keep_nodes) {
- if (p_current == p_owner) {
- r_keep_nodes.insert(p_current);
- }
-
- if (p_current->get_class() != Spatial().get_class()) {
- r_keep_nodes.insert(p_current);
- }
-
- for (int i = 0; i < p_current->get_child_count(); i++) {
- _keep_node(p_path, p_current->get_child(i), p_owner, r_keep_nodes);
- }
-}
+Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportState &state, int p_index, bool p_double_sided) {
-void EditorSceneImporterAssimp::_filter_node(const String &p_path, Node *p_current, Node *p_owner, const Set<Node *> p_keep_nodes, Set<String> &r_removed_nodes) {
- if (p_keep_nodes.has(p_current) == false) {
- r_removed_nodes.insert(p_current->get_name());
- p_current->queue_delete();
- }
- for (int i = 0; i < p_current->get_child_count(); i++) {
- _filter_node(p_path, p_current->get_child(i), p_owner, p_keep_nodes, r_removed_nodes);
- }
-}
+ ERR_FAIL_INDEX_V(p_index, (int)state.assimp_scene->mNumMaterials, Ref<Material>());
-void EditorSceneImporterAssimp::_generate_node(const String &p_path, const aiScene *p_scene, const aiNode *p_node, Node *p_parent, Node *p_owner, Set<String> &r_bone_name, Set<String> p_light_names, Set<String> p_camera_names, Map<Skeleton *, MeshInstance *> &r_skeletons, const Map<String, Transform> &p_bone_rests, Vector<MeshInstance *> &r_mesh_instances, int32_t &r_mesh_count, Skeleton *p_skeleton, const int32_t p_max_bone_weights, Set<String> &r_removed_bones, Map<String, Map<uint32_t, String> > &r_name_morph_mesh_names) {
- Spatial *child_node = NULL;
- if (p_node == NULL) {
- return;
- }
- String node_name = _ai_string_to_string(p_node->mName);
- real_t factor = 1.0f;
- String ext = p_path.get_file().get_extension().to_lower();
- if (ext == "fbx") {
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("UnitScaleFactor", factor);
- factor = factor * 0.01f;
- }
- }
- {
- Transform xform = _ai_matrix_transform(p_node->mTransformation);
-
- child_node = memnew(Spatial);
- p_parent->add_child(child_node);
- child_node->set_owner(p_owner);
- if (p_node == p_scene->mRootNode) {
- if ((ext == "fbx") && p_node == p_scene->mRootNode) {
- xform = xform.scaled(Vector3(factor, factor, factor));
- Transform format_xform = _format_rot_xform(p_path, p_scene);
- xform = format_xform * xform;
- }
- }
- child_node->set_transform(xform * child_node->get_transform());
- }
+ aiMaterial *ai_material = state.assimp_scene->mMaterials[p_index];
+ Ref<SpatialMaterial> mat;
+ mat.instance();
- if (p_node->mNumMeshes > 0) {
- MeshInstance *mesh_node = memnew(MeshInstance);
- p_parent->add_child(mesh_node);
- mesh_node->set_owner(p_owner);
- mesh_node->set_transform(child_node->get_transform());
- {
- Map<String, bool> mesh_bones;
- p_skeleton->set_use_bones_in_world_transform(true);
- _generate_node_bone(p_scene, p_node, mesh_bones, p_skeleton, p_path, p_max_bone_weights);
- Set<String> tracks;
- _get_track_set(p_scene, tracks);
- aiNode *skeleton_root = NULL;
- _calculate_skeleton_root(p_skeleton, p_scene, skeleton_root, mesh_bones, p_node);
- _generate_node_bone_parents(p_scene, p_node, mesh_bones, p_skeleton, mesh_node);
- if (p_skeleton->get_bone_count() > 0) {
- _fill_skeleton(p_scene, skeleton_root, mesh_node, p_owner, p_skeleton, mesh_bones, p_bone_rests, tracks, p_path, r_removed_bones);
- _set_bone_parent(p_skeleton, p_owner, p_scene->mRootNode);
- }
- MeshInstance *mi = Object::cast_to<MeshInstance>(mesh_node);
- if (mi) {
- r_mesh_instances.push_back(mi);
- }
- _add_mesh_to_mesh_instance(p_node, p_scene, p_skeleton, p_path, mesh_node, p_owner, r_bone_name, r_mesh_count, p_max_bone_weights, r_name_morph_mesh_names);
- }
- if (mesh_node != NULL && p_skeleton->get_bone_count() > 0 && p_owner->find_node(p_skeleton->get_name()) == NULL) {
- Node *node = p_owner->find_node(_ai_string_to_string(p_scene->mRootNode->mName));
- ERR_FAIL_COND(node == NULL);
- node->add_child(p_skeleton);
- p_skeleton->set_owner(p_owner);
- if (ext == "fbx") {
- Transform mesh_xform = _get_global_ai_node_transform(p_scene, p_node);
- mesh_xform.origin = Vector3();
- p_skeleton->set_transform(mesh_xform);
- }
- r_skeletons.insert(p_skeleton, mesh_node);
- }
- for (size_t i = 0; i < p_node->mNumMeshes; i++) {
- if (p_scene->mMeshes[p_node->mMeshes[i]]->HasBones()) {
- mesh_node->set_name(node_name);
- // Meshes without skeletons must not have skeletons
- mesh_node->set_skeleton_path(String(mesh_node->get_path_to(p_owner)) + "/" + p_owner->get_path_to(p_skeleton));
- }
+ int32_t mat_two_sided = 0;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_TWOSIDED, mat_two_sided)) {
+ if (mat_two_sided > 0) {
+ mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
}
- child_node->get_parent()->remove_child(child_node);
- memdelete(child_node);
- child_node = mesh_node;
- } else if (p_light_names.has(node_name)) {
- Spatial *light_node = Object::cast_to<Light>(p_owner->find_node(node_name));
- ERR_FAIL_COND(light_node == NULL);
- if (!p_parent->has_node(light_node->get_path())) {
- p_parent->add_child(light_node);
- }
- light_node->set_owner(p_owner);
- light_node->set_transform(child_node->get_transform().scaled(Vector3(factor, factor, factor)) *
- light_node->get_transform().scaled(Vector3(factor, factor, factor)));
- child_node->get_parent()->remove_child(child_node);
- memdelete(child_node);
- child_node = light_node;
- } else if (p_camera_names.has(node_name)) {
- Spatial *camera_node = Object::cast_to<Camera>(p_owner->find_node(node_name));
- ERR_FAIL_COND(camera_node == NULL);
- if (!p_parent->has_node(camera_node->get_path())) {
- p_parent->add_child(camera_node);
- }
- camera_node->set_owner(p_owner);
- camera_node->set_transform(child_node->get_transform().scaled(Vector3(factor, factor, factor)) *
- camera_node->get_transform().scaled(Vector3(factor, factor, factor)));
- camera_node->scale(Vector3(factor, factor, factor));
- child_node->get_parent()->remove_child(child_node);
- memdelete(child_node);
- child_node = camera_node;
- }
- child_node->set_name(node_name);
- for (size_t i = 0; i < p_node->mNumChildren; i++) {
- _generate_node(p_path, p_scene, p_node->mChildren[i], child_node, p_owner, r_bone_name, p_light_names, p_camera_names, r_skeletons, p_bone_rests, r_mesh_instances, r_mesh_count, p_skeleton, p_max_bone_weights, r_removed_bones, r_name_morph_mesh_names);
}
-}
-
-aiNode *EditorSceneImporterAssimp::_ai_find_node(aiNode *ai_child_node, const String bone_name) {
- if (_ai_string_to_string(ai_child_node->mName) == bone_name) {
- return ai_child_node;
+ //const String mesh_name = _assimp_get_string(ai_mesh->mName);
+ aiString mat_name;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_NAME, mat_name)) {
+ mat->set_name(_assimp_get_string(mat_name));
}
- aiNode *target = NULL;
- for (size_t i = 0; i < ai_child_node->mNumChildren; i++) {
- target = _ai_find_node(ai_child_node->mChildren[i], bone_name);
- if (target != NULL) {
- return target;
- }
- }
- return target;
-}
+ aiTextureType tex_normal = aiTextureType_NORMALS;
+ {
+ aiString ai_filename = aiString();
+ String filename = "";
+ aiTextureMapMode map_mode[2];
-Transform EditorSceneImporterAssimp::_format_rot_xform(const String p_path, const aiScene *p_scene) {
- String ext = p_path.get_file().get_extension().to_lower();
+ if (AI_SUCCESS == ai_material->GetTexture(tex_normal, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) {
+ filename = _assimp_raw_string_to_string(ai_filename);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
- Transform xform;
- int32_t up_axis = 0;
- Vector3 up_axis_vec3 = Vector3();
-
- int32_t front_axis = 0;
- Vector3 front_axis_vec3 = Vector3();
-
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("UpAxis", up_axis);
- if (up_axis == AssetImportFbx::UP_VECTOR_AXIS_X) {
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("FrontAxis", front_axis);
- if (front_axis == AssetImportFbx::FRONT_PARITY_EVEN) {
- // y
- } else if (front_axis == AssetImportFbx::FRONT_PARITY_ODD) {
- // z
- //front_axis_vec3 = Vector3(0.0f, Math::deg2rad(-180.f), 0.0f);
- }
- }
- } else if (up_axis == AssetImportFbx::UP_VECTOR_AXIS_Y) {
- up_axis_vec3 = Vector3(Math::deg2rad(-90.f), 0.0f, 0.0f);
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("FrontAxis", front_axis);
- if (front_axis == AssetImportFbx::FRONT_PARITY_EVEN) {
- // x
- } else if (front_axis == AssetImportFbx::FRONT_PARITY_ODD) {
- // z
- }
- }
- } else if (up_axis == AssetImportFbx::UP_VECTOR_AXIS_Z) {
- up_axis_vec3 = Vector3(0.0f, Math ::deg2rad(90.f), 0.0f);
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("FrontAxis", front_axis);
- if (front_axis == AssetImportFbx::FRONT_PARITY_EVEN) {
- // x
- } else if (front_axis == AssetImportFbx::FRONT_PARITY_ODD) {
- // y
+ if (texture != NULL) {
+ if (map_mode != NULL) {
+ _set_texture_mapping_mode(map_mode, texture);
+ }
+ mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
+ mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
}
}
}
}
- int32_t up_axis_sign = 0;
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("UpAxisSign", up_axis_sign);
- up_axis_vec3 = up_axis_vec3 * up_axis_sign;
- }
-
- int32_t front_axis_sign = 0;
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("FrontAxisSign", front_axis_sign);
- front_axis_vec3 = front_axis_vec3 * front_axis_sign;
- }
+ {
+ aiString ai_filename = aiString();
+ String filename = "";
- int32_t coord_axis = 0;
- Vector3 coord_axis_vec3 = Vector3();
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("CoordAxis", coord_axis);
- if (coord_axis == AssetImportFbx::COORD_LEFT) {
- } else if (coord_axis == AssetImportFbx::COORD_RIGHT) {
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_NORMAL_TEXTURE, ai_filename)) {
+ filename = _assimp_raw_string_to_string(ai_filename);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ if (texture != NULL) {
+ mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
+ mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
+ }
+ }
}
}
- int32_t coord_axis_sign = 0;
- if (p_scene->mMetaData != NULL) {
- p_scene->mMetaData->Get("CoordAxisSign", coord_axis_sign);
- }
-
- Quat up_quat;
- up_quat.set_euler(up_axis_vec3);
-
- Quat coord_quat;
- coord_quat.set_euler(coord_axis_vec3);
-
- Quat front_quat;
- front_quat.set_euler(front_axis_vec3);
+ aiTextureType tex_emissive = aiTextureType_EMISSIVE;
- xform.basis.set_quat(up_quat * coord_quat * front_quat);
- return xform;
-}
+ if (ai_material->GetTextureCount(tex_emissive) > 0) {
-void EditorSceneImporterAssimp::_get_track_set(const aiScene *p_scene, Set<String> &tracks) {
- for (size_t i = 0; i < p_scene->mNumAnimations; i++) {
- for (size_t j = 0; j < p_scene->mAnimations[i]->mNumChannels; j++) {
- aiString ai_name = p_scene->mAnimations[i]->mChannels[j]->mNodeName;
- String name = _ai_string_to_string(ai_name);
- tracks.insert(name);
- }
- }
-}
+ aiString ai_filename = aiString();
+ String filename = "";
+ aiTextureMapMode map_mode[2];
-void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, const aiScene *p_scene, Skeleton *s, const String &p_path, MeshInstance *p_mesh_instance, Node *p_owner, Set<String> &r_bone_name, int32_t &r_mesh_count, int32_t p_max_bone_weights, Map<String, Map<uint32_t, String> > &r_name_morph_mesh_names) {
- Ref<ArrayMesh> mesh;
- mesh.instance();
- bool has_uvs = false;
- for (size_t i = 0; i < p_node->mNumMeshes; i++) {
- const unsigned int mesh_idx = p_node->mMeshes[i];
- const aiMesh *ai_mesh = p_scene->mMeshes[mesh_idx];
-
- Map<uint32_t, Vector<float> > vertex_weight;
- Map<uint32_t, Vector<String> > vertex_bone_name;
- for (size_t b = 0; b < ai_mesh->mNumBones; b++) {
- aiBone *bone = ai_mesh->mBones[b];
- for (size_t w = 0; w < bone->mNumWeights; w++) {
- String name = _ai_string_to_string(bone->mName);
- aiVertexWeight ai_weights = bone->mWeights[w];
- uint32_t vertexId = ai_weights.mVertexId;
- Map<uint32_t, Vector<float> >::Element *result = vertex_weight.find(vertexId);
- Vector<float> weights;
- if (result != NULL) {
- weights.append_array(result->value());
- }
- weights.push_back(ai_weights.mWeight);
- if (vertex_weight.has(vertexId)) {
- vertex_weight[vertexId] = weights;
- } else {
- vertex_weight.insert(vertexId, weights);
- }
- Map<uint32_t, Vector<String> >::Element *bone_result = vertex_bone_name.find(vertexId);
- Vector<String> bone_names;
- if (bone_result != NULL) {
- bone_names.append_array(bone_result->value());
- }
- bone_names.push_back(name);
- if (vertex_bone_name.has(vertexId)) {
- vertex_bone_name[vertexId] = bone_names;
- } else {
- vertex_bone_name.insert(vertexId, bone_names);
+ if (AI_SUCCESS == ai_material->GetTexture(tex_emissive, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) {
+ filename = _assimp_raw_string_to_string(ai_filename);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ if (texture != NULL) {
+ _set_texture_mapping_mode(map_mode, texture);
+ mat->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
+ mat->set_texture(SpatialMaterial::TEXTURE_EMISSION, texture);
}
}
}
+ }
- Ref<SurfaceTool> st;
- st.instance();
- st->begin(Mesh::PRIMITIVE_TRIANGLES);
-
- for (size_t j = 0; j < ai_mesh->mNumVertices; j++) {
- if (ai_mesh->HasTextureCoords(0)) {
- has_uvs = true;
- st->add_uv(Vector2(ai_mesh->mTextureCoords[0][j].x, 1.0f - ai_mesh->mTextureCoords[0][j].y));
- }
- if (ai_mesh->HasTextureCoords(1)) {
- has_uvs = true;
- st->add_uv2(Vector2(ai_mesh->mTextureCoords[1][j].x, 1.0f - ai_mesh->mTextureCoords[1][j].y));
- }
- if (ai_mesh->HasVertexColors(0)) {
- Color color = Color(ai_mesh->mColors[0]->r, ai_mesh->mColors[0]->g, ai_mesh->mColors[0]->b, ai_mesh->mColors[0]->a);
- st->add_color(color);
- }
- if (ai_mesh->mNormals != NULL) {
- const aiVector3D normals = ai_mesh->mNormals[j];
- const Vector3 godot_normal = Vector3(normals.x, normals.y, normals.z);
- st->add_normal(godot_normal);
- if (ai_mesh->HasTangentsAndBitangents()) {
- const aiVector3D tangents = ai_mesh->mTangents[j];
- const Vector3 godot_tangent = Vector3(tangents.x, tangents.y, tangents.z);
- const aiVector3D bitangent = ai_mesh->mBitangents[j];
- const Vector3 godot_bitangent = Vector3(bitangent.x, bitangent.y, bitangent.z);
- float d = godot_normal.cross(godot_tangent).dot(godot_bitangent) > 0.0f ? 1.0f : -1.0f;
- st->add_tangent(Plane(tangents.x, tangents.y, tangents.z, d));
- }
- }
+ aiTextureType tex_albedo = aiTextureType_DIFFUSE;
+ if (ai_material->GetTextureCount(tex_albedo) > 0) {
- if (s != NULL && s->get_bone_count() > 0) {
- Map<uint32_t, Vector<String> >::Element *I = vertex_bone_name.find(j);
- Vector<int32_t> bones;
- if (I != NULL) {
- Vector<String> bone_names;
- bone_names.append_array(I->value());
- for (int32_t f = 0; f < bone_names.size(); f++) {
- int32_t bone = s->find_bone(bone_names[f]);
- ERR_EXPLAIN("Asset Importer: Mesh can't find bone " + bone_names[f]);
- ERR_FAIL_COND(bone == -1);
- bones.push_back(bone);
- }
- if (s->get_bone_count()) {
- int32_t add = CLAMP(p_max_bone_weights - bones.size(), 0, p_max_bone_weights);
- for (int32_t f = 0; f < add; f++) {
- bones.push_back(0);
- }
- }
- st->add_bones(bones);
- Map<uint32_t, Vector<float> >::Element *E = vertex_weight.find(j);
- Vector<float> weights;
- if (E != NULL) {
- weights = E->value();
- if (weights.size() != p_max_bone_weights) {
- int32_t add = CLAMP(p_max_bone_weights - weights.size(), 0, p_max_bone_weights);
- for (int32_t f = 0; f < add; f++) {
- weights.push_back(0.0f);
- }
- }
+ aiString ai_filename = aiString();
+ String filename = "";
+ aiTextureMapMode map_mode[2];
+ if (AI_SUCCESS == ai_material->GetTexture(tex_albedo, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) {
+ filename = _assimp_raw_string_to_string(ai_filename);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ if (texture != NULL) {
+ if (texture->get_data()->detect_alpha() != Image::ALPHA_NONE) {
+ _set_texture_mapping_mode(map_mode, texture);
+ mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
+ mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
}
- ERR_CONTINUE(weights.size() == 0);
- st->add_weights(weights);
+ mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
}
}
- const aiVector3D pos = ai_mesh->mVertices[j];
- Vector3 godot_pos = Vector3(pos.x, pos.y, pos.z);
- st->add_vertex(godot_pos);
}
- for (size_t j = 0; j < ai_mesh->mNumFaces; j++) {
- const aiFace face = ai_mesh->mFaces[j];
- ERR_FAIL_COND(face.mNumIndices != 3);
- Vector<size_t> order;
- order.push_back(2);
- order.push_back(1);
- order.push_back(0);
- for (int32_t k = 0; k < order.size(); k++) {
- st->add_index(face.mIndices[order[k]]);
+ } else {
+ aiColor4D clr_diffuse;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_COLOR_DIFFUSE, clr_diffuse)) {
+ if (Math::is_equal_approx(clr_diffuse.a, 1.0f) == false) {
+ mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
+ mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
+ }
+ mat->set_albedo(Color(clr_diffuse.r, clr_diffuse.g, clr_diffuse.b, clr_diffuse.a));
+ }
+ }
+
+ aiString tex_gltf_base_color_path = aiString();
+ aiTextureMapMode map_mode[2];
+ if (AI_SUCCESS == ai_material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, &tex_gltf_base_color_path, NULL, NULL, NULL, NULL, map_mode)) {
+ String filename = _assimp_raw_string_to_string(tex_gltf_base_color_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ _find_texture_path(state.path, path, found);
+ if (texture != NULL) {
+ if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) {
+ _set_texture_mapping_mode(map_mode, texture);
+ mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
+ mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
+ }
+ mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
}
}
- if (ai_mesh->HasTangentsAndBitangents() == false && has_uvs) {
- st->generate_tangents();
- }
- aiMaterial *ai_material = p_scene->mMaterials[ai_mesh->mMaterialIndex];
- Ref<SpatialMaterial> mat;
- mat.instance();
-
- int32_t mat_two_sided = 0;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_TWOSIDED, mat_two_sided)) {
- if (mat_two_sided > 0) {
- mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
+ } else {
+ aiColor4D pbr_base_color;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR, pbr_base_color)) {
+ if (Math::is_equal_approx(pbr_base_color.a, 1.0f) == false) {
+ mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
+ mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
}
+ mat->set_albedo(Color(pbr_base_color.r, pbr_base_color.g, pbr_base_color.b, pbr_base_color.a));
}
-
- const String mesh_name = _ai_string_to_string(ai_mesh->mName);
- aiString mat_name;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_NAME, mat_name)) {
- mat->set_name(_ai_string_to_string(mat_name));
- }
-
- aiTextureType tex_normal = aiTextureType_NORMALS;
- {
- aiString ai_filename = aiString();
- String filename = "";
- aiTextureMapMode map_mode[2];
-
- if (AI_SUCCESS == ai_material->GetTexture(tex_normal, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) {
- filename = _ai_raw_string_to_string(ai_filename);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
-
- if (texture != NULL) {
- if (map_mode != NULL) {
- _set_texture_mapping_mode(map_mode, texture);
- }
- mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
- mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
+ }
+ {
+ aiString tex_fbx_pbs_base_color_path = aiString();
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_TEXTURE, tex_fbx_pbs_base_color_path)) {
+ String filename = _assimp_raw_string_to_string(tex_fbx_pbs_base_color_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ _find_texture_path(state.path, path, found);
+ if (texture != NULL) {
+ if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) {
+ mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
+ mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
}
+ mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
}
}
- }
-
- {
- aiString ai_filename = aiString();
- String filename = "";
-
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_NORMAL_TEXTURE, ai_filename)) {
- filename = _ai_raw_string_to_string(ai_filename);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- if (texture != NULL) {
- mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
- mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
- }
- }
+ } else {
+ aiColor4D pbr_base_color;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_FACTOR, pbr_base_color)) {
+ mat->set_albedo(Color(pbr_base_color.r, pbr_base_color.g, pbr_base_color.b, pbr_base_color.a));
}
}
- aiTextureType tex_emissive = aiTextureType_EMISSIVE;
-
- if (ai_material->GetTextureCount(tex_emissive) > 0) {
-
- aiString ai_filename = aiString();
- String filename = "";
- aiTextureMapMode map_mode[2];
+ aiUVTransform pbr_base_color_uv_xform;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_UV_XFORM, pbr_base_color_uv_xform)) {
+ mat->set_uv1_offset(Vector3(pbr_base_color_uv_xform.mTranslation.x, pbr_base_color_uv_xform.mTranslation.y, 0.0f));
+ mat->set_uv1_scale(Vector3(pbr_base_color_uv_xform.mScaling.x, pbr_base_color_uv_xform.mScaling.y, 1.0f));
+ }
+ }
- if (AI_SUCCESS == ai_material->GetTexture(tex_emissive, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) {
- filename = _ai_raw_string_to_string(ai_filename);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- if (texture != NULL) {
- _set_texture_mapping_mode(map_mode, texture);
- mat->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
- mat->set_texture(SpatialMaterial::TEXTURE_EMISSION, texture);
- }
+ {
+ aiString tex_fbx_pbs_normal_path = aiString();
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_NORMAL_TEXTURE, tex_fbx_pbs_normal_path)) {
+ String filename = _assimp_raw_string_to_string(tex_fbx_pbs_normal_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ _find_texture_path(state.path, path, found);
+ if (texture != NULL) {
+ mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
+ mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
}
}
}
+ }
- aiTextureType tex_albedo = aiTextureType_DIFFUSE;
- if (ai_material->GetTextureCount(tex_albedo) > 0) {
-
- aiString ai_filename = aiString();
- String filename = "";
- aiTextureMapMode map_mode[2];
- if (AI_SUCCESS == ai_material->GetTexture(tex_albedo, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) {
- filename = _ai_raw_string_to_string(ai_filename);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- if (texture != NULL) {
- if (texture->get_data()->detect_alpha() != Image::ALPHA_NONE) {
- _set_texture_mapping_mode(map_mode, texture);
- mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
- mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
- }
- mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
- }
- }
- }
- } else {
- aiColor4D clr_diffuse;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_COLOR_DIFFUSE, clr_diffuse)) {
- if (Math::is_equal_approx(clr_diffuse.a, 1.0f) == false) {
- mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
- mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
+ if (p_double_sided) {
+ mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
+ }
+
+ {
+ aiString tex_fbx_stingray_normal_path = aiString();
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_TEXTURE, tex_fbx_stingray_normal_path)) {
+ String filename = _assimp_raw_string_to_string(tex_fbx_stingray_normal_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ _find_texture_path(state.path, path, found);
+ if (texture != NULL) {
+ mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
+ mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
}
- mat->set_albedo(Color(clr_diffuse.r, clr_diffuse.g, clr_diffuse.b, clr_diffuse.a));
}
}
+ }
- aiString tex_gltf_base_color_path = aiString();
- aiTextureMapMode map_mode[2];
- if (AI_SUCCESS == ai_material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, &tex_gltf_base_color_path, NULL, NULL, NULL, NULL, map_mode)) {
- String filename = _ai_raw_string_to_string(tex_gltf_base_color_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
+ {
+ aiString tex_fbx_pbs_base_color_path = aiString();
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_TEXTURE, tex_fbx_pbs_base_color_path)) {
+ String filename = _assimp_raw_string_to_string(tex_fbx_pbs_base_color_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
bool found = false;
- _find_texture_path(p_path, path, found);
+ _find_texture_path(state.path, path, found);
if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- _find_texture_path(p_path, path, found);
+ Ref<Texture> texture = _load_texture(state, path);
+ _find_texture_path(state.path, path, found);
if (texture != NULL) {
if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) {
- _set_texture_mapping_mode(map_mode, texture);
mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
}
@@ -1589,263 +1063,274 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node,
}
} else {
aiColor4D pbr_base_color;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR, pbr_base_color)) {
- if (Math::is_equal_approx(pbr_base_color.a, 1.0f) == false) {
- mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
- mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
- }
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_BASE_COLOR_FACTOR, pbr_base_color)) {
mat->set_albedo(Color(pbr_base_color.r, pbr_base_color.g, pbr_base_color.b, pbr_base_color.a));
}
}
- {
- aiString tex_fbx_pbs_base_color_path = aiString();
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_TEXTURE, tex_fbx_pbs_base_color_path)) {
- String filename = _ai_raw_string_to_string(tex_fbx_pbs_base_color_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- _find_texture_path(p_path, path, found);
- if (texture != NULL) {
- if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) {
- mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
- mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
- }
- mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
- }
- }
- } else {
- aiColor4D pbr_base_color;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_FACTOR, pbr_base_color)) {
- mat->set_albedo(Color(pbr_base_color.r, pbr_base_color.g, pbr_base_color.b, pbr_base_color.a));
- }
- }
- aiUVTransform pbr_base_color_uv_xform;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_UV_XFORM, pbr_base_color_uv_xform)) {
- mat->set_uv1_offset(Vector3(pbr_base_color_uv_xform.mTranslation.x, pbr_base_color_uv_xform.mTranslation.y, 0.0f));
- mat->set_uv1_scale(Vector3(pbr_base_color_uv_xform.mScaling.x, pbr_base_color_uv_xform.mScaling.y, 1.0f));
- }
+ aiUVTransform pbr_base_color_uv_xform;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_UV_XFORM, pbr_base_color_uv_xform)) {
+ mat->set_uv1_offset(Vector3(pbr_base_color_uv_xform.mTranslation.x, pbr_base_color_uv_xform.mTranslation.y, 0.0f));
+ mat->set_uv1_scale(Vector3(pbr_base_color_uv_xform.mScaling.x, pbr_base_color_uv_xform.mScaling.y, 1.0f));
}
+ }
- {
- aiString tex_fbx_pbs_normal_path = aiString();
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_NORMAL_TEXTURE, tex_fbx_pbs_normal_path)) {
- String filename = _ai_raw_string_to_string(tex_fbx_pbs_normal_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- _find_texture_path(p_path, path, found);
- if (texture != NULL) {
- mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
- mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
+ {
+ aiString tex_fbx_pbs_emissive_path = aiString();
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_TEXTURE, tex_fbx_pbs_emissive_path)) {
+ String filename = _assimp_raw_string_to_string(tex_fbx_pbs_emissive_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ _find_texture_path(state.path, path, found);
+ if (texture != NULL) {
+ if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) {
+ mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
+ mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
}
+ mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
}
}
+ } else {
+ aiColor4D pbr_emmissive_color;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_FACTOR, pbr_emmissive_color)) {
+ mat->set_emission(Color(pbr_emmissive_color.r, pbr_emmissive_color.g, pbr_emmissive_color.b, pbr_emmissive_color.a));
+ }
}
- aiString cull_mode;
- if (p_node->mMetaData) {
- p_node->mMetaData->Get("Culling", cull_mode);
- }
- if (cull_mode.length != 0 && cull_mode == aiString("CullingOff")) {
- mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
+ real_t pbr_emission_intensity;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_INTENSITY_FACTOR, pbr_emission_intensity)) {
+ mat->set_emission_energy(pbr_emission_intensity);
}
+ }
- {
- aiString tex_fbx_stingray_normal_path = aiString();
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_TEXTURE, tex_fbx_stingray_normal_path)) {
- String filename = _ai_raw_string_to_string(tex_fbx_stingray_normal_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- _find_texture_path(p_path, path, found);
- if (texture != NULL) {
- mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
- mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
- }
- }
+ aiString tex_gltf_pbr_metallicroughness_path;
+ if (AI_SUCCESS == ai_material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, &tex_gltf_pbr_metallicroughness_path)) {
+ String filename = _assimp_raw_string_to_string(tex_gltf_pbr_metallicroughness_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ if (texture != NULL) {
+ mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture);
+ mat->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_BLUE);
+ mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture);
+ mat->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GREEN);
}
}
+ } else {
+ float pbr_roughness = 0.0f;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR, pbr_roughness)) {
+ mat->set_roughness(pbr_roughness);
+ }
+ float pbr_metallic = 0.0f;
- {
- aiString tex_fbx_pbs_base_color_path = aiString();
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_TEXTURE, tex_fbx_pbs_base_color_path)) {
- String filename = _ai_raw_string_to_string(tex_fbx_pbs_base_color_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- _find_texture_path(p_path, path, found);
- if (texture != NULL) {
- if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) {
- mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
- mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
- }
- mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
- }
- }
- } else {
- aiColor4D pbr_base_color;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_BASE_COLOR_FACTOR, pbr_base_color)) {
- mat->set_albedo(Color(pbr_base_color.r, pbr_base_color.g, pbr_base_color.b, pbr_base_color.a));
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR, pbr_metallic)) {
+ mat->set_metallic(pbr_metallic);
+ }
+ }
+ {
+ aiString tex_fbx_pbs_metallic_path;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_TEXTURE, tex_fbx_pbs_metallic_path)) {
+ String filename = _assimp_raw_string_to_string(tex_fbx_pbs_metallic_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ if (texture != NULL) {
+ mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture);
+ mat->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE);
}
}
-
- aiUVTransform pbr_base_color_uv_xform;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_UV_XFORM, pbr_base_color_uv_xform)) {
- mat->set_uv1_offset(Vector3(pbr_base_color_uv_xform.mTranslation.x, pbr_base_color_uv_xform.mTranslation.y, 0.0f));
- mat->set_uv1_scale(Vector3(pbr_base_color_uv_xform.mScaling.x, pbr_base_color_uv_xform.mScaling.y, 1.0f));
+ } else {
+ float pbr_metallic = 0.0f;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_FACTOR, pbr_metallic)) {
+ mat->set_metallic(pbr_metallic);
}
}
- {
- aiString tex_fbx_pbs_emissive_path = aiString();
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_TEXTURE, tex_fbx_pbs_emissive_path)) {
- String filename = _ai_raw_string_to_string(tex_fbx_pbs_emissive_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- _find_texture_path(p_path, path, found);
- if (texture != NULL) {
- if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) {
- mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
- mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
- }
- mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
- }
- }
- } else {
- aiColor4D pbr_emmissive_color;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_FACTOR, pbr_emmissive_color)) {
- mat->set_emission(Color(pbr_emmissive_color.r, pbr_emmissive_color.g, pbr_emmissive_color.b, pbr_emmissive_color.a));
+ aiString tex_fbx_pbs_rough_path;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_TEXTURE, tex_fbx_pbs_rough_path)) {
+ String filename = _assimp_raw_string_to_string(tex_fbx_pbs_rough_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ if (texture != NULL) {
+ mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture);
+ mat->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE);
}
}
+ } else {
+ float pbr_roughness = 0.04f;
- real_t pbr_emission_intensity;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_INTENSITY_FACTOR, pbr_emission_intensity)) {
- mat->set_emission_energy(pbr_emission_intensity);
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_FACTOR, pbr_roughness)) {
+ mat->set_roughness(pbr_roughness);
}
}
+ }
- aiString tex_gltf_pbr_metallicroughness_path;
- if (AI_SUCCESS == ai_material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, &tex_gltf_pbr_metallicroughness_path)) {
- String filename = _ai_raw_string_to_string(tex_gltf_pbr_metallicroughness_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
+ {
+ aiString tex_fbx_pbs_metallic_path;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_METALNESS_TEXTURE, tex_fbx_pbs_metallic_path)) {
+ String filename = _assimp_raw_string_to_string(tex_fbx_pbs_metallic_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
bool found = false;
- _find_texture_path(p_path, path, found);
+ _find_texture_path(state.path, path, found);
if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
+ Ref<Texture> texture = _load_texture(state, path);
if (texture != NULL) {
mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture);
- mat->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_BLUE);
- mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture);
- mat->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GREEN);
+ mat->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE);
}
}
} else {
- float pbr_roughness = 0.0f;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR, pbr_roughness)) {
- mat->set_roughness(pbr_roughness);
- }
float pbr_metallic = 0.0f;
-
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR, pbr_metallic)) {
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_METALNESS_FACTOR, pbr_metallic)) {
mat->set_metallic(pbr_metallic);
}
}
- {
- aiString tex_fbx_pbs_metallic_path;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_TEXTURE, tex_fbx_pbs_metallic_path)) {
- String filename = _ai_raw_string_to_string(tex_fbx_pbs_metallic_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- if (texture != NULL) {
- mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture);
- mat->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE);
- }
- }
- } else {
- float pbr_metallic = 0.0f;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_FACTOR, pbr_metallic)) {
- mat->set_metallic(pbr_metallic);
+
+ aiString tex_fbx_pbs_rough_path;
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_TEXTURE, tex_fbx_pbs_rough_path)) {
+ String filename = _assimp_raw_string_to_string(tex_fbx_pbs_rough_path);
+ String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ bool found = false;
+ _find_texture_path(state.path, path, found);
+ if (found) {
+ Ref<Texture> texture = _load_texture(state, path);
+ if (texture != NULL) {
+ mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture);
+ mat->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE);
}
}
+ } else {
+ float pbr_roughness = 0.04f;
+
+ if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_FACTOR, pbr_roughness)) {
+ mat->set_roughness(pbr_roughness);
+ }
+ }
+ }
+
+ return mat;
+}
+
+Ref<Mesh> EditorSceneImporterAssimp::_generate_mesh_from_surface_indices(ImportState &state, const Vector<int> &p_surface_indices, Skeleton *p_skeleton, bool p_double_sided_material) {
+
+ Ref<ArrayMesh> mesh;
+ mesh.instance();
+ bool has_uvs = false;
- aiString tex_fbx_pbs_rough_path;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_TEXTURE, tex_fbx_pbs_rough_path)) {
- String filename = _ai_raw_string_to_string(tex_fbx_pbs_rough_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- if (texture != NULL) {
- mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture);
- mat->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE);
+ for (int i = 0; i < p_surface_indices.size(); i++) {
+ const unsigned int mesh_idx = p_surface_indices[i];
+ const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_idx];
+
+ Map<uint32_t, Vector<BoneInfo> > vertex_weights;
+
+ if (p_skeleton) {
+ for (size_t b = 0; b < ai_mesh->mNumBones; b++) {
+ aiBone *bone = ai_mesh->mBones[b];
+ String bone_name = _assimp_get_string(bone->mName);
+ int bone_index = p_skeleton->find_bone(bone_name);
+ ERR_CONTINUE(bone_index == -1); //bone refers to an unexisting index, wtf.
+
+ for (size_t w = 0; w < bone->mNumWeights; w++) {
+
+ aiVertexWeight ai_weights = bone->mWeights[w];
+
+ BoneInfo bi;
+
+ uint32_t vertex_index = ai_weights.mVertexId;
+ bi.bone = bone_index;
+ bi.weight = ai_weights.mWeight;
+ ;
+
+ if (!vertex_weights.has(vertex_index)) {
+ vertex_weights[vertex_index] = Vector<BoneInfo>();
}
- }
- } else {
- float pbr_roughness = 0.04f;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_FACTOR, pbr_roughness)) {
- mat->set_roughness(pbr_roughness);
+ vertex_weights[vertex_index].push_back(bi);
}
}
}
- {
- aiString tex_fbx_pbs_metallic_path;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_METALNESS_TEXTURE, tex_fbx_pbs_metallic_path)) {
- String filename = _ai_raw_string_to_string(tex_fbx_pbs_metallic_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- if (texture != NULL) {
- mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture);
- mat->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE);
- }
- }
- } else {
- float pbr_metallic = 0.0f;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_METALNESS_FACTOR, pbr_metallic)) {
- mat->set_metallic(pbr_metallic);
+ Ref<SurfaceTool> st;
+ st.instance();
+ st->begin(Mesh::PRIMITIVE_TRIANGLES);
+
+ for (size_t j = 0; j < ai_mesh->mNumVertices; j++) {
+ if (ai_mesh->HasTextureCoords(0)) {
+ has_uvs = true;
+ st->add_uv(Vector2(ai_mesh->mTextureCoords[0][j].x, 1.0f - ai_mesh->mTextureCoords[0][j].y));
+ }
+ if (ai_mesh->HasTextureCoords(1)) {
+ has_uvs = true;
+ st->add_uv2(Vector2(ai_mesh->mTextureCoords[1][j].x, 1.0f - ai_mesh->mTextureCoords[1][j].y));
+ }
+ if (ai_mesh->HasVertexColors(0)) {
+ Color color = Color(ai_mesh->mColors[0]->r, ai_mesh->mColors[0]->g, ai_mesh->mColors[0]->b, ai_mesh->mColors[0]->a);
+ st->add_color(color);
+ }
+ if (ai_mesh->mNormals != NULL) {
+ const aiVector3D normals = ai_mesh->mNormals[j];
+ const Vector3 godot_normal = Vector3(normals.x, normals.y, normals.z);
+ st->add_normal(godot_normal);
+ if (ai_mesh->HasTangentsAndBitangents()) {
+ const aiVector3D tangents = ai_mesh->mTangents[j];
+ const Vector3 godot_tangent = Vector3(tangents.x, tangents.y, tangents.z);
+ const aiVector3D bitangent = ai_mesh->mBitangents[j];
+ const Vector3 godot_bitangent = Vector3(bitangent.x, bitangent.y, bitangent.z);
+ float d = godot_normal.cross(godot_tangent).dot(godot_bitangent) > 0.0f ? 1.0f : -1.0f;
+ st->add_tangent(Plane(tangents.x, tangents.y, tangents.z, d));
}
}
- aiString tex_fbx_pbs_rough_path;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_TEXTURE, tex_fbx_pbs_rough_path)) {
- String filename = _ai_raw_string_to_string(tex_fbx_pbs_rough_path);
- String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/");
- bool found = false;
- _find_texture_path(p_path, path, found);
- if (found) {
- Ref<Texture> texture = _load_texture(p_scene, path);
- if (texture != NULL) {
- mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture);
- mat->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE);
- }
- }
- } else {
- float pbr_roughness = 0.04f;
+ if (vertex_weights.has(j)) {
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_FACTOR, pbr_roughness)) {
- mat->set_roughness(pbr_roughness);
+ Vector<BoneInfo> bone_info = vertex_weights[j];
+ Vector<int> bones;
+ bones.resize(bone_info.size());
+ Vector<float> weights;
+ weights.resize(bone_info.size());
+ for (int k = 0; k < bone_info.size(); k++) {
+ bones.write[k] = bone_info[k].bone;
+ weights.write[k] = bone_info[k].weight;
}
+
+ st->add_bones(bones);
+ st->add_weights(weights);
}
+
+ const aiVector3D pos = ai_mesh->mVertices[j];
+ Vector3 godot_pos = Vector3(pos.x, pos.y, pos.z);
+ st->add_vertex(godot_pos);
+ }
+
+ for (size_t j = 0; j < ai_mesh->mNumFaces; j++) {
+ const aiFace face = ai_mesh->mFaces[j];
+ ERR_CONTINUE(face.mNumIndices != 3);
+ Vector<size_t> order;
+ order.push_back(2);
+ order.push_back(1);
+ order.push_back(0);
+ for (int32_t k = 0; k < order.size(); k++) {
+ st->add_index(face.mIndices[order[k]]);
+ }
+ }
+ if (ai_mesh->HasTangentsAndBitangents() == false && has_uvs) {
+ st->generate_tangents();
+ }
+
+ Ref<Material> material;
+
+ if (!state.material_cache.has(ai_mesh->mMaterialIndex)) {
+ material = _generate_material_from_index(state, ai_mesh->mMaterialIndex, p_double_sided_material);
}
Array array_mesh = st->commit_to_arrays();
@@ -1855,13 +1340,16 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node,
Map<uint32_t, String> morph_mesh_idx_names;
for (size_t j = 0; j < ai_mesh->mNumAnimMeshes; j++) {
- String ai_anim_mesh_name = _ai_string_to_string(ai_mesh->mAnimMeshes[j]->mName);
- mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
- if (ai_anim_mesh_name.empty()) {
- ai_anim_mesh_name = String("morph_") + itos(j);
+ if (i == 0) {
+ //only do this the first time
+ String ai_anim_mesh_name = _assimp_get_string(ai_mesh->mAnimMeshes[j]->mName);
+ mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
+ if (ai_anim_mesh_name.empty()) {
+ ai_anim_mesh_name = String("morph_") + itos(j);
+ }
+ mesh->add_blend_shape(ai_anim_mesh_name);
}
- mesh->add_blend_shape(ai_anim_mesh_name);
- morph_mesh_idx_names.insert(j, ai_anim_mesh_name);
+
Array array_copy;
array_copy.resize(VisualServer::ARRAY_MAX);
@@ -1945,82 +1433,192 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node,
morphs[j] = array_copy;
}
- r_name_morph_mesh_names.insert(_ai_string_to_string(p_node->mName), morph_mesh_idx_names);
+
mesh->add_surface_from_arrays(primitive, array_mesh, morphs);
- mesh->surface_set_material(i, mat);
- mesh->surface_set_name(i, _ai_string_to_string(ai_mesh->mName));
- r_mesh_count++;
- print_line(String("Open Asset Import: Created mesh (including instances) ") + _ai_string_to_string(ai_mesh->mName) + " " + itos(r_mesh_count) + " of " + itos(p_scene->mNumMeshes));
+ mesh->surface_set_material(i, material);
+ mesh->surface_set_name(i, _assimp_get_string(ai_mesh->mName));
}
- p_mesh_instance->set_mesh(mesh);
+
+ return mesh;
}
-Ref<Texture> EditorSceneImporterAssimp::_load_texture(const aiScene *p_scene, String p_path) {
- Vector<String> split_path = p_path.get_basename().split("*");
- if (split_path.size() == 2) {
- size_t texture_idx = split_path[1].to_int();
- ERR_FAIL_COND_V(texture_idx >= p_scene->mNumTextures, Ref<Texture>());
- aiTexture *tex = p_scene->mTextures[texture_idx];
- String filename = _ai_raw_string_to_string(tex->mFilename);
- filename = filename.get_file();
- print_verbose("Open Asset Import: Loading embedded texture " + filename);
- if (tex->mHeight == 0) {
- if (tex->CheckFormat("png")) {
- Ref<Image> img = Image::_png_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
- ERR_FAIL_COND_V(img.is_null(), Ref<Texture>());
+void EditorSceneImporterAssimp::_generate_node(ImportState &state, const aiNode *p_assimp_node, Node *p_parent) {
- Ref<ImageTexture> t;
- t.instance();
- t->create_from_image(img);
- t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
- return t;
- } else if (tex->CheckFormat("jpg")) {
- Ref<Image> img = Image::_jpg_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
- ERR_FAIL_COND_V(img.is_null(), Ref<Texture>());
- Ref<ImageTexture> t;
- t.instance();
- t->create_from_image(img);
- t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
- return t;
- } else if (tex->CheckFormat("dds")) {
- ERR_EXPLAIN("Open Asset Import: Embedded dds not implemented");
- ERR_FAIL_COND_V(true, Ref<Texture>());
- //Ref<Image> img = Image::_dds_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
- //ERR_FAIL_COND_V(img.is_null(), Ref<Texture>());
- //Ref<ImageTexture> t;
- //t.instance();
- //t->create_from_image(img);
- //t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
- //return t;
+ Spatial *new_node = NULL;
+ String node_name = _assimp_get_string(p_assimp_node->mName);
+ Transform node_transform = _assimp_matrix_transform(p_assimp_node->mTransformation);
+
+ if (p_assimp_node->mNumMeshes > 0) {
+ /* MESH NODE */
+ Ref<Mesh> mesh;
+ Skeleton *skeleton = NULL;
+ {
+
+ //see if we have mesh cache for this.
+ Vector<int> surface_indices;
+ for (uint32_t i = 0; i < p_assimp_node->mNumMeshes; i++) {
+ int mesh_index = p_assimp_node->mMeshes[i];
+ surface_indices.push_back(mesh_index);
+
+ //take the chane and attempt to find the skeleton from the bones
+ if (!skeleton) {
+ aiMesh *ai_mesh = state.assimp_scene->mMeshes[p_assimp_node->mMeshes[i]];
+ for (uint32_t j = 0; j < ai_mesh->mNumBones; j++) {
+ aiBone *bone = ai_mesh->mBones[j];
+ String bone_name = _assimp_get_string(bone->mName);
+ if (state.bone_owners.has(bone_name)) {
+ skeleton = state.skeletons[state.bone_owners[bone_name]];
+ break;
+ }
+ }
+ }
}
- } else {
- Ref<Image> img;
- img.instance();
- PoolByteArray arr;
- uint32_t size = tex->mWidth * tex->mHeight;
- arr.resize(size);
- memcpy(arr.write().ptr(), tex->pcData, size);
- ERR_FAIL_COND_V(arr.size() % 4 != 0, Ref<Texture>());
- //ARGB8888 to RGBA8888
- for (int32_t i = 0; i < arr.size() / 4; i++) {
- arr.write().ptr()[(4 * i) + 3] = arr[(4 * i) + 0];
- arr.write().ptr()[(4 * i) + 0] = arr[(4 * i) + 1];
- arr.write().ptr()[(4 * i) + 1] = arr[(4 * i) + 2];
- arr.write().ptr()[(4 * i) + 2] = arr[(4 * i) + 3];
+ surface_indices.sort();
+ String mesh_key;
+ for (int i = 0; i < surface_indices.size(); i++) {
+ if (i > 0) {
+ mesh_key += ":";
+ }
+ mesh_key += itos(surface_indices[i]);
}
- img->create(tex->mWidth, tex->mHeight, true, Image::FORMAT_RGBA8, arr);
- ERR_FAIL_COND_V(img.is_null(), Ref<Texture>());
- Ref<ImageTexture> t;
- t.instance();
- t->create_from_image(img);
- t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
- return t;
+ if (!state.mesh_cache.has(mesh_key)) {
+ //adding cache
+ aiString cull_mode; //cull is on mesh, which is kind of stupid tbh
+ bool double_sided_material = false;
+ if (p_assimp_node->mMetaData) {
+ p_assimp_node->mMetaData->Get("Culling", cull_mode);
+ }
+ if (cull_mode.length != 0 && cull_mode == aiString("CullingOff")) {
+ double_sided_material = true;
+ }
+
+ mesh = _generate_mesh_from_surface_indices(state, surface_indices, skeleton, double_sided_material);
+ state.mesh_cache[mesh_key] = mesh;
+ }
+
+ mesh = state.mesh_cache[mesh_key];
}
- return Ref<Texture>();
+
+ MeshInstance *mesh_node = memnew(MeshInstance);
+ if (skeleton) {
+ state.mesh_skeletons[mesh_node] = skeleton;
+ }
+ mesh_node->set_mesh(mesh);
+ new_node = mesh_node;
+
+ } else if (state.light_cache.has(node_name)) {
+
+ Light *light = NULL;
+ aiLight *ai_light = state.assimp_scene->mLights[state.light_cache[node_name]];
+ ERR_FAIL_COND(!ai_light);
+
+ if (ai_light->mType == aiLightSource_DIRECTIONAL) {
+ light = memnew(DirectionalLight);
+ Vector3 dir = Vector3(ai_light->mDirection.y, ai_light->mDirection.x, ai_light->mDirection.z);
+ dir.normalize();
+ Vector3 pos = Vector3(ai_light->mPosition.x, ai_light->mPosition.y, ai_light->mPosition.z);
+ Vector3 up = Vector3(ai_light->mUp.x, ai_light->mUp.y, ai_light->mUp.z);
+ up.normalize();
+
+ Transform light_transform;
+ light_transform.set_look_at(pos, pos + dir, up);
+
+ node_transform *= light_transform;
+
+ } else if (ai_light->mType == aiLightSource_POINT) {
+ light = memnew(OmniLight);
+ Vector3 pos = Vector3(ai_light->mPosition.x, ai_light->mPosition.y, ai_light->mPosition.z);
+ Transform xform;
+ xform.origin = pos;
+
+ node_transform *= xform;
+
+ light->set_transform(xform);
+
+ //light->set_param(Light::PARAM_ATTENUATION, 1);
+ } else if (ai_light->mType == aiLightSource_SPOT) {
+ light = memnew(SpotLight);
+
+ Vector3 dir = Vector3(ai_light->mDirection.y, ai_light->mDirection.x, ai_light->mDirection.z);
+ dir.normalize();
+ Vector3 pos = Vector3(ai_light->mPosition.x, ai_light->mPosition.y, ai_light->mPosition.z);
+ Vector3 up = Vector3(ai_light->mUp.x, ai_light->mUp.y, ai_light->mUp.z);
+ up.normalize();
+
+ Transform light_transform;
+ light_transform.set_look_at(pos, pos + dir, up);
+ node_transform *= light_transform;
+
+ //light->set_param(Light::PARAM_ATTENUATION, 0.0f);
+ }
+ ERR_FAIL_COND(light == NULL);
+ light->set_color(Color(ai_light->mColorDiffuse.r, ai_light->mColorDiffuse.g, ai_light->mColorDiffuse.b));
+ new_node = light;
+ } else if (state.camera_cache.has(node_name)) {
+
+ aiCamera *ai_camera = state.assimp_scene->mCameras[state.camera_cache[node_name]];
+ ERR_FAIL_COND(!ai_camera);
+
+ Camera *camera = memnew(Camera);
+
+ float near = ai_camera->mClipPlaneNear;
+ if (Math::is_equal_approx(near, 0.0f)) {
+ near = 0.1f;
+ }
+ camera->set_perspective(Math::rad2deg(ai_camera->mHorizontalFOV) * 2.0f, near, ai_camera->mClipPlaneFar);
+
+ Vector3 pos = Vector3(ai_camera->mPosition.x, ai_camera->mPosition.y, ai_camera->mPosition.z);
+ Vector3 look_at = Vector3(ai_camera->mLookAt.y, ai_camera->mLookAt.x, ai_camera->mLookAt.z).normalized();
+ Vector3 up = Vector3(ai_camera->mUp.x, ai_camera->mUp.y, ai_camera->mUp.z);
+
+ Transform xform;
+ xform.set_look_at(pos, look_at, up);
+
+ new_node = camera;
+ } else if (state.bone_owners.has(node_name)) {
+
+ //have to actually put the skeleton somewhere, you know.
+ Skeleton *skeleton = state.skeletons[state.bone_owners[node_name]];
+ if (skeleton->get_parent()) {
+ //a bone for a skeleton already added..
+ //could go downwards here to add meshes children of skeleton bones
+ //but let's not support it for now.
+ return;
+ }
+ //restore rest poses to local, now that we know where the skeleton finally is
+ Transform skeleton_transform;
+ if (p_assimp_node->mParent) {
+ skeleton_transform = _get_global_assimp_node_transform(p_assimp_node->mParent);
+ }
+ for (int i = 0; i < skeleton->get_bone_count(); i++) {
+ Transform rest = skeleton_transform.affine_inverse() * skeleton->get_bone_rest(i);
+ skeleton->set_bone_rest(i, rest.affine_inverse());
+ }
+
+ skeleton->localize_rests();
+ node_name = "Skeleton"; //don't use the bone root name
+ node_transform = Transform(); //dont transform
+
+ new_node = skeleton;
+ } else {
+ //generic node
+ new_node = memnew(Spatial);
+ }
+
+ {
+
+ new_node->set_name(node_name);
+ new_node->set_transform(node_transform);
+ p_parent->add_child(new_node);
+ new_node->set_owner(state.root);
+ }
+
+ state.node_map[node_name] = new_node;
+
+ for (size_t i = 0; i < p_assimp_node->mNumChildren; i++) {
+ _generate_node(state, p_assimp_node->mChildren[i], new_node);
}
- Ref<Texture> p_texture = ResourceLoader::load(p_path, "Texture");
- return p_texture;
}
void EditorSceneImporterAssimp::_calc_tangent_from_mesh(const aiMesh *ai_mesh, int i, int tri_index, int index, PoolColorArray::Write &w) {
@@ -2122,31 +1720,25 @@ void EditorSceneImporterAssimp::_find_texture_path(const String &p_path, _Direct
}
}
-String EditorSceneImporterAssimp::_ai_string_to_string(const aiString p_string) const {
- Vector<char> raw_name;
- raw_name.resize(p_string.length);
- memcpy(raw_name.ptrw(), p_string.C_Str(), p_string.length);
+String EditorSceneImporterAssimp::_assimp_get_string(const aiString p_string) const {
+ //convert an assimp String to a Godot String
String name;
- name.parse_utf8(raw_name.ptrw(), raw_name.size());
+ name.parse_utf8(p_string.C_Str() /*,p_string.length*/);
if (name.find(":") != -1) {
String replaced_name = name.split(":")[1];
print_verbose("Replacing " + name + " containing : with " + replaced_name);
name = replaced_name;
}
- if (name.find(".") != -1) {
- String replaced_name = name.replace(".", "");
- print_verbose("Replacing " + name + " containing . with " + replaced_name);
- name = replaced_name;
- }
+
+ name = name.replace(".", ""); //can break things, specially bone names
+
return name;
}
-String EditorSceneImporterAssimp::_ai_anim_string_to_string(const aiString p_string) const {
- Vector<char> raw_name;
- raw_name.resize(p_string.length);
- memcpy(raw_name.ptrw(), p_string.C_Str(), p_string.length);
+String EditorSceneImporterAssimp::_assimp_anim_string_to_string(const aiString p_string) const {
+
String name;
- name.parse_utf8(raw_name.ptrw(), raw_name.size());
+ name.parse_utf8(p_string.C_Str() /*,p_string.length*/);
if (name.find(":") != -1) {
String replaced_name = name.split(":")[1];
print_verbose("Replacing " + name + " containing : with " + replaced_name);
@@ -2155,12 +1747,9 @@ String EditorSceneImporterAssimp::_ai_anim_string_to_string(const aiString p_str
return name;
}
-String EditorSceneImporterAssimp::_ai_raw_string_to_string(const aiString p_string) const {
- Vector<char> raw_name;
- raw_name.resize(p_string.length);
- memcpy(raw_name.ptrw(), p_string.C_Str(), p_string.length);
+String EditorSceneImporterAssimp::_assimp_raw_string_to_string(const aiString p_string) const {
String name;
- name.parse_utf8(raw_name.ptrw(), raw_name.size());
+ name.parse_utf8(p_string.C_Str() /*,p_string.length*/);
return name;
}
@@ -2168,14 +1757,10 @@ Ref<Animation> EditorSceneImporterAssimp::import_animation(const String &p_path,
return Ref<Animation>();
}
-const Transform EditorSceneImporterAssimp::_ai_matrix_transform(const aiMatrix4x4 p_matrix) {
+const Transform EditorSceneImporterAssimp::_assimp_matrix_transform(const aiMatrix4x4 p_matrix) {
aiMatrix4x4 matrix = p_matrix;
Transform xform;
- xform.set(matrix.a1, matrix.b1, matrix.c1, matrix.a2, matrix.b2, matrix.c2, matrix.a3, matrix.b3, matrix.c3, matrix.a4, matrix.b4, matrix.c4);
- xform.basis.inverse();
- xform.basis.transpose();
- Vector3 scale = xform.basis.get_scale();
- Quat rot = xform.basis.get_rotation_quat();
- xform.basis.set_quat_scale(rot, scale);
+ //xform.set(matrix.a1, matrix.b1, matrix.c1, matrix.a2, matrix.b2, matrix.c2, matrix.a3, matrix.b3, matrix.c3, matrix.a4, matrix.b4, matrix.c4);
+ xform.set(matrix.a1, matrix.a2, matrix.a3, matrix.b1, matrix.b2, matrix.b3, matrix.c1, matrix.c2, matrix.c3, matrix.a4, matrix.b4, matrix.c4);
return xform;
}
diff --git a/modules/assimp/editor_scene_importer_assimp.h b/modules/assimp/editor_scene_importer_assimp.h
index 8f9ed434ae..598845236e 100644
--- a/modules/assimp/editor_scene_importer_assimp.h
+++ b/modules/assimp/editor_scene_importer_assimp.h
@@ -146,37 +146,65 @@ private:
COORD_LEFT = 1
};
};
- Spatial *_generate_scene(const String &p_path, const aiScene *scene, const uint32_t p_flags, int p_bake_fps, const int32_t p_max_bone_weights);
- void _fill_kept_node(Set<Node *> &keep_nodes);
- String _find_skeleton_bone_root(Map<Skeleton *, MeshInstance *> &skeletons, Map<MeshInstance *, String> &meshes, Spatial *root);
- void _set_bone_parent(Skeleton *s, Node *p_owner, aiNode *p_node);
- Transform _get_global_ai_node_transform(const aiScene *p_scene, const aiNode *p_current_node);
- void _generate_node_bone(const aiScene *p_scene, const aiNode *p_node, Map<String, bool> &p_mesh_bones, Skeleton *p_skeleton, const String p_path, const int32_t p_max_bone_weights);
- void _generate_node_bone_parents(const aiScene *p_scene, const aiNode *p_node, Map<String, bool> &p_mesh_bones, Skeleton *p_skeleton, const MeshInstance *p_mi);
- void _calculate_skeleton_root(Skeleton *s, const aiScene *p_scene, aiNode *&p_ai_skeleton_root, Map<String, bool> &mesh_bones, const aiNode *p_node);
- void _fill_skeleton(const aiScene *p_scene, const aiNode *p_node, Spatial *p_current, Node *p_owner, Skeleton *p_skeleton, const Map<String, bool> p_mesh_bones, const Map<String, Transform> &p_bone_rests, Set<String> p_tracks, const String p_path, Set<String> &r_removed_bones);
- void _keep_node(const String &p_path, Node *p_current, Node *p_owner, Set<Node *> &r_keep_nodes);
- void _filter_node(const String &p_path, Node *p_current, Node *p_owner, const Set<Node *> p_keep_nodes, Set<String> &r_removed_nodes);
- void _generate_node(const String &p_path, const aiScene *p_scene, const aiNode *p_node, Node *p_parent, Node *p_owner, Set<String> &r_bone_name, Set<String> p_light_names, Set<String> p_camera_names, Map<Skeleton *, MeshInstance *> &r_skeletons, const Map<String, Transform> &p_bone_rests, Vector<MeshInstance *> &r_mesh_instances, int32_t &r_mesh_count, Skeleton *p_skeleton, const int32_t p_max_bone_weights, Set<String> &r_removed_bones, Map<String, Map<uint32_t, String> > &r_name_morph_mesh_names);
- aiNode *_ai_find_node(aiNode *ai_child_node, const String bone_name);
- Transform _format_rot_xform(const String p_path, const aiScene *p_scene);
- void _get_track_set(const aiScene *p_scene, Set<String> &tracks);
- void _insert_animation_track(const aiScene *p_scene, const String p_path, int p_bake_fps, Ref<Animation> animation, float ticks_per_second, float length, const Skeleton *sk, const aiNodeAnim *track, String node_name, NodePath node_path);
- void _add_mesh_to_mesh_instance(const aiNode *p_node, const aiScene *p_scene, Skeleton *s, const String &p_path, MeshInstance *p_mesh_instance, Node *p_owner, Set<String> &r_bone_name, int32_t &r_mesh_count, int32_t p_max_bone_weights, Map<String, Map<uint32_t, String> > &r_name_morph_mesh_names);
- Ref<Texture> _load_texture(const aiScene *p_scene, String p_path);
+
+ struct ImportState {
+
+ String path;
+ const aiScene *assimp_scene;
+ uint32_t max_bone_weights;
+ Spatial *root;
+ Map<String, Ref<Mesh> > mesh_cache;
+ Map<int, Ref<Material> > material_cache;
+ Map<String, int> light_cache;
+ Map<String, int> camera_cache;
+ Vector<Skeleton *> skeletons;
+ Map<String, int> bone_owners; //maps bones to skeleton index owned by
+ Map<String, Node *> node_map;
+ Map<MeshInstance *, Skeleton *> mesh_skeletons;
+ bool fbx; //for some reason assimp does some things different for FBX
+ AnimationPlayer *animation_player;
+ };
+
+ struct BoneInfo {
+ uint32_t bone;
+ float weight;
+ };
+
+ struct SkeletonHole { //nodes may be part of the skeleton by used by vertex
+ String name;
+ String parent;
+ Transform pose;
+ const aiNode *node;
+ };
+
+ const Transform _assimp_matrix_transform(const aiMatrix4x4 p_matrix);
+ String _assimp_get_string(const aiString p_string) const;
+ Transform _get_global_assimp_node_transform(const aiNode *p_current_node);
+
void _calc_tangent_from_mesh(const aiMesh *ai_mesh, int i, int tri_index, int index, PoolColorArray::Write &w);
void _set_texture_mapping_mode(aiTextureMapMode *map_mode, Ref<Texture> texture);
void _find_texture_path(const String &p_path, String &path, bool &r_found);
void _find_texture_path(const String &p_path, _Directory &dir, String &path, bool &found, String extension);
- String _ai_string_to_string(const aiString p_string) const;
- String _ai_anim_string_to_string(const aiString p_string) const;
- String _ai_raw_string_to_string(const aiString p_string) const;
- void _import_animation(const String p_path, const Vector<MeshInstance *> p_meshes, const aiScene *p_scene, AnimationPlayer *ap, int32_t p_index, int p_bake_fps, Map<Skeleton *, MeshInstance *> p_skeletons, const Set<String> p_removed_nodes, const Set<String> removed_bones, const Map<String, Map<uint32_t, String> > p_path_morph_mesh_names);
- void _insert_pivot_anim_track(const Vector<MeshInstance *> p_meshes, const String p_node_name, Vector<const aiNodeAnim *> F, AnimationPlayer *ap, Skeleton *sk, float &length, float ticks_per_second, Ref<Animation> animation, int p_bake_fps, const String &p_path, const aiScene *p_scene);
+
+ Ref<Texture> _load_texture(ImportState &state, String p_path);
+ Ref<Material> _generate_material_from_index(ImportState &state, int p_index, bool p_double_sided);
+ Ref<Mesh> _generate_mesh_from_surface_indices(ImportState &state, const Vector<int> &p_surface_indices, Skeleton *p_skeleton = NULL, bool p_double_sided_material = false);
+ void _generate_node(ImportState &state, const aiNode *p_assimp_node, Node *p_parent);
+ void _generate_bone_groups(ImportState &state, const aiNode *p_assimp_node, Map<String, int> &ownership, Map<String, Transform> &bind_xforms);
+ void _fill_node_relationships(ImportState &state, const aiNode *p_assimp_node, Map<String, int> &ownership, Map<int, int> &skeleton_map, int p_skeleton_id, Skeleton *p_skeleton, const String &p_parent_name, int &holecount, const Vector<SkeletonHole> &p_holes, const Map<String, Transform> &bind_xforms);
+ void _generate_skeletons(ImportState &state, const aiNode *p_assimp_node, Map<String, int> &ownership, Map<int, int> &skeleton_map, const Map<String, Transform> &bind_xforms);
+
+ void _insert_animation_track(ImportState &scene, const aiAnimation *assimp_anim, int p_track, int p_bake_fps, Ref<Animation> animation, float ticks_per_second, Skeleton *p_skeleton, const NodePath &p_path, const String &p_name);
+
+ void _import_animation(ImportState &state, int p_animation_index, int p_bake_fps);
+
+ Spatial *_generate_scene(const String &p_path, const aiScene *scene, const uint32_t p_flags, int p_bake_fps, const int32_t p_max_bone_weights);
+
+ String _assimp_anim_string_to_string(const aiString p_string) const;
+ String _assimp_raw_string_to_string(const aiString p_string) const;
float _get_fbx_fps(int32_t time_mode, const aiScene *p_scene);
template <class T>
T _interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, AssetImportAnimation::Interpolation p_interp);
- const Transform _ai_matrix_transform(const aiMatrix4x4 p_matrix);
void _register_project_setting_import(const String generic, const String import_setting_string, const Vector<String> &exts, List<String> *r_extensions, const bool p_enabled) const;
struct ImportFormat {
diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp
index 0a94690989..059c06c37c 100644
--- a/modules/dds/texture_loader_dds.cpp
+++ b/modules/dds/texture_loader_dds.cpp
@@ -432,7 +432,8 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
} break;
- default: {}
+ default: {
+ }
}
wb = PoolVector<uint8_t>::Write();
diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp
index 000917507a..193f1bb48d 100644
--- a/modules/enet/networked_multiplayer_enet.cpp
+++ b/modules/enet/networked_multiplayer_enet.cpp
@@ -690,7 +690,9 @@ size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *
case COMPRESS_ZSTD: {
mode = Compression::MODE_ZSTD;
} break;
- default: { ERR_FAIL_V(0); }
+ default: {
+ ERR_FAIL_V(0);
+ }
}
int req_size = Compression::get_max_compressed_buffer_size(ofs, mode);
@@ -727,7 +729,8 @@ size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD);
} break;
- default: {}
+ default: {
+ }
}
if (ret < 0) {
return 0;
diff --git a/modules/etc/image_etc.cpp b/modules/etc/image_etc.cpp
index 5410d367db..6f54436bf9 100644
--- a/modules/etc/image_etc.cpp
+++ b/modules/etc/image_etc.cpp
@@ -115,7 +115,8 @@ static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_f
case Image::FORMAT_RGBA5551: {
detected_channels = Image::DETECTED_RGBA;
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json
index 71e7eecd1d..9882a89794 100644
--- a/modules/gdnative/gdnative_api.json
+++ b/modules/gdnative/gdnative_api.json
@@ -6427,7 +6427,24 @@
"major": 3,
"minor": 1
},
- "next": null,
+ "next": {
+ "type": "NET",
+ "version": {
+ "major": 3,
+ "minor": 2
+ },
+ "next": null,
+ "api": [
+ {
+ "name": "godot_net_bind_webrtc_peer",
+ "return_type": "void",
+ "arguments": [
+ ["godot_object *", "p_obj"],
+ ["const godot_net_webrtc_peer *", "p_interface"]
+ ]
+ }
+ ]
+ },
"api": [
{
"name": "godot_net_bind_stream_peer",
diff --git a/modules/gdnative/include/net/godot_net.h b/modules/gdnative/include/net/godot_net.h
index d7de04e725..c1bc9daab5 100644
--- a/modules/gdnative/include/net/godot_net.h
+++ b/modules/gdnative/include/net/godot_net.h
@@ -111,6 +111,35 @@ typedef struct {
/* Binds a MultiplayerPeerGDNative to the provided interface */
void GDAPI godot_net_bind_multiplayer_peer(godot_object *p_obj, const godot_net_multiplayer_peer *);
+typedef struct {
+ godot_gdnative_api_version version; /* version of our API */
+
+ godot_object *data; /* User reference */
+
+ /* This is PacketPeer */
+ godot_error (*get_packet)(void *, const uint8_t **, int *);
+ godot_error (*put_packet)(void *, const uint8_t *, int);
+ godot_int (*get_available_packet_count)(const void *);
+ godot_int (*get_max_packet_size)(const void *);
+
+ /* This is WebRTCPeer */
+ void (*set_write_mode)(void *, godot_int);
+ godot_int (*get_write_mode)(const void *);
+ bool (*was_string_packet)(const void *);
+ godot_int (*get_connection_state)(const void *);
+
+ godot_error (*create_offer)(void *);
+ godot_error (*set_remote_description)(void *, const char *, const char *);
+ godot_error (*set_local_description)(void *, const char *, const char *);
+ godot_error (*add_ice_candidate)(void *, const char *, int, const char *);
+ godot_error (*poll)(void *);
+
+ void *next; /* For extension? */
+} godot_net_webrtc_peer;
+
+/* Binds a PacketPeerGDNative to the provided interface */
+void GDAPI godot_net_bind_webrtc_peer(godot_object *p_obj, const godot_net_webrtc_peer *);
+
#ifdef __cplusplus
}
#endif
diff --git a/modules/gdnative/net/SCsub b/modules/gdnative/net/SCsub
index e915703935..18ab9986b0 100644
--- a/modules/gdnative/net/SCsub
+++ b/modules/gdnative/net/SCsub
@@ -3,5 +3,11 @@
Import('env')
Import('env_gdnative')
-env_gdnative.add_source_files(env.modules_sources, '*.cpp')
+env_net = env_gdnative.Clone()
+
+has_webrtc = env_net["module_webrtc_enabled"]
+if has_webrtc:
+ env_net.Append(CPPDEFINES=['WEBRTC_GDNATIVE_ENABLED'])
+
+env_net.add_source_files(env.modules_sources, '*.cpp')
diff --git a/modules/gdnative/net/webrtc_peer_gdnative.cpp b/modules/gdnative/net/webrtc_peer_gdnative.cpp
new file mode 100644
index 0000000000..60b1ed4fe4
--- /dev/null
+++ b/modules/gdnative/net/webrtc_peer_gdnative.cpp
@@ -0,0 +1,45 @@
+/*************************************************************************/
+/* packet_peer_gdnative.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "modules/gdnative/gdnative.h"
+#include "modules/gdnative/include/net/godot_net.h"
+
+#ifdef WEBRTC_GDNATIVE_ENABLED
+#include "modules/webrtc/webrtc_peer_gdnative.h"
+#endif
+
+extern "C" {
+
+void GDAPI godot_net_bind_webrtc_peer(godot_object *p_obj, const godot_net_webrtc_peer *p_impl) {
+#ifdef WEBRTC_GDNATIVE_ENABLED
+ ((WebRTCPeerGDNative *)p_obj)->set_native_webrtc_peer(p_impl);
+#endif
+}
+}
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp
index 0676317f6e..eada389c51 100644
--- a/modules/gdscript/gdscript.cpp
+++ b/modules/gdscript/gdscript.cpp
@@ -1945,6 +1945,10 @@ String GDScriptWarning::get_message() const {
CHECK_SYMBOLS(1);
return "The local variable '" + symbols[0] + "' is declared but never used in the block.";
} break;
+ case SHADOWED_VARIABLE: {
+ CHECK_SYMBOLS(2);
+ return "The local variable '" + symbols[0] + "' is shadowing an already defined variable at line " + symbols[1] + ".";
+ } break;
case UNUSED_CLASS_VARIABLE: {
CHECK_SYMBOLS(1);
return "The class variable '" + symbols[0] + "' is declared but never used in the script.";
@@ -2048,6 +2052,7 @@ String GDScriptWarning::get_name_from_code(Code p_code) {
"UNASSIGNED_VARIABLE",
"UNASSIGNED_VARIABLE_OP_ASSIGN",
"UNUSED_VARIABLE",
+ "SHADOWED_VARIABLE",
"UNUSED_CLASS_VARIABLE",
"UNUSED_ARGUMENT",
"UNREACHABLE_CODE",
diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h
index c67e390e32..1d75d9e2fe 100644
--- a/modules/gdscript/gdscript.h
+++ b/modules/gdscript/gdscript.h
@@ -273,6 +273,7 @@ struct GDScriptWarning {
UNASSIGNED_VARIABLE, // Variable used but never assigned
UNASSIGNED_VARIABLE_OP_ASSIGN, // Variable never assigned but used in an assignment operation (+=, *=, etc)
UNUSED_VARIABLE, // Local variable is declared but never used
+ SHADOWED_VARIABLE, // Variable name shadowed by other variable
UNUSED_CLASS_VARIABLE, // Class variable is declared but never used in the file
UNUSED_ARGUMENT, // Function argument is never used
UNREACHABLE_CODE, // Code after a return statement
diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp
index ae67521749..f7be0ce37c 100644
--- a/modules/gdscript/gdscript_compiler.cpp
+++ b/modules/gdscript/gdscript_compiler.cpp
@@ -480,16 +480,16 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser::
switch (cast_type.kind) {
case GDScriptDataType::BUILTIN: {
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_BUILTIN);
- codegen.opcodes.push_back(cn->cast_type.builtin_type);
+ codegen.opcodes.push_back(cast_type.builtin_type);
} break;
case GDScriptDataType::NATIVE: {
int class_idx;
- if (GDScriptLanguage::get_singleton()->get_global_map().has(cn->cast_type.native_type)) {
+ if (GDScriptLanguage::get_singleton()->get_global_map().has(cast_type.native_type)) {
- class_idx = GDScriptLanguage::get_singleton()->get_global_map()[cn->cast_type.native_type];
+ class_idx = GDScriptLanguage::get_singleton()->get_global_map()[cast_type.native_type];
class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root)
} else {
- _set_error("Invalid native class type '" + String(cn->cast_type.native_type) + "'.", cn);
+ _set_error("Invalid native class type '" + String(cast_type.native_type) + "'.", cn);
return -1;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_NATIVE); // perform operator
@@ -498,7 +498,7 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser::
case GDScriptDataType::SCRIPT:
case GDScriptDataType::GDSCRIPT: {
- Variant script = cn->cast_type.script_type;
+ Variant script = cast_type.script_type;
int idx = codegen.get_constant_pos(script);
idx |= GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS; //make it a local constant (faster access)
@@ -1863,6 +1863,19 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar
p_script->base = base;
p_script->_base = base.ptr();
p_script->member_indices = base->member_indices;
+
+ if (p_class->base_type.kind == GDScriptParser::DataType::CLASS) {
+ if (!parsed_classes.has(p_script->_base)) {
+ if (parsing_classes.has(p_script->_base)) {
+ _set_error("Cyclic class reference for '" + String(p_class->name) + "'.", p_class);
+ return ERR_PARSE_ERROR;
+ }
+ Error err = _parse_class_level(p_script->_base, p_class->base_type.class_type, p_keep_state);
+ if (err) {
+ return err;
+ }
+ }
+ }
} break;
default: {
_set_error("Parser bug: invalid inheritance.", p_class);
diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp
index ee0d5ae055..df8fc2267d 100644
--- a/modules/gdscript/gdscript_editor.cpp
+++ b/modules/gdscript/gdscript_editor.cpp
@@ -1070,7 +1070,8 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G
case GDScriptParser::OperatorNode::OP_BIT_AND: vop = Variant::OP_BIT_AND; break;
case GDScriptParser::OperatorNode::OP_BIT_OR: vop = Variant::OP_BIT_OR; break;
case GDScriptParser::OperatorNode::OP_BIT_XOR: vop = Variant::OP_BIT_XOR; break;
- default: {}
+ default: {
+ }
}
if (vop == Variant::OP_MAX) {
@@ -1125,7 +1126,8 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G
} break;
}
} break;
- default: {}
+ default: {
+ }
}
// It may have found a null, but that's never useful
@@ -3380,7 +3382,8 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
return OK;
}
} break;
- default: {}
+ default: {
+ }
}
return ERR_CANT_RESOLVE;
diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp
index e75b8a14a3..80af094c2c 100644
--- a/modules/gdscript/gdscript_parser.cpp
+++ b/modules/gdscript/gdscript_parser.cpp
@@ -888,7 +888,8 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
case GDScriptTokenizer::TK_OP_SUB: e.op = OperatorNode::OP_NEG; break;
case GDScriptTokenizer::TK_OP_NOT: e.op = OperatorNode::OP_NOT; break;
case GDScriptTokenizer::TK_OP_BIT_INVERT: e.op = OperatorNode::OP_BIT_INVERT; break;
- default: {}
+ default: {
+ }
}
tokenizer->advance();
@@ -1875,7 +1876,9 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to
}
} break;
- default: { break; }
+ default: {
+ break;
+ }
}
//now se if all are constants
if (!all_constants)
@@ -1988,7 +1991,9 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to
return op->arguments[2];
}
} break;
- default: { ERR_FAIL_V(op); }
+ default: {
+ ERR_FAIL_V(op);
+ }
}
ERR_FAIL_V(op);
@@ -3495,6 +3500,10 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
_set_error("'class_name' is only valid for the main class namespace.");
return;
}
+ if (self_path.empty()) {
+ _set_error("'class_name' not allowed in built-in scripts.");
+ return;
+ }
if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) {
_set_error("'class_name' syntax: 'class_name <UniqueName>'");
@@ -3681,6 +3690,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
_add_warning(GDScriptWarning::FUNCTION_CONFLICTS_VARIABLE, -1, name);
}
}
+ for (int i = 0; i < p_class->subclasses.size(); i++) {
+ if (p_class->subclasses[i]->name == name) {
+ _add_warning(GDScriptWarning::FUNCTION_CONFLICTS_CONSTANT, -1, name);
+ }
+ }
#endif // DEBUG_ENABLED
if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
@@ -4625,6 +4639,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
return;
}
}
+
+ for (int i = 0; i < current_class->subclasses.size(); i++) {
+ if (current_class->subclasses[i]->name == member.identifier) {
+ _set_error("A class named '" + String(member.identifier) + "' already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
+ return;
+ }
+ }
#ifdef DEBUG_ENABLED
for (int i = 0; i < current_class->functions.size(); i++) {
if (current_class->functions[i]->name == member.identifier) {
@@ -4869,6 +4890,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
}
}
+ for (int i = 0; i < current_class->subclasses.size(); i++) {
+ if (current_class->subclasses[i]->name == const_id) {
+ _set_error("A class named '" + String(const_id) + "' already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
+ return;
+ }
+ }
+
tokenizer->advance();
if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) {
@@ -4939,6 +4967,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
}
}
+ for (int i = 0; i < current_class->subclasses.size(); i++) {
+ if (current_class->subclasses[i]->name == enum_name) {
+ _set_error("A class named '" + String(enum_name) + "' already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
+ return;
+ }
+ }
+
tokenizer->advance();
}
if (tokenizer->get_token() != GDScriptTokenizer::TK_CURLY_BRACKET_OPEN) {
@@ -5024,6 +5059,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
}
}
+ for (int i = 0; i < current_class->subclasses.size(); i++) {
+ if (current_class->subclasses[i]->name == const_id) {
+ _set_error("A class named '" + String(const_id) + "' already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
+ return;
+ }
+ }
+
ClassNode::Constant constant;
constant.type.has_type = true;
constant.type.kind = DataType::BUILTIN;
@@ -6351,7 +6393,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
case Variant::COLOR: {
error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING;
} break;
- default: {}
+ default: {
+ }
}
}
if (error) {
@@ -6469,7 +6512,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
}
}
} break;
- default: {}
+ default: {
+ }
}
p_node->set_datatype(_resolve_type(node_type, p_node->line));
@@ -7614,6 +7658,11 @@ void GDScriptParser::_check_function_types(FunctionNode *p_function) {
if (p_function->arguments_usage[i] == 0 && !p_function->arguments[i].operator String().begins_with("_")) {
_add_warning(GDScriptWarning::UNUSED_ARGUMENT, p_function->line, p_function->name, p_function->arguments[i].operator String());
}
+ for (int j = 0; j < current_class->variables.size(); j++) {
+ if (current_class->variables[j].identifier == p_function->arguments[i]) {
+ _add_warning(GDScriptWarning::SHADOWED_VARIABLE, p_function->line, p_function->arguments[i], itos(current_class->variables[j].line));
+ }
+ }
#endif // DEBUG_ENABLED
}
@@ -7687,6 +7736,17 @@ void GDScriptParser::_check_function_types(FunctionNode *p_function) {
p_function->return_type.has_type = false;
p_function->return_type.may_yield = true;
}
+
+#ifdef DEBUG_ENABLED
+ for (Map<StringName, LocalVarNode *>::Element *E = p_function->body->variables.front(); E; E = E->next()) {
+ LocalVarNode *lv = E->get();
+ for (int i = 0; i < current_class->variables.size(); i++) {
+ if (current_class->variables[i].identifier == lv->name) {
+ _add_warning(GDScriptWarning::SHADOWED_VARIABLE, lv->line, lv->name, itos(current_class->variables[i].line));
+ }
+ }
+ }
+#endif // DEBUG_ENABLED
}
void GDScriptParser::_check_class_blocks_types(ClassNode *p_class) {
diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp
index abc739d645..36503af4d7 100644
--- a/modules/gdscript/gdscript_tokenizer.cpp
+++ b/modules/gdscript/gdscript_tokenizer.cpp
@@ -339,7 +339,8 @@ StringName GDScriptTokenizer::get_token_literal(int p_offset) const {
return "null";
case Variant::BOOL:
return value ? "true" : "false";
- default: {}
+ default: {
+ }
}
}
case TK_OP_AND:
@@ -534,13 +535,14 @@ void GDScriptTokenizerText::_advance() {
}
}
#ifdef DEBUG_ENABLED
- if (comment.begins_with("#warning-ignore:")) {
- String code = comment.get_slice(":", 1);
+ String comment_content = comment.trim_prefix("#").trim_prefix(" ");
+ if (comment_content.begins_with("warning-ignore:")) {
+ String code = comment_content.get_slice(":", 1);
warning_skips.push_back(Pair<int, String>(line, code.strip_edges().to_lower()));
- } else if (comment.begins_with("#warning-ignore-all:")) {
- String code = comment.get_slice(":", 1);
+ } else if (comment_content.begins_with("warning-ignore-all:")) {
+ String code = comment_content.get_slice(":", 1);
warning_global_skips.insert(code.strip_edges().to_lower());
- } else if (comment.strip_edges() == "#warnings-disable") {
+ } else if (comment_content.strip_edges() == "warnings-disable") {
ignore_warnings = true;
}
#endif // DEBUG_ENABLED
@@ -1302,7 +1304,8 @@ Vector<uint8_t> GDScriptTokenizerBuffer::parse_code_string(const String &p_code)
ERR_FAIL_V(Vector<uint8_t>());
} break;
- default: {}
+ default: {
+ }
};
token_array.push_back(token);
diff --git a/modules/mobile_vr/doc_classes/MobileVRInterface.xml b/modules/mobile_vr/doc_classes/MobileVRInterface.xml
index 0a75ad4784..dbebaae38d 100644
--- a/modules/mobile_vr/doc_classes/MobileVRInterface.xml
+++ b/modules/mobile_vr/doc_classes/MobileVRInterface.xml
@@ -5,7 +5,13 @@
</brief_description>
<description>
This is a generic mobile VR implementation where you need to provide details about the phone and HMD used. It does not rely on any existing framework. This is the most basic interface we have. For the best effect you do need a mobile phone with a gyroscope and accelerometer.
- Note that even though there is no positional tracking the camera will assume the headset is at a height of 1.85 meters.
+ Note that even though there is no positional tracking the camera will assume the headset is at a height of 1.85 meters, you can change this by setting [member eye_height].
+ You can initialise this interface as follows:
+ [codeblock]
+ var interface = ARVRServer.find_interface("Native mobile")
+ if interface and interface.initialize():
+ get_viewport().arvr = true
+ [/codeblock]
</description>
<tutorials>
</tutorials>
@@ -20,6 +26,9 @@
<member name="display_width" type="float" setter="set_display_width" getter="get_display_width">
The width of the display in centimeters.
</member>
+ <member name="eye_height" type="float" setter="set_eye_height" getter="get_eye_height">
+ The height at which the camera is placed in relation to the ground (i.e. [ARVROrigin] node).
+ </member>
<member name="iod" type="float" setter="set_iod" getter="get_iod">
The interocular distance, also known as the interpupillary distance. The distance between the pupils of the left and right eye.
</member>
diff --git a/modules/mobile_vr/mobile_vr_interface.cpp b/modules/mobile_vr/mobile_vr_interface.cpp
index b4fbd417d7..dc7ed03548 100644
--- a/modules/mobile_vr/mobile_vr_interface.cpp
+++ b/modules/mobile_vr/mobile_vr_interface.cpp
@@ -200,6 +200,9 @@ void MobileVRInterface::set_position_from_sensors() {
};
void MobileVRInterface::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_eye_height", "eye_height"), &MobileVRInterface::set_eye_height);
+ ClassDB::bind_method(D_METHOD("get_eye_height"), &MobileVRInterface::get_eye_height);
+
ClassDB::bind_method(D_METHOD("set_iod", "iod"), &MobileVRInterface::set_iod);
ClassDB::bind_method(D_METHOD("get_iod"), &MobileVRInterface::get_iod);
@@ -218,6 +221,7 @@ void MobileVRInterface::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_k2", "k"), &MobileVRInterface::set_k2);
ClassDB::bind_method(D_METHOD("get_k2"), &MobileVRInterface::get_k2);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "eye_height", PROPERTY_HINT_RANGE, "0.0,3.0,0.1"), "set_eye_height", "get_eye_height");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "iod", PROPERTY_HINT_RANGE, "4.0,10.0,0.1"), "set_iod", "get_iod");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "display_width", PROPERTY_HINT_RANGE, "5.0,25.0,0.1"), "set_display_width", "get_display_width");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "display_to_lens", PROPERTY_HINT_RANGE, "5.0,25.0,0.1"), "set_display_to_lens", "get_display_to_lens");
@@ -226,6 +230,14 @@ void MobileVRInterface::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::REAL, "k2", PROPERTY_HINT_RANGE, "0.1,10.0,0.0001"), "set_k2", "get_k2");
}
+void MobileVRInterface::set_eye_height(const real_t p_eye_height) {
+ eye_height = p_eye_height;
+}
+
+real_t MobileVRInterface::get_eye_height() const {
+ return eye_height;
+}
+
void MobileVRInterface::set_iod(const real_t p_iod) {
intraocular_dist = p_iod;
};
@@ -328,6 +340,7 @@ Size2 MobileVRInterface::get_render_targetsize() {
// we use half our window size
Size2 target_size = OS::get_singleton()->get_window_size();
+
target_size.x *= 0.5 * oversample;
target_size.y *= oversample;
diff --git a/modules/mobile_vr/mobile_vr_interface.h b/modules/mobile_vr/mobile_vr_interface.h
index adc420ea5f..e595daf16e 100644
--- a/modules/mobile_vr/mobile_vr_interface.h
+++ b/modules/mobile_vr/mobile_vr_interface.h
@@ -107,6 +107,9 @@ protected:
static void _bind_methods();
public:
+ void set_eye_height(const real_t p_eye_height);
+ real_t get_eye_height() const;
+
void set_iod(const real_t p_iod);
real_t get_iod() const;
diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp
index 5f97069485..3c9644127c 100644
--- a/modules/mono/csharp_script.cpp
+++ b/modules/mono/csharp_script.cpp
@@ -1424,6 +1424,34 @@ void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
p_properties->push_back(E->value());
}
+
+ // Call _get_property_list
+
+ ERR_FAIL_COND(!script.is_valid());
+
+ MonoObject *mono_object = get_mono_object();
+ ERR_FAIL_NULL(mono_object);
+
+ GDMonoClass *top = script->script_class;
+
+ while (top && top != script->native) {
+ GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get_property_list), 0);
+
+ if (method) {
+ MonoObject *ret = method->invoke(mono_object);
+
+ if (ret) {
+ Array array = Array(GDMonoMarshal::mono_object_to_variant(ret));
+ for (int i = 0, size = array.size(); i < size; i++)
+ p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
+ return;
+ }
+
+ break;
+ }
+
+ top = top->get_parent_class();
+ }
}
Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
@@ -3027,6 +3055,7 @@ CSharpLanguage::StringNameCache::StringNameCache() {
_signal_callback = StaticCString::create("_signal_callback");
_set = StaticCString::create("_set");
_get = StaticCString::create("_get");
+ _get_property_list = StaticCString::create("_get_property_list");
_notification = StaticCString::create("_notification");
_script_source = StaticCString::create("script/source");
dotctor = StaticCString::create(".ctor");
diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h
index 99877a4379..050527d52b 100644
--- a/modules/mono/csharp_script.h
+++ b/modules/mono/csharp_script.h
@@ -298,6 +298,7 @@ class CSharpLanguage : public ScriptLanguage {
StringName _signal_callback;
StringName _set;
StringName _get;
+ StringName _get_property_list;
StringName _notification;
StringName _script_source;
StringName dotctor; // .ctor
diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp
index 84e2303cf6..fe7ced060d 100644
--- a/modules/mono/editor/bindings_generator.cpp
+++ b/modules/mono/editor/bindings_generator.cpp
@@ -100,7 +100,7 @@
#define BINDINGS_GENERATOR_VERSION UINT32_C(8)
-const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN = "\t%0 %1_in = %1;\n";
+const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN("\t%0 %1_in = %1;\n");
bool BindingsGenerator::verbose_output = false;
@@ -2520,7 +2520,8 @@ void BindingsGenerator::_default_argument_from_variant(const Variant &p_val, Arg
r_iarg.default_argument = Variant::get_type_name(p_val.get_type()) + ".Identity";
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
break;
- default: {}
+ default: {
+ }
}
if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "null")
diff --git a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml
index b5bc35df69..06d22a2d65 100644
--- a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml
+++ b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml
@@ -37,6 +37,14 @@
Generate a noise image with the requested [code]width[/code] and [code]height[/code], based on the current noise parameters.
</description>
</method>
+ <method name="get_noise_1d">
+ <return type="float">
+ </return>
+ <argument index="0" name="x" type="float">
+ </argument>
+ <description>
+ </description>
+ </method>
<method name="get_noise_2d">
<return type="float">
</return>
diff --git a/modules/squish/image_compress_squish.cpp b/modules/squish/image_compress_squish.cpp
index d89839f06a..4f38357aa1 100644
--- a/modules/squish/image_compress_squish.cpp
+++ b/modules/squish/image_compress_squish.cpp
@@ -119,7 +119,8 @@ void image_compress_squish(Image *p_image, float p_lossy_quality, Image::Compres
case Image::FORMAT_RGBA5551: {
dc = Image::DETECTED_RGBA;
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/modules/vhacd/SCsub b/modules/vhacd/SCsub
new file mode 100644
index 0000000000..11cd5f4743
--- /dev/null
+++ b/modules/vhacd/SCsub
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+
+Import('env')
+Import('env_modules')
+
+env_vhacd = env_modules.Clone()
+
+# Thirdparty source files
+
+thirdparty_dir = "#thirdparty/vhacd/"
+
+thirdparty_sources = [
+"src/vhacdManifoldMesh.cpp",
+"src/FloatMath.cpp",
+"src/vhacdMesh.cpp",
+"src/vhacdICHull.cpp",
+"src/vhacdVolume.cpp",
+"src/VHACD-ASYNC.cpp",
+"src/btAlignedAllocator.cpp",
+"src/vhacdRaycastMesh.cpp",
+"src/VHACD.cpp",
+"src/btConvexHullComputer.cpp"
+]
+
+thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
+
+env_vhacd.Append(CPPPATH=[thirdparty_dir+"/inc"])
+env_vhacd.Append(CPPFLAGS=["-DGODOT_ENET"])
+
+# upstream uses c++11
+if not env.msvc:
+ env_vhacd.Append(CCFLAGS="-std=c++11")
+
+env_thirdparty = env_vhacd.Clone()
+env_thirdparty.disable_warnings()
+env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+
+env_vhacd.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/vhacd/config.py b/modules/vhacd/config.py
new file mode 100644
index 0000000000..9ced70d2fb
--- /dev/null
+++ b/modules/vhacd/config.py
@@ -0,0 +1,6 @@
+def can_build(env, platform):
+ return True
+
+def configure(env):
+ pass
+
diff --git a/modules/vhacd/register_types.cpp b/modules/vhacd/register_types.cpp
new file mode 100644
index 0000000000..076a1738ab
--- /dev/null
+++ b/modules/vhacd/register_types.cpp
@@ -0,0 +1,88 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "register_types.h"
+#include "scene/resources/mesh.h"
+#include "thirdparty/vhacd/public/VHACD.h"
+
+static Vector<Vector<Face3> > convex_decompose(const Vector<Face3> &p_faces) {
+
+ Vector<float> vertices;
+ vertices.resize(p_faces.size() * 9);
+ Vector<uint32_t> indices;
+ indices.resize(p_faces.size() * 3);
+
+ for (int i = 0; i < p_faces.size(); i++) {
+ for (int j = 0; j < 3; j++) {
+ vertices.write[i * 9 + j * 3 + 0] = p_faces[i].vertex[j].x;
+ vertices.write[i * 9 + j * 3 + 1] = p_faces[i].vertex[j].y;
+ vertices.write[i * 9 + j * 3 + 2] = p_faces[i].vertex[j].z;
+ indices.write[i * 3 + j] = i * 3 + j;
+ }
+ }
+
+ VHACD::IVHACD *decomposer = VHACD::CreateVHACD();
+ VHACD::IVHACD::Parameters params;
+ decomposer->Compute(vertices.ptr(), vertices.size() / 3, indices.ptr(), indices.size() / 3, params);
+
+ int hull_count = decomposer->GetNConvexHulls();
+
+ Vector<Vector<Face3> > ret;
+
+ for (int i = 0; i < hull_count; i++) {
+ Vector<Face3> triangles;
+ VHACD::IVHACD::ConvexHull hull;
+ decomposer->GetConvexHull(i, hull);
+ triangles.resize(hull.m_nTriangles);
+ for (uint32_t j = 0; j < hull.m_nTriangles; j++) {
+ Face3 f;
+ for (int k = 0; k < 3; k++) {
+ for (int l = 0; l < 3; l++) {
+ f.vertex[k][l] = hull.m_points[hull.m_triangles[j * 3 + k] * 3 + l];
+ }
+ }
+ triangles.write[j] = f;
+ }
+ ret.push_back(triangles);
+ }
+
+ decomposer->Clean();
+ decomposer->Release();
+
+ return ret;
+}
+
+void register_vhacd_types() {
+ Mesh::convex_composition_function = convex_decompose;
+}
+
+void unregister_vhacd_types() {
+ Mesh::convex_composition_function = NULL;
+}
diff --git a/modules/vhacd/register_types.h b/modules/vhacd/register_types.h
new file mode 100644
index 0000000000..cb948faf44
--- /dev/null
+++ b/modules/vhacd/register_types.h
@@ -0,0 +1,32 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+void register_vhacd_types();
+void unregister_vhacd_types();
diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp
index c2ce5f0bf5..d207656705 100644
--- a/modules/visual_script/visual_script_builtin_funcs.cpp
+++ b/modules/visual_script/visual_script_builtin_funcs.cpp
@@ -1287,7 +1287,8 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
*r_return = String(color);
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/modules/visual_script/visual_script_expression.cpp b/modules/visual_script/visual_script_expression.cpp
index a76e4bc36f..772092fabe 100644
--- a/modules/visual_script/visual_script_expression.cpp
+++ b/modules/visual_script/visual_script_expression.cpp
@@ -1032,7 +1032,8 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
case TK_OP_BIT_OR: op = Variant::OP_BIT_OR; break;
case TK_OP_BIT_XOR: op = Variant::OP_BIT_XOR; break;
case TK_OP_BIT_INVERT: op = Variant::OP_BIT_NEGATE; break;
- default: {};
+ default: {
+ };
}
if (op == Variant::OP_MAX) { //stop appending stuff
diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp
index bb0435a679..8fa7d2c0d4 100644
--- a/modules/visual_script/visual_script_func_nodes.cpp
+++ b/modules/visual_script/visual_script_func_nodes.cpp
@@ -1562,7 +1562,8 @@ public:
case VisualScriptPropertySet::ASSIGN_OP_BIT_XOR: {
value = Variant::evaluate(Variant::OP_BIT_XOR, value, p_argument);
} break;
- default: {}
+ default: {
+ }
}
if (index != StringName()) {
diff --git a/modules/webrtc/SCsub b/modules/webrtc/SCsub
new file mode 100644
index 0000000000..446bd530c2
--- /dev/null
+++ b/modules/webrtc/SCsub
@@ -0,0 +1,16 @@
+#!/usr/bin/env python
+
+Import('env')
+Import('env_modules')
+
+# Thirdparty source files
+
+env_webrtc = env_modules.Clone()
+use_gdnative = env_webrtc["module_gdnative_enabled"]
+
+if use_gdnative: # GDNative is retained in Javascript for export compatibility
+ env_webrtc.Append(CPPDEFINES=['WEBRTC_GDNATIVE_ENABLED'])
+ gdnative_includes = ["#modules/gdnative/include/"]
+ env_webrtc.Append(CPPPATH=gdnative_includes)
+
+env_webrtc.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/webrtc/config.py b/modules/webrtc/config.py
new file mode 100644
index 0000000000..5ed245bad2
--- /dev/null
+++ b/modules/webrtc/config.py
@@ -0,0 +1,13 @@
+def can_build(env, platform):
+ return True
+
+def configure(env):
+ pass
+
+def get_doc_classes():
+ return [
+ "WebRTCPeer"
+ ]
+
+def get_doc_path():
+ return "doc_classes"
diff --git a/modules/webrtc/register_types.cpp b/modules/webrtc/register_types.cpp
new file mode 100644
index 0000000000..ee7a766bd9
--- /dev/null
+++ b/modules/webrtc/register_types.cpp
@@ -0,0 +1,55 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "register_types.h"
+#include "webrtc_peer.h"
+
+#ifdef JAVASCRIPT_ENABLED
+#include "emscripten.h"
+#include "webrtc_peer_js.h"
+#endif
+#ifdef WEBRTC_GDNATIVE_ENABLED
+#include "webrtc_peer_gdnative.h"
+#endif
+
+void register_webrtc_types() {
+#ifdef JAVASCRIPT_ENABLED
+ WebRTCPeerJS::make_default();
+#elif defined(WEBRTC_GDNATIVE_ENABLED)
+ WebRTCPeerGDNative::make_default();
+#endif
+
+ ClassDB::register_custom_instance_class<WebRTCPeer>();
+#ifdef WEBRTC_GDNATIVE_ENABLED
+ ClassDB::register_class<WebRTCPeerGDNative>();
+#endif
+}
+
+void unregister_webrtc_types() {}
diff --git a/modules/webrtc/register_types.h b/modules/webrtc/register_types.h
new file mode 100644
index 0000000000..18a5dcc5aa
--- /dev/null
+++ b/modules/webrtc/register_types.h
@@ -0,0 +1,32 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+void register_webrtc_types();
+void unregister_webrtc_types();
diff --git a/modules/webrtc/webrtc_peer.cpp b/modules/webrtc/webrtc_peer.cpp
new file mode 100644
index 0000000000..30c4505df9
--- /dev/null
+++ b/modules/webrtc/webrtc_peer.cpp
@@ -0,0 +1,81 @@
+/*************************************************************************/
+/* webrtc_peer.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "webrtc_peer.h"
+
+WebRTCPeer *(*WebRTCPeer::_create)() = NULL;
+
+Ref<WebRTCPeer> WebRTCPeer::create_ref() {
+
+ if (!_create)
+ return Ref<WebRTCPeer>();
+ return Ref<WebRTCPeer>(_create());
+}
+
+WebRTCPeer *WebRTCPeer::create() {
+
+ if (!_create)
+ return NULL;
+ return _create();
+}
+
+void WebRTCPeer::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("create_offer"), &WebRTCPeer::create_offer);
+ ClassDB::bind_method(D_METHOD("set_local_description", "type", "sdp"), &WebRTCPeer::set_local_description);
+ ClassDB::bind_method(D_METHOD("set_remote_description", "type", "sdp"), &WebRTCPeer::set_remote_description);
+ ClassDB::bind_method(D_METHOD("poll"), &WebRTCPeer::poll);
+ ClassDB::bind_method(D_METHOD("add_ice_candidate", "media", "index", "name"), &WebRTCPeer::add_ice_candidate);
+
+ ClassDB::bind_method(D_METHOD("was_string_packet"), &WebRTCPeer::was_string_packet);
+ ClassDB::bind_method(D_METHOD("set_write_mode", "write_mode"), &WebRTCPeer::set_write_mode);
+ ClassDB::bind_method(D_METHOD("get_write_mode"), &WebRTCPeer::get_write_mode);
+ ClassDB::bind_method(D_METHOD("get_connection_state"), &WebRTCPeer::get_connection_state);
+
+ ADD_SIGNAL(MethodInfo("offer_created", PropertyInfo(Variant::STRING, "type"), PropertyInfo(Variant::STRING, "sdp")));
+ ADD_SIGNAL(MethodInfo("new_ice_candidate", PropertyInfo(Variant::STRING, "media"), PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::STRING, "name")));
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "write_mode", PROPERTY_HINT_ENUM), "set_write_mode", "get_write_mode");
+
+ BIND_ENUM_CONSTANT(WRITE_MODE_TEXT);
+ BIND_ENUM_CONSTANT(WRITE_MODE_BINARY);
+
+ BIND_ENUM_CONSTANT(STATE_NEW);
+ BIND_ENUM_CONSTANT(STATE_CONNECTING);
+ BIND_ENUM_CONSTANT(STATE_CONNECTED);
+ BIND_ENUM_CONSTANT(STATE_DISCONNECTED);
+ BIND_ENUM_CONSTANT(STATE_FAILED);
+ BIND_ENUM_CONSTANT(STATE_CLOSED);
+}
+
+WebRTCPeer::WebRTCPeer() {
+}
+
+WebRTCPeer::~WebRTCPeer() {
+}
diff --git a/modules/webrtc/webrtc_peer.h b/modules/webrtc/webrtc_peer.h
new file mode 100644
index 0000000000..e141c14655
--- /dev/null
+++ b/modules/webrtc/webrtc_peer.h
@@ -0,0 +1,86 @@
+/*************************************************************************/
+/* webrtc_peer.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef WEBRTC_PEER_H
+#define WEBRTC_PEER_H
+
+#include "core/io/packet_peer.h"
+
+class WebRTCPeer : public PacketPeer {
+ GDCLASS(WebRTCPeer, PacketPeer);
+
+public:
+ enum WriteMode {
+ WRITE_MODE_TEXT,
+ WRITE_MODE_BINARY,
+ };
+
+ enum ConnectionState {
+ STATE_NEW,
+ STATE_CONNECTING,
+ STATE_CONNECTED,
+ STATE_DISCONNECTED,
+ STATE_FAILED,
+ STATE_CLOSED
+ };
+
+protected:
+ static void _bind_methods();
+ static WebRTCPeer *(*_create)();
+
+public:
+ virtual void set_write_mode(WriteMode mode) = 0;
+ virtual WriteMode get_write_mode() const = 0;
+ virtual bool was_string_packet() const = 0;
+ virtual ConnectionState get_connection_state() const = 0;
+
+ virtual Error create_offer() = 0;
+ virtual Error set_remote_description(String type, String sdp) = 0;
+ virtual Error set_local_description(String type, String sdp) = 0;
+ virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) = 0;
+ virtual Error poll() = 0;
+
+ /** Inherited from PacketPeer: **/
+ virtual int get_available_packet_count() const = 0;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) = 0; ///< buffer is GONE after next get_packet
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) = 0;
+
+ virtual int get_max_packet_size() const = 0;
+
+ static Ref<WebRTCPeer> create_ref();
+ static WebRTCPeer *create();
+
+ WebRTCPeer();
+ ~WebRTCPeer();
+};
+
+VARIANT_ENUM_CAST(WebRTCPeer::WriteMode);
+VARIANT_ENUM_CAST(WebRTCPeer::ConnectionState);
+#endif // WEBRTC_PEER_H
diff --git a/modules/webrtc/webrtc_peer_gdnative.cpp b/modules/webrtc/webrtc_peer_gdnative.cpp
new file mode 100644
index 0000000000..f782944980
--- /dev/null
+++ b/modules/webrtc/webrtc_peer_gdnative.cpp
@@ -0,0 +1,114 @@
+/*************************************************************************/
+/* webrtc_peer_gdnative.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifdef WEBRTC_GDNATIVE_ENABLED
+
+#include "webrtc_peer_gdnative.h"
+
+void WebRTCPeerGDNative::_bind_methods() {
+}
+
+WebRTCPeerGDNative::WebRTCPeerGDNative() {
+ interface = NULL;
+}
+
+WebRTCPeerGDNative::~WebRTCPeerGDNative() {
+}
+
+Error WebRTCPeerGDNative::create_offer() {
+ ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED);
+ return (Error)interface->create_offer(interface->data);
+}
+
+Error WebRTCPeerGDNative::set_local_description(String p_type, String p_sdp) {
+ ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED);
+ return (Error)interface->set_local_description(interface->data, p_type.utf8().get_data(), p_sdp.utf8().get_data());
+}
+
+Error WebRTCPeerGDNative::set_remote_description(String p_type, String p_sdp) {
+ ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED);
+ return (Error)interface->set_remote_description(interface->data, p_type.utf8().get_data(), p_sdp.utf8().get_data());
+}
+
+Error WebRTCPeerGDNative::add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) {
+ ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED);
+ return (Error)interface->add_ice_candidate(interface->data, sdpMidName.utf8().get_data(), sdpMlineIndexName, sdpName.utf8().get_data());
+}
+
+Error WebRTCPeerGDNative::poll() {
+ ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED);
+ return (Error)interface->poll(interface->data);
+}
+
+void WebRTCPeerGDNative::set_write_mode(WriteMode p_mode) {
+ ERR_FAIL_COND(interface == NULL);
+ interface->set_write_mode(interface->data, p_mode);
+}
+
+WebRTCPeer::WriteMode WebRTCPeerGDNative::get_write_mode() const {
+ ERR_FAIL_COND_V(interface == NULL, WRITE_MODE_BINARY);
+ return (WriteMode)interface->get_write_mode(interface->data);
+}
+
+bool WebRTCPeerGDNative::was_string_packet() const {
+ ERR_FAIL_COND_V(interface == NULL, false);
+ return interface->was_string_packet(interface->data);
+}
+
+WebRTCPeer::ConnectionState WebRTCPeerGDNative::get_connection_state() const {
+ ERR_FAIL_COND_V(interface == NULL, STATE_DISCONNECTED);
+ return STATE_DISCONNECTED;
+}
+
+Error WebRTCPeerGDNative::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
+ ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED);
+ return (Error)interface->get_packet(interface->data, r_buffer, &r_buffer_size);
+}
+
+Error WebRTCPeerGDNative::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
+ ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED);
+ return (Error)interface->put_packet(interface->data, p_buffer, p_buffer_size);
+}
+
+int WebRTCPeerGDNative::get_max_packet_size() const {
+ ERR_FAIL_COND_V(interface == NULL, 0);
+ return interface->get_max_packet_size(interface->data);
+}
+
+int WebRTCPeerGDNative::get_available_packet_count() const {
+ ERR_FAIL_COND_V(interface == NULL, 0);
+ return interface->get_available_packet_count(interface->data);
+}
+
+void WebRTCPeerGDNative::set_native_webrtc_peer(const godot_net_webrtc_peer *p_impl) {
+ interface = p_impl;
+}
+
+#endif // WEBRTC_GDNATIVE_ENABLED
diff --git a/modules/webrtc/webrtc_peer_gdnative.h b/modules/webrtc/webrtc_peer_gdnative.h
new file mode 100644
index 0000000000..6786cec8ea
--- /dev/null
+++ b/modules/webrtc/webrtc_peer_gdnative.h
@@ -0,0 +1,78 @@
+/*************************************************************************/
+/* webrtc_peer_gdnative.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifdef WEBRTC_GDNATIVE_ENABLED
+
+#ifndef WEBRTC_PEER_GDNATIVE_H
+#define WEBRTC_PEER_GDNATIVE_H
+
+#include "modules/gdnative/include/net/godot_net.h"
+#include "webrtc_peer.h"
+
+class WebRTCPeerGDNative : public WebRTCPeer {
+ GDCLASS(WebRTCPeerGDNative, WebRTCPeer);
+
+protected:
+ static void _bind_methods();
+
+private:
+ const godot_net_webrtc_peer *interface;
+
+public:
+ static WebRTCPeer *_create() { return memnew(WebRTCPeerGDNative); }
+ static void make_default() { WebRTCPeer::_create = WebRTCPeerGDNative::_create; }
+
+ void set_native_webrtc_peer(const godot_net_webrtc_peer *p_impl);
+
+ virtual void set_write_mode(WriteMode mode);
+ virtual WriteMode get_write_mode() const;
+ virtual bool was_string_packet() const;
+ virtual ConnectionState get_connection_state() const;
+
+ virtual Error create_offer();
+ virtual Error set_remote_description(String type, String sdp);
+ virtual Error set_local_description(String type, String sdp);
+ virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName);
+ virtual Error poll();
+
+ /** Inherited from PacketPeer: **/
+ virtual int get_available_packet_count() const;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
+
+ virtual int get_max_packet_size() const;
+
+ WebRTCPeerGDNative();
+ ~WebRTCPeerGDNative();
+};
+
+#endif // WEBRTC_PEER_GDNATIVE_H
+
+#endif // WEBRTC_GDNATIVE_ENABLED
diff --git a/modules/webrtc/webrtc_peer_js.cpp b/modules/webrtc/webrtc_peer_js.cpp
new file mode 100644
index 0000000000..1282e075ab
--- /dev/null
+++ b/modules/webrtc/webrtc_peer_js.cpp
@@ -0,0 +1,455 @@
+/*************************************************************************/
+/* webrtc_peer_js.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifdef JAVASCRIPT_ENABLED
+
+#include "webrtc_peer_js.h"
+#include "emscripten.h"
+
+extern "C" {
+EMSCRIPTEN_KEEPALIVE void _emrtc_on_ice_candidate(void *obj, char *p_MidName, int p_MlineIndexName, char *p_sdpName) {
+ WebRTCPeerJS *peer = static_cast<WebRTCPeerJS *>(obj);
+ peer->emit_signal("new_ice_candidate", String(p_MidName), p_MlineIndexName, String(p_sdpName));
+}
+
+EMSCRIPTEN_KEEPALIVE void _emrtc_offer_created(void *obj, char *p_type, char *p_offer) {
+ WebRTCPeerJS *peer = static_cast<WebRTCPeerJS *>(obj);
+ peer->emit_signal("offer_created", String(p_type), String(p_offer));
+}
+
+EMSCRIPTEN_KEEPALIVE void _emrtc_on_error(void *obj) {
+ WebRTCPeerJS *peer = static_cast<WebRTCPeerJS *>(obj);
+ peer->_on_error();
+}
+
+EMSCRIPTEN_KEEPALIVE void _emrtc_on_open(void *obj) {
+ WebRTCPeerJS *peer = static_cast<WebRTCPeerJS *>(obj);
+ peer->_on_open();
+}
+
+EMSCRIPTEN_KEEPALIVE void _emrtc_on_close(void *obj) {
+ WebRTCPeerJS *peer = static_cast<WebRTCPeerJS *>(obj);
+ peer->_on_close();
+}
+
+EMSCRIPTEN_KEEPALIVE void _emrtc_on_message(void *obj, uint8_t *p_data, uint32_t p_size, bool p_is_string) {
+ WebRTCPeerJS *peer = static_cast<WebRTCPeerJS *>(obj);
+ peer->_on_message(p_data, p_size, p_is_string);
+}
+
+EMSCRIPTEN_KEEPALIVE void _emrtc_bind_channel(int p_id) {
+ /* clang-format off */
+ EM_ASM({
+ if (!Module.IDHandler.has($0)) {
+ return; // Godot Object is gone!
+ }
+ var dict = Module.IDHandler.get($0);
+ var channel = dict["channel"];
+ var c_ptr = dict["ptr"];
+
+ channel.onopen = function (evt) {
+ ccall("_emrtc_on_open",
+ "void",
+ ["number"],
+ [c_ptr]
+ );
+ };
+ channel.onclose = function (evt) {
+ ccall("_emrtc_on_close",
+ "void",
+ ["number"],
+ [c_ptr]
+ );
+ };
+ channel.onerror = function (evt) {
+ ccall("_emrtc_on_error",
+ "void",
+ ["number"],
+ [c_ptr]
+ );
+ };
+
+ channel.binaryType = "arraybuffer";
+ channel.onmessage = function(event) {
+ var buffer;
+ var is_string = 0;
+ if (event.data instanceof ArrayBuffer) {
+
+ buffer = new Uint8Array(event.data);
+
+ } else if (event.data instanceof Blob) {
+
+ alert("Blob type not supported");
+ return;
+
+ } else if (typeof event.data === "string") {
+
+ is_string = 1;
+ var enc = new TextEncoder("utf-8");
+ buffer = new Uint8Array(enc.encode(event.data));
+
+ } else {
+
+ alert("Unknown message type");
+ return;
+
+ }
+ var len = buffer.length*buffer.BYTES_PER_ELEMENT;
+ var out = Module._malloc(len);
+ Module.HEAPU8.set(buffer, out);
+ ccall("_emrtc_on_message",
+ "void",
+ ["number", "number", "number", "number"],
+ [c_ptr, out, len, is_string]
+ );
+ Module._free(out);
+ }
+ }, p_id);
+ /* clang-format on */
+}
+}
+
+void _emrtc_create_pc(int p_id) {
+ /* clang-format off */
+ EM_ASM({
+ var dict = Module.IDHandler.get($0);
+ var c_ptr = dict["ptr"];
+ // Setup local connaction
+ var conn = new RTCPeerConnection();
+ conn.onicecandidate = function(event) {
+ if (!Module.IDHandler.get($0)) return;
+ if (!event.candidate) return;
+
+ var c = event.candidate;
+ // should emit on ice candidate
+ ccall("_emrtc_on_ice_candidate",
+ "void",
+ ["number", "string", "number", "string"],
+ [c_ptr, c.sdpMid, c.sdpMLineIndex, c.candidate]
+ );
+ };
+ conn.ondatachannel = function (evt) {
+ var dict = Module.IDHandler.get($0);
+ if (!dict || dict["channel"]) {
+ return;
+ }
+ var channel = evt.channel;
+ dict["channel"] = channel;
+ ccall("_emrtc_bind_channel",
+ "void",
+ ["number"],
+ [$0]
+ );
+ };
+ dict["conn"] = conn;
+ }, p_id);
+ /* clang-format on */
+}
+
+void WebRTCPeerJS::_on_open() {
+ in_buffer.resize(16);
+ _conn_state = STATE_CONNECTED;
+}
+
+void WebRTCPeerJS::_on_close() {
+ close();
+}
+
+void WebRTCPeerJS::_on_error() {
+ close();
+ _conn_state = STATE_FAILED;
+}
+
+void WebRTCPeerJS::_on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string) {
+ if (in_buffer.space_left() < p_size + 5) {
+ ERR_EXPLAIN("Buffer full! Dropping data");
+ ERR_FAIL();
+ }
+
+ uint8_t is_string = p_is_string ? 1 : 0;
+ in_buffer.write((uint8_t *)&p_size, 4);
+ in_buffer.write((uint8_t *)&is_string, 1);
+ in_buffer.write(p_data, p_size);
+ queue_count++;
+}
+
+void WebRTCPeerJS::close() {
+ in_buffer.resize(0);
+ queue_count = 0;
+ _was_string = false;
+ /* clang-format off */
+ EM_ASM({
+ var dict = Module.IDHandler.get($0);
+ if (!dict) return;
+ if (dict["channel"]) {
+ dict["channel"].close();
+ dict["channel"] = null;
+ }
+ if (dict["conn"]) {
+ dict["conn"].close();
+ }
+ }, _js_id);
+ /* clang-format on */
+ _conn_state = STATE_CLOSED;
+}
+
+Error WebRTCPeerJS::create_offer() {
+ ERR_FAIL_COND_V(_conn_state != STATE_NEW, FAILED);
+
+ _conn_state = STATE_CONNECTING;
+ /* clang-format off */
+ EM_ASM({
+ var dict = Module.IDHandler.get($0);
+ var conn = dict["conn"];
+ var c_ptr = dict["ptr"];
+ var onError = function(error) {
+ console.log(error);
+ ccall("_emrtc_on_error",
+ "void",
+ ["number"],
+ [c_ptr]
+ );
+ };
+ var onCreated = function(offer) {
+ ccall("_emrtc_offer_created",
+ "void",
+ ["number", "string", "string"],
+ [c_ptr, offer.type, offer.sdp]
+ );
+ };
+
+ var channel = conn.createDataChannel("default");
+ dict["channel"] = channel;
+ ccall("_emrtc_bind_channel",
+ "void",
+ ["number"],
+ [$0]
+ );
+ conn.createOffer().then(onCreated).catch(onError);
+ }, _js_id);
+ /* clang-format on */
+ return OK;
+}
+
+Error WebRTCPeerJS::set_local_description(String type, String sdp) {
+ /* clang-format off */
+ EM_ASM({
+ var dict = Module.IDHandler.get($0);
+ var conn = dict["conn"];
+ var c_ptr = dict["ptr"];
+ var type = UTF8ToString($1);
+ var sdp = UTF8ToString($2);
+ var onError = function(error) {
+ console.log(error);
+ ccall("_emrtc_on_error",
+ "void",
+ ["number"],
+ [c_ptr]
+ );
+ };
+ conn.setLocalDescription({
+ "sdp": sdp,
+ "type": type
+ }).catch(onError);
+ }, _js_id, type.utf8().get_data(), sdp.utf8().get_data());
+ /* clang-format on */
+ return OK;
+}
+
+Error WebRTCPeerJS::set_remote_description(String type, String sdp) {
+ if (type == "offer") {
+ ERR_FAIL_COND_V(_conn_state != STATE_NEW, FAILED);
+ _conn_state = STATE_CONNECTING;
+ }
+ /* clang-format off */
+ EM_ASM({
+ var dict = Module.IDHandler.get($0);
+ var conn = dict["conn"];
+ var c_ptr = dict["ptr"];
+ var type = UTF8ToString($1);
+ var sdp = UTF8ToString($2);
+
+ var onError = function(error) {
+ console.log(error);
+ ccall("_emrtc_on_error",
+ "void",
+ ["number"],
+ [c_ptr]
+ );
+ };
+ var onCreated = function(offer) {
+ ccall("_emrtc_offer_created",
+ "void",
+ ["number", "string", "string"],
+ [c_ptr, offer.type, offer.sdp]
+ );
+ };
+ var onSet = function() {
+ if (type != "offer") {
+ return;
+ }
+ conn.createAnswer().then(onCreated);
+ };
+ conn.setRemoteDescription({
+ "sdp": sdp,
+ "type": type
+ }).then(onSet).catch(onError);
+ }, _js_id, type.utf8().get_data(), sdp.utf8().get_data());
+ /* clang-format on */
+ return OK;
+}
+
+Error WebRTCPeerJS::add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) {
+ /* clang-format off */
+ EM_ASM({
+ var dict = Module.IDHandler.get($0);
+ var conn = dict["conn"];
+ var c_ptr = dict["ptr"];
+ var sdpMidName = UTF8ToString($1);
+ var sdpMlineIndexName = UTF8ToString($2);
+ var sdpName = UTF8ToString($3);
+ conn.addIceCandidate(new RTCIceCandidate({
+ "candidate": sdpName,
+ "sdpMid": sdpMidName,
+ "sdpMlineIndex": sdpMlineIndexName
+ }));
+ }, _js_id, sdpMidName.utf8().get_data(), sdpMlineIndexName, sdpName.utf8().get_data());
+ /* clang-format on */
+ return OK;
+}
+
+Error WebRTCPeerJS::poll() {
+ return OK;
+}
+
+WebRTCPeer::ConnectionState WebRTCPeerJS::get_connection_state() const {
+ return _conn_state;
+}
+
+int WebRTCPeerJS::get_available_packet_count() const {
+ return queue_count;
+}
+
+Error WebRTCPeerJS::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
+ ERR_FAIL_COND_V(_conn_state != STATE_CONNECTED, ERR_UNCONFIGURED);
+
+ if (queue_count == 0)
+ return ERR_UNAVAILABLE;
+
+ uint32_t to_read = 0;
+ uint32_t left = 0;
+ uint8_t is_string = 0;
+ r_buffer_size = 0;
+
+ in_buffer.read((uint8_t *)&to_read, 4);
+ --queue_count;
+ left = in_buffer.data_left();
+
+ if (left < to_read + 1) {
+ in_buffer.advance_read(left);
+ return FAILED;
+ }
+
+ in_buffer.read(&is_string, 1);
+ _was_string = is_string == 1;
+ in_buffer.read(packet_buffer, to_read);
+ *r_buffer = packet_buffer;
+ r_buffer_size = to_read;
+
+ return OK;
+}
+
+Error WebRTCPeerJS::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
+ ERR_FAIL_COND_V(_conn_state != STATE_CONNECTED, ERR_UNCONFIGURED);
+
+ int is_bin = _write_mode == WebRTCPeer::WRITE_MODE_BINARY ? 1 : 0;
+
+ /* clang-format off */
+ EM_ASM({
+ var dict = Module.IDHandler.get($0);
+ var channel = dict["channel"];
+ var bytes_array = new Uint8Array($2);
+ var i = 0;
+
+ for(i=0; i<$2; i++) {
+ bytes_array[i] = getValue($1+i, 'i8');
+ }
+
+ if ($3) {
+ channel.send(bytes_array.buffer);
+ } else {
+ var string = new TextDecoder("utf-8").decode(bytes_array);
+ channel.send(string);
+ }
+ }, _js_id, p_buffer, p_buffer_size, is_bin);
+ /* clang-format on */
+
+ return OK;
+}
+
+int WebRTCPeerJS::get_max_packet_size() const {
+ return 1200;
+}
+
+void WebRTCPeerJS::set_write_mode(WriteMode p_mode) {
+ _write_mode = p_mode;
+}
+
+WebRTCPeer::WriteMode WebRTCPeerJS::get_write_mode() const {
+ return _write_mode;
+}
+
+bool WebRTCPeerJS::was_string_packet() const {
+ return _was_string;
+}
+
+WebRTCPeerJS::WebRTCPeerJS() {
+ queue_count = 0;
+ _was_string = false;
+ _write_mode = WRITE_MODE_BINARY;
+ _conn_state = STATE_NEW;
+
+ /* clang-format off */
+ _js_id = EM_ASM_INT({
+ return Module.IDHandler.add({"conn": null, "ptr": $0, "channel": null});
+ }, this);
+ /* clang-format on */
+ _emrtc_create_pc(_js_id);
+}
+
+WebRTCPeerJS::~WebRTCPeerJS() {
+ close();
+ /* clang-format off */
+ EM_ASM({
+ Module.IDHandler.remove($0);
+ }, _js_id);
+ /* clang-format on */
+};
+#endif
diff --git a/modules/webrtc/webrtc_peer_js.h b/modules/webrtc/webrtc_peer_js.h
new file mode 100644
index 0000000000..02f0c9b55d
--- /dev/null
+++ b/modules/webrtc/webrtc_peer_js.h
@@ -0,0 +1,88 @@
+/*************************************************************************/
+/* webrtc_peer_js.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef WEBRTC_PEER_JS_H
+#define WEBRTC_PEER_JS_H
+
+#ifdef JAVASCRIPT_ENABLED
+
+#include "webrtc_peer.h"
+
+class WebRTCPeerJS : public WebRTCPeer {
+
+private:
+ enum {
+ PACKET_BUFFER_SIZE = 65536 - 5 // 4 bytes for the size, 1 for for type
+ };
+
+ bool _was_string;
+ WriteMode _write_mode;
+
+ int _js_id;
+ RingBuffer<uint8_t> in_buffer;
+ int queue_count;
+ uint8_t packet_buffer[PACKET_BUFFER_SIZE];
+ ConnectionState _conn_state;
+
+public:
+ static WebRTCPeer *_create() { return memnew(WebRTCPeerJS); }
+ static void make_default() { WebRTCPeer::_create = WebRTCPeerJS::_create; }
+
+ virtual void set_write_mode(WriteMode mode);
+ virtual WriteMode get_write_mode() const;
+ virtual bool was_string_packet() const;
+ virtual ConnectionState get_connection_state() const;
+
+ virtual Error create_offer();
+ virtual Error set_remote_description(String type, String sdp);
+ virtual Error set_local_description(String type, String sdp);
+ virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName);
+ virtual Error poll();
+
+ /** Inherited from PacketPeer: **/
+ virtual int get_available_packet_count() const;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
+
+ virtual int get_max_packet_size() const;
+
+ void close();
+ void _on_open();
+ void _on_close();
+ void _on_error();
+ void _on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string);
+
+ WebRTCPeerJS();
+ ~WebRTCPeerJS();
+};
+
+#endif
+
+#endif // WEBRTC_PEER_JS_H
diff --git a/modules/websocket/register_types.cpp b/modules/websocket/register_types.cpp
index ed6cc5638e..39bf3de982 100644
--- a/modules/websocket/register_types.cpp
+++ b/modules/websocket/register_types.cpp
@@ -60,25 +60,6 @@ void register_websocket_types() {
_SET_HINT(WSS_OUT_PKT, 1024, 16384);
#ifdef JAVASCRIPT_ENABLED
- EM_ASM({
- var IDHandler = {};
- IDHandler["ids"] = {};
- IDHandler["has"] = function(id) {
- return IDHandler.ids.hasOwnProperty(id);
- };
- IDHandler["add"] = function(obj) {
- var id = crypto.getRandomValues(new Int32Array(32))[0];
- IDHandler.ids[id] = obj;
- return id;
- };
- IDHandler["get"] = function(id) {
- return IDHandler.ids[id];
- };
- IDHandler["remove"] = function(id) {
- delete IDHandler.ids[id];
- };
- Module["IDHandler"] = IDHandler;
- });
EMWSPeer::make_default();
EMWSClient::make_default();
EMWSServer::make_default();
diff --git a/platform/android/java/src/org/godotengine/godot/Godot.java b/platform/android/java/src/org/godotengine/godot/Godot.java
index 48fd076d31..a9edc2f2f4 100644
--- a/platform/android/java/src/org/godotengine/godot/Godot.java
+++ b/platform/android/java/src/org/godotengine/godot/Godot.java
@@ -32,6 +32,7 @@ package org.godotengine.godot;
//import android.R;
+import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
@@ -53,7 +54,6 @@ import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
-import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
@@ -75,7 +75,6 @@ import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
-
import com.google.android.vending.expansion.downloader.DownloadProgressInfo;
import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
import com.google.android.vending.expansion.downloader.DownloaderServiceMarshaller;
@@ -83,10 +82,6 @@ import com.google.android.vending.expansion.downloader.Helpers;
import com.google.android.vending.expansion.downloader.IDownloaderClient;
import com.google.android.vending.expansion.downloader.IDownloaderService;
import com.google.android.vending.expansion.downloader.IStub;
-
-import org.godotengine.godot.input.GodotEditText;
-import org.godotengine.godot.payments.PaymentsManager;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
@@ -96,8 +91,9 @@ import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
-
import javax.microedition.khronos.opengles.GL10;
+import org.godotengine.godot.input.GodotEditText;
+import org.godotengine.godot.payments.PaymentsManager;
public class Godot extends Activity implements SensorEventListener, IDownloaderClient {
diff --git a/platform/android/java/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java b/platform/android/java/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java
index fb7477c09c..e7e2a3f808 100644
--- a/platform/android/java/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java
+++ b/platform/android/java/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java
@@ -30,13 +30,12 @@
package org.godotengine.godot;
-import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
-
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
+import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
/**
* You should start your derived downloader class when this receiver gets the message
diff --git a/platform/android/java/src/org/godotengine/godot/GodotDownloaderService.java b/platform/android/java/src/org/godotengine/godot/GodotDownloaderService.java
index 91a7b99c36..8e10710c9f 100644
--- a/platform/android/java/src/org/godotengine/godot/GodotDownloaderService.java
+++ b/platform/android/java/src/org/godotengine/godot/GodotDownloaderService.java
@@ -33,7 +33,6 @@ package org.godotengine.godot;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
-
import com.google.android.vending.expansion.downloader.impl.DownloaderService;
/**
diff --git a/platform/android/java/src/org/godotengine/godot/GodotIO.java b/platform/android/java/src/org/godotengine/godot/GodotIO.java
index 1b2ff61314..98174157ec 100644
--- a/platform/android/java/src/org/godotengine/godot/GodotIO.java
+++ b/platform/android/java/src/org/godotengine/godot/GodotIO.java
@@ -29,28 +29,27 @@
/*************************************************************************/
package org.godotengine.godot;
-import java.util.HashMap;
-import java.util.Locale;
-import android.net.Uri;
-import android.content.Intent;
-import android.content.res.AssetManager;
-import java.io.InputStream;
-import java.io.IOException;
import android.app.*;
import android.content.*;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.res.AssetManager;
+import android.graphics.*;
+import android.hardware.*;
+import android.media.*;
+import android.net.Uri;
+import android.os.*;
+import android.text.*;
+import android.text.method.*;
+import android.util.DisplayMetrics;
+import android.util.Log;
import android.util.SparseArray;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
-import android.os.*;
-import android.util.Log;
-import android.util.DisplayMetrics;
-import android.graphics.*;
-import android.text.method.*;
-import android.text.*;
-import android.media.*;
-import android.hardware.*;
-import android.content.*;
-import android.content.pm.ActivityInfo;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Locale;
import org.godotengine.godot.input.*;
//android.os.Build
diff --git a/platform/android/java/src/org/godotengine/godot/GodotPaymentV3.java b/platform/android/java/src/org/godotengine/godot/GodotPaymentV3.java
index c3d81c5c1d..1432cd3a67 100644
--- a/platform/android/java/src/org/godotengine/godot/GodotPaymentV3.java
+++ b/platform/android/java/src/org/godotengine/godot/GodotPaymentV3.java
@@ -32,14 +32,12 @@ package org.godotengine.godot;
import android.app.Activity;
import android.util.Log;
-
-import org.godotengine.godot.payments.PaymentsManager;
-import org.json.JSONException;
-import org.json.JSONObject;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import org.godotengine.godot.payments.PaymentsManager;
+import org.json.JSONException;
+import org.json.JSONObject;
public class GodotPaymentV3 extends Godot.SingletonBase {
diff --git a/platform/android/java/src/org/godotengine/godot/GodotView.java b/platform/android/java/src/org/godotengine/godot/GodotView.java
index ccf78f26f3..d7cd5b4360 100644
--- a/platform/android/java/src/org/godotengine/godot/GodotView.java
+++ b/platform/android/java/src/org/godotengine/godot/GodotView.java
@@ -31,16 +31,15 @@
package org.godotengine.godot;
import android.annotation.SuppressLint;
import android.content.Context;
+import android.content.ContextWrapper;
import android.graphics.PixelFormat;
+import android.hardware.input.InputManager;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.util.Log;
+import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
-import android.content.ContextWrapper;
-import android.view.InputDevice;
-import android.hardware.input.InputManager;
-
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
@@ -51,7 +50,6 @@ import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;
-
import org.godotengine.godot.input.InputManagerCompat;
import org.godotengine.godot.input.InputManagerCompat.InputDeviceListener;
/**
diff --git a/platform/android/java/src/org/godotengine/godot/input/GodotEditText.java b/platform/android/java/src/org/godotengine/godot/input/GodotEditText.java
index 44bd462ed0..45b739baa0 100644
--- a/platform/android/java/src/org/godotengine/godot/input/GodotEditText.java
+++ b/platform/android/java/src/org/godotengine/godot/input/GodotEditText.java
@@ -30,16 +30,15 @@
package org.godotengine.godot.input;
import android.content.Context;
-import android.util.AttributeSet;
-import android.view.KeyEvent;
-import android.widget.EditText;
-import org.godotengine.godot.*;
import android.os.Handler;
import android.os.Message;
-import android.view.inputmethod.InputMethodManager;
+import android.util.AttributeSet;
+import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
-
+import android.view.inputmethod.InputMethodManager;
+import android.widget.EditText;
import java.lang.ref.WeakReference;
+import org.godotengine.godot.*;
public class GodotEditText extends EditText {
// ===========================================================
diff --git a/platform/android/java/src/org/godotengine/godot/input/InputManagerV16.java b/platform/android/java/src/org/godotengine/godot/input/InputManagerV16.java
index 3b88609cc9..e4bafa7ff9 100644
--- a/platform/android/java/src/org/godotengine/godot/input/InputManagerV16.java
+++ b/platform/android/java/src/org/godotengine/godot/input/InputManagerV16.java
@@ -23,7 +23,6 @@ import android.os.Build;
import android.os.Handler;
import android.view.InputDevice;
import android.view.MotionEvent;
-
import java.util.HashMap;
import java.util.Map;
diff --git a/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java b/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java
index 1d42aa4464..f872e7af56 100644
--- a/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java
+++ b/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java
@@ -30,13 +30,11 @@
package org.godotengine.godot.payments;
-import com.android.vending.billing.IInAppBillingService;
-
import android.content.Context;
import android.os.AsyncTask;
import android.os.RemoteException;
import android.util.Log;
-
+import com.android.vending.billing.IInAppBillingService;
import java.lang.ref.WeakReference;
abstract public class ConsumeTask {
diff --git a/platform/android/java/src/org/godotengine/godot/payments/HandlePurchaseTask.java b/platform/android/java/src/org/godotengine/godot/payments/HandlePurchaseTask.java
index 835779ba00..5424ebb49d 100644
--- a/platform/android/java/src/org/godotengine/godot/payments/HandlePurchaseTask.java
+++ b/platform/android/java/src/org/godotengine/godot/payments/HandlePurchaseTask.java
@@ -30,13 +30,6 @@
package org.godotengine.godot.payments;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import org.godotengine.godot.GodotLib;
-import org.godotengine.godot.utils.Crypt;
-import com.android.vending.billing.IInAppBillingService;
-
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
@@ -47,6 +40,11 @@ import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
+import com.android.vending.billing.IInAppBillingService;
+import org.godotengine.godot.GodotLib;
+import org.godotengine.godot.utils.Crypt;
+import org.json.JSONException;
+import org.json.JSONObject;
abstract public class HandlePurchaseTask {
diff --git a/platform/android/java/src/org/godotengine/godot/payments/PaymentsManager.java b/platform/android/java/src/org/godotengine/godot/payments/PaymentsManager.java
index 747a4ffd45..a0dbc432c1 100644
--- a/platform/android/java/src/org/godotengine/godot/payments/PaymentsManager.java
+++ b/platform/android/java/src/org/godotengine/godot/payments/PaymentsManager.java
@@ -40,17 +40,14 @@ import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
-
import com.android.vending.billing.IInAppBillingService;
-
+import java.util.ArrayList;
+import java.util.Arrays;
import org.godotengine.godot.Godot;
import org.godotengine.godot.GodotPaymentV3;
import org.json.JSONException;
import org.json.JSONObject;
-import java.util.ArrayList;
-import java.util.Arrays;
-
public class PaymentsManager {
public static final int BILLING_RESPONSE_RESULT_OK = 0;
diff --git a/platform/android/java/src/org/godotengine/godot/payments/PurchaseTask.java b/platform/android/java/src/org/godotengine/godot/payments/PurchaseTask.java
index 000aaa9456..650c5178f0 100644
--- a/platform/android/java/src/org/godotengine/godot/payments/PurchaseTask.java
+++ b/platform/android/java/src/org/godotengine/godot/payments/PurchaseTask.java
@@ -30,13 +30,6 @@
package org.godotengine.godot.payments;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import org.godotengine.godot.GodotLib;
-import org.godotengine.godot.utils.Crypt;
-import com.android.vending.billing.IInAppBillingService;
-
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
@@ -47,6 +40,11 @@ import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
+import com.android.vending.billing.IInAppBillingService;
+import org.godotengine.godot.GodotLib;
+import org.godotengine.godot.utils.Crypt;
+import org.json.JSONException;
+import org.json.JSONObject;
abstract public class PurchaseTask {
diff --git a/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java b/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java
index cf750872d5..daca6ef5ae 100644
--- a/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java
+++ b/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java
@@ -34,14 +34,11 @@ import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
-
import com.android.vending.billing.IInAppBillingService;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
import java.lang.ref.WeakReference;
import java.util.ArrayList;
+import org.json.JSONException;
+import org.json.JSONObject;
abstract public class ReleaseAllConsumablesTask {
diff --git a/platform/android/java/src/org/godotengine/godot/payments/ValidateTask.java b/platform/android/java/src/org/godotengine/godot/payments/ValidateTask.java
index 6701f9396a..d32c80e8e0 100644
--- a/platform/android/java/src/org/godotengine/godot/payments/ValidateTask.java
+++ b/platform/android/java/src/org/godotengine/godot/payments/ValidateTask.java
@@ -30,17 +30,6 @@
package org.godotengine.godot.payments;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import org.godotengine.godot.Godot;
-import org.godotengine.godot.GodotLib;
-import org.godotengine.godot.GodotPaymentV3;
-import org.godotengine.godot.utils.Crypt;
-import org.godotengine.godot.utils.HttpRequester;
-import org.godotengine.godot.utils.RequestParams;
-import com.android.vending.billing.IInAppBillingService;
-
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
@@ -51,8 +40,16 @@ import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
-
+import com.android.vending.billing.IInAppBillingService;
import java.lang.ref.WeakReference;
+import org.godotengine.godot.Godot;
+import org.godotengine.godot.GodotLib;
+import org.godotengine.godot.GodotPaymentV3;
+import org.godotengine.godot.utils.Crypt;
+import org.godotengine.godot.utils.HttpRequester;
+import org.godotengine.godot.utils.RequestParams;
+import org.json.JSONException;
+import org.json.JSONObject;
abstract public class ValidateTask {
diff --git a/platform/android/java/src/org/godotengine/godot/utils/CustomSSLSocketFactory.java b/platform/android/java/src/org/godotengine/godot/utils/CustomSSLSocketFactory.java
index 3806d4bcad..b61007faa3 100644
--- a/platform/android/java/src/org/godotengine/godot/utils/CustomSSLSocketFactory.java
+++ b/platform/android/java/src/org/godotengine/godot/utils/CustomSSLSocketFactory.java
@@ -37,10 +37,8 @@ import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
-
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
-
import org.apache.http.conn.ssl.SSLSocketFactory;
/**
diff --git a/platform/android/java/src/org/godotengine/godot/utils/HttpRequester.java b/platform/android/java/src/org/godotengine/godot/utils/HttpRequester.java
index e9c81eb2e5..e98f533c23 100644
--- a/platform/android/java/src/org/godotengine/godot/utils/HttpRequester.java
+++ b/platform/android/java/src/org/godotengine/godot/utils/HttpRequester.java
@@ -30,6 +30,9 @@
package org.godotengine.godot.utils;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
@@ -39,7 +42,6 @@ import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
@@ -64,10 +66,6 @@ import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.util.Log;
-
/**
*
* @author Luis Linietsky <luis.linietsky@gmail.com>
diff --git a/platform/android/java/src/org/godotengine/godot/utils/RequestParams.java b/platform/android/java/src/org/godotengine/godot/utils/RequestParams.java
index c5778102f6..b9fe0dd0c9 100644
--- a/platform/android/java/src/org/godotengine/godot/utils/RequestParams.java
+++ b/platform/android/java/src/org/godotengine/godot/utils/RequestParams.java
@@ -34,7 +34,6 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
-
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp
index d65cf2f31e..93d39859f2 100644
--- a/platform/android/os_android.cpp
+++ b/platform/android/os_android.cpp
@@ -292,14 +292,6 @@ bool OS_Android::can_draw() const {
return true; //always?
}
-void OS_Android::set_cursor_shape(CursorShape p_shape) {
-
- //android really really really has no mouse.. how amazing..
-}
-
-void OS_Android::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
-}
-
void OS_Android::main_loop_begin() {
if (main_loop)
diff --git a/platform/android/os_android.h b/platform/android/os_android.h
index 3a5404124a..d2198b0579 100644
--- a/platform/android/os_android.h
+++ b/platform/android/os_android.h
@@ -144,9 +144,6 @@ public:
virtual bool can_draw() const;
- virtual void set_cursor_shape(CursorShape p_shape);
- virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot);
-
void main_loop_begin();
bool main_loop_iterate();
void main_loop_request_go_back();
diff --git a/platform/haiku/os_haiku.cpp b/platform/haiku/os_haiku.cpp
index a6d5a00852..f3fed6669b 100644
--- a/platform/haiku/os_haiku.cpp
+++ b/platform/haiku/os_haiku.cpp
@@ -203,6 +203,10 @@ void OS_Haiku::set_cursor_shape(CursorShape p_shape) {
//ERR_PRINT("set_cursor_shape() NOT IMPLEMENTED");
}
+OS::CursorShape OS_Haiku::get_cursor_shape() const {
+ // TODO: implement get_cursor_shape
+}
+
void OS_Haiku::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
// TODO
}
diff --git a/platform/haiku/os_haiku.h b/platform/haiku/os_haiku.h
index d7eac10635..6ab006843a 100644
--- a/platform/haiku/os_haiku.h
+++ b/platform/haiku/os_haiku.h
@@ -86,6 +86,7 @@ public:
virtual Point2 get_mouse_position() const;
virtual int get_mouse_button_state() const;
virtual void set_cursor_shape(CursorShape p_shape);
+ virtual CursorShape get_cursor_shape() const;
virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot);
virtual int get_screen_count() const;
diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp
index 7d0fdd2078..e25efc813b 100644
--- a/platform/iphone/os_iphone.cpp
+++ b/platform/iphone/os_iphone.cpp
@@ -490,17 +490,11 @@ void OSIPhone::set_keep_screen_on(bool p_enabled) {
_set_keep_screen_on(p_enabled);
};
-void OSIPhone::set_cursor_shape(CursorShape p_shape){
-
-};
-
String OSIPhone::get_user_data_dir() const {
return data_dir;
};
-void OSIPhone::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot){};
-
String OSIPhone::get_name() {
return "iOS";
diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h
index 30d7a1ba41..49c6475cf9 100644
--- a/platform/iphone/os_iphone.h
+++ b/platform/iphone/os_iphone.h
@@ -167,9 +167,6 @@ public:
virtual void hide_virtual_keyboard();
virtual int get_virtual_keyboard_height() const;
- virtual void set_cursor_shape(CursorShape p_shape);
- virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot);
-
virtual Size2 get_window_size() const;
virtual Rect2 get_window_safe_area() const;
diff --git a/platform/javascript/SCsub b/platform/javascript/SCsub
index a93c98a89f..85a633442e 100644
--- a/platform/javascript/SCsub
+++ b/platform/javascript/SCsub
@@ -20,6 +20,13 @@ for lib in js_libraries:
env.Append(LINKFLAGS=['--js-library', env.File(lib).path])
env.Depends(build, js_libraries)
+js_modules = [
+ 'id_handler.js',
+]
+for module in js_modules:
+ env.Append(LINKFLAGS=['--pre-js', env.File(module).path])
+env.Depends(build, js_modules)
+
wrapper_start = env.File('pre.js')
wrapper_end = env.File('engine.js')
js_wrapped = env.Textfile('#bin/godot', [wrapper_start, js, wrapper_end], TEXTFILESUFFIX='${PROGSUFFIX}.wrapped.js')
diff --git a/platform/javascript/id_handler.js b/platform/javascript/id_handler.js
new file mode 100644
index 0000000000..36ef5aa8ef
--- /dev/null
+++ b/platform/javascript/id_handler.js
@@ -0,0 +1,62 @@
+/*************************************************************************/
+/* id_handler.js */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+var IDHandler = function() {
+
+ var ids = {};
+ var size = 0;
+
+ this.has = function(id) {
+ return ids.hasOwnProperty(id);
+ }
+
+ this.add = function(obj) {
+ size += 1;
+ var id = crypto.getRandomValues(new Int32Array(32))[0];
+ ids[id] = obj;
+ return id;
+ }
+
+ this.get = function(id) {
+ return ids[id];
+ }
+
+ this.remove = function(id) {
+ size -= 1;
+ delete ids[id];
+ }
+
+ this.size = function() {
+ return size;
+ }
+
+ this.ids = ids;
+};
+
+Module.IDHandler = new IDHandler;
diff --git a/platform/osx/os_osx.h b/platform/osx/os_osx.h
index dfe7b27bd0..125a88ab6d 100644
--- a/platform/osx/os_osx.h
+++ b/platform/osx/os_osx.h
@@ -172,6 +172,7 @@ public:
virtual Error open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path = false);
virtual void set_cursor_shape(CursorShape p_shape);
+ virtual CursorShape get_cursor_shape() const;
virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot);
virtual void set_mouse_show(bool p_show);
diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm
index 7d2116ba7e..5a4c0593bc 100644
--- a/platform/osx/os_osx.mm
+++ b/platform/osx/os_osx.mm
@@ -271,6 +271,8 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt
- (void)windowDidExitFullScreen:(NSNotification *)notification {
OS_OSX::singleton->zoomed = false;
+ if (!OS_OSX::singleton->resizable)
+ [OS_OSX::singleton->window_object setStyleMask:[OS_OSX::singleton->window_object styleMask] & ~NSWindowStyleMaskResizable];
}
- (void)windowDidChangeBackingProperties:(NSNotification *)notification {
@@ -710,8 +712,6 @@ static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) {
if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
- if (OS_OSX::singleton->input)
- OS_OSX::singleton->input->set_mouse_in_window(false);
}
- (void)mouseEntered:(NSEvent *)event {
@@ -719,8 +719,6 @@ static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) {
return;
if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
- if (OS_OSX::singleton->input)
- OS_OSX::singleton->input->set_mouse_in_window(true);
OS::CursorShape p_shape = OS_OSX::singleton->cursor_shape;
OS_OSX::singleton->cursor_shape = OS::CURSOR_MAX;
@@ -1694,6 +1692,11 @@ void OS_OSX::set_cursor_shape(CursorShape p_shape) {
cursor_shape = p_shape;
}
+OS::CursorShape OS_OSX::get_cursor_shape() const {
+
+ return cursor_shape;
+}
+
void OS_OSX::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
if (p_cursor.is_valid()) {
Ref<Texture> texture = p_cursor;
@@ -2300,6 +2303,8 @@ void OS_OSX::set_window_fullscreen(bool p_enabled) {
if (zoomed != p_enabled) {
if (layered_window)
set_window_per_pixel_transparency_enabled(false);
+ if (!resizable)
+ [window_object setStyleMask:[window_object styleMask] | NSWindowStyleMaskResizable];
[window_object toggleFullScreen:nil];
}
zoomed = p_enabled;
@@ -2314,7 +2319,7 @@ void OS_OSX::set_window_resizable(bool p_enabled) {
if (p_enabled)
[window_object setStyleMask:[window_object styleMask] | NSWindowStyleMaskResizable];
- else
+ else if (!zoomed)
[window_object setStyleMask:[window_object styleMask] & ~NSWindowStyleMaskResizable];
resizable = p_enabled;
diff --git a/platform/server/os_server.cpp b/platform/server/os_server.cpp
index e643d3e8bb..53f2a65c8e 100644
--- a/platform/server/os_server.cpp
+++ b/platform/server/os_server.cpp
@@ -198,12 +198,6 @@ String OS_Server::get_name() {
void OS_Server::move_window_to_foreground() {
}
-void OS_Server::set_cursor_shape(CursorShape p_shape) {
-}
-
-void OS_Server::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
-}
-
OS::PowerState OS_Server::get_power_state() {
return power_manager->get_power_state();
}
diff --git a/platform/server/os_server.h b/platform/server/os_server.h
index eebe8ae777..7441064790 100644
--- a/platform/server/os_server.h
+++ b/platform/server/os_server.h
@@ -95,9 +95,6 @@ protected:
public:
virtual String get_name();
- virtual void set_cursor_shape(CursorShape p_shape);
- virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot);
-
virtual void set_mouse_show(bool p_show);
virtual void set_mouse_grab(bool p_grab);
virtual bool is_mouse_grab_enabled() const;
diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp
index bc74da8a1b..82f09032f5 100644
--- a/platform/uwp/os_uwp.cpp
+++ b/platform/uwp/os_uwp.cpp
@@ -704,6 +704,11 @@ void OS_UWP::set_cursor_shape(CursorShape p_shape) {
cursor_shape = p_shape;
}
+OS::CursorShape OS_UWP::get_cursor_shape() const {
+
+ return cursor_shape;
+}
+
void OS_UWP::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
// TODO
}
diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h
index fd78b3cdf7..00f79efb04 100644
--- a/platform/uwp/os_uwp.h
+++ b/platform/uwp/os_uwp.h
@@ -219,6 +219,7 @@ public:
virtual String get_clipboard() const;
void set_cursor_shape(CursorShape p_shape);
+ CursorShape get_cursor_shape() const;
virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot);
void set_icon(const Ref<Image> &p_icon);
diff --git a/platform/windows/detect.py b/platform/windows/detect.py
index 0118b5bae2..15e8f33eae 100644
--- a/platform/windows/detect.py
+++ b/platform/windows/detect.py
@@ -195,7 +195,7 @@ def configure_msvc(env, manual_msvc_config):
## Compile/link flags
- env.AppendUnique(CCFLAGS=['/MT', '/Gd', '/GR', '/nologo'])
+ env.AppendUnique(CCFLAGS=['/MT', '/Gd', '/GR', '/nologo', '/utf-8'])
env.AppendUnique(CXXFLAGS=['/TP']) # assume all sources are C++
if manual_msvc_config: # should be automatic if SCons found it
if os.getenv("WindowsSdkDir") is not None:
diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp
index 6125455e74..1a5050a15a 100644
--- a/platform/windows/os_windows.cpp
+++ b/platform/windows/os_windows.cpp
@@ -384,8 +384,6 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
outside = true;
if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
- if (input)
- input->set_mouse_in_window(false);
} break;
case WM_INPUT: {
@@ -480,8 +478,6 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
- if (input)
- input->set_mouse_in_window(true);
CursorShape c = cursor_shape;
cursor_shape = CURSOR_MAX;
@@ -670,7 +666,9 @@ LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
mb->set_button_index(BUTTON_XBUTTON2);
mb->set_doubleclick(true);
} break;
- default: { return 0; }
+ default: {
+ return 0;
+ }
}
mb->set_control((wParam & MK_CONTROL) != 0);
@@ -2297,6 +2295,11 @@ void OS_Windows::set_cursor_shape(CursorShape p_shape) {
cursor_shape = p_shape;
}
+OS::CursorShape OS_Windows::get_cursor_shape() const {
+
+ return cursor_shape;
+}
+
void OS_Windows::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
if (p_cursor.is_valid()) {
Ref<Texture> texture = p_cursor;
diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h
index 2d03532c69..c15e1cabc3 100644
--- a/platform/windows/os_windows.h
+++ b/platform/windows/os_windows.h
@@ -273,6 +273,7 @@ public:
virtual String get_clipboard() const;
void set_cursor_shape(CursorShape p_shape);
+ CursorShape get_cursor_shape() const;
virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot);
void GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, OUT HBITMAP &hAndMaskBitmap, OUT HBITMAP &hXorMaskBitmap);
void set_icon(const Ref<Image> &p_icon);
diff --git a/platform/x11/os_x11.cpp b/platform/x11/os_x11.cpp
index 0fe91f3d00..c96047dfbd 100644
--- a/platform/x11/os_x11.cpp
+++ b/platform/x11/os_x11.cpp
@@ -2041,15 +2041,11 @@ void OS_X11::process_xevents() {
case LeaveNotify: {
if (main_loop && !mouse_mode_grab)
main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
- if (input)
- input->set_mouse_in_window(false);
} break;
case EnterNotify: {
if (main_loop && !mouse_mode_grab)
main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
- if (input)
- input->set_mouse_in_window(true);
} break;
case FocusIn:
minimized = false;
@@ -2722,6 +2718,11 @@ void OS_X11::set_cursor_shape(CursorShape p_shape) {
current_cursor = p_shape;
}
+OS::CursorShape OS_X11::get_cursor_shape() const {
+
+ return current_cursor;
+}
+
void OS_X11::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
if (p_cursor.is_valid()) {
Ref<Texture> texture = p_cursor;
@@ -3238,6 +3239,8 @@ OS_X11::OS_X11() {
AudioDriverManager::add_driver(&driver_alsa);
#endif
+ xi.opcode = 0;
+ xi.last_relative_time = 0;
layered_window = false;
minimized = false;
xim_style = 0L;
diff --git a/platform/x11/os_x11.h b/platform/x11/os_x11.h
index 6d1a66af84..a54851d4e7 100644
--- a/platform/x11/os_x11.h
+++ b/platform/x11/os_x11.h
@@ -219,6 +219,7 @@ public:
virtual String get_name();
virtual void set_cursor_shape(CursorShape p_shape);
+ virtual CursorShape get_cursor_shape() const;
virtual void set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot);
void set_mouse_mode(MouseMode p_mode);
diff --git a/scene/2d/area_2d.cpp b/scene/2d/area_2d.cpp
index 2a225e5797..b322cfe8f1 100644
--- a/scene/2d/area_2d.cpp
+++ b/scene/2d/area_2d.cpp
@@ -261,8 +261,9 @@ void Area2D::_area_inout(int p_status, const RID &p_area, int p_instance, int p_
Map<ObjectID, AreaState>::Element *E = area_map.find(objid);
- ERR_FAIL_COND(!area_in && !E);
-
+ if (!area_in && !E) {
+ return; //likely removed from the tree
+ }
locked = true;
if (area_in) {
diff --git a/scene/2d/audio_stream_player_2d.cpp b/scene/2d/audio_stream_player_2d.cpp
index 7b28ad2c12..faefd85968 100644
--- a/scene/2d/audio_stream_player_2d.cpp
+++ b/scene/2d/audio_stream_player_2d.cpp
@@ -473,6 +473,10 @@ bool AudioStreamPlayer2D::get_stream_paused() const {
return stream_paused;
}
+Ref<AudioStreamPlayback> AudioStreamPlayer2D::get_stream_playback() {
+ return stream_playback;
+}
+
void AudioStreamPlayer2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_stream", "stream"), &AudioStreamPlayer2D::set_stream);
@@ -512,6 +516,8 @@ void AudioStreamPlayer2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_stream_paused", "pause"), &AudioStreamPlayer2D::set_stream_paused);
ClassDB::bind_method(D_METHOD("get_stream_paused"), &AudioStreamPlayer2D::get_stream_paused);
+ ClassDB::bind_method(D_METHOD("get_stream_playback"), &AudioStreamPlayer2D::get_stream_playback);
+
ClassDB::bind_method(D_METHOD("_bus_layout_changed"), &AudioStreamPlayer2D::_bus_layout_changed);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream");
diff --git a/scene/2d/audio_stream_player_2d.h b/scene/2d/audio_stream_player_2d.h
index caf5c6ee49..0cd18fb93b 100644
--- a/scene/2d/audio_stream_player_2d.h
+++ b/scene/2d/audio_stream_player_2d.h
@@ -130,6 +130,8 @@ public:
void set_stream_paused(bool p_pause);
bool get_stream_paused() const;
+ Ref<AudioStreamPlayback> get_stream_playback();
+
AudioStreamPlayer2D();
~AudioStreamPlayer2D();
};
diff --git a/scene/2d/light_occluder_2d.cpp b/scene/2d/light_occluder_2d.cpp
index 5334caed67..3a3f90ac4b 100644
--- a/scene/2d/light_occluder_2d.cpp
+++ b/scene/2d/light_occluder_2d.cpp
@@ -32,9 +32,59 @@
#include "core/engine.h"
+#define LINE_GRAB_WIDTH 8
+Rect2 OccluderPolygon2D::_edit_get_rect() const {
+
+ if (rect_cache_dirty) {
+ if (closed) {
+ PoolVector<Vector2>::Read r = polygon.read();
+ item_rect = Rect2();
+ for (int i = 0; i < polygon.size(); i++) {
+ Vector2 pos = r[i];
+ if (i == 0)
+ item_rect.position = pos;
+ else
+ item_rect.expand_to(pos);
+ }
+ rect_cache_dirty = false;
+ } else {
+ if (polygon.size() == 0) {
+ item_rect = Rect2();
+ } else {
+ Vector2 d = Vector2(LINE_GRAB_WIDTH, LINE_GRAB_WIDTH);
+ item_rect = Rect2(polygon[0] - d, 2 * d);
+ for (int i = 1; i < polygon.size(); i++) {
+ item_rect.expand_to(polygon[i] - d);
+ item_rect.expand_to(polygon[i] + d);
+ }
+ }
+ }
+ }
+
+ return item_rect;
+}
+
+bool OccluderPolygon2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
+
+ if (closed) {
+ return Geometry::is_point_in_polygon(p_point, Variant(polygon));
+ } else {
+ const real_t d = LINE_GRAB_WIDTH / 2 + p_tolerance;
+ PoolVector<Vector2>::Read points = polygon.read();
+ for (int i = 0; i < polygon.size() - 1; i++) {
+ Vector2 p = Geometry::get_closest_point_to_segment_2d(p_point, &points[i]);
+ if (p.distance_to(p_point) <= d)
+ return true;
+ }
+
+ return false;
+ }
+}
+
void OccluderPolygon2D::set_polygon(const PoolVector<Vector2> &p_polygon) {
polygon = p_polygon;
+ rect_cache_dirty = true;
VS::get_singleton()->canvas_occluder_polygon_set_shape(occ_polygon, p_polygon, closed);
emit_changed();
}
@@ -100,6 +150,7 @@ OccluderPolygon2D::OccluderPolygon2D() {
occ_polygon = VS::get_singleton()->canvas_occluder_polygon_create();
closed = true;
cull = CULL_DISABLED;
+ rect_cache_dirty = true;
}
OccluderPolygon2D::~OccluderPolygon2D() {
@@ -164,6 +215,16 @@ void LightOccluder2D::_notification(int p_what) {
}
}
+Rect2 LightOccluder2D::_edit_get_rect() const {
+
+ return occluder_polygon.is_valid() ? occluder_polygon->_edit_get_rect() : Rect2();
+}
+
+bool LightOccluder2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
+
+ return occluder_polygon.is_valid() ? occluder_polygon->_edit_is_selected_on_click(p_point, p_tolerance) : false;
+}
+
void LightOccluder2D::set_occluder_polygon(const Ref<OccluderPolygon2D> &p_polygon) {
#ifdef DEBUG_ENABLED
diff --git a/scene/2d/light_occluder_2d.h b/scene/2d/light_occluder_2d.h
index 498d65d764..7931cd0b30 100644
--- a/scene/2d/light_occluder_2d.h
+++ b/scene/2d/light_occluder_2d.h
@@ -50,10 +50,16 @@ private:
bool closed;
CullMode cull;
+ mutable Rect2 item_rect;
+ mutable bool rect_cache_dirty;
+
protected:
static void _bind_methods();
public:
+ virtual Rect2 _edit_get_rect() const;
+ virtual bool _edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const;
+
void set_polygon(const PoolVector<Vector2> &p_polygon);
PoolVector<Vector2> get_polygon() const;
@@ -85,6 +91,9 @@ protected:
static void _bind_methods();
public:
+ virtual Rect2 _edit_get_rect() const;
+ virtual bool _edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const;
+
void set_occluder_polygon(const Ref<OccluderPolygon2D> &p_polygon);
Ref<OccluderPolygon2D> get_occluder_polygon() const;
diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp
index 3562011bc2..885c9ea8bc 100644
--- a/scene/2d/tile_map.cpp
+++ b/scene/2d/tile_map.cpp
@@ -1405,7 +1405,8 @@ Vector2 TileMap::_map_to_world(int p_x, int p_y, bool p_ignore_ofs) const {
ret += get_cell_transform()[1] * (half_offset == HALF_OFFSET_Y ? 0.5 : -0.5);
}
} break;
- default: {}
+ default: {
+ }
}
}
return ret;
@@ -1480,7 +1481,8 @@ Vector2 TileMap::world_to_map(const Vector2 &p_pos) const {
ret.y += 0.5;
}
} break;
- default: {}
+ default: {
+ }
}
// Account for precision errors on the border (GH-23250).
diff --git a/scene/3d/area.cpp b/scene/3d/area.cpp
index 13d9181082..3557f0425c 100644
--- a/scene/3d/area.cpp
+++ b/scene/3d/area.cpp
@@ -356,7 +356,9 @@ void Area::_area_inout(int p_status, const RID &p_area, int p_instance, int p_ar
Map<ObjectID, AreaState>::Element *E = area_map.find(objid);
- ERR_FAIL_COND(!area_in && !E);
+ if (!area_in && !E) {
+ return; //likely removed from the tree
+ }
locked = true;
diff --git a/scene/3d/audio_stream_player_3d.cpp b/scene/3d/audio_stream_player_3d.cpp
index 4b3934c4ea..4d5ffc31b3 100644
--- a/scene/3d/audio_stream_player_3d.cpp
+++ b/scene/3d/audio_stream_player_3d.cpp
@@ -887,6 +887,10 @@ bool AudioStreamPlayer3D::get_stream_paused() const {
return stream_paused;
}
+Ref<AudioStreamPlayback> AudioStreamPlayer3D::get_stream_playback() {
+ return stream_playback;
+}
+
void AudioStreamPlayer3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_stream", "stream"), &AudioStreamPlayer3D::set_stream);
@@ -953,6 +957,8 @@ void AudioStreamPlayer3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_stream_paused", "pause"), &AudioStreamPlayer3D::set_stream_paused);
ClassDB::bind_method(D_METHOD("get_stream_paused"), &AudioStreamPlayer3D::get_stream_paused);
+ ClassDB::bind_method(D_METHOD("get_stream_playback"), &AudioStreamPlayer3D::get_stream_playback);
+
ClassDB::bind_method(D_METHOD("_bus_layout_changed"), &AudioStreamPlayer3D::_bus_layout_changed);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream");
diff --git a/scene/3d/audio_stream_player_3d.h b/scene/3d/audio_stream_player_3d.h
index e467c170fb..1175547028 100644
--- a/scene/3d/audio_stream_player_3d.h
+++ b/scene/3d/audio_stream_player_3d.h
@@ -206,6 +206,8 @@ public:
void set_stream_paused(bool p_pause);
bool get_stream_paused() const;
+ Ref<AudioStreamPlayback> get_stream_playback();
+
AudioStreamPlayer3D();
~AudioStreamPlayer3D();
};
diff --git a/scene/3d/light.cpp b/scene/3d/light.cpp
index cf1af918f7..ed533ee7a4 100644
--- a/scene/3d/light.cpp
+++ b/scene/3d/light.cpp
@@ -293,7 +293,8 @@ Light::Light(VisualServer::LightType p_type) {
case VS::LIGHT_DIRECTIONAL: light = VisualServer::get_singleton()->directional_light_create(); break;
case VS::LIGHT_OMNI: light = VisualServer::get_singleton()->omni_light_create(); break;
case VS::LIGHT_SPOT: light = VisualServer::get_singleton()->spot_light_create(); break;
- default: {};
+ default: {
+ };
}
VS::get_singleton()->instance_set_base(get_instance(), light);
diff --git a/scene/3d/skeleton.cpp b/scene/3d/skeleton.cpp
index b7279e4d4f..dafcf95b1f 100644
--- a/scene/3d/skeleton.cpp
+++ b/scene/3d/skeleton.cpp
@@ -540,10 +540,11 @@ void Skeleton::clear_bones() {
void Skeleton::set_bone_pose(int p_bone, const Transform &p_pose) {
ERR_FAIL_INDEX(p_bone, bones.size());
- ERR_FAIL_COND(!is_inside_tree());
bones.write[p_bone].pose = p_pose;
- _make_dirty();
+ if (is_inside_tree()) {
+ _make_dirty();
+ }
}
Transform Skeleton::get_bone_pose(int p_bone) const {
diff --git a/scene/3d/spatial.cpp b/scene/3d/spatial.cpp
index 83f99a2e3c..395f7b9b35 100644
--- a/scene/3d/spatial.cpp
+++ b/scene/3d/spatial.cpp
@@ -224,7 +224,8 @@ void Spatial::_notification(int p_what) {
#endif
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/scene/animation/animation_blend_tree.cpp b/scene/animation/animation_blend_tree.cpp
index 0daa574f72..e9b38ae990 100644
--- a/scene/animation/animation_blend_tree.cpp
+++ b/scene/animation/animation_blend_tree.cpp
@@ -363,6 +363,7 @@ AnimationNodeOneShot::AnimationNodeOneShot() {
fade_out = 0.1;
autorestart = false;
autorestart_delay = 1;
+ autorestart_random_delay = 0;
mix = MIX_MODE_BLEND;
sync = false;
@@ -857,6 +858,7 @@ AnimationNodeTransition::AnimationNodeTransition() {
time = "time";
current = "current";
prev_current = "prev_current";
+ xfade = 0.0;
enabled_inputs = 0;
for (int i = 0; i < MAX_INPUTS; i++) {
diff --git a/scene/animation/animation_cache.cpp b/scene/animation/animation_cache.cpp
index feefe3ddd4..84b3f103c5 100644
--- a/scene/animation/animation_cache.cpp
+++ b/scene/animation/animation_cache.cpp
@@ -309,7 +309,8 @@ void AnimationCache::set_all(float p_time, float p_delta) {
}
} break;
- default: {}
+ default: {
+ }
}
}
}
diff --git a/scene/animation/animation_tree.cpp b/scene/animation/animation_tree.cpp
index fe1b8247ff..13b8ebe12d 100644
--- a/scene/animation/animation_tree.cpp
+++ b/scene/animation/animation_tree.cpp
@@ -1276,7 +1276,8 @@ void AnimationTree::_process_graph(float p_delta) {
t->object->set_indexed(t->subpath, t->value);
} break;
- default: {} //the rest don't matter
+ default: {
+ } //the rest don't matter
}
}
}
@@ -1301,9 +1302,17 @@ void AnimationTree::_notification(int p_what) {
_clear_caches();
if (last_animation_player) {
- Object *old_player = ObjectDB::get_instance(last_animation_player);
- if (old_player) {
- old_player->disconnect("caches_cleared", this, "_clear_caches");
+ Object *player = ObjectDB::get_instance(last_animation_player);
+ if (player) {
+ player->disconnect("caches_cleared", this, "_clear_caches");
+ }
+ }
+ } else if (p_what == NOTIFICATION_ENTER_TREE) {
+ if (last_animation_player) {
+
+ Object *player = ObjectDB::get_instance(last_animation_player);
+ if (player) {
+ player->connect("caches_cleared", this, "_clear_caches");
}
}
}
diff --git a/scene/animation/animation_tree_player.cpp b/scene/animation/animation_tree_player.cpp
index 3420b48ae3..3cc90c2ad6 100644
--- a/scene/animation/animation_tree_player.cpp
+++ b/scene/animation/animation_tree_player.cpp
@@ -193,7 +193,8 @@ bool AnimationTreePlayer::_set(const StringName &p_name, const Variant &p_value)
}
} break;
- default: {};
+ default: {
+ };
}
}
@@ -352,7 +353,8 @@ bool AnimationTreePlayer::_get(const StringName &p_name, Variant &r_ret) const {
node["transitions"] = transitions;
} break;
- default: {};
+ default: {
+ };
}
nodes.push_back(node);
@@ -772,7 +774,8 @@ float AnimationTreePlayer::_process_node(const StringName &p_node, AnimationNode
}
} break;
- default: {}
+ default: {
+ }
}
return 0;
@@ -882,7 +885,8 @@ void AnimationTreePlayer::_process_animation(float p_delta) {
tr.track->object->call(method, args[0], args[1], args[2], args[3], args[4]);
}
} break;
- default: {}
+ default: {
+ }
}
}
}
@@ -969,7 +973,8 @@ void AnimationTreePlayer::add_node(NodeType p_type, const StringName &p_node) {
n = memnew(TransitionNode);
} break;
- default: {}
+ default: {
+ }
}
//n->name+=" "+itos(p_node);
diff --git a/scene/animation/skeleton_ik.cpp b/scene/animation/skeleton_ik.cpp
index 88fb2d5bfc..4da3e6ee28 100644
--- a/scene/animation/skeleton_ik.cpp
+++ b/scene/animation/skeleton_ik.cpp
@@ -335,7 +335,7 @@ void SkeletonIK::_validate_property(PropertyInfo &property) const {
if (skeleton) {
- String names;
+ String names("--,");
for (int i = 0; i < skeleton->get_bone_count(); i++) {
if (i > 0)
names += ",";
diff --git a/scene/audio/audio_stream_player.cpp b/scene/audio/audio_stream_player.cpp
index 2688041d18..47278b8fc1 100644
--- a/scene/audio/audio_stream_player.cpp
+++ b/scene/audio/audio_stream_player.cpp
@@ -331,6 +331,10 @@ void AudioStreamPlayer::_bus_layout_changed() {
_change_notify();
}
+Ref<AudioStreamPlayback> AudioStreamPlayer::get_stream_playback() {
+ return stream_playback;
+}
+
void AudioStreamPlayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_stream", "stream"), &AudioStreamPlayer::set_stream);
@@ -366,6 +370,8 @@ void AudioStreamPlayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_stream_paused", "pause"), &AudioStreamPlayer::set_stream_paused);
ClassDB::bind_method(D_METHOD("get_stream_paused"), &AudioStreamPlayer::get_stream_paused);
+ ClassDB::bind_method(D_METHOD("get_stream_playback"), &AudioStreamPlayer::get_stream_playback);
+
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "volume_db", PROPERTY_HINT_RANGE, "-80,24"), "set_volume_db", "get_volume_db");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "pitch_scale", PROPERTY_HINT_RANGE, "0.01,32,0.01"), "set_pitch_scale", "get_pitch_scale");
diff --git a/scene/audio/audio_stream_player.h b/scene/audio/audio_stream_player.h
index fba8ce7dd3..590bef95b0 100644
--- a/scene/audio/audio_stream_player.h
+++ b/scene/audio/audio_stream_player.h
@@ -106,6 +106,9 @@ public:
void set_stream_paused(bool p_pause);
bool get_stream_paused() const;
+ Ref<AudioStreamPlayback> get_stream_playback();
+
+
AudioStreamPlayer();
~AudioStreamPlayer();
};
diff --git a/scene/gui/file_dialog.cpp b/scene/gui/file_dialog.cpp
index 059e59ea21..5671b41de8 100644
--- a/scene/gui/file_dialog.cpp
+++ b/scene/gui/file_dialog.cpp
@@ -86,7 +86,9 @@ void FileDialog::_unhandled_input(const Ref<InputEvent> &p_event) {
_dir_entered("..");
} break;
- default: { handled = false; }
+ default: {
+ handled = false;
+ }
}
if (handled)
diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp
index 00d6ac3b94..3fbf809012 100644
--- a/scene/gui/rich_text_label.cpp
+++ b/scene/gui/rich_text_label.cpp
@@ -711,7 +711,8 @@ int RichTextLabel::_process_line(ItemFrame *p_frame, const Vector2 &p_ofs, int &
} break;
- default: {}
+ default: {
+ }
}
Item *itp = it;
diff --git a/scene/gui/tab_container.cpp b/scene/gui/tab_container.cpp
index 212efa4976..ad41cc4167 100644
--- a/scene/gui/tab_container.cpp
+++ b/scene/gui/tab_container.cpp
@@ -127,6 +127,9 @@ void TabContainer::_gui_input(const Ref<InputEvent> &p_event) {
// Activate the clicked tab.
pos.x -= tabs_ofs_cache;
for (int i = first_tab_cache; i <= last_tab_cache; i++) {
+ if (get_tab_hidden(i)) {
+ continue;
+ }
int tab_width = _get_tab_width(i);
if (pos.x < tab_width) {
if (!get_tab_disabled(i)) {
@@ -216,6 +219,9 @@ void TabContainer::_notification(int p_what) {
// Check if all tabs would fit into the header area.
int all_tabs_width = 0;
for (int i = 0; i < tabs.size(); i++) {
+ if (get_tab_hidden(i)) {
+ continue;
+ }
int tab_width = _get_tab_width(i);
all_tabs_width += tab_width;
@@ -241,6 +247,9 @@ void TabContainer::_notification(int p_what) {
all_tabs_width = 0;
Vector<int> tab_widths;
for (int i = first_tab_cache; i < tabs.size(); i++) {
+ if (get_tab_hidden(i)) {
+ continue;
+ }
int tab_width = _get_tab_width(i);
if (all_tabs_width + tab_width > header_width && tab_widths.size() > 0)
break;
@@ -267,6 +276,9 @@ void TabContainer::_notification(int p_what) {
// Draw all visible tabs.
int x = 0;
for (int i = 0; i < tab_widths.size(); i++) {
+ if (get_tab_hidden(i)) {
+ continue;
+ }
Ref<StyleBox> tab_style;
Color font_color;
if (get_tab_disabled(i + first_tab_cache)) {
@@ -354,7 +366,7 @@ int TabContainer::_get_tab_width(int p_index) const {
ERR_FAIL_INDEX_V(p_index, get_tab_count(), 0);
Control *control = Object::cast_to<Control>(_get_tabs()[p_index]);
- if (!control || control->is_set_as_toplevel())
+ if (!control || control->is_set_as_toplevel() || get_tab_hidden(p_index))
return 0;
// Get the width of the text displayed on the tab.
@@ -765,6 +777,36 @@ bool TabContainer::get_tab_disabled(int p_tab) const {
return false;
}
+void TabContainer::set_tab_hidden(int p_tab, bool p_hidden) {
+
+ Control *child = _get_tab(p_tab);
+ ERR_FAIL_COND(!child);
+ child->set_meta("_tab_hidden", p_hidden);
+ update();
+ for (int i = 0; i < get_tab_count(); i++) {
+ int try_tab = (p_tab + 1 + i) % get_tab_count();
+ if (get_tab_disabled(try_tab) || get_tab_hidden(try_tab)) {
+ continue;
+ }
+
+ set_current_tab(try_tab);
+ return;
+ }
+
+ //assumed no other tab can be switched to, just hide
+ child->hide();
+}
+
+bool TabContainer::get_tab_hidden(int p_tab) const {
+
+ Control *child = _get_tab(p_tab);
+ ERR_FAIL_COND_V(!child, false);
+ if (child->has_meta("_tab_hidden"))
+ return child->get_meta("_tab_hidden");
+ else
+ return false;
+}
+
void TabContainer::get_translatable_strings(List<String> *p_strings) const {
Vector<Control *> tabs = _get_tabs();
diff --git a/scene/gui/tab_container.h b/scene/gui/tab_container.h
index c110f041d0..f7a9fb64fd 100644
--- a/scene/gui/tab_container.h
+++ b/scene/gui/tab_container.h
@@ -96,6 +96,9 @@ public:
void set_tab_disabled(int p_tab, bool p_disabled);
bool get_tab_disabled(int p_tab) const;
+ void set_tab_hidden(int p_tab, bool p_hidden);
+ bool get_tab_hidden(int p_tab) const;
+
int get_tab_count() const;
void set_current_tab(int p_current);
int get_current_tab() const;
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index 9acf8d40c9..39a0b0aaf2 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -590,6 +590,12 @@ void TextEdit::_notification(int p_what) {
}
} break;
case NOTIFICATION_DRAW: {
+
+ if (first_draw) {
+ //size may not be the final one, so attempts to ensure cursor was visible may have failed
+ adjust_viewport_to_cursor();
+ first_draw = false;
+ }
Size2 size = get_size();
if ((!has_focus() && !menu->has_focus()) || !window_has_focus) {
draw_caret = false;
@@ -6356,6 +6362,7 @@ TextEdit::TextEdit() {
menu->add_item(RTR("Undo"), MENU_UNDO, KEY_MASK_CMD | KEY_Z);
menu->add_item(RTR("Redo"), MENU_REDO, KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_Z);
menu->connect("id_pressed", this, "menu_option");
+ first_draw = true;
}
TextEdit::~TextEdit() {
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index 33f0a3f45d..96b409c6d4 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -275,6 +275,7 @@ private:
int wrap_at;
int wrap_right_offset;
+ bool first_draw;
bool setting_row;
bool draw_tabs;
bool override_selected_font_color;
diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp
index 679b752fa3..7e59606d2b 100644
--- a/scene/gui/tree.cpp
+++ b/scene/gui/tree.cpp
@@ -962,7 +962,8 @@ int Tree::compute_item_height(TreeItem *p_item) const {
}
} break;
- default: {}
+ default: {
+ }
}
}
int item_min_height = p_item->get_custom_minimum_height();
@@ -2020,7 +2021,9 @@ void Tree::text_editor_enter(String p_text) {
//popup_edited_item->edited_signal.call( popup_edited_item_col );
} break;
- default: { ERR_FAIL(); }
+ default: {
+ ERR_FAIL();
+ }
}
item_edited(popup_edited_item_col, popup_edited_item);
@@ -2847,7 +2850,7 @@ void Tree::_notification(int p_what) {
if (p_what == NOTIFICATION_DRAG_BEGIN) {
single_select_defer = NULL;
- if (cache.scroll_speed > 0 && get_rect().has_point(get_viewport()->get_mouse_position() - get_global_position())) {
+ if (cache.scroll_speed > 0) {
scrolling = true;
set_physics_process_internal(true);
}
@@ -2894,22 +2897,22 @@ void Tree::_notification(int p_what) {
}
}
- if (scrolling) {
- Point2 point = get_viewport()->get_mouse_position() - get_global_position();
- if (point.x < cache.scroll_border) {
- point.x -= cache.scroll_border;
- } else if (point.x > get_size().width - cache.scroll_border) {
- point.x -= get_size().width - cache.scroll_border;
- } else {
- point.x = 0;
+ Point2 mouse_position = get_viewport()->get_mouse_position() - get_global_position();
+ if (scrolling && get_rect().grow(cache.scroll_border).has_point(mouse_position)) {
+ Point2 point;
+
+ if ((ABS(mouse_position.x) < ABS(mouse_position.x - get_size().width)) && (ABS(mouse_position.x) < cache.scroll_border)) {
+ point.x = mouse_position.x - cache.scroll_border;
+ } else if (ABS(mouse_position.x - get_size().width) < cache.scroll_border) {
+ point.x = mouse_position.x - (get_size().width - cache.scroll_border);
}
- if (point.y < cache.scroll_border) {
- point.y -= cache.scroll_border;
- } else if (point.y > get_size().height - cache.scroll_border) {
- point.y -= get_size().height - cache.scroll_border;
- } else {
- point.y = 0;
+
+ if ((ABS(mouse_position.y) < ABS(mouse_position.y - get_size().height)) && (ABS(mouse_position.y) < cache.scroll_border)) {
+ point.y = mouse_position.y - cache.scroll_border;
+ } else if (ABS(mouse_position.y - get_size().height) < cache.scroll_border) {
+ point.y = mouse_position.y - (get_size().height - cache.scroll_border);
}
+
point *= cache.scroll_speed * get_physics_process_delta_time();
point += get_scroll();
h_scroll->set_value(point.x);
@@ -3385,10 +3388,13 @@ void Tree::ensure_cursor_is_visible() {
int h = compute_item_height(selected) + cache.vseparation;
int screenh = get_size().height - h_scroll->get_combined_minimum_size().height;
- if (ofs + h > v_scroll->get_value() + screenh)
+ if (h > screenh) { //screen size is too small, maybe it was not resized yet.
+ v_scroll->set_value(ofs);
+ } else if (ofs + h > v_scroll->get_value() + screenh) {
v_scroll->call_deferred("set_value", ofs - screenh + h);
- else if (ofs < v_scroll->get_value())
+ } else if (ofs < v_scroll->get_value()) {
v_scroll->set_value(ofs);
+ }
}
int Tree::get_pressed_button() const {
diff --git a/scene/main/node.cpp b/scene/main/node.cpp
index 128168ca72..5f9c187e0b 100644
--- a/scene/main/node.cpp
+++ b/scene/main/node.cpp
@@ -2759,6 +2759,7 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("can_process"), &Node::can_process);
ClassDB::bind_method(D_METHOD("print_stray_nodes"), &Node::_print_stray_nodes);
ClassDB::bind_method(D_METHOD("get_position_in_parent"), &Node::get_position_in_parent);
+
ClassDB::bind_method(D_METHOD("set_display_folded", "fold"), &Node::set_display_folded);
ClassDB::bind_method(D_METHOD("is_displayed_folded"), &Node::is_displayed_folded);
@@ -2871,7 +2872,12 @@ void Node::_bind_methods() {
//ADD_PROPERTY( PropertyInfo( Variant::BOOL, "process/unhandled_input" ), "set_process_unhandled_input","is_processing_unhandled_input" ) ;
ADD_GROUP("Pause", "pause_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "pause_mode", PROPERTY_HINT_ENUM, "Inherit,Stop,Process"), "set_pause_mode", "get_pause_mode");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editor/display_folded", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_display_folded", "is_displayed_folded");
+
+#ifdef ENABLE_DEPRECATED
+ //no longer exists, but remains for compatibility (keep previous scenes folded
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editor/display_folded", PROPERTY_HINT_NONE, "", 0), "set_display_folded", "is_displayed_folded");
+#endif
+
ADD_PROPERTY(PropertyInfo(Variant::STRING, "name", PROPERTY_HINT_NONE, "", 0), "set_name", "get_name");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "filename", PROPERTY_HINT_NONE, "", 0), "set_filename", "get_filename");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "owner", PROPERTY_HINT_RESOURCE_TYPE, "Node", 0), "set_owner", "get_owner");
diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp
index 2524af9cfb..05c183275a 100644
--- a/scene/main/viewport.cpp
+++ b/scene/main/viewport.cpp
@@ -3222,7 +3222,7 @@ Viewport::Viewport() {
gui.tooltip_timer = -1;
//gui.tooltip_timer->force_parent_owned();
- gui.tooltip_delay = GLOBAL_DEF("gui/timers/tooltip_delay_sec", 0.7);
+ gui.tooltip_delay = GLOBAL_DEF("gui/timers/tooltip_delay_sec", 0.5);
ProjectSettings::get_singleton()->set_custom_property_info("gui/timers/tooltip_delay_sec", PropertyInfo(Variant::REAL, "gui/timers/tooltip_delay_sec", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater")); // No negative numbers
gui.tooltip = NULL;
diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp
index 87a15bbeda..3148df15dd 100644
--- a/scene/register_scene_types.cpp
+++ b/scene/register_scene_types.cpp
@@ -521,6 +521,8 @@ void register_scene_types() {
ClassDB::register_class<VisualShaderNodeTransformUniform>();
ClassDB::register_class<VisualShaderNodeTextureUniform>();
ClassDB::register_class<VisualShaderNodeCubeMapUniform>();
+ ClassDB::register_class<VisualShaderNodeIf>();
+ ClassDB::register_class<VisualShaderNodeSwitch>();
ClassDB::register_class<ShaderMaterial>();
ClassDB::register_virtual_class<CanvasItem>();
diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp
index 85018f38d7..67639858ce 100644
--- a/scene/resources/mesh.cpp
+++ b/scene/resources/mesh.cpp
@@ -37,6 +37,8 @@
#include <stdlib.h>
+Mesh::ConvexDecompositionFunc Mesh::convex_composition_function = NULL;
+
Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
if (triangle_mesh.is_valid())
@@ -543,6 +545,49 @@ void Mesh::clear_cache() const {
debug_lines.clear();
}
+Vector<Ref<Shape> > Mesh::convex_decompose() const {
+
+ ERR_FAIL_COND_V(!convex_composition_function, Vector<Ref<Shape> >());
+
+ PoolVector<Face3> faces = get_faces();
+ Vector<Face3> f3;
+ f3.resize(faces.size());
+ PoolVector<Face3>::Read f = faces.read();
+ for (int i = 0; i < f3.size(); i++) {
+ f3.write[i] = f[i];
+ }
+
+ Vector<Vector<Face3> > decomposed = convex_composition_function(f3);
+
+ Vector<Ref<Shape> > ret;
+
+ for (int i = 0; i < decomposed.size(); i++) {
+ Set<Vector3> points;
+ for (int j = 0; j < decomposed[i].size(); j++) {
+ points.insert(decomposed[i][j].vertex[0]);
+ points.insert(decomposed[i][j].vertex[1]);
+ points.insert(decomposed[i][j].vertex[2]);
+ }
+
+ PoolVector<Vector3> convex_points;
+ convex_points.resize(points.size());
+ {
+ PoolVector<Vector3>::Write w = convex_points.write();
+ int idx = 0;
+ for (Set<Vector3>::Element *E = points.front(); E; E = E->next()) {
+ w[idx++] = E->get();
+ }
+ }
+
+ Ref<ConvexPolygonShape> shape;
+ shape.instance();
+ shape->set_points(convex_points);
+ ret.push_back(shape);
+ }
+
+ return ret;
+}
+
Mesh::Mesh() {
}
diff --git a/scene/resources/mesh.h b/scene/resources/mesh.h
index dabfc6ea60..1457d283bd 100644
--- a/scene/resources/mesh.h
+++ b/scene/resources/mesh.h
@@ -31,6 +31,7 @@
#ifndef MESH_H
#define MESH_H
+#include "core/math/face3.h"
#include "core/math/triangle_mesh.h"
#include "core/resource.h"
#include "scene/resources/material.h"
@@ -147,6 +148,12 @@ public:
Size2 get_lightmap_size_hint() const;
void clear_cache() const;
+ typedef Vector<Vector<Face3> > (*ConvexDecompositionFunc)(const Vector<Face3> &);
+
+ static ConvexDecompositionFunc convex_composition_function;
+
+ Vector<Ref<Shape> > convex_decompose() const;
+
Mesh();
};
diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp
index b6efca9acc..e9f90fc85f 100644
--- a/scene/resources/resource_format_text.cpp
+++ b/scene/resources/resource_format_text.cpp
@@ -445,6 +445,11 @@ Error ResourceInteractiveLoaderText::poll() {
} else {
resource_cache.push_back(res);
+#ifdef TOOLS_ENABLED
+ //remember ID for saving
+ res->set_id_for_path(local_path,index);
+#endif
+
}
ExtResource er;
@@ -1355,7 +1360,7 @@ String ResourceFormatSaverTextInstance::_write_resource(const RES &res) {
if (external_resources.has(res)) {
- return "ExtResource( " + itos(external_resources[res] + 1) + " )";
+ return "ExtResource( " + itos(external_resources[res]) + " )";
} else {
if (internal_resources.has(res)) {
@@ -1459,7 +1464,8 @@ void ResourceFormatSaverTextInstance::_find_resources(const Variant &p_variant,
_find_resources(v);
}
} break;
- default: {}
+ default: {
+ }
}
}
@@ -1538,18 +1544,65 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_r
f->store_line("]\n"); //one empty line
}
- Vector<RES> sorted_er;
- sorted_er.resize(external_resources.size());
+ {
+
+
+ }
+
+#ifdef TOOLS_ENABLED
+ //keep order from cached ids
+ Set<int> cached_ids_found;
+ for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
+ int cached_id = E->key()->get_id_for_path(local_path);
+ if (cached_id < 0 || cached_ids_found.has(cached_id)) {
+ E->get() = -1; //reset
+ } else {
+ E->get() = cached_id;
+ cached_ids_found.insert(cached_id);
+ }
+ }
+ //create IDs for non cached resources
for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
+ if (cached_ids_found.has(E->get())) { //already cached, go on
+ continue;
+ }
+
+ int attempt = 1; //start from one, more readable format
+ while(cached_ids_found.has(attempt)) {
+ attempt++;
+ }
- sorted_er.write[E->get()] = E->key();
+ cached_ids_found.insert(attempt);
+ E->get() = attempt;
+ //update also in resource
+ Ref<Resource> res = E->key();
+ res->set_id_for_path(local_path,attempt);
}
+#else
+ //make sure to start from one, as it makes format more readable
+ for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
+ E->get() = E->get() + 1;
+ }
+#endif
+
+ Vector<ResourceSort> sorted_er;
+
+ for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
+
+ ResourceSort rs;
+ rs.resource = E->key();
+ rs.index = E->get();
+ sorted_er.push_back(rs);
+ }
+
+ sorted_er.sort();
+
for (int i = 0; i < sorted_er.size(); i++) {
- String p = sorted_er[i]->get_path();
+ String p = sorted_er[i].resource->get_path();
- f->store_string("[ext_resource path=\"" + p + "\" type=\"" + sorted_er[i]->get_save_class() + "\" id=" + itos(i + 1) + "]\n"); //bundled
+ f->store_string("[ext_resource path=\"" + p + "\" type=\"" + sorted_er[i].resource->get_save_class() + "\" id=" + itos(sorted_er[i].index) + "]\n"); //bundled
}
if (external_resources.size())
diff --git a/scene/resources/resource_format_text.h b/scene/resources/resource_format_text.h
index 8d78ab33b0..ab6f94986c 100644
--- a/scene/resources/resource_format_text.h
+++ b/scene/resources/resource_format_text.h
@@ -169,6 +169,15 @@ class ResourceFormatSaverTextInstance {
Map<RES, int> external_resources;
Map<RES, int> internal_resources;
+ struct ResourceSort {
+ RES resource;
+ int index;
+ bool operator<(const ResourceSort& p_right) const {
+ return index < p_right.index;
+ }
+
+ };
+
void _find_resources(const Variant &p_variant, bool p_main = false);
static String _write_resources(void *ud, const RES &p_resource);
diff --git a/scene/resources/sky.cpp b/scene/resources/sky.cpp
index f9f8ff19e4..48945d4e63 100644
--- a/scene/resources/sky.cpp
+++ b/scene/resources/sky.cpp
@@ -553,10 +553,10 @@ ProceduralSky::ProceduralSky(bool p_desaturate) {
ground_energy = 1;
if (p_desaturate) {
- sky_top_color.set_hsv(sky_top_color.get_h(),0,sky_top_color.get_v());
- sky_horizon_color.set_hsv(sky_horizon_color.get_h(),0,sky_horizon_color.get_v());
- ground_bottom_color.set_hsv(ground_bottom_color.get_h(),0,ground_bottom_color.get_v());
- ground_horizon_color.set_hsv(ground_horizon_color.get_h(),0,ground_horizon_color.get_v());
+ sky_top_color.set_hsv(sky_top_color.get_h(), 0, sky_top_color.get_v());
+ sky_horizon_color.set_hsv(sky_horizon_color.get_h(), 0, sky_horizon_color.get_v());
+ ground_bottom_color.set_hsv(ground_bottom_color.get_h(), 0, ground_bottom_color.get_v());
+ ground_horizon_color.set_hsv(ground_horizon_color.get_h(), 0, ground_horizon_color.get_v());
}
sun_color = Color(1, 1, 1);
sun_latitude = 35;
diff --git a/scene/resources/sky.h b/scene/resources/sky.h
index 7327b2a627..3a6f44e11b 100644
--- a/scene/resources/sky.h
+++ b/scene/resources/sky.h
@@ -191,7 +191,7 @@ public:
virtual RID get_rid() const;
- ProceduralSky(bool p_desaturate=false);
+ ProceduralSky(bool p_desaturate = false);
~ProceduralSky();
};
diff --git a/scene/resources/surface_tool.cpp b/scene/resources/surface_tool.cpp
index 83f29503fa..3ba43006a3 100644
--- a/scene/resources/surface_tool.cpp
+++ b/scene/resources/surface_tool.cpp
@@ -108,8 +108,55 @@ void SurfaceTool::add_vertex(const Vector3 &p_vertex) {
vtx.bones = last_bones;
vtx.tangent = last_tangent.normal;
vtx.binormal = last_normal.cross(last_tangent.normal).normalized() * last_tangent.d;
+
+ const int expected_vertices = 4;
+
+ if ((format & Mesh::ARRAY_FORMAT_WEIGHTS || format & Mesh::ARRAY_FORMAT_BONES) && (vtx.weights.size() != expected_vertices || vtx.bones.size() != expected_vertices)) {
+ //ensure vertices are the expected amount
+ ERR_FAIL_COND(vtx.weights.size() != vtx.bones.size());
+ if (vtx.weights.size() < expected_vertices) {
+ //less than requred, fill
+ for (int i = vtx.weights.size(); i < expected_vertices; i++) {
+ vtx.weights.push_back(0);
+ vtx.bones.push_back(0);
+ }
+ } else if (vtx.weights.size() > expected_vertices) {
+ //more than required, sort, cap and normalize.
+ Vector<WeightSort> weights;
+ for (int i = 0; i < vtx.weights.size(); i++) {
+ WeightSort ws;
+ ws.index = vtx.bones[i];
+ ws.weight = vtx.weights[i];
+ weights.push_back(ws);
+ }
+
+ //sort
+ weights.sort();
+ //cap
+ weights.resize(expected_vertices);
+ //renormalize
+ float total = 0;
+ for (int i = 0; i < expected_vertices; i++) {
+ total += weights[i].weight;
+ }
+
+ vtx.weights.resize(expected_vertices);
+ vtx.bones.resize(expected_vertices);
+
+ for (int i = 0; i < expected_vertices; i++) {
+ if (total > 0) {
+ vtx.weights.write[i] = weights[i].weight / total;
+ } else {
+ vtx.weights.write[i] = 0;
+ }
+ vtx.bones.write[i] = weights[i].index;
+ }
+ }
+ }
+
vertex_array.push_back(vtx);
first = false;
+
format |= Mesh::ARRAY_FORMAT_VERTEX;
}
void SurfaceTool::add_color(Color p_color) {
@@ -161,7 +208,6 @@ void SurfaceTool::add_uv2(const Vector2 &p_uv2) {
void SurfaceTool::add_bones(const Vector<int> &p_bones) {
ERR_FAIL_COND(!begun);
- ERR_FAIL_COND(p_bones.size() != 4);
ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_BONES));
format |= Mesh::ARRAY_FORMAT_BONES;
@@ -171,8 +217,6 @@ void SurfaceTool::add_bones(const Vector<int> &p_bones) {
void SurfaceTool::add_weights(const Vector<float> &p_weights) {
ERR_FAIL_COND(!begun);
-
- ERR_FAIL_COND(p_weights.size() != 4);
ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_WEIGHTS));
format |= Mesh::ARRAY_FORMAT_WEIGHTS;
@@ -397,7 +441,8 @@ Array SurfaceTool::commit_to_arrays() {
a[i] = array;
} break;
- default: {}
+ default: {
+ }
}
}
diff --git a/scene/resources/surface_tool.h b/scene/resources/surface_tool.h
index a3b110f0d8..c55cade813 100644
--- a/scene/resources/surface_tool.h
+++ b/scene/resources/surface_tool.h
@@ -62,6 +62,14 @@ private:
static _FORCE_INLINE_ uint32_t hash(const Vertex &p_vtx);
};
+ struct WeightSort {
+ int index;
+ float weight;
+ bool operator<(const WeightSort &p_right) const {
+ return weight < p_right.weight;
+ }
+ };
+
bool begun;
bool first;
Mesh::PrimitiveType primitive;
diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp
index bac10a1cd5..4229147ba2 100644
--- a/scene/resources/visual_shader.cpp
+++ b/scene/resources/visual_shader.cpp
@@ -782,7 +782,7 @@ Error VisualShader::_write_node(Type type, StringBuilder &global_code, StringBui
} else if (in_type == VisualShaderNode::PORT_TYPE_VECTOR && out_type == VisualShaderNode::PORT_TYPE_SCALAR) {
inputs[i] = "vec3(" + src_var + ")";
} else if (in_type == VisualShaderNode::PORT_TYPE_BOOLEAN && out_type == VisualShaderNode::PORT_TYPE_VECTOR) {
- inputs[i] = "all(" + src_var + ")";
+ inputs[i] = "all(bvec3(" + src_var + "))";
} else if (in_type == VisualShaderNode::PORT_TYPE_BOOLEAN && out_type == VisualShaderNode::PORT_TYPE_SCALAR) {
inputs[i] = src_var + ">0.0?true:false";
} else if (in_type == VisualShaderNode::PORT_TYPE_SCALAR && out_type == VisualShaderNode::PORT_TYPE_BOOLEAN) {
@@ -839,7 +839,8 @@ Error VisualShader::_write_node(Type type, StringBuilder &global_code, StringBui
case VisualShaderNode::PORT_TYPE_VECTOR: code += String() + "\tvec3 " + outputs[i] + ";\n"; break;
case VisualShaderNode::PORT_TYPE_BOOLEAN: code += String() + "\tbool " + outputs[i] + ";\n"; break;
case VisualShaderNode::PORT_TYPE_TRANSFORM: code += String() + "\tmat4 " + outputs[i] + ";\n"; break;
- default: {}
+ default: {
+ }
}
}
diff --git a/scene/resources/visual_shader_nodes.cpp b/scene/resources/visual_shader_nodes.cpp
index dac999bf1d..d02902572c 100644
--- a/scene/resources/visual_shader_nodes.cpp
+++ b/scene/resources/visual_shader_nodes.cpp
@@ -2948,3 +2948,140 @@ String VisualShaderNodeCubeMapUniform::generate_code(Shader::Mode p_mode, Visual
VisualShaderNodeCubeMapUniform::VisualShaderNodeCubeMapUniform() {
}
+
+////////////// If
+
+String VisualShaderNodeIf::get_caption() const {
+ return "If";
+}
+
+int VisualShaderNodeIf::get_input_port_count() const {
+ return 6;
+}
+
+VisualShaderNodeIf::PortType VisualShaderNodeIf::get_input_port_type(int p_port) const {
+ if (p_port == 0 || p_port == 1 || p_port == 2) {
+ return PORT_TYPE_SCALAR;
+ }
+ return PORT_TYPE_VECTOR;
+}
+
+String VisualShaderNodeIf::get_input_port_name(int p_port) const {
+ switch (p_port) {
+ case 0:
+ return "a";
+ case 1:
+ return "b";
+ case 2:
+ return "tolerance";
+ case 3:
+ return "a == b";
+ case 4:
+ return "a > b";
+ case 5:
+ return "a < b";
+ default:
+ return "";
+ }
+}
+
+int VisualShaderNodeIf::get_output_port_count() const {
+ return 1;
+}
+
+VisualShaderNodeIf::PortType VisualShaderNodeIf::get_output_port_type(int p_port) const {
+ return PORT_TYPE_VECTOR;
+}
+
+String VisualShaderNodeIf::get_output_port_name(int p_port) const {
+ return "result";
+}
+
+String VisualShaderNodeIf::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
+
+ String code;
+ code += "\tif(abs(" + p_input_vars[0] + "-" + p_input_vars[1] + ")<" + p_input_vars[2] + ")\n"; // abs(a - b) < tolerance eg. a == b
+ code += "\t{\n";
+ code += "\t\t" + p_output_vars[0] + "=" + p_input_vars[3] + ";\n";
+ code += "\t}\n";
+ code += "\telse if(" + p_input_vars[0] + "<" + p_input_vars[1] + ")\n"; // a < b
+ code += "\t{\n";
+ code += "\t\t" + p_output_vars[0] + "=" + p_input_vars[5] + ";\n";
+ code += "\t}\n";
+ code += "\telse\n"; // a > b (or a >= b if abs(a - b) < tolerance is false)
+ code += "\t{\n";
+ code += "\t\t" + p_output_vars[0] + "=" + p_input_vars[4] + ";\n";
+ code += "\t}\n";
+ return code;
+}
+
+VisualShaderNodeIf::VisualShaderNodeIf() {
+ set_input_port_default_value(0, 0.0);
+ set_input_port_default_value(1, 0.0);
+ set_input_port_default_value(2, CMP_EPSILON);
+ set_input_port_default_value(3, Vector3(0.0, 0.0, 0.0));
+ set_input_port_default_value(4, Vector3(0.0, 0.0, 0.0));
+ set_input_port_default_value(5, Vector3(0.0, 0.0, 0.0));
+}
+
+////////////// Switch
+
+String VisualShaderNodeSwitch::get_caption() const {
+ return "Switch";
+}
+
+int VisualShaderNodeSwitch::get_input_port_count() const {
+ return 3;
+}
+
+VisualShaderNodeSwitch::PortType VisualShaderNodeSwitch::get_input_port_type(int p_port) const {
+ if (p_port == 0) {
+ return PORT_TYPE_BOOLEAN;
+ }
+ return PORT_TYPE_VECTOR;
+}
+
+String VisualShaderNodeSwitch::get_input_port_name(int p_port) const {
+ switch (p_port) {
+ case 0:
+ return "value";
+ case 1:
+ return "true";
+ case 2:
+ return "false";
+ default:
+ return "";
+ }
+}
+
+int VisualShaderNodeSwitch::get_output_port_count() const {
+ return 1;
+}
+
+VisualShaderNodeSwitch::PortType VisualShaderNodeSwitch::get_output_port_type(int p_port) const {
+ return PORT_TYPE_VECTOR;
+}
+
+String VisualShaderNodeSwitch::get_output_port_name(int p_port) const {
+ return "result";
+}
+
+String VisualShaderNodeSwitch::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
+
+ String code;
+ code += "\tif(" + p_input_vars[0] + ")\n";
+ code += "\t{\n";
+ code += "\t\t" + p_output_vars[0] + "=" + p_input_vars[1] + ";\n";
+ code += "\t}\n";
+ code += "\telse\n";
+ code += "\t{\n";
+ code += "\t\t" + p_output_vars[0] + "=" + p_input_vars[2] + ";\n";
+ code += "\t}\n";
+ return code;
+}
+
+VisualShaderNodeSwitch::VisualShaderNodeSwitch() {
+ set_input_port_default_value(0, false);
+ set_input_port_default_value(1, Vector3(0.0, 0.0, 0.0));
+ set_input_port_default_value(2, Vector3(0.0, 0.0, 0.0));
+}
diff --git a/scene/resources/visual_shader_nodes.h b/scene/resources/visual_shader_nodes.h
index 28ead64fe2..90c479bd48 100644
--- a/scene/resources/visual_shader_nodes.h
+++ b/scene/resources/visual_shader_nodes.h
@@ -1440,4 +1440,48 @@ public:
VisualShaderNodeCubeMapUniform();
};
+///////////////////////////////////////
+/// IF
+///////////////////////////////////////
+
+class VisualShaderNodeIf : public VisualShaderNode {
+ GDCLASS(VisualShaderNodeIf, VisualShaderNode)
+public:
+ virtual String get_caption() const;
+
+ virtual int get_input_port_count() const;
+ virtual PortType get_input_port_type(int p_port) const;
+ virtual String get_input_port_name(int p_port) const;
+
+ virtual int get_output_port_count() const;
+ virtual PortType get_output_port_type(int p_port) const;
+ virtual String get_output_port_name(int p_port) const;
+
+ virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const;
+
+ VisualShaderNodeIf();
+};
+
+///////////////////////////////////////
+/// SWITCH
+///////////////////////////////////////
+
+class VisualShaderNodeSwitch : public VisualShaderNode {
+ GDCLASS(VisualShaderNodeSwitch, VisualShaderNode)
+public:
+ virtual String get_caption() const;
+
+ virtual int get_input_port_count() const;
+ virtual PortType get_input_port_type(int p_port) const;
+ virtual String get_input_port_name(int p_port) const;
+
+ virtual int get_output_port_count() const;
+ virtual PortType get_output_port_type(int p_port) const;
+ virtual String get_output_port_name(int p_port) const;
+
+ virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const;
+
+ VisualShaderNodeSwitch();
+};
+
#endif // VISUAL_SHADER_NODES_H
diff --git a/servers/audio/effects/audio_effect_spectrum_analyzer.cpp b/servers/audio/effects/audio_effect_spectrum_analyzer.cpp
new file mode 100644
index 0000000000..71a8904472
--- /dev/null
+++ b/servers/audio/effects/audio_effect_spectrum_analyzer.cpp
@@ -0,0 +1,249 @@
+#include "audio_effect_spectrum_analyzer.h"
+#include "servers/audio_server.h"
+
+static void smbFft(float *fftBuffer, long fftFrameSize, long sign)
+/*
+ FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse)
+ Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the
+ time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes
+ and returns the cosine and sine parts in an interleaved manner, ie.
+ fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize
+ must be a power of 2. It expects a complex input signal (see footnote 2),
+ ie. when working with 'common' audio signals our input signal has to be
+ passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform
+ of the frequencies of interest is in fftBuffer[0...fftFrameSize].
+*/
+{
+ float wr, wi, arg, *p1, *p2, temp;
+ float tr, ti, ur, ui, *p1r, *p1i, *p2r, *p2i;
+ long i, bitm, j, le, le2, k;
+
+ for (i = 2; i < 2 * fftFrameSize - 2; i += 2) {
+ for (bitm = 2, j = 0; bitm < 2 * fftFrameSize; bitm <<= 1) {
+ if (i & bitm) j++;
+ j <<= 1;
+ }
+ if (i < j) {
+ p1 = fftBuffer + i;
+ p2 = fftBuffer + j;
+ temp = *p1;
+ *(p1++) = *p2;
+ *(p2++) = temp;
+ temp = *p1;
+ *p1 = *p2;
+ *p2 = temp;
+ }
+ }
+ for (k = 0, le = 2; k < (long)(log((double)fftFrameSize) / log(2.) + .5); k++) {
+ le <<= 1;
+ le2 = le >> 1;
+ ur = 1.0;
+ ui = 0.0;
+ arg = Math_PI / (le2 >> 1);
+ wr = cos(arg);
+ wi = sign * sin(arg);
+ for (j = 0; j < le2; j += 2) {
+ p1r = fftBuffer + j;
+ p1i = p1r + 1;
+ p2r = p1r + le2;
+ p2i = p2r + 1;
+ for (i = j; i < 2 * fftFrameSize; i += le) {
+ tr = *p2r * ur - *p2i * ui;
+ ti = *p2r * ui + *p2i * ur;
+ *p2r = *p1r - tr;
+ *p2i = *p1i - ti;
+ *p1r += tr;
+ *p1i += ti;
+ p1r += le;
+ p1i += le;
+ p2r += le;
+ p2i += le;
+ }
+ tr = ur * wr - ui * wi;
+ ui = ur * wi + ui * wr;
+ ur = tr;
+ }
+ }
+}
+void AudioEffectSpectrumAnalyzerInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
+
+ uint64_t time = OS::get_singleton()->get_ticks_usec();
+
+ //copy everything over first, since this only really does capture
+ for (int i = 0; i < p_frame_count; i++) {
+ p_dst_frames[i] = p_src_frames[i];
+ }
+
+ //capture spectrum
+ while (p_frame_count) {
+ int to_fill = fft_size * 2 - temporal_fft_pos;
+ to_fill = MIN(to_fill, p_frame_count);
+
+ float *fftw = temporal_fft.ptrw();
+ for (int i = 0; i < to_fill; i++) { //left and right buffers
+ fftw[(i + temporal_fft_pos) * 2] = p_src_frames[i].l;
+ fftw[(i + temporal_fft_pos) * 2 + 1] = 0;
+ fftw[(i + temporal_fft_pos + fft_size * 2) * 2] = p_src_frames[i].r;
+ fftw[(i + temporal_fft_pos + fft_size * 2) * 2 + 1] = 0;
+ }
+
+ p_src_frames += to_fill;
+ temporal_fft_pos += to_fill;
+ p_frame_count -= to_fill;
+
+ if (temporal_fft_pos == fft_size * 2) {
+ //time to do a FFT
+ smbFft(fftw, fft_size * 2, -1);
+ smbFft(fftw + fft_size * 4, fft_size * 2, -1);
+ int next = (fft_pos + 1) % fft_count;
+
+ AudioFrame *hw = (AudioFrame *)fft_history[next].ptr(); //do not use write, avoid cow
+
+ for (int i = 0; i < fft_size; i++) {
+ //abs(vec)/fft_size normalizes each frequency
+ float window = 1.0; //-.5 * Math::cos(2. * Math_PI * (double)i / (double)fft_size) + .5;
+ hw[i].l = window * Vector2(fftw[i * 2], fftw[i * 2 + 1]).length() / float(fft_size);
+ hw[i].r = window * Vector2(fftw[fft_size * 4 + i * 2], fftw[fft_size * 4 + i * 2 + 1]).length() / float(fft_size);
+ }
+
+ fft_pos = next; //swap
+ temporal_fft_pos = 0;
+ }
+ }
+
+ //determine time of capture
+ double remainer_sec = (temporal_fft_pos / mix_rate); //substract remainder from mix time
+ last_fft_time = time - uint64_t(remainer_sec * 1000000.0);
+}
+
+void AudioEffectSpectrumAnalyzerInstance::_bind_methods() {
+
+ ClassDB::bind_method(D_METHOD("get_magnitude_for_frequency_range", "from_hz", "to_hz", "mode"), &AudioEffectSpectrumAnalyzerInstance::get_magnitude_for_frequency_range, DEFVAL(MAGNITUDE_MAX));
+ BIND_ENUM_CONSTANT(MAGNITUDE_AVERAGE);
+ BIND_ENUM_CONSTANT(MAGNITUDE_MAX);
+}
+
+Vector2 AudioEffectSpectrumAnalyzerInstance::get_magnitude_for_frequency_range(float p_begin, float p_end, MagnitudeMode p_mode) const {
+
+ if (last_fft_time == 0) {
+ return Vector2();
+ }
+ uint64_t time = OS::get_singleton()->get_ticks_usec();
+ float diff = double(time - last_fft_time) / 1000000.0 + base->get_tap_back_pos();
+ diff -= AudioServer::get_singleton()->get_output_delay();
+ float fft_time_size = float(fft_size) / mix_rate;
+
+ int fft_index = fft_pos;
+
+ while (diff > fft_time_size) {
+ diff -= fft_time_size;
+ fft_index -= 1;
+ if (fft_index < 0) {
+ fft_index = fft_count - 1;
+ }
+ }
+
+ int begin_pos = p_begin * fft_size / (mix_rate * 0.5);
+ int end_pos = p_end * fft_size / (mix_rate * 0.5);
+
+ begin_pos = CLAMP(begin_pos, 0, fft_size - 1);
+ end_pos = CLAMP(end_pos, 0, fft_size - 1);
+
+ if (begin_pos > end_pos) {
+ SWAP(begin_pos, end_pos);
+ }
+ const AudioFrame *r = fft_history[fft_index].ptr();
+
+ if (p_mode == MAGNITUDE_AVERAGE) {
+ Vector2 avg;
+
+ for (int i = begin_pos; i <= end_pos; i++) {
+ avg += Vector2(r[i]);
+ }
+
+ avg /= float(end_pos - begin_pos + 1);
+
+ return avg;
+ } else {
+
+ Vector2 max;
+
+ for (int i = begin_pos; i <= end_pos; i++) {
+ max.x = MAX(max.x, r[i].l);
+ max.y = MAX(max.x, r[i].r);
+ }
+
+ return max;
+ }
+}
+
+Ref<AudioEffectInstance> AudioEffectSpectrumAnalyzer::instance() {
+
+ Ref<AudioEffectSpectrumAnalyzerInstance> ins;
+ ins.instance();
+ ins->base = Ref<AudioEffectSpectrumAnalyzer>(this);
+ static const int fft_sizes[FFT_SIZE_MAX] = { 256, 512, 1024, 2048, 4096 };
+ ins->fft_size = fft_sizes[fft_size];
+ ins->mix_rate = AudioServer::get_singleton()->get_mix_rate();
+ ins->fft_count = (buffer_length / (float(ins->fft_size) / ins->mix_rate)) + 1;
+ ins->fft_pos = 0;
+ ins->last_fft_time = 0;
+ ins->fft_history.resize(ins->fft_count);
+ ins->temporal_fft.resize(ins->fft_size * 8); //x2 stereo, x2 amount of samples for freqs, x2 for input
+ ins->temporal_fft_pos = 0;
+ for (int i = 0; i < ins->fft_count; i++) {
+ ins->fft_history.write[i].resize(ins->fft_size); //only magnitude matters
+ for (int j = 0; j < ins->fft_size; j++) {
+ ins->fft_history.write[i].write[j] = AudioFrame(0, 0);
+ }
+ }
+ return ins;
+}
+
+void AudioEffectSpectrumAnalyzer::set_buffer_length(float p_volume) {
+ buffer_length = p_volume;
+}
+
+float AudioEffectSpectrumAnalyzer::get_buffer_length() const {
+
+ return buffer_length;
+}
+
+void AudioEffectSpectrumAnalyzer::set_tap_back_pos(float p_seconds) {
+ tapback_pos = p_seconds;
+}
+
+float AudioEffectSpectrumAnalyzer::get_tap_back_pos() const {
+ return tapback_pos;
+}
+
+void AudioEffectSpectrumAnalyzer::set_fft_size(FFT_Size p_fft_size) {
+ ERR_FAIL_INDEX(p_fft_size, FFT_SIZE_MAX);
+ fft_size = p_fft_size;
+}
+
+AudioEffectSpectrumAnalyzer::FFT_Size AudioEffectSpectrumAnalyzer::get_fft_size() const {
+ return fft_size;
+}
+
+void AudioEffectSpectrumAnalyzer::_bind_methods() {
+
+ ClassDB::bind_method(D_METHOD("set_buffer_length", "seconds"), &AudioEffectSpectrumAnalyzer::set_buffer_length);
+ ClassDB::bind_method(D_METHOD("get_buffer_length"), &AudioEffectSpectrumAnalyzer::get_buffer_length);
+
+ ClassDB::bind_method(D_METHOD("set_tap_back_pos", "seconds"), &AudioEffectSpectrumAnalyzer::set_tap_back_pos);
+ ClassDB::bind_method(D_METHOD("get_tap_back_pos"), &AudioEffectSpectrumAnalyzer::get_tap_back_pos);
+
+ ClassDB::bind_method(D_METHOD("set_fft_size", "size"), &AudioEffectSpectrumAnalyzer::set_fft_size);
+ ClassDB::bind_method(D_METHOD("get_fft_size"), &AudioEffectSpectrumAnalyzer::get_fft_size);
+
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "buffer_length", PROPERTY_HINT_RANGE, "0.1,4,0.1"), "set_buffer_length", "get_buffer_length");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap_back_pos", PROPERTY_HINT_RANGE, "0.1,4,0.1"), "set_tap_back_pos", "get_tap_back_pos");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "fft_size", PROPERTY_HINT_ENUM, "256,512,1024,2048,4096"), "set_fft_size", "get_fft_size");
+}
+
+AudioEffectSpectrumAnalyzer::AudioEffectSpectrumAnalyzer() {
+ buffer_length = 2;
+ tapback_pos = 0.01;
+ fft_size = FFT_SIZE_1024;
+}
diff --git a/servers/audio/effects/audio_effect_spectrum_analyzer.h b/servers/audio/effects/audio_effect_spectrum_analyzer.h
new file mode 100644
index 0000000000..0534426da3
--- /dev/null
+++ b/servers/audio/effects/audio_effect_spectrum_analyzer.h
@@ -0,0 +1,76 @@
+#ifndef AUDIO_EFFECT_SPECTRUM_ANALYZER_H
+#define AUDIO_EFFECT_SPECTRUM_ANALYZER_H
+
+#include "servers/audio/audio_effect.h"
+
+class AudioEffectSpectrumAnalyzer;
+
+class AudioEffectSpectrumAnalyzerInstance : public AudioEffectInstance {
+ GDCLASS(AudioEffectSpectrumAnalyzerInstance, AudioEffectInstance)
+
+public:
+ enum MagnitudeMode {
+ MAGNITUDE_AVERAGE,
+ MAGNITUDE_MAX,
+ };
+
+private:
+ friend class AudioEffectSpectrumAnalyzer;
+ Ref<AudioEffectSpectrumAnalyzer> base;
+
+ Vector<Vector<AudioFrame> > fft_history;
+ Vector<float> temporal_fft;
+ int temporal_fft_pos;
+ int fft_size;
+ int fft_count;
+ int fft_pos;
+ float mix_rate;
+ uint64_t last_fft_time;
+
+protected:
+ static void _bind_methods();
+
+public:
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
+ Vector2 get_magnitude_for_frequency_range(float p_begin, float p_end, MagnitudeMode p_mode = MAGNITUDE_MAX) const;
+};
+
+VARIANT_ENUM_CAST(AudioEffectSpectrumAnalyzerInstance::MagnitudeMode)
+
+class AudioEffectSpectrumAnalyzer : public AudioEffect {
+ GDCLASS(AudioEffectSpectrumAnalyzer, AudioEffect)
+public:
+ enum FFT_Size {
+ FFT_SIZE_256,
+ FFT_SIZE_512,
+ FFT_SIZE_1024,
+ FFT_SIZE_2048,
+ FFT_SIZE_4096,
+ FFT_SIZE_MAX
+ };
+
+public:
+ friend class AudioEffectSpectrumAnalyzerInstance;
+ float buffer_length;
+ float tapback_pos;
+ FFT_Size fft_size;
+
+protected:
+ static void _bind_methods();
+
+public:
+ Ref<AudioEffectInstance> instance();
+ void set_buffer_length(float p_seconds);
+ float get_buffer_length() const;
+ void set_tap_back_pos(float p_seconds);
+ float get_tap_back_pos() const;
+
+ void set_fft_size(FFT_Size);
+ FFT_Size get_fft_size() const;
+
+ AudioEffectSpectrumAnalyzer();
+};
+
+VARIANT_ENUM_CAST(AudioEffectSpectrumAnalyzer::FFT_Size);
+
+#endif // AUDIO_EFFECT_SPECTRUM_ANALYZER_H
diff --git a/servers/audio/effects/audio_stream_generator.cpp b/servers/audio/effects/audio_stream_generator.cpp
new file mode 100644
index 0000000000..f4a66b5643
--- /dev/null
+++ b/servers/audio/effects/audio_stream_generator.cpp
@@ -0,0 +1,182 @@
+#include "audio_stream_generator.h"
+
+void AudioStreamGenerator::set_mix_rate(float p_mix_rate) {
+ mix_rate = p_mix_rate;
+}
+
+float AudioStreamGenerator::get_mix_rate() const {
+
+ return mix_rate;
+}
+
+void AudioStreamGenerator::set_buffer_length(float p_seconds) {
+
+ buffer_len = p_seconds;
+}
+float AudioStreamGenerator::get_buffer_length() const {
+
+ return buffer_len;
+}
+
+Ref<AudioStreamPlayback> AudioStreamGenerator::instance_playback() {
+
+ Ref<AudioStreamGeneratorPlayback> playback;
+ playback.instance();
+ playback->generator = this;
+ int target_buffer_size = mix_rate * buffer_len;
+ playback->buffer.resize(nearest_shift(target_buffer_size));
+ playback->buffer.clear();
+ return playback;
+}
+String AudioStreamGenerator::get_stream_name() const {
+
+ return "UserFeed";
+}
+
+float AudioStreamGenerator::get_length() const {
+ return 0;
+}
+
+void AudioStreamGenerator::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_mix_rate", "hz"), &AudioStreamGenerator::set_mix_rate);
+ ClassDB::bind_method(D_METHOD("get_mix_rate"), &AudioStreamGenerator::get_mix_rate);
+
+ ClassDB::bind_method(D_METHOD("set_buffer_length", "seconds"), &AudioStreamGenerator::set_buffer_length);
+ ClassDB::bind_method(D_METHOD("get_buffer_length"), &AudioStreamGenerator::get_buffer_length);
+
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "mix_rate", PROPERTY_HINT_RANGE, "20,192000,1"), "set_mix_rate", "get_mix_rate");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "buffer_length", PROPERTY_HINT_RANGE, "0.01,10,0.01"), "set_buffer_length", "get_buffer_length");
+}
+
+AudioStreamGenerator::AudioStreamGenerator() {
+ mix_rate = 44100;
+ buffer_len = 0.5;
+}
+
+////////////////
+
+bool AudioStreamGeneratorPlayback::push_frame(const Vector2 &p_frame) {
+ if (buffer.space_left() < 1) {
+ return false;
+ }
+
+ AudioFrame f = p_frame;
+
+ buffer.write(&f, 1);
+ return true;
+}
+
+bool AudioStreamGeneratorPlayback::can_push_buffer(int p_frames) const {
+ return buffer.space_left() >= p_frames;
+}
+bool AudioStreamGeneratorPlayback::push_buffer(const PoolVector2Array &p_frames) {
+
+ int to_write = p_frames.size();
+ if (buffer.space_left() < to_write) {
+ return false;
+ }
+
+ PoolVector2Array::Read r = p_frames.read();
+ if (sizeof(real_t) == 4) {
+ //write directly
+ buffer.write((const AudioFrame *)r.ptr(), to_write);
+ } else {
+ //convert from double
+ AudioFrame buf[2048];
+ int ofs = 0;
+ while (to_write) {
+
+ int w = MIN(to_write, 2048);
+ for (int i = 0; i < w; i++) {
+ buf[i] = r[i + ofs];
+ }
+ buffer.write(buf, w);
+ ofs += w;
+ to_write -= w;
+ }
+ }
+ return true;
+}
+
+int AudioStreamGeneratorPlayback::get_frames_available() const {
+ return buffer.space_left();
+}
+
+int AudioStreamGeneratorPlayback::get_skips() const {
+ return skips;
+}
+
+void AudioStreamGeneratorPlayback::clear_buffer() {
+ ERR_FAIL_COND(active);
+ buffer.clear();
+ mixed = 0;
+}
+
+void AudioStreamGeneratorPlayback::_mix_internal(AudioFrame *p_buffer, int p_frames) {
+
+ int read_amount = buffer.data_left();
+ if (p_frames < read_amount) {
+ read_amount = p_frames;
+ }
+
+ buffer.read(p_buffer, read_amount);
+
+ if (read_amount < p_frames) {
+ //skipped, not ideal
+ for (int i = read_amount; i < p_frames; i++) {
+ p_buffer[i] = AudioFrame(0, 0);
+ }
+
+ skips++;
+ }
+
+ mixed += p_frames / generator->get_mix_rate();
+}
+float AudioStreamGeneratorPlayback::get_stream_sampling_rate() {
+ return generator->get_mix_rate();
+}
+
+void AudioStreamGeneratorPlayback::start(float p_from_pos) {
+
+ if (mixed == 0.0) {
+ _begin_resample();
+ }
+ skips = 0;
+ active = true;
+ mixed = 0.0;
+}
+
+void AudioStreamGeneratorPlayback::stop() {
+ active = false;
+}
+bool AudioStreamGeneratorPlayback::is_playing() const {
+
+ return active; //always playing, can't be stopped
+}
+
+int AudioStreamGeneratorPlayback::get_loop_count() const {
+ return 0;
+}
+
+float AudioStreamGeneratorPlayback::get_playback_position() const {
+ return mixed;
+}
+void AudioStreamGeneratorPlayback::seek(float p_time) {
+ //no seek possible
+}
+
+void AudioStreamGeneratorPlayback::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("push_frame", "frame"), &AudioStreamGeneratorPlayback::push_frame);
+ ClassDB::bind_method(D_METHOD("can_push_buffer", "amount"), &AudioStreamGeneratorPlayback::can_push_buffer);
+ ClassDB::bind_method(D_METHOD("push_buffer", "frames"), &AudioStreamGeneratorPlayback::push_buffer);
+ ClassDB::bind_method(D_METHOD("get_frames_available"), &AudioStreamGeneratorPlayback::get_frames_available);
+ ClassDB::bind_method(D_METHOD("get_skips"), &AudioStreamGeneratorPlayback::get_skips);
+ ClassDB::bind_method(D_METHOD("clear_buffer"), &AudioStreamGeneratorPlayback::clear_buffer);
+}
+
+AudioStreamGeneratorPlayback::AudioStreamGeneratorPlayback() {
+ generator = NULL;
+ skips = 0;
+ active = false;
+ mixed = 0;
+}
diff --git a/servers/audio/effects/audio_stream_generator.h b/servers/audio/effects/audio_stream_generator.h
new file mode 100644
index 0000000000..2082682907
--- /dev/null
+++ b/servers/audio/effects/audio_stream_generator.h
@@ -0,0 +1,66 @@
+#ifndef AUDIO_STREAM_USER_FED_H
+#define AUDIO_STREAM_USER_FED_H
+
+#include "core/ring_buffer.h"
+#include "servers/audio/audio_stream.h"
+
+class AudioStreamGenerator : public AudioStream {
+ GDCLASS(AudioStreamGenerator, AudioStream)
+
+ float mix_rate;
+ float buffer_len;
+
+protected:
+ static void _bind_methods();
+
+public:
+ void set_mix_rate(float p_mix_rate);
+ float get_mix_rate() const;
+
+ void set_buffer_length(float p_seconds);
+ float get_buffer_length() const;
+
+ virtual Ref<AudioStreamPlayback> instance_playback();
+ virtual String get_stream_name() const;
+
+ virtual float get_length() const;
+ AudioStreamGenerator();
+};
+
+class AudioStreamGeneratorPlayback : public AudioStreamPlaybackResampled {
+
+ GDCLASS(AudioStreamGeneratorPlayback, AudioStreamPlaybackResampled)
+ friend class AudioStreamGenerator;
+ RingBuffer<AudioFrame> buffer;
+ int skips;
+ bool active;
+ float mixed;
+ AudioStreamGenerator *generator;
+
+protected:
+ virtual void _mix_internal(AudioFrame *p_buffer, int p_frames);
+ virtual float get_stream_sampling_rate();
+
+ static void _bind_methods();
+
+public:
+ virtual void start(float p_from_pos = 0.0);
+ virtual void stop();
+ virtual bool is_playing() const;
+
+ virtual int get_loop_count() const; //times it looped
+
+ virtual float get_playback_position() const;
+ virtual void seek(float p_time);
+
+ bool push_frame(const Vector2 &p_frame);
+ bool can_push_buffer(int p_frames) const;
+ bool push_buffer(const PoolVector2Array &p_frames);
+ int get_frames_available() const;
+ int get_skips() const;
+
+ void clear_buffer();
+
+ AudioStreamGeneratorPlayback();
+};
+#endif // AUDIO_STREAM_USER_FED_H
diff --git a/servers/audio_server.cpp b/servers/audio_server.cpp
index 7b2b48fe47..c83c3029f3 100644
--- a/servers/audio_server.cpp
+++ b/servers/audio_server.cpp
@@ -876,6 +876,15 @@ int AudioServer::get_bus_effect_count(int p_bus) {
return buses[p_bus]->effects.size();
}
+Ref<AudioEffectInstance> AudioServer::get_bus_effect_instance(int p_bus, int p_effect, int p_channel) {
+
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), Ref<AudioEffectInstance>());
+ ERR_FAIL_INDEX_V(p_effect, buses[p_bus]->effects.size(), Ref<AudioEffectInstance>());
+ ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), Ref<AudioEffectInstance>());
+
+ return buses[p_bus]->channels[p_channel].effect_instances[p_effect];
+}
+
Ref<AudioEffect> AudioServer::get_bus_effect(int p_bus, int p_effect) {
ERR_FAIL_INDEX_V(p_bus, buses.size(), Ref<AudioEffect>());
@@ -1330,6 +1339,7 @@ void AudioServer::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_bus_effect_count", "bus_idx"), &AudioServer::get_bus_effect_count);
ClassDB::bind_method(D_METHOD("get_bus_effect", "bus_idx", "effect_idx"), &AudioServer::get_bus_effect);
+ ClassDB::bind_method(D_METHOD("get_bus_effect_instance", "bus_idx", "effect_idx", "channel"), &AudioServer::get_bus_effect_instance, DEFVAL(0));
ClassDB::bind_method(D_METHOD("swap_bus_effects", "bus_idx", "effect_idx", "by_effect_idx"), &AudioServer::swap_bus_effects);
ClassDB::bind_method(D_METHOD("set_bus_effect_enabled", "bus_idx", "effect_idx", "enabled"), &AudioServer::set_bus_effect_enabled);
diff --git a/servers/audio_server.h b/servers/audio_server.h
index 6bd8093c76..3b69cb1b88 100644
--- a/servers/audio_server.h
+++ b/servers/audio_server.h
@@ -322,6 +322,7 @@ public:
int get_bus_effect_count(int p_bus);
Ref<AudioEffect> get_bus_effect(int p_bus, int p_effect);
+ Ref<AudioEffectInstance> get_bus_effect_instance(int p_bus, int p_effect, int p_channel = 0);
void swap_bus_effects(int p_bus, int p_effect, int p_by_effect);
diff --git a/servers/physics/body_sw.cpp b/servers/physics/body_sw.cpp
index f0fbbafe1c..b4c3670a7b 100644
--- a/servers/physics/body_sw.cpp
+++ b/servers/physics/body_sw.cpp
@@ -196,7 +196,8 @@ void BodySW::set_param(PhysicsServer::BodyParameter p_param, real_t p_value) {
angular_damp = p_value;
} break;
- default: {}
+ default: {
+ }
}
}
@@ -226,7 +227,8 @@ real_t BodySW::get_param(PhysicsServer::BodyParameter p_param) const {
return angular_damp;
} break;
- default: {}
+ default: {
+ }
}
return 0;
@@ -474,7 +476,8 @@ void BodySW::integrate_forces(real_t p_step) {
_compute_area_gravity_and_dampenings(aa[i].area);
stopped = mode == PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE;
} break;
- default: {}
+ default: {
+ }
}
}
}
diff --git a/servers/physics_2d/body_2d_sw.cpp b/servers/physics_2d/body_2d_sw.cpp
index 60bcb2e28e..60bbcef4b6 100644
--- a/servers/physics_2d/body_2d_sw.cpp
+++ b/servers/physics_2d/body_2d_sw.cpp
@@ -174,7 +174,8 @@ void Body2DSW::set_param(Physics2DServer::BodyParameter p_param, real_t p_value)
angular_damp = p_value;
} break;
- default: {}
+ default: {
+ }
}
}
@@ -206,7 +207,8 @@ real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const {
return angular_damp;
} break;
- default: {}
+ default: {
+ }
}
return 0;
@@ -443,7 +445,8 @@ void Body2DSW::integrate_forces(real_t p_step) {
_compute_area_gravity_and_dampenings(aa[i].area);
stopped = mode == Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE;
} break;
- default: {}
+ default: {
+ }
}
}
}
diff --git a/servers/register_server_types.cpp b/servers/register_server_types.cpp
index 0cc1cc119c..f3394019f5 100644
--- a/servers/register_server_types.cpp
+++ b/servers/register_server_types.cpp
@@ -50,7 +50,9 @@
#include "audio/effects/audio_effect_pitch_shift.h"
#include "audio/effects/audio_effect_record.h"
#include "audio/effects/audio_effect_reverb.h"
+#include "audio/effects/audio_effect_spectrum_analyzer.h"
#include "audio/effects/audio_effect_stereo_enhance.h"
+#include "audio/effects/audio_stream_generator.h"
#include "audio_server.h"
#include "core/script_debugger_remote.h"
#include "physics/physics_server_sw.h"
@@ -120,13 +122,18 @@ void register_server_types() {
ClassDB::register_virtual_class<AudioStream>();
ClassDB::register_virtual_class<AudioStreamPlayback>();
+ ClassDB::register_virtual_class<AudioStreamPlaybackResampled>();
ClassDB::register_class<AudioStreamMicrophone>();
ClassDB::register_class<AudioStreamRandomPitch>();
ClassDB::register_virtual_class<AudioEffect>();
+ ClassDB::register_virtual_class<AudioEffectInstance>();
ClassDB::register_class<AudioEffectEQ>();
ClassDB::register_class<AudioEffectFilter>();
ClassDB::register_class<AudioBusLayout>();
+ ClassDB::register_class<AudioStreamGenerator>();
+ ClassDB::register_virtual_class<AudioStreamGeneratorPlayback>();
+
{
//audio effects
ClassDB::register_class<AudioEffectAmplify>();
@@ -156,7 +163,10 @@ void register_server_types() {
ClassDB::register_class<AudioEffectLimiter>();
ClassDB::register_class<AudioEffectPitchShift>();
ClassDB::register_class<AudioEffectPhaser>();
+
ClassDB::register_class<AudioEffectRecord>();
+ ClassDB::register_class<AudioEffectSpectrumAnalyzer>();
+ ClassDB::register_virtual_class<AudioEffectSpectrumAnalyzerInstance>();
}
ClassDB::register_virtual_class<Physics2DDirectBodyState>();
diff --git a/servers/visual/shader_language.cpp b/servers/visual/shader_language.cpp
index 1f9d263354..33714a79b2 100644
--- a/servers/visual/shader_language.cpp
+++ b/servers/visual/shader_language.cpp
@@ -3620,7 +3620,8 @@ ShaderLanguage::Node *ShaderLanguage::_reduce_expression(BlockNode *p_block, Sha
case TYPE_FLOAT: {
nv.real = -cn->values[i].real;
} break;
- default: {}
+ default: {
+ }
}
values.push_back(nv);
@@ -4822,7 +4823,8 @@ Error ShaderLanguage::complete(const String &p_code, const Map<StringName, Funct
case TYPE_MAT2: limit = 2; break;
case TYPE_MAT3: limit = 3; break;
case TYPE_MAT4: limit = 4; break;
- default: {}
+ default: {
+ }
}
for (int i = 0; i < limit; i++) {
diff --git a/servers/visual/visual_server_canvas.cpp b/servers/visual/visual_server_canvas.cpp
index 4adf53c183..15f37dd6d1 100644
--- a/servers/visual/visual_server_canvas.cpp
+++ b/servers/visual/visual_server_canvas.cpp
@@ -55,16 +55,18 @@ void _collect_ysort_children(VisualServerCanvas::Item *p_canvas_item, Transform2
int child_item_count = p_canvas_item->child_items.size();
VisualServerCanvas::Item **child_items = p_canvas_item->child_items.ptrw();
for (int i = 0; i < child_item_count; i++) {
- if (r_items) {
- r_items[r_index] = child_items[i];
- child_items[i]->ysort_xform = p_transform;
- child_items[i]->ysort_pos = p_transform.xform(child_items[i]->xform.elements[2]);
- }
+ if (child_items[i]->visible) {
+ if (r_items) {
+ r_items[r_index] = child_items[i];
+ child_items[i]->ysort_xform = p_transform;
+ child_items[i]->ysort_pos = p_transform.xform(child_items[i]->xform.elements[2]);
+ }
- r_index++;
+ r_index++;
- if (child_items[i]->sort_y)
- _collect_ysort_children(child_items[i], p_transform * child_items[i]->xform, r_items, r_index);
+ if (child_items[i]->sort_y)
+ _collect_ysort_children(child_items[i], p_transform * child_items[i]->xform, r_items, r_index);
+ }
}
}
@@ -393,6 +395,10 @@ void VisualServerCanvas::canvas_item_set_visible(RID p_item, bool p_visible) {
ERR_FAIL_COND(!canvas_item);
canvas_item->visible = p_visible;
+
+ if (canvas_item->parent.is_valid() && canvas_item_owner.owns(canvas_item->parent)) {
+ _mark_ysort_dirty(canvas_item_owner.get(canvas_item->parent), canvas_item_owner);
+ }
}
void VisualServerCanvas::canvas_item_set_light_mask(RID p_item, int p_mask) {
diff --git a/servers/visual/visual_server_scene.cpp b/servers/visual/visual_server_scene.cpp
index 2590e29aef..a5858ab661 100644
--- a/servers/visual/visual_server_scene.cpp
+++ b/servers/visual/visual_server_scene.cpp
@@ -399,7 +399,8 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base) {
VSG::scene_render->free(gi_probe->probe_instance);
} break;
- default: {}
+ default: {
+ }
}
if (instance->base_data) {
@@ -476,7 +477,8 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base) {
gi_probe->probe_instance = VSG::scene_render->gi_probe_instance_create();
} break;
- default: {}
+ default: {
+ }
}
VSG::storage->instance_add_dependency(p_base, instance);
@@ -524,7 +526,8 @@ void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {
gi_probe_update_list.remove(&gi_probe->update_element);
}
} break;
- default: {}
+ default: {
+ }
}
instance->scenario = NULL;
@@ -556,7 +559,8 @@ void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {
gi_probe_update_list.add(&gi_probe->update_element);
}
} break;
- default: {}
+ default: {
+ }
}
_instance_queue_update(instance, true, true);
@@ -671,7 +675,8 @@ void VisualServerScene::instance_set_visible(RID p_instance, bool p_visible) {
}
} break;
- default: {}
+ default: {
+ }
}
}
inline bool is_geometry_instance(VisualServer::InstanceType p_type) {
@@ -848,7 +853,8 @@ void VisualServerScene::instance_geometry_set_flag(RID p_instance, VS::InstanceF
instance->redraw_if_visible = p_enabled;
} break;
- default: {}
+ default: {
+ }
}
}
void VisualServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting) {
@@ -1040,7 +1046,8 @@ void VisualServerScene::_update_instance_aabb(Instance *p_instance) {
new_aabb = VSG::storage->lightmap_capture_get_bounds(p_instance->base);
} break;
- default: {}
+ default: {
+ }
}
// <Zylann> This is why I didn't re-use Instance::aabb to implement custom AABBs
diff --git a/servers/visual/visual_server_viewport.cpp b/servers/visual/visual_server_viewport.cpp
index 9ad3e4a308..e7f60c2c1f 100644
--- a/servers/visual/visual_server_viewport.cpp
+++ b/servers/visual/visual_server_viewport.cpp
@@ -295,8 +295,8 @@ void VisualServerViewport::draw_viewports() {
if (vp->use_arvr && arvr_interface.is_valid()) {
// override our size, make sure it matches our required size
- Size2 size = arvr_interface->get_render_targetsize();
- VSG::storage->render_target_set_size(vp->render_target, size.x, size.y);
+ vp->size = arvr_interface->get_render_targetsize();
+ VSG::storage->render_target_set_size(vp->render_target, vp->size.x, vp->size.y);
// render mono or left eye first
ARVRInterface::Eyes leftOrMono = arvr_interface->is_stereo() ? ARVRInterface::EYE_LEFT : ARVRInterface::EYE_MONO;
diff --git a/thirdparty/README.md b/thirdparty/README.md
index 7f9fc28b3e..6997a9ba96 100644
--- a/thirdparty/README.md
+++ b/thirdparty/README.md
@@ -1,5 +1,6 @@
# Third party libraries
+
## assimp
- Upstream: http://github.com/assimp/assimp
@@ -294,8 +295,12 @@ Godot build configurations, check them out when updating.
File extracted from upstream release tarball `mbedtls-2.16.0-apache.tgz`:
- All `*.h` from `include/mbedtls/` to `thirdparty/mbedtls/include/mbedtls/`
- All `*.c` from `library/` to `thirdparty/mbedtls/library/`
-- Applied the patch in `thirdparty/mbedtls/1453.diff` (PR 1453). Soon to be merged upstream. Check it out at next update.
-- Applied the patch in `thirdparty/mbedtls/padlock.diff`. This disables VIA padlock support which defines a symbol `unsupported` which clashses with a symbol in libwebsockets.
+- Applied the patch in `thirdparty/mbedtls/1453.diff` (PR 1453).
+ Soon to be merged upstream. Check it out at next update.
+- Applied the patch in `thirdparty/mbedtls/padlock.diff`. This disables VIA
+ padlock support which defines a symbol `unsupported` which clashes with
+ a symbol in libwebsockets.
+
## miniupnpc
@@ -523,6 +528,23 @@ Files extracted from upstream source:
- `tinyexr.{cc,h}`
+## vhacd
+
+- Upstream: https://github.com/kmammou/v-hacd
+- Version: git (2297aa1, 2018)
+- License: BSD-3-Clause
+
+Files extracted from upstream source:
+
+- From `src/VHACD_Lib/`: `inc`, `public` and `src`
+- `LICENSE`
+
+Some downstream changes have been made and are identified by
+`// -- GODOT start --` and `// -- GODOT end --` comments.
+They can be reapplied using the patches included in the `vhacd`
+folder.
+
+
## zlib
- Upstream: http://www.zlib.net
diff --git a/thirdparty/vhacd/0001-bullet-namespace.patch b/thirdparty/vhacd/0001-bullet-namespace.patch
new file mode 100644
index 0000000000..cfb1ffeff0
--- /dev/null
+++ b/thirdparty/vhacd/0001-bullet-namespace.patch
@@ -0,0 +1,213 @@
+diff --git a/thirdparty/vhacd/inc/btAlignedAllocator.h b/thirdparty/vhacd/inc/btAlignedAllocator.h
+index 11f6e12dc..94e71d512 100644
+--- a/thirdparty/vhacd/inc/btAlignedAllocator.h
++++ b/thirdparty/vhacd/inc/btAlignedAllocator.h
+@@ -21,6 +21,11 @@ subject to the following restrictions:
+ ///that is better portable and more predictable
+
+ #include "btScalar.h"
++
++// -- GODOT start --
++namespace VHACD {
++// -- GODOT end --
++
+ //#define BT_DEBUG_MEMORY_ALLOCATIONS 1
+ #ifdef BT_DEBUG_MEMORY_ALLOCATIONS
+
+@@ -101,4 +106,8 @@ public:
+ friend bool operator==(const self_type&, const self_type&) { return true; }
+ };
+
++// -- GODOT start --
++}; // namespace VHACD
++// -- GODOT end --
++
+ #endif //BT_ALIGNED_ALLOCATOR
+diff --git a/thirdparty/vhacd/inc/btAlignedObjectArray.h b/thirdparty/vhacd/inc/btAlignedObjectArray.h
+index e6620adf6..1ce03d21b 100644
+--- a/thirdparty/vhacd/inc/btAlignedObjectArray.h
++++ b/thirdparty/vhacd/inc/btAlignedObjectArray.h
+@@ -38,6 +38,10 @@ subject to the following restrictions:
+ #include <new> //for placement new
+ #endif //BT_USE_PLACEMENT_NEW
+
++// -- GODOT start --
++namespace VHACD {
++// -- GODOT end --
++
+ ///The btAlignedObjectArray template class uses a subset of the stl::vector interface for its methods
+ ///It is developed to replace stl::vector to avoid portability issues, including STL alignment issues to add SIMD/SSE data
+ template <typename T>
+@@ -445,4 +449,8 @@ public:
+ }
+ };
+
++// -- GODOT start --
++}; // namespace VHACD
++// -- GODOT end --
++
+ #endif //BT_OBJECT_ARRAY__
+diff --git a/thirdparty/vhacd/inc/btConvexHullComputer.h b/thirdparty/vhacd/inc/btConvexHullComputer.h
+index 3c5075c2c..04bb96f64 100644
+--- a/thirdparty/vhacd/inc/btConvexHullComputer.h
++++ b/thirdparty/vhacd/inc/btConvexHullComputer.h
+@@ -18,6 +18,10 @@ subject to the following restrictions:
+ #include "btAlignedObjectArray.h"
+ #include "btVector3.h"
+
++// -- GODOT start --
++namespace VHACD {
++// -- GODOT end --
++
+ /// Convex hull implementation based on Preparata and Hong
+ /// See http://code.google.com/p/bullet/issues/detail?id=275
+ /// Ole Kniemeyer, MAXON Computer GmbH
+@@ -94,4 +98,8 @@ public:
+ }
+ };
+
++// -- GODOT start --
++}; // namespace VHACD
++// -- GODOT end --
++
+ #endif //BT_CONVEX_HULL_COMPUTER_H
+diff --git a/thirdparty/vhacd/inc/btMinMax.h b/thirdparty/vhacd/inc/btMinMax.h
+index 40b0ceb6e..9bc1e1c77 100644
+--- a/thirdparty/vhacd/inc/btMinMax.h
++++ b/thirdparty/vhacd/inc/btMinMax.h
+@@ -17,6 +17,10 @@ subject to the following restrictions:
+
+ #include "btScalar.h"
+
++// -- GODOT start --
++namespace VHACD {
++// -- GODOT end --
++
+ template <class T>
+ SIMD_FORCE_INLINE const T& btMin(const T& a, const T& b)
+ {
+@@ -62,4 +66,8 @@ SIMD_FORCE_INLINE void btClamp(T& a, const T& lb, const T& ub)
+ }
+ }
+
++// -- GODOT start --
++}; // namespace VHACD
++// -- GODOT end --
++
+ #endif //BT_GEN_MINMAX_H
+diff --git a/thirdparty/vhacd/inc/btScalar.h b/thirdparty/vhacd/inc/btScalar.h
+index b814474bd..617fd7c44 100644
+--- a/thirdparty/vhacd/inc/btScalar.h
++++ b/thirdparty/vhacd/inc/btScalar.h
+@@ -28,11 +28,19 @@ subject to the following restrictions:
+ /* SVN $Revision$ on $Date$ from http://bullet.googlecode.com*/
+ #define BT_BULLET_VERSION 279
+
++// -- GODOT start --
++namespace VHACD {
++// -- GODOT end --
++
+ inline int32_t btGetVersion()
+ {
+ return BT_BULLET_VERSION;
+ }
+
++// -- GODOT start --
++}; // namespace VHACD
++// -- GODOT end --
++
+ #if defined(DEBUG) || defined(_DEBUG)
+ #define BT_DEBUG
+ #endif
+@@ -199,6 +207,10 @@ inline int32_t btGetVersion()
+ #endif //__CELLOS_LV2__
+ #endif
+
++// -- GODOT start --
++namespace VHACD {
++// -- GODOT end --
++
+ ///The btScalar type abstracts floating point numbers, to easily switch between double and single floating point precision.
+ #if defined(BT_USE_DOUBLE_PRECISION)
+ typedef double btScalar;
+@@ -530,4 +542,9 @@ struct btTypedObject {
+ return m_objectType;
+ }
+ };
++
++// -- GODOT start --
++}; // namespace VHACD
++// -- GODOT end --
++
+ #endif //BT_SCALAR_H
+diff --git a/thirdparty/vhacd/inc/btVector3.h b/thirdparty/vhacd/inc/btVector3.h
+index 0f2fefbbd..4ed971673 100644
+--- a/thirdparty/vhacd/inc/btVector3.h
++++ b/thirdparty/vhacd/inc/btVector3.h
+@@ -26,6 +26,10 @@ subject to the following restrictions:
+ #define btVector3DataName "btVector3FloatData"
+ #endif //BT_USE_DOUBLE_PRECISION
+
++// -- GODOT start --
++namespace VHACD {
++// -- GODOT end --
++
+ /**@brief btVector3 can be used to represent 3D points and vectors.
+ * It has an un-used w component to suit 16-byte alignment when btVector3 is stored in containers. This extra component can be used by derived classes (Quaternion?) or by user
+ * Ideally, this class should be replaced by a platform optimized SIMD version that keeps the data in registers
+@@ -712,4 +716,8 @@ SIMD_FORCE_INLINE void btVector3::deSerialize(const struct btVector3Data& dataIn
+ m_floats[i] = dataIn.m_floats[i];
+ }
+
++// -- GODOT start --
++}; // namespace VHACD
++// -- GODOT end --
++
+ #endif //BT_VECTOR3_H
+diff --git a/thirdparty/vhacd/src/btAlignedAllocator.cpp b/thirdparty/vhacd/src/btAlignedAllocator.cpp
+index 11d594f6c..ce0e7f26f 100644
+--- a/thirdparty/vhacd/src/btAlignedAllocator.cpp
++++ b/thirdparty/vhacd/src/btAlignedAllocator.cpp
+@@ -15,6 +15,10 @@ subject to the following restrictions:
+
+ #include "btAlignedAllocator.h"
+
++// -- GODOT start --
++namespace VHACD {
++// -- GODOT end --
++
+ #ifdef _MSC_VER
+ #pragma warning(disable:4311 4302)
+ #endif
+@@ -177,4 +181,8 @@ void btAlignedFreeInternal(void* ptr)
+ sAlignedFreeFunc(ptr);
+ }
+
++// -- GODOT start --
++}; // namespace VHACD
++// -- GODOT end --
++
+ #endif //BT_DEBUG_MEMORY_ALLOCATIONS
+diff --git a/thirdparty/vhacd/src/btConvexHullComputer.cpp b/thirdparty/vhacd/src/btConvexHullComputer.cpp
+index d3d749adb..8ab34af2a 100644
+--- a/thirdparty/vhacd/src/btConvexHullComputer.cpp
++++ b/thirdparty/vhacd/src/btConvexHullComputer.cpp
+@@ -49,6 +49,10 @@ typedef unsigned long long int32_t uint64_t;
+ #include <stdio.h>
+ #endif
+
++// -- GODOT start --
++namespace VHACD {
++// -- GODOT end --
++
+ // Convex hull implementation based on Preparata and Hong
+ // Ole Kniemeyer, MAXON Computer GmbH
+ class btConvexHullInternal {
+@@ -2477,3 +2481,7 @@ btScalar btConvexHullComputer::compute(const void* coords, bool doubleCoords, in
+
+ return shift;
+ }
++
++// -- GODOT start --
++}; // namespace VHACD
++// -- GODOT end --
diff --git a/thirdparty/vhacd/0002-fpermissive-fix.patch b/thirdparty/vhacd/0002-fpermissive-fix.patch
new file mode 100644
index 0000000000..965df2944a
--- /dev/null
+++ b/thirdparty/vhacd/0002-fpermissive-fix.patch
@@ -0,0 +1,53 @@
+diff --git a/thirdparty/vhacd/inc/btScalar.h b/thirdparty/vhacd/inc/btScalar.h
+index 487205062..52297cd78 100644
+--- a/thirdparty/vhacd/inc/btScalar.h
++++ b/thirdparty/vhacd/inc/btScalar.h
+@@ -535,6 +535,29 @@ struct btTypedObject {
+ }
+ };
+
++// -- GODOT start --
++// Cherry-picked from Bullet 2.88 to fix GH-27926
++///align a pointer to the provided alignment, upwards
++template <typename T>
++T *btAlignPointer(T *unalignedPtr, size_t alignment)
++{
++ struct btConvertPointerSizeT
++ {
++ union {
++ T *ptr;
++ size_t integer;
++ };
++ };
++ btConvertPointerSizeT converter;
++
++ const size_t bit_mask = ~(alignment - 1);
++ converter.ptr = unalignedPtr;
++ converter.integer += alignment - 1;
++ converter.integer &= bit_mask;
++ return converter.ptr;
++}
++// -- GODOT end --
++
+ // -- GODOT start --
+ }; // namespace VHACD
+ // -- GODOT end --
+diff --git a/thirdparty/vhacd/src/btAlignedAllocator.cpp b/thirdparty/vhacd/src/btAlignedAllocator.cpp
+index ce0e7f26f..8dee31e7e 100644
+--- a/thirdparty/vhacd/src/btAlignedAllocator.cpp
++++ b/thirdparty/vhacd/src/btAlignedAllocator.cpp
+@@ -72,8 +72,12 @@ static inline void* btAlignedAllocDefault(size_t size, int32_t alignment)
+
+ real = (char*)sAllocFunc(size + sizeof(void*) + (alignment - 1));
+ if (real) {
+- offset = (alignment - (unsigned long)(real + sizeof(void*))) & (alignment - 1);
+- ret = (void*)((real + sizeof(void*)) + offset);
++ // -- GODOT start --
++ // Synced with Bullet 2.88 to fix GH-27926
++ //offset = (alignment - (unsigned long)(real + sizeof(void*))) & (alignment - 1);
++ //ret = (void*)((real + sizeof(void*)) + offset);
++ ret = btAlignPointer(real + sizeof(void *), alignment);
++ // -- GODOT end --
+ *((void**)(ret)-1) = (void*)(real);
+ }
+ else {
diff --git a/thirdparty/vhacd/LICENSE b/thirdparty/vhacd/LICENSE
new file mode 100644
index 0000000000..efc7f64399
--- /dev/null
+++ b/thirdparty/vhacd/LICENSE
@@ -0,0 +1,29 @@
+BSD 3-Clause License
+
+Copyright (c) 2011, Khaled Mamou (kmamou at gmail dot com)
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+2. 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.
+
+3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
diff --git a/thirdparty/vhacd/inc/FloatMath.h b/thirdparty/vhacd/inc/FloatMath.h
new file mode 100644
index 0000000000..37b07cb69f
--- /dev/null
+++ b/thirdparty/vhacd/inc/FloatMath.h
@@ -0,0 +1,525 @@
+#ifndef FLOAT_MATH_LIB_H
+
+#define FLOAT_MATH_LIB_H
+
+
+#include <float.h>
+#include <stdint.h>
+
+namespace FLOAT_MATH
+{
+
+enum FM_ClipState
+{
+ FMCS_XMIN = (1<<0),
+ FMCS_XMAX = (1<<1),
+ FMCS_YMIN = (1<<2),
+ FMCS_YMAX = (1<<3),
+ FMCS_ZMIN = (1<<4),
+ FMCS_ZMAX = (1<<5),
+};
+
+enum FM_Axis
+{
+ FM_XAXIS = (1<<0),
+ FM_YAXIS = (1<<1),
+ FM_ZAXIS = (1<<2)
+};
+
+enum LineSegmentType
+{
+ LS_START,
+ LS_MIDDLE,
+ LS_END
+};
+
+
+const float FM_PI = 3.1415926535897932384626433832795028841971693993751f;
+const float FM_DEG_TO_RAD = ((2.0f * FM_PI) / 360.0f);
+const float FM_RAD_TO_DEG = (360.0f / (2.0f * FM_PI));
+
+//***************** Float versions
+//***
+//*** vectors are assumed to be 3 floats or 3 doubles representing X, Y, Z
+//*** quaternions are assumed to be 4 floats or 4 doubles representing X,Y,Z,W
+//*** matrices are assumed to be 16 floats or 16 doubles representing a standard D3D or OpenGL style 4x4 matrix
+//*** bounding volumes are expressed as two sets of 3 floats/double representing bmin(x,y,z) and bmax(x,y,z)
+//*** Plane equations are assumed to be 4 floats or 4 doubles representing Ax,By,Cz,D
+
+FM_Axis fm_getDominantAxis(const float normal[3]);
+FM_Axis fm_getDominantAxis(const double normal[3]);
+
+void fm_decomposeTransform(const float local_transform[16],float trans[3],float rot[4],float scale[3]);
+void fm_decomposeTransform(const double local_transform[16],double trans[3],double rot[4],double scale[3]);
+
+void fm_multiplyTransform(const float *pA,const float *pB,float *pM);
+void fm_multiplyTransform(const double *pA,const double *pB,double *pM);
+
+void fm_inverseTransform(const float matrix[16],float inverse_matrix[16]);
+void fm_inverseTransform(const double matrix[16],double inverse_matrix[16]);
+
+void fm_identity(float matrix[16]); // set 4x4 matrix to identity.
+void fm_identity(double matrix[16]); // set 4x4 matrix to identity.
+
+void fm_inverseRT(const float matrix[16], const float pos[3], float t[3]); // inverse rotate translate the point.
+void fm_inverseRT(const double matrix[16],const double pos[3],double t[3]); // inverse rotate translate the point.
+
+void fm_transform(const float matrix[16], const float pos[3], float t[3]); // rotate and translate this point.
+void fm_transform(const double matrix[16],const double pos[3],double t[3]); // rotate and translate this point.
+
+float fm_getDeterminant(const float matrix[16]);
+double fm_getDeterminant(const double matrix[16]);
+
+void fm_getSubMatrix(int32_t ki,int32_t kj,float pDst[16],const float matrix[16]);
+void fm_getSubMatrix(int32_t ki,int32_t kj,double pDst[16],const float matrix[16]);
+
+void fm_rotate(const float matrix[16],const float pos[3],float t[3]); // only rotate the point by a 4x4 matrix, don't translate.
+void fm_rotate(const double matri[16],const double pos[3],double t[3]); // only rotate the point by a 4x4 matrix, don't translate.
+
+void fm_eulerToMatrix(float ax,float ay,float az,float matrix[16]); // convert euler (in radians) to a dest 4x4 matrix (translation set to zero)
+void fm_eulerToMatrix(double ax,double ay,double az,double matrix[16]); // convert euler (in radians) to a dest 4x4 matrix (translation set to zero)
+
+void fm_getAABB(uint32_t vcount,const float *points,uint32_t pstride,float bmin[3],float bmax[3]);
+void fm_getAABB(uint32_t vcount,const double *points,uint32_t pstride,double bmin[3],double bmax[3]);
+
+void fm_getAABBCenter(const float bmin[3],const float bmax[3],float center[3]);
+void fm_getAABBCenter(const double bmin[3],const double bmax[3],double center[3]);
+
+void fm_transformAABB(const float bmin[3],const float bmax[3],const float matrix[16],float tbmin[3],float tbmax[3]);
+void fm_transformAABB(const double bmin[3],const double bmax[3],const double matrix[16],double tbmin[3],double tbmax[3]);
+
+void fm_eulerToQuat(float x,float y,float z,float quat[4]); // convert euler angles to quaternion.
+void fm_eulerToQuat(double x,double y,double z,double quat[4]); // convert euler angles to quaternion.
+
+void fm_quatToEuler(const float quat[4],float &ax,float &ay,float &az);
+void fm_quatToEuler(const double quat[4],double &ax,double &ay,double &az);
+
+void fm_eulerToQuat(const float euler[3],float quat[4]); // convert euler angles to quaternion. Angles must be radians not degrees!
+void fm_eulerToQuat(const double euler[3],double quat[4]); // convert euler angles to quaternion.
+
+void fm_scale(float x,float y,float z,float matrix[16]); // apply scale to the matrix.
+void fm_scale(double x,double y,double z,double matrix[16]); // apply scale to the matrix.
+
+void fm_eulerToQuatDX(float x,float y,float z,float quat[4]); // convert euler angles to quaternion using the fucked up DirectX method
+void fm_eulerToQuatDX(double x,double y,double z,double quat[4]); // convert euler angles to quaternion using the fucked up DirectX method
+
+void fm_eulerToMatrixDX(float x,float y,float z,float matrix[16]); // convert euler angles to quaternion using the fucked up DirectX method.
+void fm_eulerToMatrixDX(double x,double y,double z,double matrix[16]); // convert euler angles to quaternion using the fucked up DirectX method.
+
+void fm_quatToMatrix(const float quat[4],float matrix[16]); // convert quaterinion rotation to matrix, translation set to zero.
+void fm_quatToMatrix(const double quat[4],double matrix[16]); // convert quaterinion rotation to matrix, translation set to zero.
+
+void fm_quatRotate(const float quat[4],const float v[3],float r[3]); // rotate a vector directly by a quaternion.
+void fm_quatRotate(const double quat[4],const double v[3],double r[3]); // rotate a vector directly by a quaternion.
+
+void fm_getTranslation(const float matrix[16],float t[3]);
+void fm_getTranslation(const double matrix[16],double t[3]);
+
+void fm_setTranslation(const float *translation,float matrix[16]);
+void fm_setTranslation(const double *translation,double matrix[16]);
+
+void fm_multiplyQuat(const float *qa,const float *qb,float *quat);
+void fm_multiplyQuat(const double *qa,const double *qb,double *quat);
+
+void fm_matrixToQuat(const float matrix[16],float quat[4]); // convert the 3x3 portion of a 4x4 matrix into a quaterion as x,y,z,w
+void fm_matrixToQuat(const double matrix[16],double quat[4]); // convert the 3x3 portion of a 4x4 matrix into a quaterion as x,y,z,w
+
+float fm_sphereVolume(float radius); // return's the volume of a sphere of this radius (4/3 PI * R cubed )
+double fm_sphereVolume(double radius); // return's the volume of a sphere of this radius (4/3 PI * R cubed )
+
+float fm_cylinderVolume(float radius,float h);
+double fm_cylinderVolume(double radius,double h);
+
+float fm_capsuleVolume(float radius,float h);
+double fm_capsuleVolume(double radius,double h);
+
+float fm_distance(const float p1[3],const float p2[3]);
+double fm_distance(const double p1[3],const double p2[3]);
+
+float fm_distanceSquared(const float p1[3],const float p2[3]);
+double fm_distanceSquared(const double p1[3],const double p2[3]);
+
+float fm_distanceSquaredXZ(const float p1[3],const float p2[3]);
+double fm_distanceSquaredXZ(const double p1[3],const double p2[3]);
+
+float fm_computePlane(const float p1[3],const float p2[3],const float p3[3],float *n); // return D
+double fm_computePlane(const double p1[3],const double p2[3],const double p3[3],double *n); // return D
+
+float fm_distToPlane(const float plane[4],const float pos[3]); // computes the distance of this point from the plane.
+double fm_distToPlane(const double plane[4],const double pos[3]); // computes the distance of this point from the plane.
+
+float fm_dot(const float p1[3],const float p2[3]);
+double fm_dot(const double p1[3],const double p2[3]);
+
+void fm_cross(float cross[3],const float a[3],const float b[3]);
+void fm_cross(double cross[3],const double a[3],const double b[3]);
+
+float fm_computeNormalVector(float n[3],const float p1[3],const float p2[3]); // as P2-P1 normalized.
+double fm_computeNormalVector(double n[3],const double p1[3],const double p2[3]); // as P2-P1 normalized.
+
+bool fm_computeWindingOrder(const float p1[3],const float p2[3],const float p3[3]); // returns true if the triangle is clockwise.
+bool fm_computeWindingOrder(const double p1[3],const double p2[3],const double p3[3]); // returns true if the triangle is clockwise.
+
+float fm_normalize(float n[3]); // normalize this vector and return the distance
+double fm_normalize(double n[3]); // normalize this vector and return the distance
+
+float fm_normalizeQuat(float n[4]); // normalize this quat
+double fm_normalizeQuat(double n[4]); // normalize this quat
+
+void fm_matrixMultiply(const float A[16],const float B[16],float dest[16]);
+void fm_matrixMultiply(const double A[16],const double B[16],double dest[16]);
+
+void fm_composeTransform(const float position[3],const float quat[4],const float scale[3],float matrix[16]);
+void fm_composeTransform(const double position[3],const double quat[4],const double scale[3],double matrix[16]);
+
+float fm_computeArea(const float p1[3],const float p2[3],const float p3[3]);
+double fm_computeArea(const double p1[3],const double p2[3],const double p3[3]);
+
+void fm_lerp(const float p1[3],const float p2[3],float dest[3],float lerpValue);
+void fm_lerp(const double p1[3],const double p2[3],double dest[3],double lerpValue);
+
+bool fm_insideTriangleXZ(const float test[3],const float p1[3],const float p2[3],const float p3[3]);
+bool fm_insideTriangleXZ(const double test[3],const double p1[3],const double p2[3],const double p3[3]);
+
+bool fm_insideAABB(const float pos[3],const float bmin[3],const float bmax[3]);
+bool fm_insideAABB(const double pos[3],const double bmin[3],const double bmax[3]);
+
+bool fm_insideAABB(const float obmin[3],const float obmax[3],const float tbmin[3],const float tbmax[3]); // test if bounding box tbmin/tmbax is fully inside obmin/obmax
+bool fm_insideAABB(const double obmin[3],const double obmax[3],const double tbmin[3],const double tbmax[3]); // test if bounding box tbmin/tmbax is fully inside obmin/obmax
+
+uint32_t fm_clipTestPoint(const float bmin[3],const float bmax[3],const float pos[3]);
+uint32_t fm_clipTestPoint(const double bmin[3],const double bmax[3],const double pos[3]);
+
+uint32_t fm_clipTestPointXZ(const float bmin[3],const float bmax[3],const float pos[3]); // only tests X and Z, not Y
+uint32_t fm_clipTestPointXZ(const double bmin[3],const double bmax[3],const double pos[3]); // only tests X and Z, not Y
+
+
+uint32_t fm_clipTestAABB(const float bmin[3],const float bmax[3],const float p1[3],const float p2[3],const float p3[3],uint32_t &andCode);
+uint32_t fm_clipTestAABB(const double bmin[3],const double bmax[3],const double p1[3],const double p2[3],const double p3[3],uint32_t &andCode);
+
+
+bool fm_lineTestAABBXZ(const float p1[3],const float p2[3],const float bmin[3],const float bmax[3],float &time);
+bool fm_lineTestAABBXZ(const double p1[3],const double p2[3],const double bmin[3],const double bmax[3],double &time);
+
+bool fm_lineTestAABB(const float p1[3],const float p2[3],const float bmin[3],const float bmax[3],float &time);
+bool fm_lineTestAABB(const double p1[3],const double p2[3],const double bmin[3],const double bmax[3],double &time);
+
+
+void fm_initMinMax(const float p[3],float bmin[3],float bmax[3]);
+void fm_initMinMax(const double p[3],double bmin[3],double bmax[3]);
+
+void fm_initMinMax(float bmin[3],float bmax[3]);
+void fm_initMinMax(double bmin[3],double bmax[3]);
+
+void fm_minmax(const float p[3],float bmin[3],float bmax[3]); // accumulate to a min-max value
+void fm_minmax(const double p[3],double bmin[3],double bmax[3]); // accumulate to a min-max value
+
+// Computes the diagonal length of the bounding box and then inflates the bounding box on all sides
+// by the ratio provided.
+void fm_inflateMinMax(float bmin[3], float bmax[3], float ratio);
+void fm_inflateMinMax(double bmin[3], double bmax[3], double ratio);
+
+float fm_solveX(const float plane[4],float y,float z); // solve for X given this plane equation and the other two components.
+double fm_solveX(const double plane[4],double y,double z); // solve for X given this plane equation and the other two components.
+
+float fm_solveY(const float plane[4],float x,float z); // solve for Y given this plane equation and the other two components.
+double fm_solveY(const double plane[4],double x,double z); // solve for Y given this plane equation and the other two components.
+
+float fm_solveZ(const float plane[4],float x,float y); // solve for Z given this plane equation and the other two components.
+double fm_solveZ(const double plane[4],double x,double y); // solve for Z given this plane equation and the other two components.
+
+bool fm_computeBestFitPlane(uint32_t vcount, // number of input data points
+ const float *points, // starting address of points array.
+ uint32_t vstride, // stride between input points.
+ const float *weights, // *optional point weighting values.
+ uint32_t wstride, // weight stride for each vertex.
+ float plane[4], // Best fit plane equation
+ float center[3]); // Best fit weighted center of input points
+
+bool fm_computeBestFitPlane(uint32_t vcount, // number of input data points
+ const double *points, // starting address of points array.
+ uint32_t vstride, // stride between input points.
+ const double *weights, // *optional point weighting values.
+ uint32_t wstride, // weight stride for each vertex.
+ double plane[4],
+ double center[3]);
+
+// Computes the average center of a set of data points
+bool fm_computeCentroid(uint32_t vcount, // number of input data points
+ const float *points, // starting address of points array.
+ float *center);
+
+bool fm_computeCentroid(uint32_t vcount, // number of input data points
+ const double *points, // starting address of points array.
+ double *center);
+
+// Compute centroid of a triangle mesh; takes area of each triangle into account
+// weighted average
+bool fm_computeCentroid(uint32_t vcount, // number of input data points
+ const float *points, // starting address of points array.
+ uint32_t triangleCount,
+ const uint32_t *indices,
+ float *center);
+
+// Compute centroid of a triangle mesh; takes area of each triangle into account
+// weighted average
+bool fm_computeCentroid(uint32_t vcount, // number of input data points
+ const double *points, // starting address of points array.
+ uint32_t triangleCount,
+ const uint32_t *indices,
+ double *center);
+
+
+float fm_computeBestFitAABB(uint32_t vcount,const float *points,uint32_t pstride,float bmin[3],float bmax[3]); // returns the diagonal distance
+double fm_computeBestFitAABB(uint32_t vcount,const double *points,uint32_t pstride,double bmin[3],double bmax[3]); // returns the diagonal distance
+
+float fm_computeBestFitSphere(uint32_t vcount,const float *points,uint32_t pstride,float center[3]);
+double fm_computeBestFitSphere(uint32_t vcount,const double *points,uint32_t pstride,double center[3]);
+
+bool fm_lineSphereIntersect(const float center[3],float radius,const float p1[3],const float p2[3],float intersect[3]);
+bool fm_lineSphereIntersect(const double center[3],double radius,const double p1[3],const double p2[3],double intersect[3]);
+
+bool fm_intersectRayAABB(const float bmin[3],const float bmax[3],const float pos[3],const float dir[3],float intersect[3]);
+bool fm_intersectLineSegmentAABB(const float bmin[3],const float bmax[3],const float p1[3],const float p2[3],float intersect[3]);
+
+bool fm_lineIntersectsTriangle(const float rayStart[3],const float rayEnd[3],const float p1[3],const float p2[3],const float p3[3],float sect[3]);
+bool fm_lineIntersectsTriangle(const double rayStart[3],const double rayEnd[3],const double p1[3],const double p2[3],const double p3[3],double sect[3]);
+
+bool fm_rayIntersectsTriangle(const float origin[3],const float dir[3],const float v0[3],const float v1[3],const float v2[3],float &t);
+bool fm_rayIntersectsTriangle(const double origin[3],const double dir[3],const double v0[3],const double v1[3],const double v2[3],double &t);
+
+bool fm_raySphereIntersect(const float center[3],float radius,const float pos[3],const float dir[3],float distance,float intersect[3]);
+bool fm_raySphereIntersect(const double center[3],double radius,const double pos[3],const double dir[3],double distance,double intersect[3]);
+
+void fm_catmullRom(float out_vector[3],const float p1[3],const float p2[3],const float p3[3],const float *p4, const float s);
+void fm_catmullRom(double out_vector[3],const double p1[3],const double p2[3],const double p3[3],const double *p4, const double s);
+
+bool fm_intersectAABB(const float bmin1[3],const float bmax1[3],const float bmin2[3],const float bmax2[3]);
+bool fm_intersectAABB(const double bmin1[3],const double bmax1[3],const double bmin2[3],const double bmax2[3]);
+
+
+// computes the rotation quaternion to go from unit-vector v0 to unit-vector v1
+void fm_rotationArc(const float v0[3],const float v1[3],float quat[4]);
+void fm_rotationArc(const double v0[3],const double v1[3],double quat[4]);
+
+float fm_distancePointLineSegment(const float Point[3],const float LineStart[3],const float LineEnd[3],float intersection[3],LineSegmentType &type,float epsilon);
+double fm_distancePointLineSegment(const double Point[3],const double LineStart[3],const double LineEnd[3],double intersection[3],LineSegmentType &type,double epsilon);
+
+
+bool fm_colinear(const double p1[3],const double p2[3],const double p3[3],double epsilon=0.999); // true if these three points in a row are co-linear
+bool fm_colinear(const float p1[3],const float p2[3],const float p3[3],float epsilon=0.999f);
+
+bool fm_colinear(const float a1[3],const float a2[3],const float b1[3],const float b2[3],float epsilon=0.999f); // true if these two line segments are co-linear.
+bool fm_colinear(const double a1[3],const double a2[3],const double b1[3],const double b2[3],double epsilon=0.999); // true if these two line segments are co-linear.
+
+enum IntersectResult
+{
+ IR_DONT_INTERSECT,
+ IR_DO_INTERSECT,
+ IR_COINCIDENT,
+ IR_PARALLEL,
+};
+
+IntersectResult fm_intersectLineSegments2d(const float a1[3], const float a2[3], const float b1[3], const float b2[3], float intersectionPoint[3]);
+IntersectResult fm_intersectLineSegments2d(const double a1[3],const double a2[3],const double b1[3],const double b2[3],double intersectionPoint[3]);
+
+IntersectResult fm_intersectLineSegments2dTime(const float a1[3], const float a2[3], const float b1[3], const float b2[3],float &t1,float &t2);
+IntersectResult fm_intersectLineSegments2dTime(const double a1[3],const double a2[3],const double b1[3],const double b2[3],double &t1,double &t2);
+
+// Plane-Triangle splitting
+
+enum PlaneTriResult
+{
+ PTR_ON_PLANE,
+ PTR_FRONT,
+ PTR_BACK,
+ PTR_SPLIT,
+};
+
+PlaneTriResult fm_planeTriIntersection(const float plane[4], // the plane equation in Ax+By+Cz+D format
+ const float *triangle, // the source triangle.
+ uint32_t tstride, // stride in bytes of the input and output *vertices*
+ float epsilon, // the co-planer epsilon value.
+ float *front, // the triangle in front of the
+ uint32_t &fcount, // number of vertices in the 'front' triangle
+ float *back, // the triangle in back of the plane
+ uint32_t &bcount); // the number of vertices in the 'back' triangle.
+
+
+PlaneTriResult fm_planeTriIntersection(const double plane[4], // the plane equation in Ax+By+Cz+D format
+ const double *triangle, // the source triangle.
+ uint32_t tstride, // stride in bytes of the input and output *vertices*
+ double epsilon, // the co-planer epsilon value.
+ double *front, // the triangle in front of the
+ uint32_t &fcount, // number of vertices in the 'front' triangle
+ double *back, // the triangle in back of the plane
+ uint32_t &bcount); // the number of vertices in the 'back' triangle.
+
+
+bool fm_intersectPointPlane(const float p1[3],const float p2[3],float *split,const float plane[4]);
+bool fm_intersectPointPlane(const double p1[3],const double p2[3],double *split,const double plane[4]);
+
+PlaneTriResult fm_getSidePlane(const float p[3],const float plane[4],float epsilon);
+PlaneTriResult fm_getSidePlane(const double p[3],const double plane[4],double epsilon);
+
+
+void fm_computeBestFitOBB(uint32_t vcount,const float *points,uint32_t pstride,float *sides,float matrix[16],bool bruteForce=true);
+void fm_computeBestFitOBB(uint32_t vcount,const double *points,uint32_t pstride,double *sides,double matrix[16],bool bruteForce=true);
+
+void fm_computeBestFitOBB(uint32_t vcount,const float *points,uint32_t pstride,float *sides,float pos[3],float quat[4],bool bruteForce=true);
+void fm_computeBestFitOBB(uint32_t vcount,const double *points,uint32_t pstride,double *sides,double pos[3],double quat[4],bool bruteForce=true);
+
+void fm_computeBestFitABB(uint32_t vcount,const float *points,uint32_t pstride,float *sides,float pos[3]);
+void fm_computeBestFitABB(uint32_t vcount,const double *points,uint32_t pstride,double *sides,double pos[3]);
+
+
+//** Note, if the returned capsule height is less than zero, then you must represent it is a sphere of size radius.
+void fm_computeBestFitCapsule(uint32_t vcount,const float *points,uint32_t pstride,float &radius,float &height,float matrix[16],bool bruteForce=true);
+void fm_computeBestFitCapsule(uint32_t vcount,const double *points,uint32_t pstride,float &radius,float &height,double matrix[16],bool bruteForce=true);
+
+
+void fm_planeToMatrix(const float plane[4],float matrix[16]); // convert a plane equation to a 4x4 rotation matrix. Reference vector is 0,1,0
+void fm_planeToQuat(const float plane[4],float quat[4],float pos[3]); // convert a plane equation to a quaternion and translation
+
+void fm_planeToMatrix(const double plane[4],double matrix[16]); // convert a plane equation to a 4x4 rotation matrix
+void fm_planeToQuat(const double plane[4],double quat[4],double pos[3]); // convert a plane equation to a quaternion and translation
+
+inline void fm_doubleToFloat3(const double p[3],float t[3]) { t[0] = (float) p[0]; t[1] = (float)p[1]; t[2] = (float)p[2]; };
+inline void fm_floatToDouble3(const float p[3],double t[3]) { t[0] = (double)p[0]; t[1] = (double)p[1]; t[2] = (double)p[2]; };
+
+
+void fm_eulerMatrix(float ax,float ay,float az,float matrix[16]); // convert euler (in radians) to a dest 4x4 matrix (translation set to zero)
+void fm_eulerMatrix(double ax,double ay,double az,double matrix[16]); // convert euler (in radians) to a dest 4x4 matrix (translation set to zero)
+
+
+float fm_computeMeshVolume(const float *vertices,uint32_t tcount,const uint32_t *indices);
+double fm_computeMeshVolume(const double *vertices,uint32_t tcount,const uint32_t *indices);
+
+
+#define FM_DEFAULT_GRANULARITY 0.001f // 1 millimeter is the default granularity
+
+class fm_VertexIndex
+{
+public:
+ virtual uint32_t getIndex(const float pos[3],bool &newPos) = 0; // get welded index for this float vector[3]
+ virtual uint32_t getIndex(const double pos[3],bool &newPos) = 0; // get welded index for this double vector[3]
+ virtual const float * getVerticesFloat(void) const = 0;
+ virtual const double * getVerticesDouble(void) const = 0;
+ virtual const float * getVertexFloat(uint32_t index) const = 0;
+ virtual const double * getVertexDouble(uint32_t index) const = 0;
+ virtual uint32_t getVcount(void) const = 0;
+ virtual bool isDouble(void) const = 0;
+ virtual bool saveAsObj(const char *fname,uint32_t tcount,uint32_t *indices) = 0;
+};
+
+fm_VertexIndex * fm_createVertexIndex(double granularity,bool snapToGrid); // create an indexed vertex system for doubles
+fm_VertexIndex * fm_createVertexIndex(float granularity,bool snapToGrid); // create an indexed vertext system for floats
+void fm_releaseVertexIndex(fm_VertexIndex *vindex);
+
+
+class fm_Triangulate
+{
+public:
+ virtual const double * triangulate3d(uint32_t pcount,
+ const double *points,
+ uint32_t vstride,
+ uint32_t &tcount,
+ bool consolidate,
+ double epsilon) = 0;
+
+ virtual const float * triangulate3d(uint32_t pcount,
+ const float *points,
+ uint32_t vstride,
+ uint32_t &tcount,
+ bool consolidate,
+ float epsilon) = 0;
+};
+
+fm_Triangulate * fm_createTriangulate(void);
+void fm_releaseTriangulate(fm_Triangulate *t);
+
+
+const float * fm_getPoint(const float *points,uint32_t pstride,uint32_t index);
+const double * fm_getPoint(const double *points,uint32_t pstride,uint32_t index);
+
+bool fm_insideTriangle(float Ax, float Ay,float Bx, float By,float Cx, float Cy,float Px, float Py);
+bool fm_insideTriangle(double Ax, double Ay,double Bx, double By,double Cx, double Cy,double Px, double Py);
+float fm_areaPolygon2d(uint32_t pcount,const float *points,uint32_t pstride);
+double fm_areaPolygon2d(uint32_t pcount,const double *points,uint32_t pstride);
+
+bool fm_pointInsidePolygon2d(uint32_t pcount,const float *points,uint32_t pstride,const float *point,uint32_t xindex=0,uint32_t yindex=1);
+bool fm_pointInsidePolygon2d(uint32_t pcount,const double *points,uint32_t pstride,const double *point,uint32_t xindex=0,uint32_t yindex=1);
+
+uint32_t fm_consolidatePolygon(uint32_t pcount,const float *points,uint32_t pstride,float *dest,float epsilon=0.999999f); // collapses co-linear edges.
+uint32_t fm_consolidatePolygon(uint32_t pcount,const double *points,uint32_t pstride,double *dest,double epsilon=0.999999); // collapses co-linear edges.
+
+
+bool fm_computeSplitPlane(uint32_t vcount,const double *vertices,uint32_t tcount,const uint32_t *indices,double *plane);
+bool fm_computeSplitPlane(uint32_t vcount,const float *vertices,uint32_t tcount,const uint32_t *indices,float *plane);
+
+void fm_nearestPointInTriangle(const float *pos,const float *p1,const float *p2,const float *p3,float *nearest);
+void fm_nearestPointInTriangle(const double *pos,const double *p1,const double *p2,const double *p3,double *nearest);
+
+float fm_areaTriangle(const float *p1,const float *p2,const float *p3);
+double fm_areaTriangle(const double *p1,const double *p2,const double *p3);
+
+void fm_subtract(const float *A,const float *B,float *diff); // compute A-B and store the result in 'diff'
+void fm_subtract(const double *A,const double *B,double *diff); // compute A-B and store the result in 'diff'
+
+void fm_multiply(float *A,float scaler);
+void fm_multiply(double *A,double scaler);
+
+void fm_add(const float *A,const float *B,float *sum);
+void fm_add(const double *A,const double *B,double *sum);
+
+void fm_copy3(const float *source,float *dest);
+void fm_copy3(const double *source,double *dest);
+
+// re-indexes an indexed triangle mesh but drops unused vertices. The output_indices can be the same pointer as the input indices.
+// the output_vertices can point to the input vertices if you desire. The output_vertices buffer should be at least the same size
+// is the input buffer. The routine returns the new vertex count after re-indexing.
+uint32_t fm_copyUniqueVertices(uint32_t vcount,const float *input_vertices,float *output_vertices,uint32_t tcount,const uint32_t *input_indices,uint32_t *output_indices);
+uint32_t fm_copyUniqueVertices(uint32_t vcount,const double *input_vertices,double *output_vertices,uint32_t tcount,const uint32_t *input_indices,uint32_t *output_indices);
+
+bool fm_isMeshCoplanar(uint32_t tcount,const uint32_t *indices,const float *vertices,bool doubleSided); // returns true if this collection of indexed triangles are co-planar!
+bool fm_isMeshCoplanar(uint32_t tcount,const uint32_t *indices,const double *vertices,bool doubleSided); // returns true if this collection of indexed triangles are co-planar!
+
+bool fm_samePlane(const float p1[4],const float p2[4],float normalEpsilon=0.01f,float dEpsilon=0.001f,bool doubleSided=false); // returns true if these two plane equations are identical within an epsilon
+bool fm_samePlane(const double p1[4],const double p2[4],double normalEpsilon=0.01,double dEpsilon=0.001,bool doubleSided=false);
+
+void fm_OBBtoAABB(const float obmin[3],const float obmax[3],const float matrix[16],float abmin[3],float abmax[3]);
+
+// a utility class that will tessellate a mesh.
+class fm_Tesselate
+{
+public:
+ virtual const uint32_t * tesselate(fm_VertexIndex *vindex,uint32_t tcount,const uint32_t *indices,float longEdge,uint32_t maxDepth,uint32_t &outcount) = 0;
+};
+
+fm_Tesselate * fm_createTesselate(void);
+void fm_releaseTesselate(fm_Tesselate *t);
+
+void fm_computeMeanNormals(uint32_t vcount, // the number of vertices
+ const float *vertices, // the base address of the vertex position data.
+ uint32_t vstride, // the stride between position data.
+ float *normals, // the base address of the destination for mean vector normals
+ uint32_t nstride, // the stride between normals
+ uint32_t tcount, // the number of triangles
+ const uint32_t *indices); // the triangle indices
+
+void fm_computeMeanNormals(uint32_t vcount, // the number of vertices
+ const double *vertices, // the base address of the vertex position data.
+ uint32_t vstride, // the stride between position data.
+ double *normals, // the base address of the destination for mean vector normals
+ uint32_t nstride, // the stride between normals
+ uint32_t tcount, // the number of triangles
+ const uint32_t *indices); // the triangle indices
+
+
+bool fm_isValidTriangle(const float *p1,const float *p2,const float *p3,float epsilon=0.00001f);
+bool fm_isValidTriangle(const double *p1,const double *p2,const double *p3,double epsilon=0.00001f);
+
+
+}; // end of namespace
+
+#endif
diff --git a/thirdparty/vhacd/inc/btAlignedAllocator.h b/thirdparty/vhacd/inc/btAlignedAllocator.h
new file mode 100644
index 0000000000..94e71d5125
--- /dev/null
+++ b/thirdparty/vhacd/inc/btAlignedAllocator.h
@@ -0,0 +1,113 @@
+/*
+Bullet Continuous Collision Detection and Physics Library
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
+
+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 BT_ALIGNED_ALLOCATOR
+#define BT_ALIGNED_ALLOCATOR
+
+///we probably replace this with our own aligned memory allocator
+///so we replace _aligned_malloc and _aligned_free with our own
+///that is better portable and more predictable
+
+#include "btScalar.h"
+
+// -- GODOT start --
+namespace VHACD {
+// -- GODOT end --
+
+//#define BT_DEBUG_MEMORY_ALLOCATIONS 1
+#ifdef BT_DEBUG_MEMORY_ALLOCATIONS
+
+#define btAlignedAlloc(a, b) \
+ btAlignedAllocInternal(a, b, __LINE__, __FILE__)
+
+#define btAlignedFree(ptr) \
+ btAlignedFreeInternal(ptr, __LINE__, __FILE__)
+
+void* btAlignedAllocInternal(size_t size, int32_t alignment, int32_t line, char* filename);
+
+void btAlignedFreeInternal(void* ptr, int32_t line, char* filename);
+
+#else
+void* btAlignedAllocInternal(size_t size, int32_t alignment);
+void btAlignedFreeInternal(void* ptr);
+
+#define btAlignedAlloc(size, alignment) btAlignedAllocInternal(size, alignment)
+#define btAlignedFree(ptr) btAlignedFreeInternal(ptr)
+
+#endif
+typedef int32_t size_type;
+
+typedef void*(btAlignedAllocFunc)(size_t size, int32_t alignment);
+typedef void(btAlignedFreeFunc)(void* memblock);
+typedef void*(btAllocFunc)(size_t size);
+typedef void(btFreeFunc)(void* memblock);
+
+///The developer can let all Bullet memory allocations go through a custom memory allocator, using btAlignedAllocSetCustom
+void btAlignedAllocSetCustom(btAllocFunc* allocFunc, btFreeFunc* freeFunc);
+///If the developer has already an custom aligned allocator, then btAlignedAllocSetCustomAligned can be used. The default aligned allocator pre-allocates extra memory using the non-aligned allocator, and instruments it.
+void btAlignedAllocSetCustomAligned(btAlignedAllocFunc* allocFunc, btAlignedFreeFunc* freeFunc);
+
+///The btAlignedAllocator is a portable class for aligned memory allocations.
+///Default implementations for unaligned and aligned allocations can be overridden by a custom allocator using btAlignedAllocSetCustom and btAlignedAllocSetCustomAligned.
+template <typename T, unsigned Alignment>
+class btAlignedAllocator {
+
+ typedef btAlignedAllocator<T, Alignment> self_type;
+
+public:
+ //just going down a list:
+ btAlignedAllocator() {}
+ /*
+ btAlignedAllocator( const self_type & ) {}
+ */
+
+ template <typename Other>
+ btAlignedAllocator(const btAlignedAllocator<Other, Alignment>&) {}
+
+ typedef const T* const_pointer;
+ typedef const T& const_reference;
+ typedef T* pointer;
+ typedef T& reference;
+ typedef T value_type;
+
+ pointer address(reference ref) const { return &ref; }
+ const_pointer address(const_reference ref) const { return &ref; }
+ pointer allocate(size_type n, const_pointer* hint = 0)
+ {
+ (void)hint;
+ return reinterpret_cast<pointer>(btAlignedAlloc(sizeof(value_type) * n, Alignment));
+ }
+ void construct(pointer ptr, const value_type& value) { new (ptr) value_type(value); }
+ void deallocate(pointer ptr)
+ {
+ btAlignedFree(reinterpret_cast<void*>(ptr));
+ }
+ void destroy(pointer ptr) { ptr->~value_type(); }
+
+ template <typename O>
+ struct rebind {
+ typedef btAlignedAllocator<O, Alignment> other;
+ };
+ template <typename O>
+ self_type& operator=(const btAlignedAllocator<O, Alignment>&) { return *this; }
+
+ friend bool operator==(const self_type&, const self_type&) { return true; }
+};
+
+// -- GODOT start --
+}; // namespace VHACD
+// -- GODOT end --
+
+#endif //BT_ALIGNED_ALLOCATOR
diff --git a/thirdparty/vhacd/inc/btAlignedObjectArray.h b/thirdparty/vhacd/inc/btAlignedObjectArray.h
new file mode 100644
index 0000000000..1ce03d21bc
--- /dev/null
+++ b/thirdparty/vhacd/inc/btAlignedObjectArray.h
@@ -0,0 +1,456 @@
+/*
+Bullet Continuous Collision Detection and Physics Library
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
+
+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 BT_OBJECT_ARRAY__
+#define BT_OBJECT_ARRAY__
+
+#include "btAlignedAllocator.h"
+#include "btScalar.h" // has definitions like SIMD_FORCE_INLINE
+
+///If the platform doesn't support placement new, you can disable BT_USE_PLACEMENT_NEW
+///then the btAlignedObjectArray doesn't support objects with virtual methods, and non-trivial constructors/destructors
+///You can enable BT_USE_MEMCPY, then swapping elements in the array will use memcpy instead of operator=
+///see discussion here: http://continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=1231 and
+///http://www.continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=1240
+
+#define BT_USE_PLACEMENT_NEW 1
+//#define BT_USE_MEMCPY 1 //disable, because it is cumbersome to find out for each platform where memcpy is defined. It can be in <memory.h> or <string.h> or otherwise...
+#define BT_ALLOW_ARRAY_COPY_OPERATOR // enabling this can accidently perform deep copies of data if you are not careful
+
+#ifdef BT_USE_MEMCPY
+#include <memory.h>
+#include <string.h>
+#endif //BT_USE_MEMCPY
+
+#ifdef BT_USE_PLACEMENT_NEW
+#include <new> //for placement new
+#endif //BT_USE_PLACEMENT_NEW
+
+// -- GODOT start --
+namespace VHACD {
+// -- GODOT end --
+
+///The btAlignedObjectArray template class uses a subset of the stl::vector interface for its methods
+///It is developed to replace stl::vector to avoid portability issues, including STL alignment issues to add SIMD/SSE data
+template <typename T>
+//template <class T>
+class btAlignedObjectArray {
+ btAlignedAllocator<T, 16> m_allocator;
+
+ int32_t m_size;
+ int32_t m_capacity;
+ T* m_data;
+ //PCK: added this line
+ bool m_ownsMemory;
+
+#ifdef BT_ALLOW_ARRAY_COPY_OPERATOR
+public:
+ SIMD_FORCE_INLINE btAlignedObjectArray<T>& operator=(const btAlignedObjectArray<T>& other)
+ {
+ copyFromArray(other);
+ return *this;
+ }
+#else //BT_ALLOW_ARRAY_COPY_OPERATOR
+private:
+ SIMD_FORCE_INLINE btAlignedObjectArray<T>& operator=(const btAlignedObjectArray<T>& other);
+#endif //BT_ALLOW_ARRAY_COPY_OPERATOR
+
+protected:
+ SIMD_FORCE_INLINE int32_t allocSize(int32_t size)
+ {
+ return (size ? size * 2 : 1);
+ }
+ SIMD_FORCE_INLINE void copy(int32_t start, int32_t end, T* dest) const
+ {
+ int32_t i;
+ for (i = start; i < end; ++i)
+#ifdef BT_USE_PLACEMENT_NEW
+ new (&dest[i]) T(m_data[i]);
+#else
+ dest[i] = m_data[i];
+#endif //BT_USE_PLACEMENT_NEW
+ }
+
+ SIMD_FORCE_INLINE void init()
+ {
+ //PCK: added this line
+ m_ownsMemory = true;
+ m_data = 0;
+ m_size = 0;
+ m_capacity = 0;
+ }
+ SIMD_FORCE_INLINE void destroy(int32_t first, int32_t last)
+ {
+ int32_t i;
+ for (i = first; i < last; i++) {
+ m_data[i].~T();
+ }
+ }
+
+ SIMD_FORCE_INLINE void* allocate(int32_t size)
+ {
+ if (size)
+ return m_allocator.allocate(size);
+ return 0;
+ }
+
+ SIMD_FORCE_INLINE void deallocate()
+ {
+ if (m_data) {
+ //PCK: enclosed the deallocation in this block
+ if (m_ownsMemory) {
+ m_allocator.deallocate(m_data);
+ }
+ m_data = 0;
+ }
+ }
+
+public:
+ btAlignedObjectArray()
+ {
+ init();
+ }
+
+ ~btAlignedObjectArray()
+ {
+ clear();
+ }
+
+ ///Generally it is best to avoid using the copy constructor of an btAlignedObjectArray, and use a (const) reference to the array instead.
+ btAlignedObjectArray(const btAlignedObjectArray& otherArray)
+ {
+ init();
+
+ int32_t otherSize = otherArray.size();
+ resize(otherSize);
+ otherArray.copy(0, otherSize, m_data);
+ }
+
+ /// return the number of elements in the array
+ SIMD_FORCE_INLINE int32_t size() const
+ {
+ return m_size;
+ }
+
+ SIMD_FORCE_INLINE const T& at(int32_t n) const
+ {
+ btAssert(n >= 0);
+ btAssert(n < size());
+ return m_data[n];
+ }
+
+ SIMD_FORCE_INLINE T& at(int32_t n)
+ {
+ btAssert(n >= 0);
+ btAssert(n < size());
+ return m_data[n];
+ }
+
+ SIMD_FORCE_INLINE const T& operator[](int32_t n) const
+ {
+ btAssert(n >= 0);
+ btAssert(n < size());
+ return m_data[n];
+ }
+
+ SIMD_FORCE_INLINE T& operator[](int32_t n)
+ {
+ btAssert(n >= 0);
+ btAssert(n < size());
+ return m_data[n];
+ }
+
+ ///clear the array, deallocated memory. Generally it is better to use array.resize(0), to reduce performance overhead of run-time memory (de)allocations.
+ SIMD_FORCE_INLINE void clear()
+ {
+ destroy(0, size());
+
+ deallocate();
+
+ init();
+ }
+
+ SIMD_FORCE_INLINE void pop_back()
+ {
+ btAssert(m_size > 0);
+ m_size--;
+ m_data[m_size].~T();
+ }
+
+ ///resize changes the number of elements in the array. If the new size is larger, the new elements will be constructed using the optional second argument.
+ ///when the new number of elements is smaller, the destructor will be called, but memory will not be freed, to reduce performance overhead of run-time memory (de)allocations.
+ SIMD_FORCE_INLINE void resize(int32_t newsize, const T& fillData = T())
+ {
+ int32_t curSize = size();
+
+ if (newsize < curSize) {
+ for (int32_t i = newsize; i < curSize; i++) {
+ m_data[i].~T();
+ }
+ }
+ else {
+ if (newsize > size()) {
+ reserve(newsize);
+ }
+#ifdef BT_USE_PLACEMENT_NEW
+ for (int32_t i = curSize; i < newsize; i++) {
+ new (&m_data[i]) T(fillData);
+ }
+#endif //BT_USE_PLACEMENT_NEW
+ }
+
+ m_size = newsize;
+ }
+
+ SIMD_FORCE_INLINE T& expandNonInitializing()
+ {
+ int32_t sz = size();
+ if (sz == capacity()) {
+ reserve(allocSize(size()));
+ }
+ m_size++;
+
+ return m_data[sz];
+ }
+
+ SIMD_FORCE_INLINE T& expand(const T& fillValue = T())
+ {
+ int32_t sz = size();
+ if (sz == capacity()) {
+ reserve(allocSize(size()));
+ }
+ m_size++;
+#ifdef BT_USE_PLACEMENT_NEW
+ new (&m_data[sz]) T(fillValue); //use the in-place new (not really allocating heap memory)
+#endif
+
+ return m_data[sz];
+ }
+
+ SIMD_FORCE_INLINE void push_back(const T& _Val)
+ {
+ int32_t sz = size();
+ if (sz == capacity()) {
+ reserve(allocSize(size()));
+ }
+
+#ifdef BT_USE_PLACEMENT_NEW
+ new (&m_data[m_size]) T(_Val);
+#else
+ m_data[size()] = _Val;
+#endif //BT_USE_PLACEMENT_NEW
+
+ m_size++;
+ }
+
+ /// return the pre-allocated (reserved) elements, this is at least as large as the total number of elements,see size() and reserve()
+ SIMD_FORCE_INLINE int32_t capacity() const
+ {
+ return m_capacity;
+ }
+
+ SIMD_FORCE_INLINE void reserve(int32_t _Count)
+ { // determine new minimum length of allocated storage
+ if (capacity() < _Count) { // not enough room, reallocate
+ T* s = (T*)allocate(_Count);
+
+ copy(0, size(), s);
+
+ destroy(0, size());
+
+ deallocate();
+
+ //PCK: added this line
+ m_ownsMemory = true;
+
+ m_data = s;
+
+ m_capacity = _Count;
+ }
+ }
+
+ class less {
+ public:
+ bool operator()(const T& a, const T& b)
+ {
+ return (a < b);
+ }
+ };
+
+ template <typename L>
+ void quickSortInternal(const L& CompareFunc, int32_t lo, int32_t hi)
+ {
+ // lo is the lower index, hi is the upper index
+ // of the region of array a that is to be sorted
+ int32_t i = lo, j = hi;
+ T x = m_data[(lo + hi) / 2];
+
+ // partition
+ do {
+ while (CompareFunc(m_data[i], x))
+ i++;
+ while (CompareFunc(x, m_data[j]))
+ j--;
+ if (i <= j) {
+ swap(i, j);
+ i++;
+ j--;
+ }
+ } while (i <= j);
+
+ // recursion
+ if (lo < j)
+ quickSortInternal(CompareFunc, lo, j);
+ if (i < hi)
+ quickSortInternal(CompareFunc, i, hi);
+ }
+
+ template <typename L>
+ void quickSort(const L& CompareFunc)
+ {
+ //don't sort 0 or 1 elements
+ if (size() > 1) {
+ quickSortInternal(CompareFunc, 0, size() - 1);
+ }
+ }
+
+ ///heap sort from http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Heap/
+ template <typename L>
+ void downHeap(T* pArr, int32_t k, int32_t n, const L& CompareFunc)
+ {
+ /* PRE: a[k+1..N] is a heap */
+ /* POST: a[k..N] is a heap */
+
+ T temp = pArr[k - 1];
+ /* k has child(s) */
+ while (k <= n / 2) {
+ int32_t child = 2 * k;
+
+ if ((child < n) && CompareFunc(pArr[child - 1], pArr[child])) {
+ child++;
+ }
+ /* pick larger child */
+ if (CompareFunc(temp, pArr[child - 1])) {
+ /* move child up */
+ pArr[k - 1] = pArr[child - 1];
+ k = child;
+ }
+ else {
+ break;
+ }
+ }
+ pArr[k - 1] = temp;
+ } /*downHeap*/
+
+ void swap(int32_t index0, int32_t index1)
+ {
+#ifdef BT_USE_MEMCPY
+ char temp[sizeof(T)];
+ memcpy(temp, &m_data[index0], sizeof(T));
+ memcpy(&m_data[index0], &m_data[index1], sizeof(T));
+ memcpy(&m_data[index1], temp, sizeof(T));
+#else
+ T temp = m_data[index0];
+ m_data[index0] = m_data[index1];
+ m_data[index1] = temp;
+#endif //BT_USE_PLACEMENT_NEW
+ }
+
+ template <typename L>
+ void heapSort(const L& CompareFunc)
+ {
+ /* sort a[0..N-1], N.B. 0 to N-1 */
+ int32_t k;
+ int32_t n = m_size;
+ for (k = n / 2; k > 0; k--) {
+ downHeap(m_data, k, n, CompareFunc);
+ }
+
+ /* a[1..N] is now a heap */
+ while (n >= 1) {
+ swap(0, n - 1); /* largest of a[0..n-1] */
+
+ n = n - 1;
+ /* restore a[1..i-1] heap */
+ downHeap(m_data, 1, n, CompareFunc);
+ }
+ }
+
+ ///non-recursive binary search, assumes sorted array
+ int32_t findBinarySearch(const T& key) const
+ {
+ int32_t first = 0;
+ int32_t last = size() - 1;
+
+ //assume sorted array
+ while (first <= last) {
+ int32_t mid = (first + last) / 2; // compute mid point.
+ if (key > m_data[mid])
+ first = mid + 1; // repeat search in top half.
+ else if (key < m_data[mid])
+ last = mid - 1; // repeat search in bottom half.
+ else
+ return mid; // found it. return position /////
+ }
+ return size(); // failed to find key
+ }
+
+ int32_t findLinearSearch(const T& key) const
+ {
+ int32_t index = size();
+ int32_t i;
+
+ for (i = 0; i < size(); i++) {
+ if (m_data[i] == key) {
+ index = i;
+ break;
+ }
+ }
+ return index;
+ }
+
+ void remove(const T& key)
+ {
+
+ int32_t findIndex = findLinearSearch(key);
+ if (findIndex < size()) {
+ swap(findIndex, size() - 1);
+ pop_back();
+ }
+ }
+
+ //PCK: whole function
+ void initializeFromBuffer(void* buffer, int32_t size, int32_t capacity)
+ {
+ clear();
+ m_ownsMemory = false;
+ m_data = (T*)buffer;
+ m_size = size;
+ m_capacity = capacity;
+ }
+
+ void copyFromArray(const btAlignedObjectArray& otherArray)
+ {
+ int32_t otherSize = otherArray.size();
+ resize(otherSize);
+ otherArray.copy(0, otherSize, m_data);
+ }
+};
+
+// -- GODOT start --
+}; // namespace VHACD
+// -- GODOT end --
+
+#endif //BT_OBJECT_ARRAY__
diff --git a/thirdparty/vhacd/inc/btConvexHullComputer.h b/thirdparty/vhacd/inc/btConvexHullComputer.h
new file mode 100644
index 0000000000..04bb96f64a
--- /dev/null
+++ b/thirdparty/vhacd/inc/btConvexHullComputer.h
@@ -0,0 +1,105 @@
+/*
+Copyright (c) 2011 Ole Kniemeyer, MAXON, www.maxon.net
+
+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 BT_CONVEX_HULL_COMPUTER_H
+#define BT_CONVEX_HULL_COMPUTER_H
+
+#include "btAlignedObjectArray.h"
+#include "btVector3.h"
+
+// -- GODOT start --
+namespace VHACD {
+// -- GODOT end --
+
+/// Convex hull implementation based on Preparata and Hong
+/// See http://code.google.com/p/bullet/issues/detail?id=275
+/// Ole Kniemeyer, MAXON Computer GmbH
+class btConvexHullComputer {
+private:
+ btScalar compute(const void* coords, bool doubleCoords, int32_t stride, int32_t count, btScalar shrink, btScalar shrinkClamp);
+
+public:
+ class Edge {
+ private:
+ int32_t next;
+ int32_t reverse;
+ int32_t targetVertex;
+
+ friend class btConvexHullComputer;
+
+ public:
+ int32_t getSourceVertex() const
+ {
+ return (this + reverse)->targetVertex;
+ }
+
+ int32_t getTargetVertex() const
+ {
+ return targetVertex;
+ }
+
+ const Edge* getNextEdgeOfVertex() const // clockwise list of all edges of a vertex
+ {
+ return this + next;
+ }
+
+ const Edge* getNextEdgeOfFace() const // counter-clockwise list of all edges of a face
+ {
+ return (this + reverse)->getNextEdgeOfVertex();
+ }
+
+ const Edge* getReverseEdge() const
+ {
+ return this + reverse;
+ }
+ };
+
+ // Vertices of the output hull
+ btAlignedObjectArray<btVector3> vertices;
+
+ // Edges of the output hull
+ btAlignedObjectArray<Edge> edges;
+
+ // Faces of the convex hull. Each entry is an index into the "edges" array pointing to an edge of the face. Faces are planar n-gons
+ btAlignedObjectArray<int32_t> faces;
+
+ /*
+ Compute convex hull of "count" vertices stored in "coords". "stride" is the difference in bytes
+ between the addresses of consecutive vertices. If "shrink" is positive, the convex hull is shrunken
+ by that amount (each face is moved by "shrink" length units towards the center along its normal).
+ If "shrinkClamp" is positive, "shrink" is clamped to not exceed "shrinkClamp * innerRadius", where "innerRadius"
+ is the minimum distance of a face to the center of the convex hull.
+
+ The returned value is the amount by which the hull has been shrunken. If it is negative, the amount was so large
+ that the resulting convex hull is empty.
+
+ The output convex hull can be found in the member variables "vertices", "edges", "faces".
+ */
+ btScalar compute(const float* coords, int32_t stride, int32_t count, btScalar shrink, btScalar shrinkClamp)
+ {
+ return compute(coords, false, stride, count, shrink, shrinkClamp);
+ }
+
+ // same as above, but double precision
+ btScalar compute(const double* coords, int32_t stride, int32_t count, btScalar shrink, btScalar shrinkClamp)
+ {
+ return compute(coords, true, stride, count, shrink, shrinkClamp);
+ }
+};
+
+// -- GODOT start --
+}; // namespace VHACD
+// -- GODOT end --
+
+#endif //BT_CONVEX_HULL_COMPUTER_H
diff --git a/thirdparty/vhacd/inc/btMinMax.h b/thirdparty/vhacd/inc/btMinMax.h
new file mode 100644
index 0000000000..9bc1e1c770
--- /dev/null
+++ b/thirdparty/vhacd/inc/btMinMax.h
@@ -0,0 +1,73 @@
+/*
+Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/
+
+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 BT_GEN_MINMAX_H
+#define BT_GEN_MINMAX_H
+
+#include "btScalar.h"
+
+// -- GODOT start --
+namespace VHACD {
+// -- GODOT end --
+
+template <class T>
+SIMD_FORCE_INLINE const T& btMin(const T& a, const T& b)
+{
+ return a < b ? a : b;
+}
+
+template <class T>
+SIMD_FORCE_INLINE const T& btMax(const T& a, const T& b)
+{
+ return a > b ? a : b;
+}
+
+template <class T>
+SIMD_FORCE_INLINE const T& btClamped(const T& a, const T& lb, const T& ub)
+{
+ return a < lb ? lb : (ub < a ? ub : a);
+}
+
+template <class T>
+SIMD_FORCE_INLINE void btSetMin(T& a, const T& b)
+{
+ if (b < a) {
+ a = b;
+ }
+}
+
+template <class T>
+SIMD_FORCE_INLINE void btSetMax(T& a, const T& b)
+{
+ if (a < b) {
+ a = b;
+ }
+}
+
+template <class T>
+SIMD_FORCE_INLINE void btClamp(T& a, const T& lb, const T& ub)
+{
+ if (a < lb) {
+ a = lb;
+ }
+ else if (ub < a) {
+ a = ub;
+ }
+}
+
+// -- GODOT start --
+}; // namespace VHACD
+// -- GODOT end --
+
+#endif //BT_GEN_MINMAX_H
diff --git a/thirdparty/vhacd/inc/btScalar.h b/thirdparty/vhacd/inc/btScalar.h
new file mode 100644
index 0000000000..3999a71521
--- /dev/null
+++ b/thirdparty/vhacd/inc/btScalar.h
@@ -0,0 +1,573 @@
+/*
+Copyright (c) 2003-2009 Erwin Coumans http://bullet.googlecode.com
+
+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 BT_SCALAR_H
+#define BT_SCALAR_H
+
+#ifdef BT_MANAGED_CODE
+//Aligned data types not supported in managed code
+#pragma unmanaged
+#endif
+
+#include <float.h>
+#include <math.h>
+#include <stdlib.h> //size_t for MSVC 6.0
+#include <stdint.h>
+
+/* SVN $Revision$ on $Date$ from http://bullet.googlecode.com*/
+#define BT_BULLET_VERSION 279
+
+// -- GODOT start --
+namespace VHACD {
+// -- GODOT end --
+
+inline int32_t btGetVersion()
+{
+ return BT_BULLET_VERSION;
+}
+
+// -- GODOT start --
+}; // namespace VHACD
+// -- GODOT end --
+
+#if defined(DEBUG) || defined(_DEBUG)
+#define BT_DEBUG
+#endif
+
+#ifdef _WIN32
+
+#if defined(__MINGW32__) || defined(__CYGWIN__) || (defined(_MSC_VER) && _MSC_VER < 1300)
+
+#define SIMD_FORCE_INLINE inline
+#define ATTRIBUTE_ALIGNED16(a) a
+#define ATTRIBUTE_ALIGNED64(a) a
+#define ATTRIBUTE_ALIGNED128(a) a
+#else
+//#define BT_HAS_ALIGNED_ALLOCATOR
+#pragma warning(disable : 4324) // disable padding warning
+// #pragma warning(disable:4530) // Disable the exception disable but used in MSCV Stl warning.
+// #pragma warning(disable:4996) //Turn off warnings about deprecated C routines
+// #pragma warning(disable:4786) // Disable the "debug name too long" warning
+
+#define SIMD_FORCE_INLINE __forceinline
+#define ATTRIBUTE_ALIGNED16(a) __declspec(align(16)) a
+#define ATTRIBUTE_ALIGNED64(a) __declspec(align(64)) a
+#define ATTRIBUTE_ALIGNED128(a) __declspec(align(128)) a
+#ifdef _XBOX
+#define BT_USE_VMX128
+
+#include <ppcintrinsics.h>
+#define BT_HAVE_NATIVE_FSEL
+#define btFsel(a, b, c) __fsel((a), (b), (c))
+#else
+
+#if (defined(_WIN32) && (_MSC_VER) && _MSC_VER >= 1400) && (!defined(BT_USE_DOUBLE_PRECISION))
+#define BT_USE_SSE
+#include <emmintrin.h>
+#endif
+
+#endif //_XBOX
+
+#endif //__MINGW32__
+
+#include <assert.h>
+#ifdef BT_DEBUG
+#define btAssert assert
+#else
+#define btAssert(x)
+#endif
+//btFullAssert is optional, slows down a lot
+#define btFullAssert(x)
+
+#define btLikely(_c) _c
+#define btUnlikely(_c) _c
+
+#else
+
+#if defined(__CELLOS_LV2__)
+#define SIMD_FORCE_INLINE inline __attribute__((always_inline))
+#define ATTRIBUTE_ALIGNED16(a) a __attribute__((aligned(16)))
+#define ATTRIBUTE_ALIGNED64(a) a __attribute__((aligned(64)))
+#define ATTRIBUTE_ALIGNED128(a) a __attribute__((aligned(128)))
+#ifndef assert
+#include <assert.h>
+#endif
+#ifdef BT_DEBUG
+#ifdef __SPU__
+#include <spu_printf.h>
+#define printf spu_printf
+#define btAssert(x) \
+ { \
+ if (!(x)) { \
+ printf("Assert " __FILE__ ":%u (" #x ")\n", __LINE__); \
+ spu_hcmpeq(0, 0); \
+ } \
+ }
+#else
+#define btAssert assert
+#endif
+
+#else
+#define btAssert(x)
+#endif
+//btFullAssert is optional, slows down a lot
+#define btFullAssert(x)
+
+#define btLikely(_c) _c
+#define btUnlikely(_c) _c
+
+#else
+
+#ifdef USE_LIBSPE2
+
+#define SIMD_FORCE_INLINE __inline
+#define ATTRIBUTE_ALIGNED16(a) a __attribute__((aligned(16)))
+#define ATTRIBUTE_ALIGNED64(a) a __attribute__((aligned(64)))
+#define ATTRIBUTE_ALIGNED128(a) a __attribute__((aligned(128)))
+#ifndef assert
+#include <assert.h>
+#endif
+#ifdef BT_DEBUG
+#define btAssert assert
+#else
+#define btAssert(x)
+#endif
+//btFullAssert is optional, slows down a lot
+#define btFullAssert(x)
+
+#define btLikely(_c) __builtin_expect((_c), 1)
+#define btUnlikely(_c) __builtin_expect((_c), 0)
+
+#else
+//non-windows systems
+
+#if (defined(__APPLE__) && defined(__i386__) && (!defined(BT_USE_DOUBLE_PRECISION)))
+#define BT_USE_SSE
+#include <emmintrin.h>
+
+#define SIMD_FORCE_INLINE inline
+///@todo: check out alignment methods for other platforms/compilers
+#define ATTRIBUTE_ALIGNED16(a) a __attribute__((aligned(16)))
+#define ATTRIBUTE_ALIGNED64(a) a __attribute__((aligned(64)))
+#define ATTRIBUTE_ALIGNED128(a) a __attribute__((aligned(128)))
+#ifndef assert
+#include <assert.h>
+#endif
+
+#if defined(DEBUG) || defined(_DEBUG)
+#define btAssert assert
+#else
+#define btAssert(x)
+#endif
+
+//btFullAssert is optional, slows down a lot
+#define btFullAssert(x)
+#define btLikely(_c) _c
+#define btUnlikely(_c) _c
+
+#else
+
+#define SIMD_FORCE_INLINE inline
+///@todo: check out alignment methods for other platforms/compilers
+///#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
+///#define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
+///#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
+#define ATTRIBUTE_ALIGNED16(a) a
+#define ATTRIBUTE_ALIGNED64(a) a
+#define ATTRIBUTE_ALIGNED128(a) a
+#ifndef assert
+#include <assert.h>
+#endif
+
+#if defined(DEBUG) || defined(_DEBUG)
+#define btAssert assert
+#else
+#define btAssert(x)
+#endif
+
+//btFullAssert is optional, slows down a lot
+#define btFullAssert(x)
+#define btLikely(_c) _c
+#define btUnlikely(_c) _c
+#endif //__APPLE__
+
+#endif // LIBSPE2
+
+#endif //__CELLOS_LV2__
+#endif
+
+// -- GODOT start --
+namespace VHACD {
+// -- GODOT end --
+
+///The btScalar type abstracts floating point numbers, to easily switch between double and single floating point precision.
+#if defined(BT_USE_DOUBLE_PRECISION)
+typedef double btScalar;
+//this number could be bigger in double precision
+#define BT_LARGE_FLOAT 1e30
+#else
+typedef float btScalar;
+//keep BT_LARGE_FLOAT*BT_LARGE_FLOAT < FLT_MAX
+#define BT_LARGE_FLOAT 1e18f
+#endif
+
+#define BT_DECLARE_ALIGNED_ALLOCATOR() \
+ SIMD_FORCE_INLINE void* operator new(size_t sizeInBytes) { return btAlignedAlloc(sizeInBytes, 16); } \
+ SIMD_FORCE_INLINE void operator delete(void* ptr) { btAlignedFree(ptr); } \
+ SIMD_FORCE_INLINE void* operator new(size_t, void* ptr) { return ptr; } \
+ SIMD_FORCE_INLINE void operator delete(void*, void*) {} \
+ SIMD_FORCE_INLINE void* operator new[](size_t sizeInBytes) { return btAlignedAlloc(sizeInBytes, 16); } \
+ SIMD_FORCE_INLINE void operator delete[](void* ptr) { btAlignedFree(ptr); } \
+ SIMD_FORCE_INLINE void* operator new[](size_t, void* ptr) { return ptr; } \
+ SIMD_FORCE_INLINE void operator delete[](void*, void*) {}
+
+#if defined(BT_USE_DOUBLE_PRECISION) || defined(BT_FORCE_DOUBLE_FUNCTIONS)
+
+SIMD_FORCE_INLINE btScalar btSqrt(btScalar x)
+{
+ return sqrt(x);
+}
+SIMD_FORCE_INLINE btScalar btFabs(btScalar x) { return fabs(x); }
+SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cos(x); }
+SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sin(x); }
+SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tan(x); }
+SIMD_FORCE_INLINE btScalar btAcos(btScalar x)
+{
+ if (x < btScalar(-1))
+ x = btScalar(-1);
+ if (x > btScalar(1))
+ x = btScalar(1);
+ return acos(x);
+}
+SIMD_FORCE_INLINE btScalar btAsin(btScalar x)
+{
+ if (x < btScalar(-1))
+ x = btScalar(-1);
+ if (x > btScalar(1))
+ x = btScalar(1);
+ return asin(x);
+}
+SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atan(x); }
+SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2(x, y); }
+SIMD_FORCE_INLINE btScalar btExp(btScalar x) { return exp(x); }
+SIMD_FORCE_INLINE btScalar btLog(btScalar x) { return log(x); }
+SIMD_FORCE_INLINE btScalar btPow(btScalar x, btScalar y) { return pow(x, y); }
+SIMD_FORCE_INLINE btScalar btFmod(btScalar x, btScalar y) { return fmod(x, y); }
+
+#else
+
+SIMD_FORCE_INLINE btScalar btSqrt(btScalar y)
+{
+#ifdef USE_APPROXIMATION
+ double x, z, tempf;
+ unsigned long* tfptr = ((unsigned long*)&tempf) + 1;
+
+ tempf = y;
+ *tfptr = (0xbfcdd90a - *tfptr) >> 1; /* estimate of 1/sqrt(y) */
+ x = tempf;
+ z = y * btScalar(0.5);
+ x = (btScalar(1.5) * x) - (x * x) * (x * z); /* iteration formula */
+ x = (btScalar(1.5) * x) - (x * x) * (x * z);
+ x = (btScalar(1.5) * x) - (x * x) * (x * z);
+ x = (btScalar(1.5) * x) - (x * x) * (x * z);
+ x = (btScalar(1.5) * x) - (x * x) * (x * z);
+ return x * y;
+#else
+ return sqrtf(y);
+#endif
+}
+SIMD_FORCE_INLINE btScalar btFabs(btScalar x) { return fabsf(x); }
+SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cosf(x); }
+SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sinf(x); }
+SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tanf(x); }
+SIMD_FORCE_INLINE btScalar btAcos(btScalar x)
+{
+ if (x < btScalar(-1))
+ x = btScalar(-1);
+ if (x > btScalar(1))
+ x = btScalar(1);
+ return acosf(x);
+}
+SIMD_FORCE_INLINE btScalar btAsin(btScalar x)
+{
+ if (x < btScalar(-1))
+ x = btScalar(-1);
+ if (x > btScalar(1))
+ x = btScalar(1);
+ return asinf(x);
+}
+SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atanf(x); }
+SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2f(x, y); }
+SIMD_FORCE_INLINE btScalar btExp(btScalar x) { return expf(x); }
+SIMD_FORCE_INLINE btScalar btLog(btScalar x) { return logf(x); }
+SIMD_FORCE_INLINE btScalar btPow(btScalar x, btScalar y) { return powf(x, y); }
+SIMD_FORCE_INLINE btScalar btFmod(btScalar x, btScalar y) { return fmodf(x, y); }
+
+#endif
+
+#define SIMD_2_PI btScalar(6.283185307179586232)
+#define SIMD_PI (SIMD_2_PI * btScalar(0.5))
+#define SIMD_HALF_PI (SIMD_2_PI * btScalar(0.25))
+#define SIMD_RADS_PER_DEG (SIMD_2_PI / btScalar(360.0))
+#define SIMD_DEGS_PER_RAD (btScalar(360.0) / SIMD_2_PI)
+#define SIMDSQRT12 btScalar(0.7071067811865475244008443621048490)
+
+#define btRecipSqrt(x) ((btScalar)(btScalar(1.0) / btSqrt(btScalar(x)))) /* reciprocal square root */
+
+#ifdef BT_USE_DOUBLE_PRECISION
+#define SIMD_EPSILON DBL_EPSILON
+#define SIMD_INFINITY DBL_MAX
+#else
+#define SIMD_EPSILON FLT_EPSILON
+#define SIMD_INFINITY FLT_MAX
+#endif
+
+SIMD_FORCE_INLINE btScalar btAtan2Fast(btScalar y, btScalar x)
+{
+ btScalar coeff_1 = SIMD_PI / 4.0f;
+ btScalar coeff_2 = 3.0f * coeff_1;
+ btScalar abs_y = btFabs(y);
+ btScalar angle;
+ if (x >= 0.0f) {
+ btScalar r = (x - abs_y) / (x + abs_y);
+ angle = coeff_1 - coeff_1 * r;
+ }
+ else {
+ btScalar r = (x + abs_y) / (abs_y - x);
+ angle = coeff_2 - coeff_1 * r;
+ }
+ return (y < 0.0f) ? -angle : angle;
+}
+
+SIMD_FORCE_INLINE bool btFuzzyZero(btScalar x) { return btFabs(x) < SIMD_EPSILON; }
+
+SIMD_FORCE_INLINE bool btEqual(btScalar a, btScalar eps)
+{
+ return (((a) <= eps) && !((a) < -eps));
+}
+SIMD_FORCE_INLINE bool btGreaterEqual(btScalar a, btScalar eps)
+{
+ return (!((a) <= eps));
+}
+
+SIMD_FORCE_INLINE int32_t btIsNegative(btScalar x)
+{
+ return x < btScalar(0.0) ? 1 : 0;
+}
+
+SIMD_FORCE_INLINE btScalar btRadians(btScalar x) { return x * SIMD_RADS_PER_DEG; }
+SIMD_FORCE_INLINE btScalar btDegrees(btScalar x) { return x * SIMD_DEGS_PER_RAD; }
+
+#define BT_DECLARE_HANDLE(name) \
+ typedef struct name##__ { \
+ int32_t unused; \
+ } * name
+
+#ifndef btFsel
+SIMD_FORCE_INLINE btScalar btFsel(btScalar a, btScalar b, btScalar c)
+{
+ return a >= 0 ? b : c;
+}
+#endif
+#define btFsels(a, b, c) (btScalar) btFsel(a, b, c)
+
+SIMD_FORCE_INLINE bool btMachineIsLittleEndian()
+{
+ long int i = 1;
+ const char* p = (const char*)&i;
+ if (p[0] == 1) // Lowest address contains the least significant byte
+ return true;
+ else
+ return false;
+}
+
+///btSelect avoids branches, which makes performance much better for consoles like Playstation 3 and XBox 360
+///Thanks Phil Knight. See also http://www.cellperformance.com/articles/2006/04/more_techniques_for_eliminatin_1.html
+SIMD_FORCE_INLINE unsigned btSelect(unsigned condition, unsigned valueIfConditionNonZero, unsigned valueIfConditionZero)
+{
+ // Set testNz to 0xFFFFFFFF if condition is nonzero, 0x00000000 if condition is zero
+ // Rely on positive value or'ed with its negative having sign bit on
+ // and zero value or'ed with its negative (which is still zero) having sign bit off
+ // Use arithmetic shift right, shifting the sign bit through all 32 bits
+ unsigned testNz = (unsigned)(((int32_t)condition | -(int32_t)condition) >> 31);
+ unsigned testEqz = ~testNz;
+ return ((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz));
+}
+SIMD_FORCE_INLINE int32_t btSelect(unsigned condition, int32_t valueIfConditionNonZero, int32_t valueIfConditionZero)
+{
+ unsigned testNz = (unsigned)(((int32_t)condition | -(int32_t)condition) >> 31);
+ unsigned testEqz = ~testNz;
+ return static_cast<int32_t>((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz));
+}
+SIMD_FORCE_INLINE float btSelect(unsigned condition, float valueIfConditionNonZero, float valueIfConditionZero)
+{
+#ifdef BT_HAVE_NATIVE_FSEL
+ return (float)btFsel((btScalar)condition - btScalar(1.0f), valueIfConditionNonZero, valueIfConditionZero);
+#else
+ return (condition != 0) ? valueIfConditionNonZero : valueIfConditionZero;
+#endif
+}
+
+template <typename T>
+SIMD_FORCE_INLINE void btSwap(T& a, T& b)
+{
+ T tmp = a;
+ a = b;
+ b = tmp;
+}
+
+//PCK: endian swapping functions
+SIMD_FORCE_INLINE unsigned btSwapEndian(unsigned val)
+{
+ return (((val & 0xff000000) >> 24) | ((val & 0x00ff0000) >> 8) | ((val & 0x0000ff00) << 8) | ((val & 0x000000ff) << 24));
+}
+
+SIMD_FORCE_INLINE unsigned short btSwapEndian(unsigned short val)
+{
+ return static_cast<unsigned short>(((val & 0xff00) >> 8) | ((val & 0x00ff) << 8));
+}
+
+SIMD_FORCE_INLINE unsigned btSwapEndian(int32_t val)
+{
+ return btSwapEndian((unsigned)val);
+}
+
+SIMD_FORCE_INLINE unsigned short btSwapEndian(short val)
+{
+ return btSwapEndian((unsigned short)val);
+}
+
+///btSwapFloat uses using char pointers to swap the endianness
+////btSwapFloat/btSwapDouble will NOT return a float, because the machine might 'correct' invalid floating point values
+///Not all values of sign/exponent/mantissa are valid floating point numbers according to IEEE 754.
+///When a floating point unit is faced with an invalid value, it may actually change the value, or worse, throw an exception.
+///In most systems, running user mode code, you wouldn't get an exception, but instead the hardware/os/runtime will 'fix' the number for you.
+///so instead of returning a float/double, we return integer/long long integer
+SIMD_FORCE_INLINE uint32_t btSwapEndianFloat(float d)
+{
+ uint32_t a = 0;
+ unsigned char* dst = (unsigned char*)&a;
+ unsigned char* src = (unsigned char*)&d;
+
+ dst[0] = src[3];
+ dst[1] = src[2];
+ dst[2] = src[1];
+ dst[3] = src[0];
+ return a;
+}
+
+// unswap using char pointers
+SIMD_FORCE_INLINE float btUnswapEndianFloat(uint32_t a)
+{
+ float d = 0.0f;
+ unsigned char* src = (unsigned char*)&a;
+ unsigned char* dst = (unsigned char*)&d;
+
+ dst[0] = src[3];
+ dst[1] = src[2];
+ dst[2] = src[1];
+ dst[3] = src[0];
+
+ return d;
+}
+
+// swap using char pointers
+SIMD_FORCE_INLINE void btSwapEndianDouble(double d, unsigned char* dst)
+{
+ unsigned char* src = (unsigned char*)&d;
+
+ dst[0] = src[7];
+ dst[1] = src[6];
+ dst[2] = src[5];
+ dst[3] = src[4];
+ dst[4] = src[3];
+ dst[5] = src[2];
+ dst[6] = src[1];
+ dst[7] = src[0];
+}
+
+// unswap using char pointers
+SIMD_FORCE_INLINE double btUnswapEndianDouble(const unsigned char* src)
+{
+ double d = 0.0;
+ unsigned char* dst = (unsigned char*)&d;
+
+ dst[0] = src[7];
+ dst[1] = src[6];
+ dst[2] = src[5];
+ dst[3] = src[4];
+ dst[4] = src[3];
+ dst[5] = src[2];
+ dst[6] = src[1];
+ dst[7] = src[0];
+
+ return d;
+}
+
+// returns normalized value in range [-SIMD_PI, SIMD_PI]
+SIMD_FORCE_INLINE btScalar btNormalizeAngle(btScalar angleInRadians)
+{
+ angleInRadians = btFmod(angleInRadians, SIMD_2_PI);
+ if (angleInRadians < -SIMD_PI) {
+ return angleInRadians + SIMD_2_PI;
+ }
+ else if (angleInRadians > SIMD_PI) {
+ return angleInRadians - SIMD_2_PI;
+ }
+ else {
+ return angleInRadians;
+ }
+}
+
+///rudimentary class to provide type info
+struct btTypedObject {
+ btTypedObject(int32_t objectType)
+ : m_objectType(objectType)
+ {
+ }
+ int32_t m_objectType;
+ inline int32_t getObjectType() const
+ {
+ return m_objectType;
+ }
+};
+
+// -- GODOT start --
+// Cherry-picked from Bullet 2.88 to fix GH-27926
+///align a pointer to the provided alignment, upwards
+template <typename T>
+T *btAlignPointer(T *unalignedPtr, size_t alignment)
+{
+ struct btConvertPointerSizeT
+ {
+ union {
+ T *ptr;
+ size_t integer;
+ };
+ };
+ btConvertPointerSizeT converter;
+
+ const size_t bit_mask = ~(alignment - 1);
+ converter.ptr = unalignedPtr;
+ converter.integer += alignment - 1;
+ converter.integer &= bit_mask;
+ return converter.ptr;
+}
+// -- GODOT end --
+
+// -- GODOT start --
+}; // namespace VHACD
+// -- GODOT end --
+
+#endif //BT_SCALAR_H
diff --git a/thirdparty/vhacd/inc/btVector3.h b/thirdparty/vhacd/inc/btVector3.h
new file mode 100644
index 0000000000..4ed9716734
--- /dev/null
+++ b/thirdparty/vhacd/inc/btVector3.h
@@ -0,0 +1,723 @@
+/*
+Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/
+
+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 BT_VECTOR3_H
+#define BT_VECTOR3_H
+
+#include "btMinMax.h"
+#include "btScalar.h"
+
+#ifdef BT_USE_DOUBLE_PRECISION
+#define btVector3Data btVector3DoubleData
+#define btVector3DataName "btVector3DoubleData"
+#else
+#define btVector3Data btVector3FloatData
+#define btVector3DataName "btVector3FloatData"
+#endif //BT_USE_DOUBLE_PRECISION
+
+// -- GODOT start --
+namespace VHACD {
+// -- GODOT end --
+
+/**@brief btVector3 can be used to represent 3D points and vectors.
+ * It has an un-used w component to suit 16-byte alignment when btVector3 is stored in containers. This extra component can be used by derived classes (Quaternion?) or by user
+ * Ideally, this class should be replaced by a platform optimized SIMD version that keeps the data in registers
+ */
+ATTRIBUTE_ALIGNED16(class)
+btVector3
+{
+public:
+#if defined(__SPU__) && defined(__CELLOS_LV2__)
+ btScalar m_floats[4];
+
+public:
+ SIMD_FORCE_INLINE const vec_float4& get128() const
+ {
+ return *((const vec_float4*)&m_floats[0]);
+ }
+
+public:
+#else //__CELLOS_LV2__ __SPU__
+#ifdef BT_USE_SSE // _WIN32
+ union {
+ __m128 mVec128;
+ btScalar m_floats[4];
+ };
+ SIMD_FORCE_INLINE __m128 get128() const
+ {
+ return mVec128;
+ }
+ SIMD_FORCE_INLINE void set128(__m128 v128)
+ {
+ mVec128 = v128;
+ }
+#else
+ btScalar m_floats[4];
+#endif
+#endif //__CELLOS_LV2__ __SPU__
+
+public:
+ /**@brief No initialization constructor */
+ SIMD_FORCE_INLINE btVector3() {}
+
+ /**@brief Constructor from scalars
+ * @param x X value
+ * @param y Y value
+ * @param z Z value
+ */
+ SIMD_FORCE_INLINE btVector3(const btScalar& x, const btScalar& y, const btScalar& z)
+ {
+ m_floats[0] = x;
+ m_floats[1] = y;
+ m_floats[2] = z;
+ m_floats[3] = btScalar(0.);
+ }
+
+ /**@brief Add a vector to this one
+ * @param The vector to add to this one */
+ SIMD_FORCE_INLINE btVector3& operator+=(const btVector3& v)
+ {
+
+ m_floats[0] += v.m_floats[0];
+ m_floats[1] += v.m_floats[1];
+ m_floats[2] += v.m_floats[2];
+ return *this;
+ }
+
+ /**@brief Subtract a vector from this one
+ * @param The vector to subtract */
+ SIMD_FORCE_INLINE btVector3& operator-=(const btVector3& v)
+ {
+ m_floats[0] -= v.m_floats[0];
+ m_floats[1] -= v.m_floats[1];
+ m_floats[2] -= v.m_floats[2];
+ return *this;
+ }
+ /**@brief Scale the vector
+ * @param s Scale factor */
+ SIMD_FORCE_INLINE btVector3& operator*=(const btScalar& s)
+ {
+ m_floats[0] *= s;
+ m_floats[1] *= s;
+ m_floats[2] *= s;
+ return *this;
+ }
+
+ /**@brief Inversely scale the vector
+ * @param s Scale factor to divide by */
+ SIMD_FORCE_INLINE btVector3& operator/=(const btScalar& s)
+ {
+ btFullAssert(s != btScalar(0.0));
+ return * this *= btScalar(1.0) / s;
+ }
+
+ /**@brief Return the dot product
+ * @param v The other vector in the dot product */
+ SIMD_FORCE_INLINE btScalar dot(const btVector3& v) const
+ {
+ return m_floats[0] * v.m_floats[0] + m_floats[1] * v.m_floats[1] + m_floats[2] * v.m_floats[2];
+ }
+
+ /**@brief Return the length of the vector squared */
+ SIMD_FORCE_INLINE btScalar length2() const
+ {
+ return dot(*this);
+ }
+
+ /**@brief Return the length of the vector */
+ SIMD_FORCE_INLINE btScalar length() const
+ {
+ return btSqrt(length2());
+ }
+
+ /**@brief Return the distance squared between the ends of this and another vector
+ * This is symantically treating the vector like a point */
+ SIMD_FORCE_INLINE btScalar distance2(const btVector3& v) const;
+
+ /**@brief Return the distance between the ends of this and another vector
+ * This is symantically treating the vector like a point */
+ SIMD_FORCE_INLINE btScalar distance(const btVector3& v) const;
+
+ SIMD_FORCE_INLINE btVector3& safeNormalize()
+ {
+ btVector3 absVec = this->absolute();
+ int32_t maxIndex = absVec.maxAxis();
+ if (absVec[maxIndex] > 0) {
+ *this /= absVec[maxIndex];
+ return * this /= length();
+ }
+ setValue(1, 0, 0);
+ return *this;
+ }
+
+ /**@brief Normalize this vector
+ * x^2 + y^2 + z^2 = 1 */
+ SIMD_FORCE_INLINE btVector3& normalize()
+ {
+ return * this /= length();
+ }
+
+ /**@brief Return a normalized version of this vector */
+ SIMD_FORCE_INLINE btVector3 normalized() const;
+
+ /**@brief Return a rotated version of this vector
+ * @param wAxis The axis to rotate about
+ * @param angle The angle to rotate by */
+ SIMD_FORCE_INLINE btVector3 rotate(const btVector3& wAxis, const btScalar angle) const;
+
+ /**@brief Return the angle between this and another vector
+ * @param v The other vector */
+ SIMD_FORCE_INLINE btScalar angle(const btVector3& v) const
+ {
+ btScalar s = btSqrt(length2() * v.length2());
+ btFullAssert(s != btScalar(0.0));
+ return btAcos(dot(v) / s);
+ }
+ /**@brief Return a vector will the absolute values of each element */
+ SIMD_FORCE_INLINE btVector3 absolute() const
+ {
+ return btVector3(
+ btFabs(m_floats[0]),
+ btFabs(m_floats[1]),
+ btFabs(m_floats[2]));
+ }
+ /**@brief Return the cross product between this and another vector
+ * @param v The other vector */
+ SIMD_FORCE_INLINE btVector3 cross(const btVector3& v) const
+ {
+ return btVector3(
+ m_floats[1] * v.m_floats[2] - m_floats[2] * v.m_floats[1],
+ m_floats[2] * v.m_floats[0] - m_floats[0] * v.m_floats[2],
+ m_floats[0] * v.m_floats[1] - m_floats[1] * v.m_floats[0]);
+ }
+
+ SIMD_FORCE_INLINE btScalar triple(const btVector3& v1, const btVector3& v2) const
+ {
+ return m_floats[0] * (v1.m_floats[1] * v2.m_floats[2] - v1.m_floats[2] * v2.m_floats[1]) + m_floats[1] * (v1.m_floats[2] * v2.m_floats[0] - v1.m_floats[0] * v2.m_floats[2]) + m_floats[2] * (v1.m_floats[0] * v2.m_floats[1] - v1.m_floats[1] * v2.m_floats[0]);
+ }
+
+ /**@brief Return the axis with the smallest value
+ * Note return values are 0,1,2 for x, y, or z */
+ SIMD_FORCE_INLINE int32_t minAxis() const
+ {
+ return m_floats[0] < m_floats[1] ? (m_floats[0] < m_floats[2] ? 0 : 2) : (m_floats[1] < m_floats[2] ? 1 : 2);
+ }
+
+ /**@brief Return the axis with the largest value
+ * Note return values are 0,1,2 for x, y, or z */
+ SIMD_FORCE_INLINE int32_t maxAxis() const
+ {
+ return m_floats[0] < m_floats[1] ? (m_floats[1] < m_floats[2] ? 2 : 1) : (m_floats[0] < m_floats[2] ? 2 : 0);
+ }
+
+ SIMD_FORCE_INLINE int32_t furthestAxis() const
+ {
+ return absolute().minAxis();
+ }
+
+ SIMD_FORCE_INLINE int32_t closestAxis() const
+ {
+ return absolute().maxAxis();
+ }
+
+ SIMD_FORCE_INLINE void setInterpolate3(const btVector3& v0, const btVector3& v1, btScalar rt)
+ {
+ btScalar s = btScalar(1.0) - rt;
+ m_floats[0] = s * v0.m_floats[0] + rt * v1.m_floats[0];
+ m_floats[1] = s * v0.m_floats[1] + rt * v1.m_floats[1];
+ m_floats[2] = s * v0.m_floats[2] + rt * v1.m_floats[2];
+ //don't do the unused w component
+ // m_co[3] = s * v0[3] + rt * v1[3];
+ }
+
+ /**@brief Return the linear interpolation between this and another vector
+ * @param v The other vector
+ * @param t The ration of this to v (t = 0 => return this, t=1 => return other) */
+ SIMD_FORCE_INLINE btVector3 lerp(const btVector3& v, const btScalar& t) const
+ {
+ return btVector3(m_floats[0] + (v.m_floats[0] - m_floats[0]) * t,
+ m_floats[1] + (v.m_floats[1] - m_floats[1]) * t,
+ m_floats[2] + (v.m_floats[2] - m_floats[2]) * t);
+ }
+
+ /**@brief Elementwise multiply this vector by the other
+ * @param v The other vector */
+ SIMD_FORCE_INLINE btVector3& operator*=(const btVector3& v)
+ {
+ m_floats[0] *= v.m_floats[0];
+ m_floats[1] *= v.m_floats[1];
+ m_floats[2] *= v.m_floats[2];
+ return *this;
+ }
+
+ /**@brief Return the x value */
+ SIMD_FORCE_INLINE const btScalar& getX() const { return m_floats[0]; }
+ /**@brief Return the y value */
+ SIMD_FORCE_INLINE const btScalar& getY() const { return m_floats[1]; }
+ /**@brief Return the z value */
+ SIMD_FORCE_INLINE const btScalar& getZ() const { return m_floats[2]; }
+ /**@brief Set the x value */
+ SIMD_FORCE_INLINE void setX(btScalar x) { m_floats[0] = x; };
+ /**@brief Set the y value */
+ SIMD_FORCE_INLINE void setY(btScalar y) { m_floats[1] = y; };
+ /**@brief Set the z value */
+ SIMD_FORCE_INLINE void setZ(btScalar z) { m_floats[2] = z; };
+ /**@brief Set the w value */
+ SIMD_FORCE_INLINE void setW(btScalar w) { m_floats[3] = w; };
+ /**@brief Return the x value */
+ SIMD_FORCE_INLINE const btScalar& x() const { return m_floats[0]; }
+ /**@brief Return the y value */
+ SIMD_FORCE_INLINE const btScalar& y() const { return m_floats[1]; }
+ /**@brief Return the z value */
+ SIMD_FORCE_INLINE const btScalar& z() const { return m_floats[2]; }
+ /**@brief Return the w value */
+ SIMD_FORCE_INLINE const btScalar& w() const { return m_floats[3]; }
+
+ //SIMD_FORCE_INLINE btScalar& operator[](int32_t i) { return (&m_floats[0])[i]; }
+ //SIMD_FORCE_INLINE const btScalar& operator[](int32_t i) const { return (&m_floats[0])[i]; }
+ ///operator btScalar*() replaces operator[], using implicit conversion. We added operator != and operator == to avoid pointer comparisons.
+ SIMD_FORCE_INLINE operator btScalar*() { return &m_floats[0]; }
+ SIMD_FORCE_INLINE operator const btScalar*() const { return &m_floats[0]; }
+
+ SIMD_FORCE_INLINE bool operator==(const btVector3& other) const
+ {
+ return ((m_floats[3] == other.m_floats[3]) && (m_floats[2] == other.m_floats[2]) && (m_floats[1] == other.m_floats[1]) && (m_floats[0] == other.m_floats[0]));
+ }
+
+ SIMD_FORCE_INLINE bool operator!=(const btVector3& other) const
+ {
+ return !(*this == other);
+ }
+
+ /**@brief Set each element to the max of the current values and the values of another btVector3
+ * @param other The other btVector3 to compare with
+ */
+ SIMD_FORCE_INLINE void setMax(const btVector3& other)
+ {
+ btSetMax(m_floats[0], other.m_floats[0]);
+ btSetMax(m_floats[1], other.m_floats[1]);
+ btSetMax(m_floats[2], other.m_floats[2]);
+ btSetMax(m_floats[3], other.w());
+ }
+ /**@brief Set each element to the min of the current values and the values of another btVector3
+ * @param other The other btVector3 to compare with
+ */
+ SIMD_FORCE_INLINE void setMin(const btVector3& other)
+ {
+ btSetMin(m_floats[0], other.m_floats[0]);
+ btSetMin(m_floats[1], other.m_floats[1]);
+ btSetMin(m_floats[2], other.m_floats[2]);
+ btSetMin(m_floats[3], other.w());
+ }
+
+ SIMD_FORCE_INLINE void setValue(const btScalar& x, const btScalar& y, const btScalar& z)
+ {
+ m_floats[0] = x;
+ m_floats[1] = y;
+ m_floats[2] = z;
+ m_floats[3] = btScalar(0.);
+ }
+
+ void getSkewSymmetricMatrix(btVector3 * v0, btVector3 * v1, btVector3 * v2) const
+ {
+ v0->setValue(0., -z(), y());
+ v1->setValue(z(), 0., -x());
+ v2->setValue(-y(), x(), 0.);
+ }
+
+ void setZero()
+ {
+ setValue(btScalar(0.), btScalar(0.), btScalar(0.));
+ }
+
+ SIMD_FORCE_INLINE bool isZero() const
+ {
+ return m_floats[0] == btScalar(0) && m_floats[1] == btScalar(0) && m_floats[2] == btScalar(0);
+ }
+
+ SIMD_FORCE_INLINE bool fuzzyZero() const
+ {
+ return length2() < SIMD_EPSILON;
+ }
+
+ SIMD_FORCE_INLINE void serialize(struct btVector3Data & dataOut) const;
+
+ SIMD_FORCE_INLINE void deSerialize(const struct btVector3Data& dataIn);
+
+ SIMD_FORCE_INLINE void serializeFloat(struct btVector3FloatData & dataOut) const;
+
+ SIMD_FORCE_INLINE void deSerializeFloat(const struct btVector3FloatData& dataIn);
+
+ SIMD_FORCE_INLINE void serializeDouble(struct btVector3DoubleData & dataOut) const;
+
+ SIMD_FORCE_INLINE void deSerializeDouble(const struct btVector3DoubleData& dataIn);
+};
+
+/**@brief Return the sum of two vectors (Point symantics)*/
+SIMD_FORCE_INLINE btVector3
+operator+(const btVector3& v1, const btVector3& v2)
+{
+ return btVector3(v1.m_floats[0] + v2.m_floats[0], v1.m_floats[1] + v2.m_floats[1], v1.m_floats[2] + v2.m_floats[2]);
+}
+
+/**@brief Return the elementwise product of two vectors */
+SIMD_FORCE_INLINE btVector3
+operator*(const btVector3& v1, const btVector3& v2)
+{
+ return btVector3(v1.m_floats[0] * v2.m_floats[0], v1.m_floats[1] * v2.m_floats[1], v1.m_floats[2] * v2.m_floats[2]);
+}
+
+/**@brief Return the difference between two vectors */
+SIMD_FORCE_INLINE btVector3
+operator-(const btVector3& v1, const btVector3& v2)
+{
+ return btVector3(v1.m_floats[0] - v2.m_floats[0], v1.m_floats[1] - v2.m_floats[1], v1.m_floats[2] - v2.m_floats[2]);
+}
+/**@brief Return the negative of the vector */
+SIMD_FORCE_INLINE btVector3
+operator-(const btVector3& v)
+{
+ return btVector3(-v.m_floats[0], -v.m_floats[1], -v.m_floats[2]);
+}
+
+/**@brief Return the vector scaled by s */
+SIMD_FORCE_INLINE btVector3
+operator*(const btVector3& v, const btScalar& s)
+{
+ return btVector3(v.m_floats[0] * s, v.m_floats[1] * s, v.m_floats[2] * s);
+}
+
+/**@brief Return the vector scaled by s */
+SIMD_FORCE_INLINE btVector3
+operator*(const btScalar& s, const btVector3& v)
+{
+ return v * s;
+}
+
+/**@brief Return the vector inversely scaled by s */
+SIMD_FORCE_INLINE btVector3
+operator/(const btVector3& v, const btScalar& s)
+{
+ btFullAssert(s != btScalar(0.0));
+ return v * (btScalar(1.0) / s);
+}
+
+/**@brief Return the vector inversely scaled by s */
+SIMD_FORCE_INLINE btVector3
+operator/(const btVector3& v1, const btVector3& v2)
+{
+ return btVector3(v1.m_floats[0] / v2.m_floats[0], v1.m_floats[1] / v2.m_floats[1], v1.m_floats[2] / v2.m_floats[2]);
+}
+
+/**@brief Return the dot product between two vectors */
+SIMD_FORCE_INLINE btScalar
+btDot(const btVector3& v1, const btVector3& v2)
+{
+ return v1.dot(v2);
+}
+
+/**@brief Return the distance squared between two vectors */
+SIMD_FORCE_INLINE btScalar
+btDistance2(const btVector3& v1, const btVector3& v2)
+{
+ return v1.distance2(v2);
+}
+
+/**@brief Return the distance between two vectors */
+SIMD_FORCE_INLINE btScalar
+btDistance(const btVector3& v1, const btVector3& v2)
+{
+ return v1.distance(v2);
+}
+
+/**@brief Return the angle between two vectors */
+SIMD_FORCE_INLINE btScalar
+btAngle(const btVector3& v1, const btVector3& v2)
+{
+ return v1.angle(v2);
+}
+
+/**@brief Return the cross product of two vectors */
+SIMD_FORCE_INLINE btVector3
+btCross(const btVector3& v1, const btVector3& v2)
+{
+ return v1.cross(v2);
+}
+
+SIMD_FORCE_INLINE btScalar
+btTriple(const btVector3& v1, const btVector3& v2, const btVector3& v3)
+{
+ return v1.triple(v2, v3);
+}
+
+/**@brief Return the linear interpolation between two vectors
+ * @param v1 One vector
+ * @param v2 The other vector
+ * @param t The ration of this to v (t = 0 => return v1, t=1 => return v2) */
+SIMD_FORCE_INLINE btVector3
+lerp(const btVector3& v1, const btVector3& v2, const btScalar& t)
+{
+ return v1.lerp(v2, t);
+}
+
+SIMD_FORCE_INLINE btScalar btVector3::distance2(const btVector3& v) const
+{
+ return (v - *this).length2();
+}
+
+SIMD_FORCE_INLINE btScalar btVector3::distance(const btVector3& v) const
+{
+ return (v - *this).length();
+}
+
+SIMD_FORCE_INLINE btVector3 btVector3::normalized() const
+{
+ return *this / length();
+}
+
+SIMD_FORCE_INLINE btVector3 btVector3::rotate(const btVector3& wAxis, const btScalar angle) const
+{
+ // wAxis must be a unit lenght vector
+
+ btVector3 o = wAxis * wAxis.dot(*this);
+ btVector3 x = *this - o;
+ btVector3 y;
+
+ y = wAxis.cross(*this);
+
+ return (o + x * btCos(angle) + y * btSin(angle));
+}
+
+class btVector4 : public btVector3 {
+public:
+ SIMD_FORCE_INLINE btVector4() {}
+
+ SIMD_FORCE_INLINE btVector4(const btScalar& x, const btScalar& y, const btScalar& z, const btScalar& w)
+ : btVector3(x, y, z)
+ {
+ m_floats[3] = w;
+ }
+
+ SIMD_FORCE_INLINE btVector4 absolute4() const
+ {
+ return btVector4(
+ btFabs(m_floats[0]),
+ btFabs(m_floats[1]),
+ btFabs(m_floats[2]),
+ btFabs(m_floats[3]));
+ }
+
+ btScalar getW() const { return m_floats[3]; }
+
+ SIMD_FORCE_INLINE int32_t maxAxis4() const
+ {
+ int32_t maxIndex = -1;
+ btScalar maxVal = btScalar(-BT_LARGE_FLOAT);
+ if (m_floats[0] > maxVal) {
+ maxIndex = 0;
+ maxVal = m_floats[0];
+ }
+ if (m_floats[1] > maxVal) {
+ maxIndex = 1;
+ maxVal = m_floats[1];
+ }
+ if (m_floats[2] > maxVal) {
+ maxIndex = 2;
+ maxVal = m_floats[2];
+ }
+ if (m_floats[3] > maxVal) {
+ maxIndex = 3;
+ }
+ return maxIndex;
+ }
+
+ SIMD_FORCE_INLINE int32_t minAxis4() const
+ {
+ int32_t minIndex = -1;
+ btScalar minVal = btScalar(BT_LARGE_FLOAT);
+ if (m_floats[0] < minVal) {
+ minIndex = 0;
+ minVal = m_floats[0];
+ }
+ if (m_floats[1] < minVal) {
+ minIndex = 1;
+ minVal = m_floats[1];
+ }
+ if (m_floats[2] < minVal) {
+ minIndex = 2;
+ minVal = m_floats[2];
+ }
+ if (m_floats[3] < minVal) {
+ minIndex = 3;
+ }
+
+ return minIndex;
+ }
+
+ SIMD_FORCE_INLINE int32_t closestAxis4() const
+ {
+ return absolute4().maxAxis4();
+ }
+
+ /**@brief Set x,y,z and zero w
+ * @param x Value of x
+ * @param y Value of y
+ * @param z Value of z
+ */
+
+ /* void getValue(btScalar *m) const
+ {
+ m[0] = m_floats[0];
+ m[1] = m_floats[1];
+ m[2] =m_floats[2];
+ }
+*/
+ /**@brief Set the values
+ * @param x Value of x
+ * @param y Value of y
+ * @param z Value of z
+ * @param w Value of w
+ */
+ SIMD_FORCE_INLINE void setValue(const btScalar& x, const btScalar& y, const btScalar& z, const btScalar& w)
+ {
+ m_floats[0] = x;
+ m_floats[1] = y;
+ m_floats[2] = z;
+ m_floats[3] = w;
+ }
+};
+
+///btSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization
+SIMD_FORCE_INLINE void btSwapScalarEndian(const btScalar& sourceVal, btScalar& destVal)
+{
+#ifdef BT_USE_DOUBLE_PRECISION
+ unsigned char* dest = (unsigned char*)&destVal;
+ unsigned char* src = (unsigned char*)&sourceVal;
+ dest[0] = src[7];
+ dest[1] = src[6];
+ dest[2] = src[5];
+ dest[3] = src[4];
+ dest[4] = src[3];
+ dest[5] = src[2];
+ dest[6] = src[1];
+ dest[7] = src[0];
+#else
+ unsigned char* dest = (unsigned char*)&destVal;
+ unsigned char* src = (unsigned char*)&sourceVal;
+ dest[0] = src[3];
+ dest[1] = src[2];
+ dest[2] = src[1];
+ dest[3] = src[0];
+#endif //BT_USE_DOUBLE_PRECISION
+}
+///btSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization
+SIMD_FORCE_INLINE void btSwapVector3Endian(const btVector3& sourceVec, btVector3& destVec)
+{
+ for (int32_t i = 0; i < 4; i++) {
+ btSwapScalarEndian(sourceVec[i], destVec[i]);
+ }
+}
+
+///btUnSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization
+SIMD_FORCE_INLINE void btUnSwapVector3Endian(btVector3& vector)
+{
+
+ btVector3 swappedVec;
+ for (int32_t i = 0; i < 4; i++) {
+ btSwapScalarEndian(vector[i], swappedVec[i]);
+ }
+ vector = swappedVec;
+}
+
+template <class T>
+SIMD_FORCE_INLINE void btPlaneSpace1(const T& n, T& p, T& q)
+{
+ if (btFabs(n[2]) > SIMDSQRT12) {
+ // choose p in y-z plane
+ btScalar a = n[1] * n[1] + n[2] * n[2];
+ btScalar k = btRecipSqrt(a);
+ p[0] = 0;
+ p[1] = -n[2] * k;
+ p[2] = n[1] * k;
+ // set q = n x p
+ q[0] = a * k;
+ q[1] = -n[0] * p[2];
+ q[2] = n[0] * p[1];
+ }
+ else {
+ // choose p in x-y plane
+ btScalar a = n[0] * n[0] + n[1] * n[1];
+ btScalar k = btRecipSqrt(a);
+ p[0] = -n[1] * k;
+ p[1] = n[0] * k;
+ p[2] = 0;
+ // set q = n x p
+ q[0] = -n[2] * p[1];
+ q[1] = n[2] * p[0];
+ q[2] = a * k;
+ }
+}
+
+struct btVector3FloatData {
+ float m_floats[4];
+};
+
+struct btVector3DoubleData {
+ double m_floats[4];
+};
+
+SIMD_FORCE_INLINE void btVector3::serializeFloat(struct btVector3FloatData& dataOut) const
+{
+ ///could also do a memcpy, check if it is worth it
+ for (int32_t i = 0; i < 4; i++)
+ dataOut.m_floats[i] = float(m_floats[i]);
+}
+
+SIMD_FORCE_INLINE void btVector3::deSerializeFloat(const struct btVector3FloatData& dataIn)
+{
+ for (int32_t i = 0; i < 4; i++)
+ m_floats[i] = btScalar(dataIn.m_floats[i]);
+}
+
+SIMD_FORCE_INLINE void btVector3::serializeDouble(struct btVector3DoubleData& dataOut) const
+{
+ ///could also do a memcpy, check if it is worth it
+ for (int32_t i = 0; i < 4; i++)
+ dataOut.m_floats[i] = double(m_floats[i]);
+}
+
+SIMD_FORCE_INLINE void btVector3::deSerializeDouble(const struct btVector3DoubleData& dataIn)
+{
+ for (int32_t i = 0; i < 4; i++)
+ m_floats[i] = btScalar(dataIn.m_floats[i]);
+}
+
+SIMD_FORCE_INLINE void btVector3::serialize(struct btVector3Data& dataOut) const
+{
+ ///could also do a memcpy, check if it is worth it
+ for (int32_t i = 0; i < 4; i++)
+ dataOut.m_floats[i] = m_floats[i];
+}
+
+SIMD_FORCE_INLINE void btVector3::deSerialize(const struct btVector3Data& dataIn)
+{
+ for (int32_t i = 0; i < 4; i++)
+ m_floats[i] = dataIn.m_floats[i];
+}
+
+// -- GODOT start --
+}; // namespace VHACD
+// -- GODOT end --
+
+#endif //BT_VECTOR3_H
diff --git a/thirdparty/vhacd/inc/vhacdCircularList.h b/thirdparty/vhacd/inc/vhacdCircularList.h
new file mode 100644
index 0000000000..0f5ddf9ecf
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdCircularList.h
@@ -0,0 +1,79 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#pragma once
+#ifndef VHACD_CIRCULAR_LIST_H
+#define VHACD_CIRCULAR_LIST_H
+#include <stdlib.h>
+namespace VHACD {
+//! CircularListElement class.
+template <typename T>
+class CircularListElement {
+public:
+ T& GetData() { return m_data; }
+ const T& GetData() const { return m_data; }
+ CircularListElement<T>*& GetNext() { return m_next; }
+ CircularListElement<T>*& GetPrev() { return m_prev; }
+ const CircularListElement<T>*& GetNext() const { return m_next; }
+ const CircularListElement<T>*& GetPrev() const { return m_prev; }
+ //! Constructor
+ CircularListElement(const T& data) { m_data = data; }
+ CircularListElement(void) {}
+ //! Destructor
+ ~CircularListElement(void) {}
+private:
+ T m_data;
+ CircularListElement<T>* m_next;
+ CircularListElement<T>* m_prev;
+
+ CircularListElement(const CircularListElement& rhs);
+};
+//! CircularList class.
+template <typename T>
+class CircularList {
+public:
+ CircularListElement<T>*& GetHead() { return m_head; }
+ const CircularListElement<T>* GetHead() const { return m_head; }
+ bool IsEmpty() const { return (m_size == 0); }
+ size_t GetSize() const { return m_size; }
+ const T& GetData() const { return m_head->GetData(); }
+ T& GetData() { return m_head->GetData(); }
+ bool Delete();
+ bool Delete(CircularListElement<T>* element);
+ CircularListElement<T>* Add(const T* data = 0);
+ CircularListElement<T>* Add(const T& data);
+ bool Next();
+ bool Prev();
+ void Clear()
+ {
+ while (Delete())
+ ;
+ };
+ const CircularList& operator=(const CircularList& rhs);
+ //! Constructor
+ CircularList()
+ {
+ m_head = 0;
+ m_size = 0;
+ }
+ CircularList(const CircularList& rhs);
+ //! Destructor
+ ~CircularList(void) { Clear(); };
+private:
+ CircularListElement<T>* m_head; //!< a pointer to the head of the circular list
+ size_t m_size; //!< number of element in the circular list
+};
+}
+#include "vhacdCircularList.inl"
+#endif // VHACD_CIRCULAR_LIST_H \ No newline at end of file
diff --git a/thirdparty/vhacd/inc/vhacdCircularList.inl b/thirdparty/vhacd/inc/vhacdCircularList.inl
new file mode 100644
index 0000000000..2be5180524
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdCircularList.inl
@@ -0,0 +1,161 @@
+#pragma once
+#ifndef HACD_CIRCULAR_LIST_INL
+#define HACD_CIRCULAR_LIST_INL
+namespace VHACD
+{
+ template < typename T >
+ inline bool CircularList<T>::Delete(CircularListElement<T> * element)
+ {
+ if (!element)
+ {
+ return false;
+ }
+ if (m_size > 1)
+ {
+ CircularListElement<T> * next = element->GetNext();
+ CircularListElement<T> * prev = element->GetPrev();
+ delete element;
+ m_size--;
+ if (element == m_head)
+ {
+ m_head = next;
+ }
+ next->GetPrev() = prev;
+ prev->GetNext() = next;
+ return true;
+ }
+ else if (m_size == 1)
+ {
+ delete m_head;
+ m_size--;
+ m_head = 0;
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ template < typename T >
+ inline bool CircularList<T>::Delete()
+ {
+ if (m_size > 1)
+ {
+ CircularListElement<T> * next = m_head->GetNext();
+ CircularListElement<T> * prev = m_head->GetPrev();
+ delete m_head;
+ m_size--;
+ m_head = next;
+ next->GetPrev() = prev;
+ prev->GetNext() = next;
+ return true;
+ }
+ else if (m_size == 1)
+ {
+ delete m_head;
+ m_size--;
+ m_head = 0;
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ template < typename T >
+ inline CircularListElement<T> * CircularList<T>::Add(const T * data)
+ {
+ if (m_size == 0)
+ {
+ if (data)
+ {
+ m_head = new CircularListElement<T>(*data);
+ }
+ else
+ {
+ m_head = new CircularListElement<T>();
+ }
+ m_head->GetNext() = m_head->GetPrev() = m_head;
+ }
+ else
+ {
+ CircularListElement<T> * next = m_head->GetNext();
+ CircularListElement<T> * element = m_head;
+ if (data)
+ {
+ m_head = new CircularListElement<T>(*data);
+ }
+ else
+ {
+ m_head = new CircularListElement<T>();
+ }
+ m_head->GetNext() = next;
+ m_head->GetPrev() = element;
+ element->GetNext() = m_head;
+ next->GetPrev() = m_head;
+ }
+ m_size++;
+ return m_head;
+ }
+ template < typename T >
+ inline CircularListElement<T> * CircularList<T>::Add(const T & data)
+ {
+ const T * pData = &data;
+ return Add(pData);
+ }
+ template < typename T >
+ inline bool CircularList<T>::Next()
+ {
+ if (m_size == 0)
+ {
+ return false;
+ }
+ m_head = m_head->GetNext();
+ return true;
+ }
+ template < typename T >
+ inline bool CircularList<T>::Prev()
+ {
+ if (m_size == 0)
+ {
+ return false;
+ }
+ m_head = m_head->GetPrev();
+ return true;
+ }
+ template < typename T >
+ inline CircularList<T>::CircularList(const CircularList& rhs)
+ {
+ if (rhs.m_size > 0)
+ {
+ CircularListElement<T> * current = rhs.m_head;
+ do
+ {
+ current = current->GetNext();
+ Add(current->GetData());
+ }
+ while ( current != rhs.m_head );
+ }
+ }
+ template < typename T >
+ inline const CircularList<T>& CircularList<T>::operator=(const CircularList& rhs)
+ {
+ if (&rhs != this)
+ {
+ Clear();
+ if (rhs.m_size > 0)
+ {
+ CircularListElement<T> * current = rhs.m_head;
+ do
+ {
+ current = current->GetNext();
+ Add(current->GetData());
+ }
+ while ( current != rhs.m_head );
+ }
+ }
+ return (*this);
+ }
+}
+#endif \ No newline at end of file
diff --git a/thirdparty/vhacd/inc/vhacdICHull.h b/thirdparty/vhacd/inc/vhacdICHull.h
new file mode 100644
index 0000000000..132bdcfb3e
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdICHull.h
@@ -0,0 +1,98 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#pragma once
+#ifndef VHACD_ICHULL_H
+#define VHACD_ICHULL_H
+#include "vhacdManifoldMesh.h"
+#include "vhacdVector.h"
+
+namespace VHACD {
+//! Incremental Convex Hull algorithm (cf. http://cs.smith.edu/~orourke/books/ftp.html ).
+enum ICHullError {
+ ICHullErrorOK = 0,
+ ICHullErrorCoplanarPoints,
+ ICHullErrorNoVolume,
+ ICHullErrorInconsistent,
+ ICHullErrorNotEnoughPoints
+};
+class ICHull {
+public:
+ static const double sc_eps;
+ //!
+ bool IsFlat() { return m_isFlat; }
+ //! Returns the computed mesh
+ TMMesh& GetMesh() { return m_mesh; }
+ //! Add one point to the convex-hull
+ bool AddPoint(const Vec3<double>& point) { return AddPoints(&point, 1); }
+ //! Add one point to the convex-hull
+ bool AddPoint(const Vec3<double>& point, int32_t id);
+ //! Add points to the convex-hull
+ bool AddPoints(const Vec3<double>* points, size_t nPoints);
+ //!
+ ICHullError Process();
+ //!
+ ICHullError Process(const uint32_t nPointsCH, const double minVolume = 0.0);
+ //!
+ bool IsInside(const Vec3<double>& pt0, const double eps = 0.0);
+ //!
+ const ICHull& operator=(ICHull& rhs);
+
+ //! Constructor
+ ICHull();
+ //! Destructor
+ ~ICHull(void){};
+
+private:
+ //! DoubleTriangle builds the initial double triangle. It first finds 3 noncollinear points and makes two faces out of them, in opposite order. It then finds a fourth point that is not coplanar with that face. The vertices are stored in the face structure in counterclockwise order so that the volume between the face and the point is negative. Lastly, the 3 newfaces to the fourth point are constructed and the data structures are cleaned up.
+ ICHullError DoubleTriangle();
+ //! MakeFace creates a new face structure from three vertices (in ccw order). It returns a pointer to the face.
+ CircularListElement<TMMTriangle>* MakeFace(CircularListElement<TMMVertex>* v0,
+ CircularListElement<TMMVertex>* v1,
+ CircularListElement<TMMVertex>* v2,
+ CircularListElement<TMMTriangle>* fold);
+ //!
+ CircularListElement<TMMTriangle>* MakeConeFace(CircularListElement<TMMEdge>* e, CircularListElement<TMMVertex>* v);
+ //!
+ bool ProcessPoint();
+ //!
+ bool ComputePointVolume(double& totalVolume, bool markVisibleFaces);
+ //!
+ bool FindMaxVolumePoint(const double minVolume = 0.0);
+ //!
+ bool CleanEdges();
+ //!
+ bool CleanVertices(uint32_t& addedPoints);
+ //!
+ bool CleanTriangles();
+ //!
+ bool CleanUp(uint32_t& addedPoints);
+ //!
+ bool MakeCCW(CircularListElement<TMMTriangle>* f,
+ CircularListElement<TMMEdge>* e,
+ CircularListElement<TMMVertex>* v);
+ void Clear();
+
+private:
+ static const int32_t sc_dummyIndex;
+ TMMesh m_mesh;
+ SArray<CircularListElement<TMMEdge>*> m_edgesToDelete;
+ SArray<CircularListElement<TMMEdge>*> m_edgesToUpdate;
+ SArray<CircularListElement<TMMTriangle>*> m_trianglesToDelete;
+ Vec3<double> m_normal;
+ bool m_isFlat;
+ ICHull(const ICHull& rhs);
+};
+}
+#endif // VHACD_ICHULL_H
diff --git a/thirdparty/vhacd/inc/vhacdManifoldMesh.h b/thirdparty/vhacd/inc/vhacdManifoldMesh.h
new file mode 100644
index 0000000000..a48f53c5c5
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdManifoldMesh.h
@@ -0,0 +1,142 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+*/
+#pragma once
+#ifndef VHACD_MANIFOLD_MESH_H
+#define VHACD_MANIFOLD_MESH_H
+#include "vhacdCircularList.h"
+#include "vhacdSArray.h"
+#include "vhacdVector.h"
+namespace VHACD {
+class TMMTriangle;
+class TMMEdge;
+class TMMesh;
+class ICHull;
+
+//! Vertex data structure used in a triangular manifold mesh (TMM).
+class TMMVertex {
+public:
+ void Initialize();
+ TMMVertex(void);
+ ~TMMVertex(void);
+
+private:
+ Vec3<double> m_pos;
+ int32_t m_name;
+ size_t m_id;
+ CircularListElement<TMMEdge>* m_duplicate; // pointer to incident cone edge (or NULL)
+ bool m_onHull;
+ bool m_tag;
+ TMMVertex(const TMMVertex& rhs);
+ friend class ICHull;
+ friend class TMMesh;
+ friend class TMMTriangle;
+ friend class TMMEdge;
+};
+
+//! Edge data structure used in a triangular manifold mesh (TMM).
+class TMMEdge {
+public:
+ void Initialize();
+ TMMEdge(void);
+ ~TMMEdge(void);
+
+private:
+ size_t m_id;
+ CircularListElement<TMMTriangle>* m_triangles[2];
+ CircularListElement<TMMVertex>* m_vertices[2];
+ CircularListElement<TMMTriangle>* m_newFace;
+ TMMEdge(const TMMEdge& rhs);
+ friend class ICHull;
+ friend class TMMTriangle;
+ friend class TMMVertex;
+ friend class TMMesh;
+};
+
+//! Triangle data structure used in a triangular manifold mesh (TMM).
+class TMMTriangle {
+public:
+ void Initialize();
+ TMMTriangle(void);
+ ~TMMTriangle(void);
+
+private:
+ size_t m_id;
+ CircularListElement<TMMEdge>* m_edges[3];
+ CircularListElement<TMMVertex>* m_vertices[3];
+ bool m_visible;
+
+ TMMTriangle(const TMMTriangle& rhs);
+ friend class ICHull;
+ friend class TMMesh;
+ friend class TMMVertex;
+ friend class TMMEdge;
+};
+//! triangular manifold mesh data structure.
+class TMMesh {
+public:
+ //! Returns the number of vertices>
+ inline size_t GetNVertices() const { return m_vertices.GetSize(); }
+ //! Returns the number of edges
+ inline size_t GetNEdges() const { return m_edges.GetSize(); }
+ //! Returns the number of triangles
+ inline size_t GetNTriangles() const { return m_triangles.GetSize(); }
+ //! Returns the vertices circular list
+ inline const CircularList<TMMVertex>& GetVertices() const { return m_vertices; }
+ //! Returns the edges circular list
+ inline const CircularList<TMMEdge>& GetEdges() const { return m_edges; }
+ //! Returns the triangles circular list
+ inline const CircularList<TMMTriangle>& GetTriangles() const { return m_triangles; }
+ //! Returns the vertices circular list
+ inline CircularList<TMMVertex>& GetVertices() { return m_vertices; }
+ //! Returns the edges circular list
+ inline CircularList<TMMEdge>& GetEdges() { return m_edges; }
+ //! Returns the triangles circular list
+ inline CircularList<TMMTriangle>& GetTriangles() { return m_triangles; }
+ //! Add vertex to the mesh
+ CircularListElement<TMMVertex>* AddVertex() { return m_vertices.Add(); }
+ //! Add vertex to the mesh
+ CircularListElement<TMMEdge>* AddEdge() { return m_edges.Add(); }
+ //! Add vertex to the mesh
+ CircularListElement<TMMTriangle>* AddTriangle() { return m_triangles.Add(); }
+ //! Print mesh information
+ void Print();
+ //!
+ void GetIFS(Vec3<double>* const points, Vec3<int32_t>* const triangles);
+ //!
+ void Clear();
+ //!
+ void Copy(TMMesh& mesh);
+ //!
+ bool CheckConsistancy();
+ //!
+ bool Normalize();
+ //!
+ bool Denormalize();
+ //! Constructor
+ TMMesh();
+ //! Destructor
+ virtual ~TMMesh(void);
+
+private:
+ CircularList<TMMVertex> m_vertices;
+ CircularList<TMMEdge> m_edges;
+ CircularList<TMMTriangle> m_triangles;
+
+ // not defined
+ TMMesh(const TMMesh& rhs);
+ friend class ICHull;
+};
+}
+#endif // VHACD_MANIFOLD_MESH_H \ No newline at end of file
diff --git a/thirdparty/vhacd/inc/vhacdMesh.h b/thirdparty/vhacd/inc/vhacdMesh.h
new file mode 100644
index 0000000000..a282e2b4fb
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdMesh.h
@@ -0,0 +1,130 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#pragma once
+#ifndef VHACD_MESH_H
+#define VHACD_MESH_H
+#include "vhacdSArray.h"
+#include "vhacdVector.h"
+
+#define VHACD_DEBUG_MESH
+
+namespace VHACD {
+enum AXIS {
+ AXIS_X = 0,
+ AXIS_Y = 1,
+ AXIS_Z = 2
+};
+struct Plane {
+ double m_a;
+ double m_b;
+ double m_c;
+ double m_d;
+ AXIS m_axis;
+ short m_index;
+};
+#ifdef VHACD_DEBUG_MESH
+struct Material {
+
+ Vec3<double> m_diffuseColor;
+ double m_ambientIntensity;
+ Vec3<double> m_specularColor;
+ Vec3<double> m_emissiveColor;
+ double m_shininess;
+ double m_transparency;
+ Material(void)
+ {
+ m_diffuseColor.X() = 0.5;
+ m_diffuseColor.Y() = 0.5;
+ m_diffuseColor.Z() = 0.5;
+ m_specularColor.X() = 0.5;
+ m_specularColor.Y() = 0.5;
+ m_specularColor.Z() = 0.5;
+ m_ambientIntensity = 0.4;
+ m_emissiveColor.X() = 0.0;
+ m_emissiveColor.Y() = 0.0;
+ m_emissiveColor.Z() = 0.0;
+ m_shininess = 0.4;
+ m_transparency = 0.0;
+ };
+};
+#endif // VHACD_DEBUG_MESH
+
+//! Triangular mesh data structure
+class Mesh {
+public:
+ void AddPoint(const Vec3<double>& pt) { m_points.PushBack(pt); };
+ void SetPoint(size_t index, const Vec3<double>& pt) { m_points[index] = pt; };
+ const Vec3<double>& GetPoint(size_t index) const { return m_points[index]; };
+ Vec3<double>& GetPoint(size_t index) { return m_points[index]; };
+ size_t GetNPoints() const { return m_points.Size(); };
+ double* GetPoints() { return (double*)m_points.Data(); } // ugly
+ const double* const GetPoints() const { return (double*)m_points.Data(); } // ugly
+ const Vec3<double>* const GetPointsBuffer() const { return m_points.Data(); } //
+ Vec3<double>* const GetPointsBuffer() { return m_points.Data(); } //
+ void AddTriangle(const Vec3<int32_t>& tri) { m_triangles.PushBack(tri); };
+ void SetTriangle(size_t index, const Vec3<int32_t>& tri) { m_triangles[index] = tri; };
+ const Vec3<int32_t>& GetTriangle(size_t index) const { return m_triangles[index]; };
+ Vec3<int32_t>& GetTriangle(size_t index) { return m_triangles[index]; };
+ size_t GetNTriangles() const { return m_triangles.Size(); };
+ int32_t* GetTriangles() { return (int32_t*)m_triangles.Data(); } // ugly
+ const int32_t* const GetTriangles() const { return (int32_t*)m_triangles.Data(); } // ugly
+ const Vec3<int32_t>* const GetTrianglesBuffer() const { return m_triangles.Data(); }
+ Vec3<int32_t>* const GetTrianglesBuffer() { return m_triangles.Data(); }
+ const Vec3<double>& GetCenter() const { return m_center; }
+ const Vec3<double>& GetMinBB() const { return m_minBB; }
+ const Vec3<double>& GetMaxBB() const { return m_maxBB; }
+ void ClearPoints() { m_points.Clear(); }
+ void ClearTriangles() { m_triangles.Clear(); }
+ void Clear()
+ {
+ ClearPoints();
+ ClearTriangles();
+ }
+ void ResizePoints(size_t nPts) { m_points.Resize(nPts); }
+ void ResizeTriangles(size_t nTri) { m_triangles.Resize(nTri); }
+ void CopyPoints(SArray<Vec3<double> >& points) const { points = m_points; }
+ double GetDiagBB() const { return m_diag; }
+ double ComputeVolume() const;
+ void ComputeConvexHull(const double* const pts,
+ const size_t nPts);
+ void Clip(const Plane& plane,
+ SArray<Vec3<double> >& positivePart,
+ SArray<Vec3<double> >& negativePart) const;
+ bool IsInside(const Vec3<double>& pt) const;
+ double ComputeDiagBB();
+ Vec3<double> &ComputeCenter(void);
+
+#ifdef VHACD_DEBUG_MESH
+ bool LoadOFF(const std::string& fileName, bool invert);
+ bool SaveVRML2(const std::string& fileName) const;
+ bool SaveVRML2(std::ofstream& fout, const Material& material) const;
+ bool SaveOFF(const std::string& fileName) const;
+#endif // VHACD_DEBUG_MESH
+
+ //! Constructor.
+ Mesh();
+ //! Destructor.
+ ~Mesh(void);
+
+private:
+ SArray<Vec3<double> > m_points;
+ SArray<Vec3<int32_t> > m_triangles;
+ Vec3<double> m_minBB;
+ Vec3<double> m_maxBB;
+ Vec3<double> m_center;
+ double m_diag;
+};
+}
+#endif \ No newline at end of file
diff --git a/thirdparty/vhacd/inc/vhacdMutex.h b/thirdparty/vhacd/inc/vhacdMutex.h
new file mode 100644
index 0000000000..6b09259200
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdMutex.h
@@ -0,0 +1,148 @@
+/*!
+**
+** Copyright (c) 2009 by John W. Ratcliff mailto:jratcliffscarab@gmail.com
+**
+** Portions of this source has been released with the PhysXViewer application, as well as
+** Rocket, CreateDynamics, ODF, and as a number of sample code snippets.
+**
+** If you find this code useful or you are feeling particularily generous I would
+** ask that you please go to http://www.amillionpixels.us and make a donation
+** to Troy DeMolay.
+**
+** DeMolay is a youth group for young men between the ages of 12 and 21.
+** It teaches strong moral principles, as well as leadership skills and
+** public speaking. The donations page uses the 'pay for pixels' paradigm
+** where, in this case, a pixel is only a single penny. Donations can be
+** made for as small as $4 or as high as a $100 block. Each person who donates
+** will get a link to their own site as well as acknowledgement on the
+** donations blog located here http://www.amillionpixels.blogspot.com/
+**
+** If you wish to contact me you can use the following methods:
+**
+** Skype ID: jratcliff63367
+** Yahoo: jratcliff63367
+** AOL: jratcliff1961
+** email: jratcliffscarab@gmail.com
+**
+**
+** The MIT license:
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is furnished
+** to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in all
+** copies or substantial portions of the Software.
+
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+*/
+
+#pragma once
+#ifndef VHACD_MUTEX_H
+#define VHACD_MUTEX_H
+
+#if defined(WIN32)
+
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT 0x400
+#endif
+#include <windows.h>
+#pragma comment(lib, "winmm.lib")
+#endif
+
+#if defined(__linux__)
+//#include <sys/time.h>
+#include <errno.h>
+#include <time.h>
+#include <unistd.h>
+#define __stdcall
+#endif
+
+#if defined(__APPLE__) || defined(__linux__)
+#include <pthread.h>
+#endif
+
+#if defined(__APPLE__)
+#define PTHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE
+#endif
+
+#define VHACD_DEBUG
+
+//#define VHACD_NDEBUG
+#ifdef VHACD_NDEBUG
+#define VHACD_VERIFY(x) (x)
+#else
+#define VHACD_VERIFY(x) assert((x))
+#endif
+
+namespace VHACD {
+class Mutex {
+public:
+ Mutex(void)
+ {
+#if defined(WIN32) || defined(_XBOX)
+ InitializeCriticalSection(&m_mutex);
+#elif defined(__APPLE__) || defined(__linux__)
+ pthread_mutexattr_t mutexAttr; // Mutex Attribute
+ VHACD_VERIFY(pthread_mutexattr_init(&mutexAttr) == 0);
+ VHACD_VERIFY(pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE_NP) == 0);
+ VHACD_VERIFY(pthread_mutex_init(&m_mutex, &mutexAttr) == 0);
+ VHACD_VERIFY(pthread_mutexattr_destroy(&mutexAttr) == 0);
+#endif
+ }
+ ~Mutex(void)
+ {
+#if defined(WIN32) || defined(_XBOX)
+ DeleteCriticalSection(&m_mutex);
+#elif defined(__APPLE__) || defined(__linux__)
+ VHACD_VERIFY(pthread_mutex_destroy(&m_mutex) == 0);
+#endif
+ }
+ void Lock(void)
+ {
+#if defined(WIN32) || defined(_XBOX)
+ EnterCriticalSection(&m_mutex);
+#elif defined(__APPLE__) || defined(__linux__)
+ VHACD_VERIFY(pthread_mutex_lock(&m_mutex) == 0);
+#endif
+ }
+ bool TryLock(void)
+ {
+#if defined(WIN32) || defined(_XBOX)
+ bool bRet = false;
+ //assert(("TryEnterCriticalSection seems to not work on XP???", 0));
+ bRet = TryEnterCriticalSection(&m_mutex) ? true : false;
+ return bRet;
+#elif defined(__APPLE__) || defined(__linux__)
+ int32_t result = pthread_mutex_trylock(&m_mutex);
+ return (result == 0);
+#endif
+ }
+
+ void Unlock(void)
+ {
+#if defined(WIN32) || defined(_XBOX)
+ LeaveCriticalSection(&m_mutex);
+#elif defined(__APPLE__) || defined(__linux__)
+ VHACD_VERIFY(pthread_mutex_unlock(&m_mutex) == 0);
+#endif
+ }
+
+private:
+#if defined(WIN32) || defined(_XBOX)
+ CRITICAL_SECTION m_mutex;
+#elif defined(__APPLE__) || defined(__linux__)
+ pthread_mutex_t m_mutex;
+#endif
+};
+}
+#endif // VHACD_MUTEX_H
diff --git a/thirdparty/vhacd/inc/vhacdRaycastMesh.h b/thirdparty/vhacd/inc/vhacdRaycastMesh.h
new file mode 100644
index 0000000000..93bf299c07
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdRaycastMesh.h
@@ -0,0 +1,39 @@
+#ifndef RAYCAST_MESH_H
+
+#define RAYCAST_MESH_H
+
+#include <stdint.h>
+
+namespace VHACD
+{
+
+ // Very simple brute force raycast against a triangle mesh. Tests every triangle; no hierachy.
+ // Does a deep copy, always does calculations with full double float precision
+ class RaycastMesh
+ {
+ public:
+ static RaycastMesh * createRaycastMesh(uint32_t vcount, // The number of vertices in the source triangle mesh
+ const double *vertices, // The array of vertex positions in the format x1,y1,z1..x2,y2,z2.. etc.
+ uint32_t tcount, // The number of triangles in the source triangle mesh
+ const uint32_t *indices); // The triangle indices in the format of i1,i2,i3 ... i4,i5,i6, ...
+
+ static RaycastMesh * createRaycastMesh(uint32_t vcount, // The number of vertices in the source triangle mesh
+ const float *vertices, // The array of vertex positions in the format x1,y1,z1..x2,y2,z2.. etc.
+ uint32_t tcount, // The number of triangles in the source triangle mesh
+ const uint32_t *indices); // The triangle indices in the format of i1,i2,i3 ... i4,i5,i6, ...
+
+
+ virtual bool raycast(const double *from, // The starting point of the raycast
+ const double *to, // The ending point of the raycast
+ const double *closestToPoint, // The point to match the nearest hit location (can just be the 'from' location of no specific point)
+ double *hitLocation, // The point where the ray hit nearest to the 'closestToPoint' location
+ double *hitDistance) = 0; // The distance the ray traveled to the hit location
+
+ virtual void release(void) = 0;
+ protected:
+ virtual ~RaycastMesh(void) { };
+ };
+
+} // end of VHACD namespace
+
+#endif
diff --git a/thirdparty/vhacd/inc/vhacdSArray.h b/thirdparty/vhacd/inc/vhacdSArray.h
new file mode 100644
index 0000000000..4d84d1ae26
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdSArray.h
@@ -0,0 +1,158 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#pragma once
+#ifndef VHACD_SARRAY_H
+#define VHACD_SARRAY_H
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define SARRAY_DEFAULT_MIN_SIZE 16
+
+namespace VHACD {
+//! SArray.
+template <typename T, size_t N = 64>
+class SArray {
+public:
+ T& operator[](size_t i)
+ {
+ T* const data = Data();
+ return data[i];
+ }
+ const T& operator[](size_t i) const
+ {
+ const T* const data = Data();
+ return data[i];
+ }
+ size_t Size() const
+ {
+ return m_size;
+ }
+ T* const Data()
+ {
+ return (m_maxSize == N) ? m_data0 : m_data;
+ }
+ const T* const Data() const
+ {
+ return (m_maxSize == N) ? m_data0 : m_data;
+ }
+ void Clear()
+ {
+ m_size = 0;
+ delete[] m_data;
+ m_data = 0;
+ m_maxSize = N;
+ }
+ void PopBack()
+ {
+ --m_size;
+ }
+ void Allocate(size_t size)
+ {
+ if (size > m_maxSize) {
+ T* temp = new T[size];
+ memcpy(temp, Data(), m_size * sizeof(T));
+ delete[] m_data;
+ m_data = temp;
+ m_maxSize = size;
+ }
+ }
+ void Resize(size_t size)
+ {
+ Allocate(size);
+ m_size = size;
+ }
+
+ void PushBack(const T& value)
+ {
+ if (m_size == m_maxSize) {
+ size_t maxSize = (m_maxSize << 1);
+ T* temp = new T[maxSize];
+ memcpy(temp, Data(), m_maxSize * sizeof(T));
+ delete[] m_data;
+ m_data = temp;
+ m_maxSize = maxSize;
+ }
+ T* const data = Data();
+ data[m_size++] = value;
+ }
+ bool Find(const T& value, size_t& pos)
+ {
+ T* const data = Data();
+ for (pos = 0; pos < m_size; ++pos)
+ if (value == data[pos])
+ return true;
+ return false;
+ }
+ bool Insert(const T& value)
+ {
+ size_t pos;
+ if (Find(value, pos))
+ return false;
+ PushBack(value);
+ return true;
+ }
+ bool Erase(const T& value)
+ {
+ size_t pos;
+ T* const data = Data();
+ if (Find(value, pos)) {
+ for (size_t j = pos + 1; j < m_size; ++j)
+ data[j - 1] = data[j];
+ --m_size;
+ return true;
+ }
+ return false;
+ }
+ void operator=(const SArray& rhs)
+ {
+ if (m_maxSize < rhs.m_size) {
+ delete[] m_data;
+ m_maxSize = rhs.m_maxSize;
+ m_data = new T[m_maxSize];
+ }
+ m_size = rhs.m_size;
+ memcpy(Data(), rhs.Data(), m_size * sizeof(T));
+ }
+ void Initialize()
+ {
+ m_data = 0;
+ m_size = 0;
+ m_maxSize = N;
+ }
+ SArray(const SArray& rhs)
+ {
+ m_data = 0;
+ m_size = 0;
+ m_maxSize = N;
+ *this = rhs;
+ }
+ SArray()
+ {
+ Initialize();
+ }
+ ~SArray()
+ {
+ delete[] m_data;
+ }
+
+private:
+ T m_data0[N];
+ T* m_data;
+ size_t m_size;
+ size_t m_maxSize;
+};
+}
+#endif \ No newline at end of file
diff --git a/thirdparty/vhacd/inc/vhacdTimer.h b/thirdparty/vhacd/inc/vhacdTimer.h
new file mode 100644
index 0000000000..ba0e2c3364
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdTimer.h
@@ -0,0 +1,121 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#pragma once
+#ifndef VHACD_TIMER_H
+#define VHACD_TIMER_H
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
+#endif
+#include <windows.h>
+#elif __MACH__
+#include <mach/clock.h>
+#include <mach/mach.h>
+#else
+#include <sys/time.h>
+#include <time.h>
+#endif
+
+namespace VHACD {
+#ifdef _WIN32
+class Timer {
+public:
+ Timer(void)
+ {
+ m_start.QuadPart = 0;
+ m_stop.QuadPart = 0;
+ QueryPerformanceFrequency(&m_freq);
+ };
+ ~Timer(void){};
+ void Tic()
+ {
+ QueryPerformanceCounter(&m_start);
+ }
+ void Toc()
+ {
+ QueryPerformanceCounter(&m_stop);
+ }
+ double GetElapsedTime() // in ms
+ {
+ LARGE_INTEGER delta;
+ delta.QuadPart = m_stop.QuadPart - m_start.QuadPart;
+ return (1000.0 * delta.QuadPart) / (double)m_freq.QuadPart;
+ }
+
+private:
+ LARGE_INTEGER m_start;
+ LARGE_INTEGER m_stop;
+ LARGE_INTEGER m_freq;
+};
+
+#elif __MACH__
+class Timer {
+public:
+ Timer(void)
+ {
+ memset(this, 0, sizeof(Timer));
+ host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &m_cclock);
+ };
+ ~Timer(void)
+ {
+ mach_port_deallocate(mach_task_self(), m_cclock);
+ };
+ void Tic()
+ {
+ clock_get_time(m_cclock, &m_start);
+ }
+ void Toc()
+ {
+ clock_get_time(m_cclock, &m_stop);
+ }
+ double GetElapsedTime() // in ms
+ {
+ return 1000.0 * (m_stop.tv_sec - m_start.tv_sec + (1.0E-9) * (m_stop.tv_nsec - m_start.tv_nsec));
+ }
+
+private:
+ clock_serv_t m_cclock;
+ mach_timespec_t m_start;
+ mach_timespec_t m_stop;
+};
+#else
+class Timer {
+public:
+ Timer(void)
+ {
+ memset(this, 0, sizeof(Timer));
+ };
+ ~Timer(void){};
+ void Tic()
+ {
+ clock_gettime(CLOCK_REALTIME, &m_start);
+ }
+ void Toc()
+ {
+ clock_gettime(CLOCK_REALTIME, &m_stop);
+ }
+ double GetElapsedTime() // in ms
+ {
+ return 1000.0 * (m_stop.tv_sec - m_start.tv_sec + (1.0E-9) * (m_stop.tv_nsec - m_start.tv_nsec));
+ }
+
+private:
+ struct timespec m_start;
+ struct timespec m_stop;
+};
+#endif
+}
+#endif // VHACD_TIMER_H
diff --git a/thirdparty/vhacd/inc/vhacdVHACD.h b/thirdparty/vhacd/inc/vhacdVHACD.h
new file mode 100644
index 0000000000..d67b107642
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdVHACD.h
@@ -0,0 +1,371 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+All rights reserved.
+
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. 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.
+
+3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+*/
+#pragma once
+#ifndef VHACD_VHACD_H
+#define VHACD_VHACD_H
+
+#ifdef OPENCL_FOUND
+#ifdef __MACH__
+#include <OpenCL/cl.h>
+#else
+#include <CL/cl.h>
+#endif
+#endif //OPENCL_FOUND
+
+#include "vhacdMutex.h"
+#include "vhacdVolume.h"
+#include "vhacdRaycastMesh.h"
+#include <vector>
+
+#define USE_THREAD 1
+#define OCL_MIN_NUM_PRIMITIVES 4096
+#define CH_APP_MIN_NUM_PRIMITIVES 64000
+namespace VHACD {
+class VHACD : public IVHACD {
+public:
+ //! Constructor.
+ VHACD()
+ {
+#if USE_THREAD == 1 && _OPENMP
+ m_ompNumProcessors = 2 * omp_get_num_procs();
+ omp_set_num_threads(m_ompNumProcessors);
+#else //USE_THREAD == 1 && _OPENMP
+ m_ompNumProcessors = 1;
+#endif //USE_THREAD == 1 && _OPENMP
+#ifdef CL_VERSION_1_1
+ m_oclWorkGroupSize = 0;
+ m_oclDevice = 0;
+ m_oclQueue = 0;
+ m_oclKernelComputePartialVolumes = 0;
+ m_oclKernelComputeSum = 0;
+#endif //CL_VERSION_1_1
+ Init();
+ }
+ //! Destructor.
+ ~VHACD(void)
+ {
+ }
+ uint32_t GetNConvexHulls() const
+ {
+ return (uint32_t)m_convexHulls.Size();
+ }
+ void Cancel()
+ {
+ SetCancel(true);
+ }
+ void GetConvexHull(const uint32_t index, ConvexHull& ch) const
+ {
+ Mesh* mesh = m_convexHulls[index];
+ ch.m_nPoints = (uint32_t)mesh->GetNPoints();
+ ch.m_nTriangles = (uint32_t)mesh->GetNTriangles();
+ ch.m_points = mesh->GetPoints();
+ ch.m_triangles = (uint32_t *)mesh->GetTriangles();
+ ch.m_volume = mesh->ComputeVolume();
+ Vec3<double> &center = mesh->ComputeCenter();
+ ch.m_center[0] = center.X();
+ ch.m_center[1] = center.Y();
+ ch.m_center[2] = center.Z();
+ }
+ void Clean(void)
+ {
+ if (mRaycastMesh)
+ {
+ mRaycastMesh->release();
+ mRaycastMesh = nullptr;
+ }
+ delete m_volume;
+ delete m_pset;
+ size_t nCH = m_convexHulls.Size();
+ for (size_t p = 0; p < nCH; ++p) {
+ delete m_convexHulls[p];
+ }
+ m_convexHulls.Clear();
+ Init();
+ }
+ void Release(void)
+ {
+ delete this;
+ }
+ bool Compute(const float* const points,
+ const uint32_t nPoints,
+ const uint32_t* const triangles,
+ const uint32_t nTriangles,
+ const Parameters& params);
+ bool Compute(const double* const points,
+ const uint32_t nPoints,
+ const uint32_t* const triangles,
+ const uint32_t nTriangles,
+ const Parameters& params);
+ bool OCLInit(void* const oclDevice,
+ IUserLogger* const logger = 0);
+ bool OCLRelease(IUserLogger* const logger = 0);
+
+ virtual bool ComputeCenterOfMass(double centerOfMass[3]) const;
+
+private:
+ void SetCancel(bool cancel)
+ {
+ m_cancelMutex.Lock();
+ m_cancel = cancel;
+ m_cancelMutex.Unlock();
+ }
+ bool GetCancel()
+ {
+
+ m_cancelMutex.Lock();
+ bool cancel = m_cancel;
+ m_cancelMutex.Unlock();
+ return cancel;
+ }
+ void Update(const double stageProgress,
+ const double operationProgress,
+ const Parameters& params)
+ {
+ m_stageProgress = stageProgress;
+ m_operationProgress = operationProgress;
+ if (params.m_callback) {
+ params.m_callback->Update(m_overallProgress,
+ m_stageProgress,
+ m_operationProgress,
+ m_stage.c_str(),
+ m_operation.c_str());
+ }
+ }
+ void Init()
+ {
+ if (mRaycastMesh)
+ {
+ mRaycastMesh->release();
+ mRaycastMesh = nullptr;
+ }
+ memset(m_rot, 0, sizeof(double) * 9);
+ m_dim = 64;
+ m_volume = 0;
+ m_volumeCH0 = 0.0;
+ m_pset = 0;
+ m_overallProgress = 0.0;
+ m_stageProgress = 0.0;
+ m_operationProgress = 0.0;
+ m_stage = "";
+ m_operation = "";
+ m_barycenter[0] = m_barycenter[1] = m_barycenter[2] = 0.0;
+ m_rot[0][0] = m_rot[1][1] = m_rot[2][2] = 1.0;
+ SetCancel(false);
+ }
+ void ComputePrimitiveSet(const Parameters& params);
+ void ComputeACD(const Parameters& params);
+ void MergeConvexHulls(const Parameters& params);
+ void SimplifyConvexHull(Mesh* const ch, const size_t nvertices, const double minVolume);
+ void SimplifyConvexHulls(const Parameters& params);
+ void ComputeBestClippingPlane(const PrimitiveSet* inputPSet,
+ const double volume,
+ const SArray<Plane>& planes,
+ const Vec3<double>& preferredCuttingDirection,
+ const double w,
+ const double alpha,
+ const double beta,
+ const int32_t convexhullDownsampling,
+ const double progress0,
+ const double progress1,
+ Plane& bestPlane,
+ double& minConcavity,
+ const Parameters& params);
+ template <class T>
+ void AlignMesh(const T* const points,
+ const uint32_t stridePoints,
+ const uint32_t nPoints,
+ const int32_t* const triangles,
+ const uint32_t strideTriangles,
+ const uint32_t nTriangles,
+ const Parameters& params)
+ {
+ if (GetCancel() || !params.m_pca) {
+ return;
+ }
+ m_timer.Tic();
+
+ m_stage = "Align mesh";
+ m_operation = "Voxelization";
+
+ std::ostringstream msg;
+ if (params.m_logger) {
+ msg << "+ " << m_stage << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ Update(0.0, 0.0, params);
+ if (GetCancel()) {
+ return;
+ }
+ m_dim = (size_t)(pow((double)params.m_resolution, 1.0 / 3.0) + 0.5);
+ Volume volume;
+ volume.Voxelize(points, stridePoints, nPoints,
+ triangles, strideTriangles, nTriangles,
+ m_dim, m_barycenter, m_rot);
+ size_t n = volume.GetNPrimitivesOnSurf() + volume.GetNPrimitivesInsideSurf();
+ Update(50.0, 100.0, params);
+
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t dim = " << m_dim << "\t-> " << n << " voxels" << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+ if (GetCancel()) {
+ return;
+ }
+ m_operation = "PCA";
+ Update(50.0, 0.0, params);
+ volume.AlignToPrincipalAxes(m_rot);
+ m_overallProgress = 1.0;
+ Update(100.0, 100.0, params);
+
+ m_timer.Toc();
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t time " << m_timer.GetElapsedTime() / 1000.0 << "s" << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+ }
+ template <class T>
+ void VoxelizeMesh(const T* const points,
+ const uint32_t stridePoints,
+ const uint32_t nPoints,
+ const int32_t* const triangles,
+ const uint32_t strideTriangles,
+ const uint32_t nTriangles,
+ const Parameters& params)
+ {
+ if (GetCancel()) {
+ return;
+ }
+
+ m_timer.Tic();
+ m_stage = "Voxelization";
+
+ std::ostringstream msg;
+ if (params.m_logger) {
+ msg << "+ " << m_stage << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ delete m_volume;
+ m_volume = 0;
+ int32_t iteration = 0;
+ const int32_t maxIteration = 5;
+ double progress = 0.0;
+ while (iteration++ < maxIteration && !m_cancel) {
+ msg.str("");
+ msg << "Iteration " << iteration;
+ m_operation = msg.str();
+
+ progress = iteration * 100.0 / maxIteration;
+ Update(progress, 0.0, params);
+
+ m_volume = new Volume;
+ m_volume->Voxelize(points, stridePoints, nPoints,
+ triangles, strideTriangles, nTriangles,
+ m_dim, m_barycenter, m_rot);
+
+ Update(progress, 100.0, params);
+
+ size_t n = m_volume->GetNPrimitivesOnSurf() + m_volume->GetNPrimitivesInsideSurf();
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t dim = " << m_dim << "\t-> " << n << " voxels" << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ double a = pow((double)(params.m_resolution) / n, 0.33);
+ size_t dim_next = (size_t)(m_dim * a + 0.5);
+ if (n < params.m_resolution && iteration < maxIteration && m_volume->GetNPrimitivesOnSurf() < params.m_resolution / 8 && m_dim != dim_next) {
+ delete m_volume;
+ m_volume = 0;
+ m_dim = dim_next;
+ }
+ else {
+ break;
+ }
+ }
+ m_overallProgress = 10.0;
+ Update(100.0, 100.0, params);
+
+ m_timer.Toc();
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t time " << m_timer.GetElapsedTime() / 1000.0 << "s" << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+ }
+ template <class T>
+ bool ComputeACD(const T* const points,
+ const uint32_t nPoints,
+ const uint32_t* const triangles,
+ const uint32_t nTriangles,
+ const Parameters& params)
+ {
+ Init();
+ if (params.m_projectHullVertices)
+ {
+ mRaycastMesh = RaycastMesh::createRaycastMesh(nPoints, points, nTriangles, (const uint32_t *)triangles);
+ }
+ if (params.m_oclAcceleration) {
+ // build kernels
+ }
+ AlignMesh(points, 3, nPoints, (int32_t *)triangles, 3, nTriangles, params);
+ VoxelizeMesh(points, 3, nPoints, (int32_t *)triangles, 3, nTriangles, params);
+ ComputePrimitiveSet(params);
+ ComputeACD(params);
+ MergeConvexHulls(params);
+ SimplifyConvexHulls(params);
+ if (params.m_oclAcceleration) {
+ // Release kernels
+ }
+ if (GetCancel()) {
+ Clean();
+ return false;
+ }
+ return true;
+ }
+
+private:
+ RaycastMesh *mRaycastMesh{ nullptr };
+ SArray<Mesh*> m_convexHulls;
+ std::string m_stage;
+ std::string m_operation;
+ double m_overallProgress;
+ double m_stageProgress;
+ double m_operationProgress;
+ double m_rot[3][3];
+ double m_volumeCH0;
+ Vec3<double> m_barycenter;
+ Timer m_timer;
+ size_t m_dim;
+ Volume* m_volume;
+ PrimitiveSet* m_pset;
+ Mutex m_cancelMutex;
+ bool m_cancel;
+ int32_t m_ompNumProcessors;
+#ifdef CL_VERSION_1_1
+ cl_device_id* m_oclDevice;
+ cl_context m_oclContext;
+ cl_program m_oclProgram;
+ cl_command_queue* m_oclQueue;
+ cl_kernel* m_oclKernelComputePartialVolumes;
+ cl_kernel* m_oclKernelComputeSum;
+ size_t m_oclWorkGroupSize;
+#endif //CL_VERSION_1_1
+};
+}
+#endif // VHACD_VHACD_H
diff --git a/thirdparty/vhacd/inc/vhacdVector.h b/thirdparty/vhacd/inc/vhacdVector.h
new file mode 100644
index 0000000000..efcfcf6ad7
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdVector.h
@@ -0,0 +1,168 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#pragma once
+#ifndef VHACD_VECTOR_H
+#define VHACD_VECTOR_H
+#include <iostream>
+#include <math.h>
+
+namespace VHACD {
+//! Vector dim 3.
+template <typename T>
+class Vec3 {
+public:
+ T& operator[](size_t i) { return m_data[i]; }
+ const T& operator[](size_t i) const { return m_data[i]; }
+ T& X();
+ T& Y();
+ T& Z();
+ const T& X() const;
+ const T& Y() const;
+ const T& Z() const;
+ void Normalize();
+ T GetNorm() const;
+ void operator=(const Vec3& rhs);
+ void operator+=(const Vec3& rhs);
+ void operator-=(const Vec3& rhs);
+ void operator-=(T a);
+ void operator+=(T a);
+ void operator/=(T a);
+ void operator*=(T a);
+ Vec3 operator^(const Vec3& rhs) const;
+ T operator*(const Vec3& rhs) const;
+ Vec3 operator+(const Vec3& rhs) const;
+ Vec3 operator-(const Vec3& rhs) const;
+ Vec3 operator-() const;
+ Vec3 operator*(T rhs) const;
+ Vec3 operator/(T rhs) const;
+ bool operator<(const Vec3& rhs) const;
+ bool operator>(const Vec3& rhs) const;
+ Vec3();
+ Vec3(T a);
+ Vec3(T x, T y, T z);
+ Vec3(const Vec3& rhs);
+ /*virtual*/ ~Vec3(void);
+
+ // Compute the center of this bounding box and return the diagonal length
+ T GetCenter(const Vec3 &bmin, const Vec3 &bmax)
+ {
+ X() = (bmin.X() + bmax.X())*0.5;
+ Y() = (bmin.Y() + bmax.Y())*0.5;
+ Z() = (bmin.Z() + bmax.Z())*0.5;
+ T dx = bmax.X() - bmin.X();
+ T dy = bmax.Y() - bmin.Y();
+ T dz = bmax.Z() - bmin.Z();
+ T diagonal = T(sqrt(dx*dx + dy*dy + dz*dz));
+ return diagonal;
+ }
+
+ // Update the min/max values relative to this point
+ void UpdateMinMax(Vec3 &bmin,Vec3 &bmax) const
+ {
+ if (X() < bmin.X())
+ {
+ bmin.X() = X();
+ }
+ if (Y() < bmin.Y())
+ {
+ bmin.Y() = Y();
+ }
+ if (Z() < bmin.Z())
+ {
+ bmin.Z() = Z();
+ }
+ if (X() > bmax.X())
+ {
+ bmax.X() = X();
+ }
+ if (X() > bmax.X())
+ {
+ bmax.X() = X();
+ }
+ if (Y() > bmax.Y())
+ {
+ bmax.Y() = Y();
+ }
+ if (Z() > bmax.Z())
+ {
+ bmax.Z() = Z();
+ }
+ }
+
+ // Returns the squared distance between these two points
+ T GetDistanceSquared(const Vec3 &p) const
+ {
+ T dx = X() - p.X();
+ T dy = Y() - p.Y();
+ T dz = Z() - p.Z();
+ return dx*dx + dy*dy + dz*dz;
+ }
+
+ T GetDistance(const Vec3 &p) const
+ {
+ return sqrt(GetDistanceSquared(p));
+ }
+
+ // Returns the raw vector data as a pointer
+ T* GetData(void)
+ {
+ return m_data;
+ }
+private:
+ T m_data[3];
+};
+//! Vector dim 2.
+template <typename T>
+class Vec2 {
+public:
+ T& operator[](size_t i) { return m_data[i]; }
+ const T& operator[](size_t i) const { return m_data[i]; }
+ T& X();
+ T& Y();
+ const T& X() const;
+ const T& Y() const;
+ void Normalize();
+ T GetNorm() const;
+ void operator=(const Vec2& rhs);
+ void operator+=(const Vec2& rhs);
+ void operator-=(const Vec2& rhs);
+ void operator-=(T a);
+ void operator+=(T a);
+ void operator/=(T a);
+ void operator*=(T a);
+ T operator^(const Vec2& rhs) const;
+ T operator*(const Vec2& rhs) const;
+ Vec2 operator+(const Vec2& rhs) const;
+ Vec2 operator-(const Vec2& rhs) const;
+ Vec2 operator-() const;
+ Vec2 operator*(T rhs) const;
+ Vec2 operator/(T rhs) const;
+ Vec2();
+ Vec2(T a);
+ Vec2(T x, T y);
+ Vec2(const Vec2& rhs);
+ /*virtual*/ ~Vec2(void);
+
+private:
+ T m_data[2];
+};
+
+template <typename T>
+const bool Colinear(const Vec3<T>& a, const Vec3<T>& b, const Vec3<T>& c);
+template <typename T>
+const T ComputeVolume4(const Vec3<T>& a, const Vec3<T>& b, const Vec3<T>& c, const Vec3<T>& d);
+}
+#include "vhacdVector.inl" // template implementation
+#endif \ No newline at end of file
diff --git a/thirdparty/vhacd/inc/vhacdVector.inl b/thirdparty/vhacd/inc/vhacdVector.inl
new file mode 100644
index 0000000000..223c2ef173
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdVector.inl
@@ -0,0 +1,362 @@
+#pragma once
+#ifndef VHACD_VECTOR_INL
+#define VHACD_VECTOR_INL
+namespace VHACD
+{
+ template <typename T>
+ inline Vec3<T> operator*(T lhs, const Vec3<T> & rhs)
+ {
+ return Vec3<T>(lhs * rhs.X(), lhs * rhs.Y(), lhs * rhs.Z());
+ }
+ template <typename T>
+ inline T & Vec3<T>::X()
+ {
+ return m_data[0];
+ }
+ template <typename T>
+ inline T & Vec3<T>::Y()
+ {
+ return m_data[1];
+ }
+ template <typename T>
+ inline T & Vec3<T>::Z()
+ {
+ return m_data[2];
+ }
+ template <typename T>
+ inline const T & Vec3<T>::X() const
+ {
+ return m_data[0];
+ }
+ template <typename T>
+ inline const T & Vec3<T>::Y() const
+ {
+ return m_data[1];
+ }
+ template <typename T>
+ inline const T & Vec3<T>::Z() const
+ {
+ return m_data[2];
+ }
+ template <typename T>
+ inline void Vec3<T>::Normalize()
+ {
+ T n = sqrt(m_data[0]*m_data[0]+m_data[1]*m_data[1]+m_data[2]*m_data[2]);
+ if (n != 0.0) (*this) /= n;
+ }
+ template <typename T>
+ inline T Vec3<T>::GetNorm() const
+ {
+ return sqrt(m_data[0]*m_data[0]+m_data[1]*m_data[1]+m_data[2]*m_data[2]);
+ }
+ template <typename T>
+ inline void Vec3<T>::operator= (const Vec3 & rhs)
+ {
+ this->m_data[0] = rhs.m_data[0];
+ this->m_data[1] = rhs.m_data[1];
+ this->m_data[2] = rhs.m_data[2];
+ }
+ template <typename T>
+ inline void Vec3<T>::operator+=(const Vec3 & rhs)
+ {
+ this->m_data[0] += rhs.m_data[0];
+ this->m_data[1] += rhs.m_data[1];
+ this->m_data[2] += rhs.m_data[2];
+ }
+ template <typename T>
+ inline void Vec3<T>::operator-=(const Vec3 & rhs)
+ {
+ this->m_data[0] -= rhs.m_data[0];
+ this->m_data[1] -= rhs.m_data[1];
+ this->m_data[2] -= rhs.m_data[2];
+ }
+ template <typename T>
+ inline void Vec3<T>::operator-=(T a)
+ {
+ this->m_data[0] -= a;
+ this->m_data[1] -= a;
+ this->m_data[2] -= a;
+ }
+ template <typename T>
+ inline void Vec3<T>::operator+=(T a)
+ {
+ this->m_data[0] += a;
+ this->m_data[1] += a;
+ this->m_data[2] += a;
+ }
+ template <typename T>
+ inline void Vec3<T>::operator/=(T a)
+ {
+ this->m_data[0] /= a;
+ this->m_data[1] /= a;
+ this->m_data[2] /= a;
+ }
+ template <typename T>
+ inline void Vec3<T>::operator*=(T a)
+ {
+ this->m_data[0] *= a;
+ this->m_data[1] *= a;
+ this->m_data[2] *= a;
+ }
+ template <typename T>
+ inline Vec3<T> Vec3<T>::operator^ (const Vec3<T> & rhs) const
+ {
+ return Vec3<T>(m_data[1] * rhs.m_data[2] - m_data[2] * rhs.m_data[1],
+ m_data[2] * rhs.m_data[0] - m_data[0] * rhs.m_data[2],
+ m_data[0] * rhs.m_data[1] - m_data[1] * rhs.m_data[0]);
+ }
+ template <typename T>
+ inline T Vec3<T>::operator*(const Vec3<T> & rhs) const
+ {
+ return (m_data[0] * rhs.m_data[0] + m_data[1] * rhs.m_data[1] + m_data[2] * rhs.m_data[2]);
+ }
+ template <typename T>
+ inline Vec3<T> Vec3<T>::operator+(const Vec3<T> & rhs) const
+ {
+ return Vec3<T>(m_data[0] + rhs.m_data[0],m_data[1] + rhs.m_data[1],m_data[2] + rhs.m_data[2]);
+ }
+ template <typename T>
+ inline Vec3<T> Vec3<T>::operator-(const Vec3<T> & rhs) const
+ {
+ return Vec3<T>(m_data[0] - rhs.m_data[0],m_data[1] - rhs.m_data[1],m_data[2] - rhs.m_data[2]) ;
+ }
+ template <typename T>
+ inline Vec3<T> Vec3<T>::operator-() const
+ {
+ return Vec3<T>(-m_data[0],-m_data[1],-m_data[2]) ;
+ }
+
+ template <typename T>
+ inline Vec3<T> Vec3<T>::operator*(T rhs) const
+ {
+ return Vec3<T>(rhs * this->m_data[0], rhs * this->m_data[1], rhs * this->m_data[2]);
+ }
+ template <typename T>
+ inline Vec3<T> Vec3<T>::operator/ (T rhs) const
+ {
+ return Vec3<T>(m_data[0] / rhs, m_data[1] / rhs, m_data[2] / rhs);
+ }
+ template <typename T>
+ inline Vec3<T>::Vec3(T a)
+ {
+ m_data[0] = m_data[1] = m_data[2] = a;
+ }
+ template <typename T>
+ inline Vec3<T>::Vec3(T x, T y, T z)
+ {
+ m_data[0] = x;
+ m_data[1] = y;
+ m_data[2] = z;
+ }
+ template <typename T>
+ inline Vec3<T>::Vec3(const Vec3 & rhs)
+ {
+ m_data[0] = rhs.m_data[0];
+ m_data[1] = rhs.m_data[1];
+ m_data[2] = rhs.m_data[2];
+ }
+ template <typename T>
+ inline Vec3<T>::~Vec3(void){};
+
+ template <typename T>
+ inline Vec3<T>::Vec3() {}
+
+ template<typename T>
+ inline const bool Colinear(const Vec3<T> & a, const Vec3<T> & b, const Vec3<T> & c)
+ {
+ return ((c.Z() - a.Z()) * (b.Y() - a.Y()) - (b.Z() - a.Z()) * (c.Y() - a.Y()) == 0.0 /*EPS*/) &&
+ ((b.Z() - a.Z()) * (c.X() - a.X()) - (b.X() - a.X()) * (c.Z() - a.Z()) == 0.0 /*EPS*/) &&
+ ((b.X() - a.X()) * (c.Y() - a.Y()) - (b.Y() - a.Y()) * (c.X() - a.X()) == 0.0 /*EPS*/);
+ }
+
+ template<typename T>
+ inline const T ComputeVolume4(const Vec3<T> & a, const Vec3<T> & b, const Vec3<T> & c, const Vec3<T> & d)
+ {
+ return (a-d) * ((b-d) ^ (c-d));
+ }
+
+ template <typename T>
+ inline bool Vec3<T>::operator<(const Vec3 & rhs) const
+ {
+ if (X() == rhs[0])
+ {
+ if (Y() == rhs[1])
+ {
+ return (Z()<rhs[2]);
+ }
+ return (Y()<rhs[1]);
+ }
+ return (X()<rhs[0]);
+ }
+ template <typename T>
+ inline bool Vec3<T>::operator>(const Vec3 & rhs) const
+ {
+ if (X() == rhs[0])
+ {
+ if (Y() == rhs[1])
+ {
+ return (Z()>rhs[2]);
+ }
+ return (Y()>rhs[1]);
+ }
+ return (X()>rhs[0]);
+ }
+ template <typename T>
+ inline Vec2<T> operator*(T lhs, const Vec2<T> & rhs)
+ {
+ return Vec2<T>(lhs * rhs.X(), lhs * rhs.Y());
+ }
+ template <typename T>
+ inline T & Vec2<T>::X()
+ {
+ return m_data[0];
+ }
+ template <typename T>
+ inline T & Vec2<T>::Y()
+ {
+ return m_data[1];
+ }
+ template <typename T>
+ inline const T & Vec2<T>::X() const
+ {
+ return m_data[0];
+ }
+ template <typename T>
+ inline const T & Vec2<T>::Y() const
+ {
+ return m_data[1];
+ }
+ template <typename T>
+ inline void Vec2<T>::Normalize()
+ {
+ T n = sqrt(m_data[0]*m_data[0]+m_data[1]*m_data[1]);
+ if (n != 0.0) (*this) /= n;
+ }
+ template <typename T>
+ inline T Vec2<T>::GetNorm() const
+ {
+ return sqrt(m_data[0]*m_data[0]+m_data[1]*m_data[1]);
+ }
+ template <typename T>
+ inline void Vec2<T>::operator= (const Vec2 & rhs)
+ {
+ this->m_data[0] = rhs.m_data[0];
+ this->m_data[1] = rhs.m_data[1];
+ }
+ template <typename T>
+ inline void Vec2<T>::operator+=(const Vec2 & rhs)
+ {
+ this->m_data[0] += rhs.m_data[0];
+ this->m_data[1] += rhs.m_data[1];
+ }
+ template <typename T>
+ inline void Vec2<T>::operator-=(const Vec2 & rhs)
+ {
+ this->m_data[0] -= rhs.m_data[0];
+ this->m_data[1] -= rhs.m_data[1];
+ }
+ template <typename T>
+ inline void Vec2<T>::operator-=(T a)
+ {
+ this->m_data[0] -= a;
+ this->m_data[1] -= a;
+ }
+ template <typename T>
+ inline void Vec2<T>::operator+=(T a)
+ {
+ this->m_data[0] += a;
+ this->m_data[1] += a;
+ }
+ template <typename T>
+ inline void Vec2<T>::operator/=(T a)
+ {
+ this->m_data[0] /= a;
+ this->m_data[1] /= a;
+ }
+ template <typename T>
+ inline void Vec2<T>::operator*=(T a)
+ {
+ this->m_data[0] *= a;
+ this->m_data[1] *= a;
+ }
+ template <typename T>
+ inline T Vec2<T>::operator^ (const Vec2<T> & rhs) const
+ {
+ return m_data[0] * rhs.m_data[1] - m_data[1] * rhs.m_data[0];
+ }
+ template <typename T>
+ inline T Vec2<T>::operator*(const Vec2<T> & rhs) const
+ {
+ return (m_data[0] * rhs.m_data[0] + m_data[1] * rhs.m_data[1]);
+ }
+ template <typename T>
+ inline Vec2<T> Vec2<T>::operator+(const Vec2<T> & rhs) const
+ {
+ return Vec2<T>(m_data[0] + rhs.m_data[0],m_data[1] + rhs.m_data[1]);
+ }
+ template <typename T>
+ inline Vec2<T> Vec2<T>::operator-(const Vec2<T> & rhs) const
+ {
+ return Vec2<T>(m_data[0] - rhs.m_data[0],m_data[1] - rhs.m_data[1]);
+ }
+ template <typename T>
+ inline Vec2<T> Vec2<T>::operator-() const
+ {
+ return Vec2<T>(-m_data[0],-m_data[1]) ;
+ }
+
+ template <typename T>
+ inline Vec2<T> Vec2<T>::operator*(T rhs) const
+ {
+ return Vec2<T>(rhs * this->m_data[0], rhs * this->m_data[1]);
+ }
+ template <typename T>
+ inline Vec2<T> Vec2<T>::operator/ (T rhs) const
+ {
+ return Vec2<T>(m_data[0] / rhs, m_data[1] / rhs);
+ }
+ template <typename T>
+ inline Vec2<T>::Vec2(T a)
+ {
+ m_data[0] = m_data[1] = a;
+ }
+ template <typename T>
+ inline Vec2<T>::Vec2(T x, T y)
+ {
+ m_data[0] = x;
+ m_data[1] = y;
+ }
+ template <typename T>
+ inline Vec2<T>::Vec2(const Vec2 & rhs)
+ {
+ m_data[0] = rhs.m_data[0];
+ m_data[1] = rhs.m_data[1];
+ }
+ template <typename T>
+ inline Vec2<T>::~Vec2(void){};
+
+ template <typename T>
+ inline Vec2<T>::Vec2() {}
+
+ /*
+ InsideTriangle decides if a point P is Inside of the triangle
+ defined by A, B, C.
+ */
+ template<typename T>
+ inline const bool InsideTriangle(const Vec2<T> & a, const Vec2<T> & b, const Vec2<T> & c, const Vec2<T> & p)
+ {
+ T ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
+ T cCROSSap, bCROSScp, aCROSSbp;
+ ax = c.X() - b.X(); ay = c.Y() - b.Y();
+ bx = a.X() - c.X(); by = a.Y() - c.Y();
+ cx = b.X() - a.X(); cy = b.Y() - a.Y();
+ apx= p.X() - a.X(); apy= p.Y() - a.Y();
+ bpx= p.X() - b.X(); bpy= p.Y() - b.Y();
+ cpx= p.X() - c.X(); cpy= p.Y() - c.Y();
+ aCROSSbp = ax*bpy - ay*bpx;
+ cCROSSap = cx*apy - cy*apx;
+ bCROSScp = bx*cpy - by*cpx;
+ return ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0));
+ }
+}
+#endif //VHACD_VECTOR_INL \ No newline at end of file
diff --git a/thirdparty/vhacd/inc/vhacdVolume.h b/thirdparty/vhacd/inc/vhacdVolume.h
new file mode 100644
index 0000000000..8c47fa1e2c
--- /dev/null
+++ b/thirdparty/vhacd/inc/vhacdVolume.h
@@ -0,0 +1,430 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#pragma once
+#ifndef VHACD_VOLUME_H
+#define VHACD_VOLUME_H
+#include "vhacdMesh.h"
+#include "vhacdVector.h"
+#include <assert.h>
+
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable:4456 4701)
+#endif
+
+namespace VHACD {
+
+enum VOXEL_VALUE {
+ PRIMITIVE_UNDEFINED = 0,
+ PRIMITIVE_OUTSIDE_SURFACE = 1,
+ PRIMITIVE_INSIDE_SURFACE = 2,
+ PRIMITIVE_ON_SURFACE = 3
+};
+
+struct Voxel {
+public:
+ short m_coord[3];
+ short m_data;
+};
+
+class PrimitiveSet {
+public:
+ virtual ~PrimitiveSet(){};
+ virtual PrimitiveSet* Create() const = 0;
+ virtual const size_t GetNPrimitives() const = 0;
+ virtual const size_t GetNPrimitivesOnSurf() const = 0;
+ virtual const size_t GetNPrimitivesInsideSurf() const = 0;
+ virtual const double GetEigenValue(AXIS axis) const = 0;
+ virtual const double ComputeMaxVolumeError() const = 0;
+ virtual const double ComputeVolume() const = 0;
+ virtual void Clip(const Plane& plane, PrimitiveSet* const positivePart,
+ PrimitiveSet* const negativePart) const = 0;
+ virtual void Intersect(const Plane& plane, SArray<Vec3<double> >* const positivePts,
+ SArray<Vec3<double> >* const negativePts, const size_t sampling) const = 0;
+ virtual void ComputeExteriorPoints(const Plane& plane, const Mesh& mesh,
+ SArray<Vec3<double> >* const exteriorPts) const = 0;
+ virtual void ComputeClippedVolumes(const Plane& plane, double& positiveVolume,
+ double& negativeVolume) const = 0;
+ virtual void SelectOnSurface(PrimitiveSet* const onSurfP) const = 0;
+ virtual void ComputeConvexHull(Mesh& meshCH, const size_t sampling = 1) const = 0;
+ virtual void ComputeBB() = 0;
+ virtual void ComputePrincipalAxes() = 0;
+ virtual void AlignToPrincipalAxes() = 0;
+ virtual void RevertAlignToPrincipalAxes() = 0;
+ virtual void Convert(Mesh& mesh, const VOXEL_VALUE value) const = 0;
+ const Mesh& GetConvexHull() const { return m_convexHull; };
+ Mesh& GetConvexHull() { return m_convexHull; };
+private:
+ Mesh m_convexHull;
+};
+
+//!
+class VoxelSet : public PrimitiveSet {
+ friend class Volume;
+
+public:
+ //! Destructor.
+ ~VoxelSet(void);
+ //! Constructor.
+ VoxelSet();
+
+ const size_t GetNPrimitives() const { return m_voxels.Size(); }
+ const size_t GetNPrimitivesOnSurf() const { return m_numVoxelsOnSurface; }
+ const size_t GetNPrimitivesInsideSurf() const { return m_numVoxelsInsideSurface; }
+ const double GetEigenValue(AXIS axis) const { return m_D[axis][axis]; }
+ const double ComputeVolume() const { return m_unitVolume * m_voxels.Size(); }
+ const double ComputeMaxVolumeError() const { return m_unitVolume * m_numVoxelsOnSurface; }
+ const Vec3<short>& GetMinBBVoxels() const { return m_minBBVoxels; }
+ const Vec3<short>& GetMaxBBVoxels() const { return m_maxBBVoxels; }
+ const Vec3<double>& GetMinBB() const { return m_minBB; }
+ const double& GetScale() const { return m_scale; }
+ const double& GetUnitVolume() const { return m_unitVolume; }
+ Vec3<double> GetPoint(Vec3<short> voxel) const
+ {
+ return Vec3<double>(voxel[0] * m_scale + m_minBB[0],
+ voxel[1] * m_scale + m_minBB[1],
+ voxel[2] * m_scale + m_minBB[2]);
+ }
+ Vec3<double> GetPoint(const Voxel& voxel) const
+ {
+ return Vec3<double>(voxel.m_coord[0] * m_scale + m_minBB[0],
+ voxel.m_coord[1] * m_scale + m_minBB[1],
+ voxel.m_coord[2] * m_scale + m_minBB[2]);
+ }
+ Vec3<double> GetPoint(Vec3<double> voxel) const
+ {
+ return Vec3<double>(voxel[0] * m_scale + m_minBB[0],
+ voxel[1] * m_scale + m_minBB[1],
+ voxel[2] * m_scale + m_minBB[2]);
+ }
+ void GetPoints(const Voxel& voxel, Vec3<double>* const pts) const;
+ void ComputeConvexHull(Mesh& meshCH, const size_t sampling = 1) const;
+ void Clip(const Plane& plane, PrimitiveSet* const positivePart, PrimitiveSet* const negativePart) const;
+ void Intersect(const Plane& plane, SArray<Vec3<double> >* const positivePts,
+ SArray<Vec3<double> >* const negativePts, const size_t sampling) const;
+ void ComputeExteriorPoints(const Plane& plane, const Mesh& mesh,
+ SArray<Vec3<double> >* const exteriorPts) const;
+ void ComputeClippedVolumes(const Plane& plane, double& positiveVolume, double& negativeVolume) const;
+ void SelectOnSurface(PrimitiveSet* const onSurfP) const;
+ void ComputeBB();
+ void Convert(Mesh& mesh, const VOXEL_VALUE value) const;
+ void ComputePrincipalAxes();
+ PrimitiveSet* Create() const
+ {
+ return new VoxelSet();
+ }
+ void AlignToPrincipalAxes(){};
+ void RevertAlignToPrincipalAxes(){};
+ Voxel* const GetVoxels() { return m_voxels.Data(); }
+ const Voxel* const GetVoxels() const { return m_voxels.Data(); }
+
+private:
+ size_t m_numVoxelsOnSurface;
+ size_t m_numVoxelsInsideSurface;
+ Vec3<double> m_minBB;
+ double m_scale;
+ SArray<Voxel, 8> m_voxels;
+ double m_unitVolume;
+ Vec3<double> m_minBBPts;
+ Vec3<double> m_maxBBPts;
+ Vec3<short> m_minBBVoxels;
+ Vec3<short> m_maxBBVoxels;
+ Vec3<short> m_barycenter;
+ double m_Q[3][3];
+ double m_D[3][3];
+ Vec3<double> m_barycenterPCA;
+};
+
+struct Tetrahedron {
+public:
+ Vec3<double> m_pts[4];
+ unsigned char m_data;
+};
+
+//!
+class TetrahedronSet : public PrimitiveSet {
+ friend class Volume;
+
+public:
+ //! Destructor.
+ ~TetrahedronSet(void);
+ //! Constructor.
+ TetrahedronSet();
+
+ const size_t GetNPrimitives() const { return m_tetrahedra.Size(); }
+ const size_t GetNPrimitivesOnSurf() const { return m_numTetrahedraOnSurface; }
+ const size_t GetNPrimitivesInsideSurf() const { return m_numTetrahedraInsideSurface; }
+ const Vec3<double>& GetMinBB() const { return m_minBB; }
+ const Vec3<double>& GetMaxBB() const { return m_maxBB; }
+ const Vec3<double>& GetBarycenter() const { return m_barycenter; }
+ const double GetEigenValue(AXIS axis) const { return m_D[axis][axis]; }
+ const double GetSacle() const { return m_scale; }
+ const double ComputeVolume() const;
+ const double ComputeMaxVolumeError() const;
+ void ComputeConvexHull(Mesh& meshCH, const size_t sampling = 1) const;
+ void ComputePrincipalAxes();
+ void AlignToPrincipalAxes();
+ void RevertAlignToPrincipalAxes();
+ void Clip(const Plane& plane, PrimitiveSet* const positivePart, PrimitiveSet* const negativePart) const;
+ void Intersect(const Plane& plane, SArray<Vec3<double> >* const positivePts,
+ SArray<Vec3<double> >* const negativePts, const size_t sampling) const;
+ void ComputeExteriorPoints(const Plane& plane, const Mesh& mesh,
+ SArray<Vec3<double> >* const exteriorPts) const;
+ void ComputeClippedVolumes(const Plane& plane, double& positiveVolume, double& negativeVolume) const;
+ void SelectOnSurface(PrimitiveSet* const onSurfP) const;
+ void ComputeBB();
+ void Convert(Mesh& mesh, const VOXEL_VALUE value) const;
+ inline bool Add(Tetrahedron& tetrahedron);
+ PrimitiveSet* Create() const
+ {
+ return new TetrahedronSet();
+ }
+ static const double EPS;
+
+private:
+ void AddClippedTetrahedra(const Vec3<double> (&pts)[10], const int32_t nPts);
+
+ size_t m_numTetrahedraOnSurface;
+ size_t m_numTetrahedraInsideSurface;
+ double m_scale;
+ Vec3<double> m_minBB;
+ Vec3<double> m_maxBB;
+ Vec3<double> m_barycenter;
+ SArray<Tetrahedron, 8> m_tetrahedra;
+ double m_Q[3][3];
+ double m_D[3][3];
+};
+
+//!
+class Volume {
+public:
+ //! Destructor.
+ ~Volume(void);
+
+ //! Constructor.
+ Volume();
+
+ //! Voxelize
+ template <class T>
+ void Voxelize(const T* const points, const uint32_t stridePoints, const uint32_t nPoints,
+ const int32_t* const triangles, const uint32_t strideTriangles, const uint32_t nTriangles,
+ const size_t dim, const Vec3<double>& barycenter, const double (&rot)[3][3]);
+ unsigned char& GetVoxel(const size_t i, const size_t j, const size_t k)
+ {
+ assert(i < m_dim[0] || i >= 0);
+ assert(j < m_dim[0] || j >= 0);
+ assert(k < m_dim[0] || k >= 0);
+ return m_data[i + j * m_dim[0] + k * m_dim[0] * m_dim[1]];
+ }
+ const unsigned char& GetVoxel(const size_t i, const size_t j, const size_t k) const
+ {
+ assert(i < m_dim[0] || i >= 0);
+ assert(j < m_dim[0] || j >= 0);
+ assert(k < m_dim[0] || k >= 0);
+ return m_data[i + j * m_dim[0] + k * m_dim[0] * m_dim[1]];
+ }
+ const size_t GetNPrimitivesOnSurf() const { return m_numVoxelsOnSurface; }
+ const size_t GetNPrimitivesInsideSurf() const { return m_numVoxelsInsideSurface; }
+ void Convert(Mesh& mesh, const VOXEL_VALUE value) const;
+ void Convert(VoxelSet& vset) const;
+ void Convert(TetrahedronSet& tset) const;
+ void AlignToPrincipalAxes(double (&rot)[3][3]) const;
+
+private:
+ void FillOutsideSurface(const size_t i0, const size_t j0, const size_t k0, const size_t i1,
+ const size_t j1, const size_t k1);
+ void FillInsideSurface();
+ template <class T>
+ void ComputeBB(const T* const points, const uint32_t stridePoints, const uint32_t nPoints,
+ const Vec3<double>& barycenter, const double (&rot)[3][3]);
+ void Allocate();
+ void Free();
+
+ Vec3<double> m_minBB;
+ Vec3<double> m_maxBB;
+ double m_scale;
+ size_t m_dim[3]; //>! dim
+ size_t m_numVoxelsOnSurface;
+ size_t m_numVoxelsInsideSurface;
+ size_t m_numVoxelsOutsideSurface;
+ unsigned char* m_data;
+};
+int32_t TriBoxOverlap(const Vec3<double>& boxcenter, const Vec3<double>& boxhalfsize, const Vec3<double>& triver0,
+ const Vec3<double>& triver1, const Vec3<double>& triver2);
+template <class T>
+inline void ComputeAlignedPoint(const T* const points, const uint32_t idx, const Vec3<double>& barycenter,
+ const double (&rot)[3][3], Vec3<double>& pt){};
+template <>
+inline void ComputeAlignedPoint<float>(const float* const points, const uint32_t idx, const Vec3<double>& barycenter, const double (&rot)[3][3], Vec3<double>& pt)
+{
+ double x = points[idx + 0] - barycenter[0];
+ double y = points[idx + 1] - barycenter[1];
+ double z = points[idx + 2] - barycenter[2];
+ pt[0] = rot[0][0] * x + rot[1][0] * y + rot[2][0] * z;
+ pt[1] = rot[0][1] * x + rot[1][1] * y + rot[2][1] * z;
+ pt[2] = rot[0][2] * x + rot[1][2] * y + rot[2][2] * z;
+}
+template <>
+inline void ComputeAlignedPoint<double>(const double* const points, const uint32_t idx, const Vec3<double>& barycenter, const double (&rot)[3][3], Vec3<double>& pt)
+{
+ double x = points[idx + 0] - barycenter[0];
+ double y = points[idx + 1] - barycenter[1];
+ double z = points[idx + 2] - barycenter[2];
+ pt[0] = rot[0][0] * x + rot[1][0] * y + rot[2][0] * z;
+ pt[1] = rot[0][1] * x + rot[1][1] * y + rot[2][1] * z;
+ pt[2] = rot[0][2] * x + rot[1][2] * y + rot[2][2] * z;
+}
+template <class T>
+void Volume::ComputeBB(const T* const points, const uint32_t stridePoints, const uint32_t nPoints,
+ const Vec3<double>& barycenter, const double (&rot)[3][3])
+{
+ Vec3<double> pt;
+ ComputeAlignedPoint(points, 0, barycenter, rot, pt);
+ m_maxBB = pt;
+ m_minBB = pt;
+ for (uint32_t v = 1; v < nPoints; ++v) {
+ ComputeAlignedPoint(points, v * stridePoints, barycenter, rot, pt);
+ for (int32_t i = 0; i < 3; ++i) {
+ if (pt[i] < m_minBB[i])
+ m_minBB[i] = pt[i];
+ else if (pt[i] > m_maxBB[i])
+ m_maxBB[i] = pt[i];
+ }
+ }
+}
+template <class T>
+void Volume::Voxelize(const T* const points, const uint32_t stridePoints, const uint32_t nPoints,
+ const int32_t* const triangles, const uint32_t strideTriangles, const uint32_t nTriangles,
+ const size_t dim, const Vec3<double>& barycenter, const double (&rot)[3][3])
+{
+ if (nPoints == 0) {
+ return;
+ }
+ ComputeBB(points, stridePoints, nPoints, barycenter, rot);
+
+ double d[3] = { m_maxBB[0] - m_minBB[0], m_maxBB[1] - m_minBB[1], m_maxBB[2] - m_minBB[2] };
+ double r;
+ if (d[0] > d[1] && d[0] > d[2]) {
+ r = d[0];
+ m_dim[0] = dim;
+ m_dim[1] = 2 + static_cast<size_t>(dim * d[1] / d[0]);
+ m_dim[2] = 2 + static_cast<size_t>(dim * d[2] / d[0]);
+ }
+ else if (d[1] > d[0] && d[1] > d[2]) {
+ r = d[1];
+ m_dim[1] = dim;
+ m_dim[0] = 2 + static_cast<size_t>(dim * d[0] / d[1]);
+ m_dim[2] = 2 + static_cast<size_t>(dim * d[2] / d[1]);
+ }
+ else {
+ r = d[2];
+ m_dim[2] = dim;
+ m_dim[0] = 2 + static_cast<size_t>(dim * d[0] / d[2]);
+ m_dim[1] = 2 + static_cast<size_t>(dim * d[1] / d[2]);
+ }
+
+ m_scale = r / (dim - 1);
+ double invScale = (dim - 1) / r;
+
+ Allocate();
+ m_numVoxelsOnSurface = 0;
+ m_numVoxelsInsideSurface = 0;
+ m_numVoxelsOutsideSurface = 0;
+
+ Vec3<double> p[3];
+ size_t i, j, k;
+ size_t i0, j0, k0;
+ size_t i1, j1, k1;
+ Vec3<double> boxcenter;
+ Vec3<double> pt;
+ const Vec3<double> boxhalfsize(0.5, 0.5, 0.5);
+ for (size_t t = 0, ti = 0; t < nTriangles; ++t, ti += strideTriangles) {
+ Vec3<int32_t> tri(triangles[ti + 0],
+ triangles[ti + 1],
+ triangles[ti + 2]);
+ for (int32_t c = 0; c < 3; ++c) {
+ ComputeAlignedPoint(points, tri[c] * stridePoints, barycenter, rot, pt);
+ p[c][0] = (pt[0] - m_minBB[0]) * invScale;
+ p[c][1] = (pt[1] - m_minBB[1]) * invScale;
+ p[c][2] = (pt[2] - m_minBB[2]) * invScale;
+ i = static_cast<size_t>(p[c][0] + 0.5);
+ j = static_cast<size_t>(p[c][1] + 0.5);
+ k = static_cast<size_t>(p[c][2] + 0.5);
+ assert(i < m_dim[0] && i >= 0 && j < m_dim[1] && j >= 0 && k < m_dim[2] && k >= 0);
+
+ if (c == 0) {
+ i0 = i1 = i;
+ j0 = j1 = j;
+ k0 = k1 = k;
+ }
+ else {
+ if (i < i0)
+ i0 = i;
+ if (j < j0)
+ j0 = j;
+ if (k < k0)
+ k0 = k;
+ if (i > i1)
+ i1 = i;
+ if (j > j1)
+ j1 = j;
+ if (k > k1)
+ k1 = k;
+ }
+ }
+ if (i0 > 0)
+ --i0;
+ if (j0 > 0)
+ --j0;
+ if (k0 > 0)
+ --k0;
+ if (i1 < m_dim[0])
+ ++i1;
+ if (j1 < m_dim[1])
+ ++j1;
+ if (k1 < m_dim[2])
+ ++k1;
+ for (size_t i = i0; i < i1; ++i) {
+ boxcenter[0] = (double)i;
+ for (size_t j = j0; j < j1; ++j) {
+ boxcenter[1] = (double)j;
+ for (size_t k = k0; k < k1; ++k) {
+ boxcenter[2] = (double)k;
+ int32_t res = TriBoxOverlap(boxcenter, boxhalfsize, p[0], p[1], p[2]);
+ unsigned char& value = GetVoxel(i, j, k);
+ if (res == 1 && value == PRIMITIVE_UNDEFINED) {
+ value = PRIMITIVE_ON_SURFACE;
+ ++m_numVoxelsOnSurface;
+ }
+ }
+ }
+ }
+ }
+ FillOutsideSurface(0, 0, 0, m_dim[0], m_dim[1], 1);
+ FillOutsideSurface(0, 0, m_dim[2] - 1, m_dim[0], m_dim[1], m_dim[2]);
+ FillOutsideSurface(0, 0, 0, m_dim[0], 1, m_dim[2]);
+ FillOutsideSurface(0, m_dim[1] - 1, 0, m_dim[0], m_dim[1], m_dim[2]);
+ FillOutsideSurface(0, 0, 0, 1, m_dim[1], m_dim[2]);
+ FillOutsideSurface(m_dim[0] - 1, 0, 0, m_dim[0], m_dim[1], m_dim[2]);
+ FillInsideSurface();
+}
+}
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
+
+#endif // VHACD_VOLUME_H
diff --git a/thirdparty/vhacd/public/VHACD.h b/thirdparty/vhacd/public/VHACD.h
new file mode 100644
index 0000000000..863aeda9de
--- /dev/null
+++ b/thirdparty/vhacd/public/VHACD.h
@@ -0,0 +1,153 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#pragma once
+#ifndef VHACD_H
+#define VHACD_H
+
+#define VHACD_VERSION_MAJOR 2
+#define VHACD_VERSION_MINOR 3
+
+// Changes for version 2.3
+//
+// m_gamma : Has been removed. This used to control the error metric to merge convex hulls. Now it uses the 'm_maxConvexHulls' value instead.
+// m_maxConvexHulls : This is the maximum number of convex hulls to produce from the merge operation; replaces 'm_gamma'.
+//
+// Note that decomposition depth is no longer a user provided value. It is now derived from the
+// maximum number of hulls requested.
+//
+// As a convenience to the user, each convex hull produced now includes the volume of the hull as well as it's center.
+//
+// This version supports a convenience method to automatically make V-HACD run asynchronously in a background thread.
+// To get a fully asynchronous version, call 'CreateVHACD_ASYNC' instead of 'CreateVHACD'. You get the same interface however,
+// now when computing convex hulls, it is no longer a blocking operation. All callback messages are still returned
+// in the application's thread so you don't need to worry about mutex locks or anything in that case.
+// To tell if the operation is complete, the application should call 'IsReady'. This will return true if
+// the last approximation operation is complete and will dispatch any pending messages.
+// If you call 'Compute' while a previous operation was still running, it will automatically cancel the last request
+// and begin a new one. To cancel a currently running approximation just call 'Cancel'.
+#include <stdint.h>
+
+namespace VHACD {
+class IVHACD {
+public:
+ class IUserCallback {
+ public:
+ virtual ~IUserCallback(){};
+ virtual void Update(const double overallProgress,
+ const double stageProgress,
+ const double operationProgress,
+ const char* const stage,
+ const char* const operation)
+ = 0;
+ };
+
+ class IUserLogger {
+ public:
+ virtual ~IUserLogger(){};
+ virtual void Log(const char* const msg) = 0;
+ };
+
+ class ConvexHull {
+ public:
+ double* m_points;
+ uint32_t* m_triangles;
+ uint32_t m_nPoints;
+ uint32_t m_nTriangles;
+ double m_volume;
+ double m_center[3];
+ };
+
+ class Parameters {
+ public:
+ Parameters(void) { Init(); }
+ void Init(void)
+ {
+ m_resolution = 100000;
+ m_concavity = 0.001;
+ m_planeDownsampling = 4;
+ m_convexhullDownsampling = 4;
+ m_alpha = 0.05;
+ m_beta = 0.05;
+ m_pca = 0;
+ m_mode = 0; // 0: voxel-based (recommended), 1: tetrahedron-based
+ m_maxNumVerticesPerCH = 64;
+ m_minVolumePerCH = 0.0001;
+ m_callback = 0;
+ m_logger = 0;
+ m_convexhullApproximation = true;
+ m_oclAcceleration = true;
+ m_maxConvexHulls = 1024;
+ m_projectHullVertices = true; // This will project the output convex hull vertices onto the original source mesh to increase the floating point accuracy of the results
+ }
+ double m_concavity;
+ double m_alpha;
+ double m_beta;
+ double m_minVolumePerCH;
+ IUserCallback* m_callback;
+ IUserLogger* m_logger;
+ uint32_t m_resolution;
+ uint32_t m_maxNumVerticesPerCH;
+ uint32_t m_planeDownsampling;
+ uint32_t m_convexhullDownsampling;
+ uint32_t m_pca;
+ uint32_t m_mode;
+ uint32_t m_convexhullApproximation;
+ uint32_t m_oclAcceleration;
+ uint32_t m_maxConvexHulls;
+ bool m_projectHullVertices;
+ };
+
+ virtual void Cancel() = 0;
+ virtual bool Compute(const float* const points,
+ const uint32_t countPoints,
+ const uint32_t* const triangles,
+ const uint32_t countTriangles,
+ const Parameters& params)
+ = 0;
+ virtual bool Compute(const double* const points,
+ const uint32_t countPoints,
+ const uint32_t* const triangles,
+ const uint32_t countTriangles,
+ const Parameters& params)
+ = 0;
+ virtual uint32_t GetNConvexHulls() const = 0;
+ virtual void GetConvexHull(const uint32_t index, ConvexHull& ch) const = 0;
+ virtual void Clean(void) = 0; // release internally allocated memory
+ virtual void Release(void) = 0; // release IVHACD
+ virtual bool OCLInit(void* const oclDevice,
+ IUserLogger* const logger = 0)
+ = 0;
+ virtual bool OCLRelease(IUserLogger* const logger = 0) = 0;
+
+ // Will compute the center of mass of the convex hull decomposition results and return it
+ // in 'centerOfMass'. Returns false if the center of mass could not be computed.
+ virtual bool ComputeCenterOfMass(double centerOfMass[3]) const = 0;
+
+ // In synchronous mode (non-multi-threaded) the state is always 'ready'
+ // In asynchronous mode, this returns true if the background thread is not still actively computing
+ // a new solution. In an asynchronous config the 'IsReady' call will report any update or log
+ // messages in the caller's current thread.
+ virtual bool IsReady(void) const
+ {
+ return true;
+ }
+
+protected:
+ virtual ~IVHACD(void) {}
+};
+IVHACD* CreateVHACD(void);
+IVHACD* CreateVHACD_ASYNC(void);
+}
+#endif // VHACD_H
diff --git a/thirdparty/vhacd/src/FloatMath.cpp b/thirdparty/vhacd/src/FloatMath.cpp
new file mode 100644
index 0000000000..481e875104
--- /dev/null
+++ b/thirdparty/vhacd/src/FloatMath.cpp
@@ -0,0 +1,17 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <math.h>
+#include <float.h>
+#include "FloatMath.h"
+#include <vector>
+
+#define REAL float
+
+#include "FloatMath.inl"
+
+#undef REAL
+#define REAL double
+
+#include "FloatMath.inl"
diff --git a/thirdparty/vhacd/src/FloatMath.inl b/thirdparty/vhacd/src/FloatMath.inl
new file mode 100644
index 0000000000..ce529e6f71
--- /dev/null
+++ b/thirdparty/vhacd/src/FloatMath.inl
@@ -0,0 +1,5276 @@
+// a set of routines that let you do common 3d math
+// operations without any vector, matrix, or quaternion
+// classes or templates.
+//
+// a vector (or point) is a 'float *' to 3 floating point numbers.
+// a matrix is a 'float *' to an array of 16 floating point numbers representing a 4x4 transformation matrix compatible with D3D or OGL
+// a quaternion is a 'float *' to 4 floats representing a quaternion x,y,z,w
+//
+
+namespace FLOAT_MATH
+{
+
+void fm_inverseRT(const REAL matrix[16],const REAL pos[3],REAL t[3]) // inverse rotate translate the point.
+{
+
+ REAL _x = pos[0] - matrix[3*4+0];
+ REAL _y = pos[1] - matrix[3*4+1];
+ REAL _z = pos[2] - matrix[3*4+2];
+
+ // Multiply inverse-translated source vector by inverted rotation transform
+
+ t[0] = (matrix[0*4+0] * _x) + (matrix[0*4+1] * _y) + (matrix[0*4+2] * _z);
+ t[1] = (matrix[1*4+0] * _x) + (matrix[1*4+1] * _y) + (matrix[1*4+2] * _z);
+ t[2] = (matrix[2*4+0] * _x) + (matrix[2*4+1] * _y) + (matrix[2*4+2] * _z);
+
+}
+
+REAL fm_getDeterminant(const REAL matrix[16])
+{
+ REAL tempv[3];
+ REAL p0[3];
+ REAL p1[3];
+ REAL p2[3];
+
+
+ p0[0] = matrix[0*4+0];
+ p0[1] = matrix[0*4+1];
+ p0[2] = matrix[0*4+2];
+
+ p1[0] = matrix[1*4+0];
+ p1[1] = matrix[1*4+1];
+ p1[2] = matrix[1*4+2];
+
+ p2[0] = matrix[2*4+0];
+ p2[1] = matrix[2*4+1];
+ p2[2] = matrix[2*4+2];
+
+ fm_cross(tempv,p1,p2);
+
+ return fm_dot(p0,tempv);
+
+}
+
+REAL fm_squared(REAL x) { return x*x; };
+
+void fm_decomposeTransform(const REAL local_transform[16],REAL trans[3],REAL rot[4],REAL scale[3])
+{
+
+ trans[0] = local_transform[12];
+ trans[1] = local_transform[13];
+ trans[2] = local_transform[14];
+
+ scale[0] = (REAL)sqrt(fm_squared(local_transform[0*4+0]) + fm_squared(local_transform[0*4+1]) + fm_squared(local_transform[0*4+2]));
+ scale[1] = (REAL)sqrt(fm_squared(local_transform[1*4+0]) + fm_squared(local_transform[1*4+1]) + fm_squared(local_transform[1*4+2]));
+ scale[2] = (REAL)sqrt(fm_squared(local_transform[2*4+0]) + fm_squared(local_transform[2*4+1]) + fm_squared(local_transform[2*4+2]));
+
+ REAL m[16];
+ memcpy(m,local_transform,sizeof(REAL)*16);
+
+ REAL sx = 1.0f / scale[0];
+ REAL sy = 1.0f / scale[1];
+ REAL sz = 1.0f / scale[2];
+
+ m[0*4+0]*=sx;
+ m[0*4+1]*=sx;
+ m[0*4+2]*=sx;
+
+ m[1*4+0]*=sy;
+ m[1*4+1]*=sy;
+ m[1*4+2]*=sy;
+
+ m[2*4+0]*=sz;
+ m[2*4+1]*=sz;
+ m[2*4+2]*=sz;
+
+ fm_matrixToQuat(m,rot);
+
+}
+
+void fm_getSubMatrix(int32_t ki,int32_t kj,REAL pDst[16],const REAL matrix[16])
+{
+ int32_t row, col;
+ int32_t dstCol = 0, dstRow = 0;
+
+ for ( col = 0; col < 4; col++ )
+ {
+ if ( col == kj )
+ {
+ continue;
+ }
+ for ( dstRow = 0, row = 0; row < 4; row++ )
+ {
+ if ( row == ki )
+ {
+ continue;
+ }
+ pDst[dstCol*4+dstRow] = matrix[col*4+row];
+ dstRow++;
+ }
+ dstCol++;
+ }
+}
+
+void fm_inverseTransform(const REAL matrix[16],REAL inverse_matrix[16])
+{
+ REAL determinant = fm_getDeterminant(matrix);
+ determinant = 1.0f / determinant;
+ for (int32_t i = 0; i < 4; i++ )
+ {
+ for (int32_t j = 0; j < 4; j++ )
+ {
+ int32_t sign = 1 - ( ( i + j ) % 2 ) * 2;
+ REAL subMat[16];
+ fm_identity(subMat);
+ fm_getSubMatrix( i, j, subMat, matrix );
+ REAL subDeterminant = fm_getDeterminant(subMat);
+ inverse_matrix[i*4+j] = ( subDeterminant * sign ) * determinant;
+ }
+ }
+}
+
+void fm_identity(REAL matrix[16]) // set 4x4 matrix to identity.
+{
+ matrix[0*4+0] = 1;
+ matrix[1*4+1] = 1;
+ matrix[2*4+2] = 1;
+ matrix[3*4+3] = 1;
+
+ matrix[1*4+0] = 0;
+ matrix[2*4+0] = 0;
+ matrix[3*4+0] = 0;
+
+ matrix[0*4+1] = 0;
+ matrix[2*4+1] = 0;
+ matrix[3*4+1] = 0;
+
+ matrix[0*4+2] = 0;
+ matrix[1*4+2] = 0;
+ matrix[3*4+2] = 0;
+
+ matrix[0*4+3] = 0;
+ matrix[1*4+3] = 0;
+ matrix[2*4+3] = 0;
+
+}
+
+void fm_quatToEuler(const REAL quat[4],REAL &ax,REAL &ay,REAL &az)
+{
+ REAL x = quat[0];
+ REAL y = quat[1];
+ REAL z = quat[2];
+ REAL w = quat[3];
+
+ REAL sint = (2.0f * w * y) - (2.0f * x * z);
+ REAL cost_temp = 1.0f - (sint * sint);
+ REAL cost = 0;
+
+ if ( (REAL)fabs(cost_temp) > 0.001f )
+ {
+ cost = (REAL)sqrt( cost_temp );
+ }
+
+ REAL sinv, cosv, sinf, cosf;
+ if ( (REAL)fabs(cost) > 0.001f )
+ {
+ cost = 1.0f / cost;
+ sinv = ((2.0f * y * z) + (2.0f * w * x)) * cost;
+ cosv = (1.0f - (2.0f * x * x) - (2.0f * y * y)) * cost;
+ sinf = ((2.0f * x * y) + (2.0f * w * z)) * cost;
+ cosf = (1.0f - (2.0f * y * y) - (2.0f * z * z)) * cost;
+ }
+ else
+ {
+ sinv = (2.0f * w * x) - (2.0f * y * z);
+ cosv = 1.0f - (2.0f * x * x) - (2.0f * z * z);
+ sinf = 0;
+ cosf = 1.0f;
+ }
+
+ // compute output rotations
+ ax = (REAL)atan2( sinv, cosv );
+ ay = (REAL)atan2( sint, cost );
+ az = (REAL)atan2( sinf, cosf );
+
+}
+
+void fm_eulerToMatrix(REAL ax,REAL ay,REAL az,REAL *matrix) // convert euler (in radians) to a dest 4x4 matrix (translation set to zero)
+{
+ REAL quat[4];
+ fm_eulerToQuat(ax,ay,az,quat);
+ fm_quatToMatrix(quat,matrix);
+}
+
+void fm_getAABB(uint32_t vcount,const REAL *points,uint32_t pstride,REAL *bmin,REAL *bmax)
+{
+
+ const uint8_t *source = (const uint8_t *) points;
+
+ bmin[0] = points[0];
+ bmin[1] = points[1];
+ bmin[2] = points[2];
+
+ bmax[0] = points[0];
+ bmax[1] = points[1];
+ bmax[2] = points[2];
+
+
+ for (uint32_t i=1; i<vcount; i++)
+ {
+ source+=pstride;
+ const REAL *p = (const REAL *) source;
+
+ if ( p[0] < bmin[0] ) bmin[0] = p[0];
+ if ( p[1] < bmin[1] ) bmin[1] = p[1];
+ if ( p[2] < bmin[2] ) bmin[2] = p[2];
+
+ if ( p[0] > bmax[0] ) bmax[0] = p[0];
+ if ( p[1] > bmax[1] ) bmax[1] = p[1];
+ if ( p[2] > bmax[2] ) bmax[2] = p[2];
+
+ }
+}
+
+void fm_eulerToQuat(const REAL *euler,REAL *quat) // convert euler angles to quaternion.
+{
+ fm_eulerToQuat(euler[0],euler[1],euler[2],quat);
+}
+
+void fm_eulerToQuat(REAL roll,REAL pitch,REAL yaw,REAL *quat) // convert euler angles to quaternion.
+{
+ roll *= 0.5f;
+ pitch *= 0.5f;
+ yaw *= 0.5f;
+
+ REAL cr = (REAL)cos(roll);
+ REAL cp = (REAL)cos(pitch);
+ REAL cy = (REAL)cos(yaw);
+
+ REAL sr = (REAL)sin(roll);
+ REAL sp = (REAL)sin(pitch);
+ REAL sy = (REAL)sin(yaw);
+
+ REAL cpcy = cp * cy;
+ REAL spsy = sp * sy;
+ REAL spcy = sp * cy;
+ REAL cpsy = cp * sy;
+
+ quat[0] = ( sr * cpcy - cr * spsy);
+ quat[1] = ( cr * spcy + sr * cpsy);
+ quat[2] = ( cr * cpsy - sr * spcy);
+ quat[3] = cr * cpcy + sr * spsy;
+}
+
+void fm_quatToMatrix(const REAL *quat,REAL *matrix) // convert quaterinion rotation to matrix, zeros out the translation component.
+{
+
+ REAL xx = quat[0]*quat[0];
+ REAL yy = quat[1]*quat[1];
+ REAL zz = quat[2]*quat[2];
+ REAL xy = quat[0]*quat[1];
+ REAL xz = quat[0]*quat[2];
+ REAL yz = quat[1]*quat[2];
+ REAL wx = quat[3]*quat[0];
+ REAL wy = quat[3]*quat[1];
+ REAL wz = quat[3]*quat[2];
+
+ matrix[0*4+0] = 1 - 2 * ( yy + zz );
+ matrix[1*4+0] = 2 * ( xy - wz );
+ matrix[2*4+0] = 2 * ( xz + wy );
+
+ matrix[0*4+1] = 2 * ( xy + wz );
+ matrix[1*4+1] = 1 - 2 * ( xx + zz );
+ matrix[2*4+1] = 2 * ( yz - wx );
+
+ matrix[0*4+2] = 2 * ( xz - wy );
+ matrix[1*4+2] = 2 * ( yz + wx );
+ matrix[2*4+2] = 1 - 2 * ( xx + yy );
+
+ matrix[3*4+0] = matrix[3*4+1] = matrix[3*4+2] = (REAL) 0.0f;
+ matrix[0*4+3] = matrix[1*4+3] = matrix[2*4+3] = (REAL) 0.0f;
+ matrix[3*4+3] =(REAL) 1.0f;
+
+}
+
+
+void fm_quatRotate(const REAL *quat,const REAL *v,REAL *r) // rotate a vector directly by a quaternion.
+{
+ REAL left[4];
+
+ left[0] = quat[3]*v[0] + quat[1]*v[2] - v[1]*quat[2];
+ left[1] = quat[3]*v[1] + quat[2]*v[0] - v[2]*quat[0];
+ left[2] = quat[3]*v[2] + quat[0]*v[1] - v[0]*quat[1];
+ left[3] = - quat[0]*v[0] - quat[1]*v[1] - quat[2]*v[2];
+
+ r[0] = (left[3]*-quat[0]) + (quat[3]*left[0]) + (left[1]*-quat[2]) - (-quat[1]*left[2]);
+ r[1] = (left[3]*-quat[1]) + (quat[3]*left[1]) + (left[2]*-quat[0]) - (-quat[2]*left[0]);
+ r[2] = (left[3]*-quat[2]) + (quat[3]*left[2]) + (left[0]*-quat[1]) - (-quat[0]*left[1]);
+
+}
+
+
+void fm_getTranslation(const REAL *matrix,REAL *t)
+{
+ t[0] = matrix[3*4+0];
+ t[1] = matrix[3*4+1];
+ t[2] = matrix[3*4+2];
+}
+
+void fm_matrixToQuat(const REAL *matrix,REAL *quat) // convert the 3x3 portion of a 4x4 matrix into a quaterion as x,y,z,w
+{
+
+ REAL tr = matrix[0*4+0] + matrix[1*4+1] + matrix[2*4+2];
+
+ // check the diagonal
+
+ if (tr > 0.0f )
+ {
+ REAL s = (REAL) sqrt ( (double) (tr + 1.0f) );
+ quat[3] = s * 0.5f;
+ s = 0.5f / s;
+ quat[0] = (matrix[1*4+2] - matrix[2*4+1]) * s;
+ quat[1] = (matrix[2*4+0] - matrix[0*4+2]) * s;
+ quat[2] = (matrix[0*4+1] - matrix[1*4+0]) * s;
+
+ }
+ else
+ {
+ // diagonal is negative
+ int32_t nxt[3] = {1, 2, 0};
+ REAL qa[4];
+
+ int32_t i = 0;
+
+ if (matrix[1*4+1] > matrix[0*4+0]) i = 1;
+ if (matrix[2*4+2] > matrix[i*4+i]) i = 2;
+
+ int32_t j = nxt[i];
+ int32_t k = nxt[j];
+
+ REAL s = (REAL)sqrt ( ((matrix[i*4+i] - (matrix[j*4+j] + matrix[k*4+k])) + 1.0f) );
+
+ qa[i] = s * 0.5f;
+
+ if (s != 0.0f ) s = 0.5f / s;
+
+ qa[3] = (matrix[j*4+k] - matrix[k*4+j]) * s;
+ qa[j] = (matrix[i*4+j] + matrix[j*4+i]) * s;
+ qa[k] = (matrix[i*4+k] + matrix[k*4+i]) * s;
+
+ quat[0] = qa[0];
+ quat[1] = qa[1];
+ quat[2] = qa[2];
+ quat[3] = qa[3];
+ }
+// fm_normalizeQuat(quat);
+}
+
+
+REAL fm_sphereVolume(REAL radius) // return's the volume of a sphere of this radius (4/3 PI * R cubed )
+{
+ return (4.0f / 3.0f ) * FM_PI * radius * radius * radius;
+}
+
+
+REAL fm_cylinderVolume(REAL radius,REAL h)
+{
+ return FM_PI * radius * radius *h;
+}
+
+REAL fm_capsuleVolume(REAL radius,REAL h)
+{
+ REAL volume = fm_sphereVolume(radius); // volume of the sphere portion.
+ REAL ch = h-radius*2; // this is the cylinder length
+ if ( ch > 0 )
+ {
+ volume+=fm_cylinderVolume(radius,ch);
+ }
+ return volume;
+}
+
+void fm_transform(const REAL matrix[16],const REAL v[3],REAL t[3]) // rotate and translate this point
+{
+ if ( matrix )
+ {
+ REAL tx = (matrix[0*4+0] * v[0]) + (matrix[1*4+0] * v[1]) + (matrix[2*4+0] * v[2]) + matrix[3*4+0];
+ REAL ty = (matrix[0*4+1] * v[0]) + (matrix[1*4+1] * v[1]) + (matrix[2*4+1] * v[2]) + matrix[3*4+1];
+ REAL tz = (matrix[0*4+2] * v[0]) + (matrix[1*4+2] * v[1]) + (matrix[2*4+2] * v[2]) + matrix[3*4+2];
+ t[0] = tx;
+ t[1] = ty;
+ t[2] = tz;
+ }
+ else
+ {
+ t[0] = v[0];
+ t[1] = v[1];
+ t[2] = v[2];
+ }
+}
+
+void fm_rotate(const REAL matrix[16],const REAL v[3],REAL t[3]) // rotate and translate this point
+{
+ if ( matrix )
+ {
+ REAL tx = (matrix[0*4+0] * v[0]) + (matrix[1*4+0] * v[1]) + (matrix[2*4+0] * v[2]);
+ REAL ty = (matrix[0*4+1] * v[0]) + (matrix[1*4+1] * v[1]) + (matrix[2*4+1] * v[2]);
+ REAL tz = (matrix[0*4+2] * v[0]) + (matrix[1*4+2] * v[1]) + (matrix[2*4+2] * v[2]);
+ t[0] = tx;
+ t[1] = ty;
+ t[2] = tz;
+ }
+ else
+ {
+ t[0] = v[0];
+ t[1] = v[1];
+ t[2] = v[2];
+ }
+}
+
+
+REAL fm_distance(const REAL *p1,const REAL *p2)
+{
+ REAL dx = p1[0] - p2[0];
+ REAL dy = p1[1] - p2[1];
+ REAL dz = p1[2] - p2[2];
+
+ return (REAL)sqrt( dx*dx + dy*dy + dz *dz );
+}
+
+REAL fm_distanceSquared(const REAL *p1,const REAL *p2)
+{
+ REAL dx = p1[0] - p2[0];
+ REAL dy = p1[1] - p2[1];
+ REAL dz = p1[2] - p2[2];
+
+ return dx*dx + dy*dy + dz *dz;
+}
+
+
+REAL fm_distanceSquaredXZ(const REAL *p1,const REAL *p2)
+{
+ REAL dx = p1[0] - p2[0];
+ REAL dz = p1[2] - p2[2];
+
+ return dx*dx + dz *dz;
+}
+
+
+REAL fm_computePlane(const REAL *A,const REAL *B,const REAL *C,REAL *n) // returns D
+{
+ REAL vx = (B[0] - C[0]);
+ REAL vy = (B[1] - C[1]);
+ REAL vz = (B[2] - C[2]);
+
+ REAL wx = (A[0] - B[0]);
+ REAL wy = (A[1] - B[1]);
+ REAL wz = (A[2] - B[2]);
+
+ REAL vw_x = vy * wz - vz * wy;
+ REAL vw_y = vz * wx - vx * wz;
+ REAL vw_z = vx * wy - vy * wx;
+
+ REAL mag = (REAL)sqrt((vw_x * vw_x) + (vw_y * vw_y) + (vw_z * vw_z));
+
+ if ( mag < 0.000001f )
+ {
+ mag = 0;
+ }
+ else
+ {
+ mag = 1.0f/mag;
+ }
+
+ REAL x = vw_x * mag;
+ REAL y = vw_y * mag;
+ REAL z = vw_z * mag;
+
+
+ REAL D = 0.0f - ((x*A[0])+(y*A[1])+(z*A[2]));
+
+ n[0] = x;
+ n[1] = y;
+ n[2] = z;
+
+ return D;
+}
+
+REAL fm_distToPlane(const REAL *plane,const REAL *p) // computes the distance of this point from the plane.
+{
+ return p[0]*plane[0]+p[1]*plane[1]+p[2]*plane[2]+plane[3];
+}
+
+REAL fm_dot(const REAL *p1,const REAL *p2)
+{
+ return p1[0]*p2[0]+p1[1]*p2[1]+p1[2]*p2[2];
+}
+
+void fm_cross(REAL *cross,const REAL *a,const REAL *b)
+{
+ cross[0] = a[1]*b[2] - a[2]*b[1];
+ cross[1] = a[2]*b[0] - a[0]*b[2];
+ cross[2] = a[0]*b[1] - a[1]*b[0];
+}
+
+REAL fm_computeNormalVector(REAL *n,const REAL *p1,const REAL *p2)
+{
+ n[0] = p2[0] - p1[0];
+ n[1] = p2[1] - p1[1];
+ n[2] = p2[2] - p1[2];
+ return fm_normalize(n);
+}
+
+bool fm_computeWindingOrder(const REAL *p1,const REAL *p2,const REAL *p3) // returns true if the triangle is clockwise.
+{
+ bool ret = false;
+
+ REAL v1[3];
+ REAL v2[3];
+
+ fm_computeNormalVector(v1,p1,p2); // p2-p1 (as vector) and then normalized
+ fm_computeNormalVector(v2,p1,p3); // p3-p1 (as vector) and then normalized
+
+ REAL cross[3];
+
+ fm_cross(cross, v1, v2 );
+ REAL ref[3] = { 1, 0, 0 };
+
+ REAL d = fm_dot( cross, ref );
+
+
+ if ( d <= 0 )
+ ret = false;
+ else
+ ret = true;
+
+ return ret;
+}
+
+REAL fm_normalize(REAL *n) // normalize this vector
+{
+ REAL dist = (REAL)sqrt(n[0]*n[0] + n[1]*n[1] + n[2]*n[2]);
+ if ( dist > 0.0000001f )
+ {
+ REAL mag = 1.0f / dist;
+ n[0]*=mag;
+ n[1]*=mag;
+ n[2]*=mag;
+ }
+ else
+ {
+ n[0] = 1;
+ n[1] = 0;
+ n[2] = 0;
+ }
+
+ return dist;
+}
+
+
+void fm_matrixMultiply(const REAL *pA,const REAL *pB,REAL *pM)
+{
+#if 1
+
+ REAL a = pA[0*4+0] * pB[0*4+0] + pA[0*4+1] * pB[1*4+0] + pA[0*4+2] * pB[2*4+0] + pA[0*4+3] * pB[3*4+0];
+ REAL b = pA[0*4+0] * pB[0*4+1] + pA[0*4+1] * pB[1*4+1] + pA[0*4+2] * pB[2*4+1] + pA[0*4+3] * pB[3*4+1];
+ REAL c = pA[0*4+0] * pB[0*4+2] + pA[0*4+1] * pB[1*4+2] + pA[0*4+2] * pB[2*4+2] + pA[0*4+3] * pB[3*4+2];
+ REAL d = pA[0*4+0] * pB[0*4+3] + pA[0*4+1] * pB[1*4+3] + pA[0*4+2] * pB[2*4+3] + pA[0*4+3] * pB[3*4+3];
+
+ REAL e = pA[1*4+0] * pB[0*4+0] + pA[1*4+1] * pB[1*4+0] + pA[1*4+2] * pB[2*4+0] + pA[1*4+3] * pB[3*4+0];
+ REAL f = pA[1*4+0] * pB[0*4+1] + pA[1*4+1] * pB[1*4+1] + pA[1*4+2] * pB[2*4+1] + pA[1*4+3] * pB[3*4+1];
+ REAL g = pA[1*4+0] * pB[0*4+2] + pA[1*4+1] * pB[1*4+2] + pA[1*4+2] * pB[2*4+2] + pA[1*4+3] * pB[3*4+2];
+ REAL h = pA[1*4+0] * pB[0*4+3] + pA[1*4+1] * pB[1*4+3] + pA[1*4+2] * pB[2*4+3] + pA[1*4+3] * pB[3*4+3];
+
+ REAL i = pA[2*4+0] * pB[0*4+0] + pA[2*4+1] * pB[1*4+0] + pA[2*4+2] * pB[2*4+0] + pA[2*4+3] * pB[3*4+0];
+ REAL j = pA[2*4+0] * pB[0*4+1] + pA[2*4+1] * pB[1*4+1] + pA[2*4+2] * pB[2*4+1] + pA[2*4+3] * pB[3*4+1];
+ REAL k = pA[2*4+0] * pB[0*4+2] + pA[2*4+1] * pB[1*4+2] + pA[2*4+2] * pB[2*4+2] + pA[2*4+3] * pB[3*4+2];
+ REAL l = pA[2*4+0] * pB[0*4+3] + pA[2*4+1] * pB[1*4+3] + pA[2*4+2] * pB[2*4+3] + pA[2*4+3] * pB[3*4+3];
+
+ REAL m = pA[3*4+0] * pB[0*4+0] + pA[3*4+1] * pB[1*4+0] + pA[3*4+2] * pB[2*4+0] + pA[3*4+3] * pB[3*4+0];
+ REAL n = pA[3*4+0] * pB[0*4+1] + pA[3*4+1] * pB[1*4+1] + pA[3*4+2] * pB[2*4+1] + pA[3*4+3] * pB[3*4+1];
+ REAL o = pA[3*4+0] * pB[0*4+2] + pA[3*4+1] * pB[1*4+2] + pA[3*4+2] * pB[2*4+2] + pA[3*4+3] * pB[3*4+2];
+ REAL p = pA[3*4+0] * pB[0*4+3] + pA[3*4+1] * pB[1*4+3] + pA[3*4+2] * pB[2*4+3] + pA[3*4+3] * pB[3*4+3];
+
+ pM[0] = a;
+ pM[1] = b;
+ pM[2] = c;
+ pM[3] = d;
+
+ pM[4] = e;
+ pM[5] = f;
+ pM[6] = g;
+ pM[7] = h;
+
+ pM[8] = i;
+ pM[9] = j;
+ pM[10] = k;
+ pM[11] = l;
+
+ pM[12] = m;
+ pM[13] = n;
+ pM[14] = o;
+ pM[15] = p;
+
+
+#else
+ memset(pM, 0, sizeof(REAL)*16);
+ for(int32_t i=0; i<4; i++ )
+ for(int32_t j=0; j<4; j++ )
+ for(int32_t k=0; k<4; k++ )
+ pM[4*i+j] += pA[4*i+k] * pB[4*k+j];
+#endif
+}
+
+
+void fm_eulerToQuatDX(REAL x,REAL y,REAL z,REAL *quat) // convert euler angles to quaternion using the fucked up DirectX method
+{
+ REAL matrix[16];
+ fm_eulerToMatrix(x,y,z,matrix);
+ fm_matrixToQuat(matrix,quat);
+}
+
+// implementation copied from: http://blogs.msdn.com/mikepelton/archive/2004/10/29/249501.aspx
+void fm_eulerToMatrixDX(REAL x,REAL y,REAL z,REAL *matrix) // convert euler angles to quaternion using the fucked up DirectX method.
+{
+ fm_identity(matrix);
+ matrix[0*4+0] = (REAL)(cos(z)*cos(y) + sin(z)*sin(x)*sin(y));
+ matrix[0*4+1] = (REAL)(sin(z)*cos(x));
+ matrix[0*4+2] = (REAL)(cos(z)*-sin(y) + sin(z)*sin(x)*cos(y));
+
+ matrix[1*4+0] = (REAL)(-sin(z)*cos(y)+cos(z)*sin(x)*sin(y));
+ matrix[1*4+1] = (REAL)(cos(z)*cos(x));
+ matrix[1*4+2] = (REAL)(sin(z)*sin(y) +cos(z)*sin(x)*cos(y));
+
+ matrix[2*4+0] = (REAL)(cos(x)*sin(y));
+ matrix[2*4+1] = (REAL)(-sin(x));
+ matrix[2*4+2] = (REAL)(cos(x)*cos(y));
+}
+
+
+void fm_scale(REAL x,REAL y,REAL z,REAL *fscale) // apply scale to the matrix.
+{
+ fscale[0*4+0] = x;
+ fscale[1*4+1] = y;
+ fscale[2*4+2] = z;
+}
+
+
+void fm_composeTransform(const REAL *position,const REAL *quat,const REAL *scale,REAL *matrix)
+{
+ fm_identity(matrix);
+ fm_quatToMatrix(quat,matrix);
+
+ if ( scale && ( scale[0] != 1 || scale[1] != 1 || scale[2] != 1 ) )
+ {
+ REAL work[16];
+ memcpy(work,matrix,sizeof(REAL)*16);
+ REAL mscale[16];
+ fm_identity(mscale);
+ fm_scale(scale[0],scale[1],scale[2],mscale);
+ fm_matrixMultiply(work,mscale,matrix);
+ }
+
+ matrix[12] = position[0];
+ matrix[13] = position[1];
+ matrix[14] = position[2];
+}
+
+
+void fm_setTranslation(const REAL *translation,REAL *matrix)
+{
+ matrix[12] = translation[0];
+ matrix[13] = translation[1];
+ matrix[14] = translation[2];
+}
+
+static REAL enorm0_3d ( REAL x0, REAL y0, REAL z0, REAL x1, REAL y1, REAL z1 )
+
+/**********************************************************************/
+
+/*
+Purpose:
+
+ENORM0_3D computes the Euclidean norm of (P1-P0) in 3D.
+
+Modified:
+
+18 April 1999
+
+Author:
+
+John Burkardt
+
+Parameters:
+
+Input, REAL X0, Y0, Z0, X1, Y1, Z1, the coordinates of the points
+P0 and P1.
+
+Output, REAL ENORM0_3D, the Euclidean norm of (P1-P0).
+*/
+{
+ REAL value;
+
+ value = (REAL)sqrt (
+ ( x1 - x0 ) * ( x1 - x0 ) +
+ ( y1 - y0 ) * ( y1 - y0 ) +
+ ( z1 - z0 ) * ( z1 - z0 ) );
+
+ return value;
+}
+
+
+static REAL triangle_area_3d ( REAL x1, REAL y1, REAL z1, REAL x2,REAL y2, REAL z2, REAL x3, REAL y3, REAL z3 )
+
+ /**********************************************************************/
+
+ /*
+ Purpose:
+
+ TRIANGLE_AREA_3D computes the area of a triangle in 3D.
+
+ Modified:
+
+ 22 April 1999
+
+ Author:
+
+ John Burkardt
+
+ Parameters:
+
+ Input, REAL X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3, the (X,Y,Z)
+ coordinates of the corners of the triangle.
+
+ Output, REAL TRIANGLE_AREA_3D, the area of the triangle.
+ */
+{
+ REAL a;
+ REAL alpha;
+ REAL area;
+ REAL b;
+ REAL base;
+ REAL c;
+ REAL dot;
+ REAL height;
+ /*
+ Find the projection of (P3-P1) onto (P2-P1).
+ */
+ dot =
+ ( x2 - x1 ) * ( x3 - x1 ) +
+ ( y2 - y1 ) * ( y3 - y1 ) +
+ ( z2 - z1 ) * ( z3 - z1 );
+
+ base = enorm0_3d ( x1, y1, z1, x2, y2, z2 );
+ /*
+ The height of the triangle is the length of (P3-P1) after its
+ projection onto (P2-P1) has been subtracted.
+ */
+ if ( base == 0.0 ) {
+
+ height = 0.0;
+
+ }
+ else {
+
+ alpha = dot / ( base * base );
+
+ a = x3 - x1 - alpha * ( x2 - x1 );
+ b = y3 - y1 - alpha * ( y2 - y1 );
+ c = z3 - z1 - alpha * ( z2 - z1 );
+
+ height = (REAL)sqrt ( a * a + b * b + c * c );
+
+ }
+
+ area = 0.5f * base * height;
+
+ return area;
+}
+
+
+REAL fm_computeArea(const REAL *p1,const REAL *p2,const REAL *p3)
+{
+ REAL ret = 0;
+
+ ret = triangle_area_3d(p1[0],p1[1],p1[2],p2[0],p2[1],p2[2],p3[0],p3[1],p3[2]);
+
+ return ret;
+}
+
+
+void fm_lerp(const REAL *p1,const REAL *p2,REAL *dest,REAL lerpValue)
+{
+ dest[0] = ((p2[0] - p1[0])*lerpValue) + p1[0];
+ dest[1] = ((p2[1] - p1[1])*lerpValue) + p1[1];
+ dest[2] = ((p2[2] - p1[2])*lerpValue) + p1[2];
+}
+
+bool fm_pointTestXZ(const REAL *p,const REAL *i,const REAL *j)
+{
+ bool ret = false;
+
+ if (((( i[2] <= p[2] ) && ( p[2] < j[2] )) || (( j[2] <= p[2] ) && ( p[2] < i[2] ))) && ( p[0] < (j[0] - i[0]) * (p[2] - i[2]) / (j[2] - i[2]) + i[0]))
+ ret = true;
+
+ return ret;
+};
+
+
+bool fm_insideTriangleXZ(const REAL *p,const REAL *p1,const REAL *p2,const REAL *p3)
+{
+ bool ret = false;
+
+ int32_t c = 0;
+ if ( fm_pointTestXZ(p,p1,p2) ) c = !c;
+ if ( fm_pointTestXZ(p,p2,p3) ) c = !c;
+ if ( fm_pointTestXZ(p,p3,p1) ) c = !c;
+ if ( c ) ret = true;
+
+ return ret;
+}
+
+bool fm_insideAABB(const REAL *pos,const REAL *bmin,const REAL *bmax)
+{
+ bool ret = false;
+
+ if ( pos[0] >= bmin[0] && pos[0] <= bmax[0] &&
+ pos[1] >= bmin[1] && pos[1] <= bmax[1] &&
+ pos[2] >= bmin[2] && pos[2] <= bmax[2] )
+ ret = true;
+
+ return ret;
+}
+
+
+uint32_t fm_clipTestPoint(const REAL *bmin,const REAL *bmax,const REAL *pos)
+{
+ uint32_t ret = 0;
+
+ if ( pos[0] < bmin[0] )
+ ret|=FMCS_XMIN;
+ else if ( pos[0] > bmax[0] )
+ ret|=FMCS_XMAX;
+
+ if ( pos[1] < bmin[1] )
+ ret|=FMCS_YMIN;
+ else if ( pos[1] > bmax[1] )
+ ret|=FMCS_YMAX;
+
+ if ( pos[2] < bmin[2] )
+ ret|=FMCS_ZMIN;
+ else if ( pos[2] > bmax[2] )
+ ret|=FMCS_ZMAX;
+
+ return ret;
+}
+
+uint32_t fm_clipTestPointXZ(const REAL *bmin,const REAL *bmax,const REAL *pos) // only tests X and Z, not Y
+{
+ uint32_t ret = 0;
+
+ if ( pos[0] < bmin[0] )
+ ret|=FMCS_XMIN;
+ else if ( pos[0] > bmax[0] )
+ ret|=FMCS_XMAX;
+
+ if ( pos[2] < bmin[2] )
+ ret|=FMCS_ZMIN;
+ else if ( pos[2] > bmax[2] )
+ ret|=FMCS_ZMAX;
+
+ return ret;
+}
+
+uint32_t fm_clipTestAABB(const REAL *bmin,const REAL *bmax,const REAL *p1,const REAL *p2,const REAL *p3,uint32_t &andCode)
+{
+ uint32_t orCode = 0;
+
+ andCode = FMCS_XMIN | FMCS_XMAX | FMCS_YMIN | FMCS_YMAX | FMCS_ZMIN | FMCS_ZMAX;
+
+ uint32_t c = fm_clipTestPoint(bmin,bmax,p1);
+ orCode|=c;
+ andCode&=c;
+
+ c = fm_clipTestPoint(bmin,bmax,p2);
+ orCode|=c;
+ andCode&=c;
+
+ c = fm_clipTestPoint(bmin,bmax,p3);
+ orCode|=c;
+ andCode&=c;
+
+ return orCode;
+}
+
+bool intersect(const REAL *si,const REAL *ei,const REAL *bmin,const REAL *bmax,REAL *time)
+{
+ REAL st,et,fst = 0,fet = 1;
+
+ for (int32_t i = 0; i < 3; i++)
+ {
+ if (*si < *ei)
+ {
+ if (*si > *bmax || *ei < *bmin)
+ return false;
+ REAL di = *ei - *si;
+ st = (*si < *bmin)? (*bmin - *si) / di: 0;
+ et = (*ei > *bmax)? (*bmax - *si) / di: 1;
+ }
+ else
+ {
+ if (*ei > *bmax || *si < *bmin)
+ return false;
+ REAL di = *ei - *si;
+ st = (*si > *bmax)? (*bmax - *si) / di: 0;
+ et = (*ei < *bmin)? (*bmin - *si) / di: 1;
+ }
+
+ if (st > fst) fst = st;
+ if (et < fet) fet = et;
+ if (fet < fst)
+ return false;
+ bmin++; bmax++;
+ si++; ei++;
+ }
+
+ *time = fst;
+ return true;
+}
+
+
+
+bool fm_lineTestAABB(const REAL *p1,const REAL *p2,const REAL *bmin,const REAL *bmax,REAL &time)
+{
+ bool sect = intersect(p1,p2,bmin,bmax,&time);
+ return sect;
+}
+
+
+bool fm_lineTestAABBXZ(const REAL *p1,const REAL *p2,const REAL *bmin,const REAL *bmax,REAL &time)
+{
+ REAL _bmin[3];
+ REAL _bmax[3];
+
+ _bmin[0] = bmin[0];
+ _bmin[1] = -1e9;
+ _bmin[2] = bmin[2];
+
+ _bmax[0] = bmax[0];
+ _bmax[1] = 1e9;
+ _bmax[2] = bmax[2];
+
+ bool sect = intersect(p1,p2,_bmin,_bmax,&time);
+
+ return sect;
+}
+
+void fm_minmax(const REAL *p,REAL *bmin,REAL *bmax) // accmulate to a min-max value
+{
+
+ if ( p[0] < bmin[0] ) bmin[0] = p[0];
+ if ( p[1] < bmin[1] ) bmin[1] = p[1];
+ if ( p[2] < bmin[2] ) bmin[2] = p[2];
+
+ if ( p[0] > bmax[0] ) bmax[0] = p[0];
+ if ( p[1] > bmax[1] ) bmax[1] = p[1];
+ if ( p[2] > bmax[2] ) bmax[2] = p[2];
+
+}
+
+REAL fm_solveX(const REAL *plane,REAL y,REAL z) // solve for X given this plane equation and the other two components.
+{
+ REAL x = (y*plane[1]+z*plane[2]+plane[3]) / -plane[0];
+ return x;
+}
+
+REAL fm_solveY(const REAL *plane,REAL x,REAL z) // solve for Y given this plane equation and the other two components.
+{
+ REAL y = (x*plane[0]+z*plane[2]+plane[3]) / -plane[1];
+ return y;
+}
+
+
+REAL fm_solveZ(const REAL *plane,REAL x,REAL y) // solve for Y given this plane equation and the other two components.
+{
+ REAL z = (x*plane[0]+y*plane[1]+plane[3]) / -plane[2];
+ return z;
+}
+
+
+void fm_getAABBCenter(const REAL *bmin,const REAL *bmax,REAL *center)
+{
+ center[0] = (bmax[0]-bmin[0])*0.5f+bmin[0];
+ center[1] = (bmax[1]-bmin[1])*0.5f+bmin[1];
+ center[2] = (bmax[2]-bmin[2])*0.5f+bmin[2];
+}
+
+FM_Axis fm_getDominantAxis(const REAL normal[3])
+{
+ FM_Axis ret = FM_XAXIS;
+
+ REAL x = (REAL)fabs(normal[0]);
+ REAL y = (REAL)fabs(normal[1]);
+ REAL z = (REAL)fabs(normal[2]);
+
+ if ( y > x && y > z )
+ ret = FM_YAXIS;
+ else if ( z > x && z > y )
+ ret = FM_ZAXIS;
+
+ return ret;
+}
+
+
+bool fm_lineSphereIntersect(const REAL *center,REAL radius,const REAL *p1,const REAL *p2,REAL *intersect)
+{
+ bool ret = false;
+
+ REAL dir[3];
+
+ dir[0] = p2[0]-p1[0];
+ dir[1] = p2[1]-p1[1];
+ dir[2] = p2[2]-p1[2];
+
+ REAL distance = (REAL)sqrt( dir[0]*dir[0]+dir[1]*dir[1]+dir[2]*dir[2]);
+
+ if ( distance > 0 )
+ {
+ REAL recip = 1.0f / distance;
+ dir[0]*=recip;
+ dir[1]*=recip;
+ dir[2]*=recip;
+ ret = fm_raySphereIntersect(center,radius,p1,dir,distance,intersect);
+ }
+ else
+ {
+ dir[0] = center[0]-p1[0];
+ dir[1] = center[1]-p1[1];
+ dir[2] = center[2]-p1[2];
+ REAL d2 = dir[0]*dir[0]+dir[1]*dir[1]+dir[2]*dir[2];
+ REAL r2 = radius*radius;
+ if ( d2 < r2 )
+ {
+ ret = true;
+ if ( intersect )
+ {
+ intersect[0] = p1[0];
+ intersect[1] = p1[1];
+ intersect[2] = p1[2];
+ }
+ }
+ }
+ return ret;
+}
+
+#define DOT(p1,p2) (p1[0]*p2[0]+p1[1]*p2[1]+p1[2]*p2[2])
+
+bool fm_raySphereIntersect(const REAL *center,REAL radius,const REAL *pos,const REAL *dir,REAL distance,REAL *intersect)
+{
+ bool ret = false;
+
+ REAL E0[3];
+
+ E0[0] = center[0] - pos[0];
+ E0[1] = center[1] - pos[1];
+ E0[2] = center[2] - pos[2];
+
+ REAL V[3];
+
+ V[0] = dir[0];
+ V[1] = dir[1];
+ V[2] = dir[2];
+
+
+ REAL dist2 = E0[0]*E0[0] + E0[1]*E0[1] + E0[2] * E0[2];
+ REAL radius2 = radius*radius; // radius squared..
+
+ // Bug Fix For Gem, if origin is *inside* the sphere, invert the
+ // direction vector so that we get a valid intersection location.
+ if ( dist2 < radius2 )
+ {
+ V[0]*=-1;
+ V[1]*=-1;
+ V[2]*=-1;
+ }
+
+
+ REAL v = DOT(E0,V);
+
+ REAL disc = radius2 - (dist2 - v*v);
+
+ if (disc > 0.0f)
+ {
+ if ( intersect )
+ {
+ REAL d = (REAL)sqrt(disc);
+ REAL diff = v-d;
+ if ( diff < distance )
+ {
+ intersect[0] = pos[0]+V[0]*diff;
+ intersect[1] = pos[1]+V[1]*diff;
+ intersect[2] = pos[2]+V[2]*diff;
+ ret = true;
+ }
+ }
+ }
+
+ return ret;
+}
+
+
+void fm_catmullRom(REAL *out_vector,const REAL *p1,const REAL *p2,const REAL *p3,const REAL *p4, const REAL s)
+{
+ REAL s_squared = s * s;
+ REAL s_cubed = s_squared * s;
+
+ REAL coefficient_p1 = -s_cubed + 2*s_squared - s;
+ REAL coefficient_p2 = 3 * s_cubed - 5 * s_squared + 2;
+ REAL coefficient_p3 = -3 * s_cubed +4 * s_squared + s;
+ REAL coefficient_p4 = s_cubed - s_squared;
+
+ out_vector[0] = (coefficient_p1 * p1[0] + coefficient_p2 * p2[0] + coefficient_p3 * p3[0] + coefficient_p4 * p4[0])*0.5f;
+ out_vector[1] = (coefficient_p1 * p1[1] + coefficient_p2 * p2[1] + coefficient_p3 * p3[1] + coefficient_p4 * p4[1])*0.5f;
+ out_vector[2] = (coefficient_p1 * p1[2] + coefficient_p2 * p2[2] + coefficient_p3 * p3[2] + coefficient_p4 * p4[2])*0.5f;
+}
+
+bool fm_intersectAABB(const REAL *bmin1,const REAL *bmax1,const REAL *bmin2,const REAL *bmax2)
+{
+ if ((bmin1[0] > bmax2[0]) || (bmin2[0] > bmax1[0])) return false;
+ if ((bmin1[1] > bmax2[1]) || (bmin2[1] > bmax1[1])) return false;
+ if ((bmin1[2] > bmax2[2]) || (bmin2[2] > bmax1[2])) return false;
+ return true;
+
+}
+
+bool fm_insideAABB(const REAL *obmin,const REAL *obmax,const REAL *tbmin,const REAL *tbmax) // test if bounding box tbmin/tmbax is fully inside obmin/obmax
+{
+ bool ret = false;
+
+ if ( tbmax[0] <= obmax[0] &&
+ tbmax[1] <= obmax[1] &&
+ tbmax[2] <= obmax[2] &&
+ tbmin[0] >= obmin[0] &&
+ tbmin[1] >= obmin[1] &&
+ tbmin[2] >= obmin[2] ) ret = true;
+
+ return ret;
+}
+
+
+// Reference, from Stan Melax in Game Gems I
+// Quaternion q;
+// vector3 c = CrossProduct(v0,v1);
+// REAL d = DotProduct(v0,v1);
+// REAL s = (REAL)sqrt((1+d)*2);
+// q.x = c.x / s;
+// q.y = c.y / s;
+// q.z = c.z / s;
+// q.w = s /2.0f;
+// return q;
+void fm_rotationArc(const REAL *v0,const REAL *v1,REAL *quat)
+{
+ REAL cross[3];
+
+ fm_cross(cross,v0,v1);
+ REAL d = fm_dot(v0,v1);
+
+ if( d<= -0.99999f ) // 180 about x axis
+ {
+ if ( fabsf((float)v0[0]) < 0.1f )
+ {
+ quat[0] = 0;
+ quat[1] = v0[2];
+ quat[2] = -v0[1];
+ quat[3] = 0;
+ }
+ else
+ {
+ quat[0] = v0[1];
+ quat[1] = -v0[0];
+ quat[2] = 0;
+ quat[3] = 0;
+ }
+ REAL magnitudeSquared = quat[0]*quat[0] + quat[1]*quat[1] + quat[2]*quat[2] + quat[3]*quat[3];
+ REAL magnitude = sqrtf((float)magnitudeSquared);
+ REAL recip = 1.0f / magnitude;
+ quat[0]*=recip;
+ quat[1]*=recip;
+ quat[2]*=recip;
+ quat[3]*=recip;
+ }
+ else
+ {
+ REAL s = (REAL)sqrt((1+d)*2);
+ REAL recip = 1.0f / s;
+
+ quat[0] = cross[0] * recip;
+ quat[1] = cross[1] * recip;
+ quat[2] = cross[2] * recip;
+ quat[3] = s * 0.5f;
+ }
+}
+
+
+REAL fm_distancePointLineSegment(const REAL *Point,const REAL *LineStart,const REAL *LineEnd,REAL *intersection,LineSegmentType &type,REAL epsilon)
+{
+ REAL ret;
+
+ REAL LineMag = fm_distance( LineEnd, LineStart );
+
+ if ( LineMag > 0 )
+ {
+ REAL U = ( ( ( Point[0] - LineStart[0] ) * ( LineEnd[0] - LineStart[0] ) ) + ( ( Point[1] - LineStart[1] ) * ( LineEnd[1] - LineStart[1] ) ) + ( ( Point[2] - LineStart[2] ) * ( LineEnd[2] - LineStart[2] ) ) ) / ( LineMag * LineMag );
+ if( U < 0.0f || U > 1.0f )
+ {
+ REAL d1 = fm_distanceSquared(Point,LineStart);
+ REAL d2 = fm_distanceSquared(Point,LineEnd);
+ if ( d1 <= d2 )
+ {
+ ret = (REAL)sqrt(d1);
+ intersection[0] = LineStart[0];
+ intersection[1] = LineStart[1];
+ intersection[2] = LineStart[2];
+ type = LS_START;
+ }
+ else
+ {
+ ret = (REAL)sqrt(d2);
+ intersection[0] = LineEnd[0];
+ intersection[1] = LineEnd[1];
+ intersection[2] = LineEnd[2];
+ type = LS_END;
+ }
+ }
+ else
+ {
+ intersection[0] = LineStart[0] + U * ( LineEnd[0] - LineStart[0] );
+ intersection[1] = LineStart[1] + U * ( LineEnd[1] - LineStart[1] );
+ intersection[2] = LineStart[2] + U * ( LineEnd[2] - LineStart[2] );
+
+ ret = fm_distance(Point,intersection);
+
+ REAL d1 = fm_distanceSquared(intersection,LineStart);
+ REAL d2 = fm_distanceSquared(intersection,LineEnd);
+ REAL mag = (epsilon*2)*(epsilon*2);
+
+ if ( d1 < mag ) // if less than 1/100th the total distance, treat is as the 'start'
+ {
+ type = LS_START;
+ }
+ else if ( d2 < mag )
+ {
+ type = LS_END;
+ }
+ else
+ {
+ type = LS_MIDDLE;
+ }
+
+ }
+ }
+ else
+ {
+ ret = LineMag;
+ intersection[0] = LineEnd[0];
+ intersection[1] = LineEnd[1];
+ intersection[2] = LineEnd[2];
+ type = LS_END;
+ }
+
+ return ret;
+}
+
+
+#ifndef BEST_FIT_PLANE_H
+
+#define BEST_FIT_PLANE_H
+
+template <class Type> class Eigen
+{
+public:
+
+
+ void DecrSortEigenStuff(void)
+ {
+ Tridiagonal(); //diagonalize the matrix.
+ QLAlgorithm(); //
+ DecreasingSort();
+ GuaranteeRotation();
+ }
+
+ void Tridiagonal(void)
+ {
+ Type fM00 = mElement[0][0];
+ Type fM01 = mElement[0][1];
+ Type fM02 = mElement[0][2];
+ Type fM11 = mElement[1][1];
+ Type fM12 = mElement[1][2];
+ Type fM22 = mElement[2][2];
+
+ m_afDiag[0] = fM00;
+ m_afSubd[2] = 0;
+ if (fM02 != (Type)0.0)
+ {
+ Type fLength = (REAL)sqrt(fM01*fM01+fM02*fM02);
+ Type fInvLength = ((Type)1.0)/fLength;
+ fM01 *= fInvLength;
+ fM02 *= fInvLength;
+ Type fQ = ((Type)2.0)*fM01*fM12+fM02*(fM22-fM11);
+ m_afDiag[1] = fM11+fM02*fQ;
+ m_afDiag[2] = fM22-fM02*fQ;
+ m_afSubd[0] = fLength;
+ m_afSubd[1] = fM12-fM01*fQ;
+ mElement[0][0] = (Type)1.0;
+ mElement[0][1] = (Type)0.0;
+ mElement[0][2] = (Type)0.0;
+ mElement[1][0] = (Type)0.0;
+ mElement[1][1] = fM01;
+ mElement[1][2] = fM02;
+ mElement[2][0] = (Type)0.0;
+ mElement[2][1] = fM02;
+ mElement[2][2] = -fM01;
+ m_bIsRotation = false;
+ }
+ else
+ {
+ m_afDiag[1] = fM11;
+ m_afDiag[2] = fM22;
+ m_afSubd[0] = fM01;
+ m_afSubd[1] = fM12;
+ mElement[0][0] = (Type)1.0;
+ mElement[0][1] = (Type)0.0;
+ mElement[0][2] = (Type)0.0;
+ mElement[1][0] = (Type)0.0;
+ mElement[1][1] = (Type)1.0;
+ mElement[1][2] = (Type)0.0;
+ mElement[2][0] = (Type)0.0;
+ mElement[2][1] = (Type)0.0;
+ mElement[2][2] = (Type)1.0;
+ m_bIsRotation = true;
+ }
+ }
+
+ bool QLAlgorithm(void)
+ {
+ const int32_t iMaxIter = 32;
+
+ for (int32_t i0 = 0; i0 <3; i0++)
+ {
+ int32_t i1;
+ for (i1 = 0; i1 < iMaxIter; i1++)
+ {
+ int32_t i2;
+ for (i2 = i0; i2 <= (3-2); i2++)
+ {
+ Type fTmp = fabs(m_afDiag[i2]) + fabs(m_afDiag[i2+1]);
+ if ( fabs(m_afSubd[i2]) + fTmp == fTmp )
+ break;
+ }
+ if (i2 == i0)
+ {
+ break;
+ }
+
+ Type fG = (m_afDiag[i0+1] - m_afDiag[i0])/(((Type)2.0) * m_afSubd[i0]);
+ Type fR = (REAL)sqrt(fG*fG+(Type)1.0);
+ if (fG < (Type)0.0)
+ {
+ fG = m_afDiag[i2]-m_afDiag[i0]+m_afSubd[i0]/(fG-fR);
+ }
+ else
+ {
+ fG = m_afDiag[i2]-m_afDiag[i0]+m_afSubd[i0]/(fG+fR);
+ }
+ Type fSin = (Type)1.0, fCos = (Type)1.0, fP = (Type)0.0;
+ for (int32_t i3 = i2-1; i3 >= i0; i3--)
+ {
+ Type fF = fSin*m_afSubd[i3];
+ Type fB = fCos*m_afSubd[i3];
+ if (fabs(fF) >= fabs(fG))
+ {
+ fCos = fG/fF;
+ fR = (REAL)sqrt(fCos*fCos+(Type)1.0);
+ m_afSubd[i3+1] = fF*fR;
+ fSin = ((Type)1.0)/fR;
+ fCos *= fSin;
+ }
+ else
+ {
+ fSin = fF/fG;
+ fR = (REAL)sqrt(fSin*fSin+(Type)1.0);
+ m_afSubd[i3+1] = fG*fR;
+ fCos = ((Type)1.0)/fR;
+ fSin *= fCos;
+ }
+ fG = m_afDiag[i3+1]-fP;
+ fR = (m_afDiag[i3]-fG)*fSin+((Type)2.0)*fB*fCos;
+ fP = fSin*fR;
+ m_afDiag[i3+1] = fG+fP;
+ fG = fCos*fR-fB;
+ for (int32_t i4 = 0; i4 < 3; i4++)
+ {
+ fF = mElement[i4][i3+1];
+ mElement[i4][i3+1] = fSin*mElement[i4][i3]+fCos*fF;
+ mElement[i4][i3] = fCos*mElement[i4][i3]-fSin*fF;
+ }
+ }
+ m_afDiag[i0] -= fP;
+ m_afSubd[i0] = fG;
+ m_afSubd[i2] = (Type)0.0;
+ }
+ if (i1 == iMaxIter)
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ void DecreasingSort(void)
+ {
+ //sort eigenvalues in decreasing order, e[0] >= ... >= e[iSize-1]
+ for (int32_t i0 = 0, i1; i0 <= 3-2; i0++)
+ {
+ // locate maximum eigenvalue
+ i1 = i0;
+ Type fMax = m_afDiag[i1];
+ int32_t i2;
+ for (i2 = i0+1; i2 < 3; i2++)
+ {
+ if (m_afDiag[i2] > fMax)
+ {
+ i1 = i2;
+ fMax = m_afDiag[i1];
+ }
+ }
+
+ if (i1 != i0)
+ {
+ // swap eigenvalues
+ m_afDiag[i1] = m_afDiag[i0];
+ m_afDiag[i0] = fMax;
+ // swap eigenvectors
+ for (i2 = 0; i2 < 3; i2++)
+ {
+ Type fTmp = mElement[i2][i0];
+ mElement[i2][i0] = mElement[i2][i1];
+ mElement[i2][i1] = fTmp;
+ m_bIsRotation = !m_bIsRotation;
+ }
+ }
+ }
+ }
+
+
+ void GuaranteeRotation(void)
+ {
+ if (!m_bIsRotation)
+ {
+ // change sign on the first column
+ for (int32_t iRow = 0; iRow <3; iRow++)
+ {
+ mElement[iRow][0] = -mElement[iRow][0];
+ }
+ }
+ }
+
+ Type mElement[3][3];
+ Type m_afDiag[3];
+ Type m_afSubd[3];
+ bool m_bIsRotation;
+};
+
+#endif
+
+bool fm_computeBestFitPlane(uint32_t vcount,
+ const REAL *points,
+ uint32_t vstride,
+ const REAL *weights,
+ uint32_t wstride,
+ REAL *plane,
+ REAL *center)
+{
+ bool ret = false;
+
+ REAL kOrigin[3] = { 0, 0, 0 };
+
+ REAL wtotal = 0;
+
+ {
+ const char *source = (const char *) points;
+ const char *wsource = (const char *) weights;
+
+ for (uint32_t i=0; i<vcount; i++)
+ {
+
+ const REAL *p = (const REAL *) source;
+
+ REAL w = 1;
+
+ if ( wsource )
+ {
+ const REAL *ws = (const REAL *) wsource;
+ w = *ws; //
+ wsource+=wstride;
+ }
+
+ kOrigin[0]+=p[0]*w;
+ kOrigin[1]+=p[1]*w;
+ kOrigin[2]+=p[2]*w;
+
+ wtotal+=w;
+
+ source+=vstride;
+ }
+ }
+
+ REAL recip = 1.0f / wtotal; // reciprocol of total weighting
+
+ kOrigin[0]*=recip;
+ kOrigin[1]*=recip;
+ kOrigin[2]*=recip;
+
+ center[0] = kOrigin[0];
+ center[1] = kOrigin[1];
+ center[2] = kOrigin[2];
+
+
+ REAL fSumXX=0;
+ REAL fSumXY=0;
+ REAL fSumXZ=0;
+
+ REAL fSumYY=0;
+ REAL fSumYZ=0;
+ REAL fSumZZ=0;
+
+
+ {
+ const char *source = (const char *) points;
+ const char *wsource = (const char *) weights;
+
+ for (uint32_t i=0; i<vcount; i++)
+ {
+
+ const REAL *p = (const REAL *) source;
+
+ REAL w = 1;
+
+ if ( wsource )
+ {
+ const REAL *ws = (const REAL *) wsource;
+ w = *ws; //
+ wsource+=wstride;
+ }
+
+ REAL kDiff[3];
+
+ kDiff[0] = w*(p[0] - kOrigin[0]); // apply vertex weighting!
+ kDiff[1] = w*(p[1] - kOrigin[1]);
+ kDiff[2] = w*(p[2] - kOrigin[2]);
+
+ fSumXX+= kDiff[0] * kDiff[0]; // sume of the squares of the differences.
+ fSumXY+= kDiff[0] * kDiff[1]; // sume of the squares of the differences.
+ fSumXZ+= kDiff[0] * kDiff[2]; // sume of the squares of the differences.
+
+ fSumYY+= kDiff[1] * kDiff[1];
+ fSumYZ+= kDiff[1] * kDiff[2];
+ fSumZZ+= kDiff[2] * kDiff[2];
+
+
+ source+=vstride;
+ }
+ }
+
+ fSumXX *= recip;
+ fSumXY *= recip;
+ fSumXZ *= recip;
+ fSumYY *= recip;
+ fSumYZ *= recip;
+ fSumZZ *= recip;
+
+ // setup the eigensolver
+ Eigen<REAL> kES;
+
+ kES.mElement[0][0] = fSumXX;
+ kES.mElement[0][1] = fSumXY;
+ kES.mElement[0][2] = fSumXZ;
+
+ kES.mElement[1][0] = fSumXY;
+ kES.mElement[1][1] = fSumYY;
+ kES.mElement[1][2] = fSumYZ;
+
+ kES.mElement[2][0] = fSumXZ;
+ kES.mElement[2][1] = fSumYZ;
+ kES.mElement[2][2] = fSumZZ;
+
+ // compute eigenstuff, smallest eigenvalue is in last position
+ kES.DecrSortEigenStuff();
+
+ REAL kNormal[3];
+
+ kNormal[0] = kES.mElement[0][2];
+ kNormal[1] = kES.mElement[1][2];
+ kNormal[2] = kES.mElement[2][2];
+
+ // the minimum energy
+ plane[0] = kNormal[0];
+ plane[1] = kNormal[1];
+ plane[2] = kNormal[2];
+
+ plane[3] = 0 - fm_dot(kNormal,kOrigin);
+
+ ret = true;
+
+ return ret;
+}
+
+
+bool fm_colinear(const REAL a1[3],const REAL a2[3],const REAL b1[3],const REAL b2[3],REAL epsilon) // true if these two line segments are co-linear.
+{
+ bool ret = false;
+
+ REAL dir1[3];
+ REAL dir2[3];
+
+ dir1[0] = (a2[0] - a1[0]);
+ dir1[1] = (a2[1] - a1[1]);
+ dir1[2] = (a2[2] - a1[2]);
+
+ dir2[0] = (b2[0]-a1[0]) - (b1[0]-a1[0]);
+ dir2[1] = (b2[1]-a1[1]) - (b1[1]-a1[1]);
+ dir2[2] = (b2[2]-a2[2]) - (b1[2]-a2[2]);
+
+ fm_normalize(dir1);
+ fm_normalize(dir2);
+
+ REAL dot = fm_dot(dir1,dir2);
+
+ if ( dot >= epsilon )
+ {
+ ret = true;
+ }
+
+
+ return ret;
+}
+
+bool fm_colinear(const REAL *p1,const REAL *p2,const REAL *p3,REAL epsilon)
+{
+ bool ret = false;
+
+ REAL dir1[3];
+ REAL dir2[3];
+
+ dir1[0] = p2[0] - p1[0];
+ dir1[1] = p2[1] - p1[1];
+ dir1[2] = p2[2] - p1[2];
+
+ dir2[0] = p3[0] - p2[0];
+ dir2[1] = p3[1] - p2[1];
+ dir2[2] = p3[2] - p2[2];
+
+ fm_normalize(dir1);
+ fm_normalize(dir2);
+
+ REAL dot = fm_dot(dir1,dir2);
+
+ if ( dot >= epsilon )
+ {
+ ret = true;
+ }
+
+
+ return ret;
+}
+
+void fm_initMinMax(const REAL *p,REAL *bmin,REAL *bmax)
+{
+ bmax[0] = bmin[0] = p[0];
+ bmax[1] = bmin[1] = p[1];
+ bmax[2] = bmin[2] = p[2];
+}
+
+IntersectResult fm_intersectLineSegments2d(const REAL *a1,const REAL *a2,const REAL *b1,const REAL *b2,REAL *intersection)
+{
+ IntersectResult ret;
+
+ REAL denom = ((b2[1] - b1[1])*(a2[0] - a1[0])) - ((b2[0] - b1[0])*(a2[1] - a1[1]));
+ REAL nume_a = ((b2[0] - b1[0])*(a1[1] - b1[1])) - ((b2[1] - b1[1])*(a1[0] - b1[0]));
+ REAL nume_b = ((a2[0] - a1[0])*(a1[1] - b1[1])) - ((a2[1] - a1[1])*(a1[0] - b1[0]));
+ if (denom == 0 )
+ {
+ if(nume_a == 0 && nume_b == 0)
+ {
+ ret = IR_COINCIDENT;
+ }
+ else
+ {
+ ret = IR_PARALLEL;
+ }
+ }
+ else
+ {
+
+ REAL recip = 1 / denom;
+ REAL ua = nume_a * recip;
+ REAL ub = nume_b * recip;
+
+ if(ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1 )
+ {
+ // Get the intersection point.
+ intersection[0] = a1[0] + ua*(a2[0] - a1[0]);
+ intersection[1] = a1[1] + ua*(a2[1] - a1[1]);
+ ret = IR_DO_INTERSECT;
+ }
+ else
+ {
+ ret = IR_DONT_INTERSECT;
+ }
+ }
+ return ret;
+}
+
+IntersectResult fm_intersectLineSegments2dTime(const REAL *a1,const REAL *a2,const REAL *b1,const REAL *b2,REAL &t1,REAL &t2)
+{
+ IntersectResult ret;
+
+ REAL denom = ((b2[1] - b1[1])*(a2[0] - a1[0])) - ((b2[0] - b1[0])*(a2[1] - a1[1]));
+ REAL nume_a = ((b2[0] - b1[0])*(a1[1] - b1[1])) - ((b2[1] - b1[1])*(a1[0] - b1[0]));
+ REAL nume_b = ((a2[0] - a1[0])*(a1[1] - b1[1])) - ((a2[1] - a1[1])*(a1[0] - b1[0]));
+ if (denom == 0 )
+ {
+ if(nume_a == 0 && nume_b == 0)
+ {
+ ret = IR_COINCIDENT;
+ }
+ else
+ {
+ ret = IR_PARALLEL;
+ }
+ }
+ else
+ {
+
+ REAL recip = 1 / denom;
+ REAL ua = nume_a * recip;
+ REAL ub = nume_b * recip;
+
+ if(ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1 )
+ {
+ t1 = ua;
+ t2 = ub;
+ ret = IR_DO_INTERSECT;
+ }
+ else
+ {
+ ret = IR_DONT_INTERSECT;
+ }
+ }
+ return ret;
+}
+
+//**** Plane Triangle Intersection
+
+
+
+
+
+// assumes that the points are on opposite sides of the plane!
+bool fm_intersectPointPlane(const REAL *p1,const REAL *p2,REAL *split,const REAL *plane)
+{
+
+ REAL dp1 = fm_distToPlane(plane,p1);
+ REAL dp2 = fm_distToPlane(plane, p2);
+ if (dp1 <= 0 && dp2 <= 0)
+ {
+ return false;
+ }
+ if (dp1 >= 0 && dp2 >= 0)
+ {
+ return false;
+ }
+
+ REAL dir[3];
+
+ dir[0] = p2[0] - p1[0];
+ dir[1] = p2[1] - p1[1];
+ dir[2] = p2[2] - p1[2];
+
+ REAL dot1 = dir[0]*plane[0] + dir[1]*plane[1] + dir[2]*plane[2];
+ REAL dot2 = dp1 - plane[3];
+
+ REAL t = -(plane[3] + dot2 ) / dot1;
+
+ split[0] = (dir[0]*t)+p1[0];
+ split[1] = (dir[1]*t)+p1[1];
+ split[2] = (dir[2]*t)+p1[2];
+
+ return true;
+}
+
+PlaneTriResult fm_getSidePlane(const REAL *p,const REAL *plane,REAL epsilon)
+{
+ PlaneTriResult ret = PTR_ON_PLANE;
+
+ REAL d = fm_distToPlane(plane,p);
+
+ if ( d < -epsilon || d > epsilon )
+ {
+ if ( d > 0 )
+ ret = PTR_FRONT; // it is 'in front' within the provided epsilon value.
+ else
+ ret = PTR_BACK;
+ }
+
+ return ret;
+}
+
+
+
+#ifndef PLANE_TRIANGLE_INTERSECTION_H
+
+#define PLANE_TRIANGLE_INTERSECTION_H
+
+#define MAXPTS 256
+
+template <class Type> class point
+{
+public:
+
+ void set(const Type *p)
+ {
+ x = p[0];
+ y = p[1];
+ z = p[2];
+ }
+
+ Type x;
+ Type y;
+ Type z;
+};
+
+template <class Type> class plane
+{
+public:
+ plane(const Type *p)
+ {
+ normal.x = p[0];
+ normal.y = p[1];
+ normal.z = p[2];
+ D = p[3];
+ }
+
+ Type Classify_Point(const point<Type> &p)
+ {
+ return p.x*normal.x + p.y*normal.y + p.z*normal.z + D;
+ }
+
+ point<Type> normal;
+ Type D;
+};
+
+template <class Type> class polygon
+{
+public:
+ polygon(void)
+ {
+ mVcount = 0;
+ }
+
+ polygon(const Type *p1,const Type *p2,const Type *p3)
+ {
+ mVcount = 3;
+ mVertices[0].set(p1);
+ mVertices[1].set(p2);
+ mVertices[2].set(p3);
+ }
+
+
+ int32_t NumVertices(void) const { return mVcount; };
+
+ const point<Type>& Vertex(int32_t index)
+ {
+ if ( index < 0 ) index+=mVcount;
+ return mVertices[index];
+ };
+
+
+ void set(const point<Type> *pts,int32_t count)
+ {
+ for (int32_t i=0; i<count; i++)
+ {
+ mVertices[i] = pts[i];
+ }
+ mVcount = count;
+ }
+
+
+ void Split_Polygon(polygon<Type> *poly,plane<Type> *part, polygon<Type> &front, polygon<Type> &back)
+ {
+ int32_t count = poly->NumVertices ();
+ int32_t out_c = 0, in_c = 0;
+ point<Type> ptA, ptB,outpts[MAXPTS],inpts[MAXPTS];
+ Type sideA, sideB;
+ ptA = poly->Vertex (count - 1);
+ sideA = part->Classify_Point (ptA);
+ for (int32_t i = -1; ++i < count;)
+ {
+ ptB = poly->Vertex(i);
+ sideB = part->Classify_Point(ptB);
+ if (sideB > 0)
+ {
+ if (sideA < 0)
+ {
+ point<Type> v;
+ fm_intersectPointPlane(&ptB.x, &ptA.x, &v.x, &part->normal.x );
+ outpts[out_c++] = inpts[in_c++] = v;
+ }
+ outpts[out_c++] = ptB;
+ }
+ else if (sideB < 0)
+ {
+ if (sideA > 0)
+ {
+ point<Type> v;
+ fm_intersectPointPlane(&ptB.x, &ptA.x, &v.x, &part->normal.x );
+ outpts[out_c++] = inpts[in_c++] = v;
+ }
+ inpts[in_c++] = ptB;
+ }
+ else
+ outpts[out_c++] = inpts[in_c++] = ptB;
+ ptA = ptB;
+ sideA = sideB;
+ }
+
+ front.set(&outpts[0], out_c);
+ back.set(&inpts[0], in_c);
+ }
+
+ int32_t mVcount;
+ point<Type> mVertices[MAXPTS];
+};
+
+
+
+#endif
+
+static inline void add(const REAL *p,REAL *dest,uint32_t tstride,uint32_t &pcount)
+{
+ char *d = (char *) dest;
+ d = d + pcount*tstride;
+ dest = (REAL *) d;
+ dest[0] = p[0];
+ dest[1] = p[1];
+ dest[2] = p[2];
+ pcount++;
+ assert( pcount <= 4 );
+}
+
+
+PlaneTriResult fm_planeTriIntersection(const REAL *_plane, // the plane equation in Ax+By+Cz+D format
+ const REAL *triangle, // the source triangle.
+ uint32_t tstride, // stride in bytes of the input and output *vertices*
+ REAL epsilon, // the co-planar epsilon value.
+ REAL *front, // the triangle in front of the
+ uint32_t &fcount, // number of vertices in the 'front' triangle
+ REAL *back, // the triangle in back of the plane
+ uint32_t &bcount) // the number of vertices in the 'back' triangle.
+{
+
+ fcount = 0;
+ bcount = 0;
+
+ const char *tsource = (const char *) triangle;
+
+ // get the three vertices of the triangle.
+ const REAL *p1 = (const REAL *) (tsource);
+ const REAL *p2 = (const REAL *) (tsource+tstride);
+ const REAL *p3 = (const REAL *) (tsource+tstride*2);
+
+
+ PlaneTriResult r1 = fm_getSidePlane(p1,_plane,epsilon); // compute the side of the plane each vertex is on
+ PlaneTriResult r2 = fm_getSidePlane(p2,_plane,epsilon);
+ PlaneTriResult r3 = fm_getSidePlane(p3,_plane,epsilon);
+
+ // If any of the points lay right *on* the plane....
+ if ( r1 == PTR_ON_PLANE || r2 == PTR_ON_PLANE || r3 == PTR_ON_PLANE )
+ {
+ // If the triangle is completely co-planar, then just treat it as 'front' and return!
+ if ( r1 == PTR_ON_PLANE && r2 == PTR_ON_PLANE && r3 == PTR_ON_PLANE )
+ {
+ add(p1,front,tstride,fcount);
+ add(p2,front,tstride,fcount);
+ add(p3,front,tstride,fcount);
+ return PTR_FRONT;
+ }
+ // Decide to place the co-planar points on the same side as the co-planar point.
+ PlaneTriResult r= PTR_ON_PLANE;
+ if ( r1 != PTR_ON_PLANE )
+ r = r1;
+ else if ( r2 != PTR_ON_PLANE )
+ r = r2;
+ else if ( r3 != PTR_ON_PLANE )
+ r = r3;
+
+ if ( r1 == PTR_ON_PLANE ) r1 = r;
+ if ( r2 == PTR_ON_PLANE ) r2 = r;
+ if ( r3 == PTR_ON_PLANE ) r3 = r;
+
+ }
+
+ if ( r1 == r2 && r1 == r3 ) // if all three vertices are on the same side of the plane.
+ {
+ if ( r1 == PTR_FRONT ) // if all three are in front of the plane, then copy to the 'front' output triangle.
+ {
+ add(p1,front,tstride,fcount);
+ add(p2,front,tstride,fcount);
+ add(p3,front,tstride,fcount);
+ }
+ else
+ {
+ add(p1,back,tstride,bcount); // if all three are in 'back' then copy to the 'back' output triangle.
+ add(p2,back,tstride,bcount);
+ add(p3,back,tstride,bcount);
+ }
+ return r1; // if all three points are on the same side of the plane return result
+ }
+
+
+ polygon<REAL> pi(p1,p2,p3);
+ polygon<REAL> pfront,pback;
+
+ plane<REAL> part(_plane);
+
+ pi.Split_Polygon(&pi,&part,pfront,pback);
+
+ for (int32_t i=0; i<pfront.mVcount; i++)
+ {
+ add( &pfront.mVertices[i].x, front, tstride, fcount );
+ }
+
+ for (int32_t i=0; i<pback.mVcount; i++)
+ {
+ add( &pback.mVertices[i].x, back, tstride, bcount );
+ }
+
+ PlaneTriResult ret = PTR_SPLIT;
+
+ if ( fcount < 3 ) fcount = 0;
+ if ( bcount < 3 ) bcount = 0;
+
+ if ( fcount == 0 && bcount )
+ ret = PTR_BACK;
+
+ if ( bcount == 0 && fcount )
+ ret = PTR_FRONT;
+
+
+ return ret;
+}
+
+// computes the OBB for this set of points relative to this transform matrix.
+void computeOBB(uint32_t vcount,const REAL *points,uint32_t pstride,REAL *sides,REAL *matrix)
+{
+ const char *src = (const char *) points;
+
+ REAL bmin[3] = { 1e9, 1e9, 1e9 };
+ REAL bmax[3] = { -1e9, -1e9, -1e9 };
+
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ const REAL *p = (const REAL *) src;
+ REAL t[3];
+
+ fm_inverseRT(matrix, p, t ); // inverse rotate translate
+
+ if ( t[0] < bmin[0] ) bmin[0] = t[0];
+ if ( t[1] < bmin[1] ) bmin[1] = t[1];
+ if ( t[2] < bmin[2] ) bmin[2] = t[2];
+
+ if ( t[0] > bmax[0] ) bmax[0] = t[0];
+ if ( t[1] > bmax[1] ) bmax[1] = t[1];
+ if ( t[2] > bmax[2] ) bmax[2] = t[2];
+
+ src+=pstride;
+ }
+
+ REAL center[3];
+
+ sides[0] = bmax[0]-bmin[0];
+ sides[1] = bmax[1]-bmin[1];
+ sides[2] = bmax[2]-bmin[2];
+
+ center[0] = sides[0]*0.5f+bmin[0];
+ center[1] = sides[1]*0.5f+bmin[1];
+ center[2] = sides[2]*0.5f+bmin[2];
+
+ REAL ocenter[3];
+
+ fm_rotate(matrix,center,ocenter);
+
+ matrix[12]+=ocenter[0];
+ matrix[13]+=ocenter[1];
+ matrix[14]+=ocenter[2];
+
+}
+
+void fm_computeBestFitOBB(uint32_t vcount,const REAL *points,uint32_t pstride,REAL *sides,REAL *matrix,bool bruteForce)
+{
+ REAL plane[4];
+ REAL center[3];
+ fm_computeBestFitPlane(vcount,points,pstride,0,0,plane,center);
+ fm_planeToMatrix(plane,matrix);
+ computeOBB( vcount, points, pstride, sides, matrix );
+
+ REAL refmatrix[16];
+ memcpy(refmatrix,matrix,16*sizeof(REAL));
+
+ REAL volume = sides[0]*sides[1]*sides[2];
+ if ( bruteForce )
+ {
+ for (REAL a=10; a<180; a+=10)
+ {
+ REAL quat[4];
+ fm_eulerToQuat(0,a*FM_DEG_TO_RAD,0,quat);
+ REAL temp[16];
+ REAL pmatrix[16];
+ fm_quatToMatrix(quat,temp);
+ fm_matrixMultiply(temp,refmatrix,pmatrix);
+ REAL psides[3];
+ computeOBB( vcount, points, pstride, psides, pmatrix );
+ REAL v = psides[0]*psides[1]*psides[2];
+ if ( v < volume )
+ {
+ volume = v;
+ memcpy(matrix,pmatrix,sizeof(REAL)*16);
+ sides[0] = psides[0];
+ sides[1] = psides[1];
+ sides[2] = psides[2];
+ }
+ }
+ }
+}
+
+void fm_computeBestFitOBB(uint32_t vcount,const REAL *points,uint32_t pstride,REAL *sides,REAL *pos,REAL *quat,bool bruteForce)
+{
+ REAL matrix[16];
+ fm_computeBestFitOBB(vcount,points,pstride,sides,matrix,bruteForce);
+ fm_getTranslation(matrix,pos);
+ fm_matrixToQuat(matrix,quat);
+}
+
+void fm_computeBestFitABB(uint32_t vcount,const REAL *points,uint32_t pstride,REAL *sides,REAL *pos)
+{
+ REAL bmin[3];
+ REAL bmax[3];
+
+ bmin[0] = points[0];
+ bmin[1] = points[1];
+ bmin[2] = points[2];
+
+ bmax[0] = points[0];
+ bmax[1] = points[1];
+ bmax[2] = points[2];
+
+ const char *cp = (const char *) points;
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ const REAL *p = (const REAL *) cp;
+
+ if ( p[0] < bmin[0] ) bmin[0] = p[0];
+ if ( p[1] < bmin[1] ) bmin[1] = p[1];
+ if ( p[2] < bmin[2] ) bmin[2] = p[2];
+
+ if ( p[0] > bmax[0] ) bmax[0] = p[0];
+ if ( p[1] > bmax[1] ) bmax[1] = p[1];
+ if ( p[2] > bmax[2] ) bmax[2] = p[2];
+
+ cp+=pstride;
+ }
+
+
+ sides[0] = bmax[0] - bmin[0];
+ sides[1] = bmax[1] - bmin[1];
+ sides[2] = bmax[2] - bmin[2];
+
+ pos[0] = bmin[0]+sides[0]*0.5f;
+ pos[1] = bmin[1]+sides[1]*0.5f;
+ pos[2] = bmin[2]+sides[2]*0.5f;
+
+}
+
+
+void fm_planeToMatrix(const REAL *plane,REAL *matrix) // convert a plane equation to a 4x4 rotation matrix
+{
+ REAL ref[3] = { 0, 1, 0 };
+ REAL quat[4];
+ fm_rotationArc(ref,plane,quat);
+ fm_quatToMatrix(quat,matrix);
+ REAL origin[3] = { 0, -plane[3], 0 };
+ REAL center[3];
+ fm_transform(matrix,origin,center);
+ fm_setTranslation(center,matrix);
+}
+
+void fm_planeToQuat(const REAL *plane,REAL *quat,REAL *pos) // convert a plane equation to a quaternion and translation
+{
+ REAL ref[3] = { 0, 1, 0 };
+ REAL matrix[16];
+ fm_rotationArc(ref,plane,quat);
+ fm_quatToMatrix(quat,matrix);
+ REAL origin[3] = { 0, plane[3], 0 };
+ fm_transform(matrix,origin,pos);
+}
+
+void fm_eulerMatrix(REAL ax,REAL ay,REAL az,REAL *matrix) // convert euler (in radians) to a dest 4x4 matrix (translation set to zero)
+{
+ REAL quat[4];
+ fm_eulerToQuat(ax,ay,az,quat);
+ fm_quatToMatrix(quat,matrix);
+}
+
+
+//**********************************************************
+//**********************************************************
+//**** Vertex Welding
+//**********************************************************
+//**********************************************************
+
+#ifndef VERTEX_INDEX_H
+
+#define VERTEX_INDEX_H
+
+namespace VERTEX_INDEX
+{
+
+class KdTreeNode;
+
+typedef std::vector< KdTreeNode * > KdTreeNodeVector;
+
+enum Axes
+{
+ X_AXIS = 0,
+ Y_AXIS = 1,
+ Z_AXIS = 2
+};
+
+class KdTreeFindNode
+{
+public:
+ KdTreeFindNode(void)
+ {
+ mNode = 0;
+ mDistance = 0;
+ }
+ KdTreeNode *mNode;
+ double mDistance;
+};
+
+class KdTreeInterface
+{
+public:
+ virtual const double * getPositionDouble(uint32_t index) const = 0;
+ virtual const float * getPositionFloat(uint32_t index) const = 0;
+};
+
+class KdTreeNode
+{
+public:
+ KdTreeNode(void)
+ {
+ mIndex = 0;
+ mLeft = 0;
+ mRight = 0;
+ }
+
+ KdTreeNode(uint32_t index)
+ {
+ mIndex = index;
+ mLeft = 0;
+ mRight = 0;
+ };
+
+ ~KdTreeNode(void)
+ {
+ }
+
+
+ void addDouble(KdTreeNode *node,Axes dim,const KdTreeInterface *iface)
+ {
+ const double *nodePosition = iface->getPositionDouble( node->mIndex );
+ const double *position = iface->getPositionDouble( mIndex );
+ switch ( dim )
+ {
+ case X_AXIS:
+ if ( nodePosition[0] <= position[0] )
+ {
+ if ( mLeft )
+ mLeft->addDouble(node,Y_AXIS,iface);
+ else
+ mLeft = node;
+ }
+ else
+ {
+ if ( mRight )
+ mRight->addDouble(node,Y_AXIS,iface);
+ else
+ mRight = node;
+ }
+ break;
+ case Y_AXIS:
+ if ( nodePosition[1] <= position[1] )
+ {
+ if ( mLeft )
+ mLeft->addDouble(node,Z_AXIS,iface);
+ else
+ mLeft = node;
+ }
+ else
+ {
+ if ( mRight )
+ mRight->addDouble(node,Z_AXIS,iface);
+ else
+ mRight = node;
+ }
+ break;
+ case Z_AXIS:
+ if ( nodePosition[2] <= position[2] )
+ {
+ if ( mLeft )
+ mLeft->addDouble(node,X_AXIS,iface);
+ else
+ mLeft = node;
+ }
+ else
+ {
+ if ( mRight )
+ mRight->addDouble(node,X_AXIS,iface);
+ else
+ mRight = node;
+ }
+ break;
+ }
+
+ }
+
+
+ void addFloat(KdTreeNode *node,Axes dim,const KdTreeInterface *iface)
+ {
+ const float *nodePosition = iface->getPositionFloat( node->mIndex );
+ const float *position = iface->getPositionFloat( mIndex );
+ switch ( dim )
+ {
+ case X_AXIS:
+ if ( nodePosition[0] <= position[0] )
+ {
+ if ( mLeft )
+ mLeft->addFloat(node,Y_AXIS,iface);
+ else
+ mLeft = node;
+ }
+ else
+ {
+ if ( mRight )
+ mRight->addFloat(node,Y_AXIS,iface);
+ else
+ mRight = node;
+ }
+ break;
+ case Y_AXIS:
+ if ( nodePosition[1] <= position[1] )
+ {
+ if ( mLeft )
+ mLeft->addFloat(node,Z_AXIS,iface);
+ else
+ mLeft = node;
+ }
+ else
+ {
+ if ( mRight )
+ mRight->addFloat(node,Z_AXIS,iface);
+ else
+ mRight = node;
+ }
+ break;
+ case Z_AXIS:
+ if ( nodePosition[2] <= position[2] )
+ {
+ if ( mLeft )
+ mLeft->addFloat(node,X_AXIS,iface);
+ else
+ mLeft = node;
+ }
+ else
+ {
+ if ( mRight )
+ mRight->addFloat(node,X_AXIS,iface);
+ else
+ mRight = node;
+ }
+ break;
+ }
+
+ }
+
+
+ uint32_t getIndex(void) const { return mIndex; };
+
+ void search(Axes axis,const double *pos,double radius,uint32_t &count,uint32_t maxObjects,KdTreeFindNode *found,const KdTreeInterface *iface)
+ {
+
+ const double *position = iface->getPositionDouble(mIndex);
+
+ double dx = pos[0] - position[0];
+ double dy = pos[1] - position[1];
+ double dz = pos[2] - position[2];
+
+ KdTreeNode *search1 = 0;
+ KdTreeNode *search2 = 0;
+
+ switch ( axis )
+ {
+ case X_AXIS:
+ if ( dx <= 0 ) // JWR if we are to the left
+ {
+ search1 = mLeft; // JWR then search to the left
+ if ( -dx < radius ) // JWR if distance to the right is less than our search radius, continue on the right as well.
+ search2 = mRight;
+ }
+ else
+ {
+ search1 = mRight; // JWR ok, we go down the left tree
+ if ( dx < radius ) // JWR if the distance from the right is less than our search radius
+ search2 = mLeft;
+ }
+ axis = Y_AXIS;
+ break;
+ case Y_AXIS:
+ if ( dy <= 0 )
+ {
+ search1 = mLeft;
+ if ( -dy < radius )
+ search2 = mRight;
+ }
+ else
+ {
+ search1 = mRight;
+ if ( dy < radius )
+ search2 = mLeft;
+ }
+ axis = Z_AXIS;
+ break;
+ case Z_AXIS:
+ if ( dz <= 0 )
+ {
+ search1 = mLeft;
+ if ( -dz < radius )
+ search2 = mRight;
+ }
+ else
+ {
+ search1 = mRight;
+ if ( dz < radius )
+ search2 = mLeft;
+ }
+ axis = X_AXIS;
+ break;
+ }
+
+ double r2 = radius*radius;
+ double m = dx*dx+dy*dy+dz*dz;
+
+ if ( m < r2 )
+ {
+ switch ( count )
+ {
+ case 0:
+ found[count].mNode = this;
+ found[count].mDistance = m;
+ break;
+ case 1:
+ if ( m < found[0].mDistance )
+ {
+ if ( maxObjects == 1 )
+ {
+ found[0].mNode = this;
+ found[0].mDistance = m;
+ }
+ else
+ {
+ found[1] = found[0];
+ found[0].mNode = this;
+ found[0].mDistance = m;
+ }
+ }
+ else if ( maxObjects > 1)
+ {
+ found[1].mNode = this;
+ found[1].mDistance = m;
+ }
+ break;
+ default:
+ {
+ bool inserted = false;
+
+ for (uint32_t i=0; i<count; i++)
+ {
+ if ( m < found[i].mDistance ) // if this one is closer than a pre-existing one...
+ {
+ // insertion sort...
+ uint32_t scan = count;
+ if ( scan >= maxObjects ) scan=maxObjects-1;
+ for (uint32_t j=scan; j>i; j--)
+ {
+ found[j] = found[j-1];
+ }
+ found[i].mNode = this;
+ found[i].mDistance = m;
+ inserted = true;
+ break;
+ }
+ }
+
+ if ( !inserted && count < maxObjects )
+ {
+ found[count].mNode = this;
+ found[count].mDistance = m;
+ }
+ }
+ break;
+ }
+ count++;
+ if ( count > maxObjects )
+ {
+ count = maxObjects;
+ }
+ }
+
+
+ if ( search1 )
+ search1->search( axis, pos,radius, count, maxObjects, found, iface);
+
+ if ( search2 )
+ search2->search( axis, pos,radius, count, maxObjects, found, iface);
+
+ }
+
+ void search(Axes axis,const float *pos,float radius,uint32_t &count,uint32_t maxObjects,KdTreeFindNode *found,const KdTreeInterface *iface)
+ {
+
+ const float *position = iface->getPositionFloat(mIndex);
+
+ float dx = pos[0] - position[0];
+ float dy = pos[1] - position[1];
+ float dz = pos[2] - position[2];
+
+ KdTreeNode *search1 = 0;
+ KdTreeNode *search2 = 0;
+
+ switch ( axis )
+ {
+ case X_AXIS:
+ if ( dx <= 0 ) // JWR if we are to the left
+ {
+ search1 = mLeft; // JWR then search to the left
+ if ( -dx < radius ) // JWR if distance to the right is less than our search radius, continue on the right as well.
+ search2 = mRight;
+ }
+ else
+ {
+ search1 = mRight; // JWR ok, we go down the left tree
+ if ( dx < radius ) // JWR if the distance from the right is less than our search radius
+ search2 = mLeft;
+ }
+ axis = Y_AXIS;
+ break;
+ case Y_AXIS:
+ if ( dy <= 0 )
+ {
+ search1 = mLeft;
+ if ( -dy < radius )
+ search2 = mRight;
+ }
+ else
+ {
+ search1 = mRight;
+ if ( dy < radius )
+ search2 = mLeft;
+ }
+ axis = Z_AXIS;
+ break;
+ case Z_AXIS:
+ if ( dz <= 0 )
+ {
+ search1 = mLeft;
+ if ( -dz < radius )
+ search2 = mRight;
+ }
+ else
+ {
+ search1 = mRight;
+ if ( dz < radius )
+ search2 = mLeft;
+ }
+ axis = X_AXIS;
+ break;
+ }
+
+ float r2 = radius*radius;
+ float m = dx*dx+dy*dy+dz*dz;
+
+ if ( m < r2 )
+ {
+ switch ( count )
+ {
+ case 0:
+ found[count].mNode = this;
+ found[count].mDistance = m;
+ break;
+ case 1:
+ if ( m < found[0].mDistance )
+ {
+ if ( maxObjects == 1 )
+ {
+ found[0].mNode = this;
+ found[0].mDistance = m;
+ }
+ else
+ {
+ found[1] = found[0];
+ found[0].mNode = this;
+ found[0].mDistance = m;
+ }
+ }
+ else if ( maxObjects > 1)
+ {
+ found[1].mNode = this;
+ found[1].mDistance = m;
+ }
+ break;
+ default:
+ {
+ bool inserted = false;
+
+ for (uint32_t i=0; i<count; i++)
+ {
+ if ( m < found[i].mDistance ) // if this one is closer than a pre-existing one...
+ {
+ // insertion sort...
+ uint32_t scan = count;
+ if ( scan >= maxObjects ) scan=maxObjects-1;
+ for (uint32_t j=scan; j>i; j--)
+ {
+ found[j] = found[j-1];
+ }
+ found[i].mNode = this;
+ found[i].mDistance = m;
+ inserted = true;
+ break;
+ }
+ }
+
+ if ( !inserted && count < maxObjects )
+ {
+ found[count].mNode = this;
+ found[count].mDistance = m;
+ }
+ }
+ break;
+ }
+ count++;
+ if ( count > maxObjects )
+ {
+ count = maxObjects;
+ }
+ }
+
+
+ if ( search1 )
+ search1->search( axis, pos,radius, count, maxObjects, found, iface);
+
+ if ( search2 )
+ search2->search( axis, pos,radius, count, maxObjects, found, iface);
+
+ }
+
+private:
+
+ void setLeft(KdTreeNode *left) { mLeft = left; };
+ void setRight(KdTreeNode *right) { mRight = right; };
+
+ KdTreeNode *getLeft(void) { return mLeft; }
+ KdTreeNode *getRight(void) { return mRight; }
+
+ uint32_t mIndex;
+ KdTreeNode *mLeft;
+ KdTreeNode *mRight;
+};
+
+
+#define MAX_BUNDLE_SIZE 1024 // 1024 nodes at a time, to minimize memory allocation and guarantee that pointers are persistent.
+
+class KdTreeNodeBundle
+{
+public:
+
+ KdTreeNodeBundle(void)
+ {
+ mNext = 0;
+ mIndex = 0;
+ }
+
+ bool isFull(void) const
+ {
+ return (bool)( mIndex == MAX_BUNDLE_SIZE );
+ }
+
+ KdTreeNode * getNextNode(void)
+ {
+ assert(mIndex<MAX_BUNDLE_SIZE);
+ KdTreeNode *ret = &mNodes[mIndex];
+ mIndex++;
+ return ret;
+ }
+
+ KdTreeNodeBundle *mNext;
+ uint32_t mIndex;
+ KdTreeNode mNodes[MAX_BUNDLE_SIZE];
+};
+
+
+typedef std::vector< double > DoubleVector;
+typedef std::vector< float > FloatVector;
+
+class KdTree : public KdTreeInterface
+{
+public:
+ KdTree(void)
+ {
+ mRoot = 0;
+ mBundle = 0;
+ mVcount = 0;
+ mUseDouble = false;
+ }
+
+ virtual ~KdTree(void)
+ {
+ reset();
+ }
+
+ const double * getPositionDouble(uint32_t index) const
+ {
+ assert( mUseDouble );
+ assert ( index < mVcount );
+ return &mVerticesDouble[index*3];
+ }
+
+ const float * getPositionFloat(uint32_t index) const
+ {
+ assert( !mUseDouble );
+ assert ( index < mVcount );
+ return &mVerticesFloat[index*3];
+ }
+
+ uint32_t search(const double *pos,double radius,uint32_t maxObjects,KdTreeFindNode *found) const
+ {
+ assert( mUseDouble );
+ if ( !mRoot ) return 0;
+ uint32_t count = 0;
+ mRoot->search(X_AXIS,pos,radius,count,maxObjects,found,this);
+ return count;
+ }
+
+ uint32_t search(const float *pos,float radius,uint32_t maxObjects,KdTreeFindNode *found) const
+ {
+ assert( !mUseDouble );
+ if ( !mRoot ) return 0;
+ uint32_t count = 0;
+ mRoot->search(X_AXIS,pos,radius,count,maxObjects,found,this);
+ return count;
+ }
+
+ void reset(void)
+ {
+ mRoot = 0;
+ mVerticesDouble.clear();
+ mVerticesFloat.clear();
+ KdTreeNodeBundle *bundle = mBundle;
+ while ( bundle )
+ {
+ KdTreeNodeBundle *next = bundle->mNext;
+ delete bundle;
+ bundle = next;
+ }
+ mBundle = 0;
+ mVcount = 0;
+ }
+
+ uint32_t add(double x,double y,double z)
+ {
+ assert(mUseDouble);
+ uint32_t ret = mVcount;
+ mVerticesDouble.push_back(x);
+ mVerticesDouble.push_back(y);
+ mVerticesDouble.push_back(z);
+ mVcount++;
+ KdTreeNode *node = getNewNode(ret);
+ if ( mRoot )
+ {
+ mRoot->addDouble(node,X_AXIS,this);
+ }
+ else
+ {
+ mRoot = node;
+ }
+ return ret;
+ }
+
+ uint32_t add(float x,float y,float z)
+ {
+ assert(!mUseDouble);
+ uint32_t ret = mVcount;
+ mVerticesFloat.push_back(x);
+ mVerticesFloat.push_back(y);
+ mVerticesFloat.push_back(z);
+ mVcount++;
+ KdTreeNode *node = getNewNode(ret);
+ if ( mRoot )
+ {
+ mRoot->addFloat(node,X_AXIS,this);
+ }
+ else
+ {
+ mRoot = node;
+ }
+ return ret;
+ }
+
+ KdTreeNode * getNewNode(uint32_t index)
+ {
+ if ( mBundle == 0 )
+ {
+ mBundle = new KdTreeNodeBundle;
+ }
+ if ( mBundle->isFull() )
+ {
+ KdTreeNodeBundle *bundle = new KdTreeNodeBundle;
+ mBundle->mNext = bundle;
+ mBundle = bundle;
+ }
+ KdTreeNode *node = mBundle->getNextNode();
+ new ( node ) KdTreeNode(index);
+ return node;
+ }
+
+ uint32_t getNearest(const double *pos,double radius,bool &_found) const // returns the nearest possible neighbor's index.
+ {
+ assert( mUseDouble );
+ uint32_t ret = 0;
+
+ _found = false;
+ KdTreeFindNode found[1];
+ uint32_t count = search(pos,radius,1,found);
+ if ( count )
+ {
+ KdTreeNode *node = found[0].mNode;
+ ret = node->getIndex();
+ _found = true;
+ }
+ return ret;
+ }
+
+ uint32_t getNearest(const float *pos,float radius,bool &_found) const // returns the nearest possible neighbor's index.
+ {
+ assert( !mUseDouble );
+ uint32_t ret = 0;
+
+ _found = false;
+ KdTreeFindNode found[1];
+ uint32_t count = search(pos,radius,1,found);
+ if ( count )
+ {
+ KdTreeNode *node = found[0].mNode;
+ ret = node->getIndex();
+ _found = true;
+ }
+ return ret;
+ }
+
+ const double * getVerticesDouble(void) const
+ {
+ assert( mUseDouble );
+ const double *ret = 0;
+ if ( !mVerticesDouble.empty() )
+ {
+ ret = &mVerticesDouble[0];
+ }
+ return ret;
+ }
+
+ const float * getVerticesFloat(void) const
+ {
+ assert( !mUseDouble );
+ const float * ret = 0;
+ if ( !mVerticesFloat.empty() )
+ {
+ ret = &mVerticesFloat[0];
+ }
+ return ret;
+ }
+
+ uint32_t getVcount(void) const { return mVcount; };
+
+ void setUseDouble(bool useDouble)
+ {
+ mUseDouble = useDouble;
+ }
+
+private:
+ bool mUseDouble;
+ KdTreeNode *mRoot;
+ KdTreeNodeBundle *mBundle;
+ uint32_t mVcount;
+ DoubleVector mVerticesDouble;
+ FloatVector mVerticesFloat;
+};
+
+}; // end of namespace VERTEX_INDEX
+
+class MyVertexIndex : public fm_VertexIndex
+{
+public:
+ MyVertexIndex(double granularity,bool snapToGrid)
+ {
+ mDoubleGranularity = granularity;
+ mFloatGranularity = (float)granularity;
+ mSnapToGrid = snapToGrid;
+ mUseDouble = true;
+ mKdTree.setUseDouble(true);
+ }
+
+ MyVertexIndex(float granularity,bool snapToGrid)
+ {
+ mDoubleGranularity = granularity;
+ mFloatGranularity = (float)granularity;
+ mSnapToGrid = snapToGrid;
+ mUseDouble = false;
+ mKdTree.setUseDouble(false);
+ }
+
+ virtual ~MyVertexIndex(void)
+ {
+
+ }
+
+
+ double snapToGrid(double p)
+ {
+ double m = fmod(p,mDoubleGranularity);
+ p-=m;
+ return p;
+ }
+
+ float snapToGrid(float p)
+ {
+ float m = fmodf(p,mFloatGranularity);
+ p-=m;
+ return p;
+ }
+
+ uint32_t getIndex(const float *_p,bool &newPos) // get index for a vector float
+ {
+ uint32_t ret;
+
+ if ( mUseDouble )
+ {
+ double p[3];
+ p[0] = _p[0];
+ p[1] = _p[1];
+ p[2] = _p[2];
+ return getIndex(p,newPos);
+ }
+
+ newPos = false;
+
+ float p[3];
+
+ if ( mSnapToGrid )
+ {
+ p[0] = snapToGrid(_p[0]);
+ p[1] = snapToGrid(_p[1]);
+ p[2] = snapToGrid(_p[2]);
+ }
+ else
+ {
+ p[0] = _p[0];
+ p[1] = _p[1];
+ p[2] = _p[2];
+ }
+
+ bool found;
+ ret = mKdTree.getNearest(p,mFloatGranularity,found);
+ if ( !found )
+ {
+ newPos = true;
+ ret = mKdTree.add(p[0],p[1],p[2]);
+ }
+
+
+ return ret;
+ }
+
+ uint32_t getIndex(const double *_p,bool &newPos) // get index for a vector double
+ {
+ uint32_t ret;
+
+ if ( !mUseDouble )
+ {
+ float p[3];
+ p[0] = (float)_p[0];
+ p[1] = (float)_p[1];
+ p[2] = (float)_p[2];
+ return getIndex(p,newPos);
+ }
+
+ newPos = false;
+
+ double p[3];
+
+ if ( mSnapToGrid )
+ {
+ p[0] = snapToGrid(_p[0]);
+ p[1] = snapToGrid(_p[1]);
+ p[2] = snapToGrid(_p[2]);
+ }
+ else
+ {
+ p[0] = _p[0];
+ p[1] = _p[1];
+ p[2] = _p[2];
+ }
+
+ bool found;
+ ret = mKdTree.getNearest(p,mDoubleGranularity,found);
+ if ( !found )
+ {
+ newPos = true;
+ ret = mKdTree.add(p[0],p[1],p[2]);
+ }
+
+
+ return ret;
+ }
+
+ const float * getVerticesFloat(void) const
+ {
+ const float * ret = 0;
+
+ assert( !mUseDouble );
+
+ ret = mKdTree.getVerticesFloat();
+
+ return ret;
+ }
+
+ const double * getVerticesDouble(void) const
+ {
+ const double * ret = 0;
+
+ assert( mUseDouble );
+
+ ret = mKdTree.getVerticesDouble();
+
+ return ret;
+ }
+
+ const float * getVertexFloat(uint32_t index) const
+ {
+ const float * ret = 0;
+ assert( !mUseDouble );
+#ifdef _DEBUG
+ uint32_t vcount = mKdTree.getVcount();
+ assert( index < vcount );
+#endif
+ ret = mKdTree.getVerticesFloat();
+ ret = &ret[index*3];
+ return ret;
+ }
+
+ const double * getVertexDouble(uint32_t index) const
+ {
+ const double * ret = 0;
+ assert( mUseDouble );
+#ifdef _DEBUG
+ uint32_t vcount = mKdTree.getVcount();
+ assert( index < vcount );
+#endif
+ ret = mKdTree.getVerticesDouble();
+ ret = &ret[index*3];
+
+ return ret;
+ }
+
+ uint32_t getVcount(void) const
+ {
+ return mKdTree.getVcount();
+ }
+
+ bool isDouble(void) const
+ {
+ return mUseDouble;
+ }
+
+
+ bool saveAsObj(const char *fname,uint32_t tcount,uint32_t *indices)
+ {
+ bool ret = false;
+
+
+ FILE *fph = fopen(fname,"wb");
+ if ( fph )
+ {
+ ret = true;
+
+ uint32_t vcount = getVcount();
+ if ( mUseDouble )
+ {
+ const double *v = getVerticesDouble();
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ fprintf(fph,"v %0.9f %0.9f %0.9f\r\n", (float)v[0], (float)v[1], (float)v[2] );
+ v+=3;
+ }
+ }
+ else
+ {
+ const float *v = getVerticesFloat();
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ fprintf(fph,"v %0.9f %0.9f %0.9f\r\n", v[0], v[1], v[2] );
+ v+=3;
+ }
+ }
+
+ for (uint32_t i=0; i<tcount; i++)
+ {
+ uint32_t i1 = *indices++;
+ uint32_t i2 = *indices++;
+ uint32_t i3 = *indices++;
+ fprintf(fph,"f %d %d %d\r\n", i1+1, i2+1, i3+1 );
+ }
+ fclose(fph);
+ }
+
+ return ret;
+ }
+
+private:
+ bool mUseDouble:1;
+ bool mSnapToGrid:1;
+ double mDoubleGranularity;
+ float mFloatGranularity;
+ VERTEX_INDEX::KdTree mKdTree;
+};
+
+fm_VertexIndex * fm_createVertexIndex(double granularity,bool snapToGrid) // create an indexed vertex system for doubles
+{
+ MyVertexIndex *ret = new MyVertexIndex(granularity,snapToGrid);
+ return static_cast< fm_VertexIndex *>(ret);
+}
+
+fm_VertexIndex * fm_createVertexIndex(float granularity,bool snapToGrid) // create an indexed vertext system for floats
+{
+ MyVertexIndex *ret = new MyVertexIndex(granularity,snapToGrid);
+ return static_cast< fm_VertexIndex *>(ret);
+}
+
+void fm_releaseVertexIndex(fm_VertexIndex *vindex)
+{
+ MyVertexIndex *m = static_cast< MyVertexIndex *>(vindex);
+ delete m;
+}
+
+#endif // END OF VERTEX WELDING CODE
+
+
+REAL fm_computeBestFitAABB(uint32_t vcount,const REAL *points,uint32_t pstride,REAL *bmin,REAL *bmax) // returns the diagonal distance
+{
+
+ const uint8_t *source = (const uint8_t *) points;
+
+ bmin[0] = points[0];
+ bmin[1] = points[1];
+ bmin[2] = points[2];
+
+ bmax[0] = points[0];
+ bmax[1] = points[1];
+ bmax[2] = points[2];
+
+
+ for (uint32_t i=1; i<vcount; i++)
+ {
+ source+=pstride;
+ const REAL *p = (const REAL *) source;
+
+ if ( p[0] < bmin[0] ) bmin[0] = p[0];
+ if ( p[1] < bmin[1] ) bmin[1] = p[1];
+ if ( p[2] < bmin[2] ) bmin[2] = p[2];
+
+ if ( p[0] > bmax[0] ) bmax[0] = p[0];
+ if ( p[1] > bmax[1] ) bmax[1] = p[1];
+ if ( p[2] > bmax[2] ) bmax[2] = p[2];
+
+ }
+
+ REAL dx = bmax[0] - bmin[0];
+ REAL dy = bmax[1] - bmin[1];
+ REAL dz = bmax[2] - bmin[2];
+
+ return (REAL) sqrt( dx*dx + dy*dy + dz*dz );
+
+}
+
+
+
+/* a = b - c */
+#define vector(a,b,c) \
+ (a)[0] = (b)[0] - (c)[0]; \
+ (a)[1] = (b)[1] - (c)[1]; \
+ (a)[2] = (b)[2] - (c)[2];
+
+
+
+#define innerProduct(v,q) \
+ ((v)[0] * (q)[0] + \
+ (v)[1] * (q)[1] + \
+ (v)[2] * (q)[2])
+
+#define crossProduct(a,b,c) \
+ (a)[0] = (b)[1] * (c)[2] - (c)[1] * (b)[2]; \
+ (a)[1] = (b)[2] * (c)[0] - (c)[2] * (b)[0]; \
+ (a)[2] = (b)[0] * (c)[1] - (c)[0] * (b)[1];
+
+
+bool fm_lineIntersectsTriangle(const REAL *rayStart,const REAL *rayEnd,const REAL *p1,const REAL *p2,const REAL *p3,REAL *sect)
+{
+ REAL dir[3];
+
+ dir[0] = rayEnd[0] - rayStart[0];
+ dir[1] = rayEnd[1] - rayStart[1];
+ dir[2] = rayEnd[2] - rayStart[2];
+
+ REAL d = (REAL)sqrt(dir[0]*dir[0] + dir[1]*dir[1] + dir[2]*dir[2]);
+ REAL r = 1.0f / d;
+
+ dir[0]*=r;
+ dir[1]*=r;
+ dir[2]*=r;
+
+
+ REAL t;
+
+ bool ret = fm_rayIntersectsTriangle(rayStart, dir, p1, p2, p3, t );
+
+ if ( ret )
+ {
+ if ( t > d )
+ {
+ sect[0] = rayStart[0] + dir[0]*t;
+ sect[1] = rayStart[1] + dir[1]*t;
+ sect[2] = rayStart[2] + dir[2]*t;
+ }
+ else
+ {
+ ret = false;
+ }
+ }
+
+ return ret;
+}
+
+
+
+bool fm_rayIntersectsTriangle(const REAL *p,const REAL *d,const REAL *v0,const REAL *v1,const REAL *v2,REAL &t)
+{
+ REAL e1[3],e2[3],h[3],s[3],q[3];
+ REAL a,f,u,v;
+
+ vector(e1,v1,v0);
+ vector(e2,v2,v0);
+ crossProduct(h,d,e2);
+ a = innerProduct(e1,h);
+
+ if (a > -0.00001 && a < 0.00001)
+ return(false);
+
+ f = 1/a;
+ vector(s,p,v0);
+ u = f * (innerProduct(s,h));
+
+ if (u < 0.0 || u > 1.0)
+ return(false);
+
+ crossProduct(q,s,e1);
+ v = f * innerProduct(d,q);
+ if (v < 0.0 || u + v > 1.0)
+ return(false);
+ // at this stage we can compute t to find out where
+ // the intersection point is on the line
+ t = f * innerProduct(e2,q);
+ if (t > 0) // ray intersection
+ return(true);
+ else // this means that there is a line intersection
+ // but not a ray intersection
+ return (false);
+}
+
+
+inline REAL det(const REAL *p1,const REAL *p2,const REAL *p3)
+{
+ return p1[0]*p2[1]*p3[2] + p2[0]*p3[1]*p1[2] + p3[0]*p1[1]*p2[2] -p1[0]*p3[1]*p2[2] - p2[0]*p1[1]*p3[2] - p3[0]*p2[1]*p1[2];
+}
+
+
+REAL fm_computeMeshVolume(const REAL *vertices,uint32_t tcount,const uint32_t *indices)
+{
+ REAL volume = 0;
+
+ for (uint32_t i=0; i<tcount; i++,indices+=3)
+ {
+ const REAL *p1 = &vertices[ indices[0]*3 ];
+ const REAL *p2 = &vertices[ indices[1]*3 ];
+ const REAL *p3 = &vertices[ indices[2]*3 ];
+ volume+=det(p1,p2,p3); // compute the volume of the tetrahedran relative to the origin.
+ }
+
+ volume*=(1.0f/6.0f);
+ if ( volume < 0 )
+ volume*=-1;
+ return volume;
+}
+
+
+const REAL * fm_getPoint(const REAL *points,uint32_t pstride,uint32_t index)
+{
+ const uint8_t *scan = (const uint8_t *)points;
+ scan+=(index*pstride);
+ return (REAL *)scan;
+}
+
+
+bool fm_insideTriangle(REAL Ax, REAL Ay,
+ REAL Bx, REAL By,
+ REAL Cx, REAL Cy,
+ REAL Px, REAL Py)
+
+{
+ REAL ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
+ REAL cCROSSap, bCROSScp, aCROSSbp;
+
+ ax = Cx - Bx; ay = Cy - By;
+ bx = Ax - Cx; by = Ay - Cy;
+ cx = Bx - Ax; cy = By - Ay;
+ apx= Px - Ax; apy= Py - Ay;
+ bpx= Px - Bx; bpy= Py - By;
+ cpx= Px - Cx; cpy= Py - Cy;
+
+ aCROSSbp = ax*bpy - ay*bpx;
+ cCROSSap = cx*apy - cy*apx;
+ bCROSScp = bx*cpy - by*cpx;
+
+ return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f));
+}
+
+
+REAL fm_areaPolygon2d(uint32_t pcount,const REAL *points,uint32_t pstride)
+{
+ int32_t n = (int32_t)pcount;
+
+ REAL A=0.0f;
+ for(int32_t p=n-1,q=0; q<n; p=q++)
+ {
+ const REAL *p1 = fm_getPoint(points,pstride,p);
+ const REAL *p2 = fm_getPoint(points,pstride,q);
+ A+= p1[0]*p2[1] - p2[0]*p1[1];
+ }
+ return A*0.5f;
+}
+
+
+bool fm_pointInsidePolygon2d(uint32_t pcount,const REAL *points,uint32_t pstride,const REAL *point,uint32_t xindex,uint32_t yindex)
+{
+ uint32_t j = pcount-1;
+ int32_t oddNodes = 0;
+
+ REAL x = point[xindex];
+ REAL y = point[yindex];
+
+ for (uint32_t i=0; i<pcount; i++)
+ {
+ const REAL *p1 = fm_getPoint(points,pstride,i);
+ const REAL *p2 = fm_getPoint(points,pstride,j);
+
+ REAL x1 = p1[xindex];
+ REAL y1 = p1[yindex];
+
+ REAL x2 = p2[xindex];
+ REAL y2 = p2[yindex];
+
+ if ( (y1 < y && y2 >= y) || (y2 < y && y1 >= y) )
+ {
+ if (x1+(y-y1)/(y2-y1)*(x2-x1)<x)
+ {
+ oddNodes = 1-oddNodes;
+ }
+ }
+ j = i;
+ }
+
+ return oddNodes ? true : false;
+}
+
+
+uint32_t fm_consolidatePolygon(uint32_t pcount,const REAL *points,uint32_t pstride,REAL *_dest,REAL epsilon) // collapses co-linear edges.
+{
+ uint32_t ret = 0;
+
+
+ if ( pcount >= 3 )
+ {
+ const REAL *prev = fm_getPoint(points,pstride,pcount-1);
+ const REAL *current = points;
+ const REAL *next = fm_getPoint(points,pstride,1);
+ REAL *dest = _dest;
+
+ for (uint32_t i=0; i<pcount; i++)
+ {
+
+ next = (i+1)==pcount ? points : next;
+
+ if ( !fm_colinear(prev,current,next,epsilon) )
+ {
+ dest[0] = current[0];
+ dest[1] = current[1];
+ dest[2] = current[2];
+
+ dest+=3;
+ ret++;
+ }
+
+ prev = current;
+ current+=3;
+ next+=3;
+
+ }
+ }
+
+ return ret;
+}
+
+
+#ifndef RECT3D_TEMPLATE
+
+#define RECT3D_TEMPLATE
+
+template <class T> class Rect3d
+{
+public:
+ Rect3d(void) { };
+
+ Rect3d(const T *bmin,const T *bmax)
+ {
+
+ mMin[0] = bmin[0];
+ mMin[1] = bmin[1];
+ mMin[2] = bmin[2];
+
+ mMax[0] = bmax[0];
+ mMax[1] = bmax[1];
+ mMax[2] = bmax[2];
+
+ }
+
+ void SetMin(const T *bmin)
+ {
+ mMin[0] = bmin[0];
+ mMin[1] = bmin[1];
+ mMin[2] = bmin[2];
+ }
+
+ void SetMax(const T *bmax)
+ {
+ mMax[0] = bmax[0];
+ mMax[1] = bmax[1];
+ mMax[2] = bmax[2];
+ }
+
+ void SetMin(T x,T y,T z)
+ {
+ mMin[0] = x;
+ mMin[1] = y;
+ mMin[2] = z;
+ }
+
+ void SetMax(T x,T y,T z)
+ {
+ mMax[0] = x;
+ mMax[1] = y;
+ mMax[2] = z;
+ }
+
+ T mMin[3];
+ T mMax[3];
+};
+
+#endif
+
+void splitRect(uint32_t axis,
+ const Rect3d<REAL> &source,
+ Rect3d<REAL> &b1,
+ Rect3d<REAL> &b2,
+ const REAL *midpoint)
+{
+ switch ( axis )
+ {
+ case 0:
+ b1.SetMin(source.mMin);
+ b1.SetMax( midpoint[0], source.mMax[1], source.mMax[2] );
+
+ b2.SetMin( midpoint[0], source.mMin[1], source.mMin[2] );
+ b2.SetMax(source.mMax);
+
+ break;
+ case 1:
+ b1.SetMin(source.mMin);
+ b1.SetMax( source.mMax[0], midpoint[1], source.mMax[2] );
+
+ b2.SetMin( source.mMin[0], midpoint[1], source.mMin[2] );
+ b2.SetMax(source.mMax);
+
+ break;
+ case 2:
+ b1.SetMin(source.mMin);
+ b1.SetMax( source.mMax[0], source.mMax[1], midpoint[2] );
+
+ b2.SetMin( source.mMin[0], source.mMin[1], midpoint[2] );
+ b2.SetMax(source.mMax);
+
+ break;
+ }
+}
+
+bool fm_computeSplitPlane(uint32_t vcount,
+ const REAL *vertices,
+ uint32_t /* tcount */,
+ const uint32_t * /* indices */,
+ REAL *plane)
+{
+
+ REAL sides[3];
+ REAL matrix[16];
+
+ fm_computeBestFitOBB( vcount, vertices, sizeof(REAL)*3, sides, matrix );
+
+ REAL bmax[3];
+ REAL bmin[3];
+
+ bmax[0] = sides[0]*0.5f;
+ bmax[1] = sides[1]*0.5f;
+ bmax[2] = sides[2]*0.5f;
+
+ bmin[0] = -bmax[0];
+ bmin[1] = -bmax[1];
+ bmin[2] = -bmax[2];
+
+
+ REAL dx = sides[0];
+ REAL dy = sides[1];
+ REAL dz = sides[2];
+
+
+ uint32_t axis = 0;
+
+ if ( dy > dx )
+ {
+ axis = 1;
+ }
+
+ if ( dz > dx && dz > dy )
+ {
+ axis = 2;
+ }
+
+ REAL p1[3];
+ REAL p2[3];
+ REAL p3[3];
+
+ p3[0] = p2[0] = p1[0] = bmin[0] + dx*0.5f;
+ p3[1] = p2[1] = p1[1] = bmin[1] + dy*0.5f;
+ p3[2] = p2[2] = p1[2] = bmin[2] + dz*0.5f;
+
+ Rect3d<REAL> b(bmin,bmax);
+
+ Rect3d<REAL> b1,b2;
+
+ splitRect(axis,b,b1,b2,p1);
+
+
+ switch ( axis )
+ {
+ case 0:
+ p2[1] = bmin[1];
+ p2[2] = bmin[2];
+
+ if ( dz > dy )
+ {
+ p3[1] = bmax[1];
+ p3[2] = bmin[2];
+ }
+ else
+ {
+ p3[1] = bmin[1];
+ p3[2] = bmax[2];
+ }
+
+ break;
+ case 1:
+ p2[0] = bmin[0];
+ p2[2] = bmin[2];
+
+ if ( dx > dz )
+ {
+ p3[0] = bmax[0];
+ p3[2] = bmin[2];
+ }
+ else
+ {
+ p3[0] = bmin[0];
+ p3[2] = bmax[2];
+ }
+
+ break;
+ case 2:
+ p2[0] = bmin[0];
+ p2[1] = bmin[1];
+
+ if ( dx > dy )
+ {
+ p3[0] = bmax[0];
+ p3[1] = bmin[1];
+ }
+ else
+ {
+ p3[0] = bmin[0];
+ p3[1] = bmax[1];
+ }
+
+ break;
+ }
+
+ REAL tp1[3];
+ REAL tp2[3];
+ REAL tp3[3];
+
+ fm_transform(matrix,p1,tp1);
+ fm_transform(matrix,p2,tp2);
+ fm_transform(matrix,p3,tp3);
+
+ plane[3] = fm_computePlane(tp1,tp2,tp3,plane);
+
+ return true;
+
+}
+
+#pragma warning(disable:4100)
+
+void fm_nearestPointInTriangle(const REAL * /*nearestPoint*/,const REAL * /*p1*/,const REAL * /*p2*/,const REAL * /*p3*/,REAL * /*nearest*/)
+{
+
+}
+
+static REAL Partial(const REAL *a,const REAL *p)
+{
+ return (a[0]*p[1]) - (p[0]*a[1]);
+}
+
+REAL fm_areaTriangle(const REAL *p0,const REAL *p1,const REAL *p2)
+{
+ REAL A = Partial(p0,p1);
+ A+= Partial(p1,p2);
+ A+= Partial(p2,p0);
+ return A*0.5f;
+}
+
+void fm_subtract(const REAL *A,const REAL *B,REAL *diff) // compute A-B and store the result in 'diff'
+{
+ diff[0] = A[0]-B[0];
+ diff[1] = A[1]-B[1];
+ diff[2] = A[2]-B[2];
+}
+
+
+void fm_multiplyTransform(const REAL *pA,const REAL *pB,REAL *pM)
+{
+
+ REAL a = pA[0*4+0] * pB[0*4+0] + pA[0*4+1] * pB[1*4+0] + pA[0*4+2] * pB[2*4+0] + pA[0*4+3] * pB[3*4+0];
+ REAL b = pA[0*4+0] * pB[0*4+1] + pA[0*4+1] * pB[1*4+1] + pA[0*4+2] * pB[2*4+1] + pA[0*4+3] * pB[3*4+1];
+ REAL c = pA[0*4+0] * pB[0*4+2] + pA[0*4+1] * pB[1*4+2] + pA[0*4+2] * pB[2*4+2] + pA[0*4+3] * pB[3*4+2];
+ REAL d = pA[0*4+0] * pB[0*4+3] + pA[0*4+1] * pB[1*4+3] + pA[0*4+2] * pB[2*4+3] + pA[0*4+3] * pB[3*4+3];
+
+ REAL e = pA[1*4+0] * pB[0*4+0] + pA[1*4+1] * pB[1*4+0] + pA[1*4+2] * pB[2*4+0] + pA[1*4+3] * pB[3*4+0];
+ REAL f = pA[1*4+0] * pB[0*4+1] + pA[1*4+1] * pB[1*4+1] + pA[1*4+2] * pB[2*4+1] + pA[1*4+3] * pB[3*4+1];
+ REAL g = pA[1*4+0] * pB[0*4+2] + pA[1*4+1] * pB[1*4+2] + pA[1*4+2] * pB[2*4+2] + pA[1*4+3] * pB[3*4+2];
+ REAL h = pA[1*4+0] * pB[0*4+3] + pA[1*4+1] * pB[1*4+3] + pA[1*4+2] * pB[2*4+3] + pA[1*4+3] * pB[3*4+3];
+
+ REAL i = pA[2*4+0] * pB[0*4+0] + pA[2*4+1] * pB[1*4+0] + pA[2*4+2] * pB[2*4+0] + pA[2*4+3] * pB[3*4+0];
+ REAL j = pA[2*4+0] * pB[0*4+1] + pA[2*4+1] * pB[1*4+1] + pA[2*4+2] * pB[2*4+1] + pA[2*4+3] * pB[3*4+1];
+ REAL k = pA[2*4+0] * pB[0*4+2] + pA[2*4+1] * pB[1*4+2] + pA[2*4+2] * pB[2*4+2] + pA[2*4+3] * pB[3*4+2];
+ REAL l = pA[2*4+0] * pB[0*4+3] + pA[2*4+1] * pB[1*4+3] + pA[2*4+2] * pB[2*4+3] + pA[2*4+3] * pB[3*4+3];
+
+ REAL m = pA[3*4+0] * pB[0*4+0] + pA[3*4+1] * pB[1*4+0] + pA[3*4+2] * pB[2*4+0] + pA[3*4+3] * pB[3*4+0];
+ REAL n = pA[3*4+0] * pB[0*4+1] + pA[3*4+1] * pB[1*4+1] + pA[3*4+2] * pB[2*4+1] + pA[3*4+3] * pB[3*4+1];
+ REAL o = pA[3*4+0] * pB[0*4+2] + pA[3*4+1] * pB[1*4+2] + pA[3*4+2] * pB[2*4+2] + pA[3*4+3] * pB[3*4+2];
+ REAL p = pA[3*4+0] * pB[0*4+3] + pA[3*4+1] * pB[1*4+3] + pA[3*4+2] * pB[2*4+3] + pA[3*4+3] * pB[3*4+3];
+
+ pM[0] = a; pM[1] = b; pM[2] = c; pM[3] = d;
+
+ pM[4] = e; pM[5] = f; pM[6] = g; pM[7] = h;
+
+ pM[8] = i; pM[9] = j; pM[10] = k; pM[11] = l;
+
+ pM[12] = m; pM[13] = n; pM[14] = o; pM[15] = p;
+}
+
+void fm_multiply(REAL *A,REAL scaler)
+{
+ A[0]*=scaler;
+ A[1]*=scaler;
+ A[2]*=scaler;
+}
+
+void fm_add(const REAL *A,const REAL *B,REAL *sum)
+{
+ sum[0] = A[0]+B[0];
+ sum[1] = A[1]+B[1];
+ sum[2] = A[2]+B[2];
+}
+
+void fm_copy3(const REAL *source,REAL *dest)
+{
+ dest[0] = source[0];
+ dest[1] = source[1];
+ dest[2] = source[2];
+}
+
+
+uint32_t fm_copyUniqueVertices(uint32_t vcount,const REAL *input_vertices,REAL *output_vertices,uint32_t tcount,const uint32_t *input_indices,uint32_t *output_indices)
+{
+ uint32_t ret = 0;
+
+ REAL *vertices = (REAL *)malloc(sizeof(REAL)*vcount*3);
+ memcpy(vertices,input_vertices,sizeof(REAL)*vcount*3);
+ REAL *dest = output_vertices;
+
+ uint32_t *reindex = (uint32_t *)malloc(sizeof(uint32_t)*vcount);
+ memset(reindex,0xFF,sizeof(uint32_t)*vcount);
+
+ uint32_t icount = tcount*3;
+
+ for (uint32_t i=0; i<icount; i++)
+ {
+ uint32_t index = *input_indices++;
+
+ assert( index < vcount );
+
+ if ( reindex[index] == 0xFFFFFFFF )
+ {
+ *output_indices++ = ret;
+ reindex[index] = ret;
+ const REAL *pos = &vertices[index*3];
+ dest[0] = pos[0];
+ dest[1] = pos[1];
+ dest[2] = pos[2];
+ dest+=3;
+ ret++;
+ }
+ else
+ {
+ *output_indices++ = reindex[index];
+ }
+ }
+ free(vertices);
+ free(reindex);
+ return ret;
+}
+
+bool fm_isMeshCoplanar(uint32_t tcount,const uint32_t *indices,const REAL *vertices,bool doubleSided) // returns true if this collection of indexed triangles are co-planar!
+{
+ bool ret = true;
+
+ if ( tcount > 0 )
+ {
+ uint32_t i1 = indices[0];
+ uint32_t i2 = indices[1];
+ uint32_t i3 = indices[2];
+ const REAL *p1 = &vertices[i1*3];
+ const REAL *p2 = &vertices[i2*3];
+ const REAL *p3 = &vertices[i3*3];
+ REAL plane[4];
+ plane[3] = fm_computePlane(p1,p2,p3,plane);
+ const uint32_t *scan = &indices[3];
+ for (uint32_t i=1; i<tcount; i++)
+ {
+ i1 = *scan++;
+ i2 = *scan++;
+ i3 = *scan++;
+ p1 = &vertices[i1*3];
+ p2 = &vertices[i2*3];
+ p3 = &vertices[i3*3];
+ REAL _plane[4];
+ _plane[3] = fm_computePlane(p1,p2,p3,_plane);
+ if ( !fm_samePlane(plane,_plane,0.01f,0.001f,doubleSided) )
+ {
+ ret = false;
+ break;
+ }
+ }
+ }
+ return ret;
+}
+
+
+bool fm_samePlane(const REAL p1[4],const REAL p2[4],REAL normalEpsilon,REAL dEpsilon,bool doubleSided)
+{
+ bool ret = false;
+
+#if 0
+ if (p1[0] == p2[0] &&
+ p1[1] == p2[1] &&
+ p1[2] == p2[2] &&
+ p1[3] == p2[3])
+ {
+ ret = true;
+ }
+#else
+ REAL diff = (REAL) fabs(p1[3]-p2[3]);
+ if ( diff < dEpsilon ) // if the plane -d co-efficient is within our epsilon
+ {
+ REAL dot = fm_dot(p1,p2); // compute the dot-product of the vector normals.
+ if ( doubleSided ) dot = (REAL)fabs(dot);
+ REAL dmin = 1 - normalEpsilon;
+ REAL dmax = 1 + normalEpsilon;
+ if ( dot >= dmin && dot <= dmax )
+ {
+ ret = true; // then the plane equation is for practical purposes identical.
+ }
+ }
+#endif
+ return ret;
+}
+
+
+void fm_initMinMax(REAL bmin[3],REAL bmax[3])
+{
+ bmin[0] = FLT_MAX;
+ bmin[1] = FLT_MAX;
+ bmin[2] = FLT_MAX;
+
+ bmax[0] = -FLT_MAX;
+ bmax[1] = -FLT_MAX;
+ bmax[2] = -FLT_MAX;
+}
+
+void fm_inflateMinMax(REAL bmin[3], REAL bmax[3], REAL ratio)
+{
+ REAL inflate = fm_distance(bmin, bmax)*0.5f*ratio;
+
+ bmin[0] -= inflate;
+ bmin[1] -= inflate;
+ bmin[2] -= inflate;
+
+ bmax[0] += inflate;
+ bmax[1] += inflate;
+ bmax[2] += inflate;
+}
+
+#ifndef TESSELATE_H
+
+#define TESSELATE_H
+
+typedef std::vector< uint32_t > UintVector;
+
+class Myfm_Tesselate : public fm_Tesselate
+{
+public:
+ virtual ~Myfm_Tesselate(void)
+ {
+
+ }
+
+ const uint32_t * tesselate(fm_VertexIndex *vindex,uint32_t tcount,const uint32_t *indices,float longEdge,uint32_t maxDepth,uint32_t &outcount)
+ {
+ const uint32_t *ret = 0;
+
+ mMaxDepth = maxDepth;
+ mLongEdge = longEdge*longEdge;
+ mLongEdgeD = mLongEdge;
+ mVertices = vindex;
+
+ if ( mVertices->isDouble() )
+ {
+ uint32_t vcount = mVertices->getVcount();
+ double *vertices = (double *)malloc(sizeof(double)*vcount*3);
+ memcpy(vertices,mVertices->getVerticesDouble(),sizeof(double)*vcount*3);
+
+ for (uint32_t i=0; i<tcount; i++)
+ {
+ uint32_t i1 = *indices++;
+ uint32_t i2 = *indices++;
+ uint32_t i3 = *indices++;
+
+ const double *p1 = &vertices[i1*3];
+ const double *p2 = &vertices[i2*3];
+ const double *p3 = &vertices[i3*3];
+
+ tesselate(p1,p2,p3,0);
+
+ }
+ free(vertices);
+ }
+ else
+ {
+ uint32_t vcount = mVertices->getVcount();
+ float *vertices = (float *)malloc(sizeof(float)*vcount*3);
+ memcpy(vertices,mVertices->getVerticesFloat(),sizeof(float)*vcount*3);
+
+
+ for (uint32_t i=0; i<tcount; i++)
+ {
+ uint32_t i1 = *indices++;
+ uint32_t i2 = *indices++;
+ uint32_t i3 = *indices++;
+
+ const float *p1 = &vertices[i1*3];
+ const float *p2 = &vertices[i2*3];
+ const float *p3 = &vertices[i3*3];
+
+ tesselate(p1,p2,p3,0);
+
+ }
+ free(vertices);
+ }
+
+ outcount = (uint32_t)(mIndices.size()/3);
+ ret = &mIndices[0];
+
+
+ return ret;
+ }
+
+ void tesselate(const float *p1,const float *p2,const float *p3,uint32_t recurse)
+ {
+ bool split = false;
+ float l1,l2,l3;
+
+ l1 = l2 = l3 = 0;
+
+ if ( recurse < mMaxDepth )
+ {
+ l1 = fm_distanceSquared(p1,p2);
+ l2 = fm_distanceSquared(p2,p3);
+ l3 = fm_distanceSquared(p3,p1);
+
+ if ( l1 > mLongEdge || l2 > mLongEdge || l3 > mLongEdge )
+ split = true;
+
+ }
+
+ if ( split )
+ {
+ uint32_t edge;
+
+ if ( l1 >= l2 && l1 >= l3 )
+ edge = 0;
+ else if ( l2 >= l1 && l2 >= l3 )
+ edge = 1;
+ else
+ edge = 2;
+
+ float splits[3];
+
+ switch ( edge )
+ {
+ case 0:
+ {
+ fm_lerp(p1,p2,splits,0.5f);
+ tesselate(p1,splits,p3, recurse+1 );
+ tesselate(splits,p2,p3, recurse+1 );
+ }
+ break;
+ case 1:
+ {
+ fm_lerp(p2,p3,splits,0.5f);
+ tesselate(p1,p2,splits, recurse+1 );
+ tesselate(p1,splits,p3, recurse+1 );
+ }
+ break;
+ case 2:
+ {
+ fm_lerp(p3,p1,splits,0.5f);
+ tesselate(p1,p2,splits, recurse+1 );
+ tesselate(splits,p2,p3, recurse+1 );
+ }
+ break;
+ }
+ }
+ else
+ {
+ bool newp;
+
+ uint32_t i1 = mVertices->getIndex(p1,newp);
+ uint32_t i2 = mVertices->getIndex(p2,newp);
+ uint32_t i3 = mVertices->getIndex(p3,newp);
+
+ mIndices.push_back(i1);
+ mIndices.push_back(i2);
+ mIndices.push_back(i3);
+ }
+
+ }
+
+ void tesselate(const double *p1,const double *p2,const double *p3,uint32_t recurse)
+ {
+ bool split = false;
+ double l1,l2,l3;
+
+ l1 = l2 = l3 = 0;
+
+ if ( recurse < mMaxDepth )
+ {
+ l1 = fm_distanceSquared(p1,p2);
+ l2 = fm_distanceSquared(p2,p3);
+ l3 = fm_distanceSquared(p3,p1);
+
+ if ( l1 > mLongEdgeD || l2 > mLongEdgeD || l3 > mLongEdgeD )
+ split = true;
+
+ }
+
+ if ( split )
+ {
+ uint32_t edge;
+
+ if ( l1 >= l2 && l1 >= l3 )
+ edge = 0;
+ else if ( l2 >= l1 && l2 >= l3 )
+ edge = 1;
+ else
+ edge = 2;
+
+ double splits[3];
+
+ switch ( edge )
+ {
+ case 0:
+ {
+ fm_lerp(p1,p2,splits,0.5);
+ tesselate(p1,splits,p3, recurse+1 );
+ tesselate(splits,p2,p3, recurse+1 );
+ }
+ break;
+ case 1:
+ {
+ fm_lerp(p2,p3,splits,0.5);
+ tesselate(p1,p2,splits, recurse+1 );
+ tesselate(p1,splits,p3, recurse+1 );
+ }
+ break;
+ case 2:
+ {
+ fm_lerp(p3,p1,splits,0.5);
+ tesselate(p1,p2,splits, recurse+1 );
+ tesselate(splits,p2,p3, recurse+1 );
+ }
+ break;
+ }
+ }
+ else
+ {
+ bool newp;
+
+ uint32_t i1 = mVertices->getIndex(p1,newp);
+ uint32_t i2 = mVertices->getIndex(p2,newp);
+ uint32_t i3 = mVertices->getIndex(p3,newp);
+
+ mIndices.push_back(i1);
+ mIndices.push_back(i2);
+ mIndices.push_back(i3);
+ }
+
+ }
+
+private:
+ float mLongEdge;
+ double mLongEdgeD;
+ fm_VertexIndex *mVertices;
+ UintVector mIndices;
+ uint32_t mMaxDepth;
+};
+
+fm_Tesselate * fm_createTesselate(void)
+{
+ Myfm_Tesselate *m = new Myfm_Tesselate;
+ return static_cast< fm_Tesselate * >(m);
+}
+
+void fm_releaseTesselate(fm_Tesselate *t)
+{
+ Myfm_Tesselate *m = static_cast< Myfm_Tesselate *>(t);
+ delete m;
+}
+
+#endif
+
+
+#ifndef RAY_ABB_INTERSECT
+
+#define RAY_ABB_INTERSECT
+
+//! Integer representation of a floating-point value.
+#define IR(x) ((uint32_t&)x)
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+* A method to compute a ray-AABB intersection.
+* Original code by Andrew Woo, from "Graphics Gems", Academic Press, 1990
+* Optimized code by Pierre Terdiman, 2000 (~20-30% faster on my Celeron 500)
+* Epsilon value added by Klaus Hartmann. (discarding it saves a few cycles only)
+*
+* Hence this version is faster as well as more robust than the original one.
+*
+* Should work provided:
+* 1) the integer representation of 0.0f is 0x00000000
+* 2) the sign bit of the float is the most significant one
+*
+* Report bugs: p.terdiman@codercorner.com
+*
+* \param aabb [in] the axis-aligned bounding box
+* \param origin [in] ray origin
+* \param dir [in] ray direction
+* \param coord [out] impact coordinates
+* \return true if ray intersects AABB
+*/
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+#define RAYAABB_EPSILON 0.00001f
+bool fm_intersectRayAABB(const float MinB[3],const float MaxB[3],const float origin[3],const float dir[3],float coord[3])
+{
+ bool Inside = true;
+ float MaxT[3];
+ MaxT[0]=MaxT[1]=MaxT[2]=-1.0f;
+
+ // Find candidate planes.
+ for(uint32_t i=0;i<3;i++)
+ {
+ if(origin[i] < MinB[i])
+ {
+ coord[i] = MinB[i];
+ Inside = false;
+
+ // Calculate T distances to candidate planes
+ if(IR(dir[i])) MaxT[i] = (MinB[i] - origin[i]) / dir[i];
+ }
+ else if(origin[i] > MaxB[i])
+ {
+ coord[i] = MaxB[i];
+ Inside = false;
+
+ // Calculate T distances to candidate planes
+ if(IR(dir[i])) MaxT[i] = (MaxB[i] - origin[i]) / dir[i];
+ }
+ }
+
+ // Ray origin inside bounding box
+ if(Inside)
+ {
+ coord[0] = origin[0];
+ coord[1] = origin[1];
+ coord[2] = origin[2];
+ return true;
+ }
+
+ // Get largest of the maxT's for final choice of intersection
+ uint32_t WhichPlane = 0;
+ if(MaxT[1] > MaxT[WhichPlane]) WhichPlane = 1;
+ if(MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2;
+
+ // Check final candidate actually inside box
+ if(IR(MaxT[WhichPlane])&0x80000000) return false;
+
+ for(uint32_t i=0;i<3;i++)
+ {
+ if(i!=WhichPlane)
+ {
+ coord[i] = origin[i] + MaxT[WhichPlane] * dir[i];
+#ifdef RAYAABB_EPSILON
+ if(coord[i] < MinB[i] - RAYAABB_EPSILON || coord[i] > MaxB[i] + RAYAABB_EPSILON) return false;
+#else
+ if(coord[i] < MinB[i] || coord[i] > MaxB[i]) return false;
+#endif
+ }
+ }
+ return true; // ray hits box
+}
+
+bool fm_intersectLineSegmentAABB(const float bmin[3],const float bmax[3],const float p1[3],const float p2[3],float intersect[3])
+{
+ bool ret = false;
+
+ float dir[3];
+ dir[0] = p2[0] - p1[0];
+ dir[1] = p2[1] - p1[1];
+ dir[2] = p2[2] - p1[2];
+ float dist = fm_normalize(dir);
+ if ( dist > RAYAABB_EPSILON )
+ {
+ ret = fm_intersectRayAABB(bmin,bmax,p1,dir,intersect);
+ if ( ret )
+ {
+ float d = fm_distanceSquared(p1,intersect);
+ if ( d > (dist*dist) )
+ {
+ ret = false;
+ }
+ }
+ }
+ return ret;
+}
+
+#endif
+
+#ifndef OBB_TO_AABB
+
+#define OBB_TO_AABB
+
+#pragma warning(disable:4100)
+
+void fm_OBBtoAABB(const float /*obmin*/[3],const float /*obmax*/[3],const float /*matrix*/[16],float /*abmin*/[3],float /*abmax*/[3])
+{
+ assert(0); // not yet implemented.
+}
+
+
+const REAL * computePos(uint32_t index,const REAL *vertices,uint32_t vstride)
+{
+ const char *tmp = (const char *)vertices;
+ tmp+=(index*vstride);
+ return (const REAL*)tmp;
+}
+
+void computeNormal(uint32_t index,REAL *normals,uint32_t nstride,const REAL *normal)
+{
+ char *tmp = (char *)normals;
+ tmp+=(index*nstride);
+ REAL *dest = (REAL *)tmp;
+ dest[0]+=normal[0];
+ dest[1]+=normal[1];
+ dest[2]+=normal[2];
+}
+
+void fm_computeMeanNormals(uint32_t vcount, // the number of vertices
+ const REAL *vertices, // the base address of the vertex position data.
+ uint32_t vstride, // the stride between position data.
+ REAL *normals, // the base address of the destination for mean vector normals
+ uint32_t nstride, // the stride between normals
+ uint32_t tcount, // the number of triangles
+ const uint32_t *indices) // the triangle indices
+{
+
+ // Step #1 : Zero out the vertex normals
+ char *dest = (char *)normals;
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ REAL *n = (REAL *)dest;
+ n[0] = 0;
+ n[1] = 0;
+ n[2] = 0;
+ dest+=nstride;
+ }
+
+ // Step #2 : Compute the face normals and accumulate them
+ const uint32_t *scan = indices;
+ for (uint32_t i=0; i<tcount; i++)
+ {
+
+ uint32_t i1 = *scan++;
+ uint32_t i2 = *scan++;
+ uint32_t i3 = *scan++;
+
+ const REAL *p1 = computePos(i1,vertices,vstride);
+ const REAL *p2 = computePos(i2,vertices,vstride);
+ const REAL *p3 = computePos(i3,vertices,vstride);
+
+ REAL normal[3];
+ fm_computePlane(p3,p2,p1,normal);
+
+ computeNormal(i1,normals,nstride,normal);
+ computeNormal(i2,normals,nstride,normal);
+ computeNormal(i3,normals,nstride,normal);
+ }
+
+
+ // Normalize the accumulated normals
+ dest = (char *)normals;
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ REAL *n = (REAL *)dest;
+ fm_normalize(n);
+ dest+=nstride;
+ }
+
+}
+
+#endif
+
+
+#define BIGNUMBER 100000000.0 /* hundred million */
+
+static inline void Set(REAL *n,REAL x,REAL y,REAL z)
+{
+ n[0] = x;
+ n[1] = y;
+ n[2] = z;
+};
+
+static inline void Copy(REAL *dest,const REAL *source)
+{
+ dest[0] = source[0];
+ dest[1] = source[1];
+ dest[2] = source[2];
+}
+
+
+REAL fm_computeBestFitSphere(uint32_t vcount,const REAL *points,uint32_t pstride,REAL *center)
+{
+ REAL radius;
+ REAL radius2;
+
+ REAL xmin[3];
+ REAL xmax[3];
+ REAL ymin[3];
+ REAL ymax[3];
+ REAL zmin[3];
+ REAL zmax[3];
+ REAL dia1[3];
+ REAL dia2[3];
+
+ /* FIRST PASS: find 6 minima/maxima points */
+ Set(xmin,BIGNUMBER,BIGNUMBER,BIGNUMBER);
+ Set(xmax,-BIGNUMBER,-BIGNUMBER,-BIGNUMBER);
+ Set(ymin,BIGNUMBER,BIGNUMBER,BIGNUMBER);
+ Set(ymax,-BIGNUMBER,-BIGNUMBER,-BIGNUMBER);
+ Set(zmin,BIGNUMBER,BIGNUMBER,BIGNUMBER);
+ Set(zmax,-BIGNUMBER,-BIGNUMBER,-BIGNUMBER);
+
+ {
+ const char *scan = (const char *)points;
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ const REAL *caller_p = (const REAL *)scan;
+ if (caller_p[0]<xmin[0])
+ Copy(xmin,caller_p); /* New xminimum point */
+ if (caller_p[0]>xmax[0])
+ Copy(xmax,caller_p);
+ if (caller_p[1]<ymin[1])
+ Copy(ymin,caller_p);
+ if (caller_p[1]>ymax[1])
+ Copy(ymax,caller_p);
+ if (caller_p[2]<zmin[2])
+ Copy(zmin,caller_p);
+ if (caller_p[2]>zmax[2])
+ Copy(zmax,caller_p);
+ scan+=pstride;
+ }
+ }
+
+ /* Set xspan = distance between the 2 points xmin & xmax (squared) */
+ REAL dx = xmax[0] - xmin[0];
+ REAL dy = xmax[1] - xmin[1];
+ REAL dz = xmax[2] - xmin[2];
+ REAL xspan = dx*dx + dy*dy + dz*dz;
+
+/* Same for y & z spans */
+ dx = ymax[0] - ymin[0];
+ dy = ymax[1] - ymin[1];
+ dz = ymax[2] - ymin[2];
+ REAL yspan = dx*dx + dy*dy + dz*dz;
+
+ dx = zmax[0] - zmin[0];
+ dy = zmax[1] - zmin[1];
+ dz = zmax[2] - zmin[2];
+ REAL zspan = dx*dx + dy*dy + dz*dz;
+
+ /* Set points dia1 & dia2 to the maximally separated pair */
+ Copy(dia1,xmin);
+ Copy(dia2,xmax); /* assume xspan biggest */
+ REAL maxspan = xspan;
+
+ if (yspan>maxspan)
+ {
+ maxspan = yspan;
+ Copy(dia1,ymin);
+ Copy(dia2,ymax);
+ }
+
+ if (zspan>maxspan)
+ {
+ maxspan = zspan;
+ Copy(dia1,zmin);
+ Copy(dia2,zmax);
+ }
+
+
+ /* dia1,dia2 is a diameter of initial sphere */
+ /* calc initial center */
+ center[0] = (dia1[0]+dia2[0])*0.5f;
+ center[1] = (dia1[1]+dia2[1])*0.5f;
+ center[2] = (dia1[2]+dia2[2])*0.5f;
+
+ /* calculate initial radius**2 and radius */
+
+ dx = dia2[0]-center[0]; /* x component of radius vector */
+ dy = dia2[1]-center[1]; /* y component of radius vector */
+ dz = dia2[2]-center[2]; /* z component of radius vector */
+
+ radius2 = dx*dx + dy*dy + dz*dz;
+ radius = REAL(sqrt(radius2));
+
+ /* SECOND PASS: increment current sphere */
+ {
+ const char *scan = (const char *)points;
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ const REAL *caller_p = (const REAL *)scan;
+ dx = caller_p[0]-center[0];
+ dy = caller_p[1]-center[1];
+ dz = caller_p[2]-center[2];
+ REAL old_to_p_sq = dx*dx + dy*dy + dz*dz;
+ if (old_to_p_sq > radius2) /* do r**2 test first */
+ { /* this point is outside of current sphere */
+ REAL old_to_p = REAL(sqrt(old_to_p_sq));
+ /* calc radius of new sphere */
+ radius = (radius + old_to_p) * 0.5f;
+ radius2 = radius*radius; /* for next r**2 compare */
+ REAL old_to_new = old_to_p - radius;
+ /* calc center of new sphere */
+ REAL recip = 1.0f /old_to_p;
+ REAL cx = (radius*center[0] + old_to_new*caller_p[0]) * recip;
+ REAL cy = (radius*center[1] + old_to_new*caller_p[1]) * recip;
+ REAL cz = (radius*center[2] + old_to_new*caller_p[2]) * recip;
+ Set(center,cx,cy,cz);
+ scan+=pstride;
+ }
+ }
+ }
+ return radius;
+}
+
+
+void fm_computeBestFitCapsule(uint32_t vcount,const REAL *points,uint32_t pstride,REAL &radius,REAL &height,REAL matrix[16],bool bruteForce)
+{
+ REAL sides[3];
+ REAL omatrix[16];
+ fm_computeBestFitOBB(vcount,points,pstride,sides,omatrix,bruteForce);
+
+ int32_t axis = 0;
+ if ( sides[0] > sides[1] && sides[0] > sides[2] )
+ axis = 0;
+ else if ( sides[1] > sides[0] && sides[1] > sides[2] )
+ axis = 1;
+ else
+ axis = 2;
+
+ REAL localTransform[16];
+
+ REAL maxDist = 0;
+ REAL maxLen = 0;
+
+ switch ( axis )
+ {
+ case 0:
+ {
+ fm_eulerMatrix(0,0,FM_PI/2,localTransform);
+ fm_matrixMultiply(localTransform,omatrix,matrix);
+
+ const uint8_t *scan = (const uint8_t *)points;
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ const REAL *p = (const REAL *)scan;
+ REAL t[3];
+ fm_inverseRT(omatrix,p,t);
+ REAL dist = t[1]*t[1]+t[2]*t[2];
+ if ( dist > maxDist )
+ {
+ maxDist = dist;
+ }
+ REAL l = (REAL) fabs(t[0]);
+ if ( l > maxLen )
+ {
+ maxLen = l;
+ }
+ scan+=pstride;
+ }
+ }
+ height = sides[0];
+ break;
+ case 1:
+ {
+ fm_eulerMatrix(0,FM_PI/2,0,localTransform);
+ fm_matrixMultiply(localTransform,omatrix,matrix);
+
+ const uint8_t *scan = (const uint8_t *)points;
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ const REAL *p = (const REAL *)scan;
+ REAL t[3];
+ fm_inverseRT(omatrix,p,t);
+ REAL dist = t[0]*t[0]+t[2]*t[2];
+ if ( dist > maxDist )
+ {
+ maxDist = dist;
+ }
+ REAL l = (REAL) fabs(t[1]);
+ if ( l > maxLen )
+ {
+ maxLen = l;
+ }
+ scan+=pstride;
+ }
+ }
+ height = sides[1];
+ break;
+ case 2:
+ {
+ fm_eulerMatrix(FM_PI/2,0,0,localTransform);
+ fm_matrixMultiply(localTransform,omatrix,matrix);
+
+ const uint8_t *scan = (const uint8_t *)points;
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ const REAL *p = (const REAL *)scan;
+ REAL t[3];
+ fm_inverseRT(omatrix,p,t);
+ REAL dist = t[0]*t[0]+t[1]*t[1];
+ if ( dist > maxDist )
+ {
+ maxDist = dist;
+ }
+ REAL l = (REAL) fabs(t[2]);
+ if ( l > maxLen )
+ {
+ maxLen = l;
+ }
+ scan+=pstride;
+ }
+ }
+ height = sides[2];
+ break;
+ }
+ radius = (REAL)sqrt(maxDist);
+ height = (maxLen*2)-(radius*2);
+}
+
+
+//************* Triangulation
+
+#ifndef TRIANGULATE_H
+
+#define TRIANGULATE_H
+
+typedef uint32_t TU32;
+
+class TVec
+{
+public:
+ TVec(double _x,double _y,double _z) { x = _x; y = _y; z = _z; };
+ TVec(void) { };
+
+ double x;
+ double y;
+ double z;
+};
+
+typedef std::vector< TVec > TVecVector;
+typedef std::vector< TU32 > TU32Vector;
+
+class CTriangulator
+{
+public:
+ /// Default constructor
+ CTriangulator();
+
+ /// Default destructor
+ virtual ~CTriangulator();
+
+ /// Triangulates the contour
+ void triangulate(TU32Vector &indices);
+
+ /// Returns the given point in the triangulator array
+ inline TVec get(const TU32 id) { return mPoints[id]; }
+
+ virtual void reset(void)
+ {
+ mInputPoints.clear();
+ mPoints.clear();
+ mIndices.clear();
+ }
+
+ virtual void addPoint(double x,double y,double z)
+ {
+ TVec v(x,y,z);
+ // update bounding box...
+ if ( mInputPoints.empty() )
+ {
+ mMin = v;
+ mMax = v;
+ }
+ else
+ {
+ if ( x < mMin.x ) mMin.x = x;
+ if ( y < mMin.y ) mMin.y = y;
+ if ( z < mMin.z ) mMin.z = z;
+
+ if ( x > mMax.x ) mMax.x = x;
+ if ( y > mMax.y ) mMax.y = y;
+ if ( z > mMax.z ) mMax.z = z;
+ }
+ mInputPoints.push_back(v);
+ }
+
+ // Triangulation happens in 2d. We could inverse transform the polygon around the normal direction, or we just use the two most signficant axes
+ // Here we find the two longest axes and use them to triangulate. Inverse transforming them would introduce more doubleing point error and isn't worth it.
+ virtual uint32_t * triangulate(uint32_t &tcount,double epsilon)
+ {
+ uint32_t *ret = 0;
+ tcount = 0;
+ mEpsilon = epsilon;
+
+ if ( !mInputPoints.empty() )
+ {
+ mPoints.clear();
+
+ double dx = mMax.x - mMin.x; // locate the first, second and third longest edges and store them in i1, i2, i3
+ double dy = mMax.y - mMin.y;
+ double dz = mMax.z - mMin.z;
+
+ uint32_t i1,i2,i3;
+
+ if ( dx > dy && dx > dz )
+ {
+ i1 = 0;
+ if ( dy > dz )
+ {
+ i2 = 1;
+ i3 = 2;
+ }
+ else
+ {
+ i2 = 2;
+ i3 = 1;
+ }
+ }
+ else if ( dy > dx && dy > dz )
+ {
+ i1 = 1;
+ if ( dx > dz )
+ {
+ i2 = 0;
+ i3 = 2;
+ }
+ else
+ {
+ i2 = 2;
+ i3 = 0;
+ }
+ }
+ else
+ {
+ i1 = 2;
+ if ( dx > dy )
+ {
+ i2 = 0;
+ i3 = 1;
+ }
+ else
+ {
+ i2 = 1;
+ i3 = 0;
+ }
+ }
+
+ uint32_t pcount = (uint32_t)mInputPoints.size();
+ const double *points = &mInputPoints[0].x;
+ for (uint32_t i=0; i<pcount; i++)
+ {
+ TVec v( points[i1], points[i2], points[i3] );
+ mPoints.push_back(v);
+ points+=3;
+ }
+
+ mIndices.clear();
+ triangulate(mIndices);
+ tcount = (uint32_t)mIndices.size()/3;
+ if ( tcount )
+ {
+ ret = &mIndices[0];
+ }
+ }
+ return ret;
+ }
+
+ virtual const double * getPoint(uint32_t index)
+ {
+ return &mInputPoints[index].x;
+ }
+
+
+private:
+ double mEpsilon;
+ TVec mMin;
+ TVec mMax;
+ TVecVector mInputPoints;
+ TVecVector mPoints;
+ TU32Vector mIndices;
+
+ /// Tests if a point is inside the given triangle
+ bool _insideTriangle(const TVec& A, const TVec& B, const TVec& C,const TVec& P);
+
+ /// Returns the area of the contour
+ double _area();
+
+ bool _snip(int32_t u, int32_t v, int32_t w, int32_t n, int32_t *V);
+
+ /// Processes the triangulation
+ void _process(TU32Vector &indices);
+
+};
+
+/// Default constructor
+CTriangulator::CTriangulator(void)
+{
+}
+
+/// Default destructor
+CTriangulator::~CTriangulator()
+{
+}
+
+/// Triangulates the contour
+void CTriangulator::triangulate(TU32Vector &indices)
+{
+ _process(indices);
+}
+
+/// Processes the triangulation
+void CTriangulator::_process(TU32Vector &indices)
+{
+ const int32_t n = (const int32_t)mPoints.size();
+ if (n < 3)
+ return;
+ int32_t *V = (int32_t *)malloc(sizeof(int32_t)*n);
+
+ bool flipped = false;
+
+ if (0.0f < _area())
+ {
+ for (int32_t v = 0; v < n; v++)
+ V[v] = v;
+ }
+ else
+ {
+ flipped = true;
+ for (int32_t v = 0; v < n; v++)
+ V[v] = (n - 1) - v;
+ }
+
+ int32_t nv = n;
+ int32_t count = 2 * nv;
+ for (int32_t m = 0, v = nv - 1; nv > 2;)
+ {
+ if (0 >= (count--))
+ return;
+
+ int32_t u = v;
+ if (nv <= u)
+ u = 0;
+ v = u + 1;
+ if (nv <= v)
+ v = 0;
+ int32_t w = v + 1;
+ if (nv <= w)
+ w = 0;
+
+ if (_snip(u, v, w, nv, V))
+ {
+ int32_t a, b, c, s, t;
+ a = V[u];
+ b = V[v];
+ c = V[w];
+ if ( flipped )
+ {
+ indices.push_back(a);
+ indices.push_back(b);
+ indices.push_back(c);
+ }
+ else
+ {
+ indices.push_back(c);
+ indices.push_back(b);
+ indices.push_back(a);
+ }
+ m++;
+ for (s = v, t = v + 1; t < nv; s++, t++)
+ V[s] = V[t];
+ nv--;
+ count = 2 * nv;
+ }
+ }
+
+ free(V);
+}
+
+/// Returns the area of the contour
+double CTriangulator::_area()
+{
+ int32_t n = (uint32_t)mPoints.size();
+ double A = 0.0f;
+ for (int32_t p = n - 1, q = 0; q < n; p = q++)
+ {
+ const TVec &pval = mPoints[p];
+ const TVec &qval = mPoints[q];
+ A += pval.x * qval.y - qval.x * pval.y;
+ }
+ A*=0.5f;
+ return A;
+}
+
+bool CTriangulator::_snip(int32_t u, int32_t v, int32_t w, int32_t n, int32_t *V)
+{
+ int32_t p;
+
+ const TVec &A = mPoints[ V[u] ];
+ const TVec &B = mPoints[ V[v] ];
+ const TVec &C = mPoints[ V[w] ];
+
+ if (mEpsilon > (((B.x - A.x) * (C.y - A.y)) - ((B.y - A.y) * (C.x - A.x))) )
+ return false;
+
+ for (p = 0; p < n; p++)
+ {
+ if ((p == u) || (p == v) || (p == w))
+ continue;
+ const TVec &P = mPoints[ V[p] ];
+ if (_insideTriangle(A, B, C, P))
+ return false;
+ }
+ return true;
+}
+
+/// Tests if a point is inside the given triangle
+bool CTriangulator::_insideTriangle(const TVec& A, const TVec& B, const TVec& C,const TVec& P)
+{
+ double ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
+ double cCROSSap, bCROSScp, aCROSSbp;
+
+ ax = C.x - B.x; ay = C.y - B.y;
+ bx = A.x - C.x; by = A.y - C.y;
+ cx = B.x - A.x; cy = B.y - A.y;
+ apx = P.x - A.x; apy = P.y - A.y;
+ bpx = P.x - B.x; bpy = P.y - B.y;
+ cpx = P.x - C.x; cpy = P.y - C.y;
+
+ aCROSSbp = ax * bpy - ay * bpx;
+ cCROSSap = cx * apy - cy * apx;
+ bCROSScp = bx * cpy - by * cpx;
+
+ return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f));
+}
+
+class Triangulate : public fm_Triangulate
+{
+public:
+ Triangulate(void)
+ {
+ mPointsFloat = 0;
+ mPointsDouble = 0;
+ }
+
+ virtual ~Triangulate(void)
+ {
+ reset();
+ }
+ void reset(void)
+ {
+ free(mPointsFloat);
+ free(mPointsDouble);
+ mPointsFloat = 0;
+ mPointsDouble = 0;
+ }
+
+ virtual const double * triangulate3d(uint32_t pcount,
+ const double *_points,
+ uint32_t vstride,
+ uint32_t &tcount,
+ bool consolidate,
+ double epsilon)
+ {
+ reset();
+
+ double *points = (double *)malloc(sizeof(double)*pcount*3);
+ if ( consolidate )
+ {
+ pcount = fm_consolidatePolygon(pcount,_points,vstride,points,1-epsilon);
+ }
+ else
+ {
+ double *dest = points;
+ for (uint32_t i=0; i<pcount; i++)
+ {
+ const double *src = fm_getPoint(_points,vstride,i);
+ dest[0] = src[0];
+ dest[1] = src[1];
+ dest[2] = src[2];
+ dest+=3;
+ }
+ vstride = sizeof(double)*3;
+ }
+
+ if ( pcount >= 3 )
+ {
+ CTriangulator ct;
+ for (uint32_t i=0; i<pcount; i++)
+ {
+ const double *src = fm_getPoint(points,vstride,i);
+ ct.addPoint( src[0], src[1], src[2] );
+ }
+ uint32_t _tcount;
+ uint32_t *indices = ct.triangulate(_tcount,epsilon);
+ if ( indices )
+ {
+ tcount = _tcount;
+ mPointsDouble = (double *)malloc(sizeof(double)*tcount*3*3);
+ double *dest = mPointsDouble;
+ for (uint32_t i=0; i<tcount; i++)
+ {
+ uint32_t i1 = indices[i*3+0];
+ uint32_t i2 = indices[i*3+1];
+ uint32_t i3 = indices[i*3+2];
+ const double *p1 = ct.getPoint(i1);
+ const double *p2 = ct.getPoint(i2);
+ const double *p3 = ct.getPoint(i3);
+
+ dest[0] = p1[0];
+ dest[1] = p1[1];
+ dest[2] = p1[2];
+
+ dest[3] = p2[0];
+ dest[4] = p2[1];
+ dest[5] = p2[2];
+
+ dest[6] = p3[0];
+ dest[7] = p3[1];
+ dest[8] = p3[2];
+ dest+=9;
+ }
+ }
+ }
+ free(points);
+
+ return mPointsDouble;
+ }
+
+ virtual const float * triangulate3d(uint32_t pcount,
+ const float *points,
+ uint32_t vstride,
+ uint32_t &tcount,
+ bool consolidate,
+ float epsilon)
+ {
+ reset();
+
+ double *temp = (double *)malloc(sizeof(double)*pcount*3);
+ double *dest = temp;
+ for (uint32_t i=0; i<pcount; i++)
+ {
+ const float *p = fm_getPoint(points,vstride,i);
+ dest[0] = p[0];
+ dest[1] = p[1];
+ dest[2] = p[2];
+ dest+=3;
+ }
+ const double *results = triangulate3d(pcount,temp,sizeof(double)*3,tcount,consolidate,epsilon);
+ if ( results )
+ {
+ uint32_t fcount = tcount*3*3;
+ mPointsFloat = (float *)malloc(sizeof(float)*tcount*3*3);
+ for (uint32_t i=0; i<fcount; i++)
+ {
+ mPointsFloat[i] = (float) results[i];
+ }
+ free(mPointsDouble);
+ mPointsDouble = 0;
+ }
+ free(temp);
+
+ return mPointsFloat;
+ }
+
+private:
+ float *mPointsFloat;
+ double *mPointsDouble;
+};
+
+fm_Triangulate * fm_createTriangulate(void)
+{
+ Triangulate *t = new Triangulate;
+ return static_cast< fm_Triangulate *>(t);
+}
+
+void fm_releaseTriangulate(fm_Triangulate *t)
+{
+ Triangulate *tt = static_cast< Triangulate *>(t);
+ delete tt;
+}
+
+#endif
+
+bool validDistance(const REAL *p1,const REAL *p2,REAL epsilon)
+{
+ bool ret = true;
+
+ REAL dx = p1[0] - p2[0];
+ REAL dy = p1[1] - p2[1];
+ REAL dz = p1[2] - p2[2];
+ REAL dist = dx*dx+dy*dy+dz*dz;
+ if ( dist < (epsilon*epsilon) )
+ {
+ ret = false;
+ }
+ return ret;
+}
+
+bool fm_isValidTriangle(const REAL *p1,const REAL *p2,const REAL *p3,REAL epsilon)
+{
+ bool ret = false;
+
+ if ( validDistance(p1,p2,epsilon) &&
+ validDistance(p1,p3,epsilon) &&
+ validDistance(p2,p3,epsilon) )
+ {
+
+ REAL area = fm_computeArea(p1,p2,p3);
+ if ( area > epsilon )
+ {
+ REAL _vertices[3*3],vertices[64*3];
+
+ _vertices[0] = p1[0];
+ _vertices[1] = p1[1];
+ _vertices[2] = p1[2];
+
+ _vertices[3] = p2[0];
+ _vertices[4] = p2[1];
+ _vertices[5] = p2[2];
+
+ _vertices[6] = p3[0];
+ _vertices[7] = p3[1];
+ _vertices[8] = p3[2];
+
+ uint32_t pcount = fm_consolidatePolygon(3,_vertices,sizeof(REAL)*3,vertices,1-epsilon);
+ if ( pcount == 3 )
+ {
+ ret = true;
+ }
+ }
+ }
+ return ret;
+}
+
+
+void fm_multiplyQuat(const REAL *left,const REAL *right,REAL *quat)
+{
+ REAL a,b,c,d;
+
+ a = left[3]*right[3] - left[0]*right[0] - left[1]*right[1] - left[2]*right[2];
+ b = left[3]*right[0] + right[3]*left[0] + left[1]*right[2] - right[1]*left[2];
+ c = left[3]*right[1] + right[3]*left[1] + left[2]*right[0] - right[2]*left[0];
+ d = left[3]*right[2] + right[3]*left[2] + left[0]*right[1] - right[0]*left[1];
+
+ quat[3] = a;
+ quat[0] = b;
+ quat[1] = c;
+ quat[2] = d;
+}
+
+bool fm_computeCentroid(uint32_t vcount, // number of input data points
+ const REAL *points, // starting address of points array.
+ REAL *center)
+
+{
+ bool ret = false;
+ if ( vcount )
+ {
+ center[0] = 0;
+ center[1] = 0;
+ center[2] = 0;
+ const REAL *p = points;
+ for (uint32_t i=0; i<vcount; i++)
+ {
+ center[0]+=p[0];
+ center[1]+=p[1];
+ center[2]+=p[2];
+ p += 3;
+ }
+ REAL recip = 1.0f / (REAL)vcount;
+ center[0]*=recip;
+ center[1]*=recip;
+ center[2]*=recip;
+ ret = true;
+ }
+ return ret;
+}
+
+bool fm_computeCentroid(uint32_t vcount, // number of input data points
+ const REAL *points, // starting address of points array.
+ uint32_t triCount,
+ const uint32_t *indices,
+ REAL *center)
+
+{
+ bool ret = false;
+ if (vcount)
+ {
+ center[0] = 0;
+ center[1] = 0;
+ center[2] = 0;
+
+ REAL numerator[3] = { 0, 0, 0 };
+ REAL denomintaor = 0;
+
+ for (uint32_t i = 0; i < triCount; i++)
+ {
+ uint32_t i1 = indices[i * 3 + 0];
+ uint32_t i2 = indices[i * 3 + 1];
+ uint32_t i3 = indices[i * 3 + 2];
+
+ const REAL *p1 = &points[i1 * 3];
+ const REAL *p2 = &points[i2 * 3];
+ const REAL *p3 = &points[i3 * 3];
+
+ // Compute the sum of the three positions
+ REAL sum[3];
+ sum[0] = p1[0] + p2[0] + p3[0];
+ sum[1] = p1[1] + p2[1] + p3[1];
+ sum[2] = p1[2] + p2[2] + p3[2];
+
+ // Compute the average of the three positions
+ sum[0] = sum[0] / 3;
+ sum[1] = sum[1] / 3;
+ sum[2] = sum[2] / 3;
+
+ // Compute the area of this triangle
+ REAL area = fm_computeArea(p1, p2, p3);
+
+ numerator[0]+= (sum[0] * area);
+ numerator[1]+= (sum[1] * area);
+ numerator[2]+= (sum[2] * area);
+
+ denomintaor += area;
+
+ }
+ REAL recip = 1 / denomintaor;
+ center[0] = numerator[0] * recip;
+ center[1] = numerator[1] * recip;
+ center[2] = numerator[2] * recip;
+ ret = true;
+ }
+ return ret;
+}
+
+
+#ifndef TEMPLATE_VEC3
+#define TEMPLATE_VEC3
+template <class Type> class Vec3
+{
+public:
+ Vec3(void)
+ {
+
+ }
+ Vec3(Type _x,Type _y,Type _z)
+ {
+ x = _x;
+ y = _y;
+ z = _z;
+ }
+ Type x;
+ Type y;
+ Type z;
+};
+#endif
+
+void fm_transformAABB(const REAL bmin[3],const REAL bmax[3],const REAL matrix[16],REAL tbmin[3],REAL tbmax[3])
+{
+ Vec3<REAL> box[8];
+ box[0] = Vec3< REAL >( bmin[0], bmin[1], bmin[2] );
+ box[1] = Vec3< REAL >( bmax[0], bmin[1], bmin[2] );
+ box[2] = Vec3< REAL >( bmax[0], bmax[1], bmin[2] );
+ box[3] = Vec3< REAL >( bmin[0], bmax[1], bmin[2] );
+ box[4] = Vec3< REAL >( bmin[0], bmin[1], bmax[2] );
+ box[5] = Vec3< REAL >( bmax[0], bmin[1], bmax[2] );
+ box[6] = Vec3< REAL >( bmax[0], bmax[1], bmax[2] );
+ box[7] = Vec3< REAL >( bmin[0], bmax[1], bmax[2] );
+ // transform all 8 corners of the box and then recompute a new AABB
+ for (unsigned int i=0; i<8; i++)
+ {
+ Vec3< REAL > &p = box[i];
+ fm_transform(matrix,&p.x,&p.x);
+ if ( i == 0 )
+ {
+ tbmin[0] = tbmax[0] = p.x;
+ tbmin[1] = tbmax[1] = p.y;
+ tbmin[2] = tbmax[2] = p.z;
+ }
+ else
+ {
+ if ( p.x < tbmin[0] ) tbmin[0] = p.x;
+ if ( p.y < tbmin[1] ) tbmin[1] = p.y;
+ if ( p.z < tbmin[2] ) tbmin[2] = p.z;
+ if ( p.x > tbmax[0] ) tbmax[0] = p.x;
+ if ( p.y > tbmax[1] ) tbmax[1] = p.y;
+ if ( p.z > tbmax[2] ) tbmax[2] = p.z;
+ }
+ }
+}
+
+REAL fm_normalizeQuat(REAL n[4]) // normalize this quat
+{
+ REAL dx = n[0]*n[0];
+ REAL dy = n[1]*n[1];
+ REAL dz = n[2]*n[2];
+ REAL dw = n[3]*n[3];
+
+ REAL dist = dx*dx+dy*dy+dz*dz+dw*dw;
+
+ dist = (REAL)sqrt(dist);
+
+ REAL recip = 1.0f / dist;
+
+ n[0]*=recip;
+ n[1]*=recip;
+ n[2]*=recip;
+ n[3]*=recip;
+
+ return dist;
+}
+
+
+}; // end of namespace
diff --git a/thirdparty/vhacd/src/VHACD-ASYNC.cpp b/thirdparty/vhacd/src/VHACD-ASYNC.cpp
new file mode 100644
index 0000000000..baf309d6a1
--- /dev/null
+++ b/thirdparty/vhacd/src/VHACD-ASYNC.cpp
@@ -0,0 +1,334 @@
+#include "../public/VHACD.h"
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <thread>
+#include <atomic>
+#include <mutex>
+#include <string>
+#include <float.h>
+
+#define ENABLE_ASYNC 1
+
+#define HACD_ALLOC(x) malloc(x)
+#define HACD_FREE(x) free(x)
+#define HACD_ASSERT(x) assert(x)
+
+namespace VHACD
+{
+
+class MyHACD_API : public VHACD::IVHACD, public VHACD::IVHACD::IUserCallback, VHACD::IVHACD::IUserLogger
+{
+public:
+ MyHACD_API(void)
+ {
+ mVHACD = VHACD::CreateVHACD();
+ }
+
+ virtual ~MyHACD_API(void)
+ {
+ releaseHACD();
+ Cancel();
+ mVHACD->Release();
+ }
+
+
+ virtual bool Compute(const double* const _points,
+ const uint32_t countPoints,
+ const uint32_t* const _triangles,
+ const uint32_t countTriangles,
+ const Parameters& _desc) final
+ {
+#if ENABLE_ASYNC
+ Cancel(); // if we previously had a solution running; cancel it.
+ releaseHACD();
+
+ // We need to copy the input vertices and triangles into our own buffers so we can operate
+ // on them safely from the background thread.
+ mVertices = (double *)HACD_ALLOC(sizeof(double)*countPoints * 3);
+ mIndices = (uint32_t *)HACD_ALLOC(sizeof(uint32_t)*countTriangles * 3);
+ memcpy(mVertices, _points, sizeof(double)*countPoints * 3);
+ memcpy(mIndices, _triangles, sizeof(uint32_t)*countTriangles * 3);
+ mRunning = true;
+ mThread = new std::thread([this, countPoints, countTriangles, _desc]()
+ {
+ ComputeNow(mVertices, countPoints, mIndices, countTriangles, _desc);
+ mRunning = false;
+ });
+#else
+ releaseHACD();
+ ComputeNow(_points, countPoints, _triangles, countTriangles, _desc);
+#endif
+ return true;
+ }
+
+ bool ComputeNow(const double* const points,
+ const uint32_t countPoints,
+ const uint32_t* const triangles,
+ const uint32_t countTriangles,
+ const Parameters& _desc)
+ {
+ uint32_t ret = 0;
+
+ mHullCount = 0;
+ mCallback = _desc.m_callback;
+ mLogger = _desc.m_logger;
+
+ IVHACD::Parameters desc = _desc;
+ // Set our intercepting callback interfaces if non-null
+ desc.m_callback = desc.m_callback ? this : nullptr;
+ desc.m_logger = desc.m_logger ? this : nullptr;
+
+ if ( countPoints )
+ {
+ bool ok = mVHACD->Compute(points, countPoints, triangles, countTriangles, desc);
+ if (ok)
+ {
+ ret = mVHACD->GetNConvexHulls();
+ mHulls = new IVHACD::ConvexHull[ret];
+ for (uint32_t i = 0; i < ret; i++)
+ {
+ VHACD::IVHACD::ConvexHull vhull;
+ mVHACD->GetConvexHull(i, vhull);
+ VHACD::IVHACD::ConvexHull h;
+ h.m_nPoints = vhull.m_nPoints;
+ h.m_points = (double *)HACD_ALLOC(sizeof(double) * 3 * h.m_nPoints);
+ memcpy(h.m_points, vhull.m_points, sizeof(double) * 3 * h.m_nPoints);
+ h.m_nTriangles = vhull.m_nTriangles;
+ h.m_triangles = (uint32_t *)HACD_ALLOC(sizeof(uint32_t) * 3 * h.m_nTriangles);
+ memcpy(h.m_triangles, vhull.m_triangles, sizeof(uint32_t) * 3 * h.m_nTriangles);
+ h.m_volume = vhull.m_volume;
+ h.m_center[0] = vhull.m_center[0];
+ h.m_center[1] = vhull.m_center[1];
+ h.m_center[2] = vhull.m_center[2];
+ mHulls[i] = h;
+ if (mCancel)
+ {
+ ret = 0;
+ break;
+ }
+ }
+ }
+ }
+
+ mHullCount = ret;
+ return ret ? true : false;
+ }
+
+ void releaseHull(VHACD::IVHACD::ConvexHull &h)
+ {
+ HACD_FREE((void *)h.m_triangles);
+ HACD_FREE((void *)h.m_points);
+ h.m_triangles = nullptr;
+ h.m_points = nullptr;
+ }
+
+ virtual void GetConvexHull(const uint32_t index, VHACD::IVHACD::ConvexHull& ch) const final
+ {
+ if ( index < mHullCount )
+ {
+ ch = mHulls[index];
+ }
+ }
+
+ void releaseHACD(void) // release memory associated with the last HACD request
+ {
+ for (uint32_t i=0; i<mHullCount; i++)
+ {
+ releaseHull(mHulls[i]);
+ }
+ delete[]mHulls;
+ mHulls = nullptr;
+ mHullCount = 0;
+ HACD_FREE(mVertices);
+ mVertices = nullptr;
+ HACD_FREE(mIndices);
+ mIndices = nullptr;
+ }
+
+
+ virtual void release(void) // release the HACD_API interface
+ {
+ delete this;
+ }
+
+ virtual uint32_t getHullCount(void)
+ {
+ return mHullCount;
+ }
+
+ virtual void Cancel() final
+ {
+ if (mRunning)
+ {
+ mVHACD->Cancel(); // Set the cancel signal to the base VHACD
+ }
+ if (mThread)
+ {
+ mThread->join(); // Wait for the thread to fully exit before we delete the instance
+ delete mThread;
+ mThread = nullptr;
+ Log("Convex Decomposition thread canceled\n");
+ }
+ mCancel = false; // clear the cancel semaphore
+ }
+
+ virtual bool Compute(const float* const points,
+ const uint32_t countPoints,
+ const uint32_t* const triangles,
+ const uint32_t countTriangles,
+ const Parameters& params) final
+ {
+
+ double *vertices = (double *)HACD_ALLOC(sizeof(double)*countPoints * 3);
+ const float *source = points;
+ double *dest = vertices;
+ for (uint32_t i = 0; i < countPoints; i++)
+ {
+ dest[0] = source[0];
+ dest[1] = source[1];
+ dest[2] = source[2];
+ dest += 3;
+ source += 3;
+ }
+
+ bool ret = Compute(vertices, countPoints, triangles, countTriangles, params);
+ HACD_FREE(vertices);
+ return ret;
+ }
+
+ virtual uint32_t GetNConvexHulls() const final
+ {
+ processPendingMessages();
+ return mHullCount;
+ }
+
+ virtual void Clean(void) final // release internally allocated memory
+ {
+ Cancel();
+ releaseHACD();
+ mVHACD->Clean();
+ }
+
+ virtual void Release(void) final // release IVHACD
+ {
+ delete this;
+ }
+
+ virtual bool OCLInit(void* const oclDevice,
+ IVHACD::IUserLogger* const logger = 0) final
+ {
+ return mVHACD->OCLInit(oclDevice, logger);
+ }
+
+ virtual bool OCLRelease(IVHACD::IUserLogger* const logger = 0) final
+ {
+ return mVHACD->OCLRelease(logger);
+ }
+
+ virtual void Update(const double overallProgress,
+ const double stageProgress,
+ const double operationProgress,
+ const char* const stage,
+ const char* const operation) final
+ {
+ mMessageMutex.lock();
+ mHaveUpdateMessage = true;
+ mOverallProgress = overallProgress;
+ mStageProgress = stageProgress;
+ mOperationProgress = operationProgress;
+ mStage = std::string(stage);
+ mOperation = std::string(operation);
+ mMessageMutex.unlock();
+ }
+
+ virtual void Log(const char* const msg) final
+ {
+ mMessageMutex.lock();
+ mHaveLogMessage = true;
+ mMessage = std::string(msg);
+ mMessageMutex.unlock();
+ }
+
+ virtual bool IsReady(void) const final
+ {
+ processPendingMessages();
+ return !mRunning;
+ }
+
+ // As a convenience for the calling application we only send it update and log messages from it's own main
+ // thread. This reduces the complexity burden on the caller by making sure it only has to deal with log
+ // messages in it's main application thread.
+ void processPendingMessages(void) const
+ {
+ // If we have a new update message and the user has specified a callback we send the message and clear the semaphore
+ if (mHaveUpdateMessage && mCallback)
+ {
+ mMessageMutex.lock();
+ mCallback->Update(mOverallProgress, mStageProgress, mOperationProgress, mStage.c_str(), mOperation.c_str());
+ mHaveUpdateMessage = false;
+ mMessageMutex.unlock();
+ }
+ // If we have a new log message and the user has specified a callback we send the message and clear the semaphore
+ if (mHaveLogMessage && mLogger)
+ {
+ mMessageMutex.lock();
+ mLogger->Log(mMessage.c_str());
+ mHaveLogMessage = false;
+ mMessageMutex.unlock();
+ }
+ }
+
+ // Will compute the center of mass of the convex hull decomposition results and return it
+ // in 'centerOfMass'. Returns false if the center of mass could not be computed.
+ virtual bool ComputeCenterOfMass(double centerOfMass[3]) const
+ {
+ bool ret = false;
+
+ centerOfMass[0] = 0;
+ centerOfMass[1] = 0;
+ centerOfMass[2] = 0;
+
+ if (mVHACD && IsReady() )
+ {
+ ret = mVHACD->ComputeCenterOfMass(centerOfMass);
+ }
+ return ret;
+ }
+
+private:
+ double *mVertices{ nullptr };
+ uint32_t *mIndices{ nullptr };
+ std::atomic< uint32_t> mHullCount{ 0 };
+ VHACD::IVHACD::ConvexHull *mHulls{ nullptr };
+ VHACD::IVHACD::IUserCallback *mCallback{ nullptr };
+ VHACD::IVHACD::IUserLogger *mLogger{ nullptr };
+ VHACD::IVHACD *mVHACD{ nullptr };
+ std::thread *mThread{ nullptr };
+ std::atomic< bool > mRunning{ false };
+ std::atomic<bool> mCancel{ false };
+
+ // Thread safe caching mechanism for messages and update status.
+ // This is so that caller always gets messages in his own thread
+ // Member variables are marked as 'mutable' since the message dispatch function
+ // is called from const query methods.
+ mutable std::mutex mMessageMutex;
+ mutable std::atomic< bool > mHaveUpdateMessage{ false };
+ mutable std::atomic< bool > mHaveLogMessage{ false };
+ mutable double mOverallProgress{ 0 };
+ mutable double mStageProgress{ 0 };
+ mutable double mOperationProgress{ 0 };
+ mutable std::string mStage;
+ mutable std::string mOperation;
+ mutable std::string mMessage;
+};
+
+IVHACD* CreateVHACD_ASYNC(void)
+{
+ MyHACD_API *m = new MyHACD_API;
+ return static_cast<IVHACD *>(m);
+}
+
+
+}; // end of VHACD namespace
+
diff --git a/thirdparty/vhacd/src/VHACD.cpp b/thirdparty/vhacd/src/VHACD.cpp
new file mode 100644
index 0000000000..54cc6e3761
--- /dev/null
+++ b/thirdparty/vhacd/src/VHACD.cpp
@@ -0,0 +1,1589 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include <algorithm>
+#include <fstream>
+#include <iomanip>
+#include <limits>
+#include <sstream>
+#if _OPENMP
+#include <omp.h>
+#endif // _OPENMP
+
+#include "../public/VHACD.h"
+#include "btConvexHullComputer.h"
+#include "vhacdICHull.h"
+#include "vhacdMesh.h"
+#include "vhacdSArray.h"
+#include "vhacdTimer.h"
+#include "vhacdVHACD.h"
+#include "vhacdVector.h"
+#include "vhacdVolume.h"
+#include "FloatMath.h"
+
+#define MAX(a, b) (((a) > (b)) ? (a) : (b))
+#define MIN(a, b) (((a) < (b)) ? (a) : (b))
+#define ABS(a) (((a) < 0) ? -(a) : (a))
+#define ZSGN(a) (((a) < 0) ? -1 : (a) > 0 ? 1 : 0)
+#define MAX_DOUBLE (1.79769e+308)
+
+#ifdef _MSC_VER
+#pragma warning(disable:4267 4100 4244 4456)
+#endif
+
+#ifdef USE_SSE
+#include <immintrin.h>
+
+const int32_t SIMD_WIDTH = 4;
+inline int32_t FindMinimumElement(const float* const d, float* const _, const int32_t n)
+{
+ // Min within vectors
+ __m128 min_i = _mm_set1_ps(-1.0f);
+ __m128 min_v = _mm_set1_ps(std::numeric_limits<float>::max());
+ for (int32_t i = 0; i <= n - SIMD_WIDTH; i += SIMD_WIDTH) {
+ const __m128 data = _mm_load_ps(&d[i]);
+ const __m128 pred = _mm_cmplt_ps(data, min_v);
+
+ min_i = _mm_blendv_ps(min_i, _mm_set1_ps(i), pred);
+ min_v = _mm_min_ps(data, min_v);
+ }
+
+ /* Min within vector */
+ const __m128 min1 = _mm_shuffle_ps(min_v, min_v, _MM_SHUFFLE(1, 0, 3, 2));
+ const __m128 min2 = _mm_min_ps(min_v, min1);
+ const __m128 min3 = _mm_shuffle_ps(min2, min2, _MM_SHUFFLE(0, 1, 0, 1));
+ const __m128 min4 = _mm_min_ps(min2, min3);
+ float min_d = _mm_cvtss_f32(min4);
+
+ // Min index
+ const int32_t min_idx = __builtin_ctz(_mm_movemask_ps(_mm_cmpeq_ps(min_v, min4)));
+ int32_t ret = min_i[min_idx] + min_idx;
+
+ // Trailing elements
+ for (int32_t i = (n & ~(SIMD_WIDTH - 1)); i < n; ++i) {
+ if (d[i] < min_d) {
+ min_d = d[i];
+ ret = i;
+ }
+ }
+
+ *m = min_d;
+ return ret;
+}
+
+inline int32_t FindMinimumElement(const float* const d, float* const m, const int32_t begin, const int32_t end)
+{
+ // Leading elements
+ int32_t min_i = -1;
+ float min_d = std::numeric_limits<float>::max();
+ const int32_t aligned = (begin & ~(SIMD_WIDTH - 1)) + ((begin & (SIMD_WIDTH - 1)) ? SIMD_WIDTH : 0);
+ for (int32_t i = begin; i < std::min(end, aligned); ++i) {
+ if (d[i] < min_d) {
+ min_d = d[i];
+ min_i = i;
+ }
+ }
+
+ // Middle and trailing elements
+ float r_m = std::numeric_limits<float>::max();
+ const int32_t n = end - aligned;
+ const int32_t r_i = (n > 0) ? FindMinimumElement(&d[aligned], &r_m, n) : 0;
+
+ // Pick the lowest
+ if (r_m < min_d) {
+ *m = r_m;
+ return r_i + aligned;
+ }
+ else {
+ *m = min_d;
+ return min_i;
+ }
+}
+#else
+inline int32_t FindMinimumElement(const float* const d, float* const m, const int32_t begin, const int32_t end)
+{
+ int32_t idx = -1;
+ float min = (std::numeric_limits<float>::max)();
+ for (size_t i = begin; i < size_t(end); ++i) {
+ if (d[i] < min) {
+ idx = i;
+ min = d[i];
+ }
+ }
+
+ *m = min;
+ return idx;
+}
+#endif
+
+//#define OCL_SOURCE_FROM_FILE
+#ifndef OCL_SOURCE_FROM_FILE
+const char* oclProgramSource = "\
+__kernel void ComputePartialVolumes(__global short4 * voxels, \
+ const int numVoxels, \
+ const float4 plane, \
+ const float4 minBB, \
+ const float4 scale, \
+ __local uint4 * localPartialVolumes, \
+ __global uint4 * partialVolumes) \
+{ \
+ int localId = get_local_id(0); \
+ int groupSize = get_local_size(0); \
+ int i0 = get_global_id(0) << 2; \
+ float4 voxel; \
+ uint4 v; \
+ voxel = convert_float4(voxels[i0]); \
+ v.s0 = (dot(plane, mad(scale, voxel, minBB)) >= 0.0f) * (i0 < numVoxels);\
+ voxel = convert_float4(voxels[i0 + 1]); \
+ v.s1 = (dot(plane, mad(scale, voxel, minBB)) >= 0.0f) * (i0 + 1 < numVoxels);\
+ voxel = convert_float4(voxels[i0 + 2]); \
+ v.s2 = (dot(plane, mad(scale, voxel, minBB)) >= 0.0f) * (i0 + 2 < numVoxels);\
+ voxel = convert_float4(voxels[i0 + 3]); \
+ v.s3 = (dot(plane, mad(scale, voxel, minBB)) >= 0.0f) * (i0 + 3 < numVoxels);\
+ localPartialVolumes[localId] = v; \
+ barrier(CLK_LOCAL_MEM_FENCE); \
+ for (int i = groupSize >> 1; i > 0; i >>= 1) \
+ { \
+ if (localId < i) \
+ { \
+ localPartialVolumes[localId] += localPartialVolumes[localId + i]; \
+ } \
+ barrier(CLK_LOCAL_MEM_FENCE); \
+ } \
+ if (localId == 0) \
+ { \
+ partialVolumes[get_group_id(0)] = localPartialVolumes[0]; \
+ } \
+} \
+__kernel void ComputePartialSums(__global uint4 * data, \
+ const int dataSize, \
+ __local uint4 * partialSums) \
+{ \
+ int globalId = get_global_id(0); \
+ int localId = get_local_id(0); \
+ int groupSize = get_local_size(0); \
+ int i; \
+ if (globalId < dataSize) \
+ { \
+ partialSums[localId] = data[globalId]; \
+ } \
+ else \
+ { \
+ partialSums[localId] = (0, 0, 0, 0); \
+ } \
+ barrier(CLK_LOCAL_MEM_FENCE); \
+ for (i = groupSize >> 1; i > 0; i >>= 1) \
+ { \
+ if (localId < i) \
+ { \
+ partialSums[localId] += partialSums[localId + i]; \
+ } \
+ barrier(CLK_LOCAL_MEM_FENCE); \
+ } \
+ if (localId == 0) \
+ { \
+ data[get_group_id(0)] = partialSums[0]; \
+ } \
+}";
+#endif //OCL_SOURCE_FROM_FILE
+
+namespace VHACD {
+IVHACD* CreateVHACD(void)
+{
+ return new VHACD();
+}
+bool VHACD::OCLInit(void* const oclDevice, IUserLogger* const logger)
+{
+#ifdef CL_VERSION_1_1
+ m_oclDevice = (cl_device_id*)oclDevice;
+ cl_int error;
+ m_oclContext = clCreateContext(NULL, 1, m_oclDevice, NULL, NULL, &error);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't create context\n");
+ }
+ return false;
+ }
+
+#ifdef OCL_SOURCE_FROM_FILE
+ std::string cl_files = OPENCL_CL_FILES;
+// read kernal from file
+#ifdef _WIN32
+ std::replace(cl_files.begin(), cl_files.end(), '/', '\\');
+#endif // _WIN32
+
+ FILE* program_handle = fopen(cl_files.c_str(), "rb");
+ fseek(program_handle, 0, SEEK_END);
+ size_t program_size = ftell(program_handle);
+ rewind(program_handle);
+ char* program_buffer = new char[program_size + 1];
+ program_buffer[program_size] = '\0';
+ fread(program_buffer, sizeof(char), program_size, program_handle);
+ fclose(program_handle);
+ // create program
+ m_oclProgram = clCreateProgramWithSource(m_oclContext, 1, (const char**)&program_buffer, &program_size, &error);
+ delete[] program_buffer;
+#else
+ size_t program_size = strlen(oclProgramSource);
+ m_oclProgram = clCreateProgramWithSource(m_oclContext, 1, (const char**)&oclProgramSource, &program_size, &error);
+#endif
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't create program\n");
+ }
+ return false;
+ }
+
+ /* Build program */
+ error = clBuildProgram(m_oclProgram, 1, m_oclDevice, "-cl-denorms-are-zero", NULL, NULL);
+ if (error != CL_SUCCESS) {
+ size_t log_size;
+ /* Find Size of log and print to std output */
+ clGetProgramBuildInfo(m_oclProgram, *m_oclDevice, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
+ char* program_log = new char[log_size + 2];
+ program_log[log_size] = '\n';
+ program_log[log_size + 1] = '\0';
+ clGetProgramBuildInfo(m_oclProgram, *m_oclDevice, CL_PROGRAM_BUILD_LOG, log_size + 1, program_log, NULL);
+ if (logger) {
+ logger->Log("Couldn't build program\n");
+ logger->Log(program_log);
+ }
+ delete[] program_log;
+ return false;
+ }
+
+ delete[] m_oclQueue;
+ delete[] m_oclKernelComputePartialVolumes;
+ delete[] m_oclKernelComputeSum;
+ m_oclQueue = new cl_command_queue[m_ompNumProcessors];
+ m_oclKernelComputePartialVolumes = new cl_kernel[m_ompNumProcessors];
+ m_oclKernelComputeSum = new cl_kernel[m_ompNumProcessors];
+
+ const char nameKernelComputePartialVolumes[] = "ComputePartialVolumes";
+ const char nameKernelComputeSum[] = "ComputePartialSums";
+ for (int32_t k = 0; k < m_ompNumProcessors; ++k) {
+ m_oclKernelComputePartialVolumes[k] = clCreateKernel(m_oclProgram, nameKernelComputePartialVolumes, &error);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't create kernel\n");
+ }
+ return false;
+ }
+ m_oclKernelComputeSum[k] = clCreateKernel(m_oclProgram, nameKernelComputeSum, &error);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't create kernel\n");
+ }
+ return false;
+ }
+ }
+
+ error = clGetKernelWorkGroupInfo(m_oclKernelComputePartialVolumes[0],
+ *m_oclDevice,
+ CL_KERNEL_WORK_GROUP_SIZE,
+ sizeof(size_t),
+ &m_oclWorkGroupSize,
+ NULL);
+ size_t workGroupSize = 0;
+ error = clGetKernelWorkGroupInfo(m_oclKernelComputeSum[0],
+ *m_oclDevice,
+ CL_KERNEL_WORK_GROUP_SIZE,
+ sizeof(size_t),
+ &workGroupSize,
+ NULL);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't query work group info\n");
+ }
+ return false;
+ }
+
+ if (workGroupSize < m_oclWorkGroupSize) {
+ m_oclWorkGroupSize = workGroupSize;
+ }
+
+ for (int32_t k = 0; k < m_ompNumProcessors; ++k) {
+ m_oclQueue[k] = clCreateCommandQueue(m_oclContext, *m_oclDevice, 0 /*CL_QUEUE_PROFILING_ENABLE*/, &error);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't create queue\n");
+ }
+ return false;
+ }
+ }
+ return true;
+#else //CL_VERSION_1_1
+ return false;
+#endif //CL_VERSION_1_1
+}
+bool VHACD::OCLRelease(IUserLogger* const logger)
+{
+#ifdef CL_VERSION_1_1
+ cl_int error;
+ if (m_oclKernelComputePartialVolumes) {
+ for (int32_t k = 0; k < m_ompNumProcessors; ++k) {
+ error = clReleaseKernel(m_oclKernelComputePartialVolumes[k]);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't release kernal\n");
+ }
+ return false;
+ }
+ }
+ delete[] m_oclKernelComputePartialVolumes;
+ }
+ if (m_oclKernelComputeSum) {
+ for (int32_t k = 0; k < m_ompNumProcessors; ++k) {
+ error = clReleaseKernel(m_oclKernelComputeSum[k]);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't release kernal\n");
+ }
+ return false;
+ }
+ }
+ delete[] m_oclKernelComputeSum;
+ }
+ if (m_oclQueue) {
+ for (int32_t k = 0; k < m_ompNumProcessors; ++k) {
+ error = clReleaseCommandQueue(m_oclQueue[k]);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't release queue\n");
+ }
+ return false;
+ }
+ }
+ delete[] m_oclQueue;
+ }
+ error = clReleaseProgram(m_oclProgram);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't release program\n");
+ }
+ return false;
+ }
+ error = clReleaseContext(m_oclContext);
+ if (error != CL_SUCCESS) {
+ if (logger) {
+ logger->Log("Couldn't release context\n");
+ }
+ return false;
+ }
+
+ return true;
+#else //CL_VERSION_1_1
+ return false;
+#endif //CL_VERSION_1_1
+}
+void VHACD::ComputePrimitiveSet(const Parameters& params)
+{
+ if (GetCancel()) {
+ return;
+ }
+ m_timer.Tic();
+
+ m_stage = "Compute primitive set";
+ m_operation = "Convert volume to pset";
+
+ std::ostringstream msg;
+ if (params.m_logger) {
+ msg << "+ " << m_stage << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ Update(0.0, 0.0, params);
+ if (params.m_mode == 0) {
+ VoxelSet* vset = new VoxelSet;
+ m_volume->Convert(*vset);
+ m_pset = vset;
+ }
+ else {
+ TetrahedronSet* tset = new TetrahedronSet;
+ m_volume->Convert(*tset);
+ m_pset = tset;
+ }
+
+ delete m_volume;
+ m_volume = 0;
+
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t # primitives " << m_pset->GetNPrimitives() << std::endl;
+ msg << "\t # inside surface " << m_pset->GetNPrimitivesInsideSurf() << std::endl;
+ msg << "\t # on surface " << m_pset->GetNPrimitivesOnSurf() << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ m_overallProgress = 15.0;
+ Update(100.0, 100.0, params);
+ m_timer.Toc();
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t time " << m_timer.GetElapsedTime() / 1000.0 << "s" << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+}
+bool VHACD::Compute(const double* const points, const uint32_t nPoints,
+ const uint32_t* const triangles,const uint32_t nTriangles, const Parameters& params)
+{
+ return ComputeACD(points, nPoints, triangles, nTriangles, params);
+}
+bool VHACD::Compute(const float* const points,const uint32_t nPoints,
+ const uint32_t* const triangles,const uint32_t nTriangles, const Parameters& params)
+{
+ return ComputeACD(points, nPoints, triangles, nTriangles, params);
+}
+double ComputePreferredCuttingDirection(const PrimitiveSet* const tset, Vec3<double>& dir)
+{
+ double ex = tset->GetEigenValue(AXIS_X);
+ double ey = tset->GetEigenValue(AXIS_Y);
+ double ez = tset->GetEigenValue(AXIS_Z);
+ double vx = (ey - ez) * (ey - ez);
+ double vy = (ex - ez) * (ex - ez);
+ double vz = (ex - ey) * (ex - ey);
+ if (vx < vy && vx < vz) {
+ double e = ey * ey + ez * ez;
+ dir[0] = 1.0;
+ dir[1] = 0.0;
+ dir[2] = 0.0;
+ return (e == 0.0) ? 0.0 : 1.0 - vx / e;
+ }
+ else if (vy < vx && vy < vz) {
+ double e = ex * ex + ez * ez;
+ dir[0] = 0.0;
+ dir[1] = 1.0;
+ dir[2] = 0.0;
+ return (e == 0.0) ? 0.0 : 1.0 - vy / e;
+ }
+ else {
+ double e = ex * ex + ey * ey;
+ dir[0] = 0.0;
+ dir[1] = 0.0;
+ dir[2] = 1.0;
+ return (e == 0.0) ? 0.0 : 1.0 - vz / e;
+ }
+}
+void ComputeAxesAlignedClippingPlanes(const VoxelSet& vset, const short downsampling, SArray<Plane>& planes)
+{
+ const Vec3<short> minV = vset.GetMinBBVoxels();
+ const Vec3<short> maxV = vset.GetMaxBBVoxels();
+ Vec3<double> pt;
+ Plane plane;
+ const short i0 = minV[0];
+ const short i1 = maxV[0];
+ plane.m_a = 1.0;
+ plane.m_b = 0.0;
+ plane.m_c = 0.0;
+ plane.m_axis = AXIS_X;
+ for (short i = i0; i <= i1; i += downsampling) {
+ pt = vset.GetPoint(Vec3<double>(i + 0.5, 0.0, 0.0));
+ plane.m_d = -pt[0];
+ plane.m_index = i;
+ planes.PushBack(plane);
+ }
+ const short j0 = minV[1];
+ const short j1 = maxV[1];
+ plane.m_a = 0.0;
+ plane.m_b = 1.0;
+ plane.m_c = 0.0;
+ plane.m_axis = AXIS_Y;
+ for (short j = j0; j <= j1; j += downsampling) {
+ pt = vset.GetPoint(Vec3<double>(0.0, j + 0.5, 0.0));
+ plane.m_d = -pt[1];
+ plane.m_index = j;
+ planes.PushBack(plane);
+ }
+ const short k0 = minV[2];
+ const short k1 = maxV[2];
+ plane.m_a = 0.0;
+ plane.m_b = 0.0;
+ plane.m_c = 1.0;
+ plane.m_axis = AXIS_Z;
+ for (short k = k0; k <= k1; k += downsampling) {
+ pt = vset.GetPoint(Vec3<double>(0.0, 0.0, k + 0.5));
+ plane.m_d = -pt[2];
+ plane.m_index = k;
+ planes.PushBack(plane);
+ }
+}
+void ComputeAxesAlignedClippingPlanes(const TetrahedronSet& tset, const short downsampling, SArray<Plane>& planes)
+{
+ const Vec3<double> minV = tset.GetMinBB();
+ const Vec3<double> maxV = tset.GetMaxBB();
+ const double scale = tset.GetSacle();
+ const short i0 = 0;
+ const short j0 = 0;
+ const short k0 = 0;
+ const short i1 = static_cast<short>((maxV[0] - minV[0]) / scale + 0.5);
+ const short j1 = static_cast<short>((maxV[1] - minV[1]) / scale + 0.5);
+ const short k1 = static_cast<short>((maxV[2] - minV[2]) / scale + 0.5);
+
+ Plane plane;
+ plane.m_a = 1.0;
+ plane.m_b = 0.0;
+ plane.m_c = 0.0;
+ plane.m_axis = AXIS_X;
+ for (short i = i0; i <= i1; i += downsampling) {
+ double x = minV[0] + scale * i;
+ plane.m_d = -x;
+ plane.m_index = i;
+ planes.PushBack(plane);
+ }
+ plane.m_a = 0.0;
+ plane.m_b = 1.0;
+ plane.m_c = 0.0;
+ plane.m_axis = AXIS_Y;
+ for (short j = j0; j <= j1; j += downsampling) {
+ double y = minV[1] + scale * j;
+ plane.m_d = -y;
+ plane.m_index = j;
+ planes.PushBack(plane);
+ }
+ plane.m_a = 0.0;
+ plane.m_b = 0.0;
+ plane.m_c = 1.0;
+ plane.m_axis = AXIS_Z;
+ for (short k = k0; k <= k1; k += downsampling) {
+ double z = minV[2] + scale * k;
+ plane.m_d = -z;
+ plane.m_index = k;
+ planes.PushBack(plane);
+ }
+}
+void RefineAxesAlignedClippingPlanes(const VoxelSet& vset, const Plane& bestPlane, const short downsampling,
+ SArray<Plane>& planes)
+{
+ const Vec3<short> minV = vset.GetMinBBVoxels();
+ const Vec3<short> maxV = vset.GetMaxBBVoxels();
+ Vec3<double> pt;
+ Plane plane;
+
+ if (bestPlane.m_axis == AXIS_X) {
+ const short i0 = MAX(minV[0], bestPlane.m_index - downsampling);
+ const short i1 = MIN(maxV[0], bestPlane.m_index + downsampling);
+ plane.m_a = 1.0;
+ plane.m_b = 0.0;
+ plane.m_c = 0.0;
+ plane.m_axis = AXIS_X;
+ for (short i = i0; i <= i1; ++i) {
+ pt = vset.GetPoint(Vec3<double>(i + 0.5, 0.0, 0.0));
+ plane.m_d = -pt[0];
+ plane.m_index = i;
+ planes.PushBack(plane);
+ }
+ }
+ else if (bestPlane.m_axis == AXIS_Y) {
+ const short j0 = MAX(minV[1], bestPlane.m_index - downsampling);
+ const short j1 = MIN(maxV[1], bestPlane.m_index + downsampling);
+ plane.m_a = 0.0;
+ plane.m_b = 1.0;
+ plane.m_c = 0.0;
+ plane.m_axis = AXIS_Y;
+ for (short j = j0; j <= j1; ++j) {
+ pt = vset.GetPoint(Vec3<double>(0.0, j + 0.5, 0.0));
+ plane.m_d = -pt[1];
+ plane.m_index = j;
+ planes.PushBack(plane);
+ }
+ }
+ else {
+ const short k0 = MAX(minV[2], bestPlane.m_index - downsampling);
+ const short k1 = MIN(maxV[2], bestPlane.m_index + downsampling);
+ plane.m_a = 0.0;
+ plane.m_b = 0.0;
+ plane.m_c = 1.0;
+ plane.m_axis = AXIS_Z;
+ for (short k = k0; k <= k1; ++k) {
+ pt = vset.GetPoint(Vec3<double>(0.0, 0.0, k + 0.5));
+ plane.m_d = -pt[2];
+ plane.m_index = k;
+ planes.PushBack(plane);
+ }
+ }
+}
+void RefineAxesAlignedClippingPlanes(const TetrahedronSet& tset, const Plane& bestPlane, const short downsampling,
+ SArray<Plane>& planes)
+{
+ const Vec3<double> minV = tset.GetMinBB();
+ const Vec3<double> maxV = tset.GetMaxBB();
+ const double scale = tset.GetSacle();
+ Plane plane;
+
+ if (bestPlane.m_axis == AXIS_X) {
+ const short i0 = MAX(0, bestPlane.m_index - downsampling);
+ const short i1 = static_cast<short>(MIN((maxV[0] - minV[0]) / scale + 0.5, bestPlane.m_index + downsampling));
+ plane.m_a = 1.0;
+ plane.m_b = 0.0;
+ plane.m_c = 0.0;
+ plane.m_axis = AXIS_X;
+ for (short i = i0; i <= i1; ++i) {
+ double x = minV[0] + scale * i;
+ plane.m_d = -x;
+ plane.m_index = i;
+ planes.PushBack(plane);
+ }
+ }
+ else if (bestPlane.m_axis == AXIS_Y) {
+ const short j0 = MAX(0, bestPlane.m_index - downsampling);
+ const short j1 = static_cast<short>(MIN((maxV[1] - minV[1]) / scale + 0.5, bestPlane.m_index + downsampling));
+ plane.m_a = 0.0;
+ plane.m_b = 1.0;
+ plane.m_c = 0.0;
+ plane.m_axis = AXIS_Y;
+ for (short j = j0; j <= j1; ++j) {
+ double y = minV[1] + scale * j;
+ plane.m_d = -y;
+ plane.m_index = j;
+ planes.PushBack(plane);
+ }
+ }
+ else {
+ const short k0 = MAX(0, bestPlane.m_index - downsampling);
+ const short k1 = static_cast<short>(MIN((maxV[2] - minV[2]) / scale + 0.5, bestPlane.m_index + downsampling));
+ plane.m_a = 0.0;
+ plane.m_b = 0.0;
+ plane.m_c = 1.0;
+ plane.m_axis = AXIS_Z;
+ for (short k = k0; k <= k1; ++k) {
+ double z = minV[2] + scale * k;
+ plane.m_d = -z;
+ plane.m_index = k;
+ planes.PushBack(plane);
+ }
+ }
+}
+inline double ComputeLocalConcavity(const double volume, const double volumeCH)
+{
+ return fabs(volumeCH - volume) / volumeCH;
+}
+inline double ComputeConcavity(const double volume, const double volumeCH, const double volume0)
+{
+ return fabs(volumeCH - volume) / volume0;
+}
+
+//#define DEBUG_TEMP
+void VHACD::ComputeBestClippingPlane(const PrimitiveSet* inputPSet, const double volume, const SArray<Plane>& planes,
+ const Vec3<double>& preferredCuttingDirection, const double w, const double alpha, const double beta,
+ const int32_t convexhullDownsampling, const double progress0, const double progress1, Plane& bestPlane,
+ double& minConcavity, const Parameters& params)
+{
+ if (GetCancel()) {
+ return;
+ }
+ char msg[256];
+ size_t nPrimitives = inputPSet->GetNPrimitives();
+ bool oclAcceleration = (nPrimitives > OCL_MIN_NUM_PRIMITIVES && params.m_oclAcceleration && params.m_mode == 0) ? true : false;
+ int32_t iBest = -1;
+ int32_t nPlanes = static_cast<int32_t>(planes.Size());
+ bool cancel = false;
+ int32_t done = 0;
+ double minTotal = MAX_DOUBLE;
+ double minBalance = MAX_DOUBLE;
+ double minSymmetry = MAX_DOUBLE;
+ minConcavity = MAX_DOUBLE;
+
+ SArray<Vec3<double> >* chPts = new SArray<Vec3<double> >[2 * m_ompNumProcessors];
+ Mesh* chs = new Mesh[2 * m_ompNumProcessors];
+ PrimitiveSet* onSurfacePSet = inputPSet->Create();
+ inputPSet->SelectOnSurface(onSurfacePSet);
+
+ PrimitiveSet** psets = 0;
+ if (!params.m_convexhullApproximation) {
+ psets = new PrimitiveSet*[2 * m_ompNumProcessors];
+ for (int32_t i = 0; i < 2 * m_ompNumProcessors; ++i) {
+ psets[i] = inputPSet->Create();
+ }
+ }
+
+#ifdef CL_VERSION_1_1
+ // allocate OpenCL data structures
+ cl_mem voxels;
+ cl_mem* partialVolumes = 0;
+ size_t globalSize = 0;
+ size_t nWorkGroups = 0;
+ double unitVolume = 0.0;
+ if (oclAcceleration) {
+ VoxelSet* vset = (VoxelSet*)inputPSet;
+ const Vec3<double> minBB = vset->GetMinBB();
+ const float fMinBB[4] = { (float)minBB[0], (float)minBB[1], (float)minBB[2], 1.0f };
+ const float fSclae[4] = { (float)vset->GetScale(), (float)vset->GetScale(), (float)vset->GetScale(), 0.0f };
+ const int32_t nVoxels = (int32_t)nPrimitives;
+ unitVolume = vset->GetUnitVolume();
+ nWorkGroups = (nPrimitives + 4 * m_oclWorkGroupSize - 1) / (4 * m_oclWorkGroupSize);
+ globalSize = nWorkGroups * m_oclWorkGroupSize;
+ cl_int error;
+ voxels = clCreateBuffer(m_oclContext,
+ CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
+ sizeof(Voxel) * nPrimitives,
+ vset->GetVoxels(),
+ &error);
+ if (error != CL_SUCCESS) {
+ if (params.m_logger) {
+ params.m_logger->Log("Couldn't create buffer\n");
+ }
+ SetCancel(true);
+ }
+
+ partialVolumes = new cl_mem[m_ompNumProcessors];
+ for (int32_t i = 0; i < m_ompNumProcessors; ++i) {
+ partialVolumes[i] = clCreateBuffer(m_oclContext,
+ CL_MEM_WRITE_ONLY,
+ sizeof(uint32_t) * 4 * nWorkGroups,
+ NULL,
+ &error);
+ if (error != CL_SUCCESS) {
+ if (params.m_logger) {
+ params.m_logger->Log("Couldn't create buffer\n");
+ }
+ SetCancel(true);
+ break;
+ }
+ error = clSetKernelArg(m_oclKernelComputePartialVolumes[i], 0, sizeof(cl_mem), &voxels);
+ error |= clSetKernelArg(m_oclKernelComputePartialVolumes[i], 1, sizeof(uint32_t), &nVoxels);
+ error |= clSetKernelArg(m_oclKernelComputePartialVolumes[i], 3, sizeof(float) * 4, fMinBB);
+ error |= clSetKernelArg(m_oclKernelComputePartialVolumes[i], 4, sizeof(float) * 4, &fSclae);
+ error |= clSetKernelArg(m_oclKernelComputePartialVolumes[i], 5, sizeof(uint32_t) * 4 * m_oclWorkGroupSize, NULL);
+ error |= clSetKernelArg(m_oclKernelComputePartialVolumes[i], 6, sizeof(cl_mem), &(partialVolumes[i]));
+ error |= clSetKernelArg(m_oclKernelComputeSum[i], 0, sizeof(cl_mem), &(partialVolumes[i]));
+ error |= clSetKernelArg(m_oclKernelComputeSum[i], 2, sizeof(uint32_t) * 4 * m_oclWorkGroupSize, NULL);
+ if (error != CL_SUCCESS) {
+ if (params.m_logger) {
+ params.m_logger->Log("Couldn't kernel arguments \n");
+ }
+ SetCancel(true);
+ }
+ }
+ }
+#else // CL_VERSION_1_1
+ oclAcceleration = false;
+#endif // CL_VERSION_1_1
+
+#ifdef DEBUG_TEMP
+ Timer timerComputeCost;
+ timerComputeCost.Tic();
+#endif // DEBUG_TEMP
+
+#if USE_THREAD == 1 && _OPENMP
+#pragma omp parallel for
+#endif
+ for (int32_t x = 0; x < nPlanes; ++x) {
+ int32_t threadID = 0;
+#if USE_THREAD == 1 && _OPENMP
+ threadID = omp_get_thread_num();
+#pragma omp flush(cancel)
+#endif
+ if (!cancel) {
+ //Update progress
+ if (GetCancel()) {
+ cancel = true;
+#if USE_THREAD == 1 && _OPENMP
+#pragma omp flush(cancel)
+#endif
+ }
+ Plane plane = planes[x];
+
+ if (oclAcceleration) {
+#ifdef CL_VERSION_1_1
+ const float fPlane[4] = { (float)plane.m_a, (float)plane.m_b, (float)plane.m_c, (float)plane.m_d };
+ cl_int error = clSetKernelArg(m_oclKernelComputePartialVolumes[threadID], 2, sizeof(float) * 4, fPlane);
+ if (error != CL_SUCCESS) {
+ if (params.m_logger) {
+ params.m_logger->Log("Couldn't kernel atguments \n");
+ }
+ SetCancel(true);
+ }
+
+ error = clEnqueueNDRangeKernel(m_oclQueue[threadID], m_oclKernelComputePartialVolumes[threadID],
+ 1, NULL, &globalSize, &m_oclWorkGroupSize, 0, NULL, NULL);
+ if (error != CL_SUCCESS) {
+ if (params.m_logger) {
+ params.m_logger->Log("Couldn't run kernel \n");
+ }
+ SetCancel(true);
+ }
+ int32_t nValues = (int32_t)nWorkGroups;
+ while (nValues > 1) {
+ error = clSetKernelArg(m_oclKernelComputeSum[threadID], 1, sizeof(int32_t), &nValues);
+ if (error != CL_SUCCESS) {
+ if (params.m_logger) {
+ params.m_logger->Log("Couldn't kernel atguments \n");
+ }
+ SetCancel(true);
+ }
+ size_t nWorkGroups = (nValues + m_oclWorkGroupSize - 1) / m_oclWorkGroupSize;
+ size_t globalSize = nWorkGroups * m_oclWorkGroupSize;
+ error = clEnqueueNDRangeKernel(m_oclQueue[threadID], m_oclKernelComputeSum[threadID],
+ 1, NULL, &globalSize, &m_oclWorkGroupSize, 0, NULL, NULL);
+ if (error != CL_SUCCESS) {
+ if (params.m_logger) {
+ params.m_logger->Log("Couldn't run kernel \n");
+ }
+ SetCancel(true);
+ }
+ nValues = (int32_t)nWorkGroups;
+ }
+#endif // CL_VERSION_1_1
+ }
+
+ Mesh& leftCH = chs[threadID];
+ Mesh& rightCH = chs[threadID + m_ompNumProcessors];
+ rightCH.ResizePoints(0);
+ leftCH.ResizePoints(0);
+ rightCH.ResizeTriangles(0);
+ leftCH.ResizeTriangles(0);
+
+// compute convex-hulls
+#ifdef TEST_APPROX_CH
+ double volumeLeftCH1;
+ double volumeRightCH1;
+#endif //TEST_APPROX_CH
+ if (params.m_convexhullApproximation) {
+ SArray<Vec3<double> >& leftCHPts = chPts[threadID];
+ SArray<Vec3<double> >& rightCHPts = chPts[threadID + m_ompNumProcessors];
+ rightCHPts.Resize(0);
+ leftCHPts.Resize(0);
+ onSurfacePSet->Intersect(plane, &rightCHPts, &leftCHPts, convexhullDownsampling * 32);
+ inputPSet->GetConvexHull().Clip(plane, rightCHPts, leftCHPts);
+ rightCH.ComputeConvexHull((double*)rightCHPts.Data(), rightCHPts.Size());
+ leftCH.ComputeConvexHull((double*)leftCHPts.Data(), leftCHPts.Size());
+#ifdef TEST_APPROX_CH
+ Mesh leftCH1;
+ Mesh rightCH1;
+ VoxelSet right;
+ VoxelSet left;
+ onSurfacePSet->Clip(plane, &right, &left);
+ right.ComputeConvexHull(rightCH1, convexhullDownsampling);
+ left.ComputeConvexHull(leftCH1, convexhullDownsampling);
+
+ volumeLeftCH1 = leftCH1.ComputeVolume();
+ volumeRightCH1 = rightCH1.ComputeVolume();
+#endif //TEST_APPROX_CH
+ }
+ else {
+ PrimitiveSet* const right = psets[threadID];
+ PrimitiveSet* const left = psets[threadID + m_ompNumProcessors];
+ onSurfacePSet->Clip(plane, right, left);
+ right->ComputeConvexHull(rightCH, convexhullDownsampling);
+ left->ComputeConvexHull(leftCH, convexhullDownsampling);
+ }
+ double volumeLeftCH = leftCH.ComputeVolume();
+ double volumeRightCH = rightCH.ComputeVolume();
+
+ // compute clipped volumes
+ double volumeLeft = 0.0;
+ double volumeRight = 0.0;
+ if (oclAcceleration) {
+#ifdef CL_VERSION_1_1
+ uint32_t volumes[4];
+ cl_int error = clEnqueueReadBuffer(m_oclQueue[threadID], partialVolumes[threadID], CL_TRUE,
+ 0, sizeof(uint32_t) * 4, volumes, 0, NULL, NULL);
+ size_t nPrimitivesRight = volumes[0] + volumes[1] + volumes[2] + volumes[3];
+ size_t nPrimitivesLeft = nPrimitives - nPrimitivesRight;
+ volumeRight = nPrimitivesRight * unitVolume;
+ volumeLeft = nPrimitivesLeft * unitVolume;
+ if (error != CL_SUCCESS) {
+ if (params.m_logger) {
+ params.m_logger->Log("Couldn't read buffer \n");
+ }
+ SetCancel(true);
+ }
+#endif // CL_VERSION_1_1
+ }
+ else {
+ inputPSet->ComputeClippedVolumes(plane, volumeRight, volumeLeft);
+ }
+ double concavityLeft = ComputeConcavity(volumeLeft, volumeLeftCH, m_volumeCH0);
+ double concavityRight = ComputeConcavity(volumeRight, volumeRightCH, m_volumeCH0);
+ double concavity = (concavityLeft + concavityRight);
+
+ // compute cost
+ double balance = alpha * fabs(volumeLeft - volumeRight) / m_volumeCH0;
+ double d = w * (preferredCuttingDirection[0] * plane.m_a + preferredCuttingDirection[1] * plane.m_b + preferredCuttingDirection[2] * plane.m_c);
+ double symmetry = beta * d;
+ double total = concavity + balance + symmetry;
+
+#if USE_THREAD == 1 && _OPENMP
+#pragma omp critical
+#endif
+ {
+ if (total < minTotal || (total == minTotal && x < iBest)) {
+ minConcavity = concavity;
+ minBalance = balance;
+ minSymmetry = symmetry;
+ bestPlane = plane;
+ minTotal = total;
+ iBest = x;
+ }
+ ++done;
+ if (!(done & 127)) // reduce update frequency
+ {
+ double progress = done * (progress1 - progress0) / nPlanes + progress0;
+ Update(m_stageProgress, progress, params);
+ }
+ }
+ }
+ }
+
+#ifdef DEBUG_TEMP
+ timerComputeCost.Toc();
+ printf_s("Cost[%i] = %f\n", nPlanes, timerComputeCost.GetElapsedTime());
+#endif // DEBUG_TEMP
+
+#ifdef CL_VERSION_1_1
+ if (oclAcceleration) {
+ clReleaseMemObject(voxels);
+ for (int32_t i = 0; i < m_ompNumProcessors; ++i) {
+ clReleaseMemObject(partialVolumes[i]);
+ }
+ delete[] partialVolumes;
+ }
+#endif // CL_VERSION_1_1
+
+ if (psets) {
+ for (int32_t i = 0; i < 2 * m_ompNumProcessors; ++i) {
+ delete psets[i];
+ }
+ delete[] psets;
+ }
+ delete onSurfacePSet;
+ delete[] chPts;
+ delete[] chs;
+ if (params.m_logger) {
+ sprintf(msg, "\n\t\t\t Best %04i T=%2.6f C=%2.6f B=%2.6f S=%2.6f (%1.1f, %1.1f, %1.1f, %3.3f)\n\n", iBest, minTotal, minConcavity, minBalance, minSymmetry, bestPlane.m_a, bestPlane.m_b, bestPlane.m_c, bestPlane.m_d);
+ params.m_logger->Log(msg);
+ }
+}
+void VHACD::ComputeACD(const Parameters& params)
+{
+ if (GetCancel()) {
+ return;
+ }
+ m_timer.Tic();
+
+ m_stage = "Approximate Convex Decomposition";
+ m_stageProgress = 0.0;
+ std::ostringstream msg;
+ if (params.m_logger) {
+ msg << "+ " << m_stage << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ SArray<PrimitiveSet*> parts;
+ SArray<PrimitiveSet*> inputParts;
+ SArray<PrimitiveSet*> temp;
+ inputParts.PushBack(m_pset);
+ m_pset = 0;
+ SArray<Plane> planes;
+ SArray<Plane> planesRef;
+ uint32_t sub = 0;
+ bool firstIteration = true;
+ m_volumeCH0 = 1.0;
+
+ // Compute the decomposition depth based on the number of convex hulls being requested..
+ uint32_t hullCount = 2;
+ uint32_t depth = 1;
+ while (params.m_maxConvexHulls > hullCount)
+ {
+ depth++;
+ hullCount *= 2;
+ }
+ // We must always increment the decomposition depth one higher than the maximum number of hulls requested.
+ // The reason for this is as follows.
+ // Say, for example, the user requests 32 convex hulls exactly. This would be a decomposition depth of 5.
+ // However, when we do that, we do *not* necessarily get 32 hulls as a result. This is because, during
+ // the recursive descent of the binary tree, one or more of the leaf nodes may have no concavity and
+ // will not be split. So, in this way, even with a decomposition depth of 5, you can produce fewer than
+ // 32 hulls. So, in this case, we would set the decomposition depth to 6 (producing up to as high as 64 convex hulls).
+ // Then, the merge step which combines over-described hulls down to the user requested amount, we will end up
+ // getting exactly 32 convex hulls as a result.
+ // We could just allow the artist to directly control the decomposition depth directly, but this would be a bit
+ // too complex and the preference is simply to let them specify how many hulls they want and derive the solution
+ // from that.
+ depth++;
+
+
+ while (sub++ < depth && inputParts.Size() > 0 && !m_cancel) {
+ msg.str("");
+ msg << "Subdivision level " << sub;
+ m_operation = msg.str();
+
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t Subdivision level " << sub << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ double maxConcavity = 0.0;
+ const size_t nInputParts = inputParts.Size();
+ Update(m_stageProgress, 0.0, params);
+ for (size_t p = 0; p < nInputParts && !m_cancel; ++p) {
+ const double progress0 = p * 100.0 / nInputParts;
+ const double progress1 = (p + 0.75) * 100.0 / nInputParts;
+ const double progress2 = (p + 1.00) * 100.0 / nInputParts;
+
+ Update(m_stageProgress, progress0, params);
+
+ PrimitiveSet* pset = inputParts[p];
+ inputParts[p] = 0;
+ double volume = pset->ComputeVolume();
+ pset->ComputeBB();
+ pset->ComputePrincipalAxes();
+ if (params.m_pca) {
+ pset->AlignToPrincipalAxes();
+ }
+
+ pset->ComputeConvexHull(pset->GetConvexHull());
+ double volumeCH = fabs(pset->GetConvexHull().ComputeVolume());
+ if (firstIteration) {
+ m_volumeCH0 = volumeCH;
+ }
+
+ double concavity = ComputeConcavity(volume, volumeCH, m_volumeCH0);
+ double error = 1.01 * pset->ComputeMaxVolumeError() / m_volumeCH0;
+
+ if (firstIteration) {
+ firstIteration = false;
+ }
+
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t -> Part[" << p
+ << "] C = " << concavity
+ << ", E = " << error
+ << ", VS = " << pset->GetNPrimitivesOnSurf()
+ << ", VI = " << pset->GetNPrimitivesInsideSurf()
+ << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ if (concavity > params.m_concavity && concavity > error) {
+ Vec3<double> preferredCuttingDirection;
+ double w = ComputePreferredCuttingDirection(pset, preferredCuttingDirection);
+ planes.Resize(0);
+ if (params.m_mode == 0) {
+ VoxelSet* vset = (VoxelSet*)pset;
+ ComputeAxesAlignedClippingPlanes(*vset, params.m_planeDownsampling, planes);
+ }
+ else {
+ TetrahedronSet* tset = (TetrahedronSet*)pset;
+ ComputeAxesAlignedClippingPlanes(*tset, params.m_planeDownsampling, planes);
+ }
+
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t\t [Regular sampling] Number of clipping planes " << planes.Size() << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ Plane bestPlane;
+ double minConcavity = MAX_DOUBLE;
+ ComputeBestClippingPlane(pset,
+ volume,
+ planes,
+ preferredCuttingDirection,
+ w,
+ concavity * params.m_alpha,
+ concavity * params.m_beta,
+ params.m_convexhullDownsampling,
+ progress0,
+ progress1,
+ bestPlane,
+ minConcavity,
+ params);
+ if (!m_cancel && (params.m_planeDownsampling > 1 || params.m_convexhullDownsampling > 1)) {
+ planesRef.Resize(0);
+
+ if (params.m_mode == 0) {
+ VoxelSet* vset = (VoxelSet*)pset;
+ RefineAxesAlignedClippingPlanes(*vset, bestPlane, params.m_planeDownsampling, planesRef);
+ }
+ else {
+ TetrahedronSet* tset = (TetrahedronSet*)pset;
+ RefineAxesAlignedClippingPlanes(*tset, bestPlane, params.m_planeDownsampling, planesRef);
+ }
+
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t\t [Refining] Number of clipping planes " << planesRef.Size() << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+ ComputeBestClippingPlane(pset,
+ volume,
+ planesRef,
+ preferredCuttingDirection,
+ w,
+ concavity * params.m_alpha,
+ concavity * params.m_beta,
+ 1, // convexhullDownsampling = 1
+ progress1,
+ progress2,
+ bestPlane,
+ minConcavity,
+ params);
+ }
+ if (GetCancel()) {
+ delete pset; // clean up
+ break;
+ }
+ else {
+ if (maxConcavity < minConcavity) {
+ maxConcavity = minConcavity;
+ }
+ PrimitiveSet* bestLeft = pset->Create();
+ PrimitiveSet* bestRight = pset->Create();
+ temp.PushBack(bestLeft);
+ temp.PushBack(bestRight);
+ pset->Clip(bestPlane, bestRight, bestLeft);
+ if (params.m_pca) {
+ bestRight->RevertAlignToPrincipalAxes();
+ bestLeft->RevertAlignToPrincipalAxes();
+ }
+ delete pset;
+ }
+ }
+ else {
+ if (params.m_pca) {
+ pset->RevertAlignToPrincipalAxes();
+ }
+ parts.PushBack(pset);
+ }
+ }
+
+ Update(95.0 * (1.0 - maxConcavity) / (1.0 - params.m_concavity), 100.0, params);
+ if (GetCancel()) {
+ const size_t nTempParts = temp.Size();
+ for (size_t p = 0; p < nTempParts; ++p) {
+ delete temp[p];
+ }
+ temp.Resize(0);
+ }
+ else {
+ inputParts = temp;
+ temp.Resize(0);
+ }
+ }
+ const size_t nInputParts = inputParts.Size();
+ for (size_t p = 0; p < nInputParts; ++p) {
+ parts.PushBack(inputParts[p]);
+ }
+
+ if (GetCancel()) {
+ const size_t nParts = parts.Size();
+ for (size_t p = 0; p < nParts; ++p) {
+ delete parts[p];
+ }
+ return;
+ }
+
+ m_overallProgress = 90.0;
+ Update(m_stageProgress, 100.0, params);
+
+ msg.str("");
+ msg << "Generate convex-hulls";
+ m_operation = msg.str();
+ size_t nConvexHulls = parts.Size();
+ if (params.m_logger) {
+ msg.str("");
+ msg << "+ Generate " << nConvexHulls << " convex-hulls " << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ Update(m_stageProgress, 0.0, params);
+ m_convexHulls.Resize(0);
+ for (size_t p = 0; p < nConvexHulls && !m_cancel; ++p) {
+ Update(m_stageProgress, p * 100.0 / nConvexHulls, params);
+ m_convexHulls.PushBack(new Mesh);
+ parts[p]->ComputeConvexHull(*m_convexHulls[p]);
+ size_t nv = m_convexHulls[p]->GetNPoints();
+ double x, y, z;
+ for (size_t i = 0; i < nv; ++i) {
+ Vec3<double>& pt = m_convexHulls[p]->GetPoint(i);
+ x = pt[0];
+ y = pt[1];
+ z = pt[2];
+ pt[0] = m_rot[0][0] * x + m_rot[0][1] * y + m_rot[0][2] * z + m_barycenter[0];
+ pt[1] = m_rot[1][0] * x + m_rot[1][1] * y + m_rot[1][2] * z + m_barycenter[1];
+ pt[2] = m_rot[2][0] * x + m_rot[2][1] * y + m_rot[2][2] * z + m_barycenter[2];
+ }
+ }
+
+ const size_t nParts = parts.Size();
+ for (size_t p = 0; p < nParts; ++p) {
+ delete parts[p];
+ parts[p] = 0;
+ }
+ parts.Resize(0);
+
+ if (GetCancel()) {
+ const size_t nConvexHulls = m_convexHulls.Size();
+ for (size_t p = 0; p < nConvexHulls; ++p) {
+ delete m_convexHulls[p];
+ }
+ m_convexHulls.Clear();
+ return;
+ }
+
+ m_overallProgress = 95.0;
+ Update(100.0, 100.0, params);
+ m_timer.Toc();
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t time " << m_timer.GetElapsedTime() / 1000.0 << "s" << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+}
+void AddPoints(const Mesh* const mesh, SArray<Vec3<double> >& pts)
+{
+ const int32_t n = (int32_t)mesh->GetNPoints();
+ for (int32_t i = 0; i < n; ++i) {
+ pts.PushBack(mesh->GetPoint(i));
+ }
+}
+void ComputeConvexHull(const Mesh* const ch1, const Mesh* const ch2, SArray<Vec3<double> >& pts, Mesh* const combinedCH)
+{
+ pts.Resize(0);
+ AddPoints(ch1, pts);
+ AddPoints(ch2, pts);
+
+ btConvexHullComputer ch;
+ ch.compute((double*)pts.Data(), 3 * sizeof(double), (int32_t)pts.Size(), -1.0, -1.0);
+ combinedCH->ResizePoints(0);
+ combinedCH->ResizeTriangles(0);
+ for (int32_t v = 0; v < ch.vertices.size(); v++) {
+ combinedCH->AddPoint(Vec3<double>(ch.vertices[v].getX(), ch.vertices[v].getY(), ch.vertices[v].getZ()));
+ }
+ const int32_t nt = ch.faces.size();
+ for (int32_t t = 0; t < nt; ++t) {
+ const btConvexHullComputer::Edge* sourceEdge = &(ch.edges[ch.faces[t]]);
+ int32_t a = sourceEdge->getSourceVertex();
+ int32_t b = sourceEdge->getTargetVertex();
+ const btConvexHullComputer::Edge* edge = sourceEdge->getNextEdgeOfFace();
+ int32_t c = edge->getTargetVertex();
+ while (c != a) {
+ combinedCH->AddTriangle(Vec3<int32_t>(a, b, c));
+ edge = edge->getNextEdgeOfFace();
+ b = c;
+ c = edge->getTargetVertex();
+ }
+ }
+}
+void VHACD::MergeConvexHulls(const Parameters& params)
+{
+ if (GetCancel()) {
+ return;
+ }
+ m_timer.Tic();
+
+ m_stage = "Merge Convex Hulls";
+
+ std::ostringstream msg;
+ if (params.m_logger) {
+ msg << "+ " << m_stage << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ // Get the current number of convex hulls
+ size_t nConvexHulls = m_convexHulls.Size();
+ // Iteration counter
+ int32_t iteration = 0;
+ // While we have more than at least one convex hull and the user has not asked us to cancel the operation
+ if (nConvexHulls > 1 && !m_cancel)
+ {
+ // Get the gamma error threshold for when to exit
+ SArray<Vec3<double> > pts;
+ Mesh combinedCH;
+
+ // Populate the cost matrix
+ size_t idx = 0;
+ SArray<float> costMatrix;
+ costMatrix.Resize(((nConvexHulls * nConvexHulls) - nConvexHulls) >> 1);
+ for (size_t p1 = 1; p1 < nConvexHulls; ++p1)
+ {
+ const float volume1 = m_convexHulls[p1]->ComputeVolume();
+ for (size_t p2 = 0; p2 < p1; ++p2)
+ {
+ ComputeConvexHull(m_convexHulls[p1], m_convexHulls[p2], pts, &combinedCH);
+ costMatrix[idx++] = ComputeConcavity(volume1 + m_convexHulls[p2]->ComputeVolume(), combinedCH.ComputeVolume(), m_volumeCH0);
+ }
+ }
+
+ // Until we cant merge below the maximum cost
+ size_t costSize = m_convexHulls.Size();
+ while (!m_cancel)
+ {
+ msg.str("");
+ msg << "Iteration " << iteration++;
+ m_operation = msg.str();
+
+ // Search for lowest cost
+ float bestCost = (std::numeric_limits<float>::max)();
+ const size_t addr = FindMinimumElement(costMatrix.Data(), &bestCost, 0, costMatrix.Size());
+ if ( (costSize-1) < params.m_maxConvexHulls)
+ {
+ break;
+ }
+ const size_t addrI = (static_cast<int32_t>(sqrt(1 + (8 * addr))) - 1) >> 1;
+ const size_t p1 = addrI + 1;
+ const size_t p2 = addr - ((addrI * (addrI + 1)) >> 1);
+ assert(p1 >= 0);
+ assert(p2 >= 0);
+ assert(p1 < costSize);
+ assert(p2 < costSize);
+
+ if (params.m_logger)
+ {
+ msg.str("");
+ msg << "\t\t Merging (" << p1 << ", " << p2 << ") " << bestCost << std::endl
+ << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ // Make the lowest cost row and column into a new hull
+ Mesh* cch = new Mesh;
+ ComputeConvexHull(m_convexHulls[p1], m_convexHulls[p2], pts, cch);
+ delete m_convexHulls[p2];
+ m_convexHulls[p2] = cch;
+
+ delete m_convexHulls[p1];
+ std::swap(m_convexHulls[p1], m_convexHulls[m_convexHulls.Size() - 1]);
+ m_convexHulls.PopBack();
+
+ costSize = costSize - 1;
+
+ // Calculate costs versus the new hull
+ size_t rowIdx = ((p2 - 1) * p2) >> 1;
+ const float volume1 = m_convexHulls[p2]->ComputeVolume();
+ for (size_t i = 0; (i < p2) && (!m_cancel); ++i)
+ {
+ ComputeConvexHull(m_convexHulls[p2], m_convexHulls[i], pts, &combinedCH);
+ costMatrix[rowIdx++] = ComputeConcavity(volume1 + m_convexHulls[i]->ComputeVolume(), combinedCH.ComputeVolume(), m_volumeCH0);
+ }
+
+ rowIdx += p2;
+ for (size_t i = p2 + 1; (i < costSize) && (!m_cancel); ++i)
+ {
+ ComputeConvexHull(m_convexHulls[p2], m_convexHulls[i], pts, &combinedCH);
+ costMatrix[rowIdx] = ComputeConcavity(volume1 + m_convexHulls[i]->ComputeVolume(), combinedCH.ComputeVolume(), m_volumeCH0);
+ rowIdx += i;
+ assert(rowIdx >= 0);
+ }
+
+ // Move the top column in to replace its space
+ const size_t erase_idx = ((costSize - 1) * costSize) >> 1;
+ if (p1 < costSize) {
+ rowIdx = (addrI * p1) >> 1;
+ size_t top_row = erase_idx;
+ for (size_t i = 0; i < p1; ++i) {
+ if (i != p2) {
+ costMatrix[rowIdx] = costMatrix[top_row];
+ }
+ ++rowIdx;
+ ++top_row;
+ }
+
+ ++top_row;
+ rowIdx += p1;
+ for (size_t i = p1 + 1; i < (costSize + 1); ++i) {
+ costMatrix[rowIdx] = costMatrix[top_row++];
+ rowIdx += i;
+ assert(rowIdx >= 0);
+ }
+ }
+ costMatrix.Resize(erase_idx);
+ }
+ }
+ m_overallProgress = 99.0;
+ Update(100.0, 100.0, params);
+ m_timer.Toc();
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t time " << m_timer.GetElapsedTime() / 1000.0 << "s" << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+}
+void VHACD::SimplifyConvexHull(Mesh* const ch, const size_t nvertices, const double minVolume)
+{
+ if (nvertices <= 4) {
+ return;
+ }
+ ICHull icHull;
+ if (mRaycastMesh)
+ {
+ // We project these points onto the original source mesh to increase precision
+ // The voxelization process drops floating point precision so returned data points are not exactly lying on the
+ // surface of the original source mesh.
+ // The first step is we need to compute the bounding box of the mesh we are trying to build a convex hull for.
+ // From this bounding box, we compute the length of the diagonal to get a relative size and center for point projection
+ uint32_t nPoints = ch->GetNPoints();
+ Vec3<double> *inputPoints = ch->GetPointsBuffer();
+ Vec3<double> bmin(inputPoints[0]);
+ Vec3<double> bmax(inputPoints[1]);
+ for (uint32_t i = 1; i < nPoints; i++)
+ {
+ const Vec3<double> &p = inputPoints[i];
+ p.UpdateMinMax(bmin, bmax);
+ }
+ Vec3<double> center;
+ double diagonalLength = center.GetCenter(bmin, bmax); // Get the center of the bounding box
+ // This is the error threshold for determining if we should use the raycast result data point vs. the voxelized result.
+ double pointDistanceThreshold = diagonalLength * 0.05;
+ // If a new point is within 1/100th the diagonal length of the bounding volume we do not add it. To do so would create a
+ // thin sliver in the resulting convex hull
+ double snapDistanceThreshold = diagonalLength * 0.01;
+ double snapDistanceThresholdSquared = snapDistanceThreshold*snapDistanceThreshold;
+
+ // Allocate buffer for projected vertices
+ Vec3<double> *outputPoints = new Vec3<double>[nPoints];
+ uint32_t outCount = 0;
+ for (uint32_t i = 0; i < nPoints; i++)
+ {
+ Vec3<double> &inputPoint = inputPoints[i];
+ Vec3<double> &outputPoint = outputPoints[outCount];
+ // Compute the direction vector from the center of this mesh to the vertex
+ Vec3<double> dir = inputPoint - center;
+ // Normalize the direction vector.
+ dir.Normalize();
+ // Multiply times the diagonal length of the mesh
+ dir *= diagonalLength;
+ // Add the center back in again to get the destination point
+ dir += center;
+ // By default the output point is equal to the input point
+ outputPoint = inputPoint;
+ double pointDistance;
+ if (mRaycastMesh->raycast(center.GetData(), dir.GetData(), inputPoint.GetData(), outputPoint.GetData(),&pointDistance) )
+ {
+ // If the nearest intersection point is too far away, we keep the original source data point.
+ // Not all points lie directly on the original mesh surface
+ if (pointDistance > pointDistanceThreshold)
+ {
+ outputPoint = inputPoint;
+ }
+ }
+ // Ok, before we add this point, we do not want to create points which are extremely close to each other.
+ // This will result in tiny sliver triangles which are really bad for collision detection.
+ bool foundNearbyPoint = false;
+ for (uint32_t j = 0; j < outCount; j++)
+ {
+ // If this new point is extremely close to an existing point, we do not add it!
+ double squaredDistance = outputPoints[j].GetDistanceSquared(outputPoint);
+ if (squaredDistance < snapDistanceThresholdSquared )
+ {
+ foundNearbyPoint = true;
+ break;
+ }
+ }
+ if (!foundNearbyPoint)
+ {
+ outCount++;
+ }
+ }
+ icHull.AddPoints(outputPoints, outCount);
+ delete[]outputPoints;
+ }
+ else
+ {
+ icHull.AddPoints(ch->GetPointsBuffer(), ch->GetNPoints());
+ }
+ icHull.Process((uint32_t)nvertices, minVolume);
+ TMMesh& mesh = icHull.GetMesh();
+ const size_t nT = mesh.GetNTriangles();
+ const size_t nV = mesh.GetNVertices();
+ ch->ResizePoints(nV);
+ ch->ResizeTriangles(nT);
+ mesh.GetIFS(ch->GetPointsBuffer(), ch->GetTrianglesBuffer());
+}
+void VHACD::SimplifyConvexHulls(const Parameters& params)
+{
+ if (m_cancel || params.m_maxNumVerticesPerCH < 4) {
+ return;
+ }
+ m_timer.Tic();
+
+ m_stage = "Simplify convex-hulls";
+ m_operation = "Simplify convex-hulls";
+
+ std::ostringstream msg;
+ const size_t nConvexHulls = m_convexHulls.Size();
+ if (params.m_logger) {
+ msg << "+ Simplify " << nConvexHulls << " convex-hulls " << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+
+ Update(0.0, 0.0, params);
+ for (size_t i = 0; i < nConvexHulls && !m_cancel; ++i) {
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t\t Simplify CH[" << std::setfill('0') << std::setw(5) << i << "] " << m_convexHulls[i]->GetNPoints() << " V, " << m_convexHulls[i]->GetNTriangles() << " T" << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+ SimplifyConvexHull(m_convexHulls[i], params.m_maxNumVerticesPerCH, m_volumeCH0 * params.m_minVolumePerCH);
+ }
+
+ m_overallProgress = 100.0;
+ Update(100.0, 100.0, params);
+ m_timer.Toc();
+ if (params.m_logger) {
+ msg.str("");
+ msg << "\t time " << m_timer.GetElapsedTime() / 1000.0 << "s" << std::endl;
+ params.m_logger->Log(msg.str().c_str());
+ }
+}
+
+bool VHACD::ComputeCenterOfMass(double centerOfMass[3]) const
+{
+ bool ret = false;
+
+ centerOfMass[0] = 0;
+ centerOfMass[1] = 0;
+ centerOfMass[2] = 0;
+ // Get number of convex hulls in the result
+ uint32_t hullCount = GetNConvexHulls();
+ if (hullCount) // if we have results
+ {
+ ret = true;
+ double totalVolume = 0;
+ // Initialize the center of mass to zero
+ centerOfMass[0] = 0;
+ centerOfMass[1] = 0;
+ centerOfMass[2] = 0;
+ // Compute the total volume of all convex hulls
+ for (uint32_t i = 0; i < hullCount; i++)
+ {
+ ConvexHull ch;
+ GetConvexHull(i, ch);
+ totalVolume += ch.m_volume;
+ }
+ // compute the reciprocal of the total volume
+ double recipVolume = 1.0 / totalVolume;
+ // Add in the weighted by volume average of the center point of each convex hull
+ for (uint32_t i = 0; i < hullCount; i++)
+ {
+ ConvexHull ch;
+ GetConvexHull(i, ch);
+ double ratio = ch.m_volume*recipVolume;
+ centerOfMass[0] += ch.m_center[0] * ratio;
+ centerOfMass[1] += ch.m_center[1] * ratio;
+ centerOfMass[2] += ch.m_center[2] * ratio;
+ }
+ }
+ return ret;
+}
+
+} // end of VHACD namespace
diff --git a/thirdparty/vhacd/src/btAlignedAllocator.cpp b/thirdparty/vhacd/src/btAlignedAllocator.cpp
new file mode 100644
index 0000000000..8dee31e7e3
--- /dev/null
+++ b/thirdparty/vhacd/src/btAlignedAllocator.cpp
@@ -0,0 +1,192 @@
+/*
+Bullet Continuous Collision Detection and Physics Library
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
+
+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 "btAlignedAllocator.h"
+
+// -- GODOT start --
+namespace VHACD {
+// -- GODOT end --
+
+#ifdef _MSC_VER
+#pragma warning(disable:4311 4302)
+#endif
+
+int32_t gNumAlignedAllocs = 0;
+int32_t gNumAlignedFree = 0;
+int32_t gTotalBytesAlignedAllocs = 0; //detect memory leaks
+
+static void* btAllocDefault(size_t size)
+{
+ return malloc(size);
+}
+
+static void btFreeDefault(void* ptr)
+{
+ free(ptr);
+}
+
+static btAllocFunc* sAllocFunc = btAllocDefault;
+static btFreeFunc* sFreeFunc = btFreeDefault;
+
+#if defined(BT_HAS_ALIGNED_ALLOCATOR)
+#include <malloc.h>
+static void* btAlignedAllocDefault(size_t size, int32_t alignment)
+{
+ return _aligned_malloc(size, (size_t)alignment);
+}
+
+static void btAlignedFreeDefault(void* ptr)
+{
+ _aligned_free(ptr);
+}
+#elif defined(__CELLOS_LV2__)
+#include <stdlib.h>
+
+static inline void* btAlignedAllocDefault(size_t size, int32_t alignment)
+{
+ return memalign(alignment, size);
+}
+
+static inline void btAlignedFreeDefault(void* ptr)
+{
+ free(ptr);
+}
+#else
+static inline void* btAlignedAllocDefault(size_t size, int32_t alignment)
+{
+ void* ret;
+ char* real;
+ unsigned long offset;
+
+ real = (char*)sAllocFunc(size + sizeof(void*) + (alignment - 1));
+ if (real) {
+ // -- GODOT start --
+ // Synced with Bullet 2.88 to fix GH-27926
+ //offset = (alignment - (unsigned long)(real + sizeof(void*))) & (alignment - 1);
+ //ret = (void*)((real + sizeof(void*)) + offset);
+ ret = btAlignPointer(real + sizeof(void *), alignment);
+ // -- GODOT end --
+ *((void**)(ret)-1) = (void*)(real);
+ }
+ else {
+ ret = (void*)(real);
+ }
+ return (ret);
+}
+
+static inline void btAlignedFreeDefault(void* ptr)
+{
+ void* real;
+
+ if (ptr) {
+ real = *((void**)(ptr)-1);
+ sFreeFunc(real);
+ }
+}
+#endif
+
+static btAlignedAllocFunc* sAlignedAllocFunc = btAlignedAllocDefault;
+static btAlignedFreeFunc* sAlignedFreeFunc = btAlignedFreeDefault;
+
+void btAlignedAllocSetCustomAligned(btAlignedAllocFunc* allocFunc, btAlignedFreeFunc* freeFunc)
+{
+ sAlignedAllocFunc = allocFunc ? allocFunc : btAlignedAllocDefault;
+ sAlignedFreeFunc = freeFunc ? freeFunc : btAlignedFreeDefault;
+}
+
+void btAlignedAllocSetCustom(btAllocFunc* allocFunc, btFreeFunc* freeFunc)
+{
+ sAllocFunc = allocFunc ? allocFunc : btAllocDefault;
+ sFreeFunc = freeFunc ? freeFunc : btFreeDefault;
+}
+
+#ifdef BT_DEBUG_MEMORY_ALLOCATIONS
+//this generic allocator provides the total allocated number of bytes
+#include <stdio.h>
+
+void* btAlignedAllocInternal(size_t size, int32_t alignment, int32_t line, char* filename)
+{
+ void* ret;
+ char* real;
+ unsigned long offset;
+
+ gTotalBytesAlignedAllocs += size;
+ gNumAlignedAllocs++;
+
+ real = (char*)sAllocFunc(size + 2 * sizeof(void*) + (alignment - 1));
+ if (real) {
+ offset = (alignment - (unsigned long)(real + 2 * sizeof(void*))) & (alignment - 1);
+ ret = (void*)((real + 2 * sizeof(void*)) + offset);
+ *((void**)(ret)-1) = (void*)(real);
+ *((int32_t*)(ret)-2) = size;
+ }
+ else {
+ ret = (void*)(real); //??
+ }
+
+ printf("allocation#%d at address %x, from %s,line %d, size %d\n", gNumAlignedAllocs, real, filename, line, size);
+
+ int32_t* ptr = (int32_t*)ret;
+ *ptr = 12;
+ return (ret);
+}
+
+void btAlignedFreeInternal(void* ptr, int32_t line, char* filename)
+{
+
+ void* real;
+ gNumAlignedFree++;
+
+ if (ptr) {
+ real = *((void**)(ptr)-1);
+ int32_t size = *((int32_t*)(ptr)-2);
+ gTotalBytesAlignedAllocs -= size;
+
+ printf("free #%d at address %x, from %s,line %d, size %d\n", gNumAlignedFree, real, filename, line, size);
+
+ sFreeFunc(real);
+ }
+ else {
+ printf("NULL ptr\n");
+ }
+}
+
+#else //BT_DEBUG_MEMORY_ALLOCATIONS
+
+void* btAlignedAllocInternal(size_t size, int32_t alignment)
+{
+ gNumAlignedAllocs++;
+ void* ptr;
+ ptr = sAlignedAllocFunc(size, alignment);
+ // printf("btAlignedAllocInternal %d, %x\n",size,ptr);
+ return ptr;
+}
+
+void btAlignedFreeInternal(void* ptr)
+{
+ if (!ptr) {
+ return;
+ }
+
+ gNumAlignedFree++;
+ // printf("btAlignedFreeInternal %x\n",ptr);
+ sAlignedFreeFunc(ptr);
+}
+
+// -- GODOT start --
+}; // namespace VHACD
+// -- GODOT end --
+
+#endif //BT_DEBUG_MEMORY_ALLOCATIONS
diff --git a/thirdparty/vhacd/src/btConvexHullComputer.cpp b/thirdparty/vhacd/src/btConvexHullComputer.cpp
new file mode 100644
index 0000000000..8ab34af2ab
--- /dev/null
+++ b/thirdparty/vhacd/src/btConvexHullComputer.cpp
@@ -0,0 +1,2487 @@
+/*
+Copyright (c) 2011 Ole Kniemeyer, MAXON, www.maxon.net
+
+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 <string.h>
+
+#include "btAlignedObjectArray.h"
+#include "btConvexHullComputer.h"
+#include "btMinMax.h"
+#include "btVector3.h"
+
+#ifdef __GNUC__
+#include <stdint.h>
+#elif defined(_MSC_VER)
+typedef __int32 int32_t;
+typedef __int64 int64_t;
+typedef unsigned __int32 uint32_t;
+typedef unsigned __int64 uint64_t;
+#else
+typedef int32_t int32_t;
+typedef long long int32_t int64_t;
+typedef uint32_t uint32_t;
+typedef unsigned long long int32_t uint64_t;
+#endif
+
+#ifdef _MSC_VER
+#pragma warning(disable:4458)
+#endif
+
+//The definition of USE_X86_64_ASM is moved into the build system. You can enable it manually by commenting out the following lines
+//#if (defined(__GNUC__) && defined(__x86_64__) && !defined(__ICL)) // || (defined(__ICL) && defined(_M_X64)) bug in Intel compiler, disable inline assembly
+// #define USE_X86_64_ASM
+//#endif
+
+//#define DEBUG_CONVEX_HULL
+//#define SHOW_ITERATIONS
+
+#if defined(DEBUG_CONVEX_HULL) || defined(SHOW_ITERATIONS)
+#include <stdio.h>
+#endif
+
+// -- GODOT start --
+namespace VHACD {
+// -- GODOT end --
+
+// Convex hull implementation based on Preparata and Hong
+// Ole Kniemeyer, MAXON Computer GmbH
+class btConvexHullInternal {
+public:
+ class Point64 {
+ public:
+ int64_t x;
+ int64_t y;
+ int64_t z;
+
+ Point64(int64_t x, int64_t y, int64_t z)
+ : x(x)
+ , y(y)
+ , z(z)
+ {
+ }
+
+ bool isZero()
+ {
+ return (x == 0) && (y == 0) && (z == 0);
+ }
+
+ int64_t dot(const Point64& b) const
+ {
+ return x * b.x + y * b.y + z * b.z;
+ }
+ };
+
+ class Point32 {
+ public:
+ int32_t x;
+ int32_t y;
+ int32_t z;
+ int32_t index;
+
+ Point32()
+ {
+ }
+
+ Point32(int32_t x, int32_t y, int32_t z)
+ : x(x)
+ , y(y)
+ , z(z)
+ , index(-1)
+ {
+ }
+
+ bool operator==(const Point32& b) const
+ {
+ return (x == b.x) && (y == b.y) && (z == b.z);
+ }
+
+ bool operator!=(const Point32& b) const
+ {
+ return (x != b.x) || (y != b.y) || (z != b.z);
+ }
+
+ bool isZero()
+ {
+ return (x == 0) && (y == 0) && (z == 0);
+ }
+
+ Point64 cross(const Point32& b) const
+ {
+ return Point64(y * b.z - z * b.y, z * b.x - x * b.z, x * b.y - y * b.x);
+ }
+
+ Point64 cross(const Point64& b) const
+ {
+ return Point64(y * b.z - z * b.y, z * b.x - x * b.z, x * b.y - y * b.x);
+ }
+
+ int64_t dot(const Point32& b) const
+ {
+ return x * b.x + y * b.y + z * b.z;
+ }
+
+ int64_t dot(const Point64& b) const
+ {
+ return x * b.x + y * b.y + z * b.z;
+ }
+
+ Point32 operator+(const Point32& b) const
+ {
+ return Point32(x + b.x, y + b.y, z + b.z);
+ }
+
+ Point32 operator-(const Point32& b) const
+ {
+ return Point32(x - b.x, y - b.y, z - b.z);
+ }
+ };
+
+ class Int128 {
+ public:
+ uint64_t low;
+ uint64_t high;
+
+ Int128()
+ {
+ }
+
+ Int128(uint64_t low, uint64_t high)
+ : low(low)
+ , high(high)
+ {
+ }
+
+ Int128(uint64_t low)
+ : low(low)
+ , high(0)
+ {
+ }
+
+ Int128(int64_t value)
+ : low(value)
+ , high((value >= 0) ? 0 : (uint64_t)-1LL)
+ {
+ }
+
+ static Int128 mul(int64_t a, int64_t b);
+
+ static Int128 mul(uint64_t a, uint64_t b);
+
+ Int128 operator-() const
+ {
+ return Int128((uint64_t) - (int64_t)low, ~high + (low == 0));
+ }
+
+ Int128 operator+(const Int128& b) const
+ {
+#ifdef USE_X86_64_ASM
+ Int128 result;
+ __asm__("addq %[bl], %[rl]\n\t"
+ "adcq %[bh], %[rh]\n\t"
+ : [rl] "=r"(result.low), [rh] "=r"(result.high)
+ : "0"(low), "1"(high), [bl] "g"(b.low), [bh] "g"(b.high)
+ : "cc");
+ return result;
+#else
+ uint64_t lo = low + b.low;
+ return Int128(lo, high + b.high + (lo < low));
+#endif
+ }
+
+ Int128 operator-(const Int128& b) const
+ {
+#ifdef USE_X86_64_ASM
+ Int128 result;
+ __asm__("subq %[bl], %[rl]\n\t"
+ "sbbq %[bh], %[rh]\n\t"
+ : [rl] "=r"(result.low), [rh] "=r"(result.high)
+ : "0"(low), "1"(high), [bl] "g"(b.low), [bh] "g"(b.high)
+ : "cc");
+ return result;
+#else
+ return *this + -b;
+#endif
+ }
+
+ Int128& operator+=(const Int128& b)
+ {
+#ifdef USE_X86_64_ASM
+ __asm__("addq %[bl], %[rl]\n\t"
+ "adcq %[bh], %[rh]\n\t"
+ : [rl] "=r"(low), [rh] "=r"(high)
+ : "0"(low), "1"(high), [bl] "g"(b.low), [bh] "g"(b.high)
+ : "cc");
+#else
+ uint64_t lo = low + b.low;
+ if (lo < low) {
+ ++high;
+ }
+ low = lo;
+ high += b.high;
+#endif
+ return *this;
+ }
+
+ Int128& operator++()
+ {
+ if (++low == 0) {
+ ++high;
+ }
+ return *this;
+ }
+
+ Int128 operator*(int64_t b) const;
+
+ btScalar toScalar() const
+ {
+ return ((int64_t)high >= 0) ? btScalar(high) * (btScalar(0x100000000LL) * btScalar(0x100000000LL)) + btScalar(low)
+ : -(-*this).toScalar();
+ }
+
+ int32_t getSign() const
+ {
+ return ((int64_t)high < 0) ? -1 : (high || low) ? 1 : 0;
+ }
+
+ bool operator<(const Int128& b) const
+ {
+ return (high < b.high) || ((high == b.high) && (low < b.low));
+ }
+
+ int32_t ucmp(const Int128& b) const
+ {
+ if (high < b.high) {
+ return -1;
+ }
+ if (high > b.high) {
+ return 1;
+ }
+ if (low < b.low) {
+ return -1;
+ }
+ if (low > b.low) {
+ return 1;
+ }
+ return 0;
+ }
+ };
+
+ class Rational64 {
+ private:
+ uint64_t m_numerator;
+ uint64_t m_denominator;
+ int32_t sign;
+
+ public:
+ Rational64(int64_t numerator, int64_t denominator)
+ {
+ if (numerator > 0) {
+ sign = 1;
+ m_numerator = (uint64_t)numerator;
+ }
+ else if (numerator < 0) {
+ sign = -1;
+ m_numerator = (uint64_t)-numerator;
+ }
+ else {
+ sign = 0;
+ m_numerator = 0;
+ }
+ if (denominator > 0) {
+ m_denominator = (uint64_t)denominator;
+ }
+ else if (denominator < 0) {
+ sign = -sign;
+ m_denominator = (uint64_t)-denominator;
+ }
+ else {
+ m_denominator = 0;
+ }
+ }
+
+ bool isNegativeInfinity() const
+ {
+ return (sign < 0) && (m_denominator == 0);
+ }
+
+ bool isNaN() const
+ {
+ return (sign == 0) && (m_denominator == 0);
+ }
+
+ int32_t compare(const Rational64& b) const;
+
+ btScalar toScalar() const
+ {
+ return sign * ((m_denominator == 0) ? SIMD_INFINITY : (btScalar)m_numerator / m_denominator);
+ }
+ };
+
+ class Rational128 {
+ private:
+ Int128 numerator;
+ Int128 denominator;
+ int32_t sign;
+ bool isInt64;
+
+ public:
+ Rational128(int64_t value)
+ {
+ if (value > 0) {
+ sign = 1;
+ this->numerator = value;
+ }
+ else if (value < 0) {
+ sign = -1;
+ this->numerator = -value;
+ }
+ else {
+ sign = 0;
+ this->numerator = (uint64_t)0;
+ }
+ this->denominator = (uint64_t)1;
+ isInt64 = true;
+ }
+
+ Rational128(const Int128& numerator, const Int128& denominator)
+ {
+ sign = numerator.getSign();
+ if (sign >= 0) {
+ this->numerator = numerator;
+ }
+ else {
+ this->numerator = -numerator;
+ }
+ int32_t dsign = denominator.getSign();
+ if (dsign >= 0) {
+ this->denominator = denominator;
+ }
+ else {
+ sign = -sign;
+ this->denominator = -denominator;
+ }
+ isInt64 = false;
+ }
+
+ int32_t compare(const Rational128& b) const;
+
+ int32_t compare(int64_t b) const;
+
+ btScalar toScalar() const
+ {
+ return sign * ((denominator.getSign() == 0) ? SIMD_INFINITY : numerator.toScalar() / denominator.toScalar());
+ }
+ };
+
+ class PointR128 {
+ public:
+ Int128 x;
+ Int128 y;
+ Int128 z;
+ Int128 denominator;
+
+ PointR128()
+ {
+ }
+
+ PointR128(Int128 x, Int128 y, Int128 z, Int128 denominator)
+ : x(x)
+ , y(y)
+ , z(z)
+ , denominator(denominator)
+ {
+ }
+
+ btScalar xvalue() const
+ {
+ return x.toScalar() / denominator.toScalar();
+ }
+
+ btScalar yvalue() const
+ {
+ return y.toScalar() / denominator.toScalar();
+ }
+
+ btScalar zvalue() const
+ {
+ return z.toScalar() / denominator.toScalar();
+ }
+ };
+
+ class Edge;
+ class Face;
+
+ class Vertex {
+ public:
+ Vertex* next;
+ Vertex* prev;
+ Edge* edges;
+ Face* firstNearbyFace;
+ Face* lastNearbyFace;
+ PointR128 point128;
+ Point32 point;
+ int32_t copy;
+
+ Vertex()
+ : next(NULL)
+ , prev(NULL)
+ , edges(NULL)
+ , firstNearbyFace(NULL)
+ , lastNearbyFace(NULL)
+ , copy(-1)
+ {
+ }
+
+#ifdef DEBUG_CONVEX_HULL
+ void print()
+ {
+ printf("V%d (%d, %d, %d)", point.index, point.x, point.y, point.z);
+ }
+
+ void printGraph();
+#endif
+
+ Point32 operator-(const Vertex& b) const
+ {
+ return point - b.point;
+ }
+
+ Rational128 dot(const Point64& b) const
+ {
+ return (point.index >= 0) ? Rational128(point.dot(b))
+ : Rational128(point128.x * b.x + point128.y * b.y + point128.z * b.z, point128.denominator);
+ }
+
+ btScalar xvalue() const
+ {
+ return (point.index >= 0) ? btScalar(point.x) : point128.xvalue();
+ }
+
+ btScalar yvalue() const
+ {
+ return (point.index >= 0) ? btScalar(point.y) : point128.yvalue();
+ }
+
+ btScalar zvalue() const
+ {
+ return (point.index >= 0) ? btScalar(point.z) : point128.zvalue();
+ }
+
+ void receiveNearbyFaces(Vertex* src)
+ {
+ if (lastNearbyFace) {
+ lastNearbyFace->nextWithSameNearbyVertex = src->firstNearbyFace;
+ }
+ else {
+ firstNearbyFace = src->firstNearbyFace;
+ }
+ if (src->lastNearbyFace) {
+ lastNearbyFace = src->lastNearbyFace;
+ }
+ for (Face* f = src->firstNearbyFace; f; f = f->nextWithSameNearbyVertex) {
+ btAssert(f->nearbyVertex == src);
+ f->nearbyVertex = this;
+ }
+ src->firstNearbyFace = NULL;
+ src->lastNearbyFace = NULL;
+ }
+ };
+
+ class Edge {
+ public:
+ Edge* next;
+ Edge* prev;
+ Edge* reverse;
+ Vertex* target;
+ Face* face;
+ int32_t copy;
+
+ ~Edge()
+ {
+ next = NULL;
+ prev = NULL;
+ reverse = NULL;
+ target = NULL;
+ face = NULL;
+ }
+
+ void link(Edge* n)
+ {
+ btAssert(reverse->target == n->reverse->target);
+ next = n;
+ n->prev = this;
+ }
+
+#ifdef DEBUG_CONVEX_HULL
+ void print()
+ {
+ printf("E%p : %d -> %d, n=%p p=%p (0 %d\t%d\t%d) -> (%d %d %d)", this, reverse->target->point.index, target->point.index, next, prev,
+ reverse->target->point.x, reverse->target->point.y, reverse->target->point.z, target->point.x, target->point.y, target->point.z);
+ }
+#endif
+ };
+
+ class Face {
+ public:
+ Face* next;
+ Vertex* nearbyVertex;
+ Face* nextWithSameNearbyVertex;
+ Point32 origin;
+ Point32 dir0;
+ Point32 dir1;
+
+ Face()
+ : next(NULL)
+ , nearbyVertex(NULL)
+ , nextWithSameNearbyVertex(NULL)
+ {
+ }
+
+ void init(Vertex* a, Vertex* b, Vertex* c)
+ {
+ nearbyVertex = a;
+ origin = a->point;
+ dir0 = *b - *a;
+ dir1 = *c - *a;
+ if (a->lastNearbyFace) {
+ a->lastNearbyFace->nextWithSameNearbyVertex = this;
+ }
+ else {
+ a->firstNearbyFace = this;
+ }
+ a->lastNearbyFace = this;
+ }
+
+ Point64 getNormal()
+ {
+ return dir0.cross(dir1);
+ }
+ };
+
+ template <typename UWord, typename UHWord>
+ class DMul {
+ private:
+ static uint32_t high(uint64_t value)
+ {
+ return (uint32_t)(value >> 32);
+ }
+
+ static uint32_t low(uint64_t value)
+ {
+ return (uint32_t)value;
+ }
+
+ static uint64_t mul(uint32_t a, uint32_t b)
+ {
+ return (uint64_t)a * (uint64_t)b;
+ }
+
+ static void shlHalf(uint64_t& value)
+ {
+ value <<= 32;
+ }
+
+ static uint64_t high(Int128 value)
+ {
+ return value.high;
+ }
+
+ static uint64_t low(Int128 value)
+ {
+ return value.low;
+ }
+
+ static Int128 mul(uint64_t a, uint64_t b)
+ {
+ return Int128::mul(a, b);
+ }
+
+ static void shlHalf(Int128& value)
+ {
+ value.high = value.low;
+ value.low = 0;
+ }
+
+ public:
+ static void mul(UWord a, UWord b, UWord& resLow, UWord& resHigh)
+ {
+ UWord p00 = mul(low(a), low(b));
+ UWord p01 = mul(low(a), high(b));
+ UWord p10 = mul(high(a), low(b));
+ UWord p11 = mul(high(a), high(b));
+ UWord p0110 = UWord(low(p01)) + UWord(low(p10));
+ p11 += high(p01);
+ p11 += high(p10);
+ p11 += high(p0110);
+ shlHalf(p0110);
+ p00 += p0110;
+ if (p00 < p0110) {
+ ++p11;
+ }
+ resLow = p00;
+ resHigh = p11;
+ }
+ };
+
+private:
+ class IntermediateHull {
+ public:
+ Vertex* minXy;
+ Vertex* maxXy;
+ Vertex* minYx;
+ Vertex* maxYx;
+
+ IntermediateHull()
+ : minXy(NULL)
+ , maxXy(NULL)
+ , minYx(NULL)
+ , maxYx(NULL)
+ {
+ }
+
+ void print();
+ };
+
+ enum Orientation { NONE,
+ CLOCKWISE,
+ COUNTER_CLOCKWISE };
+
+ template <typename T>
+ class PoolArray {
+ private:
+ T* array;
+ int32_t size;
+
+ public:
+ PoolArray<T>* next;
+
+ PoolArray(int32_t size)
+ : size(size)
+ , next(NULL)
+ {
+ array = (T*)btAlignedAlloc(sizeof(T) * size, 16);
+ }
+
+ ~PoolArray()
+ {
+ btAlignedFree(array);
+ }
+
+ T* init()
+ {
+ T* o = array;
+ for (int32_t i = 0; i < size; i++, o++) {
+ o->next = (i + 1 < size) ? o + 1 : NULL;
+ }
+ return array;
+ }
+ };
+
+ template <typename T>
+ class Pool {
+ private:
+ PoolArray<T>* arrays;
+ PoolArray<T>* nextArray;
+ T* freeObjects;
+ int32_t arraySize;
+
+ public:
+ Pool()
+ : arrays(NULL)
+ , nextArray(NULL)
+ , freeObjects(NULL)
+ , arraySize(256)
+ {
+ }
+
+ ~Pool()
+ {
+ while (arrays) {
+ PoolArray<T>* p = arrays;
+ arrays = p->next;
+ p->~PoolArray<T>();
+ btAlignedFree(p);
+ }
+ }
+
+ void reset()
+ {
+ nextArray = arrays;
+ freeObjects = NULL;
+ }
+
+ void setArraySize(int32_t arraySize)
+ {
+ this->arraySize = arraySize;
+ }
+
+ T* newObject()
+ {
+ T* o = freeObjects;
+ if (!o) {
+ PoolArray<T>* p = nextArray;
+ if (p) {
+ nextArray = p->next;
+ }
+ else {
+ p = new (btAlignedAlloc(sizeof(PoolArray<T>), 16)) PoolArray<T>(arraySize);
+ p->next = arrays;
+ arrays = p;
+ }
+ o = p->init();
+ }
+ freeObjects = o->next;
+ return new (o) T();
+ };
+
+ void freeObject(T* object)
+ {
+ object->~T();
+ object->next = freeObjects;
+ freeObjects = object;
+ }
+ };
+
+ btVector3 scaling;
+ btVector3 center;
+ Pool<Vertex> vertexPool;
+ Pool<Edge> edgePool;
+ Pool<Face> facePool;
+ btAlignedObjectArray<Vertex*> originalVertices;
+ int32_t mergeStamp;
+ int32_t minAxis;
+ int32_t medAxis;
+ int32_t maxAxis;
+ int32_t usedEdgePairs;
+ int32_t maxUsedEdgePairs;
+
+ static Orientation getOrientation(const Edge* prev, const Edge* next, const Point32& s, const Point32& t);
+ Edge* findMaxAngle(bool ccw, const Vertex* start, const Point32& s, const Point64& rxs, const Point64& sxrxs, Rational64& minCot);
+ void findEdgeForCoplanarFaces(Vertex* c0, Vertex* c1, Edge*& e0, Edge*& e1, Vertex* stop0, Vertex* stop1);
+
+ Edge* newEdgePair(Vertex* from, Vertex* to);
+
+ void removeEdgePair(Edge* edge)
+ {
+ Edge* n = edge->next;
+ Edge* r = edge->reverse;
+
+ btAssert(edge->target && r->target);
+
+ if (n != edge) {
+ n->prev = edge->prev;
+ edge->prev->next = n;
+ r->target->edges = n;
+ }
+ else {
+ r->target->edges = NULL;
+ }
+
+ n = r->next;
+
+ if (n != r) {
+ n->prev = r->prev;
+ r->prev->next = n;
+ edge->target->edges = n;
+ }
+ else {
+ edge->target->edges = NULL;
+ }
+
+ edgePool.freeObject(edge);
+ edgePool.freeObject(r);
+ usedEdgePairs--;
+ }
+
+ void computeInternal(int32_t start, int32_t end, IntermediateHull& result);
+
+ bool mergeProjection(IntermediateHull& h0, IntermediateHull& h1, Vertex*& c0, Vertex*& c1);
+
+ void merge(IntermediateHull& h0, IntermediateHull& h1);
+
+ btVector3 toBtVector(const Point32& v);
+
+ btVector3 getBtNormal(Face* face);
+
+ bool shiftFace(Face* face, btScalar amount, btAlignedObjectArray<Vertex*> stack);
+
+public:
+ Vertex* vertexList;
+
+ void compute(const void* coords, bool doubleCoords, int32_t stride, int32_t count);
+
+ btVector3 getCoordinates(const Vertex* v);
+
+ btScalar shrink(btScalar amount, btScalar clampAmount);
+};
+
+btConvexHullInternal::Int128 btConvexHullInternal::Int128::operator*(int64_t b) const
+{
+ bool negative = (int64_t)high < 0;
+ Int128 a = negative ? -*this : *this;
+ if (b < 0) {
+ negative = !negative;
+ b = -b;
+ }
+ Int128 result = mul(a.low, (uint64_t)b);
+ result.high += a.high * (uint64_t)b;
+ return negative ? -result : result;
+}
+
+btConvexHullInternal::Int128 btConvexHullInternal::Int128::mul(int64_t a, int64_t b)
+{
+ Int128 result;
+
+#ifdef USE_X86_64_ASM
+ __asm__("imulq %[b]"
+ : "=a"(result.low), "=d"(result.high)
+ : "0"(a), [b] "r"(b)
+ : "cc");
+ return result;
+
+#else
+ bool negative = a < 0;
+ if (negative) {
+ a = -a;
+ }
+ if (b < 0) {
+ negative = !negative;
+ b = -b;
+ }
+ DMul<uint64_t, uint32_t>::mul((uint64_t)a, (uint64_t)b, result.low, result.high);
+ return negative ? -result : result;
+#endif
+}
+
+btConvexHullInternal::Int128 btConvexHullInternal::Int128::mul(uint64_t a, uint64_t b)
+{
+ Int128 result;
+
+#ifdef USE_X86_64_ASM
+ __asm__("mulq %[b]"
+ : "=a"(result.low), "=d"(result.high)
+ : "0"(a), [b] "r"(b)
+ : "cc");
+
+#else
+ DMul<uint64_t, uint32_t>::mul(a, b, result.low, result.high);
+#endif
+
+ return result;
+}
+
+int32_t btConvexHullInternal::Rational64::compare(const Rational64& b) const
+{
+ if (sign != b.sign) {
+ return sign - b.sign;
+ }
+ else if (sign == 0) {
+ return 0;
+ }
+
+// return (numerator * b.denominator > b.numerator * denominator) ? sign : (numerator * b.denominator < b.numerator * denominator) ? -sign : 0;
+
+#ifdef USE_X86_64_ASM
+
+ int32_t result;
+ int64_t tmp;
+ int64_t dummy;
+ __asm__("mulq %[bn]\n\t"
+ "movq %%rax, %[tmp]\n\t"
+ "movq %%rdx, %%rbx\n\t"
+ "movq %[tn], %%rax\n\t"
+ "mulq %[bd]\n\t"
+ "subq %[tmp], %%rax\n\t"
+ "sbbq %%rbx, %%rdx\n\t" // rdx:rax contains 128-bit-difference "numerator*b.denominator - b.numerator*denominator"
+ "setnsb %%bh\n\t" // bh=1 if difference is non-negative, bh=0 otherwise
+ "orq %%rdx, %%rax\n\t"
+ "setnzb %%bl\n\t" // bl=1 if difference if non-zero, bl=0 if it is zero
+ "decb %%bh\n\t" // now bx=0x0000 if difference is zero, 0xff01 if it is negative, 0x0001 if it is positive (i.e., same sign as difference)
+ "shll $16, %%ebx\n\t" // ebx has same sign as difference
+ : "=&b"(result), [tmp] "=&r"(tmp), "=a"(dummy)
+ : "a"(denominator), [bn] "g"(b.numerator), [tn] "g"(numerator), [bd] "g"(b.denominator)
+ : "%rdx", "cc");
+ return result ? result ^ sign // if sign is +1, only bit 0 of result is inverted, which does not change the sign of result (and cannot result in zero)
+ // if sign is -1, all bits of result are inverted, which changes the sign of result (and again cannot result in zero)
+ : 0;
+
+#else
+
+ return sign * Int128::mul(m_numerator, b.m_denominator).ucmp(Int128::mul(m_denominator, b.m_numerator));
+
+#endif
+}
+
+int32_t btConvexHullInternal::Rational128::compare(const Rational128& b) const
+{
+ if (sign != b.sign) {
+ return sign - b.sign;
+ }
+ else if (sign == 0) {
+ return 0;
+ }
+ if (isInt64) {
+ return -b.compare(sign * (int64_t)numerator.low);
+ }
+
+ Int128 nbdLow, nbdHigh, dbnLow, dbnHigh;
+ DMul<Int128, uint64_t>::mul(numerator, b.denominator, nbdLow, nbdHigh);
+ DMul<Int128, uint64_t>::mul(denominator, b.numerator, dbnLow, dbnHigh);
+
+ int32_t cmp = nbdHigh.ucmp(dbnHigh);
+ if (cmp) {
+ return cmp * sign;
+ }
+ return nbdLow.ucmp(dbnLow) * sign;
+}
+
+int32_t btConvexHullInternal::Rational128::compare(int64_t b) const
+{
+ if (isInt64) {
+ int64_t a = sign * (int64_t)numerator.low;
+ return (a > b) ? 1 : (a < b) ? -1 : 0;
+ }
+ if (b > 0) {
+ if (sign <= 0) {
+ return -1;
+ }
+ }
+ else if (b < 0) {
+ if (sign >= 0) {
+ return 1;
+ }
+ b = -b;
+ }
+ else {
+ return sign;
+ }
+
+ return numerator.ucmp(denominator * b) * sign;
+}
+
+btConvexHullInternal::Edge* btConvexHullInternal::newEdgePair(Vertex* from, Vertex* to)
+{
+ btAssert(from && to);
+ Edge* e = edgePool.newObject();
+ Edge* r = edgePool.newObject();
+ e->reverse = r;
+ r->reverse = e;
+ e->copy = mergeStamp;
+ r->copy = mergeStamp;
+ e->target = to;
+ r->target = from;
+ e->face = NULL;
+ r->face = NULL;
+ usedEdgePairs++;
+ if (usedEdgePairs > maxUsedEdgePairs) {
+ maxUsedEdgePairs = usedEdgePairs;
+ }
+ return e;
+}
+
+bool btConvexHullInternal::mergeProjection(IntermediateHull& h0, IntermediateHull& h1, Vertex*& c0, Vertex*& c1)
+{
+ Vertex* v0 = h0.maxYx;
+ Vertex* v1 = h1.minYx;
+ if ((v0->point.x == v1->point.x) && (v0->point.y == v1->point.y)) {
+ btAssert(v0->point.z < v1->point.z);
+ Vertex* v1p = v1->prev;
+ if (v1p == v1) {
+ c0 = v0;
+ if (v1->edges) {
+ btAssert(v1->edges->next == v1->edges);
+ v1 = v1->edges->target;
+ btAssert(v1->edges->next == v1->edges);
+ }
+ c1 = v1;
+ return false;
+ }
+ Vertex* v1n = v1->next;
+ v1p->next = v1n;
+ v1n->prev = v1p;
+ if (v1 == h1.minXy) {
+ if ((v1n->point.x < v1p->point.x) || ((v1n->point.x == v1p->point.x) && (v1n->point.y < v1p->point.y))) {
+ h1.minXy = v1n;
+ }
+ else {
+ h1.minXy = v1p;
+ }
+ }
+ if (v1 == h1.maxXy) {
+ if ((v1n->point.x > v1p->point.x) || ((v1n->point.x == v1p->point.x) && (v1n->point.y > v1p->point.y))) {
+ h1.maxXy = v1n;
+ }
+ else {
+ h1.maxXy = v1p;
+ }
+ }
+ }
+
+ v0 = h0.maxXy;
+ v1 = h1.maxXy;
+ Vertex* v00 = NULL;
+ Vertex* v10 = NULL;
+ int32_t sign = 1;
+
+ for (int32_t side = 0; side <= 1; side++) {
+ int32_t dx = (v1->point.x - v0->point.x) * sign;
+ if (dx > 0) {
+ while (true) {
+ int32_t dy = v1->point.y - v0->point.y;
+
+ Vertex* w0 = side ? v0->next : v0->prev;
+ if (w0 != v0) {
+ int32_t dx0 = (w0->point.x - v0->point.x) * sign;
+ int32_t dy0 = w0->point.y - v0->point.y;
+ if ((dy0 <= 0) && ((dx0 == 0) || ((dx0 < 0) && (dy0 * dx <= dy * dx0)))) {
+ v0 = w0;
+ dx = (v1->point.x - v0->point.x) * sign;
+ continue;
+ }
+ }
+
+ Vertex* w1 = side ? v1->next : v1->prev;
+ if (w1 != v1) {
+ int32_t dx1 = (w1->point.x - v1->point.x) * sign;
+ int32_t dy1 = w1->point.y - v1->point.y;
+ int32_t dxn = (w1->point.x - v0->point.x) * sign;
+ if ((dxn > 0) && (dy1 < 0) && ((dx1 == 0) || ((dx1 < 0) && (dy1 * dx < dy * dx1)))) {
+ v1 = w1;
+ dx = dxn;
+ continue;
+ }
+ }
+
+ break;
+ }
+ }
+ else if (dx < 0) {
+ while (true) {
+ int32_t dy = v1->point.y - v0->point.y;
+
+ Vertex* w1 = side ? v1->prev : v1->next;
+ if (w1 != v1) {
+ int32_t dx1 = (w1->point.x - v1->point.x) * sign;
+ int32_t dy1 = w1->point.y - v1->point.y;
+ if ((dy1 >= 0) && ((dx1 == 0) || ((dx1 < 0) && (dy1 * dx <= dy * dx1)))) {
+ v1 = w1;
+ dx = (v1->point.x - v0->point.x) * sign;
+ continue;
+ }
+ }
+
+ Vertex* w0 = side ? v0->prev : v0->next;
+ if (w0 != v0) {
+ int32_t dx0 = (w0->point.x - v0->point.x) * sign;
+ int32_t dy0 = w0->point.y - v0->point.y;
+ int32_t dxn = (v1->point.x - w0->point.x) * sign;
+ if ((dxn < 0) && (dy0 > 0) && ((dx0 == 0) || ((dx0 < 0) && (dy0 * dx < dy * dx0)))) {
+ v0 = w0;
+ dx = dxn;
+ continue;
+ }
+ }
+
+ break;
+ }
+ }
+ else {
+ int32_t x = v0->point.x;
+ int32_t y0 = v0->point.y;
+ Vertex* w0 = v0;
+ Vertex* t;
+ while (((t = side ? w0->next : w0->prev) != v0) && (t->point.x == x) && (t->point.y <= y0)) {
+ w0 = t;
+ y0 = t->point.y;
+ }
+ v0 = w0;
+
+ int32_t y1 = v1->point.y;
+ Vertex* w1 = v1;
+ while (((t = side ? w1->prev : w1->next) != v1) && (t->point.x == x) && (t->point.y >= y1)) {
+ w1 = t;
+ y1 = t->point.y;
+ }
+ v1 = w1;
+ }
+
+ if (side == 0) {
+ v00 = v0;
+ v10 = v1;
+
+ v0 = h0.minXy;
+ v1 = h1.minXy;
+ sign = -1;
+ }
+ }
+
+ v0->prev = v1;
+ v1->next = v0;
+
+ v00->next = v10;
+ v10->prev = v00;
+
+ if (h1.minXy->point.x < h0.minXy->point.x) {
+ h0.minXy = h1.minXy;
+ }
+ if (h1.maxXy->point.x >= h0.maxXy->point.x) {
+ h0.maxXy = h1.maxXy;
+ }
+
+ h0.maxYx = h1.maxYx;
+
+ c0 = v00;
+ c1 = v10;
+
+ return true;
+}
+
+void btConvexHullInternal::computeInternal(int32_t start, int32_t end, IntermediateHull& result)
+{
+ int32_t n = end - start;
+ switch (n) {
+ case 0:
+ result.minXy = NULL;
+ result.maxXy = NULL;
+ result.minYx = NULL;
+ result.maxYx = NULL;
+ return;
+ case 2: {
+ Vertex* v = originalVertices[start];
+ Vertex* w = v + 1;
+ if (v->point != w->point) {
+ int32_t dx = v->point.x - w->point.x;
+ int32_t dy = v->point.y - w->point.y;
+
+ if ((dx == 0) && (dy == 0)) {
+ if (v->point.z > w->point.z) {
+ Vertex* t = w;
+ w = v;
+ v = t;
+ }
+ btAssert(v->point.z < w->point.z);
+ v->next = v;
+ v->prev = v;
+ result.minXy = v;
+ result.maxXy = v;
+ result.minYx = v;
+ result.maxYx = v;
+ }
+ else {
+ v->next = w;
+ v->prev = w;
+ w->next = v;
+ w->prev = v;
+
+ if ((dx < 0) || ((dx == 0) && (dy < 0))) {
+ result.minXy = v;
+ result.maxXy = w;
+ }
+ else {
+ result.minXy = w;
+ result.maxXy = v;
+ }
+
+ if ((dy < 0) || ((dy == 0) && (dx < 0))) {
+ result.minYx = v;
+ result.maxYx = w;
+ }
+ else {
+ result.minYx = w;
+ result.maxYx = v;
+ }
+ }
+
+ Edge* e = newEdgePair(v, w);
+ e->link(e);
+ v->edges = e;
+
+ e = e->reverse;
+ e->link(e);
+ w->edges = e;
+
+ return;
+ }
+ }
+ // lint -fallthrough
+ case 1: {
+ Vertex* v = originalVertices[start];
+ v->edges = NULL;
+ v->next = v;
+ v->prev = v;
+
+ result.minXy = v;
+ result.maxXy = v;
+ result.minYx = v;
+ result.maxYx = v;
+
+ return;
+ }
+ }
+
+ int32_t split0 = start + n / 2;
+ Point32 p = originalVertices[split0 - 1]->point;
+ int32_t split1 = split0;
+ while ((split1 < end) && (originalVertices[split1]->point == p)) {
+ split1++;
+ }
+ computeInternal(start, split0, result);
+ IntermediateHull hull1;
+ computeInternal(split1, end, hull1);
+#ifdef DEBUG_CONVEX_HULL
+ printf("\n\nMerge\n");
+ result.print();
+ hull1.print();
+#endif
+ merge(result, hull1);
+#ifdef DEBUG_CONVEX_HULL
+ printf("\n Result\n");
+ result.print();
+#endif
+}
+
+#ifdef DEBUG_CONVEX_HULL
+void btConvexHullInternal::IntermediateHull::print()
+{
+ printf(" Hull\n");
+ for (Vertex* v = minXy; v;) {
+ printf(" ");
+ v->print();
+ if (v == maxXy) {
+ printf(" maxXy");
+ }
+ if (v == minYx) {
+ printf(" minYx");
+ }
+ if (v == maxYx) {
+ printf(" maxYx");
+ }
+ if (v->next->prev != v) {
+ printf(" Inconsistency");
+ }
+ printf("\n");
+ v = v->next;
+ if (v == minXy) {
+ break;
+ }
+ }
+ if (minXy) {
+ minXy->copy = (minXy->copy == -1) ? -2 : -1;
+ minXy->printGraph();
+ }
+}
+
+void btConvexHullInternal::Vertex::printGraph()
+{
+ print();
+ printf("\nEdges\n");
+ Edge* e = edges;
+ if (e) {
+ do {
+ e->print();
+ printf("\n");
+ e = e->next;
+ } while (e != edges);
+ do {
+ Vertex* v = e->target;
+ if (v->copy != copy) {
+ v->copy = copy;
+ v->printGraph();
+ }
+ e = e->next;
+ } while (e != edges);
+ }
+}
+#endif
+
+btConvexHullInternal::Orientation btConvexHullInternal::getOrientation(const Edge* prev, const Edge* next, const Point32& s, const Point32& t)
+{
+ btAssert(prev->reverse->target == next->reverse->target);
+ if (prev->next == next) {
+ if (prev->prev == next) {
+ Point64 n = t.cross(s);
+ Point64 m = (*prev->target - *next->reverse->target).cross(*next->target - *next->reverse->target);
+ btAssert(!m.isZero());
+ int64_t dot = n.dot(m);
+ btAssert(dot != 0);
+ return (dot > 0) ? COUNTER_CLOCKWISE : CLOCKWISE;
+ }
+ return COUNTER_CLOCKWISE;
+ }
+ else if (prev->prev == next) {
+ return CLOCKWISE;
+ }
+ else {
+ return NONE;
+ }
+}
+
+btConvexHullInternal::Edge* btConvexHullInternal::findMaxAngle(bool ccw, const Vertex* start, const Point32& s, const Point64& rxs, const Point64& sxrxs, Rational64& minCot)
+{
+ Edge* minEdge = NULL;
+
+#ifdef DEBUG_CONVEX_HULL
+ printf("find max edge for %d\n", start->point.index);
+#endif
+ Edge* e = start->edges;
+ if (e) {
+ do {
+ if (e->copy > mergeStamp) {
+ Point32 t = *e->target - *start;
+ Rational64 cot(t.dot(sxrxs), t.dot(rxs));
+#ifdef DEBUG_CONVEX_HULL
+ printf(" Angle is %f (%d) for ", (float)btAtan(cot.toScalar()), (int32_t)cot.isNaN());
+ e->print();
+#endif
+ if (cot.isNaN()) {
+ btAssert(ccw ? (t.dot(s) < 0) : (t.dot(s) > 0));
+ }
+ else {
+ int32_t cmp;
+ if (minEdge == NULL) {
+ minCot = cot;
+ minEdge = e;
+ }
+ else if ((cmp = cot.compare(minCot)) < 0) {
+ minCot = cot;
+ minEdge = e;
+ }
+ else if ((cmp == 0) && (ccw == (getOrientation(minEdge, e, s, t) == COUNTER_CLOCKWISE))) {
+ minEdge = e;
+ }
+ }
+#ifdef DEBUG_CONVEX_HULL
+ printf("\n");
+#endif
+ }
+ e = e->next;
+ } while (e != start->edges);
+ }
+ return minEdge;
+}
+
+void btConvexHullInternal::findEdgeForCoplanarFaces(Vertex* c0, Vertex* c1, Edge*& e0, Edge*& e1, Vertex* stop0, Vertex* stop1)
+{
+ Edge* start0 = e0;
+ Edge* start1 = e1;
+ Point32 et0 = start0 ? start0->target->point : c0->point;
+ Point32 et1 = start1 ? start1->target->point : c1->point;
+ Point32 s = c1->point - c0->point;
+ Point64 normal = ((start0 ? start0 : start1)->target->point - c0->point).cross(s);
+ int64_t dist = c0->point.dot(normal);
+ btAssert(!start1 || (start1->target->point.dot(normal) == dist));
+ Point64 perp = s.cross(normal);
+ btAssert(!perp.isZero());
+
+#ifdef DEBUG_CONVEX_HULL
+ printf(" Advancing %d %d (%p %p, %d %d)\n", c0->point.index, c1->point.index, start0, start1, start0 ? start0->target->point.index : -1, start1 ? start1->target->point.index : -1);
+#endif
+
+ int64_t maxDot0 = et0.dot(perp);
+ if (e0) {
+ while (e0->target != stop0) {
+ Edge* e = e0->reverse->prev;
+ if (e->target->point.dot(normal) < dist) {
+ break;
+ }
+ btAssert(e->target->point.dot(normal) == dist);
+ if (e->copy == mergeStamp) {
+ break;
+ }
+ int64_t dot = e->target->point.dot(perp);
+ if (dot <= maxDot0) {
+ break;
+ }
+ maxDot0 = dot;
+ e0 = e;
+ et0 = e->target->point;
+ }
+ }
+
+ int64_t maxDot1 = et1.dot(perp);
+ if (e1) {
+ while (e1->target != stop1) {
+ Edge* e = e1->reverse->next;
+ if (e->target->point.dot(normal) < dist) {
+ break;
+ }
+ btAssert(e->target->point.dot(normal) == dist);
+ if (e->copy == mergeStamp) {
+ break;
+ }
+ int64_t dot = e->target->point.dot(perp);
+ if (dot <= maxDot1) {
+ break;
+ }
+ maxDot1 = dot;
+ e1 = e;
+ et1 = e->target->point;
+ }
+ }
+
+#ifdef DEBUG_CONVEX_HULL
+ printf(" Starting at %d %d\n", et0.index, et1.index);
+#endif
+
+ int64_t dx = maxDot1 - maxDot0;
+ if (dx > 0) {
+ while (true) {
+ int64_t dy = (et1 - et0).dot(s);
+
+ if (e0 && (e0->target != stop0)) {
+ Edge* f0 = e0->next->reverse;
+ if (f0->copy > mergeStamp) {
+ int64_t dx0 = (f0->target->point - et0).dot(perp);
+ int64_t dy0 = (f0->target->point - et0).dot(s);
+ if ((dx0 == 0) ? (dy0 < 0) : ((dx0 < 0) && (Rational64(dy0, dx0).compare(Rational64(dy, dx)) >= 0))) {
+ et0 = f0->target->point;
+ dx = (et1 - et0).dot(perp);
+ e0 = (e0 == start0) ? NULL : f0;
+ continue;
+ }
+ }
+ }
+
+ if (e1 && (e1->target != stop1)) {
+ Edge* f1 = e1->reverse->next;
+ if (f1->copy > mergeStamp) {
+ Point32 d1 = f1->target->point - et1;
+ if (d1.dot(normal) == 0) {
+ int64_t dx1 = d1.dot(perp);
+ int64_t dy1 = d1.dot(s);
+ int64_t dxn = (f1->target->point - et0).dot(perp);
+ if ((dxn > 0) && ((dx1 == 0) ? (dy1 < 0) : ((dx1 < 0) && (Rational64(dy1, dx1).compare(Rational64(dy, dx)) > 0)))) {
+ e1 = f1;
+ et1 = e1->target->point;
+ dx = dxn;
+ continue;
+ }
+ }
+ else {
+ btAssert((e1 == start1) && (d1.dot(normal) < 0));
+ }
+ }
+ }
+
+ break;
+ }
+ }
+ else if (dx < 0) {
+ while (true) {
+ int64_t dy = (et1 - et0).dot(s);
+
+ if (e1 && (e1->target != stop1)) {
+ Edge* f1 = e1->prev->reverse;
+ if (f1->copy > mergeStamp) {
+ int64_t dx1 = (f1->target->point - et1).dot(perp);
+ int64_t dy1 = (f1->target->point - et1).dot(s);
+ if ((dx1 == 0) ? (dy1 > 0) : ((dx1 < 0) && (Rational64(dy1, dx1).compare(Rational64(dy, dx)) <= 0))) {
+ et1 = f1->target->point;
+ dx = (et1 - et0).dot(perp);
+ e1 = (e1 == start1) ? NULL : f1;
+ continue;
+ }
+ }
+ }
+
+ if (e0 && (e0->target != stop0)) {
+ Edge* f0 = e0->reverse->prev;
+ if (f0->copy > mergeStamp) {
+ Point32 d0 = f0->target->point - et0;
+ if (d0.dot(normal) == 0) {
+ int64_t dx0 = d0.dot(perp);
+ int64_t dy0 = d0.dot(s);
+ int64_t dxn = (et1 - f0->target->point).dot(perp);
+ if ((dxn < 0) && ((dx0 == 0) ? (dy0 > 0) : ((dx0 < 0) && (Rational64(dy0, dx0).compare(Rational64(dy, dx)) < 0)))) {
+ e0 = f0;
+ et0 = e0->target->point;
+ dx = dxn;
+ continue;
+ }
+ }
+ else {
+ btAssert((e0 == start0) && (d0.dot(normal) < 0));
+ }
+ }
+ }
+
+ break;
+ }
+ }
+#ifdef DEBUG_CONVEX_HULL
+ printf(" Advanced edges to %d %d\n", et0.index, et1.index);
+#endif
+}
+
+void btConvexHullInternal::merge(IntermediateHull& h0, IntermediateHull& h1)
+{
+ if (!h1.maxXy) {
+ return;
+ }
+ if (!h0.maxXy) {
+ h0 = h1;
+ return;
+ }
+
+ mergeStamp--;
+
+ Vertex* c0 = NULL;
+ Edge* toPrev0 = NULL;
+ Edge* firstNew0 = NULL;
+ Edge* pendingHead0 = NULL;
+ Edge* pendingTail0 = NULL;
+ Vertex* c1 = NULL;
+ Edge* toPrev1 = NULL;
+ Edge* firstNew1 = NULL;
+ Edge* pendingHead1 = NULL;
+ Edge* pendingTail1 = NULL;
+ Point32 prevPoint;
+
+ if (mergeProjection(h0, h1, c0, c1)) {
+ Point32 s = *c1 - *c0;
+ Point64 normal = Point32(0, 0, -1).cross(s);
+ Point64 t = s.cross(normal);
+ btAssert(!t.isZero());
+
+ Edge* e = c0->edges;
+ Edge* start0 = NULL;
+ if (e) {
+ do {
+ int64_t dot = (*e->target - *c0).dot(normal);
+ btAssert(dot <= 0);
+ if ((dot == 0) && ((*e->target - *c0).dot(t) > 0)) {
+ if (!start0 || (getOrientation(start0, e, s, Point32(0, 0, -1)) == CLOCKWISE)) {
+ start0 = e;
+ }
+ }
+ e = e->next;
+ } while (e != c0->edges);
+ }
+
+ e = c1->edges;
+ Edge* start1 = NULL;
+ if (e) {
+ do {
+ int64_t dot = (*e->target - *c1).dot(normal);
+ btAssert(dot <= 0);
+ if ((dot == 0) && ((*e->target - *c1).dot(t) > 0)) {
+ if (!start1 || (getOrientation(start1, e, s, Point32(0, 0, -1)) == COUNTER_CLOCKWISE)) {
+ start1 = e;
+ }
+ }
+ e = e->next;
+ } while (e != c1->edges);
+ }
+
+ if (start0 || start1) {
+ findEdgeForCoplanarFaces(c0, c1, start0, start1, NULL, NULL);
+ if (start0) {
+ c0 = start0->target;
+ }
+ if (start1) {
+ c1 = start1->target;
+ }
+ }
+
+ prevPoint = c1->point;
+ prevPoint.z++;
+ }
+ else {
+ prevPoint = c1->point;
+ prevPoint.x++;
+ }
+
+ Vertex* first0 = c0;
+ Vertex* first1 = c1;
+ bool firstRun = true;
+
+ while (true) {
+ Point32 s = *c1 - *c0;
+ Point32 r = prevPoint - c0->point;
+ Point64 rxs = r.cross(s);
+ Point64 sxrxs = s.cross(rxs);
+
+#ifdef DEBUG_CONVEX_HULL
+ printf("\n Checking %d %d\n", c0->point.index, c1->point.index);
+#endif
+ Rational64 minCot0(0, 0);
+ Edge* min0 = findMaxAngle(false, c0, s, rxs, sxrxs, minCot0);
+ Rational64 minCot1(0, 0);
+ Edge* min1 = findMaxAngle(true, c1, s, rxs, sxrxs, minCot1);
+ if (!min0 && !min1) {
+ Edge* e = newEdgePair(c0, c1);
+ e->link(e);
+ c0->edges = e;
+
+ e = e->reverse;
+ e->link(e);
+ c1->edges = e;
+ return;
+ }
+ else {
+ int32_t cmp = !min0 ? 1 : !min1 ? -1 : minCot0.compare(minCot1);
+#ifdef DEBUG_CONVEX_HULL
+ printf(" -> Result %d\n", cmp);
+#endif
+ if (firstRun || ((cmp >= 0) ? !minCot1.isNegativeInfinity() : !minCot0.isNegativeInfinity())) {
+ Edge* e = newEdgePair(c0, c1);
+ if (pendingTail0) {
+ pendingTail0->prev = e;
+ }
+ else {
+ pendingHead0 = e;
+ }
+ e->next = pendingTail0;
+ pendingTail0 = e;
+
+ e = e->reverse;
+ if (pendingTail1) {
+ pendingTail1->next = e;
+ }
+ else {
+ pendingHead1 = e;
+ }
+ e->prev = pendingTail1;
+ pendingTail1 = e;
+ }
+
+ Edge* e0 = min0;
+ Edge* e1 = min1;
+
+#ifdef DEBUG_CONVEX_HULL
+ printf(" Found min edges to %d %d\n", e0 ? e0->target->point.index : -1, e1 ? e1->target->point.index : -1);
+#endif
+
+ if (cmp == 0) {
+ findEdgeForCoplanarFaces(c0, c1, e0, e1, NULL, NULL);
+ }
+
+ if ((cmp >= 0) && e1) {
+ if (toPrev1) {
+ for (Edge *e = toPrev1->next, *n = NULL; e != min1; e = n) {
+ n = e->next;
+ removeEdgePair(e);
+ }
+ }
+
+ if (pendingTail1) {
+ if (toPrev1) {
+ toPrev1->link(pendingHead1);
+ }
+ else {
+ min1->prev->link(pendingHead1);
+ firstNew1 = pendingHead1;
+ }
+ pendingTail1->link(min1);
+ pendingHead1 = NULL;
+ pendingTail1 = NULL;
+ }
+ else if (!toPrev1) {
+ firstNew1 = min1;
+ }
+
+ prevPoint = c1->point;
+ c1 = e1->target;
+ toPrev1 = e1->reverse;
+ }
+
+ if ((cmp <= 0) && e0) {
+ if (toPrev0) {
+ for (Edge *e = toPrev0->prev, *n = NULL; e != min0; e = n) {
+ n = e->prev;
+ removeEdgePair(e);
+ }
+ }
+
+ if (pendingTail0) {
+ if (toPrev0) {
+ pendingHead0->link(toPrev0);
+ }
+ else {
+ pendingHead0->link(min0->next);
+ firstNew0 = pendingHead0;
+ }
+ min0->link(pendingTail0);
+ pendingHead0 = NULL;
+ pendingTail0 = NULL;
+ }
+ else if (!toPrev0) {
+ firstNew0 = min0;
+ }
+
+ prevPoint = c0->point;
+ c0 = e0->target;
+ toPrev0 = e0->reverse;
+ }
+ }
+
+ if ((c0 == first0) && (c1 == first1)) {
+ if (toPrev0 == NULL) {
+ pendingHead0->link(pendingTail0);
+ c0->edges = pendingTail0;
+ }
+ else {
+ for (Edge *e = toPrev0->prev, *n = NULL; e != firstNew0; e = n) {
+ n = e->prev;
+ removeEdgePair(e);
+ }
+ if (pendingTail0) {
+ pendingHead0->link(toPrev0);
+ firstNew0->link(pendingTail0);
+ }
+ }
+
+ if (toPrev1 == NULL) {
+ pendingTail1->link(pendingHead1);
+ c1->edges = pendingTail1;
+ }
+ else {
+ for (Edge *e = toPrev1->next, *n = NULL; e != firstNew1; e = n) {
+ n = e->next;
+ removeEdgePair(e);
+ }
+ if (pendingTail1) {
+ toPrev1->link(pendingHead1);
+ pendingTail1->link(firstNew1);
+ }
+ }
+
+ return;
+ }
+
+ firstRun = false;
+ }
+}
+
+static bool pointCmp(const btConvexHullInternal::Point32& p, const btConvexHullInternal::Point32& q)
+{
+ return (p.y < q.y) || ((p.y == q.y) && ((p.x < q.x) || ((p.x == q.x) && (p.z < q.z))));
+}
+
+void btConvexHullInternal::compute(const void* coords, bool doubleCoords, int32_t stride, int32_t count)
+{
+ btVector3 min(btScalar(1e30), btScalar(1e30), btScalar(1e30)), max(btScalar(-1e30), btScalar(-1e30), btScalar(-1e30));
+ const char* ptr = (const char*)coords;
+ if (doubleCoords) {
+ for (int32_t i = 0; i < count; i++) {
+ const double* v = (const double*)ptr;
+ btVector3 p((btScalar)v[0], (btScalar)v[1], (btScalar)v[2]);
+ ptr += stride;
+ min.setMin(p);
+ max.setMax(p);
+ }
+ }
+ else {
+ for (int32_t i = 0; i < count; i++) {
+ const float* v = (const float*)ptr;
+ btVector3 p(v[0], v[1], v[2]);
+ ptr += stride;
+ min.setMin(p);
+ max.setMax(p);
+ }
+ }
+
+ btVector3 s = max - min;
+ maxAxis = s.maxAxis();
+ minAxis = s.minAxis();
+ if (minAxis == maxAxis) {
+ minAxis = (maxAxis + 1) % 3;
+ }
+ medAxis = 3 - maxAxis - minAxis;
+
+ s /= btScalar(10216);
+ if (((medAxis + 1) % 3) != maxAxis) {
+ s *= -1;
+ }
+ scaling = s;
+
+ if (s[0] != 0) {
+ s[0] = btScalar(1) / s[0];
+ }
+ if (s[1] != 0) {
+ s[1] = btScalar(1) / s[1];
+ }
+ if (s[2] != 0) {
+ s[2] = btScalar(1) / s[2];
+ }
+
+ center = (min + max) * btScalar(0.5);
+
+ btAlignedObjectArray<Point32> points;
+ points.resize(count);
+ ptr = (const char*)coords;
+ if (doubleCoords) {
+ for (int32_t i = 0; i < count; i++) {
+ const double* v = (const double*)ptr;
+ btVector3 p((btScalar)v[0], (btScalar)v[1], (btScalar)v[2]);
+ ptr += stride;
+ p = (p - center) * s;
+ points[i].x = (int32_t)p[medAxis];
+ points[i].y = (int32_t)p[maxAxis];
+ points[i].z = (int32_t)p[minAxis];
+ points[i].index = i;
+ }
+ }
+ else {
+ for (int32_t i = 0; i < count; i++) {
+ const float* v = (const float*)ptr;
+ btVector3 p(v[0], v[1], v[2]);
+ ptr += stride;
+ p = (p - center) * s;
+ points[i].x = (int32_t)p[medAxis];
+ points[i].y = (int32_t)p[maxAxis];
+ points[i].z = (int32_t)p[minAxis];
+ points[i].index = i;
+ }
+ }
+ points.quickSort(pointCmp);
+
+ vertexPool.reset();
+ vertexPool.setArraySize(count);
+ originalVertices.resize(count);
+ for (int32_t i = 0; i < count; i++) {
+ Vertex* v = vertexPool.newObject();
+ v->edges = NULL;
+ v->point = points[i];
+ v->copy = -1;
+ originalVertices[i] = v;
+ }
+
+ points.clear();
+
+ edgePool.reset();
+ edgePool.setArraySize(6 * count);
+
+ usedEdgePairs = 0;
+ maxUsedEdgePairs = 0;
+
+ mergeStamp = -3;
+
+ IntermediateHull hull;
+ computeInternal(0, count, hull);
+ vertexList = hull.minXy;
+#ifdef DEBUG_CONVEX_HULL
+ printf("max. edges %d (3v = %d)", maxUsedEdgePairs, 3 * count);
+#endif
+}
+
+btVector3 btConvexHullInternal::toBtVector(const Point32& v)
+{
+ btVector3 p;
+ p[medAxis] = btScalar(v.x);
+ p[maxAxis] = btScalar(v.y);
+ p[minAxis] = btScalar(v.z);
+ return p * scaling;
+}
+
+btVector3 btConvexHullInternal::getBtNormal(Face* face)
+{
+ return toBtVector(face->dir0).cross(toBtVector(face->dir1)).normalized();
+}
+
+btVector3 btConvexHullInternal::getCoordinates(const Vertex* v)
+{
+ btVector3 p;
+ p[medAxis] = v->xvalue();
+ p[maxAxis] = v->yvalue();
+ p[minAxis] = v->zvalue();
+ return p * scaling + center;
+}
+
+btScalar btConvexHullInternal::shrink(btScalar amount, btScalar clampAmount)
+{
+ if (!vertexList) {
+ return 0;
+ }
+ int32_t stamp = --mergeStamp;
+ btAlignedObjectArray<Vertex*> stack;
+ vertexList->copy = stamp;
+ stack.push_back(vertexList);
+ btAlignedObjectArray<Face*> faces;
+
+ Point32 ref = vertexList->point;
+ Int128 hullCenterX(0, 0);
+ Int128 hullCenterY(0, 0);
+ Int128 hullCenterZ(0, 0);
+ Int128 volume(0, 0);
+
+ while (stack.size() > 0) {
+ Vertex* v = stack[stack.size() - 1];
+ stack.pop_back();
+ Edge* e = v->edges;
+ if (e) {
+ do {
+ if (e->target->copy != stamp) {
+ e->target->copy = stamp;
+ stack.push_back(e->target);
+ }
+ if (e->copy != stamp) {
+ Face* face = facePool.newObject();
+ face->init(e->target, e->reverse->prev->target, v);
+ faces.push_back(face);
+ Edge* f = e;
+
+ Vertex* a = NULL;
+ Vertex* b = NULL;
+ do {
+ if (a && b) {
+ int64_t vol = (v->point - ref).dot((a->point - ref).cross(b->point - ref));
+ btAssert(vol >= 0);
+ Point32 c = v->point + a->point + b->point + ref;
+ hullCenterX += vol * c.x;
+ hullCenterY += vol * c.y;
+ hullCenterZ += vol * c.z;
+ volume += vol;
+ }
+
+ btAssert(f->copy != stamp);
+ f->copy = stamp;
+ f->face = face;
+
+ a = b;
+ b = f->target;
+
+ f = f->reverse->prev;
+ } while (f != e);
+ }
+ e = e->next;
+ } while (e != v->edges);
+ }
+ }
+
+ if (volume.getSign() <= 0) {
+ return 0;
+ }
+
+ btVector3 hullCenter;
+ hullCenter[medAxis] = hullCenterX.toScalar();
+ hullCenter[maxAxis] = hullCenterY.toScalar();
+ hullCenter[minAxis] = hullCenterZ.toScalar();
+ hullCenter /= 4 * volume.toScalar();
+ hullCenter *= scaling;
+
+ int32_t faceCount = faces.size();
+
+ if (clampAmount > 0) {
+ btScalar minDist = SIMD_INFINITY;
+ for (int32_t i = 0; i < faceCount; i++) {
+ btVector3 normal = getBtNormal(faces[i]);
+ btScalar dist = normal.dot(toBtVector(faces[i]->origin) - hullCenter);
+ if (dist < minDist) {
+ minDist = dist;
+ }
+ }
+
+ if (minDist <= 0) {
+ return 0;
+ }
+
+ amount = btMin(amount, minDist * clampAmount);
+ }
+
+ uint32_t seed = 243703;
+ for (int32_t i = 0; i < faceCount; i++, seed = 1664525 * seed + 1013904223) {
+ btSwap(faces[i], faces[seed % faceCount]);
+ }
+
+ for (int32_t i = 0; i < faceCount; i++) {
+ if (!shiftFace(faces[i], amount, stack)) {
+ return -amount;
+ }
+ }
+
+ return amount;
+}
+
+bool btConvexHullInternal::shiftFace(Face* face, btScalar amount, btAlignedObjectArray<Vertex*> stack)
+{
+ btVector3 origShift = getBtNormal(face) * -amount;
+ if (scaling[0] != 0) {
+ origShift[0] /= scaling[0];
+ }
+ if (scaling[1] != 0) {
+ origShift[1] /= scaling[1];
+ }
+ if (scaling[2] != 0) {
+ origShift[2] /= scaling[2];
+ }
+ Point32 shift((int32_t)origShift[medAxis], (int32_t)origShift[maxAxis], (int32_t)origShift[minAxis]);
+ if (shift.isZero()) {
+ return true;
+ }
+ Point64 normal = face->getNormal();
+#ifdef DEBUG_CONVEX_HULL
+ printf("\nShrinking face (%d %d %d) (%d %d %d) (%d %d %d) by (%d %d %d)\n",
+ face->origin.x, face->origin.y, face->origin.z, face->dir0.x, face->dir0.y, face->dir0.z, face->dir1.x, face->dir1.y, face->dir1.z, shift.x, shift.y, shift.z);
+#endif
+ int64_t origDot = face->origin.dot(normal);
+ Point32 shiftedOrigin = face->origin + shift;
+ int64_t shiftedDot = shiftedOrigin.dot(normal);
+ btAssert(shiftedDot <= origDot);
+ if (shiftedDot >= origDot) {
+ return false;
+ }
+
+ Edge* intersection = NULL;
+
+ Edge* startEdge = face->nearbyVertex->edges;
+#ifdef DEBUG_CONVEX_HULL
+ printf("Start edge is ");
+ startEdge->print();
+ printf(", normal is (%lld %lld %lld), shifted dot is %lld\n", normal.x, normal.y, normal.z, shiftedDot);
+#endif
+ Rational128 optDot = face->nearbyVertex->dot(normal);
+ int32_t cmp = optDot.compare(shiftedDot);
+#ifdef SHOW_ITERATIONS
+ int32_t n = 0;
+#endif
+ if (cmp >= 0) {
+ Edge* e = startEdge;
+ do {
+#ifdef SHOW_ITERATIONS
+ n++;
+#endif
+ Rational128 dot = e->target->dot(normal);
+ btAssert(dot.compare(origDot) <= 0);
+#ifdef DEBUG_CONVEX_HULL
+ printf("Moving downwards, edge is ");
+ e->print();
+ printf(", dot is %f (%f %lld)\n", (float)dot.toScalar(), (float)optDot.toScalar(), shiftedDot);
+#endif
+ if (dot.compare(optDot) < 0) {
+ int32_t c = dot.compare(shiftedDot);
+ optDot = dot;
+ e = e->reverse;
+ startEdge = e;
+ if (c < 0) {
+ intersection = e;
+ break;
+ }
+ cmp = c;
+ }
+ e = e->prev;
+ } while (e != startEdge);
+
+ if (!intersection) {
+ return false;
+ }
+ }
+ else {
+ Edge* e = startEdge;
+ do {
+#ifdef SHOW_ITERATIONS
+ n++;
+#endif
+ Rational128 dot = e->target->dot(normal);
+ btAssert(dot.compare(origDot) <= 0);
+#ifdef DEBUG_CONVEX_HULL
+ printf("Moving upwards, edge is ");
+ e->print();
+ printf(", dot is %f (%f %lld)\n", (float)dot.toScalar(), (float)optDot.toScalar(), shiftedDot);
+#endif
+ if (dot.compare(optDot) > 0) {
+ cmp = dot.compare(shiftedDot);
+ if (cmp >= 0) {
+ intersection = e;
+ break;
+ }
+ optDot = dot;
+ e = e->reverse;
+ startEdge = e;
+ }
+ e = e->prev;
+ } while (e != startEdge);
+
+ if (!intersection) {
+ return true;
+ }
+ }
+
+#ifdef SHOW_ITERATIONS
+ printf("Needed %d iterations to find initial intersection\n", n);
+#endif
+
+ if (cmp == 0) {
+ Edge* e = intersection->reverse->next;
+#ifdef SHOW_ITERATIONS
+ n = 0;
+#endif
+ while (e->target->dot(normal).compare(shiftedDot) <= 0) {
+#ifdef SHOW_ITERATIONS
+ n++;
+#endif
+ e = e->next;
+ if (e == intersection->reverse) {
+ return true;
+ }
+#ifdef DEBUG_CONVEX_HULL
+ printf("Checking for outwards edge, current edge is ");
+ e->print();
+ printf("\n");
+#endif
+ }
+#ifdef SHOW_ITERATIONS
+ printf("Needed %d iterations to check for complete containment\n", n);
+#endif
+ }
+
+ Edge* firstIntersection = NULL;
+ Edge* faceEdge = NULL;
+ Edge* firstFaceEdge = NULL;
+
+#ifdef SHOW_ITERATIONS
+ int32_t m = 0;
+#endif
+ while (true) {
+#ifdef SHOW_ITERATIONS
+ m++;
+#endif
+#ifdef DEBUG_CONVEX_HULL
+ printf("Intersecting edge is ");
+ intersection->print();
+ printf("\n");
+#endif
+ if (cmp == 0) {
+ Edge* e = intersection->reverse->next;
+ startEdge = e;
+#ifdef SHOW_ITERATIONS
+ n = 0;
+#endif
+ while (true) {
+#ifdef SHOW_ITERATIONS
+ n++;
+#endif
+ if (e->target->dot(normal).compare(shiftedDot) >= 0) {
+ break;
+ }
+ intersection = e->reverse;
+ e = e->next;
+ if (e == startEdge) {
+ return true;
+ }
+ }
+#ifdef SHOW_ITERATIONS
+ printf("Needed %d iterations to advance intersection\n", n);
+#endif
+ }
+
+#ifdef DEBUG_CONVEX_HULL
+ printf("Advanced intersecting edge to ");
+ intersection->print();
+ printf(", cmp = %d\n", cmp);
+#endif
+
+ if (!firstIntersection) {
+ firstIntersection = intersection;
+ }
+ else if (intersection == firstIntersection) {
+ break;
+ }
+
+ int32_t prevCmp = cmp;
+ Edge* prevIntersection = intersection;
+ Edge* prevFaceEdge = faceEdge;
+
+ Edge* e = intersection->reverse;
+#ifdef SHOW_ITERATIONS
+ n = 0;
+#endif
+ while (true) {
+#ifdef SHOW_ITERATIONS
+ n++;
+#endif
+ e = e->reverse->prev;
+ btAssert(e != intersection->reverse);
+ cmp = e->target->dot(normal).compare(shiftedDot);
+#ifdef DEBUG_CONVEX_HULL
+ printf("Testing edge ");
+ e->print();
+ printf(" -> cmp = %d\n", cmp);
+#endif
+ if (cmp >= 0) {
+ intersection = e;
+ break;
+ }
+ }
+#ifdef SHOW_ITERATIONS
+ printf("Needed %d iterations to find other intersection of face\n", n);
+#endif
+
+ if (cmp > 0) {
+ Vertex* removed = intersection->target;
+ e = intersection->reverse;
+ if (e->prev == e) {
+ removed->edges = NULL;
+ }
+ else {
+ removed->edges = e->prev;
+ e->prev->link(e->next);
+ e->link(e);
+ }
+#ifdef DEBUG_CONVEX_HULL
+ printf("1: Removed part contains (%d %d %d)\n", removed->point.x, removed->point.y, removed->point.z);
+#endif
+
+ Point64 n0 = intersection->face->getNormal();
+ Point64 n1 = intersection->reverse->face->getNormal();
+ int64_t m00 = face->dir0.dot(n0);
+ int64_t m01 = face->dir1.dot(n0);
+ int64_t m10 = face->dir0.dot(n1);
+ int64_t m11 = face->dir1.dot(n1);
+ int64_t r0 = (intersection->face->origin - shiftedOrigin).dot(n0);
+ int64_t r1 = (intersection->reverse->face->origin - shiftedOrigin).dot(n1);
+ Int128 det = Int128::mul(m00, m11) - Int128::mul(m01, m10);
+ btAssert(det.getSign() != 0);
+ Vertex* v = vertexPool.newObject();
+ v->point.index = -1;
+ v->copy = -1;
+ v->point128 = PointR128(Int128::mul(face->dir0.x * r0, m11) - Int128::mul(face->dir0.x * r1, m01)
+ + Int128::mul(face->dir1.x * r1, m00) - Int128::mul(face->dir1.x * r0, m10) + det * shiftedOrigin.x,
+ Int128::mul(face->dir0.y * r0, m11) - Int128::mul(face->dir0.y * r1, m01)
+ + Int128::mul(face->dir1.y * r1, m00) - Int128::mul(face->dir1.y * r0, m10) + det * shiftedOrigin.y,
+ Int128::mul(face->dir0.z * r0, m11) - Int128::mul(face->dir0.z * r1, m01)
+ + Int128::mul(face->dir1.z * r1, m00) - Int128::mul(face->dir1.z * r0, m10) + det * shiftedOrigin.z,
+ det);
+ v->point.x = (int32_t)v->point128.xvalue();
+ v->point.y = (int32_t)v->point128.yvalue();
+ v->point.z = (int32_t)v->point128.zvalue();
+ intersection->target = v;
+ v->edges = e;
+
+ stack.push_back(v);
+ stack.push_back(removed);
+ stack.push_back(NULL);
+ }
+
+ if (cmp || prevCmp || (prevIntersection->reverse->next->target != intersection->target)) {
+ faceEdge = newEdgePair(prevIntersection->target, intersection->target);
+ if (prevCmp == 0) {
+ faceEdge->link(prevIntersection->reverse->next);
+ }
+ if ((prevCmp == 0) || prevFaceEdge) {
+ prevIntersection->reverse->link(faceEdge);
+ }
+ if (cmp == 0) {
+ intersection->reverse->prev->link(faceEdge->reverse);
+ }
+ faceEdge->reverse->link(intersection->reverse);
+ }
+ else {
+ faceEdge = prevIntersection->reverse->next;
+ }
+
+ if (prevFaceEdge) {
+ if (prevCmp > 0) {
+ faceEdge->link(prevFaceEdge->reverse);
+ }
+ else if (faceEdge != prevFaceEdge->reverse) {
+ stack.push_back(prevFaceEdge->target);
+ while (faceEdge->next != prevFaceEdge->reverse) {
+ Vertex* removed = faceEdge->next->target;
+ removeEdgePair(faceEdge->next);
+ stack.push_back(removed);
+#ifdef DEBUG_CONVEX_HULL
+ printf("2: Removed part contains (%d %d %d)\n", removed->point.x, removed->point.y, removed->point.z);
+#endif
+ }
+ stack.push_back(NULL);
+ }
+ }
+ faceEdge->face = face;
+ faceEdge->reverse->face = intersection->face;
+
+ if (!firstFaceEdge) {
+ firstFaceEdge = faceEdge;
+ }
+ }
+#ifdef SHOW_ITERATIONS
+ printf("Needed %d iterations to process all intersections\n", m);
+#endif
+
+ if (cmp > 0) {
+ firstFaceEdge->reverse->target = faceEdge->target;
+ firstIntersection->reverse->link(firstFaceEdge);
+ firstFaceEdge->link(faceEdge->reverse);
+ }
+ else if (firstFaceEdge != faceEdge->reverse) {
+ stack.push_back(faceEdge->target);
+ while (firstFaceEdge->next != faceEdge->reverse) {
+ Vertex* removed = firstFaceEdge->next->target;
+ removeEdgePair(firstFaceEdge->next);
+ stack.push_back(removed);
+#ifdef DEBUG_CONVEX_HULL
+ printf("3: Removed part contains (%d %d %d)\n", removed->point.x, removed->point.y, removed->point.z);
+#endif
+ }
+ stack.push_back(NULL);
+ }
+
+ btAssert(stack.size() > 0);
+ vertexList = stack[0];
+
+#ifdef DEBUG_CONVEX_HULL
+ printf("Removing part\n");
+#endif
+#ifdef SHOW_ITERATIONS
+ n = 0;
+#endif
+ int32_t pos = 0;
+ while (pos < stack.size()) {
+ int32_t end = stack.size();
+ while (pos < end) {
+ Vertex* kept = stack[pos++];
+#ifdef DEBUG_CONVEX_HULL
+ kept->print();
+#endif
+ bool deeper = false;
+ Vertex* removed;
+ while ((removed = stack[pos++]) != NULL) {
+#ifdef SHOW_ITERATIONS
+ n++;
+#endif
+ kept->receiveNearbyFaces(removed);
+ while (removed->edges) {
+ if (!deeper) {
+ deeper = true;
+ stack.push_back(kept);
+ }
+ stack.push_back(removed->edges->target);
+ removeEdgePair(removed->edges);
+ }
+ }
+ if (deeper) {
+ stack.push_back(NULL);
+ }
+ }
+ }
+#ifdef SHOW_ITERATIONS
+ printf("Needed %d iterations to remove part\n", n);
+#endif
+
+ stack.resize(0);
+ face->origin = shiftedOrigin;
+
+ return true;
+}
+
+static int32_t getVertexCopy(btConvexHullInternal::Vertex* vertex, btAlignedObjectArray<btConvexHullInternal::Vertex*>& vertices)
+{
+ int32_t index = vertex->copy;
+ if (index < 0) {
+ index = vertices.size();
+ vertex->copy = index;
+ vertices.push_back(vertex);
+#ifdef DEBUG_CONVEX_HULL
+ printf("Vertex %d gets index *%d\n", vertex->point.index, index);
+#endif
+ }
+ return index;
+}
+
+btScalar btConvexHullComputer::compute(const void* coords, bool doubleCoords, int32_t stride, int32_t count, btScalar shrink, btScalar shrinkClamp)
+{
+ if (count <= 0) {
+ vertices.clear();
+ edges.clear();
+ faces.clear();
+ return 0;
+ }
+
+ btConvexHullInternal hull;
+ hull.compute(coords, doubleCoords, stride, count);
+
+ btScalar shift = 0;
+ if ((shrink > 0) && ((shift = hull.shrink(shrink, shrinkClamp)) < 0)) {
+ vertices.clear();
+ edges.clear();
+ faces.clear();
+ return shift;
+ }
+
+ vertices.resize(0);
+ edges.resize(0);
+ faces.resize(0);
+
+ btAlignedObjectArray<btConvexHullInternal::Vertex*> oldVertices;
+ getVertexCopy(hull.vertexList, oldVertices);
+ int32_t copied = 0;
+ while (copied < oldVertices.size()) {
+ btConvexHullInternal::Vertex* v = oldVertices[copied];
+ vertices.push_back(hull.getCoordinates(v));
+ btConvexHullInternal::Edge* firstEdge = v->edges;
+ if (firstEdge) {
+ int32_t firstCopy = -1;
+ int32_t prevCopy = -1;
+ btConvexHullInternal::Edge* e = firstEdge;
+ do {
+ if (e->copy < 0) {
+ int32_t s = edges.size();
+ edges.push_back(Edge());
+ edges.push_back(Edge());
+ Edge* c = &edges[s];
+ Edge* r = &edges[s + 1];
+ e->copy = s;
+ e->reverse->copy = s + 1;
+ c->reverse = 1;
+ r->reverse = -1;
+ c->targetVertex = getVertexCopy(e->target, oldVertices);
+ r->targetVertex = copied;
+#ifdef DEBUG_CONVEX_HULL
+ printf(" CREATE: Vertex *%d has edge to *%d\n", copied, c->getTargetVertex());
+#endif
+ }
+ if (prevCopy >= 0) {
+ edges[e->copy].next = prevCopy - e->copy;
+ }
+ else {
+ firstCopy = e->copy;
+ }
+ prevCopy = e->copy;
+ e = e->next;
+ } while (e != firstEdge);
+ edges[firstCopy].next = prevCopy - firstCopy;
+ }
+ copied++;
+ }
+
+ for (int32_t i = 0; i < copied; i++) {
+ btConvexHullInternal::Vertex* v = oldVertices[i];
+ btConvexHullInternal::Edge* firstEdge = v->edges;
+ if (firstEdge) {
+ btConvexHullInternal::Edge* e = firstEdge;
+ do {
+ if (e->copy >= 0) {
+#ifdef DEBUG_CONVEX_HULL
+ printf("Vertex *%d has edge to *%d\n", i, edges[e->copy].getTargetVertex());
+#endif
+ faces.push_back(e->copy);
+ btConvexHullInternal::Edge* f = e;
+ do {
+#ifdef DEBUG_CONVEX_HULL
+ printf(" Face *%d\n", edges[f->copy].getTargetVertex());
+#endif
+ f->copy = -1;
+ f = f->reverse->prev;
+ } while (f != e);
+ }
+ e = e->next;
+ } while (e != firstEdge);
+ }
+ }
+
+ return shift;
+}
+
+// -- GODOT start --
+}; // namespace VHACD
+// -- GODOT end --
diff --git a/thirdparty/vhacd/src/vhacdICHull.cpp b/thirdparty/vhacd/src/vhacdICHull.cpp
new file mode 100644
index 0000000000..989587c124
--- /dev/null
+++ b/thirdparty/vhacd/src/vhacdICHull.cpp
@@ -0,0 +1,731 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#include "vhacdICHull.h"
+#include <limits>
+
+#ifdef _MSC_VER
+#pragma warning(disable:4456 4706)
+#endif
+
+
+namespace VHACD {
+const double ICHull::sc_eps = 1.0e-15;
+const int32_t ICHull::sc_dummyIndex = std::numeric_limits<int32_t>::max();
+ICHull::ICHull()
+{
+ m_isFlat = false;
+}
+bool ICHull::AddPoints(const Vec3<double>* points, size_t nPoints)
+{
+ if (!points) {
+ return false;
+ }
+ CircularListElement<TMMVertex>* vertex = NULL;
+ for (size_t i = 0; i < nPoints; i++) {
+ vertex = m_mesh.AddVertex();
+ vertex->GetData().m_pos.X() = points[i].X();
+ vertex->GetData().m_pos.Y() = points[i].Y();
+ vertex->GetData().m_pos.Z() = points[i].Z();
+ vertex->GetData().m_name = static_cast<int32_t>(i);
+ }
+ return true;
+}
+bool ICHull::AddPoint(const Vec3<double>& point, int32_t id)
+{
+ if (AddPoints(&point, 1)) {
+ m_mesh.m_vertices.GetData().m_name = id;
+ return true;
+ }
+ return false;
+}
+
+ICHullError ICHull::Process()
+{
+ uint32_t addedPoints = 0;
+ if (m_mesh.GetNVertices() < 3) {
+ return ICHullErrorNotEnoughPoints;
+ }
+ if (m_mesh.GetNVertices() == 3) {
+ m_isFlat = true;
+ CircularListElement<TMMTriangle>* t1 = m_mesh.AddTriangle();
+ CircularListElement<TMMTriangle>* t2 = m_mesh.AddTriangle();
+ CircularListElement<TMMVertex>* v0 = m_mesh.m_vertices.GetHead();
+ CircularListElement<TMMVertex>* v1 = v0->GetNext();
+ CircularListElement<TMMVertex>* v2 = v1->GetNext();
+ // Compute the normal to the plane
+ Vec3<double> p0 = v0->GetData().m_pos;
+ Vec3<double> p1 = v1->GetData().m_pos;
+ Vec3<double> p2 = v2->GetData().m_pos;
+ m_normal = (p1 - p0) ^ (p2 - p0);
+ m_normal.Normalize();
+ t1->GetData().m_vertices[0] = v0;
+ t1->GetData().m_vertices[1] = v1;
+ t1->GetData().m_vertices[2] = v2;
+ t2->GetData().m_vertices[0] = v1;
+ t2->GetData().m_vertices[1] = v2;
+ t2->GetData().m_vertices[2] = v2;
+ return ICHullErrorOK;
+ }
+ if (m_isFlat) {
+ m_mesh.m_edges.Clear();
+ m_mesh.m_triangles.Clear();
+ m_isFlat = false;
+ }
+ if (m_mesh.GetNTriangles() == 0) // we have to create the first polyhedron
+ {
+ ICHullError res = DoubleTriangle();
+ if (res != ICHullErrorOK) {
+ return res;
+ }
+ else {
+ addedPoints += 3;
+ }
+ }
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ // go to the first added and not processed vertex
+ while (!(vertices.GetHead()->GetPrev()->GetData().m_tag)) {
+ vertices.Prev();
+ }
+ while (!vertices.GetData().m_tag) // not processed
+ {
+ vertices.GetData().m_tag = true;
+ if (ProcessPoint()) {
+ addedPoints++;
+ CleanUp(addedPoints);
+ vertices.Next();
+ if (!GetMesh().CheckConsistancy()) {
+ size_t nV = m_mesh.GetNVertices();
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ for (size_t v = 0; v < nV; ++v) {
+ if (vertices.GetData().m_name == sc_dummyIndex) {
+ vertices.Delete();
+ break;
+ }
+ vertices.Next();
+ }
+ return ICHullErrorInconsistent;
+ }
+ }
+ }
+ if (m_isFlat) {
+ SArray<CircularListElement<TMMTriangle>*> trianglesToDuplicate;
+ size_t nT = m_mesh.GetNTriangles();
+ for (size_t f = 0; f < nT; f++) {
+ TMMTriangle& currentTriangle = m_mesh.m_triangles.GetHead()->GetData();
+ if (currentTriangle.m_vertices[0]->GetData().m_name == sc_dummyIndex || currentTriangle.m_vertices[1]->GetData().m_name == sc_dummyIndex || currentTriangle.m_vertices[2]->GetData().m_name == sc_dummyIndex) {
+ m_trianglesToDelete.PushBack(m_mesh.m_triangles.GetHead());
+ for (int32_t k = 0; k < 3; k++) {
+ for (int32_t h = 0; h < 2; h++) {
+ if (currentTriangle.m_edges[k]->GetData().m_triangles[h] == m_mesh.m_triangles.GetHead()) {
+ currentTriangle.m_edges[k]->GetData().m_triangles[h] = 0;
+ break;
+ }
+ }
+ }
+ }
+ else {
+ trianglesToDuplicate.PushBack(m_mesh.m_triangles.GetHead());
+ }
+ m_mesh.m_triangles.Next();
+ }
+ size_t nE = m_mesh.GetNEdges();
+ for (size_t e = 0; e < nE; e++) {
+ TMMEdge& currentEdge = m_mesh.m_edges.GetHead()->GetData();
+ if (currentEdge.m_triangles[0] == 0 && currentEdge.m_triangles[1] == 0) {
+ m_edgesToDelete.PushBack(m_mesh.m_edges.GetHead());
+ }
+ m_mesh.m_edges.Next();
+ }
+ size_t nV = m_mesh.GetNVertices();
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ for (size_t v = 0; v < nV; ++v) {
+ if (vertices.GetData().m_name == sc_dummyIndex) {
+ vertices.Delete();
+ }
+ else {
+ vertices.GetData().m_tag = false;
+ vertices.Next();
+ }
+ }
+ CleanEdges();
+ CleanTriangles();
+ CircularListElement<TMMTriangle>* newTriangle;
+ for (size_t t = 0; t < trianglesToDuplicate.Size(); t++) {
+ newTriangle = m_mesh.AddTriangle();
+ newTriangle->GetData().m_vertices[0] = trianglesToDuplicate[t]->GetData().m_vertices[1];
+ newTriangle->GetData().m_vertices[1] = trianglesToDuplicate[t]->GetData().m_vertices[0];
+ newTriangle->GetData().m_vertices[2] = trianglesToDuplicate[t]->GetData().m_vertices[2];
+ }
+ }
+ return ICHullErrorOK;
+}
+ICHullError ICHull::Process(const uint32_t nPointsCH,
+ const double minVolume)
+{
+ uint32_t addedPoints = 0;
+ if (nPointsCH < 3 || m_mesh.GetNVertices() < 3) {
+ return ICHullErrorNotEnoughPoints;
+ }
+ if (m_mesh.GetNVertices() == 3) {
+ m_isFlat = true;
+ CircularListElement<TMMTriangle>* t1 = m_mesh.AddTriangle();
+ CircularListElement<TMMTriangle>* t2 = m_mesh.AddTriangle();
+ CircularListElement<TMMVertex>* v0 = m_mesh.m_vertices.GetHead();
+ CircularListElement<TMMVertex>* v1 = v0->GetNext();
+ CircularListElement<TMMVertex>* v2 = v1->GetNext();
+ // Compute the normal to the plane
+ Vec3<double> p0 = v0->GetData().m_pos;
+ Vec3<double> p1 = v1->GetData().m_pos;
+ Vec3<double> p2 = v2->GetData().m_pos;
+ m_normal = (p1 - p0) ^ (p2 - p0);
+ m_normal.Normalize();
+ t1->GetData().m_vertices[0] = v0;
+ t1->GetData().m_vertices[1] = v1;
+ t1->GetData().m_vertices[2] = v2;
+ t2->GetData().m_vertices[0] = v1;
+ t2->GetData().m_vertices[1] = v0;
+ t2->GetData().m_vertices[2] = v2;
+ return ICHullErrorOK;
+ }
+
+ if (m_isFlat) {
+ m_mesh.m_triangles.Clear();
+ m_mesh.m_edges.Clear();
+ m_isFlat = false;
+ }
+
+ if (m_mesh.GetNTriangles() == 0) // we have to create the first polyhedron
+ {
+ ICHullError res = DoubleTriangle();
+ if (res != ICHullErrorOK) {
+ return res;
+ }
+ else {
+ addedPoints += 3;
+ }
+ }
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ while (!vertices.GetData().m_tag && addedPoints < nPointsCH) // not processed
+ {
+ if (!FindMaxVolumePoint((addedPoints > 4) ? minVolume : 0.0)) {
+ break;
+ }
+ vertices.GetData().m_tag = true;
+ if (ProcessPoint()) {
+ addedPoints++;
+ CleanUp(addedPoints);
+ if (!GetMesh().CheckConsistancy()) {
+ size_t nV = m_mesh.GetNVertices();
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ for (size_t v = 0; v < nV; ++v) {
+ if (vertices.GetData().m_name == sc_dummyIndex) {
+ vertices.Delete();
+ break;
+ }
+ vertices.Next();
+ }
+ return ICHullErrorInconsistent;
+ }
+ vertices.Next();
+ }
+ }
+ // delete remaining points
+ while (!vertices.GetData().m_tag) {
+ vertices.Delete();
+ }
+ if (m_isFlat) {
+ SArray<CircularListElement<TMMTriangle>*> trianglesToDuplicate;
+ size_t nT = m_mesh.GetNTriangles();
+ for (size_t f = 0; f < nT; f++) {
+ TMMTriangle& currentTriangle = m_mesh.m_triangles.GetHead()->GetData();
+ if (currentTriangle.m_vertices[0]->GetData().m_name == sc_dummyIndex || currentTriangle.m_vertices[1]->GetData().m_name == sc_dummyIndex || currentTriangle.m_vertices[2]->GetData().m_name == sc_dummyIndex) {
+ m_trianglesToDelete.PushBack(m_mesh.m_triangles.GetHead());
+ for (int32_t k = 0; k < 3; k++) {
+ for (int32_t h = 0; h < 2; h++) {
+ if (currentTriangle.m_edges[k]->GetData().m_triangles[h] == m_mesh.m_triangles.GetHead()) {
+ currentTriangle.m_edges[k]->GetData().m_triangles[h] = 0;
+ break;
+ }
+ }
+ }
+ }
+ else {
+ trianglesToDuplicate.PushBack(m_mesh.m_triangles.GetHead());
+ }
+ m_mesh.m_triangles.Next();
+ }
+ size_t nE = m_mesh.GetNEdges();
+ for (size_t e = 0; e < nE; e++) {
+ TMMEdge& currentEdge = m_mesh.m_edges.GetHead()->GetData();
+ if (currentEdge.m_triangles[0] == 0 && currentEdge.m_triangles[1] == 0) {
+ m_edgesToDelete.PushBack(m_mesh.m_edges.GetHead());
+ }
+ m_mesh.m_edges.Next();
+ }
+ size_t nV = m_mesh.GetNVertices();
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ for (size_t v = 0; v < nV; ++v) {
+ if (vertices.GetData().m_name == sc_dummyIndex) {
+ vertices.Delete();
+ }
+ else {
+ vertices.GetData().m_tag = false;
+ vertices.Next();
+ }
+ }
+ CleanEdges();
+ CleanTriangles();
+ CircularListElement<TMMTriangle>* newTriangle;
+ for (size_t t = 0; t < trianglesToDuplicate.Size(); t++) {
+ newTriangle = m_mesh.AddTriangle();
+ newTriangle->GetData().m_vertices[0] = trianglesToDuplicate[t]->GetData().m_vertices[1];
+ newTriangle->GetData().m_vertices[1] = trianglesToDuplicate[t]->GetData().m_vertices[0];
+ newTriangle->GetData().m_vertices[2] = trianglesToDuplicate[t]->GetData().m_vertices[2];
+ }
+ }
+ return ICHullErrorOK;
+}
+bool ICHull::FindMaxVolumePoint(const double minVolume)
+{
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ CircularListElement<TMMVertex>* vMaxVolume = 0;
+ CircularListElement<TMMVertex>* vHeadPrev = vertices.GetHead()->GetPrev();
+
+ double maxVolume = minVolume;
+ double volume = 0.0;
+ while (!vertices.GetData().m_tag) // not processed
+ {
+ if (ComputePointVolume(volume, false)) {
+ if (maxVolume < volume) {
+ maxVolume = volume;
+ vMaxVolume = vertices.GetHead();
+ }
+ vertices.Next();
+ }
+ }
+ CircularListElement<TMMVertex>* vHead = vHeadPrev->GetNext();
+ vertices.GetHead() = vHead;
+ if (!vMaxVolume) {
+ return false;
+ }
+ if (vMaxVolume != vHead) {
+ Vec3<double> pos = vHead->GetData().m_pos;
+ int32_t id = vHead->GetData().m_name;
+ vHead->GetData().m_pos = vMaxVolume->GetData().m_pos;
+ vHead->GetData().m_name = vMaxVolume->GetData().m_name;
+ vMaxVolume->GetData().m_pos = pos;
+ vHead->GetData().m_name = id;
+ }
+ return true;
+}
+ICHullError ICHull::DoubleTriangle()
+{
+ // find three non colinear points
+ m_isFlat = false;
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ CircularListElement<TMMVertex>* v0 = vertices.GetHead();
+ while (Colinear(v0->GetData().m_pos,
+ v0->GetNext()->GetData().m_pos,
+ v0->GetNext()->GetNext()->GetData().m_pos)) {
+ if ((v0 = v0->GetNext()) == vertices.GetHead()) {
+ return ICHullErrorCoplanarPoints;
+ }
+ }
+ CircularListElement<TMMVertex>* v1 = v0->GetNext();
+ CircularListElement<TMMVertex>* v2 = v1->GetNext();
+ // mark points as processed
+ v0->GetData().m_tag = v1->GetData().m_tag = v2->GetData().m_tag = true;
+
+ // create two triangles
+ CircularListElement<TMMTriangle>* f0 = MakeFace(v0, v1, v2, 0);
+ MakeFace(v2, v1, v0, f0);
+
+ // find a fourth non-coplanar point to form tetrahedron
+ CircularListElement<TMMVertex>* v3 = v2->GetNext();
+ vertices.GetHead() = v3;
+
+ double vol = ComputeVolume4(v0->GetData().m_pos, v1->GetData().m_pos, v2->GetData().m_pos, v3->GetData().m_pos);
+ while (fabs(vol) < sc_eps && !v3->GetNext()->GetData().m_tag) {
+ v3 = v3->GetNext();
+ vol = ComputeVolume4(v0->GetData().m_pos, v1->GetData().m_pos, v2->GetData().m_pos, v3->GetData().m_pos);
+ }
+ if (fabs(vol) < sc_eps) {
+ // compute the barycenter
+ Vec3<double> bary(0.0, 0.0, 0.0);
+ CircularListElement<TMMVertex>* vBary = v0;
+ do {
+ bary += vBary->GetData().m_pos;
+ } while ((vBary = vBary->GetNext()) != v0);
+ bary /= static_cast<double>(vertices.GetSize());
+
+ // Compute the normal to the plane
+ Vec3<double> p0 = v0->GetData().m_pos;
+ Vec3<double> p1 = v1->GetData().m_pos;
+ Vec3<double> p2 = v2->GetData().m_pos;
+ m_normal = (p1 - p0) ^ (p2 - p0);
+ m_normal.Normalize();
+ // add dummy vertex placed at (bary + normal)
+ vertices.GetHead() = v2;
+ Vec3<double> newPt = bary + m_normal;
+ AddPoint(newPt, sc_dummyIndex);
+ m_isFlat = true;
+ return ICHullErrorOK;
+ }
+ else if (v3 != vertices.GetHead()) {
+ TMMVertex temp;
+ temp.m_name = v3->GetData().m_name;
+ temp.m_pos = v3->GetData().m_pos;
+ v3->GetData().m_name = vertices.GetHead()->GetData().m_name;
+ v3->GetData().m_pos = vertices.GetHead()->GetData().m_pos;
+ vertices.GetHead()->GetData().m_name = temp.m_name;
+ vertices.GetHead()->GetData().m_pos = temp.m_pos;
+ }
+ return ICHullErrorOK;
+}
+CircularListElement<TMMTriangle>* ICHull::MakeFace(CircularListElement<TMMVertex>* v0,
+ CircularListElement<TMMVertex>* v1,
+ CircularListElement<TMMVertex>* v2,
+ CircularListElement<TMMTriangle>* fold)
+{
+ CircularListElement<TMMEdge>* e0;
+ CircularListElement<TMMEdge>* e1;
+ CircularListElement<TMMEdge>* e2;
+ int32_t index = 0;
+ if (!fold) // if first face to be created
+ {
+ e0 = m_mesh.AddEdge(); // create the three edges
+ e1 = m_mesh.AddEdge();
+ e2 = m_mesh.AddEdge();
+ }
+ else // otherwise re-use existing edges (in reverse order)
+ {
+ e0 = fold->GetData().m_edges[2];
+ e1 = fold->GetData().m_edges[1];
+ e2 = fold->GetData().m_edges[0];
+ index = 1;
+ }
+ e0->GetData().m_vertices[0] = v0;
+ e0->GetData().m_vertices[1] = v1;
+ e1->GetData().m_vertices[0] = v1;
+ e1->GetData().m_vertices[1] = v2;
+ e2->GetData().m_vertices[0] = v2;
+ e2->GetData().m_vertices[1] = v0;
+ // create the new face
+ CircularListElement<TMMTriangle>* f = m_mesh.AddTriangle();
+ f->GetData().m_edges[0] = e0;
+ f->GetData().m_edges[1] = e1;
+ f->GetData().m_edges[2] = e2;
+ f->GetData().m_vertices[0] = v0;
+ f->GetData().m_vertices[1] = v1;
+ f->GetData().m_vertices[2] = v2;
+ // link edges to face f
+ e0->GetData().m_triangles[index] = e1->GetData().m_triangles[index] = e2->GetData().m_triangles[index] = f;
+ return f;
+}
+CircularListElement<TMMTriangle>* ICHull::MakeConeFace(CircularListElement<TMMEdge>* e, CircularListElement<TMMVertex>* p)
+{
+ // create two new edges if they don't already exist
+ CircularListElement<TMMEdge>* newEdges[2];
+ for (int32_t i = 0; i < 2; ++i) {
+ if (!(newEdges[i] = e->GetData().m_vertices[i]->GetData().m_duplicate)) { // if the edge doesn't exits add it and mark the vertex as duplicated
+ newEdges[i] = m_mesh.AddEdge();
+ newEdges[i]->GetData().m_vertices[0] = e->GetData().m_vertices[i];
+ newEdges[i]->GetData().m_vertices[1] = p;
+ e->GetData().m_vertices[i]->GetData().m_duplicate = newEdges[i];
+ }
+ }
+ // make the new face
+ CircularListElement<TMMTriangle>* newFace = m_mesh.AddTriangle();
+ newFace->GetData().m_edges[0] = e;
+ newFace->GetData().m_edges[1] = newEdges[0];
+ newFace->GetData().m_edges[2] = newEdges[1];
+ MakeCCW(newFace, e, p);
+ for (int32_t i = 0; i < 2; ++i) {
+ for (int32_t j = 0; j < 2; ++j) {
+ if (!newEdges[i]->GetData().m_triangles[j]) {
+ newEdges[i]->GetData().m_triangles[j] = newFace;
+ break;
+ }
+ }
+ }
+ return newFace;
+}
+bool ICHull::ComputePointVolume(double& totalVolume, bool markVisibleFaces)
+{
+ // mark visible faces
+ CircularListElement<TMMTriangle>* fHead = m_mesh.GetTriangles().GetHead();
+ CircularListElement<TMMTriangle>* f = fHead;
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ CircularListElement<TMMVertex>* vertex0 = vertices.GetHead();
+ bool visible = false;
+ Vec3<double> pos0 = Vec3<double>(vertex0->GetData().m_pos.X(),
+ vertex0->GetData().m_pos.Y(),
+ vertex0->GetData().m_pos.Z());
+ double vol = 0.0;
+ totalVolume = 0.0;
+ Vec3<double> ver0, ver1, ver2;
+ do {
+ ver0.X() = f->GetData().m_vertices[0]->GetData().m_pos.X();
+ ver0.Y() = f->GetData().m_vertices[0]->GetData().m_pos.Y();
+ ver0.Z() = f->GetData().m_vertices[0]->GetData().m_pos.Z();
+ ver1.X() = f->GetData().m_vertices[1]->GetData().m_pos.X();
+ ver1.Y() = f->GetData().m_vertices[1]->GetData().m_pos.Y();
+ ver1.Z() = f->GetData().m_vertices[1]->GetData().m_pos.Z();
+ ver2.X() = f->GetData().m_vertices[2]->GetData().m_pos.X();
+ ver2.Y() = f->GetData().m_vertices[2]->GetData().m_pos.Y();
+ ver2.Z() = f->GetData().m_vertices[2]->GetData().m_pos.Z();
+ vol = ComputeVolume4(ver0, ver1, ver2, pos0);
+ if (vol < -sc_eps) {
+ vol = fabs(vol);
+ totalVolume += vol;
+ if (markVisibleFaces) {
+ f->GetData().m_visible = true;
+ m_trianglesToDelete.PushBack(f);
+ }
+ visible = true;
+ }
+ f = f->GetNext();
+ } while (f != fHead);
+
+ if (m_trianglesToDelete.Size() == m_mesh.m_triangles.GetSize()) {
+ for (size_t i = 0; i < m_trianglesToDelete.Size(); i++) {
+ m_trianglesToDelete[i]->GetData().m_visible = false;
+ }
+ visible = false;
+ }
+ // if no faces visible from p then p is inside the hull
+ if (!visible && markVisibleFaces) {
+ vertices.Delete();
+ m_trianglesToDelete.Resize(0);
+ return false;
+ }
+ return true;
+}
+bool ICHull::ProcessPoint()
+{
+ double totalVolume = 0.0;
+ if (!ComputePointVolume(totalVolume, true)) {
+ return false;
+ }
+ // Mark edges in interior of visible region for deletion.
+ // Create a new face based on each border edge
+ CircularListElement<TMMVertex>* v0 = m_mesh.GetVertices().GetHead();
+ CircularListElement<TMMEdge>* eHead = m_mesh.GetEdges().GetHead();
+ CircularListElement<TMMEdge>* e = eHead;
+ CircularListElement<TMMEdge>* tmp = 0;
+ int32_t nvisible = 0;
+ m_edgesToDelete.Resize(0);
+ m_edgesToUpdate.Resize(0);
+ do {
+ tmp = e->GetNext();
+ nvisible = 0;
+ for (int32_t k = 0; k < 2; k++) {
+ if (e->GetData().m_triangles[k]->GetData().m_visible) {
+ nvisible++;
+ }
+ }
+ if (nvisible == 2) {
+ m_edgesToDelete.PushBack(e);
+ }
+ else if (nvisible == 1) {
+ e->GetData().m_newFace = MakeConeFace(e, v0);
+ m_edgesToUpdate.PushBack(e);
+ }
+ e = tmp;
+ } while (e != eHead);
+ return true;
+}
+bool ICHull::MakeCCW(CircularListElement<TMMTriangle>* f,
+ CircularListElement<TMMEdge>* e,
+ CircularListElement<TMMVertex>* v)
+{
+ // the visible face adjacent to e
+ CircularListElement<TMMTriangle>* fv;
+ if (e->GetData().m_triangles[0]->GetData().m_visible) {
+ fv = e->GetData().m_triangles[0];
+ }
+ else {
+ fv = e->GetData().m_triangles[1];
+ }
+
+ // set vertex[0] and vertex[1] to have the same orientation as the corresponding vertices of fv.
+ int32_t i; // index of e->m_vertices[0] in fv
+ CircularListElement<TMMVertex>* v0 = e->GetData().m_vertices[0];
+ CircularListElement<TMMVertex>* v1 = e->GetData().m_vertices[1];
+ for (i = 0; fv->GetData().m_vertices[i] != v0; i++)
+ ;
+
+ if (fv->GetData().m_vertices[(i + 1) % 3] != e->GetData().m_vertices[1]) {
+ f->GetData().m_vertices[0] = v1;
+ f->GetData().m_vertices[1] = v0;
+ }
+ else {
+ f->GetData().m_vertices[0] = v0;
+ f->GetData().m_vertices[1] = v1;
+ // swap edges
+ CircularListElement<TMMEdge>* tmp = f->GetData().m_edges[0];
+ f->GetData().m_edges[0] = f->GetData().m_edges[1];
+ f->GetData().m_edges[1] = tmp;
+ }
+ f->GetData().m_vertices[2] = v;
+ return true;
+}
+bool ICHull::CleanUp(uint32_t& addedPoints)
+{
+ bool r0 = CleanEdges();
+ bool r1 = CleanTriangles();
+ bool r2 = CleanVertices(addedPoints);
+ return r0 && r1 && r2;
+}
+bool ICHull::CleanEdges()
+{
+ // integrate the new faces into the data structure
+ CircularListElement<TMMEdge>* e;
+ const size_t ne_update = m_edgesToUpdate.Size();
+ for (size_t i = 0; i < ne_update; ++i) {
+ e = m_edgesToUpdate[i];
+ if (e->GetData().m_newFace) {
+ if (e->GetData().m_triangles[0]->GetData().m_visible) {
+ e->GetData().m_triangles[0] = e->GetData().m_newFace;
+ }
+ else {
+ e->GetData().m_triangles[1] = e->GetData().m_newFace;
+ }
+ e->GetData().m_newFace = 0;
+ }
+ }
+ // delete edges maked for deletion
+ CircularList<TMMEdge>& edges = m_mesh.GetEdges();
+ const size_t ne_delete = m_edgesToDelete.Size();
+ for (size_t i = 0; i < ne_delete; ++i) {
+ edges.Delete(m_edgesToDelete[i]);
+ }
+ m_edgesToDelete.Resize(0);
+ m_edgesToUpdate.Resize(0);
+ return true;
+}
+bool ICHull::CleanTriangles()
+{
+ CircularList<TMMTriangle>& triangles = m_mesh.GetTriangles();
+ const size_t nt_delete = m_trianglesToDelete.Size();
+ for (size_t i = 0; i < nt_delete; ++i) {
+ triangles.Delete(m_trianglesToDelete[i]);
+ }
+ m_trianglesToDelete.Resize(0);
+ return true;
+}
+bool ICHull::CleanVertices(uint32_t& addedPoints)
+{
+ // mark all vertices incident to some undeleted edge as on the hull
+ CircularList<TMMEdge>& edges = m_mesh.GetEdges();
+ CircularListElement<TMMEdge>* e = edges.GetHead();
+ size_t nE = edges.GetSize();
+ for (size_t i = 0; i < nE; i++) {
+ e->GetData().m_vertices[0]->GetData().m_onHull = true;
+ e->GetData().m_vertices[1]->GetData().m_onHull = true;
+ e = e->GetNext();
+ }
+ // delete all the vertices that have been processed but are not on the hull
+ CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
+ CircularListElement<TMMVertex>* vHead = vertices.GetHead();
+ CircularListElement<TMMVertex>* v = vHead;
+ v = v->GetPrev();
+ do {
+ if (v->GetData().m_tag && !v->GetData().m_onHull) {
+ CircularListElement<TMMVertex>* tmp = v->GetPrev();
+ vertices.Delete(v);
+ v = tmp;
+ addedPoints--;
+ }
+ else {
+ v->GetData().m_duplicate = 0;
+ v->GetData().m_onHull = false;
+ v = v->GetPrev();
+ }
+ } while (v->GetData().m_tag && v != vHead);
+ return true;
+}
+void ICHull::Clear()
+{
+ m_mesh.Clear();
+ m_edgesToDelete.Resize(0);
+ m_edgesToUpdate.Resize(0);
+ m_trianglesToDelete.Resize(0);
+ m_isFlat = false;
+}
+const ICHull& ICHull::operator=(ICHull& rhs)
+{
+ if (&rhs != this) {
+ m_mesh.Copy(rhs.m_mesh);
+ m_edgesToDelete = rhs.m_edgesToDelete;
+ m_edgesToUpdate = rhs.m_edgesToUpdate;
+ m_trianglesToDelete = rhs.m_trianglesToDelete;
+ m_isFlat = rhs.m_isFlat;
+ }
+ return (*this);
+}
+bool ICHull::IsInside(const Vec3<double>& pt0, const double eps)
+{
+ const Vec3<double> pt(pt0.X(), pt0.Y(), pt0.Z());
+ if (m_isFlat) {
+ size_t nT = m_mesh.m_triangles.GetSize();
+ Vec3<double> ver0, ver1, ver2, a, b, c;
+ double u, v;
+ for (size_t t = 0; t < nT; t++) {
+ ver0.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.X();
+ ver0.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.Y();
+ ver0.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.Z();
+ ver1.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.X();
+ ver1.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.Y();
+ ver1.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.Z();
+ ver2.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.X();
+ ver2.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.Y();
+ ver2.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.Z();
+ a = ver1 - ver0;
+ b = ver2 - ver0;
+ c = pt - ver0;
+ u = c * a;
+ v = c * b;
+ if (u >= 0.0 && u <= 1.0 && v >= 0.0 && u + v <= 1.0) {
+ return true;
+ }
+ m_mesh.m_triangles.Next();
+ }
+ return false;
+ }
+ else {
+ size_t nT = m_mesh.m_triangles.GetSize();
+ Vec3<double> ver0, ver1, ver2;
+ double vol;
+ for (size_t t = 0; t < nT; t++) {
+ ver0.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.X();
+ ver0.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.Y();
+ ver0.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.Z();
+ ver1.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.X();
+ ver1.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.Y();
+ ver1.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.Z();
+ ver2.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.X();
+ ver2.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.Y();
+ ver2.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.Z();
+ vol = ComputeVolume4(ver0, ver1, ver2, pt);
+ if (vol < eps) {
+ return false;
+ }
+ m_mesh.m_triangles.Next();
+ }
+ return true;
+ }
+}
+}
diff --git a/thirdparty/vhacd/src/vhacdManifoldMesh.cpp b/thirdparty/vhacd/src/vhacdManifoldMesh.cpp
new file mode 100644
index 0000000000..7aac9c0d17
--- /dev/null
+++ b/thirdparty/vhacd/src/vhacdManifoldMesh.cpp
@@ -0,0 +1,202 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
+ */
+#include "vhacdManifoldMesh.h"
+namespace VHACD {
+TMMVertex::TMMVertex(void)
+{
+ Initialize();
+}
+void TMMVertex::Initialize()
+{
+ m_name = 0;
+ m_id = 0;
+ m_duplicate = 0;
+ m_onHull = false;
+ m_tag = false;
+}
+
+TMMVertex::~TMMVertex(void)
+{
+}
+TMMEdge::TMMEdge(void)
+{
+ Initialize();
+}
+void TMMEdge::Initialize()
+{
+ m_id = 0;
+ m_triangles[0] = m_triangles[1] = m_newFace = 0;
+ m_vertices[0] = m_vertices[1] = 0;
+}
+TMMEdge::~TMMEdge(void)
+{
+}
+void TMMTriangle::Initialize()
+{
+ m_id = 0;
+ for (int32_t i = 0; i < 3; i++) {
+ m_edges[i] = 0;
+ m_vertices[0] = 0;
+ }
+ m_visible = false;
+}
+TMMTriangle::TMMTriangle(void)
+{
+ Initialize();
+}
+TMMTriangle::~TMMTriangle(void)
+{
+}
+TMMesh::TMMesh()
+{
+}
+TMMesh::~TMMesh(void)
+{
+}
+void TMMesh::GetIFS(Vec3<double>* const points, Vec3<int32_t>* const triangles)
+{
+ size_t nV = m_vertices.GetSize();
+ size_t nT = m_triangles.GetSize();
+
+ for (size_t v = 0; v < nV; v++) {
+ points[v] = m_vertices.GetData().m_pos;
+ m_vertices.GetData().m_id = v;
+ m_vertices.Next();
+ }
+ for (size_t f = 0; f < nT; f++) {
+ TMMTriangle& currentTriangle = m_triangles.GetData();
+ triangles[f].X() = static_cast<int32_t>(currentTriangle.m_vertices[0]->GetData().m_id);
+ triangles[f].Y() = static_cast<int32_t>(currentTriangle.m_vertices[1]->GetData().m_id);
+ triangles[f].Z() = static_cast<int32_t>(currentTriangle.m_vertices[2]->GetData().m_id);
+ m_triangles.Next();
+ }
+}
+void TMMesh::Clear()
+{
+ m_vertices.Clear();
+ m_edges.Clear();
+ m_triangles.Clear();
+}
+void TMMesh::Copy(TMMesh& mesh)
+{
+ Clear();
+ // updating the id's
+ size_t nV = mesh.m_vertices.GetSize();
+ size_t nE = mesh.m_edges.GetSize();
+ size_t nT = mesh.m_triangles.GetSize();
+ for (size_t v = 0; v < nV; v++) {
+ mesh.m_vertices.GetData().m_id = v;
+ mesh.m_vertices.Next();
+ }
+ for (size_t e = 0; e < nE; e++) {
+ mesh.m_edges.GetData().m_id = e;
+ mesh.m_edges.Next();
+ }
+ for (size_t f = 0; f < nT; f++) {
+ mesh.m_triangles.GetData().m_id = f;
+ mesh.m_triangles.Next();
+ }
+ // copying data
+ m_vertices = mesh.m_vertices;
+ m_edges = mesh.m_edges;
+ m_triangles = mesh.m_triangles;
+
+ // generate mapping
+ CircularListElement<TMMVertex>** vertexMap = new CircularListElement<TMMVertex>*[nV];
+ CircularListElement<TMMEdge>** edgeMap = new CircularListElement<TMMEdge>*[nE];
+ CircularListElement<TMMTriangle>** triangleMap = new CircularListElement<TMMTriangle>*[nT];
+ for (size_t v = 0; v < nV; v++) {
+ vertexMap[v] = m_vertices.GetHead();
+ m_vertices.Next();
+ }
+ for (size_t e = 0; e < nE; e++) {
+ edgeMap[e] = m_edges.GetHead();
+ m_edges.Next();
+ }
+ for (size_t f = 0; f < nT; f++) {
+ triangleMap[f] = m_triangles.GetHead();
+ m_triangles.Next();
+ }
+
+ // updating pointers
+ for (size_t v = 0; v < nV; v++) {
+ if (vertexMap[v]->GetData().m_duplicate) {
+ vertexMap[v]->GetData().m_duplicate = edgeMap[vertexMap[v]->GetData().m_duplicate->GetData().m_id];
+ }
+ }
+ for (size_t e = 0; e < nE; e++) {
+ if (edgeMap[e]->GetData().m_newFace) {
+ edgeMap[e]->GetData().m_newFace = triangleMap[edgeMap[e]->GetData().m_newFace->GetData().m_id];
+ }
+ if (nT > 0) {
+ for (int32_t f = 0; f < 2; f++) {
+ if (edgeMap[e]->GetData().m_triangles[f]) {
+ edgeMap[e]->GetData().m_triangles[f] = triangleMap[edgeMap[e]->GetData().m_triangles[f]->GetData().m_id];
+ }
+ }
+ }
+ for (int32_t v = 0; v < 2; v++) {
+ if (edgeMap[e]->GetData().m_vertices[v]) {
+ edgeMap[e]->GetData().m_vertices[v] = vertexMap[edgeMap[e]->GetData().m_vertices[v]->GetData().m_id];
+ }
+ }
+ }
+ for (size_t f = 0; f < nT; f++) {
+ if (nE > 0) {
+ for (int32_t e = 0; e < 3; e++) {
+ if (triangleMap[f]->GetData().m_edges[e]) {
+ triangleMap[f]->GetData().m_edges[e] = edgeMap[triangleMap[f]->GetData().m_edges[e]->GetData().m_id];
+ }
+ }
+ }
+ for (int32_t v = 0; v < 3; v++) {
+ if (triangleMap[f]->GetData().m_vertices[v]) {
+ triangleMap[f]->GetData().m_vertices[v] = vertexMap[triangleMap[f]->GetData().m_vertices[v]->GetData().m_id];
+ }
+ }
+ }
+ delete[] vertexMap;
+ delete[] edgeMap;
+ delete[] triangleMap;
+}
+bool TMMesh::CheckConsistancy()
+{
+ size_t nE = m_edges.GetSize();
+ size_t nT = m_triangles.GetSize();
+ for (size_t e = 0; e < nE; e++) {
+ for (int32_t f = 0; f < 2; f++) {
+ if (!m_edges.GetHead()->GetData().m_triangles[f]) {
+ return false;
+ }
+ }
+ m_edges.Next();
+ }
+ for (size_t f = 0; f < nT; f++) {
+ for (int32_t e = 0; e < 3; e++) {
+ int32_t found = 0;
+ for (int32_t k = 0; k < 2; k++) {
+ if (m_triangles.GetHead()->GetData().m_edges[e]->GetData().m_triangles[k] == m_triangles.GetHead()) {
+ found++;
+ }
+ }
+ if (found != 1) {
+ return false;
+ }
+ }
+ m_triangles.Next();
+ }
+ return true;
+}
+} \ No newline at end of file
diff --git a/thirdparty/vhacd/src/vhacdMesh.cpp b/thirdparty/vhacd/src/vhacdMesh.cpp
new file mode 100644
index 0000000000..5d03989fda
--- /dev/null
+++ b/thirdparty/vhacd/src/vhacdMesh.cpp
@@ -0,0 +1,376 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include "btConvexHullComputer.h"
+#include "vhacdMesh.h"
+#include "FloatMath.h"
+#include <fstream>
+#include <iosfwd>
+#include <iostream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string>
+
+namespace VHACD {
+Mesh::Mesh()
+{
+ m_diag = 1.0;
+}
+Mesh::~Mesh()
+{
+}
+
+Vec3<double>& Mesh::ComputeCenter(void)
+{
+ const size_t nV = GetNPoints();
+ if (nV)
+ {
+ double center[3];
+ uint32_t pcount = uint32_t(GetNPoints());
+ const double *points = GetPoints();
+ uint32_t tcount = uint32_t(GetNTriangles());
+ const uint32_t *indices = (const uint32_t *)GetTriangles();
+ FLOAT_MATH::fm_computeCentroid(pcount, points, tcount, indices, center);
+ m_center.X() = center[0];
+ m_center.Y() = center[1];
+ m_center.Z() = center[2];
+ m_minBB = GetPoint(0);
+ m_maxBB = GetPoint(0);
+ for (size_t v = 1; v < nV; v++)
+ {
+ Vec3<double> p = GetPoint(v);
+ if (p.X() < m_minBB.X())
+ {
+ m_minBB.X() = p.X();
+ }
+ if (p.Y() < m_minBB.Y())
+ {
+ m_minBB.Y() = p.Y();
+ }
+ if (p.Z() < m_minBB.Z())
+ {
+ m_minBB.Z() = p.Z();
+ }
+ if (p.X() > m_maxBB.X())
+ {
+ m_maxBB.X() = p.X();
+ }
+ if (p.Y() > m_maxBB.Y())
+ {
+ m_maxBB.Y() = p.Y();
+ }
+ if (p.Z() > m_maxBB.Z())
+ {
+ m_maxBB.Z() = p.Z();
+ }
+ }
+ }
+ return m_center;
+}
+
+double Mesh::ComputeVolume() const
+{
+ const size_t nV = GetNPoints();
+ const size_t nT = GetNTriangles();
+ if (nV == 0 || nT == 0) {
+ return 0.0;
+ }
+
+ Vec3<double> bary(0.0, 0.0, 0.0);
+ for (size_t v = 0; v < nV; v++) {
+ bary += GetPoint(v);
+ }
+ bary /= static_cast<double>(nV);
+
+ Vec3<double> ver0, ver1, ver2;
+ double totalVolume = 0.0;
+ for (int32_t t = 0; t < int32_t(nT); t++) {
+ const Vec3<int32_t>& tri = GetTriangle(t);
+ ver0 = GetPoint(tri[0]);
+ ver1 = GetPoint(tri[1]);
+ ver2 = GetPoint(tri[2]);
+ totalVolume += ComputeVolume4(ver0, ver1, ver2, bary);
+ }
+ return totalVolume / 6.0;
+}
+
+void Mesh::ComputeConvexHull(const double* const pts,
+ const size_t nPts)
+{
+ ResizePoints(0);
+ ResizeTriangles(0);
+ btConvexHullComputer ch;
+ ch.compute(pts, 3 * sizeof(double), (int32_t)nPts, -1.0, -1.0);
+ for (int32_t v = 0; v < ch.vertices.size(); v++) {
+ AddPoint(Vec3<double>(ch.vertices[v].getX(), ch.vertices[v].getY(), ch.vertices[v].getZ()));
+ }
+ const int32_t nt = ch.faces.size();
+ for (int32_t t = 0; t < nt; ++t) {
+ const btConvexHullComputer::Edge* sourceEdge = &(ch.edges[ch.faces[t]]);
+ int32_t a = sourceEdge->getSourceVertex();
+ int32_t b = sourceEdge->getTargetVertex();
+ const btConvexHullComputer::Edge* edge = sourceEdge->getNextEdgeOfFace();
+ int32_t c = edge->getTargetVertex();
+ while (c != a) {
+ AddTriangle(Vec3<int32_t>(a, b, c));
+ edge = edge->getNextEdgeOfFace();
+ b = c;
+ c = edge->getTargetVertex();
+ }
+ }
+}
+void Mesh::Clip(const Plane& plane,
+ SArray<Vec3<double> >& positivePart,
+ SArray<Vec3<double> >& negativePart) const
+{
+ const size_t nV = GetNPoints();
+ if (nV == 0) {
+ return;
+ }
+ double d;
+ for (size_t v = 0; v < nV; v++) {
+ const Vec3<double>& pt = GetPoint(v);
+ d = plane.m_a * pt[0] + plane.m_b * pt[1] + plane.m_c * pt[2] + plane.m_d;
+ if (d > 0.0) {
+ positivePart.PushBack(pt);
+ }
+ else if (d < 0.0) {
+ negativePart.PushBack(pt);
+ }
+ else {
+ positivePart.PushBack(pt);
+ negativePart.PushBack(pt);
+ }
+ }
+}
+bool Mesh::IsInside(const Vec3<double>& pt) const
+{
+ const size_t nV = GetNPoints();
+ const size_t nT = GetNTriangles();
+ if (nV == 0 || nT == 0) {
+ return false;
+ }
+ Vec3<double> ver0, ver1, ver2;
+ double volume;
+ for (int32_t t = 0; t < int32_t(nT); t++) {
+ const Vec3<int32_t>& tri = GetTriangle(t);
+ ver0 = GetPoint(tri[0]);
+ ver1 = GetPoint(tri[1]);
+ ver2 = GetPoint(tri[2]);
+ volume = ComputeVolume4(ver0, ver1, ver2, pt);
+ if (volume < 0.0) {
+ return false;
+ }
+ }
+ return true;
+}
+double Mesh::ComputeDiagBB()
+{
+ const size_t nPoints = GetNPoints();
+ if (nPoints == 0)
+ return 0.0;
+ Vec3<double> minBB = m_points[0];
+ Vec3<double> maxBB = m_points[0];
+ double x, y, z;
+ for (size_t v = 1; v < nPoints; v++) {
+ x = m_points[v][0];
+ y = m_points[v][1];
+ z = m_points[v][2];
+ if (x < minBB[0])
+ minBB[0] = x;
+ else if (x > maxBB[0])
+ maxBB[0] = x;
+ if (y < minBB[1])
+ minBB[1] = y;
+ else if (y > maxBB[1])
+ maxBB[1] = y;
+ if (z < minBB[2])
+ minBB[2] = z;
+ else if (z > maxBB[2])
+ maxBB[2] = z;
+ }
+ return (m_diag = (maxBB - minBB).GetNorm());
+}
+
+#ifdef VHACD_DEBUG_MESH
+bool Mesh::SaveVRML2(const std::string& fileName) const
+{
+ std::ofstream fout(fileName.c_str());
+ if (fout.is_open()) {
+ const Material material;
+
+ if (SaveVRML2(fout, material)) {
+ fout.close();
+ return true;
+ }
+ return false;
+ }
+ return false;
+}
+bool Mesh::SaveVRML2(std::ofstream& fout, const Material& material) const
+{
+ if (fout.is_open()) {
+ fout.setf(std::ios::fixed, std::ios::floatfield);
+ fout.setf(std::ios::showpoint);
+ fout.precision(6);
+ size_t nV = m_points.Size();
+ size_t nT = m_triangles.Size();
+ fout << "#VRML V2.0 utf8" << std::endl;
+ fout << "" << std::endl;
+ fout << "# Vertices: " << nV << std::endl;
+ fout << "# Triangles: " << nT << std::endl;
+ fout << "" << std::endl;
+ fout << "Group {" << std::endl;
+ fout << " children [" << std::endl;
+ fout << " Shape {" << std::endl;
+ fout << " appearance Appearance {" << std::endl;
+ fout << " material Material {" << std::endl;
+ fout << " diffuseColor " << material.m_diffuseColor[0] << " "
+ << material.m_diffuseColor[1] << " "
+ << material.m_diffuseColor[2] << std::endl;
+ fout << " ambientIntensity " << material.m_ambientIntensity << std::endl;
+ fout << " specularColor " << material.m_specularColor[0] << " "
+ << material.m_specularColor[1] << " "
+ << material.m_specularColor[2] << std::endl;
+ fout << " emissiveColor " << material.m_emissiveColor[0] << " "
+ << material.m_emissiveColor[1] << " "
+ << material.m_emissiveColor[2] << std::endl;
+ fout << " shininess " << material.m_shininess << std::endl;
+ fout << " transparency " << material.m_transparency << std::endl;
+ fout << " }" << std::endl;
+ fout << " }" << std::endl;
+ fout << " geometry IndexedFaceSet {" << std::endl;
+ fout << " ccw TRUE" << std::endl;
+ fout << " solid TRUE" << std::endl;
+ fout << " convex TRUE" << std::endl;
+ if (nV > 0) {
+ fout << " coord DEF co Coordinate {" << std::endl;
+ fout << " point [" << std::endl;
+ for (size_t v = 0; v < nV; v++) {
+ fout << " " << m_points[v][0] << " "
+ << m_points[v][1] << " "
+ << m_points[v][2] << "," << std::endl;
+ }
+ fout << " ]" << std::endl;
+ fout << " }" << std::endl;
+ }
+ if (nT > 0) {
+ fout << " coordIndex [ " << std::endl;
+ for (size_t f = 0; f < nT; f++) {
+ fout << " " << m_triangles[f][0] << ", "
+ << m_triangles[f][1] << ", "
+ << m_triangles[f][2] << ", -1," << std::endl;
+ }
+ fout << " ]" << std::endl;
+ }
+ fout << " }" << std::endl;
+ fout << " }" << std::endl;
+ fout << " ]" << std::endl;
+ fout << "}" << std::endl;
+ return true;
+ }
+ return false;
+}
+bool Mesh::SaveOFF(const std::string& fileName) const
+{
+ std::ofstream fout(fileName.c_str());
+ if (fout.is_open()) {
+ size_t nV = m_points.Size();
+ size_t nT = m_triangles.Size();
+ fout << "OFF" << std::endl;
+ fout << nV << " " << nT << " " << 0 << std::endl;
+ for (size_t v = 0; v < nV; v++) {
+ fout << m_points[v][0] << " "
+ << m_points[v][1] << " "
+ << m_points[v][2] << std::endl;
+ }
+ for (size_t f = 0; f < nT; f++) {
+ fout << "3 " << m_triangles[f][0] << " "
+ << m_triangles[f][1] << " "
+ << m_triangles[f][2] << std::endl;
+ }
+ fout.close();
+ return true;
+ }
+ return false;
+}
+
+bool Mesh::LoadOFF(const std::string& fileName, bool invert)
+{
+ FILE* fid = fopen(fileName.c_str(), "r");
+ if (fid) {
+ const std::string strOFF("OFF");
+ char temp[1024];
+ fscanf(fid, "%s", temp);
+ if (std::string(temp) != strOFF) {
+ fclose(fid);
+ return false;
+ }
+ else {
+ int32_t nv = 0;
+ int32_t nf = 0;
+ int32_t ne = 0;
+ fscanf(fid, "%i", &nv);
+ fscanf(fid, "%i", &nf);
+ fscanf(fid, "%i", &ne);
+ m_points.Resize(nv);
+ m_triangles.Resize(nf);
+ Vec3<double> coord;
+ float x, y, z;
+ for (int32_t p = 0; p < nv; p++) {
+ fscanf(fid, "%f", &x);
+ fscanf(fid, "%f", &y);
+ fscanf(fid, "%f", &z);
+ m_points[p][0] = x;
+ m_points[p][1] = y;
+ m_points[p][2] = z;
+ }
+ int32_t i, j, k, s;
+ for (int32_t t = 0; t < nf; ++t) {
+ fscanf(fid, "%i", &s);
+ if (s == 3) {
+ fscanf(fid, "%i", &i);
+ fscanf(fid, "%i", &j);
+ fscanf(fid, "%i", &k);
+ m_triangles[t][0] = i;
+ if (invert) {
+ m_triangles[t][1] = k;
+ m_triangles[t][2] = j;
+ }
+ else {
+ m_triangles[t][1] = j;
+ m_triangles[t][2] = k;
+ }
+ }
+ else // Fix me: support only triangular meshes
+ {
+ for (int32_t h = 0; h < s; ++h)
+ fscanf(fid, "%i", &s);
+ }
+ }
+ fclose(fid);
+ }
+ }
+ else {
+ return false;
+ }
+ return true;
+}
+#endif // VHACD_DEBUG_MESH
+}
diff --git a/thirdparty/vhacd/src/vhacdRaycastMesh.cpp b/thirdparty/vhacd/src/vhacdRaycastMesh.cpp
new file mode 100644
index 0000000000..e8b9435d5f
--- /dev/null
+++ b/thirdparty/vhacd/src/vhacdRaycastMesh.cpp
@@ -0,0 +1,208 @@
+#include "vhacdRaycastMesh.h"
+#include <math.h>
+#include <assert.h>
+
+namespace RAYCAST_MESH
+{
+
+/* a = b - c */
+#define vector(a,b,c) \
+ (a)[0] = (b)[0] - (c)[0]; \
+ (a)[1] = (b)[1] - (c)[1]; \
+ (a)[2] = (b)[2] - (c)[2];
+
+#define innerProduct(v,q) \
+ ((v)[0] * (q)[0] + \
+ (v)[1] * (q)[1] + \
+ (v)[2] * (q)[2])
+
+#define crossProduct(a,b,c) \
+ (a)[0] = (b)[1] * (c)[2] - (c)[1] * (b)[2]; \
+ (a)[1] = (b)[2] * (c)[0] - (c)[2] * (b)[0]; \
+ (a)[2] = (b)[0] * (c)[1] - (c)[0] * (b)[1];
+
+
+static inline bool rayIntersectsTriangle(const double *p,const double *d,const double *v0,const double *v1,const double *v2,double &t)
+{
+ double e1[3],e2[3],h[3],s[3],q[3];
+ double a,f,u,v;
+
+ vector(e1,v1,v0);
+ vector(e2,v2,v0);
+ crossProduct(h,d,e2);
+ a = innerProduct(e1,h);
+
+ if (a > -0.00001 && a < 0.00001)
+ return(false);
+
+ f = 1/a;
+ vector(s,p,v0);
+ u = f * (innerProduct(s,h));
+
+ if (u < 0.0 || u > 1.0)
+ return(false);
+
+ crossProduct(q,s,e1);
+ v = f * innerProduct(d,q);
+ if (v < 0.0 || u + v > 1.0)
+ return(false);
+ // at this stage we can compute t to find out where
+ // the intersection point is on the line
+ t = f * innerProduct(e2,q);
+ if (t > 0) // ray intersection
+ return(true);
+ else // this means that there is a line intersection
+ // but not a ray intersection
+ return (false);
+}
+
+static double getPointDistance(const double *p1, const double *p2)
+{
+ double dx = p1[0] - p2[0];
+ double dy = p1[1] - p2[1];
+ double dz = p1[2] - p2[2];
+ return sqrt(dx*dx + dy*dy + dz*dz);
+}
+
+class MyRaycastMesh : public VHACD::RaycastMesh
+{
+public:
+
+ template <class T>
+ MyRaycastMesh(uint32_t vcount,
+ const T *vertices,
+ uint32_t tcount,
+ const uint32_t *indices)
+ {
+ mVcount = vcount;
+ mVertices = new double[mVcount * 3];
+ for (uint32_t i = 0; i < mVcount; i++)
+ {
+ mVertices[i * 3 + 0] = vertices[0];
+ mVertices[i * 3 + 1] = vertices[1];
+ mVertices[i * 3 + 2] = vertices[2];
+ vertices += 3;
+ }
+ mTcount = tcount;
+ mIndices = new uint32_t[mTcount * 3];
+ for (uint32_t i = 0; i < mTcount; i++)
+ {
+ mIndices[i * 3 + 0] = indices[0];
+ mIndices[i * 3 + 1] = indices[1];
+ mIndices[i * 3 + 2] = indices[2];
+ indices += 3;
+ }
+ }
+
+
+ ~MyRaycastMesh(void)
+ {
+ delete[]mVertices;
+ delete[]mIndices;
+ }
+
+ virtual void release(void)
+ {
+ delete this;
+ }
+
+ virtual bool raycast(const double *from, // The starting point of the raycast
+ const double *to, // The ending point of the raycast
+ const double *closestToPoint, // The point to match the nearest hit location (can just be the 'from' location of no specific point)
+ double *hitLocation, // The point where the ray hit nearest to the 'closestToPoint' location
+ double *hitDistance) final // The distance the ray traveled to the hit location
+ {
+ bool ret = false;
+
+ double dir[3];
+
+ dir[0] = to[0] - from[0];
+ dir[1] = to[1] - from[1];
+ dir[2] = to[2] - from[2];
+
+ double distance = sqrt( dir[0]*dir[0] + dir[1]*dir[1]+dir[2]*dir[2] );
+ if ( distance < 0.0000000001f ) return false;
+ double recipDistance = 1.0f / distance;
+ dir[0]*=recipDistance;
+ dir[1]*=recipDistance;
+ dir[2]*=recipDistance;
+ const uint32_t *indices = mIndices;
+ const double *vertices = mVertices;
+ double nearestDistance = distance;
+
+ for (uint32_t tri=0; tri<mTcount; tri++)
+ {
+ uint32_t i1 = indices[tri*3+0];
+ uint32_t i2 = indices[tri*3+1];
+ uint32_t i3 = indices[tri*3+2];
+
+ const double *p1 = &vertices[i1*3];
+ const double *p2 = &vertices[i2*3];
+ const double *p3 = &vertices[i3*3];
+
+ double t;
+ if ( rayIntersectsTriangle(from,dir,p1,p2,p3,t))
+ {
+ double hitPos[3];
+
+ hitPos[0] = from[0] + dir[0] * t;
+ hitPos[1] = from[1] + dir[1] * t;
+ hitPos[2] = from[2] + dir[2] * t;
+
+ double pointDistance = getPointDistance(hitPos, closestToPoint);
+
+ if (pointDistance < nearestDistance )
+ {
+ nearestDistance = pointDistance;
+ if ( hitLocation )
+ {
+ hitLocation[0] = hitPos[0];
+ hitLocation[1] = hitPos[1];
+ hitLocation[2] = hitPos[2];
+ }
+ if ( hitDistance )
+ {
+ *hitDistance = pointDistance;
+ }
+ ret = true;
+ }
+ }
+ }
+ return ret;
+ }
+
+ uint32_t mVcount;
+ double *mVertices;
+ uint32_t mTcount;
+ uint32_t *mIndices;
+};
+
+};
+
+
+
+using namespace RAYCAST_MESH;
+
+namespace VHACD
+{
+
+ RaycastMesh * RaycastMesh::createRaycastMesh(uint32_t vcount, // The number of vertices in the source triangle mesh
+ const double *vertices, // The array of vertex positions in the format x1,y1,z1..x2,y2,z2.. etc.
+ uint32_t tcount, // The number of triangles in the source triangle mesh
+ const uint32_t *indices) // The triangle indices in the format of i1,i2,i3 ... i4,i5,i6, ...
+ {
+ MyRaycastMesh *m = new MyRaycastMesh(vcount, vertices, tcount, indices);
+ return static_cast<RaycastMesh *>(m);
+ }
+
+ RaycastMesh * RaycastMesh::createRaycastMesh(uint32_t vcount, // The number of vertices in the source triangle mesh
+ const float *vertices, // The array of vertex positions in the format x1,y1,z1..x2,y2,z2.. etc.
+ uint32_t tcount, // The number of triangles in the source triangle mesh
+ const uint32_t *indices) // The triangle indices in the format of i1,i2,i3 ... i4,i5,i6, ...
+ {
+ MyRaycastMesh *m = new MyRaycastMesh(vcount, vertices, tcount, indices);
+ return static_cast<RaycastMesh *>(m);
+ }
+
+
+} // end of VHACD namespace \ No newline at end of file
diff --git a/thirdparty/vhacd/src/vhacdVolume.cpp b/thirdparty/vhacd/src/vhacdVolume.cpp
new file mode 100644
index 0000000000..a250e5acaa
--- /dev/null
+++ b/thirdparty/vhacd/src/vhacdVolume.cpp
@@ -0,0 +1,1626 @@
+/* Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)
+ All rights reserved.
+
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+ 2. 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.
+
+ 3. The names of the contributors may not 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include "btConvexHullComputer.h"
+#include "vhacdVolume.h"
+#include <algorithm>
+#include <float.h>
+#include <math.h>
+#include <queue>
+#include <string.h>
+
+#ifdef _MSC_VER
+#pragma warning(disable:4458 4100)
+#endif
+
+
+namespace VHACD {
+/********************************************************/
+/* AABB-triangle overlap test code */
+/* by Tomas Akenine-M�ller */
+/* Function: int32_t triBoxOverlap(float boxcenter[3], */
+/* float boxhalfsize[3],float triverts[3][3]); */
+/* History: */
+/* 2001-03-05: released the code in its first version */
+/* 2001-06-18: changed the order of the tests, faster */
+/* */
+/* Acknowledgement: Many thanks to Pierre Terdiman for */
+/* suggestions and discussions on how to optimize code. */
+/* Thanks to David Hunt for finding a ">="-bug! */
+/********************************************************/
+
+#define X 0
+#define Y 1
+#define Z 2
+#define FINDMINMAX(x0, x1, x2, min, max) \
+ min = max = x0; \
+ if (x1 < min) \
+ min = x1; \
+ if (x1 > max) \
+ max = x1; \
+ if (x2 < min) \
+ min = x2; \
+ if (x2 > max) \
+ max = x2;
+
+#define AXISTEST_X01(a, b, fa, fb) \
+ p0 = a * v0[Y] - b * v0[Z]; \
+ p2 = a * v2[Y] - b * v2[Z]; \
+ if (p0 < p2) { \
+ min = p0; \
+ max = p2; \
+ } \
+ else { \
+ min = p2; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize[Y] + fb * boxhalfsize[Z]; \
+ if (min > rad || max < -rad) \
+ return 0;
+
+#define AXISTEST_X2(a, b, fa, fb) \
+ p0 = a * v0[Y] - b * v0[Z]; \
+ p1 = a * v1[Y] - b * v1[Z]; \
+ if (p0 < p1) { \
+ min = p0; \
+ max = p1; \
+ } \
+ else { \
+ min = p1; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize[Y] + fb * boxhalfsize[Z]; \
+ if (min > rad || max < -rad) \
+ return 0;
+
+#define AXISTEST_Y02(a, b, fa, fb) \
+ p0 = -a * v0[X] + b * v0[Z]; \
+ p2 = -a * v2[X] + b * v2[Z]; \
+ if (p0 < p2) { \
+ min = p0; \
+ max = p2; \
+ } \
+ else { \
+ min = p2; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize[X] + fb * boxhalfsize[Z]; \
+ if (min > rad || max < -rad) \
+ return 0;
+
+#define AXISTEST_Y1(a, b, fa, fb) \
+ p0 = -a * v0[X] + b * v0[Z]; \
+ p1 = -a * v1[X] + b * v1[Z]; \
+ if (p0 < p1) { \
+ min = p0; \
+ max = p1; \
+ } \
+ else { \
+ min = p1; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize[X] + fb * boxhalfsize[Z]; \
+ if (min > rad || max < -rad) \
+ return 0;
+
+#define AXISTEST_Z12(a, b, fa, fb) \
+ p1 = a * v1[X] - b * v1[Y]; \
+ p2 = a * v2[X] - b * v2[Y]; \
+ if (p2 < p1) { \
+ min = p2; \
+ max = p1; \
+ } \
+ else { \
+ min = p1; \
+ max = p2; \
+ } \
+ rad = fa * boxhalfsize[X] + fb * boxhalfsize[Y]; \
+ if (min > rad || max < -rad) \
+ return 0;
+
+#define AXISTEST_Z0(a, b, fa, fb) \
+ p0 = a * v0[X] - b * v0[Y]; \
+ p1 = a * v1[X] - b * v1[Y]; \
+ if (p0 < p1) { \
+ min = p0; \
+ max = p1; \
+ } \
+ else { \
+ min = p1; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize[X] + fb * boxhalfsize[Y]; \
+ if (min > rad || max < -rad) \
+ return 0;
+
+int32_t PlaneBoxOverlap(const Vec3<double>& normal,
+ const Vec3<double>& vert,
+ const Vec3<double>& maxbox)
+{
+ int32_t q;
+ Vec3<double> vmin, vmax;
+ double v;
+ for (q = X; q <= Z; q++) {
+ v = vert[q];
+ if (normal[q] > 0.0) {
+ vmin[q] = -maxbox[q] - v;
+ vmax[q] = maxbox[q] - v;
+ }
+ else {
+ vmin[q] = maxbox[q] - v;
+ vmax[q] = -maxbox[q] - v;
+ }
+ }
+ if (normal * vmin > 0.0)
+ return 0;
+ if (normal * vmax >= 0.0)
+ return 1;
+ return 0;
+}
+
+int32_t TriBoxOverlap(const Vec3<double>& boxcenter,
+ const Vec3<double>& boxhalfsize,
+ const Vec3<double>& triver0,
+ const Vec3<double>& triver1,
+ const Vec3<double>& triver2)
+{
+ /* use separating axis theorem to test overlap between triangle and box */
+ /* need to test for overlap in these directions: */
+ /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
+ /* we do not even need to test these) */
+ /* 2) normal of the triangle */
+ /* 3) crossproduct(edge from tri, {x,y,z}-directin) */
+ /* this gives 3x3=9 more tests */
+
+ Vec3<double> v0, v1, v2;
+ double min, max, p0, p1, p2, rad, fex, fey, fez; // -NJMP- "d" local variable removed
+ Vec3<double> normal, e0, e1, e2;
+
+ /* This is the fastest branch on Sun */
+ /* move everything so that the boxcenter is in (0,0,0) */
+
+ v0 = triver0 - boxcenter;
+ v1 = triver1 - boxcenter;
+ v2 = triver2 - boxcenter;
+
+ /* compute triangle edges */
+ e0 = v1 - v0; /* tri edge 0 */
+ e1 = v2 - v1; /* tri edge 1 */
+ e2 = v0 - v2; /* tri edge 2 */
+
+ /* Bullet 3: */
+ /* test the 9 tests first (this was faster) */
+ fex = fabs(e0[X]);
+ fey = fabs(e0[Y]);
+ fez = fabs(e0[Z]);
+
+ AXISTEST_X01(e0[Z], e0[Y], fez, fey);
+ AXISTEST_Y02(e0[Z], e0[X], fez, fex);
+ AXISTEST_Z12(e0[Y], e0[X], fey, fex);
+
+ fex = fabs(e1[X]);
+ fey = fabs(e1[Y]);
+ fez = fabs(e1[Z]);
+
+ AXISTEST_X01(e1[Z], e1[Y], fez, fey);
+ AXISTEST_Y02(e1[Z], e1[X], fez, fex);
+ AXISTEST_Z0(e1[Y], e1[X], fey, fex);
+
+ fex = fabs(e2[X]);
+ fey = fabs(e2[Y]);
+ fez = fabs(e2[Z]);
+
+ AXISTEST_X2(e2[Z], e2[Y], fez, fey);
+ AXISTEST_Y1(e2[Z], e2[X], fez, fex);
+ AXISTEST_Z12(e2[Y], e2[X], fey, fex);
+
+ /* Bullet 1: */
+ /* first test overlap in the {x,y,z}-directions */
+ /* find min, max of the triangle each direction, and test for overlap in */
+ /* that direction -- this is equivalent to testing a minimal AABB around */
+ /* the triangle against the AABB */
+
+ /* test in X-direction */
+ FINDMINMAX(v0[X], v1[X], v2[X], min, max);
+ if (min > boxhalfsize[X] || max < -boxhalfsize[X])
+ return 0;
+
+ /* test in Y-direction */
+ FINDMINMAX(v0[Y], v1[Y], v2[Y], min, max);
+ if (min > boxhalfsize[Y] || max < -boxhalfsize[Y])
+ return 0;
+
+ /* test in Z-direction */
+ FINDMINMAX(v0[Z], v1[Z], v2[Z], min, max);
+ if (min > boxhalfsize[Z] || max < -boxhalfsize[Z])
+ return 0;
+
+ /* Bullet 2: */
+ /* test if the box intersects the plane of the triangle */
+ /* compute plane equation of triangle: normal*x+d=0 */
+ normal = e0 ^ e1;
+
+ if (!PlaneBoxOverlap(normal, v0, boxhalfsize))
+ return 0;
+ return 1; /* box and triangle overlaps */
+}
+
+// Slightly modified version of Stan Melax's code for 3x3 matrix diagonalization (Thanks Stan!)
+// source: http://www.melax.com/diag.html?attredirects=0
+void Diagonalize(const double (&A)[3][3], double (&Q)[3][3], double (&D)[3][3])
+{
+ // A must be a symmetric matrix.
+ // returns Q and D such that
+ // Diagonal matrix D = QT * A * Q; and A = Q*D*QT
+ const int32_t maxsteps = 24; // certainly wont need that many.
+ int32_t k0, k1, k2;
+ double o[3], m[3];
+ double q[4] = { 0.0, 0.0, 0.0, 1.0 };
+ double jr[4];
+ double sqw, sqx, sqy, sqz;
+ double tmp1, tmp2, mq;
+ double AQ[3][3];
+ double thet, sgn, t, c;
+ for (int32_t i = 0; i < maxsteps; ++i) {
+ // quat to matrix
+ sqx = q[0] * q[0];
+ sqy = q[1] * q[1];
+ sqz = q[2] * q[2];
+ sqw = q[3] * q[3];
+ Q[0][0] = (sqx - sqy - sqz + sqw);
+ Q[1][1] = (-sqx + sqy - sqz + sqw);
+ Q[2][2] = (-sqx - sqy + sqz + sqw);
+ tmp1 = q[0] * q[1];
+ tmp2 = q[2] * q[3];
+ Q[1][0] = 2.0 * (tmp1 + tmp2);
+ Q[0][1] = 2.0 * (tmp1 - tmp2);
+ tmp1 = q[0] * q[2];
+ tmp2 = q[1] * q[3];
+ Q[2][0] = 2.0 * (tmp1 - tmp2);
+ Q[0][2] = 2.0 * (tmp1 + tmp2);
+ tmp1 = q[1] * q[2];
+ tmp2 = q[0] * q[3];
+ Q[2][1] = 2.0 * (tmp1 + tmp2);
+ Q[1][2] = 2.0 * (tmp1 - tmp2);
+
+ // AQ = A * Q
+ AQ[0][0] = Q[0][0] * A[0][0] + Q[1][0] * A[0][1] + Q[2][0] * A[0][2];
+ AQ[0][1] = Q[0][1] * A[0][0] + Q[1][1] * A[0][1] + Q[2][1] * A[0][2];
+ AQ[0][2] = Q[0][2] * A[0][0] + Q[1][2] * A[0][1] + Q[2][2] * A[0][2];
+ AQ[1][0] = Q[0][0] * A[0][1] + Q[1][0] * A[1][1] + Q[2][0] * A[1][2];
+ AQ[1][1] = Q[0][1] * A[0][1] + Q[1][1] * A[1][1] + Q[2][1] * A[1][2];
+ AQ[1][2] = Q[0][2] * A[0][1] + Q[1][2] * A[1][1] + Q[2][2] * A[1][2];
+ AQ[2][0] = Q[0][0] * A[0][2] + Q[1][0] * A[1][2] + Q[2][0] * A[2][2];
+ AQ[2][1] = Q[0][1] * A[0][2] + Q[1][1] * A[1][2] + Q[2][1] * A[2][2];
+ AQ[2][2] = Q[0][2] * A[0][2] + Q[1][2] * A[1][2] + Q[2][2] * A[2][2];
+ // D = Qt * AQ
+ D[0][0] = AQ[0][0] * Q[0][0] + AQ[1][0] * Q[1][0] + AQ[2][0] * Q[2][0];
+ D[0][1] = AQ[0][0] * Q[0][1] + AQ[1][0] * Q[1][1] + AQ[2][0] * Q[2][1];
+ D[0][2] = AQ[0][0] * Q[0][2] + AQ[1][0] * Q[1][2] + AQ[2][0] * Q[2][2];
+ D[1][0] = AQ[0][1] * Q[0][0] + AQ[1][1] * Q[1][0] + AQ[2][1] * Q[2][0];
+ D[1][1] = AQ[0][1] * Q[0][1] + AQ[1][1] * Q[1][1] + AQ[2][1] * Q[2][1];
+ D[1][2] = AQ[0][1] * Q[0][2] + AQ[1][1] * Q[1][2] + AQ[2][1] * Q[2][2];
+ D[2][0] = AQ[0][2] * Q[0][0] + AQ[1][2] * Q[1][0] + AQ[2][2] * Q[2][0];
+ D[2][1] = AQ[0][2] * Q[0][1] + AQ[1][2] * Q[1][1] + AQ[2][2] * Q[2][1];
+ D[2][2] = AQ[0][2] * Q[0][2] + AQ[1][2] * Q[1][2] + AQ[2][2] * Q[2][2];
+ o[0] = D[1][2];
+ o[1] = D[0][2];
+ o[2] = D[0][1];
+ m[0] = fabs(o[0]);
+ m[1] = fabs(o[1]);
+ m[2] = fabs(o[2]);
+
+ k0 = (m[0] > m[1] && m[0] > m[2]) ? 0 : (m[1] > m[2]) ? 1 : 2; // index of largest element of offdiag
+ k1 = (k0 + 1) % 3;
+ k2 = (k0 + 2) % 3;
+ if (o[k0] == 0.0) {
+ break; // diagonal already
+ }
+ thet = (D[k2][k2] - D[k1][k1]) / (2.0 * o[k0]);
+ sgn = (thet > 0.0) ? 1.0 : -1.0;
+ thet *= sgn; // make it positive
+ t = sgn / (thet + ((thet < 1.E6) ? sqrt(thet * thet + 1.0) : thet)); // sign(T)/(|T|+sqrt(T^2+1))
+ c = 1.0 / sqrt(t * t + 1.0); // c= 1/(t^2+1) , t=s/c
+ if (c == 1.0) {
+ break; // no room for improvement - reached machine precision.
+ }
+ jr[0] = jr[1] = jr[2] = jr[3] = 0.0;
+ jr[k0] = sgn * sqrt((1.0 - c) / 2.0); // using 1/2 angle identity sin(a/2) = sqrt((1-cos(a))/2)
+ jr[k0] *= -1.0; // since our quat-to-matrix convention was for v*M instead of M*v
+ jr[3] = sqrt(1.0 - jr[k0] * jr[k0]);
+ if (jr[3] == 1.0) {
+ break; // reached limits of floating point precision
+ }
+ q[0] = (q[3] * jr[0] + q[0] * jr[3] + q[1] * jr[2] - q[2] * jr[1]);
+ q[1] = (q[3] * jr[1] - q[0] * jr[2] + q[1] * jr[3] + q[2] * jr[0]);
+ q[2] = (q[3] * jr[2] + q[0] * jr[1] - q[1] * jr[0] + q[2] * jr[3]);
+ q[3] = (q[3] * jr[3] - q[0] * jr[0] - q[1] * jr[1] - q[2] * jr[2]);
+ mq = sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]);
+ q[0] /= mq;
+ q[1] /= mq;
+ q[2] /= mq;
+ q[3] /= mq;
+ }
+}
+const double TetrahedronSet::EPS = 0.0000000000001;
+VoxelSet::VoxelSet()
+{
+ m_minBB[0] = m_minBB[1] = m_minBB[2] = 0.0;
+ m_minBBVoxels[0] = m_minBBVoxels[1] = m_minBBVoxels[2] = 0;
+ m_maxBBVoxels[0] = m_maxBBVoxels[1] = m_maxBBVoxels[2] = 1;
+ m_minBBPts[0] = m_minBBPts[1] = m_minBBPts[2] = 0;
+ m_maxBBPts[0] = m_maxBBPts[1] = m_maxBBPts[2] = 1;
+ m_barycenter[0] = m_barycenter[1] = m_barycenter[2] = 0;
+ m_barycenterPCA[0] = m_barycenterPCA[1] = m_barycenterPCA[2] = 0.0;
+ m_scale = 1.0;
+ m_unitVolume = 1.0;
+ m_numVoxelsOnSurface = 0;
+ m_numVoxelsInsideSurface = 0;
+ memset(m_Q, 0, sizeof(double) * 9);
+ memset(m_D, 0, sizeof(double) * 9);
+}
+VoxelSet::~VoxelSet(void)
+{
+}
+void VoxelSet::ComputeBB()
+{
+ const size_t nVoxels = m_voxels.Size();
+ if (nVoxels == 0)
+ return;
+ for (int32_t h = 0; h < 3; ++h) {
+ m_minBBVoxels[h] = m_voxels[0].m_coord[h];
+ m_maxBBVoxels[h] = m_voxels[0].m_coord[h];
+ }
+ Vec3<double> bary(0.0);
+ for (size_t p = 0; p < nVoxels; ++p) {
+ for (int32_t h = 0; h < 3; ++h) {
+ bary[h] += m_voxels[p].m_coord[h];
+ if (m_minBBVoxels[h] > m_voxels[p].m_coord[h])
+ m_minBBVoxels[h] = m_voxels[p].m_coord[h];
+ if (m_maxBBVoxels[h] < m_voxels[p].m_coord[h])
+ m_maxBBVoxels[h] = m_voxels[p].m_coord[h];
+ }
+ }
+ bary /= (double)nVoxels;
+ for (int32_t h = 0; h < 3; ++h) {
+ m_minBBPts[h] = m_minBBVoxels[h] * m_scale + m_minBB[h];
+ m_maxBBPts[h] = m_maxBBVoxels[h] * m_scale + m_minBB[h];
+ m_barycenter[h] = (short)(bary[h] + 0.5);
+ }
+}
+void VoxelSet::ComputeConvexHull(Mesh& meshCH, const size_t sampling) const
+{
+ const size_t CLUSTER_SIZE = 65536;
+ const size_t nVoxels = m_voxels.Size();
+ if (nVoxels == 0)
+ return;
+
+ SArray<Vec3<double> > cpoints;
+
+ Vec3<double>* points = new Vec3<double>[CLUSTER_SIZE];
+ size_t p = 0;
+ size_t s = 0;
+ short i, j, k;
+ while (p < nVoxels) {
+ size_t q = 0;
+ while (q < CLUSTER_SIZE && p < nVoxels) {
+ if (m_voxels[p].m_data == PRIMITIVE_ON_SURFACE) {
+ ++s;
+ if (s == sampling) {
+ s = 0;
+ i = m_voxels[p].m_coord[0];
+ j = m_voxels[p].m_coord[1];
+ k = m_voxels[p].m_coord[2];
+ Vec3<double> p0((i - 0.5) * m_scale, (j - 0.5) * m_scale, (k - 0.5) * m_scale);
+ Vec3<double> p1((i + 0.5) * m_scale, (j - 0.5) * m_scale, (k - 0.5) * m_scale);
+ Vec3<double> p2((i + 0.5) * m_scale, (j + 0.5) * m_scale, (k - 0.5) * m_scale);
+ Vec3<double> p3((i - 0.5) * m_scale, (j + 0.5) * m_scale, (k - 0.5) * m_scale);
+ Vec3<double> p4((i - 0.5) * m_scale, (j - 0.5) * m_scale, (k + 0.5) * m_scale);
+ Vec3<double> p5((i + 0.5) * m_scale, (j - 0.5) * m_scale, (k + 0.5) * m_scale);
+ Vec3<double> p6((i + 0.5) * m_scale, (j + 0.5) * m_scale, (k + 0.5) * m_scale);
+ Vec3<double> p7((i - 0.5) * m_scale, (j + 0.5) * m_scale, (k + 0.5) * m_scale);
+ points[q++] = p0 + m_minBB;
+ points[q++] = p1 + m_minBB;
+ points[q++] = p2 + m_minBB;
+ points[q++] = p3 + m_minBB;
+ points[q++] = p4 + m_minBB;
+ points[q++] = p5 + m_minBB;
+ points[q++] = p6 + m_minBB;
+ points[q++] = p7 + m_minBB;
+ }
+ }
+ ++p;
+ }
+ btConvexHullComputer ch;
+ ch.compute((double*)points, 3 * sizeof(double), (int32_t)q, -1.0, -1.0);
+ for (int32_t v = 0; v < ch.vertices.size(); v++) {
+ cpoints.PushBack(Vec3<double>(ch.vertices[v].getX(), ch.vertices[v].getY(), ch.vertices[v].getZ()));
+ }
+ }
+ delete[] points;
+
+ points = cpoints.Data();
+ btConvexHullComputer ch;
+ ch.compute((double*)points, 3 * sizeof(double), (int32_t)cpoints.Size(), -1.0, -1.0);
+ meshCH.ResizePoints(0);
+ meshCH.ResizeTriangles(0);
+ for (int32_t v = 0; v < ch.vertices.size(); v++) {
+ meshCH.AddPoint(Vec3<double>(ch.vertices[v].getX(), ch.vertices[v].getY(), ch.vertices[v].getZ()));
+ }
+ const int32_t nt = ch.faces.size();
+ for (int32_t t = 0; t < nt; ++t) {
+ const btConvexHullComputer::Edge* sourceEdge = &(ch.edges[ch.faces[t]]);
+ int32_t a = sourceEdge->getSourceVertex();
+ int32_t b = sourceEdge->getTargetVertex();
+ const btConvexHullComputer::Edge* edge = sourceEdge->getNextEdgeOfFace();
+ int32_t c = edge->getTargetVertex();
+ while (c != a) {
+ meshCH.AddTriangle(Vec3<int32_t>(a, b, c));
+ edge = edge->getNextEdgeOfFace();
+ b = c;
+ c = edge->getTargetVertex();
+ }
+ }
+}
+void VoxelSet::GetPoints(const Voxel& voxel,
+ Vec3<double>* const pts) const
+{
+ short i = voxel.m_coord[0];
+ short j = voxel.m_coord[1];
+ short k = voxel.m_coord[2];
+ pts[0][0] = (i - 0.5) * m_scale + m_minBB[0];
+ pts[1][0] = (i + 0.5) * m_scale + m_minBB[0];
+ pts[2][0] = (i + 0.5) * m_scale + m_minBB[0];
+ pts[3][0] = (i - 0.5) * m_scale + m_minBB[0];
+ pts[4][0] = (i - 0.5) * m_scale + m_minBB[0];
+ pts[5][0] = (i + 0.5) * m_scale + m_minBB[0];
+ pts[6][0] = (i + 0.5) * m_scale + m_minBB[0];
+ pts[7][0] = (i - 0.5) * m_scale + m_minBB[0];
+ pts[0][1] = (j - 0.5) * m_scale + m_minBB[1];
+ pts[1][1] = (j - 0.5) * m_scale + m_minBB[1];
+ pts[2][1] = (j + 0.5) * m_scale + m_minBB[1];
+ pts[3][1] = (j + 0.5) * m_scale + m_minBB[1];
+ pts[4][1] = (j - 0.5) * m_scale + m_minBB[1];
+ pts[5][1] = (j - 0.5) * m_scale + m_minBB[1];
+ pts[6][1] = (j + 0.5) * m_scale + m_minBB[1];
+ pts[7][1] = (j + 0.5) * m_scale + m_minBB[1];
+ pts[0][2] = (k - 0.5) * m_scale + m_minBB[2];
+ pts[1][2] = (k - 0.5) * m_scale + m_minBB[2];
+ pts[2][2] = (k - 0.5) * m_scale + m_minBB[2];
+ pts[3][2] = (k - 0.5) * m_scale + m_minBB[2];
+ pts[4][2] = (k + 0.5) * m_scale + m_minBB[2];
+ pts[5][2] = (k + 0.5) * m_scale + m_minBB[2];
+ pts[6][2] = (k + 0.5) * m_scale + m_minBB[2];
+ pts[7][2] = (k + 0.5) * m_scale + m_minBB[2];
+}
+void VoxelSet::Intersect(const Plane& plane,
+ SArray<Vec3<double> >* const positivePts,
+ SArray<Vec3<double> >* const negativePts,
+ const size_t sampling) const
+{
+ const size_t nVoxels = m_voxels.Size();
+ if (nVoxels == 0)
+ return;
+ const double d0 = m_scale;
+ double d;
+ Vec3<double> pts[8];
+ Vec3<double> pt;
+ Voxel voxel;
+ size_t sp = 0;
+ size_t sn = 0;
+ for (size_t v = 0; v < nVoxels; ++v) {
+ voxel = m_voxels[v];
+ pt = GetPoint(voxel);
+ d = plane.m_a * pt[0] + plane.m_b * pt[1] + plane.m_c * pt[2] + plane.m_d;
+ // if (d >= 0.0 && d <= d0) positivePts->PushBack(pt);
+ // else if (d < 0.0 && -d <= d0) negativePts->PushBack(pt);
+ if (d >= 0.0) {
+ if (d <= d0) {
+ GetPoints(voxel, pts);
+ for (int32_t k = 0; k < 8; ++k) {
+ positivePts->PushBack(pts[k]);
+ }
+ }
+ else {
+ if (++sp == sampling) {
+ // positivePts->PushBack(pt);
+ GetPoints(voxel, pts);
+ for (int32_t k = 0; k < 8; ++k) {
+ positivePts->PushBack(pts[k]);
+ }
+ sp = 0;
+ }
+ }
+ }
+ else {
+ if (-d <= d0) {
+ GetPoints(voxel, pts);
+ for (int32_t k = 0; k < 8; ++k) {
+ negativePts->PushBack(pts[k]);
+ }
+ }
+ else {
+ if (++sn == sampling) {
+ // negativePts->PushBack(pt);
+ GetPoints(voxel, pts);
+ for (int32_t k = 0; k < 8; ++k) {
+ negativePts->PushBack(pts[k]);
+ }
+ sn = 0;
+ }
+ }
+ }
+ }
+}
+void VoxelSet::ComputeExteriorPoints(const Plane& plane,
+ const Mesh& mesh,
+ SArray<Vec3<double> >* const exteriorPts) const
+{
+ const size_t nVoxels = m_voxels.Size();
+ if (nVoxels == 0)
+ return;
+ double d;
+ Vec3<double> pt;
+ Vec3<double> pts[8];
+ Voxel voxel;
+ for (size_t v = 0; v < nVoxels; ++v) {
+ voxel = m_voxels[v];
+ pt = GetPoint(voxel);
+ d = plane.m_a * pt[0] + plane.m_b * pt[1] + plane.m_c * pt[2] + plane.m_d;
+ if (d >= 0.0) {
+ if (!mesh.IsInside(pt)) {
+ GetPoints(voxel, pts);
+ for (int32_t k = 0; k < 8; ++k) {
+ exteriorPts->PushBack(pts[k]);
+ }
+ }
+ }
+ }
+}
+void VoxelSet::ComputeClippedVolumes(const Plane& plane,
+ double& positiveVolume,
+ double& negativeVolume) const
+{
+ negativeVolume = 0.0;
+ positiveVolume = 0.0;
+ const size_t nVoxels = m_voxels.Size();
+ if (nVoxels == 0)
+ return;
+ double d;
+ Vec3<double> pt;
+ size_t nPositiveVoxels = 0;
+ for (size_t v = 0; v < nVoxels; ++v) {
+ pt = GetPoint(m_voxels[v]);
+ d = plane.m_a * pt[0] + plane.m_b * pt[1] + plane.m_c * pt[2] + plane.m_d;
+ nPositiveVoxels += (d >= 0.0);
+ }
+ size_t nNegativeVoxels = nVoxels - nPositiveVoxels;
+ positiveVolume = m_unitVolume * nPositiveVoxels;
+ negativeVolume = m_unitVolume * nNegativeVoxels;
+}
+void VoxelSet::SelectOnSurface(PrimitiveSet* const onSurfP) const
+{
+ VoxelSet* const onSurf = (VoxelSet*)onSurfP;
+ const size_t nVoxels = m_voxels.Size();
+ if (nVoxels == 0)
+ return;
+
+ for (int32_t h = 0; h < 3; ++h) {
+ onSurf->m_minBB[h] = m_minBB[h];
+ }
+ onSurf->m_voxels.Resize(0);
+ onSurf->m_scale = m_scale;
+ onSurf->m_unitVolume = m_unitVolume;
+ onSurf->m_numVoxelsOnSurface = 0;
+ onSurf->m_numVoxelsInsideSurface = 0;
+ Voxel voxel;
+ for (size_t v = 0; v < nVoxels; ++v) {
+ voxel = m_voxels[v];
+ if (voxel.m_data == PRIMITIVE_ON_SURFACE) {
+ onSurf->m_voxels.PushBack(voxel);
+ ++onSurf->m_numVoxelsOnSurface;
+ }
+ }
+}
+void VoxelSet::Clip(const Plane& plane,
+ PrimitiveSet* const positivePartP,
+ PrimitiveSet* const negativePartP) const
+{
+ VoxelSet* const positivePart = (VoxelSet*)positivePartP;
+ VoxelSet* const negativePart = (VoxelSet*)negativePartP;
+ const size_t nVoxels = m_voxels.Size();
+ if (nVoxels == 0)
+ return;
+
+ for (int32_t h = 0; h < 3; ++h) {
+ negativePart->m_minBB[h] = positivePart->m_minBB[h] = m_minBB[h];
+ }
+ positivePart->m_voxels.Resize(0);
+ negativePart->m_voxels.Resize(0);
+ positivePart->m_voxels.Allocate(nVoxels);
+ negativePart->m_voxels.Allocate(nVoxels);
+ negativePart->m_scale = positivePart->m_scale = m_scale;
+ negativePart->m_unitVolume = positivePart->m_unitVolume = m_unitVolume;
+ negativePart->m_numVoxelsOnSurface = positivePart->m_numVoxelsOnSurface = 0;
+ negativePart->m_numVoxelsInsideSurface = positivePart->m_numVoxelsInsideSurface = 0;
+
+ double d;
+ Vec3<double> pt;
+ Voxel voxel;
+ const double d0 = m_scale;
+ for (size_t v = 0; v < nVoxels; ++v) {
+ voxel = m_voxels[v];
+ pt = GetPoint(voxel);
+ d = plane.m_a * pt[0] + plane.m_b * pt[1] + plane.m_c * pt[2] + plane.m_d;
+ if (d >= 0.0) {
+ if (voxel.m_data == PRIMITIVE_ON_SURFACE || d <= d0) {
+ voxel.m_data = PRIMITIVE_ON_SURFACE;
+ positivePart->m_voxels.PushBack(voxel);
+ ++positivePart->m_numVoxelsOnSurface;
+ }
+ else {
+ positivePart->m_voxels.PushBack(voxel);
+ ++positivePart->m_numVoxelsInsideSurface;
+ }
+ }
+ else {
+ if (voxel.m_data == PRIMITIVE_ON_SURFACE || -d <= d0) {
+ voxel.m_data = PRIMITIVE_ON_SURFACE;
+ negativePart->m_voxels.PushBack(voxel);
+ ++negativePart->m_numVoxelsOnSurface;
+ }
+ else {
+ negativePart->m_voxels.PushBack(voxel);
+ ++negativePart->m_numVoxelsInsideSurface;
+ }
+ }
+ }
+}
+void VoxelSet::Convert(Mesh& mesh, const VOXEL_VALUE value) const
+{
+ const size_t nVoxels = m_voxels.Size();
+ if (nVoxels == 0)
+ return;
+ Voxel voxel;
+ Vec3<double> pts[8];
+ for (size_t v = 0; v < nVoxels; ++v) {
+ voxel = m_voxels[v];
+ if (voxel.m_data == value) {
+ GetPoints(voxel, pts);
+ int32_t s = (int32_t)mesh.GetNPoints();
+ for (int32_t k = 0; k < 8; ++k) {
+ mesh.AddPoint(pts[k]);
+ }
+ mesh.AddTriangle(Vec3<int32_t>(s + 0, s + 2, s + 1));
+ mesh.AddTriangle(Vec3<int32_t>(s + 0, s + 3, s + 2));
+ mesh.AddTriangle(Vec3<int32_t>(s + 4, s + 5, s + 6));
+ mesh.AddTriangle(Vec3<int32_t>(s + 4, s + 6, s + 7));
+ mesh.AddTriangle(Vec3<int32_t>(s + 7, s + 6, s + 2));
+ mesh.AddTriangle(Vec3<int32_t>(s + 7, s + 2, s + 3));
+ mesh.AddTriangle(Vec3<int32_t>(s + 4, s + 1, s + 5));
+ mesh.AddTriangle(Vec3<int32_t>(s + 4, s + 0, s + 1));
+ mesh.AddTriangle(Vec3<int32_t>(s + 6, s + 5, s + 1));
+ mesh.AddTriangle(Vec3<int32_t>(s + 6, s + 1, s + 2));
+ mesh.AddTriangle(Vec3<int32_t>(s + 7, s + 0, s + 4));
+ mesh.AddTriangle(Vec3<int32_t>(s + 7, s + 3, s + 0));
+ }
+ }
+}
+void VoxelSet::ComputePrincipalAxes()
+{
+ const size_t nVoxels = m_voxels.Size();
+ if (nVoxels == 0)
+ return;
+ m_barycenterPCA[0] = m_barycenterPCA[1] = m_barycenterPCA[2] = 0.0;
+ for (size_t v = 0; v < nVoxels; ++v) {
+ Voxel& voxel = m_voxels[v];
+ m_barycenterPCA[0] += voxel.m_coord[0];
+ m_barycenterPCA[1] += voxel.m_coord[1];
+ m_barycenterPCA[2] += voxel.m_coord[2];
+ }
+ m_barycenterPCA /= (double)nVoxels;
+
+ double covMat[3][3] = { { 0.0, 0.0, 0.0 },
+ { 0.0, 0.0, 0.0 },
+ { 0.0, 0.0, 0.0 } };
+ double x, y, z;
+ for (size_t v = 0; v < nVoxels; ++v) {
+ Voxel& voxel = m_voxels[v];
+ x = voxel.m_coord[0] - m_barycenter[0];
+ y = voxel.m_coord[1] - m_barycenter[1];
+ z = voxel.m_coord[2] - m_barycenter[2];
+ covMat[0][0] += x * x;
+ covMat[1][1] += y * y;
+ covMat[2][2] += z * z;
+ covMat[0][1] += x * y;
+ covMat[0][2] += x * z;
+ covMat[1][2] += y * z;
+ }
+ covMat[0][0] /= nVoxels;
+ covMat[1][1] /= nVoxels;
+ covMat[2][2] /= nVoxels;
+ covMat[0][1] /= nVoxels;
+ covMat[0][2] /= nVoxels;
+ covMat[1][2] /= nVoxels;
+ covMat[1][0] = covMat[0][1];
+ covMat[2][0] = covMat[0][2];
+ covMat[2][1] = covMat[1][2];
+ Diagonalize(covMat, m_Q, m_D);
+}
+Volume::Volume()
+{
+ m_dim[0] = m_dim[1] = m_dim[2] = 0;
+ m_minBB[0] = m_minBB[1] = m_minBB[2] = 0.0;
+ m_maxBB[0] = m_maxBB[1] = m_maxBB[2] = 1.0;
+ m_numVoxelsOnSurface = 0;
+ m_numVoxelsInsideSurface = 0;
+ m_numVoxelsOutsideSurface = 0;
+ m_scale = 1.0;
+ m_data = 0;
+}
+Volume::~Volume(void)
+{
+ delete[] m_data;
+}
+void Volume::Allocate()
+{
+ delete[] m_data;
+ size_t size = m_dim[0] * m_dim[1] * m_dim[2];
+ m_data = new unsigned char[size];
+ memset(m_data, PRIMITIVE_UNDEFINED, sizeof(unsigned char) * size);
+}
+void Volume::Free()
+{
+ delete[] m_data;
+ m_data = 0;
+}
+void Volume::FillOutsideSurface(const size_t i0,
+ const size_t j0,
+ const size_t k0,
+ const size_t i1,
+ const size_t j1,
+ const size_t k1)
+{
+ const short neighbours[6][3] = { { 1, 0, 0 },
+ { 0, 1, 0 },
+ { 0, 0, 1 },
+ { -1, 0, 0 },
+ { 0, -1, 0 },
+ { 0, 0, -1 } };
+ std::queue<Vec3<short> > fifo;
+ Vec3<short> current;
+ short a, b, c;
+ for (size_t i = i0; i < i1; ++i) {
+ for (size_t j = j0; j < j1; ++j) {
+ for (size_t k = k0; k < k1; ++k) {
+
+ if (GetVoxel(i, j, k) == PRIMITIVE_UNDEFINED) {
+ current[0] = (short)i;
+ current[1] = (short)j;
+ current[2] = (short)k;
+ fifo.push(current);
+ GetVoxel(current[0], current[1], current[2]) = PRIMITIVE_OUTSIDE_SURFACE;
+ ++m_numVoxelsOutsideSurface;
+ while (fifo.size() > 0) {
+ current = fifo.front();
+ fifo.pop();
+ for (int32_t h = 0; h < 6; ++h) {
+ a = current[0] + neighbours[h][0];
+ b = current[1] + neighbours[h][1];
+ c = current[2] + neighbours[h][2];
+ if (a < 0 || a >= (int32_t)m_dim[0] || b < 0 || b >= (int32_t)m_dim[1] || c < 0 || c >= (int32_t)m_dim[2]) {
+ continue;
+ }
+ unsigned char& v = GetVoxel(a, b, c);
+ if (v == PRIMITIVE_UNDEFINED) {
+ v = PRIMITIVE_OUTSIDE_SURFACE;
+ ++m_numVoxelsOutsideSurface;
+ fifo.push(Vec3<short>(a, b, c));
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+void Volume::FillInsideSurface()
+{
+ const size_t i0 = m_dim[0];
+ const size_t j0 = m_dim[1];
+ const size_t k0 = m_dim[2];
+ for (size_t i = 0; i < i0; ++i) {
+ for (size_t j = 0; j < j0; ++j) {
+ for (size_t k = 0; k < k0; ++k) {
+ unsigned char& v = GetVoxel(i, j, k);
+ if (v == PRIMITIVE_UNDEFINED) {
+ v = PRIMITIVE_INSIDE_SURFACE;
+ ++m_numVoxelsInsideSurface;
+ }
+ }
+ }
+ }
+}
+void Volume::Convert(Mesh& mesh, const VOXEL_VALUE value) const
+{
+ const size_t i0 = m_dim[0];
+ const size_t j0 = m_dim[1];
+ const size_t k0 = m_dim[2];
+ for (size_t i = 0; i < i0; ++i) {
+ for (size_t j = 0; j < j0; ++j) {
+ for (size_t k = 0; k < k0; ++k) {
+ const unsigned char& voxel = GetVoxel(i, j, k);
+ if (voxel == value) {
+ Vec3<double> p0((i - 0.5) * m_scale, (j - 0.5) * m_scale, (k - 0.5) * m_scale);
+ Vec3<double> p1((i + 0.5) * m_scale, (j - 0.5) * m_scale, (k - 0.5) * m_scale);
+ Vec3<double> p2((i + 0.5) * m_scale, (j + 0.5) * m_scale, (k - 0.5) * m_scale);
+ Vec3<double> p3((i - 0.5) * m_scale, (j + 0.5) * m_scale, (k - 0.5) * m_scale);
+ Vec3<double> p4((i - 0.5) * m_scale, (j - 0.5) * m_scale, (k + 0.5) * m_scale);
+ Vec3<double> p5((i + 0.5) * m_scale, (j - 0.5) * m_scale, (k + 0.5) * m_scale);
+ Vec3<double> p6((i + 0.5) * m_scale, (j + 0.5) * m_scale, (k + 0.5) * m_scale);
+ Vec3<double> p7((i - 0.5) * m_scale, (j + 0.5) * m_scale, (k + 0.5) * m_scale);
+ int32_t s = (int32_t)mesh.GetNPoints();
+ mesh.AddPoint(p0 + m_minBB);
+ mesh.AddPoint(p1 + m_minBB);
+ mesh.AddPoint(p2 + m_minBB);
+ mesh.AddPoint(p3 + m_minBB);
+ mesh.AddPoint(p4 + m_minBB);
+ mesh.AddPoint(p5 + m_minBB);
+ mesh.AddPoint(p6 + m_minBB);
+ mesh.AddPoint(p7 + m_minBB);
+ mesh.AddTriangle(Vec3<int32_t>(s + 0, s + 2, s + 1));
+ mesh.AddTriangle(Vec3<int32_t>(s + 0, s + 3, s + 2));
+ mesh.AddTriangle(Vec3<int32_t>(s + 4, s + 5, s + 6));
+ mesh.AddTriangle(Vec3<int32_t>(s + 4, s + 6, s + 7));
+ mesh.AddTriangle(Vec3<int32_t>(s + 7, s + 6, s + 2));
+ mesh.AddTriangle(Vec3<int32_t>(s + 7, s + 2, s + 3));
+ mesh.AddTriangle(Vec3<int32_t>(s + 4, s + 1, s + 5));
+ mesh.AddTriangle(Vec3<int32_t>(s + 4, s + 0, s + 1));
+ mesh.AddTriangle(Vec3<int32_t>(s + 6, s + 5, s + 1));
+ mesh.AddTriangle(Vec3<int32_t>(s + 6, s + 1, s + 2));
+ mesh.AddTriangle(Vec3<int32_t>(s + 7, s + 0, s + 4));
+ mesh.AddTriangle(Vec3<int32_t>(s + 7, s + 3, s + 0));
+ }
+ }
+ }
+ }
+}
+void Volume::Convert(VoxelSet& vset) const
+{
+ for (int32_t h = 0; h < 3; ++h) {
+ vset.m_minBB[h] = m_minBB[h];
+ }
+ vset.m_voxels.Allocate(m_numVoxelsInsideSurface + m_numVoxelsOnSurface);
+ vset.m_scale = m_scale;
+ vset.m_unitVolume = m_scale * m_scale * m_scale;
+ const short i0 = (short)m_dim[0];
+ const short j0 = (short)m_dim[1];
+ const short k0 = (short)m_dim[2];
+ Voxel voxel;
+ vset.m_numVoxelsOnSurface = 0;
+ vset.m_numVoxelsInsideSurface = 0;
+ for (short i = 0; i < i0; ++i) {
+ for (short j = 0; j < j0; ++j) {
+ for (short k = 0; k < k0; ++k) {
+ const unsigned char& value = GetVoxel(i, j, k);
+ if (value == PRIMITIVE_INSIDE_SURFACE) {
+ voxel.m_coord[0] = i;
+ voxel.m_coord[1] = j;
+ voxel.m_coord[2] = k;
+ voxel.m_data = PRIMITIVE_INSIDE_SURFACE;
+ vset.m_voxels.PushBack(voxel);
+ ++vset.m_numVoxelsInsideSurface;
+ }
+ else if (value == PRIMITIVE_ON_SURFACE) {
+ voxel.m_coord[0] = i;
+ voxel.m_coord[1] = j;
+ voxel.m_coord[2] = k;
+ voxel.m_data = PRIMITIVE_ON_SURFACE;
+ vset.m_voxels.PushBack(voxel);
+ ++vset.m_numVoxelsOnSurface;
+ }
+ }
+ }
+ }
+}
+
+void Volume::Convert(TetrahedronSet& tset) const
+{
+ tset.m_tetrahedra.Allocate(5 * (m_numVoxelsInsideSurface + m_numVoxelsOnSurface));
+ tset.m_scale = m_scale;
+ const short i0 = (short)m_dim[0];
+ const short j0 = (short)m_dim[1];
+ const short k0 = (short)m_dim[2];
+ tset.m_numTetrahedraOnSurface = 0;
+ tset.m_numTetrahedraInsideSurface = 0;
+ Tetrahedron tetrahedron;
+ for (short i = 0; i < i0; ++i) {
+ for (short j = 0; j < j0; ++j) {
+ for (short k = 0; k < k0; ++k) {
+ const unsigned char& value = GetVoxel(i, j, k);
+ if (value == PRIMITIVE_INSIDE_SURFACE || value == PRIMITIVE_ON_SURFACE) {
+ tetrahedron.m_data = value;
+ Vec3<double> p1((i - 0.5) * m_scale + m_minBB[0], (j - 0.5) * m_scale + m_minBB[1], (k - 0.5) * m_scale + m_minBB[2]);
+ Vec3<double> p2((i + 0.5) * m_scale + m_minBB[0], (j - 0.5) * m_scale + m_minBB[1], (k - 0.5) * m_scale + m_minBB[2]);
+ Vec3<double> p3((i + 0.5) * m_scale + m_minBB[0], (j + 0.5) * m_scale + m_minBB[1], (k - 0.5) * m_scale + m_minBB[2]);
+ Vec3<double> p4((i - 0.5) * m_scale + m_minBB[0], (j + 0.5) * m_scale + m_minBB[1], (k - 0.5) * m_scale + m_minBB[2]);
+ Vec3<double> p5((i - 0.5) * m_scale + m_minBB[0], (j - 0.5) * m_scale + m_minBB[1], (k + 0.5) * m_scale + m_minBB[2]);
+ Vec3<double> p6((i + 0.5) * m_scale + m_minBB[0], (j - 0.5) * m_scale + m_minBB[1], (k + 0.5) * m_scale + m_minBB[2]);
+ Vec3<double> p7((i + 0.5) * m_scale + m_minBB[0], (j + 0.5) * m_scale + m_minBB[1], (k + 0.5) * m_scale + m_minBB[2]);
+ Vec3<double> p8((i - 0.5) * m_scale + m_minBB[0], (j + 0.5) * m_scale + m_minBB[1], (k + 0.5) * m_scale + m_minBB[2]);
+
+ tetrahedron.m_pts[0] = p2;
+ tetrahedron.m_pts[1] = p4;
+ tetrahedron.m_pts[2] = p7;
+ tetrahedron.m_pts[3] = p5;
+ tset.m_tetrahedra.PushBack(tetrahedron);
+
+ tetrahedron.m_pts[0] = p6;
+ tetrahedron.m_pts[1] = p2;
+ tetrahedron.m_pts[2] = p7;
+ tetrahedron.m_pts[3] = p5;
+ tset.m_tetrahedra.PushBack(tetrahedron);
+
+ tetrahedron.m_pts[0] = p3;
+ tetrahedron.m_pts[1] = p4;
+ tetrahedron.m_pts[2] = p7;
+ tetrahedron.m_pts[3] = p2;
+ tset.m_tetrahedra.PushBack(tetrahedron);
+
+ tetrahedron.m_pts[0] = p1;
+ tetrahedron.m_pts[1] = p4;
+ tetrahedron.m_pts[2] = p2;
+ tetrahedron.m_pts[3] = p5;
+ tset.m_tetrahedra.PushBack(tetrahedron);
+
+ tetrahedron.m_pts[0] = p8;
+ tetrahedron.m_pts[1] = p5;
+ tetrahedron.m_pts[2] = p7;
+ tetrahedron.m_pts[3] = p4;
+ tset.m_tetrahedra.PushBack(tetrahedron);
+ if (value == PRIMITIVE_INSIDE_SURFACE) {
+ tset.m_numTetrahedraInsideSurface += 5;
+ }
+ else {
+ tset.m_numTetrahedraOnSurface += 5;
+ }
+ }
+ }
+ }
+ }
+}
+
+void Volume::AlignToPrincipalAxes(double (&rot)[3][3]) const
+{
+ const short i0 = (short)m_dim[0];
+ const short j0 = (short)m_dim[1];
+ const short k0 = (short)m_dim[2];
+ Vec3<double> barycenter(0.0);
+ size_t nVoxels = 0;
+ for (short i = 0; i < i0; ++i) {
+ for (short j = 0; j < j0; ++j) {
+ for (short k = 0; k < k0; ++k) {
+ const unsigned char& value = GetVoxel(i, j, k);
+ if (value == PRIMITIVE_INSIDE_SURFACE || value == PRIMITIVE_ON_SURFACE) {
+ barycenter[0] += i;
+ barycenter[1] += j;
+ barycenter[2] += k;
+ ++nVoxels;
+ }
+ }
+ }
+ }
+ barycenter /= (double)nVoxels;
+
+ double covMat[3][3] = { { 0.0, 0.0, 0.0 },
+ { 0.0, 0.0, 0.0 },
+ { 0.0, 0.0, 0.0 } };
+ double x, y, z;
+ for (short i = 0; i < i0; ++i) {
+ for (short j = 0; j < j0; ++j) {
+ for (short k = 0; k < k0; ++k) {
+ const unsigned char& value = GetVoxel(i, j, k);
+ if (value == PRIMITIVE_INSIDE_SURFACE || value == PRIMITIVE_ON_SURFACE) {
+ x = i - barycenter[0];
+ y = j - barycenter[1];
+ z = k - barycenter[2];
+ covMat[0][0] += x * x;
+ covMat[1][1] += y * y;
+ covMat[2][2] += z * z;
+ covMat[0][1] += x * y;
+ covMat[0][2] += x * z;
+ covMat[1][2] += y * z;
+ }
+ }
+ }
+ }
+ covMat[1][0] = covMat[0][1];
+ covMat[2][0] = covMat[0][2];
+ covMat[2][1] = covMat[1][2];
+ double D[3][3];
+ Diagonalize(covMat, rot, D);
+}
+TetrahedronSet::TetrahedronSet()
+{
+ m_minBB[0] = m_minBB[1] = m_minBB[2] = 0.0;
+ m_maxBB[0] = m_maxBB[1] = m_maxBB[2] = 1.0;
+ m_barycenter[0] = m_barycenter[1] = m_barycenter[2] = 0.0;
+ m_scale = 1.0;
+ m_numTetrahedraOnSurface = 0;
+ m_numTetrahedraInsideSurface = 0;
+ memset(m_Q, 0, sizeof(double) * 9);
+ memset(m_D, 0, sizeof(double) * 9);
+}
+TetrahedronSet::~TetrahedronSet(void)
+{
+}
+void TetrahedronSet::ComputeBB()
+{
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+
+ for (int32_t h = 0; h < 3; ++h) {
+ m_minBB[h] = m_maxBB[h] = m_tetrahedra[0].m_pts[0][h];
+ m_barycenter[h] = 0.0;
+ }
+ for (size_t p = 0; p < nTetrahedra; ++p) {
+ for (int32_t i = 0; i < 4; ++i) {
+ for (int32_t h = 0; h < 3; ++h) {
+ if (m_minBB[h] > m_tetrahedra[p].m_pts[i][h])
+ m_minBB[h] = m_tetrahedra[p].m_pts[i][h];
+ if (m_maxBB[h] < m_tetrahedra[p].m_pts[i][h])
+ m_maxBB[h] = m_tetrahedra[p].m_pts[i][h];
+ m_barycenter[h] += m_tetrahedra[p].m_pts[i][h];
+ }
+ }
+ }
+ m_barycenter /= (double)(4 * nTetrahedra);
+}
+void TetrahedronSet::ComputeConvexHull(Mesh& meshCH, const size_t sampling) const
+{
+ const size_t CLUSTER_SIZE = 65536;
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+
+ SArray<Vec3<double> > cpoints;
+
+ Vec3<double>* points = new Vec3<double>[CLUSTER_SIZE];
+ size_t p = 0;
+ while (p < nTetrahedra) {
+ size_t q = 0;
+ size_t s = 0;
+ while (q < CLUSTER_SIZE && p < nTetrahedra) {
+ if (m_tetrahedra[p].m_data == PRIMITIVE_ON_SURFACE) {
+ ++s;
+ if (s == sampling) {
+ s = 0;
+ for (int32_t a = 0; a < 4; ++a) {
+ points[q++] = m_tetrahedra[p].m_pts[a];
+ for (int32_t xx = 0; xx < 3; ++xx) {
+ assert(m_tetrahedra[p].m_pts[a][xx] + EPS >= m_minBB[xx]);
+ assert(m_tetrahedra[p].m_pts[a][xx] <= m_maxBB[xx] + EPS);
+ }
+ }
+ }
+ }
+ ++p;
+ }
+ btConvexHullComputer ch;
+ ch.compute((double*)points, 3 * sizeof(double), (int32_t)q, -1.0, -1.0);
+ for (int32_t v = 0; v < ch.vertices.size(); v++) {
+ cpoints.PushBack(Vec3<double>(ch.vertices[v].getX(), ch.vertices[v].getY(), ch.vertices[v].getZ()));
+ }
+ }
+ delete[] points;
+
+ points = cpoints.Data();
+ btConvexHullComputer ch;
+ ch.compute((double*)points, 3 * sizeof(double), (int32_t)cpoints.Size(), -1.0, -1.0);
+ meshCH.ResizePoints(0);
+ meshCH.ResizeTriangles(0);
+ for (int32_t v = 0; v < ch.vertices.size(); v++) {
+ meshCH.AddPoint(Vec3<double>(ch.vertices[v].getX(), ch.vertices[v].getY(), ch.vertices[v].getZ()));
+ }
+ const int32_t nt = ch.faces.size();
+ for (int32_t t = 0; t < nt; ++t) {
+ const btConvexHullComputer::Edge* sourceEdge = &(ch.edges[ch.faces[t]]);
+ int32_t a = sourceEdge->getSourceVertex();
+ int32_t b = sourceEdge->getTargetVertex();
+ const btConvexHullComputer::Edge* edge = sourceEdge->getNextEdgeOfFace();
+ int32_t c = edge->getTargetVertex();
+ while (c != a) {
+ meshCH.AddTriangle(Vec3<int32_t>(a, b, c));
+ edge = edge->getNextEdgeOfFace();
+ b = c;
+ c = edge->getTargetVertex();
+ }
+ }
+}
+inline bool TetrahedronSet::Add(Tetrahedron& tetrahedron)
+{
+ double v = ComputeVolume4(tetrahedron.m_pts[0], tetrahedron.m_pts[1], tetrahedron.m_pts[2], tetrahedron.m_pts[3]);
+
+ const double EPS = 0.0000000001;
+ if (fabs(v) < EPS) {
+ return false;
+ }
+ else if (v < 0.0) {
+ Vec3<double> tmp = tetrahedron.m_pts[0];
+ tetrahedron.m_pts[0] = tetrahedron.m_pts[1];
+ tetrahedron.m_pts[1] = tmp;
+ }
+
+ for (int32_t a = 0; a < 4; ++a) {
+ for (int32_t xx = 0; xx < 3; ++xx) {
+ assert(tetrahedron.m_pts[a][xx] + EPS >= m_minBB[xx]);
+ assert(tetrahedron.m_pts[a][xx] <= m_maxBB[xx] + EPS);
+ }
+ }
+ m_tetrahedra.PushBack(tetrahedron);
+ return true;
+}
+
+void TetrahedronSet::AddClippedTetrahedra(const Vec3<double> (&pts)[10], const int32_t nPts)
+{
+ const int32_t tetF[4][3] = { { 0, 1, 2 }, { 2, 1, 3 }, { 3, 1, 0 }, { 3, 0, 2 } };
+ if (nPts < 4) {
+ return;
+ }
+ else if (nPts == 4) {
+ Tetrahedron tetrahedron;
+ tetrahedron.m_data = PRIMITIVE_ON_SURFACE;
+ tetrahedron.m_pts[0] = pts[0];
+ tetrahedron.m_pts[1] = pts[1];
+ tetrahedron.m_pts[2] = pts[2];
+ tetrahedron.m_pts[3] = pts[3];
+ if (Add(tetrahedron)) {
+ ++m_numTetrahedraOnSurface;
+ }
+ }
+ else if (nPts == 5) {
+ const int32_t tet[15][4] = {
+ { 0, 1, 2, 3 }, { 1, 2, 3, 4 }, { 0, 2, 3, 4 }, { 0, 1, 3, 4 }, { 0, 1, 2, 4 },
+ };
+ const int32_t rem[5] = { 4, 0, 1, 2, 3 };
+ double maxVol = 0.0;
+ int32_t h0 = -1;
+ Tetrahedron tetrahedron0;
+ tetrahedron0.m_data = PRIMITIVE_ON_SURFACE;
+ for (int32_t h = 0; h < 5; ++h) {
+ double v = ComputeVolume4(pts[tet[h][0]], pts[tet[h][1]], pts[tet[h][2]], pts[tet[h][3]]);
+ if (v > maxVol) {
+ h0 = h;
+ tetrahedron0.m_pts[0] = pts[tet[h][0]];
+ tetrahedron0.m_pts[1] = pts[tet[h][1]];
+ tetrahedron0.m_pts[2] = pts[tet[h][2]];
+ tetrahedron0.m_pts[3] = pts[tet[h][3]];
+ maxVol = v;
+ }
+ else if (-v > maxVol) {
+ h0 = h;
+ tetrahedron0.m_pts[0] = pts[tet[h][1]];
+ tetrahedron0.m_pts[1] = pts[tet[h][0]];
+ tetrahedron0.m_pts[2] = pts[tet[h][2]];
+ tetrahedron0.m_pts[3] = pts[tet[h][3]];
+ maxVol = -v;
+ }
+ }
+ if (h0 == -1)
+ return;
+ if (Add(tetrahedron0)) {
+ ++m_numTetrahedraOnSurface;
+ }
+ else {
+ return;
+ }
+ int32_t a = rem[h0];
+ maxVol = 0.0;
+ int32_t h1 = -1;
+ Tetrahedron tetrahedron1;
+ tetrahedron1.m_data = PRIMITIVE_ON_SURFACE;
+ for (int32_t h = 0; h < 4; ++h) {
+ double v = ComputeVolume4(pts[a], tetrahedron0.m_pts[tetF[h][0]], tetrahedron0.m_pts[tetF[h][1]], tetrahedron0.m_pts[tetF[h][2]]);
+ if (v > maxVol) {
+ h1 = h;
+ tetrahedron1.m_pts[0] = pts[a];
+ tetrahedron1.m_pts[1] = tetrahedron0.m_pts[tetF[h][0]];
+ tetrahedron1.m_pts[2] = tetrahedron0.m_pts[tetF[h][1]];
+ tetrahedron1.m_pts[3] = tetrahedron0.m_pts[tetF[h][2]];
+ maxVol = v;
+ }
+ }
+ if (h1 == -1 && Add(tetrahedron1)) {
+ ++m_numTetrahedraOnSurface;
+ }
+ }
+ else if (nPts == 6) {
+
+ const int32_t tet[15][4] = { { 2, 3, 4, 5 }, { 1, 3, 4, 5 }, { 1, 2, 4, 5 }, { 1, 2, 3, 5 }, { 1, 2, 3, 4 },
+ { 0, 3, 4, 5 }, { 0, 2, 4, 5 }, { 0, 2, 3, 5 }, { 0, 2, 3, 4 }, { 0, 1, 4, 5 },
+ { 0, 1, 3, 5 }, { 0, 1, 3, 4 }, { 0, 1, 2, 5 }, { 0, 1, 2, 4 }, { 0, 1, 2, 3 } };
+ const int32_t rem[15][2] = { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 0, 5 },
+ { 1, 2 }, { 1, 3 }, { 1, 4 }, { 1, 5 }, { 2, 3 },
+ { 2, 4 }, { 2, 5 }, { 3, 4 }, { 3, 5 }, { 4, 5 } };
+ double maxVol = 0.0;
+ int32_t h0 = -1;
+ Tetrahedron tetrahedron0;
+ tetrahedron0.m_data = PRIMITIVE_ON_SURFACE;
+ for (int32_t h = 0; h < 15; ++h) {
+ double v = ComputeVolume4(pts[tet[h][0]], pts[tet[h][1]], pts[tet[h][2]], pts[tet[h][3]]);
+ if (v > maxVol) {
+ h0 = h;
+ tetrahedron0.m_pts[0] = pts[tet[h][0]];
+ tetrahedron0.m_pts[1] = pts[tet[h][1]];
+ tetrahedron0.m_pts[2] = pts[tet[h][2]];
+ tetrahedron0.m_pts[3] = pts[tet[h][3]];
+ maxVol = v;
+ }
+ else if (-v > maxVol) {
+ h0 = h;
+ tetrahedron0.m_pts[0] = pts[tet[h][1]];
+ tetrahedron0.m_pts[1] = pts[tet[h][0]];
+ tetrahedron0.m_pts[2] = pts[tet[h][2]];
+ tetrahedron0.m_pts[3] = pts[tet[h][3]];
+ maxVol = -v;
+ }
+ }
+ if (h0 == -1)
+ return;
+ if (Add(tetrahedron0)) {
+ ++m_numTetrahedraOnSurface;
+ }
+ else {
+ return;
+ }
+
+ int32_t a0 = rem[h0][0];
+ int32_t a1 = rem[h0][1];
+ int32_t h1 = -1;
+ Tetrahedron tetrahedron1;
+ tetrahedron1.m_data = PRIMITIVE_ON_SURFACE;
+ maxVol = 0.0;
+ for (int32_t h = 0; h < 4; ++h) {
+ double v = ComputeVolume4(pts[a0], tetrahedron0.m_pts[tetF[h][0]], tetrahedron0.m_pts[tetF[h][1]], tetrahedron0.m_pts[tetF[h][2]]);
+ if (v > maxVol) {
+ h1 = h;
+ tetrahedron1.m_pts[0] = pts[a0];
+ tetrahedron1.m_pts[1] = tetrahedron0.m_pts[tetF[h][0]];
+ tetrahedron1.m_pts[2] = tetrahedron0.m_pts[tetF[h][1]];
+ tetrahedron1.m_pts[3] = tetrahedron0.m_pts[tetF[h][2]];
+ maxVol = v;
+ }
+ }
+ if (h1 != -1 && Add(tetrahedron1)) {
+ ++m_numTetrahedraOnSurface;
+ }
+ else {
+ h1 = -1;
+ }
+ maxVol = 0.0;
+ int32_t h2 = -1;
+ Tetrahedron tetrahedron2;
+ tetrahedron2.m_data = PRIMITIVE_ON_SURFACE;
+ for (int32_t h = 0; h < 4; ++h) {
+ double v = ComputeVolume4(pts[a0], tetrahedron0.m_pts[tetF[h][0]], tetrahedron0.m_pts[tetF[h][1]], tetrahedron0.m_pts[tetF[h][2]]);
+ if (h == h1)
+ continue;
+ if (v > maxVol) {
+ h2 = h;
+ tetrahedron2.m_pts[0] = pts[a1];
+ tetrahedron2.m_pts[1] = tetrahedron0.m_pts[tetF[h][0]];
+ tetrahedron2.m_pts[2] = tetrahedron0.m_pts[tetF[h][1]];
+ tetrahedron2.m_pts[3] = tetrahedron0.m_pts[tetF[h][2]];
+ maxVol = v;
+ }
+ }
+ if (h1 != -1) {
+ for (int32_t h = 0; h < 4; ++h) {
+ double v = ComputeVolume4(pts[a1], tetrahedron1.m_pts[tetF[h][0]], tetrahedron1.m_pts[tetF[h][1]], tetrahedron1.m_pts[tetF[h][2]]);
+ if (h == 1)
+ continue;
+ if (v > maxVol) {
+ h2 = h;
+ tetrahedron2.m_pts[0] = pts[a1];
+ tetrahedron2.m_pts[1] = tetrahedron1.m_pts[tetF[h][0]];
+ tetrahedron2.m_pts[2] = tetrahedron1.m_pts[tetF[h][1]];
+ tetrahedron2.m_pts[3] = tetrahedron1.m_pts[tetF[h][2]];
+ maxVol = v;
+ }
+ }
+ }
+ if (h2 != -1 && Add(tetrahedron2)) {
+ ++m_numTetrahedraOnSurface;
+ }
+ }
+ else {
+ assert(0);
+ }
+}
+
+void TetrahedronSet::Intersect(const Plane& plane,
+ SArray<Vec3<double> >* const positivePts,
+ SArray<Vec3<double> >* const negativePts,
+ const size_t sampling) const
+{
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+}
+void TetrahedronSet::ComputeExteriorPoints(const Plane& plane,
+ const Mesh& mesh,
+ SArray<Vec3<double> >* const exteriorPts) const
+{
+}
+void TetrahedronSet::ComputeClippedVolumes(const Plane& plane,
+ double& positiveVolume,
+ double& negativeVolume) const
+{
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+}
+
+void TetrahedronSet::SelectOnSurface(PrimitiveSet* const onSurfP) const
+{
+ TetrahedronSet* const onSurf = (TetrahedronSet*)onSurfP;
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+ onSurf->m_tetrahedra.Resize(0);
+ onSurf->m_scale = m_scale;
+ onSurf->m_numTetrahedraOnSurface = 0;
+ onSurf->m_numTetrahedraInsideSurface = 0;
+ onSurf->m_barycenter = m_barycenter;
+ onSurf->m_minBB = m_minBB;
+ onSurf->m_maxBB = m_maxBB;
+ for (int32_t i = 0; i < 3; ++i) {
+ for (int32_t j = 0; j < 3; ++j) {
+ onSurf->m_Q[i][j] = m_Q[i][j];
+ onSurf->m_D[i][j] = m_D[i][j];
+ }
+ }
+ Tetrahedron tetrahedron;
+ for (size_t v = 0; v < nTetrahedra; ++v) {
+ tetrahedron = m_tetrahedra[v];
+ if (tetrahedron.m_data == PRIMITIVE_ON_SURFACE) {
+ onSurf->m_tetrahedra.PushBack(tetrahedron);
+ ++onSurf->m_numTetrahedraOnSurface;
+ }
+ }
+}
+void TetrahedronSet::Clip(const Plane& plane,
+ PrimitiveSet* const positivePartP,
+ PrimitiveSet* const negativePartP) const
+{
+ TetrahedronSet* const positivePart = (TetrahedronSet*)positivePartP;
+ TetrahedronSet* const negativePart = (TetrahedronSet*)negativePartP;
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+ positivePart->m_tetrahedra.Resize(0);
+ negativePart->m_tetrahedra.Resize(0);
+ positivePart->m_tetrahedra.Allocate(nTetrahedra);
+ negativePart->m_tetrahedra.Allocate(nTetrahedra);
+ negativePart->m_scale = positivePart->m_scale = m_scale;
+ negativePart->m_numTetrahedraOnSurface = positivePart->m_numTetrahedraOnSurface = 0;
+ negativePart->m_numTetrahedraInsideSurface = positivePart->m_numTetrahedraInsideSurface = 0;
+ negativePart->m_barycenter = m_barycenter;
+ positivePart->m_barycenter = m_barycenter;
+ negativePart->m_minBB = m_minBB;
+ positivePart->m_minBB = m_minBB;
+ negativePart->m_maxBB = m_maxBB;
+ positivePart->m_maxBB = m_maxBB;
+ for (int32_t i = 0; i < 3; ++i) {
+ for (int32_t j = 0; j < 3; ++j) {
+ negativePart->m_Q[i][j] = positivePart->m_Q[i][j] = m_Q[i][j];
+ negativePart->m_D[i][j] = positivePart->m_D[i][j] = m_D[i][j];
+ }
+ }
+
+ Tetrahedron tetrahedron;
+ double delta, alpha;
+ int32_t sign[4];
+ int32_t npos, nneg;
+ Vec3<double> posPts[10];
+ Vec3<double> negPts[10];
+ Vec3<double> P0, P1, M;
+ const Vec3<double> n(plane.m_a, plane.m_b, plane.m_c);
+ const int32_t edges[6][2] = { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 1, 2 }, { 1, 3 }, { 2, 3 } };
+ double dist;
+ for (size_t v = 0; v < nTetrahedra; ++v) {
+ tetrahedron = m_tetrahedra[v];
+ npos = nneg = 0;
+ for (int32_t i = 0; i < 4; ++i) {
+ dist = plane.m_a * tetrahedron.m_pts[i][0] + plane.m_b * tetrahedron.m_pts[i][1] + plane.m_c * tetrahedron.m_pts[i][2] + plane.m_d;
+ if (dist > 0.0) {
+ sign[i] = 1;
+ posPts[npos] = tetrahedron.m_pts[i];
+ ++npos;
+ }
+ else {
+ sign[i] = -1;
+ negPts[nneg] = tetrahedron.m_pts[i];
+ ++nneg;
+ }
+ }
+
+ if (npos == 4) {
+ positivePart->Add(tetrahedron);
+ if (tetrahedron.m_data == PRIMITIVE_ON_SURFACE) {
+ ++positivePart->m_numTetrahedraOnSurface;
+ }
+ else {
+ ++positivePart->m_numTetrahedraInsideSurface;
+ }
+ }
+ else if (nneg == 4) {
+ negativePart->Add(tetrahedron);
+ if (tetrahedron.m_data == PRIMITIVE_ON_SURFACE) {
+ ++negativePart->m_numTetrahedraOnSurface;
+ }
+ else {
+ ++negativePart->m_numTetrahedraInsideSurface;
+ }
+ }
+ else {
+ int32_t nnew = 0;
+ for (int32_t j = 0; j < 6; ++j) {
+ if (sign[edges[j][0]] * sign[edges[j][1]] == -1) {
+ P0 = tetrahedron.m_pts[edges[j][0]];
+ P1 = tetrahedron.m_pts[edges[j][1]];
+ delta = (P0 - P1) * n;
+ alpha = -(plane.m_d + (n * P1)) / delta;
+ assert(alpha >= 0.0 && alpha <= 1.0);
+ M = alpha * P0 + (1 - alpha) * P1;
+ for (int32_t xx = 0; xx < 3; ++xx) {
+ assert(M[xx] + EPS >= m_minBB[xx]);
+ assert(M[xx] <= m_maxBB[xx] + EPS);
+ }
+ posPts[npos++] = M;
+ negPts[nneg++] = M;
+ ++nnew;
+ }
+ }
+ negativePart->AddClippedTetrahedra(negPts, nneg);
+ positivePart->AddClippedTetrahedra(posPts, npos);
+ }
+ }
+}
+void TetrahedronSet::Convert(Mesh& mesh, const VOXEL_VALUE value) const
+{
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+ for (size_t v = 0; v < nTetrahedra; ++v) {
+ const Tetrahedron& tetrahedron = m_tetrahedra[v];
+ if (tetrahedron.m_data == value) {
+ int32_t s = (int32_t)mesh.GetNPoints();
+ mesh.AddPoint(tetrahedron.m_pts[0]);
+ mesh.AddPoint(tetrahedron.m_pts[1]);
+ mesh.AddPoint(tetrahedron.m_pts[2]);
+ mesh.AddPoint(tetrahedron.m_pts[3]);
+ mesh.AddTriangle(Vec3<int32_t>(s + 0, s + 1, s + 2));
+ mesh.AddTriangle(Vec3<int32_t>(s + 2, s + 1, s + 3));
+ mesh.AddTriangle(Vec3<int32_t>(s + 3, s + 1, s + 0));
+ mesh.AddTriangle(Vec3<int32_t>(s + 3, s + 0, s + 2));
+ }
+ }
+}
+const double TetrahedronSet::ComputeVolume() const
+{
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return 0.0;
+ double volume = 0.0;
+ for (size_t v = 0; v < nTetrahedra; ++v) {
+ const Tetrahedron& tetrahedron = m_tetrahedra[v];
+ volume += fabs(ComputeVolume4(tetrahedron.m_pts[0], tetrahedron.m_pts[1], tetrahedron.m_pts[2], tetrahedron.m_pts[3]));
+ }
+ return volume / 6.0;
+}
+const double TetrahedronSet::ComputeMaxVolumeError() const
+{
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return 0.0;
+ double volume = 0.0;
+ for (size_t v = 0; v < nTetrahedra; ++v) {
+ const Tetrahedron& tetrahedron = m_tetrahedra[v];
+ if (tetrahedron.m_data == PRIMITIVE_ON_SURFACE) {
+ volume += fabs(ComputeVolume4(tetrahedron.m_pts[0], tetrahedron.m_pts[1], tetrahedron.m_pts[2], tetrahedron.m_pts[3]));
+ }
+ }
+ return volume / 6.0;
+}
+void TetrahedronSet::RevertAlignToPrincipalAxes()
+{
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+ double x, y, z;
+ for (size_t v = 0; v < nTetrahedra; ++v) {
+ Tetrahedron& tetrahedron = m_tetrahedra[v];
+ for (int32_t i = 0; i < 4; ++i) {
+ x = tetrahedron.m_pts[i][0] - m_barycenter[0];
+ y = tetrahedron.m_pts[i][1] - m_barycenter[1];
+ z = tetrahedron.m_pts[i][2] - m_barycenter[2];
+ tetrahedron.m_pts[i][0] = m_Q[0][0] * x + m_Q[0][1] * y + m_Q[0][2] * z + m_barycenter[0];
+ tetrahedron.m_pts[i][1] = m_Q[1][0] * x + m_Q[1][1] * y + m_Q[1][2] * z + m_barycenter[1];
+ tetrahedron.m_pts[i][2] = m_Q[2][0] * x + m_Q[2][1] * y + m_Q[2][2] * z + m_barycenter[2];
+ }
+ }
+ ComputeBB();
+}
+void TetrahedronSet::ComputePrincipalAxes()
+{
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+ double covMat[3][3] = { { 0.0, 0.0, 0.0 },
+ { 0.0, 0.0, 0.0 },
+ { 0.0, 0.0, 0.0 } };
+ double x, y, z;
+ for (size_t v = 0; v < nTetrahedra; ++v) {
+ Tetrahedron& tetrahedron = m_tetrahedra[v];
+ for (int32_t i = 0; i < 4; ++i) {
+ x = tetrahedron.m_pts[i][0] - m_barycenter[0];
+ y = tetrahedron.m_pts[i][1] - m_barycenter[1];
+ z = tetrahedron.m_pts[i][2] - m_barycenter[2];
+ covMat[0][0] += x * x;
+ covMat[1][1] += y * y;
+ covMat[2][2] += z * z;
+ covMat[0][1] += x * y;
+ covMat[0][2] += x * z;
+ covMat[1][2] += y * z;
+ }
+ }
+ double n = nTetrahedra * 4.0;
+ covMat[0][0] /= n;
+ covMat[1][1] /= n;
+ covMat[2][2] /= n;
+ covMat[0][1] /= n;
+ covMat[0][2] /= n;
+ covMat[1][2] /= n;
+ covMat[1][0] = covMat[0][1];
+ covMat[2][0] = covMat[0][2];
+ covMat[2][1] = covMat[1][2];
+ Diagonalize(covMat, m_Q, m_D);
+}
+void TetrahedronSet::AlignToPrincipalAxes()
+{
+ const size_t nTetrahedra = m_tetrahedra.Size();
+ if (nTetrahedra == 0)
+ return;
+ double x, y, z;
+ for (size_t v = 0; v < nTetrahedra; ++v) {
+ Tetrahedron& tetrahedron = m_tetrahedra[v];
+ for (int32_t i = 0; i < 4; ++i) {
+ x = tetrahedron.m_pts[i][0] - m_barycenter[0];
+ y = tetrahedron.m_pts[i][1] - m_barycenter[1];
+ z = tetrahedron.m_pts[i][2] - m_barycenter[2];
+ tetrahedron.m_pts[i][0] = m_Q[0][0] * x + m_Q[1][0] * y + m_Q[2][0] * z + m_barycenter[0];
+ tetrahedron.m_pts[i][1] = m_Q[0][1] * x + m_Q[1][1] * y + m_Q[2][1] * z + m_barycenter[1];
+ tetrahedron.m_pts[i][2] = m_Q[0][2] * x + m_Q[1][2] * y + m_Q[2][2] * z + m_barycenter[2];
+ }
+ }
+ ComputeBB();
+}
+}