diff options
-rw-r--r-- | core/os/thread.cpp | 6 | ||||
-rw-r--r-- | core/os/thread.h | 9 | ||||
-rw-r--r-- | doc/classes/@GlobalScope.xml | 56 | ||||
-rw-r--r-- | doc/classes/TileData.xml | 30 | ||||
-rw-r--r-- | doc/classes/TileMap.xml | 18 | ||||
-rw-r--r-- | editor/plugins/tiles/tile_data_editors.cpp | 91 | ||||
-rw-r--r-- | modules/gltf/gltf_document.cpp | 631 | ||||
-rw-r--r-- | modules/gltf/gltf_document.h | 63 | ||||
-rw-r--r-- | modules/gltf/gltf_state.h | 5 | ||||
-rw-r--r-- | modules/text_server_fb/text_server_fb.cpp | 39 | ||||
-rw-r--r-- | scene/2d/tile_map.cpp | 266 | ||||
-rw-r--r-- | scene/2d/tile_map.h | 13 | ||||
-rw-r--r-- | scene/resources/tile_set.cpp | 74 | ||||
-rw-r--r-- | scene/resources/tile_set.h | 8 |
14 files changed, 743 insertions, 566 deletions
diff --git a/core/os/thread.cpp b/core/os/thread.cpp index 92e43963d2..27aefc98de 100644 --- a/core/os/thread.cpp +++ b/core/os/thread.cpp @@ -28,9 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -// Define PLATFORM_CUSTOM_THREAD_H in platform_config.h -// Overriding the platform implementation is required in some proprietary platforms -#ifndef PLATFORM_CUSTOM_THREAD_H +#ifndef PLATFORM_THREAD_OVERRIDE // See details in thread.h #include "thread.h" @@ -130,4 +128,4 @@ Thread::~Thread() { } #endif -#endif // PLATFORM_CUSTOM_THREAD_H +#endif // PLATFORM_THREAD_OVERRIDE diff --git a/core/os/thread.h b/core/os/thread.h index 3a0938c7f7..59cb58ac57 100644 --- a/core/os/thread.h +++ b/core/os/thread.h @@ -28,10 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -// Define PLATFORM_CUSTOM_THREAD_H in platform_config.h +// Define PLATFORM_THREAD_OVERRIDE in your platform's `platform_config.h` +// to use a custom Thread implementation defined in `platform/[your_platform]/platform_thread.h` // Overriding the platform implementation is required in some proprietary platforms -#ifdef PLATFORM_CUSTOM_THREAD_H -#include PLATFORM_CUSTOM_THREAD_H +#ifdef PLATFORM_THREAD_OVERRIDE +#include "platform_thread.h" #else #ifndef THREAD_H #define THREAD_H @@ -121,4 +122,4 @@ public: }; #endif // THREAD_H -#endif // PLATFORM_CUSTOM_THREAD_H +#endif // PLATFORM_THREAD_OVERRIDE diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml index 0334bab32a..4c306b6df1 100644 --- a/doc/classes/@GlobalScope.xml +++ b/doc/classes/@GlobalScope.xml @@ -23,7 +23,7 @@ Returns the absolute value of float parameter [code]x[/code] (i.e. positive value). [codeblock] # a is 1.2 - a = absf(-1.2) + var a = absf(-1.2) [/codeblock] </description> </method> @@ -34,7 +34,7 @@ Returns the absolute value of int parameter [code]x[/code] (i.e. positive value). [codeblock] # a is 1 - a = absi(-1) + var a = absi(-1) [/codeblock] </description> </method> @@ -45,7 +45,7 @@ Returns the arc cosine of [code]x[/code] in radians. Use to get the angle of cosine [code]x[/code]. [code]x[/code] must be between [code]-1.0[/code] and [code]1.0[/code] (inclusive), otherwise, [method acos] will return [constant @GDScript.NAN]. [codeblock] # c is 0.523599 or 30 degrees if converted with rad2deg(c) - c = acos(0.866025) + var c = acos(0.866025) [/codeblock] </description> </method> @@ -56,7 +56,7 @@ Returns the arc sine of [code]x[/code] in radians. Use to get the angle of sine [code]x[/code]. [code]x[/code] must be between [code]-1.0[/code] and [code]1.0[/code] (inclusive), otherwise, [method asin] will return [constant @GDScript.NAN]. [codeblock] # s is 0.523599 or 30 degrees if converted with rad2deg(s) - s = asin(0.5) + var s = asin(0.5) [/codeblock] </description> </method> @@ -64,11 +64,12 @@ <return type="float" /> <argument index="0" name="x" type="float" /> <description> - Returns the arc tangent of [code]x[/code] in radians. Use it to get the angle from an angle's tangent in trigonometry: [code]atan(tan(angle)) == angle[/code]. + Returns the arc tangent of [code]x[/code] in radians. Use it to get the angle from an angle's tangent in trigonometry. The method cannot know in which quadrant the angle should fall. See [method atan2] if you have both [code]y[/code] and [code]x[/code]. [codeblock] - a = atan(0.5) # a is 0.463648 + var a = atan(0.5) # a is 0.463648 [/codeblock] + If [code]x[/code] is between [code]-PI / 2[/code] and [code]PI / 2[/code] (inclusive), [code]atan(tan(x))[/code] is equal to [code]x[/code]. </description> </method> <method name="atan2"> @@ -79,7 +80,7 @@ Returns the arc tangent of [code]y/x[/code] in radians. Use to get the angle of tangent [code]y/x[/code]. To compute the value, the method takes into account the sign of both arguments in order to determine the quadrant. Important note: The Y coordinate comes first, by convention. [codeblock] - a = atan2(0, -1) # a is 3.141593 + var a = atan2(0, -1) # a is 3.141593 [/codeblock] </description> </method> @@ -105,8 +106,8 @@ <description> Rounds [code]x[/code] upward (towards positive infinity), returning the smallest whole number that is not less than [code]x[/code]. [codeblock] - i = ceil(1.45) # i is 2 - i = ceil(1.001) # i is 2 + var i = ceil(1.45) # i is 2.0 + i = ceil(1.001) # i is 2.0 [/codeblock] See also [method floor], [method round], and [method snapped]. </description> @@ -127,9 +128,9 @@ <description> Clamps the float [code]value[/code] and returns a value not less than [code]min[/code] and not more than [code]max[/code]. [codeblock] - speed = 42.1 + var speed = 42.1 # a is 20.0 - a = clampf(speed, 1.0, 20.0) + var a = clampf(speed, 1.0, 20.0) speed = -10.0 # a is -1.0 @@ -145,9 +146,9 @@ <description> Clamps the integer [code]value[/code] and returns a value not less than [code]min[/code] and not more than [code]max[/code]. [codeblock] - speed = 42 + var speed = 42 # a is 20 - a = clampi(speed, 1, 20) + var a = clampi(speed, 1, 20) speed = -10 # a is -1 @@ -161,9 +162,9 @@ <description> Returns the cosine of angle [code]angle_rad[/code] in radians. [codeblock] - # Prints 1 then -1 - print(cos(PI * 2)) - print(cos(PI)) + cos(PI * 2) # Returns 1.0 + cos(PI) # Returns -1.0 + cos(deg2rad(90)) # Returns 0.0 [/codeblock] </description> </method> @@ -192,7 +193,7 @@ Converts an angle expressed in degrees to radians. [codeblock] # r is 3.141593 - r = deg2rad(180) + var r = deg2rad(180) [/codeblock] </description> </method> @@ -219,7 +220,7 @@ [b]e[/b] has an approximate value of 2.71828, and can be obtained with [code]exp(1)[/code]. For exponents to other bases use the method [method pow]. [codeblock] - a = exp(2) # Approximately 7.39 + var a = exp(2) # Approximately 7.39 [/codeblock] </description> </method> @@ -230,7 +231,7 @@ Rounds [code]x[/code] downward (towards negative infinity), returning the largest whole number that is not more than [code]x[/code]. [codeblock] # a is 2.0 - a = floor(2.99) + var a = floor(2.99) # a is -3.0 a = floor(-2.99) [/codeblock] @@ -550,7 +551,7 @@ <description> Converts one or more arguments of any type to string in the best way possible and prints them to the console. [codeblock] - a = [1, 2, 3] + var a = [1, 2, 3] print("a", "b", a) # Prints ab[1, 2, 3] [/codeblock] [b]Note:[/b] Consider using [method push_error] and [method push_warning] to print error and warning messages instead of [method print]. This distinguishes them from print messages used for debugging purposes, while also displaying a stack trace when an error or warning is printed. @@ -729,7 +730,7 @@ <description> Sets seed for the random number generator. [codeblock] - my_seed = "Godot Rocks" + var my_seed = "Godot Rocks" seed(my_seed.hash()) [/codeblock] </description> @@ -770,7 +771,8 @@ <description> Returns the sine of angle [code]angle_rad[/code] in radians. [codeblock] - sin(0.523599) # Returns 0.5 + sin(0.523599) # Returns 0.5 + sin(deg2rad(90)) # Returns 1.0 [/codeblock] </description> </method> @@ -780,7 +782,7 @@ <description> Returns the hyperbolic sine of [code]x[/code]. [codeblock] - a = log(2.0) # Returns 0.693147 + var a = log(2.0) # Returns 0.693147 sinh(a) # Returns 0.75 [/codeblock] </description> @@ -833,7 +835,7 @@ Returns the position of the first non-zero digit, after the decimal point. Note that the maximum return value is 10, which is a design decision in the implementation. [codeblock] # n is 0 - n = step_decimals(5) + var n = step_decimals(5) # n is 4 n = step_decimals(1.0005) # n is 9 @@ -853,8 +855,8 @@ <description> Converts a formatted string that was returned by [method var2str] to the original value. [codeblock] - a = '{ "a": 1, "b": 2 }' - b = str2var(a) + var a = '{ "a": 1, "b": 2 }' + var b = str2var(a) print(b["a"]) # Prints 1 [/codeblock] </description> @@ -875,7 +877,7 @@ <description> Returns the hyperbolic tangent of [code]x[/code]. [codeblock] - a = log(2.0) # Returns 0.693147 + var a = log(2.0) # Returns 0.693147 tanh(a) # Returns 0.6 [/codeblock] </description> diff --git a/doc/classes/TileData.xml b/doc/classes/TileData.xml index 0d3282c6d3..81c5743ccc 100644 --- a/doc/classes/TileData.xml +++ b/doc/classes/TileData.xml @@ -37,6 +37,20 @@ Returns how many polygons the tile has for TileSet physics layer with index [code]layer_id[/code]. </description> </method> + <method name="get_constant_angular_velocity" qualifiers="const"> + <return type="float" /> + <argument index="0" name="layer_id" type="int" /> + <description> + Returns the constant angular velocity applied to objects colliding with this tile. + </description> + </method> + <method name="get_constant_linear_velocity" qualifiers="const"> + <return type="Vector2" /> + <argument index="0" name="layer_id" type="int" /> + <description> + Returns the constant linear velocity applied to objects colliding with this tile. + </description> + </method> <method name="get_custom_data" qualifiers="const"> <return type="Variant" /> <argument index="0" name="layer_name" type="String" /> @@ -123,6 +137,22 @@ Sets the polygons count for TileSet physics layer with index [code]layer_id[/code]. </description> </method> + <method name="set_constant_angular_velocity"> + <return type="void" /> + <argument index="0" name="layer_id" type="int" /> + <argument index="1" name="velocity" type="float" /> + <description> + Sets the constant angular velocity. This does not rotate the tile. This angular velocity is applied to objects colliding with this tile. + </description> + </method> + <method name="set_constant_linear_velocity"> + <return type="void" /> + <argument index="0" name="layer_id" type="int" /> + <argument index="1" name="velocity" type="Vector2" /> + <description> + Sets the constant linear velocity. This does not move the tile. This linear velocity is applied to objects colliding with this tile. This is useful to create conveyor belts. + </description> + </method> <method name="set_custom_data"> <return type="void" /> <argument index="0" name="layer_name" type="String" /> diff --git a/doc/classes/TileMap.xml b/doc/classes/TileMap.xml index 4621d138ac..e5fe823be6 100644 --- a/doc/classes/TileMap.xml +++ b/doc/classes/TileMap.xml @@ -29,6 +29,13 @@ Clears all cells. </description> </method> + <method name="clear_layer"> + <return type="void" /> + <argument index="0" name="layer" type="int" /> + <description> + Clears all cells on the given layer. + </description> + </method> <method name="fix_invalid_tiles"> <return type="void" /> <description> @@ -62,6 +69,13 @@ Returns the tile source ID of the cell on layer [code]layer[/code] at coordinates [code]coords[/code]. If [code]use_proxies[/code] is [code]false[/code], ignores the [TileSet]'s tile proxies, returning the raw alternative identifier. See [method TileSet.map_tile_proxy]. </description> </method> + <method name="get_coords_for_body_rid"> + <return type="Vector2i" /> + <argument index="0" name="body" type="RID" /> + <description> + Returns the coodinates of the tile for given physics body RID. Such RID can be retrieved from [member KinematicCollision2D.collider_rid], when colliding with a tile. + </description> + </method> <method name="get_layer_name" qualifiers="const"> <return type="String" /> <argument index="0" name="layer" type="int" /> @@ -220,6 +234,10 @@ <member name="cell_quadrant_size" type="int" setter="set_quadrant_size" getter="get_quadrant_size" default="16"> The TileMap's quadrant size. Optimizes drawing by batching, using chunks of this size. </member> + <member name="collision_animatable" type="bool" setter="set_collision_animatable" getter="is_collision_animatable" default="false"> + If enabled, the TileMap will see its collisions synced to the physics tick and change its collision type from static to kinematic. This is required to create TileMap-based moving platform. + [b]Note:[/b] Enabling [code]collision_animatable[/code] may have a small performance impact, only do it if the TileMap is moving and has colliding tiles. + </member> <member name="collision_visibility_mode" type="int" setter="set_collision_visibility_mode" getter="get_collision_visibility_mode" enum="TileMap.VisibilityMode" default="0"> Show or hide the TileMap's collision shapes. If set to [code]VISIBILITY_MODE_DEFAULT[/code], this depends on the show collision debug settings. </member> diff --git a/editor/plugins/tiles/tile_data_editors.cpp b/editor/plugins/tiles/tile_data_editors.cpp index 216c5f7c7d..5f72cfe313 100644 --- a/editor/plugins/tiles/tile_data_editors.cpp +++ b/editor/plugins/tiles/tile_data_editors.cpp @@ -231,10 +231,14 @@ void GenericTilePolygonEditor::_zoom_changed() { void GenericTilePolygonEditor::_advanced_menu_item_pressed(int p_item_pressed) { switch (p_item_pressed) { - case RESET_TO_DEFAULT_TILE: + case RESET_TO_DEFAULT_TILE: { undo_redo->create_action(TTR("Edit Polygons")); undo_redo->add_do_method(this, "clear_polygons"); - undo_redo->add_do_method(this, "add_polygon", tile_set->get_tile_shape_polygon()); + Vector<Vector2> polygon = tile_set->get_tile_shape_polygon(); + for (int i = 0; i < polygon.size(); i++) { + polygon.write[i] = polygon[i] * tile_set->get_tile_size(); + } + undo_redo->add_do_method(this, "add_polygon", polygon); undo_redo->add_do_method(base_control, "update"); undo_redo->add_do_method(this, "emit_signal", "polygons_changed"); undo_redo->add_undo_method(this, "clear_polygons"); @@ -244,8 +248,8 @@ void GenericTilePolygonEditor::_advanced_menu_item_pressed(int p_item_pressed) { undo_redo->add_undo_method(base_control, "update"); undo_redo->add_undo_method(this, "emit_signal", "polygons_changed"); undo_redo->commit_action(true); - break; - case CLEAR_TILE: + } break; + case CLEAR_TILE: { undo_redo->create_action(TTR("Edit Polygons")); undo_redo->add_do_method(this, "clear_polygons"); undo_redo->add_do_method(base_control, "update"); @@ -257,7 +261,7 @@ void GenericTilePolygonEditor::_advanced_menu_item_pressed(int p_item_pressed) { undo_redo->add_undo_method(base_control, "update"); undo_redo->add_undo_method(this, "emit_signal", "polygons_changed"); undo_redo->commit_action(true); - break; + } break; default: break; } @@ -308,6 +312,9 @@ void GenericTilePolygonEditor::_snap_to_tile_shape(Point2 &r_point, float &r_cur ERR_FAIL_COND(!tile_set.is_valid()); Vector<Point2> polygon = tile_set->get_tile_shape_polygon(); + for (int i = 0; i < polygon.size(); i++) { + polygon.write[i] = polygon[i] * tile_set->get_tile_size(); + } Point2 snapped_point = r_point; // Snap to polygon vertices. @@ -539,7 +546,11 @@ void GenericTilePolygonEditor::set_tile_set(Ref<TileSet> p_tile_set) { // Set the default tile shape clear_polygons(); if (p_tile_set.is_valid()) { - add_polygon(p_tile_set->get_tile_shape_polygon()); + Vector<Vector2> polygon = p_tile_set->get_tile_shape_polygon(); + for (int i = 0; i < polygon.size(); i++) { + polygon.write[i] = polygon[i] * p_tile_set->get_tile_size(); + } + add_polygon(polygon); } } tile_set = p_tile_set; @@ -1265,17 +1276,21 @@ void TileDataCollisionEditor::_polygons_changed() { } Variant TileDataCollisionEditor::_get_painted_value() { + Dictionary dict; + dict["linear_velocity"] = dummy_object->get("linear_velocity"); + dict["angular_velocity"] = dummy_object->get("angular_velocity"); Array array; for (int i = 0; i < polygon_editor->get_polygon_count(); i++) { ERR_FAIL_COND_V(polygon_editor->get_polygon(i).size() < 3, Variant()); - Dictionary dict; - dict["points"] = polygon_editor->get_polygon(i); - dict["one_way"] = dummy_object->get(vformat("polygon_%d_one_way", i)); - dict["one_way_margin"] = dummy_object->get(vformat("polygon_%d_one_way_margin", i)); - array.push_back(dict); + Dictionary polygon_dict; + polygon_dict["points"] = polygon_editor->get_polygon(i); + polygon_dict["one_way"] = dummy_object->get(vformat("polygon_%d_one_way", i)); + polygon_dict["one_way_margin"] = dummy_object->get(vformat("polygon_%d_one_way_margin", i)); + array.push_back(polygon_dict); } + dict["polygons"] = array; - return array; + return dict; } void TileDataCollisionEditor::_set_painted_value(TileSetAtlasSource *p_tile_set_atlas_source, Vector2 p_coords, int p_alternative_tile) { @@ -1291,6 +1306,8 @@ void TileDataCollisionEditor::_set_painted_value(TileSetAtlasSource *p_tile_set_ } _polygons_changed(); + dummy_object->set("linear_velocity", tile_data->get_constant_linear_velocity(physics_layer)); + dummy_object->set("angular_velocity", tile_data->get_constant_angular_velocity(physics_layer)); for (int i = 0; i < tile_data->get_collision_polygons_count(physics_layer); i++) { dummy_object->set(vformat("polygon_%d_one_way", i), tile_data->is_collision_polygon_one_way(physics_layer, i)); dummy_object->set(vformat("polygon_%d_one_way_margin", i), tile_data->get_collision_polygon_one_way_margin(physics_layer, i)); @@ -1306,13 +1323,16 @@ void TileDataCollisionEditor::_set_value(TileSetAtlasSource *p_tile_set_atlas_so TileData *tile_data = Object::cast_to<TileData>(p_tile_set_atlas_source->get_tile_data(p_coords, p_alternative_tile)); ERR_FAIL_COND(!tile_data); - Array array = p_value; + Dictionary dict = p_value; + tile_data->set_constant_linear_velocity(physics_layer, dict["linear_velocity"]); + tile_data->set_constant_angular_velocity(physics_layer, dict["angular_velocity"]); + Array array = dict["polygons"]; tile_data->set_collision_polygons_count(physics_layer, array.size()); for (int i = 0; i < array.size(); i++) { - Dictionary dict = array[i]; - tile_data->set_collision_polygon_points(physics_layer, i, dict["points"]); - tile_data->set_collision_polygon_one_way(physics_layer, i, dict["one_way"]); - tile_data->set_collision_polygon_one_way_margin(physics_layer, i, dict["one_way_margin"]); + Dictionary polygon_dict = array[i]; + tile_data->set_collision_polygon_points(physics_layer, i, polygon_dict["points"]); + tile_data->set_collision_polygon_one_way(physics_layer, i, polygon_dict["one_way"]); + tile_data->set_collision_polygon_one_way_margin(physics_layer, i, polygon_dict["one_way_margin"]); } polygon_editor->set_background(p_tile_set_atlas_source->get_texture(), p_tile_set_atlas_source->get_tile_texture_region(p_coords), p_tile_set_atlas_source->get_tile_effective_texture_offset(p_coords, p_alternative_tile), tile_data->get_flip_h(), tile_data->get_flip_v(), tile_data->get_transpose(), tile_data->get_modulate()); @@ -1322,15 +1342,19 @@ Variant TileDataCollisionEditor::_get_value(TileSetAtlasSource *p_tile_set_atlas TileData *tile_data = Object::cast_to<TileData>(p_tile_set_atlas_source->get_tile_data(p_coords, p_alternative_tile)); ERR_FAIL_COND_V(!tile_data, Variant()); + Dictionary dict; + dict["linear_velocity"] = tile_data->get_constant_linear_velocity(physics_layer); + dict["angular_velocity"] = tile_data->get_constant_angular_velocity(physics_layer); Array array; for (int i = 0; i < tile_data->get_collision_polygons_count(physics_layer); i++) { - Dictionary dict; - dict["points"] = tile_data->get_collision_polygon_points(physics_layer, i); - dict["one_way"] = tile_data->is_collision_polygon_one_way(physics_layer, i); - dict["one_way_margin"] = tile_data->get_collision_polygon_one_way_margin(physics_layer, i); - array.push_back(dict); + Dictionary polygon_dict; + polygon_dict["points"] = tile_data->get_collision_polygon_points(physics_layer, i); + polygon_dict["one_way"] = tile_data->is_collision_polygon_one_way(physics_layer, i); + polygon_dict["one_way_margin"] = tile_data->get_collision_polygon_one_way_margin(physics_layer, i); + array.push_back(polygon_dict); } - return array; + dict["polygons"] = array; + return dict; } void TileDataCollisionEditor::_setup_undo_redo_action(TileSetAtlasSource *p_tile_set_atlas_source, Map<TileMapCell, Variant> p_previous_values, Variant p_new_value) { @@ -1378,6 +1402,27 @@ TileDataCollisionEditor::TileDataCollisionEditor() { polygon_editor->connect("polygons_changed", callable_mp(this, &TileDataCollisionEditor::_polygons_changed)); add_child(polygon_editor); + dummy_object->add_dummy_property("linear_velocity"); + dummy_object->set("linear_velocity", Vector2()); + dummy_object->add_dummy_property("angular_velocity"); + dummy_object->set("angular_velocity", 0.0); + + EditorProperty *linear_velocity_editor = EditorInspectorDefaultPlugin::get_editor_for_property(dummy_object, Variant::VECTOR2, "linear_velocity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); + linear_velocity_editor->set_object_and_property(dummy_object, "linear_velocity"); + linear_velocity_editor->set_label("linear_velocity"); + linear_velocity_editor->connect("property_changed", callable_mp(this, &TileDataCollisionEditor::_property_value_changed).unbind(1)); + linear_velocity_editor->update_property(); + add_child(linear_velocity_editor); + property_editors["linear_velocity"] = linear_velocity_editor; + + EditorProperty *angular_velocity_editor = EditorInspectorDefaultPlugin::get_editor_for_property(dummy_object, Variant::FLOAT, "angular_velocity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT); + angular_velocity_editor->set_object_and_property(dummy_object, "angular_velocity"); + angular_velocity_editor->set_label("angular_velocity"); + angular_velocity_editor->connect("property_changed", callable_mp(this, &TileDataCollisionEditor::_property_value_changed).unbind(1)); + angular_velocity_editor->update_property(); + add_child(angular_velocity_editor); + property_editors["angular_velocity"] = linear_velocity_editor; + _polygons_changed(); } diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp index a92eb88edb..5f2e8d4ba6 100644 --- a/modules/gltf/gltf_document.cpp +++ b/modules/gltf/gltf_document.cpp @@ -78,7 +78,10 @@ Error GLTFDocument::serialize(Ref<GLTFState> state, Node *p_root, const String &p_path) { uint64_t begin_time = OS::get_singleton()->get_ticks_usec(); - _convert_scene_node(state, p_root, p_root, -1, -1); + state->skeleton3d_to_gltf_skeleton.clear(); + state->skin_and_skeleton3d_to_gltf_skin.clear(); + + _convert_scene_node(state, p_root, -1, -1); if (!state->buffers.size()) { state->buffers.push_back(Vector<uint8_t>()); } @@ -97,11 +100,7 @@ Error GLTFDocument::serialize(Ref<GLTFState> state, Node *p_root, const String & if (err != OK) { return Error::FAILED; } - /* STEP 4 CREATE BONE ATTACHMENTS */ - err = _serialize_bone_attachment(state); - if (err != OK) { - return Error::FAILED; - } + /* STEP 5 SERIALIZE MESHES (we have enough info now) */ err = _serialize_meshes(state); if (err != OK) { @@ -249,30 +248,6 @@ Error GLTFDocument::_parse_json(const String &p_path, Ref<GLTFState> state) { return OK; } -Error GLTFDocument::_serialize_bone_attachment(Ref<GLTFState> state) { - for (int skeleton_i = 0; skeleton_i < state->skeletons.size(); skeleton_i++) { - for (int attachment_i = 0; attachment_i < state->skeletons[skeleton_i]->bone_attachments.size(); attachment_i++) { - BoneAttachment3D *bone_attachment = state->skeletons[skeleton_i]->bone_attachments[attachment_i]; - String bone_name = bone_attachment->get_bone_name(); - bone_name = _sanitize_bone_name(bone_name); - int32_t bone = state->skeletons[skeleton_i]->godot_skeleton->find_bone(bone_name); - ERR_CONTINUE(bone == -1); - for (int skin_i = 0; skin_i < state->skins.size(); skin_i++) { - if (state->skins[skin_i]->skeleton != skeleton_i) { - continue; - } - - for (int node_i = 0; node_i < bone_attachment->get_child_count(); node_i++) { - ERR_CONTINUE(bone >= state->skins[skin_i]->joints.size()); - _convert_scene_node(state, bone_attachment->get_child(node_i), bone_attachment->get_owner(), state->skins[skin_i]->joints[bone], 0); - } - break; - } - } - } - return OK; -} - Error GLTFDocument::_parse_glb(const String &p_path, Ref<GLTFState> state) { Error err; FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err); @@ -2131,11 +2106,14 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) { continue; } Array primitives; - Array targets; Dictionary gltf_mesh; Array target_names; Array weights; + for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) { + target_names.push_back(import_mesh->get_blend_shape_name(morph_i)); + } for (int surface_i = 0; surface_i < import_mesh->get_surface_count(); surface_i++) { + Array targets; Dictionary primitive; Mesh::PrimitiveType primitive_type = import_mesh->get_surface_primitive_type(surface_i); switch (primitive_type) { @@ -2337,10 +2315,10 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) { const Array &a = array[Mesh::ARRAY_WEIGHTS]; const Vector<Vector3> &vertex_array = array[Mesh::ARRAY_VERTEX]; if ((a.size() / JOINT_GROUP_SIZE) == vertex_array.size()) { - const int ret_size = a.size() / JOINT_GROUP_SIZE; + int32_t vertex_count = vertex_array.size(); Vector<Color> attribs; - attribs.resize(ret_size); - for (int i = 0; i < ret_size; i++) { + attribs.resize(vertex_count); + for (int i = 0; i < vertex_count; i++) { attribs.write[i] = Color(a[(i * JOINT_GROUP_SIZE) + 0], a[(i * JOINT_GROUP_SIZE) + 1], a[(i * JOINT_GROUP_SIZE) + 2], a[(i * JOINT_GROUP_SIZE) + 3]); } attributes["WEIGHTS_0"] = _encode_accessor_as_weights(state, attribs, true); @@ -2410,7 +2388,6 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) { ArrayMesh::BlendShapeMode shape_mode = import_mesh->get_blend_shape_mode(); for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) { Array array_morph = import_mesh->get_surface_blend_shape_arrays(surface_i, morph_i); - target_names.push_back(import_mesh->get_blend_shape_name(morph_i)); Dictionary t; Vector<Vector3> varr = array_morph[Mesh::ARRAY_VERTEX]; Array mesh_arrays = import_mesh->get_surface_arrays(surface_i); @@ -2427,22 +2404,21 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) { } Vector<Vector3> narr = array_morph[Mesh::ARRAY_NORMAL]; - if (varr.size()) { + if (narr.size()) { t["NORMAL"] = _encode_accessor_as_vec3(state, narr, true); } Vector<real_t> tarr = array_morph[Mesh::ARRAY_TANGENT]; if (tarr.size()) { const int ret_size = tarr.size() / 4; - Vector<Color> attribs; + Vector<Vector3> attribs; attribs.resize(ret_size); for (int i = 0; i < ret_size; i++) { - Color tangent; - tangent.r = tarr[(i * 4) + 0]; - tangent.g = tarr[(i * 4) + 1]; - tangent.b = tarr[(i * 4) + 2]; - tangent.a = tarr[(i * 4) + 3]; + Vector3 vec3; + vec3.x = tarr[(i * 4) + 0]; + vec3.y = tarr[(i * 4) + 1]; + vec3.z = tarr[(i * 4) + 2]; } - t["TANGENT"] = _encode_accessor_as_color(state, attribs, true); + t["TANGENT"] = _encode_accessor_as_vec3(state, attribs, true); } targets.push_back(t); } @@ -2471,12 +2447,13 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) { Dictionary e; e["targetNames"] = target_names; - for (int j = 0; j < target_names.size(); j++) { + weights.resize(target_names.size()); + for (int name_i = 0; name_i < target_names.size(); name_i++) { real_t weight = 0.0; - if (j < state->meshes.write[gltf_mesh_i]->get_blend_weights().size()) { - weight = state->meshes.write[gltf_mesh_i]->get_blend_weights()[j]; + if (name_i < state->meshes.write[gltf_mesh_i]->get_blend_weights().size()) { + weight = state->meshes.write[gltf_mesh_i]->get_blend_weights()[name_i]; } - weights.push_back(weight); + weights[name_i] = weight; } if (weights.size()) { gltf_mesh["weights"] = weights; @@ -4285,6 +4262,7 @@ Error GLTFDocument::_create_skeletons(Ref<GLTFState> state) { Skeleton3D *skeleton = memnew(Skeleton3D); gltf_skeleton->godot_skeleton = skeleton; + state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()] = skel_i; // Make a unique name, no gltf node represents this skeleton skeleton->set_name(_gen_unique_name(state, "Skeleton3D")); @@ -4370,6 +4348,16 @@ Error GLTFDocument::_map_skin_joints_indices_to_skeleton_bone_indices(Ref<GLTFSt Error GLTFDocument::_serialize_skins(Ref<GLTFState> state) { _remove_duplicate_skins(state); + Array json_skins; + for (int skin_i = 0; skin_i < state->skins.size(); skin_i++) { + Ref<GLTFSkin> gltf_skin = state->skins[skin_i]; + Dictionary json_skin; + json_skin["inverseBindMatrices"] = _encode_accessor_as_xform(state, gltf_skin->inverse_binds, false); + json_skin["joints"] = gltf_skin->get_joints(); + json_skin["name"] = gltf_skin->get_name(); + json_skins.push_back(json_skin); + } + state->json["skins"] = json_skins; return OK; } @@ -4748,30 +4736,74 @@ Error GLTFDocument::_serialize_animations(Ref<GLTFState> state) { channels.push_back(t); } if (track.weight_tracks.size()) { + double length = 0.0f; + + for (int32_t track_idx = 0; track_idx < track.weight_tracks.size(); track_idx++) { + int32_t last_time_index = track.weight_tracks[track_idx].times.size() - 1; + length = MAX(length, track.weight_tracks[track_idx].times[last_time_index]); + } + Dictionary t; t["sampler"] = samplers.size(); Dictionary s; - Vector<real_t> times; - Vector<real_t> values; + const double increment = 1.0 / BAKE_FPS; + { + double time = 0.0; + bool last = false; + while (true) { + times.push_back(time); + if (last) { + break; + } + time += increment; + if (time >= length) { + last = true; + time = length; + } + } + } - for (int32_t times_i = 0; times_i < track.weight_tracks[0].times.size(); times_i++) { - real_t time = track.weight_tracks[0].times[times_i]; - times.push_back(time); + for (int32_t track_idx = 0; track_idx < track.weight_tracks.size(); track_idx++) { + double time = 0.0; + bool last = false; + Vector<real_t> weight_track; + while (true) { + float weight = _interpolate_track<float>(track.weight_tracks[track_idx].times, + track.weight_tracks[track_idx].values, + time, + track.weight_tracks[track_idx].interpolation); + weight_track.push_back(weight); + if (last) { + break; + } + time += increment; + if (time >= length) { + last = true; + time = length; + } + } + track.weight_tracks.write[track_idx].times = times; + track.weight_tracks.write[track_idx].values = weight_track; } - values.resize(times.size() * track.weight_tracks.size()); - // TODO Sort by order in blend shapes + Vector<real_t> all_track_times = times; + Vector<real_t> all_track_values; + int32_t values_size = track.weight_tracks[0].values.size(); + int32_t weight_tracks_size = track.weight_tracks.size(); + all_track_values.resize(weight_tracks_size * values_size); for (int k = 0; k < track.weight_tracks.size(); k++) { Vector<float> wdata = track.weight_tracks[k].values; for (int l = 0; l < wdata.size(); l++) { - values.write[l * track.weight_tracks.size() + k] = wdata.write[l]; + int32_t index = l * weight_tracks_size + k; + ERR_BREAK(index >= all_track_values.size()); + all_track_values.write[index] = wdata.write[l]; } } s["interpolation"] = interpolation_to_string(track.weight_tracks[track.weight_tracks.size() - 1].interpolation); - s["input"] = _encode_accessor_as_floats(state, times, false); - s["output"] = _encode_accessor_as_floats(state, values, false); + s["input"] = _encode_accessor_as_floats(state, all_track_times, false); + s["output"] = _encode_accessor_as_floats(state, all_track_values, false); samplers.push_back(s); @@ -4905,7 +4937,7 @@ Error GLTFDocument::_parse_animations(Ref<GLTFState> state) { track->weight_tracks.resize(wc); const int expected_value_count = times.size() * output_count * wc; - ERR_FAIL_COND_V_MSG(weights.size() != expected_value_count, ERR_PARSE_ERROR, "Invalid weight data, expected " + itos(expected_value_count) + " weight values, got " + itos(weights.size()) + " instead."); + ERR_CONTINUE_MSG(weights.size() != expected_value_count, "Invalid weight data, expected " + itos(expected_value_count) + " weight values, got " + itos(weights.size()) + " instead."); const int wlen = weights.size() / wc; for (int k = 0; k < wc; k++) { //separate tracks, having them together is not such a good idea @@ -4970,7 +5002,7 @@ BoneAttachment3D *GLTFDocument::_generate_bone_attachment(Ref<GLTFState> state, return bone_attachment; } -GLTFMeshIndex GLTFDocument::_convert_mesh_instance(Ref<GLTFState> state, MeshInstance3D *p_mesh_instance) { +GLTFMeshIndex GLTFDocument::_convert_mesh_to_gltf(Ref<GLTFState> state, MeshInstance3D *p_mesh_instance) { ERR_FAIL_NULL_V(p_mesh_instance, -1); if (p_mesh_instance->get_mesh().is_null()) { return -1; @@ -5167,17 +5199,6 @@ GLTFLightIndex GLTFDocument::_convert_light(Ref<GLTFState> state, Light3D *p_lig return light_index; } -GLTFSkeletonIndex GLTFDocument::_convert_skeleton(Ref<GLTFState> state, Skeleton3D *p_skeleton) { - print_verbose("glTF: Converting skeleton: " + p_skeleton->get_name()); - Ref<GLTFSkeleton> gltf_skeleton; - gltf_skeleton.instantiate(); - gltf_skeleton->set_name(_gen_unique_name(state, p_skeleton->get_name())); - gltf_skeleton->godot_skeleton = p_skeleton; - GLTFSkeletonIndex skeleton_i = state->skeletons.size(); - state->skeletons.push_back(gltf_skeleton); - return skeleton_i; -} - void GLTFDocument::_convert_spatial(Ref<GLTFState> state, Node3D *p_spatial, Ref<GLTFNode> p_node) { Transform3D xform = p_spatial->get_transform(); p_node->scale = xform.basis.get_scale(); @@ -5193,7 +5214,7 @@ Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> state, Node *scene_parent return spatial; } -void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, Node *p_root, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) { +void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) { bool retflag = true; _check_visibility(p_current, retflag); if (retflag) { @@ -5207,37 +5228,41 @@ void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, No _convert_spatial(state, spatial, gltf_node); } if (cast_to<MeshInstance3D>(p_current)) { - Node3D *spatial = cast_to<Node3D>(p_current); - _convert_mesh_to_gltf(p_current, state, spatial, gltf_node); + MeshInstance3D *mi = cast_to<MeshInstance3D>(p_current); + _convert_mesh_instance_to_gltf(mi, state, gltf_node); } else if (cast_to<BoneAttachment3D>(p_current)) { - _convert_bone_attachment_to_gltf(p_current, state, gltf_node, retflag); - // TODO 2020-12-21 iFire Handle the case of objects under the bone attachment. + BoneAttachment3D *bone = cast_to<BoneAttachment3D>(p_current); + _convert_bone_attachment_to_gltf(bone, state, p_gltf_parent, p_gltf_root, gltf_node); return; } else if (cast_to<Skeleton3D>(p_current)) { - _convert_skeleton_to_gltf(p_current, state, p_gltf_parent, p_gltf_root, gltf_node, p_root); + Skeleton3D *skel = cast_to<Skeleton3D>(p_current); + _convert_skeleton_to_gltf(skel, state, p_gltf_parent, p_gltf_root, gltf_node); // We ignore the Godot Engine node that is the skeleton. return; } else if (cast_to<MultiMeshInstance3D>(p_current)) { - _convert_mult_mesh_instance_to_gltf(p_current, p_gltf_parent, p_gltf_root, gltf_node, state, p_root); + MultiMeshInstance3D *multi = cast_to<MultiMeshInstance3D>(p_current); + _convert_mult_mesh_instance_to_gltf(multi, p_gltf_parent, p_gltf_root, gltf_node, state); #ifdef MODULE_CSG_ENABLED } else if (cast_to<CSGShape3D>(p_current)) { - if (p_current->get_parent() && cast_to<CSGShape3D>(p_current)->is_root_shape()) { - _convert_csg_shape_to_gltf(p_current, p_gltf_parent, gltf_node, state); + CSGShape3D *shape = cast_to<CSGShape3D>(p_current); + if (shape->get_parent() && shape->is_root_shape()) { + _convert_csg_shape_to_gltf(shape, p_gltf_parent, gltf_node, state); } #endif // MODULE_CSG_ENABLED #ifdef MODULE_GRIDMAP_ENABLED } else if (cast_to<GridMap>(p_current)) { - _convert_grid_map_to_gltf(p_current, p_gltf_parent, p_gltf_root, gltf_node, state, p_root); + GridMap *gridmap = Object::cast_to<GridMap>(p_current); + _convert_grid_map_to_gltf(gridmap, p_gltf_parent, p_gltf_root, gltf_node, state); #endif // MODULE_GRIDMAP_ENABLED } else if (cast_to<Camera3D>(p_current)) { Camera3D *camera = Object::cast_to<Camera3D>(p_current); - _convert_camera_to_gltf(camera, state, camera, gltf_node); + _convert_camera_to_gltf(camera, state, gltf_node); } else if (cast_to<Light3D>(p_current)) { Light3D *light = Object::cast_to<Light3D>(p_current); - _convert_light_to_gltf(light, state, light, gltf_node); + _convert_light_to_gltf(light, state, gltf_node); } else if (cast_to<AnimationPlayer>(p_current)) { AnimationPlayer *animation_player = Object::cast_to<AnimationPlayer>(p_current); - _convert_animation_player_to_gltf(animation_player, state, p_gltf_parent, p_gltf_root, gltf_node, p_current, p_root); + _convert_animation_player_to_gltf(animation_player, state, p_gltf_parent, p_gltf_root, gltf_node, p_current); } GLTFNodeIndex current_node_i = state->nodes.size(); GLTFNodeIndex gltf_root = p_gltf_root; @@ -5249,13 +5274,13 @@ void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, No } _create_gltf_node(state, p_current, current_node_i, p_gltf_parent, gltf_root, gltf_node); for (int node_i = 0; node_i < p_current->get_child_count(); node_i++) { - _convert_scene_node(state, p_current->get_child(node_i), p_root, current_node_i, gltf_root); + _convert_scene_node(state, p_current->get_child(node_i), current_node_i, gltf_root); } } #ifdef MODULE_CSG_ENABLED -void GLTFDocument::_convert_csg_shape_to_gltf(Node *p_current, GLTFNodeIndex p_gltf_parent, Ref<GLTFNode> gltf_node, Ref<GLTFState> state) { - CSGShape3D *csg = Object::cast_to<CSGShape3D>(p_current); +void GLTFDocument::_convert_csg_shape_to_gltf(CSGShape3D *p_current, GLTFNodeIndex p_gltf_parent, Ref<GLTFNode> gltf_node, Ref<GLTFState> state) { + CSGShape3D *csg = p_current; csg->call("_update_shape"); Array meshes = csg->get_meshes(); if (meshes.size() != 2) { @@ -5286,16 +5311,15 @@ void GLTFDocument::_create_gltf_node(Ref<GLTFState> state, Node *p_scene_parent, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_gltf_node, Ref<GLTFNode> gltf_node) { state->scene_nodes.insert(current_node_i, p_scene_parent); state->nodes.push_back(gltf_node); - if (current_node_i == p_parent_node_index) { - return; - } + ERR_FAIL_COND(current_node_i == p_parent_node_index); + state->nodes.write[current_node_i]->parent = p_parent_node_index; if (p_parent_node_index == -1) { return; } state->nodes.write[p_parent_node_index]->children.push_back(current_node_i); } -void GLTFDocument::_convert_animation_player_to_gltf(AnimationPlayer *animation_player, Ref<GLTFState> state, const GLTFNodeIndex &p_gltf_current, const GLTFNodeIndex &p_gltf_root_index, Ref<GLTFNode> p_gltf_node, Node *p_scene_parent, Node *p_root) { +void GLTFDocument::_convert_animation_player_to_gltf(AnimationPlayer *animation_player, Ref<GLTFState> state, GLTFNodeIndex p_gltf_current, GLTFNodeIndex p_gltf_root_index, Ref<GLTFNode> p_gltf_node, Node *p_scene_parent) { ERR_FAIL_COND(!animation_player); state->animation_players.push_back(animation_player); print_verbose(String("glTF: Converting animation player: ") + animation_player->get_name()); @@ -5314,7 +5338,7 @@ void GLTFDocument::_check_visibility(Node *p_node, bool &retflag) { retflag = false; } -void GLTFDocument::_convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> state, Node3D *spatial, Ref<GLTFNode> gltf_node) { +void GLTFDocument::_convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> state, Ref<GLTFNode> gltf_node) { ERR_FAIL_COND(!camera); GLTFCameraIndex camera_index = _convert_camera(state, camera); if (camera_index != -1) { @@ -5322,7 +5346,7 @@ void GLTFDocument::_convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> stat } } -void GLTFDocument::_convert_light_to_gltf(Light3D *light, Ref<GLTFState> state, Node3D *spatial, Ref<GLTFNode> gltf_node) { +void GLTFDocument::_convert_light_to_gltf(Light3D *light, Ref<GLTFState> state, Ref<GLTFNode> gltf_node) { ERR_FAIL_COND(!light); GLTFLightIndex light_index = _convert_light(state, light); if (light_index != -1) { @@ -5331,43 +5355,39 @@ void GLTFDocument::_convert_light_to_gltf(Light3D *light, Ref<GLTFState> state, } #ifdef MODULE_GRIDMAP_ENABLED -void GLTFDocument::_convert_grid_map_to_gltf(Node *p_scene_parent, const GLTFNodeIndex &p_parent_node_index, const GLTFNodeIndex &p_root_node_index, Ref<GLTFNode> gltf_node, Ref<GLTFState> state, Node *p_root_node) { - GridMap *grid_map = Object::cast_to<GridMap>(p_scene_parent); - ERR_FAIL_COND(!grid_map); - Array cells = grid_map->get_used_cells(); +void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> gltf_node, Ref<GLTFState> state) { + Array cells = p_grid_map->get_used_cells(); for (int32_t k = 0; k < cells.size(); k++) { GLTFNode *new_gltf_node = memnew(GLTFNode); gltf_node->children.push_back(state->nodes.size()); state->nodes.push_back(new_gltf_node); Vector3 cell_location = cells[k]; - int32_t cell = grid_map->get_cell_item( + int32_t cell = p_grid_map->get_cell_item( Vector3(cell_location.x, cell_location.y, cell_location.z)); EditorSceneImporterMeshNode3D *import_mesh_node = memnew(EditorSceneImporterMeshNode3D); - import_mesh_node->set_mesh(grid_map->get_mesh_library()->get_item_mesh(cell)); + import_mesh_node->set_mesh(p_grid_map->get_mesh_library()->get_item_mesh(cell)); Transform3D cell_xform; cell_xform.basis.set_orthogonal_index( - grid_map->get_cell_item_orientation( + p_grid_map->get_cell_item_orientation( Vector3(cell_location.x, cell_location.y, cell_location.z))); - cell_xform.basis.scale(Vector3(grid_map->get_cell_scale(), - grid_map->get_cell_scale(), - grid_map->get_cell_scale())); - cell_xform.set_origin(grid_map->map_to_world( + cell_xform.basis.scale(Vector3(p_grid_map->get_cell_scale(), + p_grid_map->get_cell_scale(), + p_grid_map->get_cell_scale())); + cell_xform.set_origin(p_grid_map->map_to_world( Vector3(cell_location.x, cell_location.y, cell_location.z))); Ref<GLTFMesh> gltf_mesh; gltf_mesh.instantiate(); gltf_mesh = import_mesh_node; new_gltf_node->mesh = state->meshes.size(); state->meshes.push_back(gltf_mesh); - new_gltf_node->xform = cell_xform * grid_map->get_transform(); - new_gltf_node->set_name(_gen_unique_name(state, grid_map->get_mesh_library()->get_item_name(cell))); + new_gltf_node->xform = cell_xform * p_grid_map->get_transform(); + new_gltf_node->set_name(_gen_unique_name(state, p_grid_map->get_mesh_library()->get_item_name(cell))); } } #endif // MODULE_GRIDMAP_ENABLED -void GLTFDocument::_convert_mult_mesh_instance_to_gltf(Node *p_scene_parent, const GLTFNodeIndex &p_parent_node_index, const GLTFNodeIndex &p_root_node_index, Ref<GLTFNode> gltf_node, Ref<GLTFState> state, Node *p_root_node) { - MultiMeshInstance3D *multi_mesh_instance = Object::cast_to<MultiMeshInstance3D>(p_scene_parent); - ERR_FAIL_COND(!multi_mesh_instance); - Ref<MultiMesh> multi_mesh = multi_mesh_instance->get_multimesh(); +void GLTFDocument::_convert_mult_mesh_instance_to_gltf(MultiMeshInstance3D *p_multi_mesh_instance, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> gltf_node, Ref<GLTFState> state) { + Ref<MultiMesh> multi_mesh = p_multi_mesh_instance->get_multimesh(); if (multi_mesh.is_valid()) { for (int32_t instance_i = 0; instance_i < multi_mesh->get_instance_count(); instance_i++) { @@ -5383,9 +5403,9 @@ void GLTFDocument::_convert_mult_mesh_instance_to_gltf(Node *p_scene_parent, con transform.basis.set_quaternion_scale(quaternion, Vector3(scale.x, 0, scale.y)); transform = - multi_mesh_instance->get_transform() * transform; + p_multi_mesh_instance->get_transform() * transform; } else if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_3D) { - transform = multi_mesh_instance->get_transform() * + transform = p_multi_mesh_instance->get_transform() * multi_mesh->get_instance_transform(instance_i); } Ref<ArrayMesh> mm = multi_mesh->get_mesh(); @@ -5405,56 +5425,102 @@ void GLTFDocument::_convert_mult_mesh_instance_to_gltf(Node *p_scene_parent, con state->meshes.push_back(gltf_mesh); } new_gltf_node->xform = transform; - new_gltf_node->set_name(_gen_unique_name(state, multi_mesh_instance->get_name())); + new_gltf_node->set_name(_gen_unique_name(state, p_multi_mesh_instance->get_name())); gltf_node->children.push_back(state->nodes.size()); state->nodes.push_back(new_gltf_node); } } } -void GLTFDocument::_convert_skeleton_to_gltf(Node *p_scene_parent, Ref<GLTFState> state, const GLTFNodeIndex &p_parent_node_index, const GLTFNodeIndex &p_root_node_index, Ref<GLTFNode> gltf_node, Node *p_root_node) { - Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_scene_parent); - if (skeleton) { - // Remove placeholder skeleton3d node by not creating the gltf node - // Skins are per mesh - for (int node_i = 0; node_i < skeleton->get_child_count(); node_i++) { - _convert_scene_node(state, skeleton->get_child(node_i), p_root_node, p_parent_node_index, p_root_node_index); +void GLTFDocument::_convert_skeleton_to_gltf(Skeleton3D *p_skeleton3d, Ref<GLTFState> state, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> gltf_node) { + Skeleton3D *skeleton = p_skeleton3d; + Ref<GLTFSkeleton> gltf_skeleton; + gltf_skeleton.instantiate(); + // GLTFSkeleton is only used to hold internal state data. It will not be written to the document. + // + gltf_skeleton->godot_skeleton = skeleton; + GLTFSkeletonIndex skeleton_i = state->skeletons.size(); + state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()] = skeleton_i; + state->skeletons.push_back(gltf_skeleton); + + BoneId bone_count = skeleton->get_bone_count(); + for (BoneId bone_i = 0; bone_i < bone_count; bone_i++) { + Ref<GLTFNode> joint_node; + joint_node.instantiate(); + // Note that we cannot use _gen_unique_bone_name here, because glTF spec requires all node + // names to be unique regardless of whether or not they are used as joints. + joint_node->set_name(_gen_unique_name(state, skeleton->get_bone_name(bone_i))); + Transform3D xform = skeleton->get_bone_rest(bone_i) * skeleton->get_bone_pose(bone_i); + joint_node->scale = xform.basis.get_scale(); + joint_node->rotation = xform.basis.get_rotation_quaternion(); + joint_node->position = xform.origin; + joint_node->joint = true; + GLTFNodeIndex current_node_i = state->nodes.size(); + state->scene_nodes.insert(current_node_i, skeleton); + state->nodes.push_back(joint_node); + + gltf_skeleton->joints.push_back(current_node_i); + if (skeleton->get_bone_parent(bone_i) == -1) { + gltf_skeleton->roots.push_back(current_node_i); + } + gltf_skeleton->godot_bone_node.insert(bone_i, current_node_i); + } + for (BoneId bone_i = 0; bone_i < bone_count; bone_i++) { + GLTFNodeIndex current_node_i = gltf_skeleton->godot_bone_node[bone_i]; + BoneId parent_bone_id = skeleton->get_bone_parent(bone_i); + if (parent_bone_id == -1) { + if (p_parent_node_index != -1) { + state->nodes.write[current_node_i]->parent = p_parent_node_index; + state->nodes.write[p_parent_node_index]->children.push_back(current_node_i); + } + } else { + GLTFNodeIndex parent_node_i = gltf_skeleton->godot_bone_node[parent_bone_id]; + state->nodes.write[current_node_i]->parent = parent_node_i; + state->nodes.write[parent_node_i]->children.push_back(current_node_i); } } + // Remove placeholder skeleton3d node by not creating the gltf node + // Skins are per mesh + for (int node_i = 0; node_i < skeleton->get_child_count(); node_i++) { + _convert_scene_node(state, skeleton->get_child(node_i), p_parent_node_index, p_root_node_index); + } } -void GLTFDocument::_convert_bone_attachment_to_gltf(Node *p_scene_parent, Ref<GLTFState> state, Ref<GLTFNode> gltf_node, bool &retflag) { - retflag = true; - BoneAttachment3D *bone_attachment = Object::cast_to<BoneAttachment3D>(p_scene_parent); - if (bone_attachment) { - Node *node = bone_attachment->get_parent(); - while (node) { - Skeleton3D *bone_attachment_skeleton = Object::cast_to<Skeleton3D>(node); - if (bone_attachment_skeleton) { - for (GLTFSkeletonIndex skeleton_i = 0; skeleton_i < state->skeletons.size(); skeleton_i++) { - if (state->skeletons[skeleton_i]->godot_skeleton != bone_attachment_skeleton) { - continue; - } - state->skeletons.write[skeleton_i]->bone_attachments.push_back(bone_attachment); - break; - } - break; - } - node = node->get_parent(); +void GLTFDocument::_convert_bone_attachment_to_gltf(BoneAttachment3D *p_bone_attachment, Ref<GLTFState> state, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> gltf_node) { + Skeleton3D *skeleton; + // Note that relative transforms to external skeletons and pose overrides are not supported. + if (p_bone_attachment->get_use_external_skeleton()) { + skeleton = cast_to<Skeleton3D>(p_bone_attachment->get_node_or_null(p_bone_attachment->get_external_skeleton())); + } else { + skeleton = cast_to<Skeleton3D>(p_bone_attachment->get_parent()); + } + GLTFSkeletonIndex skel_gltf_i = -1; + if (skeleton != nullptr && state->skeleton3d_to_gltf_skeleton.has(skeleton->get_instance_id())) { + skel_gltf_i = state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()]; + } + int bone_idx = -1; + if (skeleton != nullptr) { + bone_idx = p_bone_attachment->get_bone_idx(); + if (bone_idx == -1) { + bone_idx = skeleton->find_bone(p_bone_attachment->get_bone_name()); } - gltf_node.unref(); - return; } - retflag = false; + GLTFNodeIndex par_node_index = p_parent_node_index; + if (skeleton != nullptr && bone_idx != -1 && skel_gltf_i != -1) { + Ref<GLTFSkeleton> gltf_skeleton = state->skeletons.write[skel_gltf_i]; + gltf_skeleton->bone_attachments.push_back(p_bone_attachment); + par_node_index = gltf_skeleton->joints[bone_idx]; + } + + for (int node_i = 0; node_i < p_bone_attachment->get_child_count(); node_i++) { + _convert_scene_node(state, p_bone_attachment->get_child(node_i), par_node_index, p_root_node_index); + } } -void GLTFDocument::_convert_mesh_to_gltf(Node *p_scene_parent, Ref<GLTFState> state, Node3D *spatial, Ref<GLTFNode> gltf_node) { - MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_scene_parent); - if (mi) { - GLTFMeshIndex gltf_mesh_index = _convert_mesh_instance(state, mi); - if (gltf_mesh_index != -1) { - gltf_node->mesh = gltf_mesh_index; - } +void GLTFDocument::_convert_mesh_instance_to_gltf(MeshInstance3D *p_scene_parent, Ref<GLTFState> state, Ref<GLTFNode> gltf_node) { + GLTFMeshIndex gltf_mesh_index = _convert_mesh_to_gltf(state, p_scene_parent); + if (gltf_mesh_index != -1) { + gltf_node->mesh = gltf_mesh_index; } } @@ -5908,10 +5974,6 @@ void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) { if (node->mesh < 0) { continue; } - Array json_skins; - if (state->json.has("skins")) { - json_skins = state->json["skins"]; - } Map<GLTFNodeIndex, Node *>::Element *mi_element = state->scene_nodes.find(mi_node_i); if (!mi_element) { continue; @@ -5923,7 +5985,6 @@ void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) { node->rotation = mi_xform.basis.get_rotation_quaternion(); node->position = mi_xform.origin; - Dictionary json_skin; Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(mi->get_node(mi->get_skeleton_path())); if (!skeleton) { continue; @@ -5932,121 +5993,75 @@ void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) { continue; } Ref<Skin> skin = mi->get_skin(); - if (skin.is_null()) { - skin = skeleton->register_skin(nullptr)->get_skin(); - } Ref<GLTFSkin> gltf_skin; gltf_skin.instantiate(); Array json_joints; - GLTFSkeletonIndex skeleton_gltf_i = -1; NodePath skeleton_path = mi->get_skeleton_path(); - bool is_unique = true; - for (int32_t skin_i = 0; skin_i < state->skins.size(); skin_i++) { - Ref<GLTFSkin> prev_gltf_skin = state->skins.write[skin_i]; - if (gltf_skin.is_null()) { - continue; - } - GLTFSkeletonIndex prev_skeleton = prev_gltf_skin->get_skeleton(); - if (prev_skeleton == -1 || prev_skeleton >= state->skeletons.size()) { - continue; - } - if (prev_gltf_skin->get_godot_skin() == skin && state->skeletons[prev_skeleton]->godot_skeleton == skeleton) { - node->skin = skin_i; - node->skeleton = prev_skeleton; - is_unique = false; - break; - } - } - if (!is_unique) { - continue; - } - GLTFSkeletonIndex skeleton_i = _convert_skeleton(state, skeleton); - skeleton_gltf_i = skeleton_i; - ERR_CONTINUE(skeleton_gltf_i == -1); - gltf_skin->skeleton = skeleton_gltf_i; - Ref<GLTFSkeleton> gltf_skeleton = state->skeletons.write[skeleton_gltf_i]; - for (int32_t bind_i = 0; bind_i < skin->get_bind_count(); bind_i++) { - String godot_bone_name = skin->get_bind_name(bind_i); - if (godot_bone_name.is_empty()) { - int32_t bone = skin->get_bind_bone(bind_i); - godot_bone_name = skeleton->get_bone_name(bone); - } - if (skeleton->find_bone(godot_bone_name) == -1) { - godot_bone_name = skeleton->get_bone_name(0); - } - BoneId bone_index = skeleton->find_bone(godot_bone_name); - ERR_CONTINUE(bone_index == -1); - Ref<GLTFNode> joint_node; - joint_node.instantiate(); - String gltf_bone_name = _gen_unique_bone_name(state, skeleton_gltf_i, godot_bone_name); - joint_node->set_name(gltf_bone_name); - - Transform3D bone_rest_xform = skeleton->get_bone_rest(bone_index); - joint_node->scale = bone_rest_xform.basis.get_scale(); - joint_node->rotation = bone_rest_xform.basis.get_rotation_quaternion(); - joint_node->position = bone_rest_xform.origin; - joint_node->joint = true; - - int32_t joint_node_i = state->nodes.size(); - state->nodes.push_back(joint_node); - gltf_skeleton->godot_bone_node.insert(bone_index, joint_node_i); - int32_t joint_index = gltf_skin->joints.size(); - gltf_skin->joint_i_to_bone_i.insert(joint_index, bone_index); - gltf_skin->joints.push_back(joint_node_i); - gltf_skin->joints_original.push_back(joint_node_i); - gltf_skin->inverse_binds.push_back(skin->get_bind_pose(bind_i)); - json_joints.push_back(joint_node_i); - for (Map<GLTFNodeIndex, Node *>::Element *skin_scene_node_i = state->scene_nodes.front(); skin_scene_node_i; skin_scene_node_i = skin_scene_node_i->next()) { - if (skin_scene_node_i->get() == skeleton) { - gltf_skin->skin_root = skin_scene_node_i->key(); - json_skin["skeleton"] = skin_scene_node_i->key(); - } - } - gltf_skin->godot_skin = skin; - gltf_skin->set_name(_gen_unique_name(state, skin->get_name())); - } - for (int32_t bind_i = 0; bind_i < skin->get_bind_count(); bind_i++) { - String bone_name = skeleton->get_bone_name(bind_i); - String godot_bone_name = skin->get_bind_name(bind_i); - int32_t bone = -1; - if (skin->get_bind_bone(bind_i) != -1) { - bone = skin->get_bind_bone(bind_i); - godot_bone_name = skeleton->get_bone_name(bone); - } - bone = skeleton->find_bone(godot_bone_name); - if (bone == -1) { - continue; - } - BoneId bone_parent = skeleton->get_bone_parent(bone); - GLTFNodeIndex joint_node_i = gltf_skeleton->godot_bone_node[bone]; - ERR_CONTINUE(joint_node_i >= state->nodes.size()); - if (bone_parent != -1) { - GLTFNodeIndex parent_joint_gltf_node = gltf_skin->joints[bone_parent]; - Ref<GLTFNode> parent_joint_node = state->nodes.write[parent_joint_gltf_node]; - parent_joint_node->children.push_back(joint_node_i); + Node *skel_node = mi->get_node_or_null(skeleton_path); + Skeleton3D *godot_skeleton = nullptr; + if (skel_node != nullptr) { + godot_skeleton = cast_to<Skeleton3D>(skel_node); + } + if (godot_skeleton != nullptr && state->skeleton3d_to_gltf_skeleton.has(godot_skeleton->get_instance_id())) { + // This is a skinned mesh. If the mesh has no ARRAY_WEIGHTS or ARRAY_BONES, it will be invisible. + const GLTFSkeletonIndex skeleton_gltf_i = state->skeleton3d_to_gltf_skeleton[godot_skeleton->get_instance_id()]; + Ref<GLTFSkeleton> gltf_skeleton = state->skeletons[skeleton_gltf_i]; + int bone_cnt = skeleton->get_bone_count(); + ERR_FAIL_COND(bone_cnt != gltf_skeleton->joints.size()); + + ObjectID gltf_skin_key = skin->get_instance_id(); + ObjectID gltf_skel_key = godot_skeleton->get_instance_id(); + GLTFSkinIndex skin_gltf_i = -1; + GLTFNodeIndex root_gltf_i = -1; + if (!gltf_skeleton->roots.is_empty()) { + root_gltf_i = gltf_skeleton->roots[0]; + } + if (state->skin_and_skeleton3d_to_gltf_skin.has(gltf_skin_key) && state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key].has(gltf_skel_key)) { + skin_gltf_i = state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key][gltf_skel_key]; } else { - Node *node_parent = skeleton->get_parent(); - ERR_CONTINUE(!node_parent); - for (Map<GLTFNodeIndex, Node *>::Element *E = state->scene_nodes.front(); E; E = E->next()) { - if (E->get() == node_parent) { - GLTFNodeIndex gltf_node_i = E->key(); - Ref<GLTFNode> gltf_node = state->nodes.write[gltf_node_i]; - gltf_node->children.push_back(joint_node_i); - break; + if (skin.is_null()) { + // Note that gltf_skin_key should remain null, so these can share a reference. + skin = skeleton->register_skin(nullptr)->get_skin(); + } + gltf_skin.instantiate(); + gltf_skin->godot_skin = skin; + gltf_skin->set_name(skin->get_name()); + gltf_skin->skeleton = skeleton_gltf_i; + gltf_skin->skin_root = root_gltf_i; + //gltf_state->godot_to_gltf_node[skel_node] + HashMap<StringName, int> bone_name_to_idx; + for (int bone_i = 0; bone_i < bone_cnt; bone_i++) { + bone_name_to_idx[skeleton->get_bone_name(bone_i)] = bone_i; + } + for (int bind_i = 0, cnt = skin->get_bind_count(); bind_i < cnt; bind_i++) { + int bone_i = skin->get_bind_bone(bind_i); + Transform3D bind_pose = skin->get_bind_pose(bind_i); + StringName bind_name = skin->get_bind_name(bind_i); + if (bind_name != StringName()) { + bone_i = bone_name_to_idx[bind_name]; } + ERR_CONTINUE(bone_i < 0 || bone_i >= bone_cnt); + if (bind_name == StringName()) { + bind_name = skeleton->get_bone_name(bone_i); + } + GLTFNodeIndex skeleton_bone_i = gltf_skeleton->joints[bone_i]; + gltf_skin->joints_original.push_back(skeleton_bone_i); + gltf_skin->joints.push_back(skeleton_bone_i); + gltf_skin->inverse_binds.push_back(bind_pose); + if (skeleton->get_bone_parent(bone_i) == -1) { + gltf_skin->roots.push_back(skeleton_bone_i); + } + gltf_skin->joint_i_to_bone_i[bind_i] = bone_i; + gltf_skin->joint_i_to_name[bind_i] = bind_name; } + skin_gltf_i = state->skins.size(); + state->skins.push_back(gltf_skin); + state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key][gltf_skel_key] = skin_gltf_i; } + node->skin = skin_gltf_i; + node->skeleton = skeleton_gltf_i; } - _expand_skin(state, gltf_skin); - node->skin = state->skins.size(); - state->skins.push_back(gltf_skin); - - json_skin["inverseBindMatrices"] = _encode_accessor_as_xform(state, gltf_skin->inverse_binds, false); - json_skin["joints"] = json_joints; - json_skin["name"] = gltf_skin->get_name(); - json_skins.push_back(json_skin); - state->json["skins"] = json_skins; } } @@ -6129,7 +6144,6 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state for (int32_t key_i = 0; key_i < key_count; key_i++) { times.write[key_i] = p_animation->track_get_key_time(p_track_i, key_i); } - const float BAKE_FPS = 30.0f; if (track_type == Animation::TYPE_TRANSFORM3D) { p_track.position_track.times = times; p_track.position_track.interpolation = gltf_interpolation; @@ -6367,69 +6381,58 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, const Vector<String> node_suffix = String(orig_track_path).split(":blend_shapes/"); const NodePath path = node_suffix[0]; const String suffix = node_suffix[1]; - const Node *node = ap->get_parent()->get_node_or_null(path); - for (Map<GLTFNodeIndex, Node *>::Element *transform_track_i = state->scene_nodes.front(); transform_track_i; transform_track_i = transform_track_i->next()) { - if (transform_track_i->get() == node) { - const MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(node); - if (!mi) { - continue; - } - Ref<ArrayMesh> array_mesh = mi->get_mesh(); - if (array_mesh.is_null()) { + Node *node = ap->get_parent()->get_node_or_null(path); + MeshInstance3D *mi = cast_to<MeshInstance3D>(node); + Ref<Mesh> mesh = mi->get_mesh(); + ERR_CONTINUE(mesh.is_null()); + int32_t mesh_index = -1; + for (Map<GLTFNodeIndex, Node *>::Element *mesh_track_i = state->scene_nodes.front(); mesh_track_i; mesh_track_i = mesh_track_i->next()) { + if (mesh_track_i->get() == node) { + mesh_index = mesh_track_i->key(); + } + } + ERR_CONTINUE(mesh_index == -1); + Map<int, GLTFAnimation::Track> &tracks = gltf_animation->get_tracks(); + GLTFAnimation::Track track = gltf_animation->get_tracks().has(mesh_index) ? gltf_animation->get_tracks()[mesh_index] : GLTFAnimation::Track(); + if (!tracks.has(mesh_index)) { + for (int32_t shape_i = 0; shape_i < mesh->get_blend_shape_count(); shape_i++) { + String shape_name = mesh->get_blend_shape_name(shape_i); + NodePath shape_path = String(path) + ":blend_shapes/" + shape_name; + int32_t shape_track_i = animation->find_track(shape_path); + if (shape_track_i == -1) { + GLTFAnimation::Channel<float> weight; + weight.interpolation = GLTFAnimation::INTERP_LINEAR; + weight.times.push_back(0.0f); + weight.times.push_back(0.0f); + weight.values.push_back(0.0f); + weight.values.push_back(0.0f); + track.weight_tracks.push_back(weight); continue; } - if (node_suffix.size() != 2) { - continue; + Animation::InterpolationType interpolation = animation->track_get_interpolation_type(track_i); + GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::INTERP_LINEAR; + if (interpolation == Animation::InterpolationType::INTERPOLATION_LINEAR) { + gltf_interpolation = GLTFAnimation::INTERP_LINEAR; + } else if (interpolation == Animation::InterpolationType::INTERPOLATION_NEAREST) { + gltf_interpolation = GLTFAnimation::INTERP_STEP; + } else if (interpolation == Animation::InterpolationType::INTERPOLATION_CUBIC) { + gltf_interpolation = GLTFAnimation::INTERP_CUBIC_SPLINE; } - GLTFNodeIndex mesh_index = -1; - for (GLTFNodeIndex node_i = 0; node_i < state->scene_nodes.size(); node_i++) { - if (state->scene_nodes[node_i] == node) { - mesh_index = node_i; - break; - } + int32_t key_count = animation->track_get_key_count(shape_track_i); + GLTFAnimation::Channel<float> weight; + weight.interpolation = gltf_interpolation; + weight.times.resize(key_count); + for (int32_t time_i = 0; time_i < key_count; time_i++) { + weight.times.write[time_i] = animation->track_get_key_time(shape_track_i, time_i); } - ERR_CONTINUE(mesh_index == -1); - Ref<Mesh> mesh = mi->get_mesh(); - ERR_CONTINUE(mesh.is_null()); - for (int32_t shape_i = 0; shape_i < mesh->get_blend_shape_count(); shape_i++) { - if (mesh->get_blend_shape_name(shape_i) != suffix) { - continue; - } - GLTFAnimation::Track track; - Map<int, GLTFAnimation::Track>::Element *blend_shape_track_i = gltf_animation->get_tracks().find(mesh_index); - if (blend_shape_track_i) { - track = blend_shape_track_i->get(); - } - Animation::InterpolationType interpolation = animation->track_get_interpolation_type(track_i); - - GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::INTERP_LINEAR; - if (interpolation == Animation::InterpolationType::INTERPOLATION_LINEAR) { - gltf_interpolation = GLTFAnimation::INTERP_LINEAR; - } else if (interpolation == Animation::InterpolationType::INTERPOLATION_NEAREST) { - gltf_interpolation = GLTFAnimation::INTERP_STEP; - } else if (interpolation == Animation::InterpolationType::INTERPOLATION_CUBIC) { - gltf_interpolation = GLTFAnimation::INTERP_CUBIC_SPLINE; - } - Animation::TrackType track_type = animation->track_get_type(track_i); - if (track_type == Animation::TYPE_VALUE) { - int32_t key_count = animation->track_get_key_count(track_i); - GLTFAnimation::Channel<float> weight; - weight.interpolation = gltf_interpolation; - weight.times.resize(key_count); - for (int32_t time_i = 0; time_i < key_count; time_i++) { - weight.times.write[time_i] = animation->track_get_key_time(track_i, time_i); - } - weight.values.resize(key_count); - for (int32_t value_i = 0; value_i < key_count; value_i++) { - weight.values.write[value_i] = animation->track_get_key_value(track_i, value_i); - } - track.weight_tracks.push_back(weight); - } - gltf_animation->get_tracks()[mesh_index] = track; + weight.values.resize(key_count); + for (int32_t value_i = 0; value_i < key_count; value_i++) { + weight.values.write[value_i] = animation->track_get_key_value(shape_track_i, value_i); } + track.weight_tracks.push_back(weight); } + tracks[mesh_index] = track; } - } else if (String(orig_track_path).find(":") != -1) { //Process skeleton const Vector<String> node_suffix = String(orig_track_path).split(":"); diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h index fb798a055a..18aeb81bc0 100644 --- a/modules/gltf/gltf_document.h +++ b/modules/gltf/gltf_document.h @@ -51,6 +51,9 @@ class GLTFSkin; class GLTFNode; class GLTFSpecGloss; class GLTFSkeleton; +class CSGShape3D; +class GridMap; +class MultiMeshInstance3D; using GLTFAccessorIndex = int; using GLTFAnimationIndex = int; @@ -72,6 +75,9 @@ class GLTFDocument : public Resource { friend class GLTFSkin; friend class GLTFSkeleton; +private: + const float BAKE_FPS = 30.0f; + public: const int32_t JOINT_GROUP_SIZE = 4; enum GLTFType { @@ -350,7 +356,6 @@ private: GLTFNodeIndex p_node_i); Error _encode_buffer_bins(Ref<GLTFState> state, const String &p_path); Error _encode_buffer_glb(Ref<GLTFState> state, const String &p_path); - Error _serialize_bone_attachment(Ref<GLTFState> state); Dictionary _serialize_texture_transform_uv1(Ref<BaseMaterial3D> p_material); Dictionary _serialize_texture_transform_uv2(Ref<BaseMaterial3D> p_material); Error _serialize_version(Ref<GLTFState> state); @@ -381,20 +386,17 @@ public: void _generate_skeleton_bone_node(Ref<GLTFState> state, Node *scene_parent, Node3D *scene_root, const GLTFNodeIndex node_index); void _import_animation(Ref<GLTFState> state, AnimationPlayer *ap, const GLTFAnimationIndex index, const int bake_fps); - GLTFMeshIndex _convert_mesh_instance(Ref<GLTFState> state, - MeshInstance3D *p_mesh_instance); void _convert_mesh_instances(Ref<GLTFState> state); GLTFCameraIndex _convert_camera(Ref<GLTFState> state, Camera3D *p_camera); - void _convert_light_to_gltf(Light3D *light, Ref<GLTFState> state, Node3D *spatial, Ref<GLTFNode> gltf_node); + void _convert_light_to_gltf(Light3D *light, Ref<GLTFState> state, Ref<GLTFNode> gltf_node); GLTFLightIndex _convert_light(Ref<GLTFState> state, Light3D *p_light); - GLTFSkeletonIndex _convert_skeleton(Ref<GLTFState> state, Skeleton3D *p_skeleton); void _convert_spatial(Ref<GLTFState> state, Node3D *p_spatial, Ref<GLTFNode> p_node); - void _convert_scene_node(Ref<GLTFState> state, Node *p_current, Node *p_root, + void _convert_scene_node(Ref<GLTFState> state, Node *p_current, const GLTFNodeIndex p_gltf_current, const GLTFNodeIndex p_gltf_root); #ifdef MODULE_CSG_ENABLED - void _convert_csg_shape_to_gltf(Node *p_current, GLTFNodeIndex p_gltf_parent, Ref<GLTFNode> gltf_node, Ref<GLTFState> state); + void _convert_csg_shape_to_gltf(CSGShape3D *p_current, GLTFNodeIndex p_gltf_parent, Ref<GLTFNode> gltf_node, Ref<GLTFState> state); #endif // MODULE_CSG_ENABLED void _create_gltf_node(Ref<GLTFState> state, @@ -405,40 +407,39 @@ public: Ref<GLTFNode> gltf_node); void _convert_animation_player_to_gltf( AnimationPlayer *animation_player, Ref<GLTFState> state, - const GLTFNodeIndex &p_gltf_current, - const GLTFNodeIndex &p_gltf_root_index, - Ref<GLTFNode> p_gltf_node, Node *p_scene_parent, - Node *p_root); + GLTFNodeIndex p_gltf_current, + GLTFNodeIndex p_gltf_root_index, + Ref<GLTFNode> p_gltf_node, Node *p_scene_parent); void _check_visibility(Node *p_node, bool &retflag); void _convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> state, - Node3D *spatial, Ref<GLTFNode> gltf_node); #ifdef MODULE_GRIDMAP_ENABLED void _convert_grid_map_to_gltf( - Node *p_scene_parent, - const GLTFNodeIndex &p_parent_node_index, - const GLTFNodeIndex &p_root_node_index, - Ref<GLTFNode> gltf_node, Ref<GLTFState> state, - Node *p_root_node); + GridMap *p_grid_map, + GLTFNodeIndex p_parent_node_index, + GLTFNodeIndex p_root_node_index, + Ref<GLTFNode> gltf_node, Ref<GLTFState> state); #endif // MODULE_GRIDMAP_ENABLED void _convert_mult_mesh_instance_to_gltf( - Node *p_scene_parent, - const GLTFNodeIndex &p_parent_node_index, - const GLTFNodeIndex &p_root_node_index, - Ref<GLTFNode> gltf_node, Ref<GLTFState> state, - Node *p_root_node); + MultiMeshInstance3D *p_scene_parent, + GLTFNodeIndex p_parent_node_index, + GLTFNodeIndex p_root_node_index, + Ref<GLTFNode> gltf_node, Ref<GLTFState> state); void _convert_skeleton_to_gltf( - Node *p_scene_parent, Ref<GLTFState> state, - const GLTFNodeIndex &p_parent_node_index, - const GLTFNodeIndex &p_root_node_index, - Ref<GLTFNode> gltf_node, Node *p_root_node); - void _convert_bone_attachment_to_gltf(Node *p_scene_parent, + Skeleton3D *p_scene_parent, Ref<GLTFState> state, + GLTFNodeIndex p_parent_node_index, + GLTFNodeIndex p_root_node_index, + Ref<GLTFNode> gltf_node); + void _convert_bone_attachment_to_gltf(BoneAttachment3D *p_bone_attachment, + Ref<GLTFState> state, + GLTFNodeIndex p_parent_node_index, + GLTFNodeIndex p_root_node_index, + Ref<GLTFNode> gltf_node); + void _convert_mesh_instance_to_gltf(MeshInstance3D *p_mesh_instance, Ref<GLTFState> state, - Ref<GLTFNode> gltf_node, - bool &retflag); - void _convert_mesh_to_gltf(Node *p_scene_parent, - Ref<GLTFState> state, Node3D *spatial, Ref<GLTFNode> gltf_node); + GLTFMeshIndex _convert_mesh_to_gltf(Ref<GLTFState> state, + MeshInstance3D *p_mesh_instance); void _convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, String p_animation_track_name); Error serialize(Ref<GLTFState> state, Node *p_root, const String &p_path); diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h index 896ea5fc56..d6614da804 100644 --- a/modules/gltf/gltf_state.h +++ b/modules/gltf/gltf_state.h @@ -44,6 +44,8 @@ #include "gltf_texture.h" #include "core/io/resource.h" +#include "core/templates/map.h" +#include "core/templates/pair.h" #include "core/templates/vector.h" #include "scene/animation/animation_player.h" #include "scene/resources/texture.h" @@ -87,6 +89,9 @@ class GLTFState : public Resource { Vector<Ref<GLTFAnimation>> animations; Map<GLTFNodeIndex, Node *> scene_nodes; + Map<ObjectID, GLTFSkeletonIndex> skeleton3d_to_gltf_skeleton; + Map<ObjectID, Map<ObjectID, GLTFSkinIndex>> skin_and_skeleton3d_to_gltf_skin; + protected: static void _bind_methods(); diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp index 1323aa80ce..0dd48f98e2 100644 --- a/modules/text_server_fb/text_server_fb.cpp +++ b/modules/text_server_fb/text_server_fb.cpp @@ -611,11 +611,13 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_glyph(FontDataFallback *p_font_d flags |= FT_LOAD_COLOR; } + int32_t glyph_index = FT_Get_Char_Index(fd->face, p_glyph); + FT_Fixed v, h; - FT_Get_Advance(fd->face, p_glyph, flags, &h); - FT_Get_Advance(fd->face, p_glyph, flags | FT_LOAD_VERTICAL_LAYOUT, &v); + FT_Get_Advance(fd->face, glyph_index, flags, &h); + FT_Get_Advance(fd->face, glyph_index, flags | FT_LOAD_VERTICAL_LAYOUT, &v); - int error = FT_Load_Glyph(fd->face, p_glyph, flags); + int error = FT_Load_Glyph(fd->face, glyph_index, flags); if (error) { fd->glyph_map[p_glyph] = FontGlyph(); ERR_FAIL_V_MSG(false, "FreeType: Failed to load glyph."); @@ -1542,7 +1544,7 @@ bool TextServerFallback::font_get_glyph_contours(RID p_font_rid, int p_size, int ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), false); #ifdef MODULE_FREETYPE_ENABLED - int error = FT_Load_Glyph(fd->cache[size]->face, p_index, FT_LOAD_NO_BITMAP | (fd->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)); + int error = FT_Load_Glyph(fd->cache[size]->face, FT_Get_Char_Index(fd->cache[size]->face, p_index), FT_LOAD_NO_BITMAP | (fd->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)); ERR_FAIL_COND_V(error, false); r_points.clear(); @@ -1636,7 +1638,9 @@ Vector2 TextServerFallback::font_get_kerning(RID p_font_rid, int p_size, const V #ifdef MODULE_FREETYPE_ENABLED if (fd->cache[size]->face) { FT_Vector delta; - FT_Get_Kerning(fd->cache[size]->face, p_glyph_pair.x, p_glyph_pair.y, FT_KERNING_DEFAULT, &delta); + int32_t glyph_a = FT_Get_Char_Index(fd->cache[size]->face, p_glyph_pair.x); + int32_t glyph_b = FT_Get_Char_Index(fd->cache[size]->face, p_glyph_pair.y); + FT_Get_Kerning(fd->cache[size]->face, glyph_a, glyph_b, FT_KERNING_DEFAULT, &delta); if (fd->msdf) { return Vector2(delta.x, delta.y) * (real_t)p_size / (real_t)fd->msdf_source_size; } else { @@ -1649,26 +1653,7 @@ Vector2 TextServerFallback::font_get_kerning(RID p_font_rid, int p_size, const V } int32_t TextServerFallback::font_get_glyph_index(RID p_font_rid, int p_size, char32_t p_char, char32_t p_variation_selector) const { - FontDataFallback *fd = font_owner.getornull(p_font_rid); - ERR_FAIL_COND_V(!fd, 0); - - MutexLock lock(fd->mutex); - Vector2i size = _get_size(fd, p_size); - ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), 0); - -#ifdef MODULE_FREETYPE_ENABLED - if (fd->cache[size]->face) { - if (p_variation_selector) { - return FT_Face_GetCharVariantIndex(fd->cache[size]->face, p_char, p_variation_selector); - } else { - return FT_Get_Char_Index(fd->cache[size]->face, p_char); - } - } else { - return 0; - } -#else return (int32_t)p_char; -#endif } bool TextServerFallback::font_has_char(RID p_font_rid, char32_t p_char) const { @@ -1731,12 +1716,6 @@ void TextServerFallback::font_render_range(RID p_font_rid, const Vector2i &p_siz Vector2i size = _get_size_outline(fd, p_size); ERR_FAIL_COND(!_ensure_cache_for_size(fd, size)); for (char32_t i = p_start; i <= p_end; i++) { -#ifdef MODULE_FREETYPE_ENABLED - if (fd->cache[size]->face) { - _ensure_glyph(fd, size, FT_Get_Char_Index(fd->cache[size]->face, i)); - continue; - } -#endif _ensure_glyph(fd, size, (int32_t)i); } } diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp index 929233e4e0..78d018ac53 100644 --- a/scene/2d/tile_map.cpp +++ b/scene/2d/tile_map.cpp @@ -452,6 +452,19 @@ int TileMap::get_layer_z_index(int p_layer) const { return layers[p_layer].z_index; } +void TileMap::set_collision_animatable(bool p_enabled) { + collision_animatable = p_enabled; + _clear_internals(); + set_notify_local_transform(p_enabled); + set_physics_process_internal(p_enabled); + _recreate_internals(); + emit_signal(SNAME("changed")); +} + +bool TileMap::is_collision_animatable() const { + return collision_animatable; +} + void TileMap::set_collision_visibility_mode(TileMap::VisibilityMode p_show_collision) { collision_visibility_mode = p_show_collision; _clear_internals(); @@ -508,7 +521,6 @@ Map<Vector2i, TileMapQuadrant>::Element *TileMap::_create_quadrant(int p_layer, // Call the create_quadrant method on plugins if (tile_set.is_valid()) { _rendering_create_quadrant(&q); - _physics_create_quadrant(&q); } return layers[p_layer].quadrant_map.insert(p_qk, q); @@ -1092,24 +1104,67 @@ void TileMap::draw_tile(RID p_canvas_item, Vector2i p_position, const Ref<TileSe void TileMap::_physics_notification(int p_what) { switch (p_what) { + case CanvasItem::NOTIFICATION_INTERNAL_PHYSICS_PROCESS: { + bool in_editor = false; +#ifdef TOOLS_ENABLED + in_editor = Engine::get_singleton()->is_editor_hint(); +#endif + if (is_inside_tree() && collision_animatable && !in_editor) { + // Update tranform on the physics tick when in animatable mode. + last_valid_transform = new_transform; + set_notify_local_transform(false); + set_global_transform(new_transform); + set_notify_local_transform(true); + } + } break; case CanvasItem::NOTIFICATION_TRANSFORM_CHANGED: { - // Update the bodies transforms. - if (is_inside_tree()) { + bool in_editor = false; +#ifdef TOOLS_ENABLED + in_editor = Engine::get_singleton()->is_editor_hint(); +#endif + if (is_inside_tree() && (!collision_animatable || in_editor)) { + // Update the new transform directly if we are not in animatable mode. + Transform2D global_transform = get_global_transform(); for (int layer = 0; layer < (int)layers.size(); layer++) { - Transform2D global_transform = get_global_transform(); + for (Map<Vector2i, TileMapQuadrant>::Element *E = layers[layer].quadrant_map.front(); E; E = E->next()) { + TileMapQuadrant &q = E->get(); + for (RID body : q.bodies) { + Transform2D xform; + xform.set_origin(map_to_world(bodies_coords[body])); + xform = global_transform * xform; + PhysicsServer2D::get_singleton()->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform); + } + } + } + } + } break; + case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: { + bool in_editor = false; +#ifdef TOOLS_ENABLED + in_editor = Engine::get_singleton()->is_editor_hint(); +#endif + if (is_inside_tree() && !in_editor && collision_animatable) { + // Only active when animatable. Send the new transform to the physics... + new_transform = get_global_transform(); + for (int layer = 0; layer < (int)layers.size(); layer++) { for (Map<Vector2i, TileMapQuadrant>::Element *E = layers[layer].quadrant_map.front(); E; E = E->next()) { TileMapQuadrant &q = E->get(); - Transform2D xform; - xform.set_origin(map_to_world(E->key() * get_effective_quadrant_size(layer))); - xform = global_transform * xform; + for (RID body : q.bodies) { + Transform2D xform; + xform.set_origin(map_to_world(bodies_coords[body])); + xform = new_transform * xform; - for (int body_index = 0; body_index < q.bodies.size(); body_index++) { - PhysicsServer2D::get_singleton()->body_set_state(q.bodies[body_index], PhysicsServer2D::BODY_STATE_TRANSFORM, xform); + PhysicsServer2D::get_singleton()->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform); } } } + + // ... but then revert changes. + set_notify_local_transform(false); + set_global_transform(last_valid_transform); + set_notify_local_transform(true); } } break; } @@ -1120,29 +1175,23 @@ void TileMap::_physics_update_dirty_quadrants(SelfList<TileMapQuadrant>::List &r ERR_FAIL_COND(!tile_set.is_valid()); Transform2D global_transform = get_global_transform(); + last_valid_transform = global_transform; + new_transform = global_transform; PhysicsServer2D *ps = PhysicsServer2D::get_singleton(); + RID space = get_world_2d()->get_space(); SelfList<TileMapQuadrant> *q_list_element = r_dirty_quadrant_list.first(); while (q_list_element) { TileMapQuadrant &q = *q_list_element->self(); - Vector2 quadrant_pos = map_to_world(q.coords * get_effective_quadrant_size(q.layer)); - - LocalVector<int> body_shape_count; - body_shape_count.resize(q.bodies.size()); - - // Clear shapes. - for (int body_index = 0; body_index < q.bodies.size(); body_index++) { - ps->body_clear_shapes(q.bodies[body_index]); - body_shape_count[body_index] = 0; - - // Position the bodies. - Transform2D xform; - xform.set_origin(quadrant_pos); - xform = global_transform * xform; - ps->body_set_state(q.bodies[body_index], PhysicsServer2D::BODY_STATE_TRANSFORM, xform); + // Clear bodies. + for (RID body : q.bodies) { + bodies_coords.erase(body); + ps->free(body); } + q.bodies.clear(); + // Recreate bodies and shapes. for (Set<Vector2i>::Element *E_cell = q.cells.front(); E_cell; E_cell = E_cell->next()) { TileMapCell c = get_cell(q.layer, E_cell->get(), true); @@ -1158,26 +1207,53 @@ void TileMap::_physics_update_dirty_quadrants(SelfList<TileMapQuadrant>::List &r if (atlas_source) { TileData *tile_data = Object::cast_to<TileData>(atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile)); - for (int body_index = 0; body_index < q.bodies.size(); body_index++) { - int &body_shape_index = body_shape_count[body_index]; + for (int tile_set_physics_layer = 0; tile_set_physics_layer < tile_set->get_physics_layers_count(); tile_set_physics_layer++) { + Ref<PhysicsMaterial> physics_material = tile_set->get_physics_layer_physics_material(tile_set_physics_layer); + uint32_t physics_layer = tile_set->get_physics_layer_collision_layer(tile_set_physics_layer); + uint32_t physics_mask = tile_set->get_physics_layer_collision_mask(tile_set_physics_layer); - // Add the shapes again. - for (int polygon_index = 0; polygon_index < tile_data->get_collision_polygons_count(body_index); polygon_index++) { - bool one_way_collision = tile_data->is_collision_polygon_one_way(body_index, polygon_index); - float one_way_collision_margin = tile_data->get_collision_polygon_one_way_margin(body_index, polygon_index); + // Create the body. + RID body = ps->body_create(); + bodies_coords[body] = E_cell->get(); + ps->body_set_mode(body, collision_animatable ? PhysicsServer2D::BODY_MODE_KINEMATIC : PhysicsServer2D::BODY_MODE_STATIC); + ps->body_set_space(body, space); - int shapes_count = tile_data->get_collision_polygon_shapes_count(body_index, polygon_index); - for (int shape_index = 0; shape_index < shapes_count; shape_index++) { - Transform2D xform = Transform2D(); - xform.set_origin(map_to_world(E_cell->get()) - quadrant_pos); + Transform2D xform; + xform.set_origin(map_to_world(E_cell->get())); + xform = global_transform * xform; + ps->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform); + + ps->body_attach_object_instance_id(body, get_instance_id()); + ps->body_set_collision_layer(body, physics_layer); + ps->body_set_collision_mask(body, physics_mask); + ps->body_set_pickable(body, false); + ps->body_set_state(body, PhysicsServer2D::BODY_STATE_LINEAR_VELOCITY, tile_data->get_constant_linear_velocity(tile_set_physics_layer)); + ps->body_set_state(body, PhysicsServer2D::BODY_STATE_ANGULAR_VELOCITY, tile_data->get_constant_angular_velocity(tile_set_physics_layer)); + + if (!physics_material.is_valid()) { + ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, 0); + ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, 1); + } else { + ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, physics_material->computed_bounce()); + ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, physics_material->computed_friction()); + } + q.bodies.push_back(body); + + // Add the shapes to the body. + int body_shape_index = 0; + for (int polygon_index = 0; polygon_index < tile_data->get_collision_polygons_count(tile_set_physics_layer); polygon_index++) { + // Iterate over the polygons. + bool one_way_collision = tile_data->is_collision_polygon_one_way(tile_set_physics_layer, polygon_index); + float one_way_collision_margin = tile_data->get_collision_polygon_one_way_margin(tile_set_physics_layer, polygon_index); + int shapes_count = tile_data->get_collision_polygon_shapes_count(tile_set_physics_layer, polygon_index); + for (int shape_index = 0; shape_index < shapes_count; shape_index++) { // Add decomposed convex shapes. - Ref<ConvexPolygonShape2D> shape = tile_data->get_collision_polygon_shape(body_index, polygon_index, shape_index); - ps->body_add_shape(q.bodies[body_index], shape->get_rid(), xform); - ps->body_set_shape_metadata(q.bodies[body_index], body_shape_index, E_cell->get()); - ps->body_set_shape_as_one_way_collision(q.bodies[body_index], body_shape_index, one_way_collision, one_way_collision_margin); + Ref<ConvexPolygonShape2D> shape = tile_data->get_collision_polygon_shape(tile_set_physics_layer, polygon_index, shape_index); + ps->body_add_shape(body, shape->get_rid()); + ps->body_set_shape_as_one_way_collision(body, body_shape_index, one_way_collision, one_way_collision_margin); - ++body_shape_index; + body_shape_index++; } } } @@ -1189,54 +1265,11 @@ void TileMap::_physics_update_dirty_quadrants(SelfList<TileMapQuadrant>::List &r } } -void TileMap::_physics_create_quadrant(TileMapQuadrant *p_quadrant) { - ERR_FAIL_COND(!tile_set.is_valid()); - - //Get the TileMap's gobla transform. - Transform2D global_transform; - if (is_inside_tree()) { - global_transform = get_global_transform(); - } - - // Clear all bodies. - p_quadrant->bodies.clear(); - - // Create the body and set its parameters. - for (int layer = 0; layer < tile_set->get_physics_layers_count(); layer++) { - RID body = PhysicsServer2D::get_singleton()->body_create(); - PhysicsServer2D::get_singleton()->body_set_mode(body, PhysicsServer2D::BODY_MODE_STATIC); - - PhysicsServer2D::get_singleton()->body_attach_object_instance_id(body, get_instance_id()); - PhysicsServer2D::get_singleton()->body_set_collision_layer(body, tile_set->get_physics_layer_collision_layer(layer)); - PhysicsServer2D::get_singleton()->body_set_collision_mask(body, tile_set->get_physics_layer_collision_mask(layer)); - - Ref<PhysicsMaterial> physics_material = tile_set->get_physics_layer_physics_material(layer); - if (!physics_material.is_valid()) { - PhysicsServer2D::get_singleton()->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, 0); - PhysicsServer2D::get_singleton()->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, 1); - } else { - PhysicsServer2D::get_singleton()->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, physics_material->computed_bounce()); - PhysicsServer2D::get_singleton()->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, physics_material->computed_friction()); - } - - if (is_inside_tree()) { - RID space = get_world_2d()->get_space(); - PhysicsServer2D::get_singleton()->body_set_space(body, space); - - Transform2D xform; - xform.set_origin(map_to_world(p_quadrant->coords * get_effective_quadrant_size(p_quadrant->layer))); - xform = global_transform * xform; - PhysicsServer2D::get_singleton()->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform); - } - - p_quadrant->bodies.push_back(body); - } -} - void TileMap::_physics_cleanup_quadrant(TileMapQuadrant *p_quadrant) { // Remove a quadrant. - for (int body_index = 0; body_index < p_quadrant->bodies.size(); body_index++) { - PhysicsServer2D::get_singleton()->free(p_quadrant->bodies[body_index]); + for (RID body : p_quadrant->bodies) { + bodies_coords.erase(body); + PhysicsServer2D::get_singleton()->free(body); } p_quadrant->bodies.clear(); } @@ -1252,7 +1285,7 @@ void TileMap::_physics_draw_quadrant_debug(TileMapQuadrant *p_quadrant) { bool show_collision = false; switch (collision_visibility_mode) { case TileMap::VISIBILITY_MODE_DEFAULT: - show_collision = !Engine::get_singleton()->is_editor_hint() && (get_tree() && get_tree()->is_debugging_navigation_hint()); + show_collision = !Engine::get_singleton()->is_editor_hint() && (get_tree() && get_tree()->is_debugging_collisions_hint()); break; case TileMap::VISIBILITY_MODE_FORCE_HIDE: show_collision = false; @@ -1266,39 +1299,28 @@ void TileMap::_physics_draw_quadrant_debug(TileMapQuadrant *p_quadrant) { } RenderingServer *rs = RenderingServer::get_singleton(); - - Vector2 quadrant_pos = map_to_world(p_quadrant->coords * get_effective_quadrant_size(p_quadrant->layer)); + PhysicsServer2D *ps = PhysicsServer2D::get_singleton(); Color debug_collision_color = get_tree()->get_debug_collisions_color(); - for (Set<Vector2i>::Element *E_cell = p_quadrant->cells.front(); E_cell; E_cell = E_cell->next()) { - TileMapCell c = get_cell(p_quadrant->layer, E_cell->get(), true); - - Transform2D xform; - xform.set_origin(map_to_world(E_cell->get()) - quadrant_pos); - rs->canvas_item_add_set_transform(p_quadrant->debug_canvas_item, xform); + Vector<Color> color; + color.push_back(debug_collision_color); - if (tile_set->has_source(c.source_id)) { - TileSetSource *source = *tile_set->get_source(c.source_id); - - if (!source->has_tile(c.get_atlas_coords()) || !source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) { - continue; - } - - TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source); - if (atlas_source) { - TileData *tile_data = Object::cast_to<TileData>(atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile)); + Vector2 quadrant_pos = map_to_world(p_quadrant->coords * get_effective_quadrant_size(p_quadrant->layer)); + Transform2D qudrant_xform; + qudrant_xform.set_origin(quadrant_pos); + Transform2D global_transform_inv = (get_global_transform() * qudrant_xform).affine_inverse(); - for (int body_index = 0; body_index < p_quadrant->bodies.size(); body_index++) { - for (int polygon_index = 0; polygon_index < tile_data->get_collision_polygons_count(body_index); polygon_index++) { - // Draw the debug polygon. - Vector<Vector2> polygon = tile_data->get_collision_polygon_points(body_index, polygon_index); - if (polygon.size() >= 3) { - Vector<Color> color; - color.push_back(debug_collision_color); - rs->canvas_item_add_polygon(p_quadrant->debug_canvas_item, polygon, color); - } - } - } + for (RID body : p_quadrant->bodies) { + Transform2D xform = Transform2D(ps->body_get_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM)) * global_transform_inv; + rs->canvas_item_add_set_transform(p_quadrant->debug_canvas_item, xform); + for (int shape_index = 0; shape_index < ps->body_get_shape_count(body); shape_index++) { + const RID &shape = ps->body_get_shape(body, shape_index); + PhysicsServer2D::ShapeType type = ps->shape_get_type(shape); + if (type == PhysicsServer2D::SHAPE_CONVEX_POLYGON) { + Vector<Vector2> polygon = ps->shape_get_data(shape); + rs->canvas_item_add_polygon(p_quadrant->debug_canvas_item, polygon, color); + } else { + WARN_PRINT("Wrong shape type for a tile, should be SHAPE_CONVEX_POLYGON."); } } rs->canvas_item_add_set_transform(p_quadrant->debug_canvas_item, Transform2D()); @@ -1858,6 +1880,11 @@ Map<Vector2i, TileMapQuadrant> *TileMap::get_quadrant_map(int p_layer) { return &layers[p_layer].quadrant_map; } +Vector2i TileMap::get_coords_for_body_rid(RID p_physics_body) { + ERR_FAIL_COND_V_MSG(!bodies_coords.has(p_physics_body), Vector2i(), vformat("No tiles for the given body RID %d.", p_physics_body)); + return bodies_coords[p_physics_body]; +} + void TileMap::fix_invalid_tiles() { ERR_FAIL_COND_MSG(tile_set.is_null(), "Cannot fix invalid tiles if Tileset is not open."); @@ -3007,6 +3034,8 @@ void TileMap::_bind_methods() { ClassDB::bind_method(D_METHOD("set_layer_z_index", "layer", "z_index"), &TileMap::set_layer_z_index); ClassDB::bind_method(D_METHOD("get_layer_z_index", "layer"), &TileMap::get_layer_z_index); + ClassDB::bind_method(D_METHOD("set_collision_animatable", "enabled"), &TileMap::set_collision_animatable); + ClassDB::bind_method(D_METHOD("is_collision_animatable"), &TileMap::is_collision_animatable); ClassDB::bind_method(D_METHOD("set_collision_visibility_mode", "collision_visibility_mode"), &TileMap::set_collision_visibility_mode); ClassDB::bind_method(D_METHOD("get_collision_visibility_mode"), &TileMap::get_collision_visibility_mode); @@ -3018,10 +3047,14 @@ void TileMap::_bind_methods() { ClassDB::bind_method(D_METHOD("get_cell_atlas_coords", "layer", "coords", "use_proxies"), &TileMap::get_cell_atlas_coords); ClassDB::bind_method(D_METHOD("get_cell_alternative_tile", "layer", "coords", "use_proxies"), &TileMap::get_cell_alternative_tile); + ClassDB::bind_method(D_METHOD("get_coords_for_body_rid", "body"), &TileMap::get_coords_for_body_rid); + ClassDB::bind_method(D_METHOD("fix_invalid_tiles"), &TileMap::fix_invalid_tiles); - ClassDB::bind_method(D_METHOD("get_surrounding_tiles", "coords"), &TileMap::get_surrounding_tiles); + ClassDB::bind_method(D_METHOD("clear_layer", "layer"), &TileMap::clear_layer); ClassDB::bind_method(D_METHOD("clear"), &TileMap::clear); + ClassDB::bind_method(D_METHOD("get_surrounding_tiles", "coords"), &TileMap::get_surrounding_tiles); + ClassDB::bind_method(D_METHOD("get_used_cells", "layer"), &TileMap::get_used_cells); ClassDB::bind_method(D_METHOD("get_used_rect"), &TileMap::get_used_rect); @@ -3037,6 +3070,7 @@ void TileMap::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tile_set", PROPERTY_HINT_RESOURCE_TYPE, "TileSet"), "set_tileset", "get_tileset"); ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_quadrant_size", PROPERTY_HINT_RANGE, "1,128,1"), "set_quadrant_size", "get_quadrant_size"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision_animatable"), "set_collision_animatable", "is_collision_animatable"); ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_visibility_mode", PROPERTY_HINT_ENUM, "Default,Force Show,Force Hide"), "set_collision_visibility_mode", "get_collision_visibility_mode"); ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_visibility_mode", PROPERTY_HINT_ENUM, "Default,Force Show,Force Hide"), "set_navigation_visibility_mode", "get_navigation_visibility_mode"); diff --git a/scene/2d/tile_map.h b/scene/2d/tile_map.h index ca38baa550..2faede2445 100644 --- a/scene/2d/tile_map.h +++ b/scene/2d/tile_map.h @@ -202,6 +202,7 @@ private: // Properties. Ref<TileSet> tile_set; int quadrant_size = 16; + bool collision_animatable = false; VisibilityMode collision_visibility_mode = VISIBILITY_MODE_DEFAULT; VisibilityMode navigation_visibility_mode = VISIBILITY_MODE_DEFAULT; @@ -229,6 +230,9 @@ private: LocalVector<TileMapLayer> layers; int selected_layer = -1; + // Mapping for RID to coords. + Map<RID, Vector2i> bodies_coords; + // Quadrants and internals management. Vector2i _coords_to_quadrant_coords(int p_layer, const Vector2i &p_coords) const; @@ -259,9 +263,10 @@ private: void _rendering_cleanup_quadrant(TileMapQuadrant *p_quadrant); void _rendering_draw_quadrant_debug(TileMapQuadrant *p_quadrant); + Transform2D last_valid_transform; + Transform2D new_transform; void _physics_notification(int p_what); void _physics_update_dirty_quadrants(SelfList<TileMapQuadrant>::List &r_dirty_quadrant_list); - void _physics_create_quadrant(TileMapQuadrant *p_quadrant); void _physics_cleanup_quadrant(TileMapQuadrant *p_quadrant); void _physics_draw_quadrant_debug(TileMapQuadrant *p_quadrant); @@ -325,6 +330,9 @@ public: void set_selected_layer(int p_layer_id); // For editor use. int get_selected_layer() const; + void set_collision_animatable(bool p_enabled); + bool is_collision_animatable() const; + void set_collision_visibility_mode(VisibilityMode p_show_collision); VisibilityMode get_collision_visibility_mode(); @@ -364,6 +372,9 @@ public: virtual void set_texture_filter(CanvasItem::TextureFilter p_texture_filter) override; virtual void set_texture_repeat(CanvasItem::TextureRepeat p_texture_repeat) override; + // For finding tiles from collision. + Vector2i get_coords_for_body_rid(RID p_physics_body); + // Fixing a nclearing methods. void fix_invalid_tiles(); diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp index 5a8c5b3782..15e622c9d6 100644 --- a/scene/resources/tile_set.cpp +++ b/scene/resources/tile_set.cpp @@ -3124,7 +3124,7 @@ Vector2i TileSetAtlasSource::get_atlas_grid_size() const { } bool TileSetAtlasSource::_set(const StringName &p_name, const Variant &p_value) { - Vector<String> components = String(p_name).split("/", true, 3); + Vector<String> components = String(p_name).split("/", true, 2); // Compute the vector2i if we have coordinates. Vector<String> coords_split = components[0].split(":"); @@ -4316,9 +4316,26 @@ Ref<OccluderPolygon2D> TileData::get_occluder(int p_layer_id) const { } // Physics -int TileData::get_collision_polygons_count(int p_layer_id) const { - ERR_FAIL_INDEX_V(p_layer_id, physics.size(), 0); - return physics[p_layer_id].polygons.size(); +void TileData::set_constant_linear_velocity(int p_layer_id, const Vector2 &p_velocity) { + ERR_FAIL_INDEX(p_layer_id, physics.size()); + physics.write[p_layer_id].linear_velocity = p_velocity; + emit_signal(SNAME("changed")); +} + +Vector2 TileData::get_constant_linear_velocity(int p_layer_id) const { + ERR_FAIL_INDEX_V(p_layer_id, physics.size(), Vector2()); + return physics[p_layer_id].linear_velocity; +} + +void TileData::set_constant_angular_velocity(int p_layer_id, real_t p_velocity) { + ERR_FAIL_INDEX(p_layer_id, physics.size()); + physics.write[p_layer_id].angular_velocity = p_velocity; + emit_signal(SNAME("changed")); +} + +real_t TileData::get_constant_angular_velocity(int p_layer_id) const { + ERR_FAIL_INDEX_V(p_layer_id, physics.size(), 0.0); + return physics[p_layer_id].angular_velocity; } void TileData::set_collision_polygons_count(int p_layer_id, int p_polygons_count) { @@ -4329,6 +4346,11 @@ void TileData::set_collision_polygons_count(int p_layer_id, int p_polygons_count emit_signal(SNAME("changed")); } +int TileData::get_collision_polygons_count(int p_layer_id) const { + ERR_FAIL_INDEX_V(p_layer_id, physics.size(), 0); + return physics[p_layer_id].polygons.size(); +} + void TileData::add_collision_polygon(int p_layer_id) { ERR_FAIL_INDEX(p_layer_id, physics.size()); physics.write[p_layer_id].polygons.push_back(PhysicsLayerTileData::PolygonShapeTileData()); @@ -4530,11 +4552,7 @@ bool TileData::_set(const StringName &p_name, const Variant &p_value) { // Physics layers. int layer_index = components[0].trim_prefix("physics_layer_").to_int(); ERR_FAIL_COND_V(layer_index < 0, false); - if (components.size() == 2 && components[1] == "polygons_count") { - if (p_value.get_type() != Variant::INT) { - return false; - } - + if (components.size() == 2) { if (layer_index >= physics.size()) { if (tile_set) { return false; @@ -4542,8 +4560,19 @@ bool TileData::_set(const StringName &p_name, const Variant &p_value) { physics.resize(layer_index + 1); } } - set_collision_polygons_count(layer_index, p_value); - return true; + if (components[1] == "linear_velocity") { + set_constant_linear_velocity(layer_index, p_value); + return true; + } else if (components[1] == "angular_velocity") { + set_constant_angular_velocity(layer_index, p_value); + return true; + } else if (components[1] == "polygons_count") { + if (p_value.get_type() != Variant::INT) { + return false; + } + set_collision_polygons_count(layer_index, p_value); + return true; + } } else if (components.size() == 3 && components[1].begins_with("polygon_") && components[1].trim_prefix("polygon_").is_valid_int()) { int polygon_index = components[1].trim_prefix("polygon_").to_int(); ERR_FAIL_COND_V(polygon_index < 0, false); @@ -4645,9 +4674,18 @@ bool TileData::_get(const StringName &p_name, Variant &r_ret) const { if (layer_index >= physics.size()) { return false; } - if (components.size() == 2 && components[1] == "polygons_count") { - r_ret = get_collision_polygons_count(layer_index); - return true; + + if (components.size() == 2) { + if (components[1] == "linear_velocity") { + r_ret = get_constant_linear_velocity(layer_index); + return true; + } else if (components[1] == "angular_velocity") { + r_ret = get_constant_angular_velocity(layer_index); + return true; + } else if (components[1] == "polygons_count") { + r_ret = get_collision_polygons_count(layer_index); + return true; + } } else if (components.size() == 3 && components[1].begins_with("polygon_") && components[1].trim_prefix("polygon_").is_valid_int()) { int polygon_index = components[1].trim_prefix("polygon_").to_int(); ERR_FAIL_COND_V(polygon_index < 0, false); @@ -4718,6 +4756,8 @@ void TileData::_get_property_list(List<PropertyInfo> *p_list) const { // Physics layers. p_list->push_back(PropertyInfo(Variant::NIL, "Physics", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_GROUP)); for (int i = 0; i < physics.size(); i++) { + p_list->push_back(PropertyInfo(Variant::VECTOR2, vformat("physics_layer_%d/linear_velocity", i), PROPERTY_HINT_NONE)); + p_list->push_back(PropertyInfo(Variant::FLOAT, vformat("physics_layer_%d/angular_velocity", i), PROPERTY_HINT_NONE)); p_list->push_back(PropertyInfo(Variant::INT, vformat("physics_layer_%d/polygons_count", i), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR)); for (int j = 0; j < physics[i].polygons.size(); j++) { @@ -4807,8 +4847,12 @@ void TileData::_bind_methods() { ClassDB::bind_method(D_METHOD("get_occluder", "layer_id"), &TileData::get_occluder); // Physics. - ClassDB::bind_method(D_METHOD("get_collision_polygons_count", "layer_id"), &TileData::get_collision_polygons_count); + ClassDB::bind_method(D_METHOD("set_constant_linear_velocity", "layer_id", "velocity"), &TileData::set_constant_linear_velocity); + ClassDB::bind_method(D_METHOD("get_constant_linear_velocity", "layer_id"), &TileData::get_constant_linear_velocity); + ClassDB::bind_method(D_METHOD("set_constant_angular_velocity", "layer_id", "velocity"), &TileData::set_constant_angular_velocity); + ClassDB::bind_method(D_METHOD("get_constant_angular_velocity", "layer_id"), &TileData::get_constant_angular_velocity); ClassDB::bind_method(D_METHOD("set_collision_polygons_count", "layer_id", "polygons_count"), &TileData::set_collision_polygons_count); + ClassDB::bind_method(D_METHOD("get_collision_polygons_count", "layer_id"), &TileData::get_collision_polygons_count); ClassDB::bind_method(D_METHOD("add_collision_polygon", "layer_id"), &TileData::add_collision_polygon); ClassDB::bind_method(D_METHOD("remove_collision_polygon", "layer_id", "polygon_index"), &TileData::remove_collision_polygon); ClassDB::bind_method(D_METHOD("set_collision_polygon_points", "layer_id", "polygon_index", "polygon"), &TileData::set_collision_polygon_points); diff --git a/scene/resources/tile_set.h b/scene/resources/tile_set.h index 46cb1fb36d..42b82957fb 100644 --- a/scene/resources/tile_set.h +++ b/scene/resources/tile_set.h @@ -645,6 +645,8 @@ private: float one_way_margin = 1.0; }; + Vector2 linear_velocity; + float angular_velocity; Vector<PolygonShapeTileData> polygons; }; Vector<PhysicsLayerTileData> physics; @@ -718,8 +720,12 @@ public: Ref<OccluderPolygon2D> get_occluder(int p_layer_id) const; // Physics - int get_collision_polygons_count(int p_layer_id) const; + void set_constant_linear_velocity(int p_layer_id, const Vector2 &p_velocity); + Vector2 get_constant_linear_velocity(int p_layer_id) const; + void set_constant_angular_velocity(int p_layer_id, real_t p_velocity); + real_t get_constant_angular_velocity(int p_layer_id) const; void set_collision_polygons_count(int p_layer_id, int p_shapes_count); + int get_collision_polygons_count(int p_layer_id) const; void add_collision_polygon(int p_layer_id); void remove_collision_polygon(int p_layer_id, int p_polygon_index); void set_collision_polygon_points(int p_layer_id, int p_polygon_index, Vector<Vector2> p_polygon); |