New and improved IK system for Skeleton2D

This PR and commit adds a new IK system for 2D with the Skeleton2D node
that adds several new IK solvers, a way to control bones in a Skeleton2D
node similar to that in Skeleton3D. It also adds additional changes
and functionality.

This work was sponsored by GSoC 2020 and TwistedTwigleg.

Full list of changes:
* Adds a SkeletonModifier2D resource
  * This resource is the base where all IK code is written and executed
  * Has a function for clamping angles, since it is so commonly used
  * Modifiers are unique when duplicated so it works with instancing
* Adds a SkeletonModifierStack2D resource
  * This resource manages a series of SkeletonModification2Ds
  * This is what the Skeleton2D directly interfaces with to make IK possible
* Adds SkeletonModifier2D resources for LookAt, CCDIK, FABRIK, Jiggle, and TwoBoneIK
  * Each modification is in its own file
  * There is also a SkeletonModifier2D resource that acts as a stack for using multiple stacks together
* Adds a PhysicalBone2D node
  * Works similar to the PhysicalBone3D node, but uses a RigidBody2D node
* Changes to Skeleton2D listed below:
  * Skeleton2D now holds a single SkeletonModificationStack2D for IK
  * Skeleton2D now has a local_pose_override, which overrides the Bone2D position similar to how the overrides work in Skeleton3D
* Changes to Bone2D listed below:
  * The default_length property has been changed to length. Length is the length of the bone to its child bone node
  * New bone_angle property, which is the angle the bone has to its first child bone node
  * Bone2D caches its transform when not modified by IK for IK interpolation purposes
  * Bone2D draws its own editor gizmo, though this is stated to change in the future
* Changes to CanvasItemEditor listed below:
  * Bone2D gizmo drawing code removed
  * The 2D IK code is removed. Now Bone2D is the only bone system for 2D
* Transform2D now has a looking_at function for rotating to face a position
* Two new node notifications: NOTIFICATION_EDITOR_PRE_SAVE and NOTIFICATION_EDITOR_POST_SAVE
  * These notifications only are called in the editor right before and after saving a scene
  * Needed for not saving the IK position when executing IK in the editor
* Documentation for all the changes listed above.
This commit is contained in:
TwistedTwigleg 2020-08-03 14:02:24 -04:00
parent 7085c0d801
commit 8aa3c2f091
47 changed files with 6591 additions and 613 deletions

View file

@ -158,6 +158,13 @@ bool Transform2D::is_equal_approx(const Transform2D &p_transform) const {
return elements[0].is_equal_approx(p_transform.elements[0]) && elements[1].is_equal_approx(p_transform.elements[1]) && elements[2].is_equal_approx(p_transform.elements[2]);
}
Transform2D Transform2D::looking_at(const Vector2 &p_target) const {
Transform2D return_trans = Transform2D(get_rotation(), get_origin());
Vector2 target_position = affine_inverse().xform(p_target);
return_trans.set_rotation(return_trans.get_rotation() + (target_position * get_scale()).angle());
return return_trans;
}
bool Transform2D::operator==(const Transform2D &p_transform) const {
for (int i = 0; i < 3; i++) {
if (elements[i] != p_transform.elements[i]) {

View file

@ -100,6 +100,8 @@ struct Transform2D {
Transform2D orthonormalized() const;
bool is_equal_approx(const Transform2D &p_transform) const;
Transform2D looking_at(const Vector2 &p_target) const;
bool operator==(const Transform2D &p_transform) const;
bool operator!=(const Transform2D &p_transform) const;

View file

@ -1651,6 +1651,8 @@ static void _register_variant_builtin_methods() {
bind_method(Transform2D, basis_xform_inv, sarray("v"), varray());
bind_method(Transform2D, interpolate_with, sarray("xform", "weight"), varray());
bind_method(Transform2D, is_equal_approx, sarray("xform"), varray());
bind_method(Transform2D, set_rotation, sarray("rotation"), varray());
bind_method(Transform2D, looking_at, sarray("target"), varray(Transform2D()));
/* Basis */

View file

@ -19,6 +19,28 @@
Stores the node's current transforms in [member rest].
</description>
</method>
<method name="get_autocalculate_length_and_angle" qualifiers="const">
<return type="bool">
</return>
<description>
Returns whether this [code]Bone2D[/code] node is going to autocalculate its length and bone angle using its first [code]Bone2D[/code] child node, if one exists. If there are no [code]Bone2D[/code] children, then it cannot autocalculate these values and will print a warning.
</description>
</method>
<method name="get_bone_angle" qualifiers="const">
<return type="float">
</return>
<description>
Returns the angle of the bone in the [code]Bone2D[/code] node.
[b]Note:[/b] This is different from the [code]Bone2D[/code]'s rotation. The bone angle is the rotation of the bone shown by the [code]Bone2D[/code] gizmo, and because [code]Bone2D[/code] bones are based on positions, this can vary from the actual rotation of the [code]Bone2D[/code] node.
</description>
</method>
<method name="get_default_length" qualifiers="const">
<return type="float">
</return>
<description>
Deprecated. Please use [code]get_length[/code] instead.
</description>
</method>
<method name="get_index_in_skeleton" qualifiers="const">
<return type="int">
</return>
@ -26,6 +48,13 @@
Returns the node's index as part of the entire skeleton. See [Skeleton2D].
</description>
</method>
<method name="get_length" qualifiers="const">
<return type="float">
</return>
<description>
Returns the length of the bone in the [code]Bone2D[/code] node.
</description>
</method>
<method name="get_skeleton_rest" qualifiers="const">
<return type="Transform2D">
</return>
@ -33,11 +62,45 @@
Returns the node's [member rest] [code]Transform2D[/code] if it doesn't have a parent, or its rest pose relative to its parent.
</description>
</method>
<method name="set_autocalculate_length_and_angle">
<return type="void">
</return>
<argument index="0" name="auto_calculate" type="bool">
</argument>
<description>
When set to [code]true[/code], the [code]Bone2D[/code] node will attempt to automatically calculate the bone angle and length using the first child [code]Bone2D[/code] node, if one exists. If none exist, the [code]Bone2D[/code] cannot automatically calculate these values and will print a warning.
</description>
</method>
<method name="set_bone_angle">
<return type="void">
</return>
<argument index="0" name="angle" type="float">
</argument>
<description>
Sets the bone angle for the [code]Bone2D[/code] node. This is typically set to the rotation from the [code]Bone2D[/code] node to a child [code]Bone2D[/code] node.
[b]Note:[/b] This is different from the [code]Bone2D[/code]'s rotation. The bone angle is the rotation of the bone shown by the [code]Bone2D[/code] gizmo, and because [code]Bone2D[/code] bones are based on positions, this can vary from the actual rotation of the [code]Bone2D[/code] node.
</description>
</method>
<method name="set_default_length">
<return type="void">
</return>
<argument index="0" name="default_length" type="float">
</argument>
<description>
Deprecated. Please use [code]set_length[/code] instead.
</description>
</method>
<method name="set_length">
<return type="void">
</return>
<argument index="0" name="length" type="float">
</argument>
<description>
Sets the length of the bone in the [code]Bone2D[/code] node.
</description>
</method>
</methods>
<members>
<member name="default_length" type="float" setter="set_default_length" getter="get_default_length" default="16.0">
Length of the bone's representation drawn in the editor's viewport in pixels.
</member>
<member name="rest" type="Transform2D" setter="set_rest" getter="get_rest" default="Transform2D( 0, 0, 0, 0, 0, 0 )">
Rest transform of the bone. You can reset the node's transforms to this value using [method apply_rest].
</member>

View file

@ -969,6 +969,12 @@
<constant name="NOTIFICATION_POST_ENTER_TREE" value="27">
Notification received when the node is ready, just before [constant NOTIFICATION_READY] is received. Unlike the latter, it's sent every time the node enters tree, instead of only once.
</constant>
<constant name="NOTIFICATION_EDITOR_PRE_SAVE" value="9001">
Notification received right before the scene with the node is saved in the editor. This notification is only sent in the Godot editor and will not occur in exported projects.
</constant>
<constant name="NOTIFICATION_EDITOR_POST_SAVE" value="9002">
Notification received right after the scene with the node is saved in the editor. This notification is only sent in the Godot editor and will not occur in exported projects.
</constant>
<constant name="NOTIFICATION_WM_MOUSE_ENTER" value="1002">
Notification received from the OS when the mouse enters the game window.
Implemented on desktop and web platforms.

View file

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="PhysicalBone2D" inherits="RigidBody2D" version="4.0">
<brief_description>
A 2D node that can be used for physically aware bones in 2D.
</brief_description>
<description>
The [code]PhysicalBone2D[/code] node is a [RigidBody2D]-based node that can be used to make [Bone2D] nodes in a [Skeleton2D] react to physics. This node is very similar to the [PhysicalBone3D] node, just for 2D instead of 3D.
[b]Note:[/b] To have the Bone2D nodes visually follow the [code]PhysicalBone2D[/code] node, use a [SkeletonModification2DPhysicalBones] modification on the [Skeleton2D] node with the [Bone2D] nodes.
[b]Note:[/b] The PhysicalBone2D node does not automatically create a [Joint2D] node to keep [code]PhysicalBone2D[/code] nodes together. You will need to create these manually. For most cases, you want to use a [PinJoint2D] node. The [code]PhysicalBone2D[/code] node can automatically configure the [Joint2D] node once it's been created as a child node.
</description>
<tutorials>
</tutorials>
<methods>
<method name="get_joint" qualifiers="const">
<return type="Joint2D">
</return>
<description>
Returns the first [Joint2D] child node, if one exists. This is mainly a helper function to make it easier to get the [Joint2D] that the [code]PhysicalBone2D[/code] is autoconfiguring.
</description>
</method>
<method name="is_simulating_physics" qualifiers="const">
<return type="bool">
</return>
<description>
Returns a boolean that indicates whether the [code]PhysicalBone2D[/code] node is running and simulating using the Godot 2D physics engine. When [code]true[/code], the PhysicalBone2D node is using physics.
</description>
</method>
</methods>
<members>
<member name="auto_configure_joint" type="bool" setter="set_auto_configure_joint" getter="get_auto_configure_joint" default="true">
If [code]true[/code], the [code]PhysicalBone2D[/code] node will automatically configure the first [Joint2D] child node. The automatic configuration is limited to setting up the node properties and positioning the [Joint2D].
</member>
<member name="bone2d_index" type="int" setter="set_bone2d_index" getter="get_bone2d_index" default="-1">
The index of the [Bone2D] node that this [code]PhysicalBone2D[/code] node is supposed to be simulating.
</member>
<member name="bone2d_nodepath" type="NodePath" setter="set_bone2d_nodepath" getter="get_bone2d_nodepath" default="NodePath(&quot;&quot;)">
The [NodePath] to the [Bone2D] node that this [code]PhysicalBone2D[/code] node is supposed to be simulating.
</member>
<member name="follow_bone_when_simulating" type="bool" setter="set_follow_bone_when_simulating" getter="get_follow_bone_when_simulating" default="false">
If [code]true[/code], the [code]PhysicalBone2D[/code] will keep the transform of the bone it is bound to when simulating physics.
</member>
<member name="simulate_physics" type="bool" setter="set_simulate_physics" getter="get_simulate_physics" default="false">
If [code]true[/code], the [code]PhysicalBone2D[/code] will start simulating using physics. If [code]false[/code], the [code]PhysicalBone2D[/code] will follow the transform of the [Bone2D] node.
[b]Note:[/b] To have the Bone2D nodes visually follow the [code]PhysicalBone2D[/code] node, use a [SkeletonModification2DPhysicalBones] modification on the [Skeleton2D] node with the [Bone2D] nodes.
</member>
</members>
<constants>
</constants>
</class>

View file

@ -10,6 +10,17 @@
<link title="2D skeletons">https://docs.godotengine.org/en/latest/tutorials/animation/2d_skeletons.html</link>
</tutorials>
<methods>
<method name="execute_modifications">
<return type="void">
</return>
<argument index="0" name="execution_mode" type="float">
</argument>
<argument index="1" name="execution_mode" type="int">
</argument>
<description>
Executes all the modifications on the [SkeletonModificationStack2D], if the Skeleton3D has one assigned.
</description>
</method>
<method name="get_bone">
<return type="Bone2D">
</return>
@ -26,6 +37,22 @@
Returns the number of [Bone2D] nodes in the node hierarchy parented by Skeleton2D.
</description>
</method>
<method name="get_bone_local_pose_override">
<return type="Transform2D">
</return>
<argument index="0" name="bone_idx" type="int">
</argument>
<description>
Returns the local pose override transform for [code]bone_idx[/code].
</description>
</method>
<method name="get_modification_stack" qualifiers="const">
<return type="SkeletonModificationStack2D">
</return>
<description>
Returns the [SkeletonModificationStack2D] attached to this skeleton, if one exists.
</description>
</method>
<method name="get_skeleton" qualifiers="const">
<return type="RID">
</return>
@ -33,10 +60,37 @@
Returns the [RID] of a Skeleton2D instance.
</description>
</method>
<method name="set_bone_local_pose_override">
<return type="void">
</return>
<argument index="0" name="bone_idx" type="int">
</argument>
<argument index="1" name="override_pose" type="Transform2D">
</argument>
<argument index="2" name="strength" type="float">
</argument>
<argument index="3" name="persistent" type="bool">
</argument>
<description>
Sets the local pose transform, [code]pose[/code], for the bone at [code]bone_idx[/code].
[code]amount[/code] is the interpolation strengh that will be used when applying the pose, and [code]persistent[/code] determines if the applied pose will remain.
[b]Note:[/b] The pose transform needs to be a local transform relative to the [Bone2D] node at [code]bone_idx[/code]!
</description>
</method>
<method name="set_modification_stack">
<return type="void">
</return>
<argument index="0" name="modification_stack" type="SkeletonModificationStack2D">
</argument>
<description>
Sets the [SkeletonModificationStack2D] attached to this skeleton.
</description>
</method>
</methods>
<signals>
<signal name="bone_setup_changed">
<description>
Emitted when the [Bone2D] setup attached to this skeletons changes. This is primarily used internally within the skeleton.
</description>
</signal>
</signals>

View file

@ -0,0 +1,104 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SkeletonModification2D" inherits="Resource" version="4.0">
<brief_description>
A resource that operates on [Bone2D] nodes in a [Skeleton2D].
</brief_description>
<description>
This resource provides an interface that can be expanded so code that operates on [Bone2D] nodes in a [Skeleton2D] can be mixed and matched together to create complex interactions.
This is used to provide Godot with a flexible and powerful Inverse Kinematics solution that can be adapted for many different uses.
</description>
<tutorials>
</tutorials>
<methods>
<method name="_draw_editor_gizmo" qualifiers="virtual">
<return type="void">
</return>
<description>
Used for drawing [b]editor-only[/b] modification gizmos. This function will only be called in the Godot editor and can be overriden to draw custom gizmos.
[b]Note:[/b] You will need to use the Skeleton2D from [method SkeletonModificationStack2D.get_skeleton] and it's draw functions, as the [SkeletonModification2D] resource cannot draw on its own.
</description>
</method>
<method name="_execute" qualifiers="virtual">
<return type="void">
</return>
<argument index="0" name="delta" type="float">
</argument>
<description>
Executes the given modification. This is where the modification performs whatever function it is designed to do.
</description>
</method>
<method name="_setup_modification" qualifiers="virtual">
<return type="void">
</return>
<argument index="0" name="modification_stack" type="SkeletonModificationStack2D">
</argument>
<description>
Called when the modification is setup. This is where the modification performs initialization.
</description>
</method>
<method name="clamp_angle">
<return type="float">
</return>
<argument index="0" name="angle" type="float">
</argument>
<argument index="1" name="min" type="float">
</argument>
<argument index="2" name="max" type="float">
</argument>
<argument index="3" name="invert" type="bool">
</argument>
<description>
Takes a angle and clamps it so it is within the passed-in [code]min[/code] and [code]max[/code] range. [code]invert[/code] will inversely clamp the angle, clamping it to the range outside of the given bounds.
</description>
</method>
<method name="get_editor_draw_gizmo" qualifiers="const">
<return type="bool">
</return>
<description>
Returns whether this modification will call [method _draw_editor_gizmo] in the Godot editor to draw modification-specific gizmos.
</description>
</method>
<method name="get_is_setup" qualifiers="const">
<return type="bool">
</return>
<description>
Returns whether this modification has been successfully setup or not.
</description>
</method>
<method name="get_modification_stack">
<return type="SkeletonModificationStack2D">
</return>
<description>
Returns the [SkeletonModificationStack2D] that this modification is bound to. Through the modification stack, you can access the Skeleton3D the modification is operating on.
</description>
</method>
<method name="set_editor_draw_gizmo">
<return type="void">
</return>
<argument index="0" name="draw_gizmo" type="bool">
</argument>
<description>
Sets whether this modification will call [method _draw_editor_gizmo] in the Godot editor to draw modification-specific gizmos.
</description>
</method>
<method name="set_is_setup">
<return type="void">
</return>
<argument index="0" name="is_setup" type="bool">
</argument>
<description>
Manually allows you to set the setup state of the modification. This function should only rarely be used, as the [SkeletonModificationStack2D] the modification is bound to should handle setting the modification up.
</description>
</method>
</methods>
<members>
<member name="enabled" type="bool" setter="set_enabled" getter="get_enabled" default="true">
If [code]true[/code], the modification's [method _execute] function will be called by the [SkeletonModificationStack2D].
</member>
<member name="execution_mode" type="int" setter="set_execution_mode" getter="get_execution_mode" default="0">
The execution mode for the modification. This tells the modification stack when to execute the modification. Some modifications have settings that are only availible in certain execution modes.
</member>
</members>
<constants>
</constants>
</class>

View file

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SkeletonModification2DCCDIK" inherits="SkeletonModification2D" version="4.0">
<brief_description>
A modification that uses CCDIK to manipulate a series of bones to reach a target in 2D.
</brief_description>
<description>
This [SkeletonModification2D] uses an algorithm called [b]C[/b]yclic [b]C[/b]oordinate [b]D[/b]escent [b]I[/b]nverse [b]K[/b]inematics, or CCDIK, to maniuplate a chain of bones in a [Skeleton2D] so it reaches a defined target.
CCDIK works by rotating a set of bones, typically called a "bone chain", on a single axis. Each bone is rotated to face the target from the tip (by default), which over a chain of bones allow it to rotate properly to reach the target. Because the bones only rotate on a single axis, CCDIK [i]can[/i] look more robotic than other IK solvers.
[b]Note:[/b] The CCDIK modifier has [code]ccdik_joints[/code], which are the data objects that hold the data for each joint in the CCDIK chain. This is different from a bone! CCDIK joints hold the data needed for each bone in the bone chain used by CCDIK.
CCDIK also fully supports angle constraints, allowing for more control over how a solution is met.
</description>
<tutorials>
</tutorials>
<methods>
<method name="get_ccdik_joint_bone2d_node" qualifiers="const">
<return type="NodePath">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the [Bone2D] node assigned to the CCDIK joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_ccdik_joint_bone_index" qualifiers="const">
<return type="int">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the index of the [Bone2D] node assigned to the CCDIK joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_ccdik_joint_constraint_angle_invert" qualifiers="const">
<return type="bool">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns whether the CCDIK joint at [code]joint_idx[/code] uses an inverted joint constraint. See [method set_ccdik_joint_constraint_angle_invert] for details.
</description>
</method>
<method name="get_ccdik_joint_constraint_angle_max" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the maximum angle constraint for the joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_ccdik_joint_constraint_angle_min" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the minimum angle constraint for the joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_ccdik_joint_enable_constraint" qualifiers="const">
<return type="bool">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns whether angle constraints on the CCDIK joint at [code]joint_idx[/code] are enabled.
</description>
</method>
<method name="get_ccdik_joint_rotate_from_joint" qualifiers="const">
<return type="bool">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns whether the joint at [code]joint_idx[/code] is set to rotate from the joint, [code]true[/code], or to rotate from the tip, [code]false[/code]. The default is to rotate from the tip.
</description>
</method>
<method name="set_ccdik_joint_bone2d_node">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="bone2d_nodepath" type="NodePath">
</argument>
<description>
Sets the [Bone2D] node assigned to the CCDIK joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_ccdik_joint_bone_index">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="bone_idx" type="int">
</argument>
<description>
Sets the bone index, [code]bone_index[/code], of the CCDIK joint at [code]joint_idx[/code]. When possible, this will also update the [code]bone2d_node[/code] of the CCDIK joint based on data provided by the linked skeleton.
</description>
</method>
<method name="set_ccdik_joint_constraint_angle_invert">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="invert" type="bool">
</argument>
<description>
Sets whether the CCDIK joint at [code]joint_idx[/code] uses an inverted joint constraint.
An inverted joint constraint only constraints the CCDIK joint to the angles [i]outside of[/i] the inputted minimum and maximum angles. For this reason, it is referred to as an inverted joint constraint, as it constraints the joint to the outside of the inputted values.
</description>
</method>
<method name="set_ccdik_joint_constraint_angle_max">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="angle_max" type="float">
</argument>
<description>
Sets the maximum angle constraint for the joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_ccdik_joint_constraint_angle_min">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="angle_min" type="float">
</argument>
<description>
Sets the minimum angle constraint for the joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_ccdik_joint_enable_constraint">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="enable_constraint" type="bool">
</argument>
<description>
Determines whether angle constraints on the CCDIK joint at [code]joint_idx[/code] are enabled. When [code]true[/code], constraints will be enabled and taken into account when solving.
</description>
</method>
<method name="set_ccdik_joint_rotate_from_joint">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="rotate_from_joint" type="bool">
</argument>
<description>
Sets whether the joint at [code]joint_idx[/code] is set to rotate from the joint, [code]true[/code], or to rotate from the tip, [code]false[/code].
</description>
</method>
</methods>
<members>
<member name="ccdik_data_chain_length" type="int" setter="set_ccdik_data_chain_length" getter="get_ccdik_data_chain_length" default="0">
The amount of CCDIK joints in the CCDIK modification.
</member>
<member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath(&quot;&quot;)">
The NodePath to the node that is the target for the CCDIK modification. This node is what the CCDIK chain will attempt to rotate the bone chain to.
</member>
<member name="tip_nodepath" type="NodePath" setter="set_tip_node" getter="get_tip_node" default="NodePath(&quot;&quot;)">
The end position of the CCDIK chain. Typically, this should be a child of a [Bone2D] node attached to the final [Bone2D] in the CCDIK chain.
</member>
</members>
<constants>
</constants>
</class>

View file

@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SkeletonModification2DFABRIK" inherits="SkeletonModification2D" version="4.0">
<brief_description>
A modification that uses FABRIK to manipulate a series of [Bone2D] nodes to reach a target.
</brief_description>
<description>
This [SkeletonModification2D] uses an algorithm called [b]F[/b]orward [b]A[/b]nd [b]B[/b]ackward [b]R[/b]eaching [b]I[/b]nverse [b]K[/b]inematics, or FABRIK, to rotate a bone chain so that it reaches a target.
FABRIK works by knowing the positions and lengths of a series of bones, typically called a "bone chain". It first starts by running a forward pass, which places the final bone at the target's position. Then all other bones are moved towards the tip bone, so they stay at the defined bone length away. Then a backwards pass is performed, where the root/first bone in the FABRIK chain is placed back at the origin. then all other bones are moved so they stay at the defined bone length away. This positions the bone chain so that it reaches the target when possible, but all of the bones stay the correct length away from each other.
Because of how FABRIK works, it often gives more natural results than those seen in [SkeletonModification2DCCDIK]. FABRIK also supports angle constraints, which are fully taken into account when solving.
[b]Note:[/b] The FABRIK modifier has [code]fabrik_joints[/code], which are the data objects that hold the data for each joint in the FABRIK chain. This is different from [Bone2D] nodes! FABRIK joints hold the data needed for each [Bone2D] in the bone chain used by FABRIK.
To help control how the FABRIK joints move, a magnet vector can be passed, which can nudge the bones in a certain direction prior to solving, giving a level of control over the final result.
</description>
<tutorials>
</tutorials>
<methods>
<method name="get_fabrik_joint_bone2d_node" qualifiers="const">
<return type="NodePath">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the [Bone2D] node assigned to the FABRIK joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_fabrik_joint_bone_index" qualifiers="const">
<return type="int">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the index of the [Bone2D] node assigned to the FABRIK joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_fabrik_joint_magnet_position" qualifiers="const">
<return type="Vector2">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the magnet position vector for the joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_fabrik_joint_use_target_rotation" qualifiers="const">
<return type="bool">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns whether the joint is using the target's rotation rather than allowing FABRIK to rotate the joint. This option only applies to the tip/final joint in the chain.
</description>
</method>
<method name="set_fabrik_joint_bone2d_node">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="bone2d_nodepath" type="NodePath">
</argument>
<description>
Sets the [Bone2D] node assigned to the FABRIK joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_fabrik_joint_bone_index">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="bone_idx" type="int">
</argument>
<description>
Sets the bone index, [code]bone_index[/code], of the FABRIK joint at [code]joint_idx[/code]. When possible, this will also update the [code]bone2d_node[/code] of the FABRIK joint based on data provided by the linked skeleton.
</description>
</method>
<method name="set_fabrik_joint_magnet_position">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="magnet_position" type="Vector2">
</argument>
<description>
Sets the magnet position vector for the joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_fabrik_joint_use_target_rotation">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="use_target_rotation" type="bool">
</argument>
<description>
Sets whether the joint at [code]joint_idx[/code] will use the target node's rotation rather than letting FABRIK rotate the node.
[b]Note:[/b] This option only works for the tip/final joint in the chain. For all other nodes, this option will be ignored.
</description>
</method>
</methods>
<members>
<member name="fabrik_data_chain_length" type="int" setter="set_fabrik_data_chain_length" getter="get_fabrik_data_chain_length" default="0">
The amount of FABRIK joints in the FABRIK modification.
</member>
<member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath(&quot;&quot;)">
The NodePath to the node that is the target for the FABRIK modification. This node is what the FABRIK chain will attempt to rotate the bone chain to.
</member>
</members>
<constants>
</constants>
</class>

View file

@ -0,0 +1,232 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SkeletonModification2DJiggle" inherits="SkeletonModification2D" version="4.0">
<brief_description>
A modification that jiggles [Bone2D] nodes as they move towards a target.
</brief_description>
<description>
This modification moves a series of bones, typically called a bone chain, towards a target. What makes this modification special is that it calculates the velocity and acceleration for each bone in the bone chain, and runs a very light physics-like calculation using the inputted values. This allows the bones to overshoot the target and "jiggle" around. It can be configured to act more like a spring, or sway around like cloth might.
This modification is useful for adding additional motion to things like hair, the edges of clothing, and more. It has several settings to that allow control over how the joint moves when the target moves.
[b]Note:[/b] The Jiggle modifier has [code]jiggle_joints[/code], which are the data objects that hold the data for each joint in the Jiggle chain. This is different from than [Bone2D] nodes! Jiggle joints hold the data needed for each [Bone2D] in the bone chain used by the Jiggle modification.
</description>
<tutorials>
</tutorials>
<methods>
<method name="get_collision_mask" qualifiers="const">
<return type="int">
</return>
<description>
Returns the collision mask used by the Jiggle modifier when collisions are enabled.
</description>
</method>
<method name="get_jiggle_joint_bone2d_node" qualifiers="const">
<return type="NodePath">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the [Bone2D] node assigned to the Jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_jiggle_joint_bone_index" qualifiers="const">
<return type="int">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the index of the [Bone2D] node assigned to the Jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_jiggle_joint_damping" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the amount of damping of the Jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_jiggle_joint_gravity" qualifiers="const">
<return type="Vector2">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns a [Vector2] representing the amount of gravity the Jiggle joint at [code]joint_idx[/code] is influenced by.
</description>
</method>
<method name="get_jiggle_joint_mass" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the amount of mass of the jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_jiggle_joint_override" qualifiers="const">
<return type="bool">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns a boolean that indiciates whether the joint at [code]joint_idx[/code] is overriding the default Jiggle joint data defined in the modification.
</description>
</method>
<method name="get_jiggle_joint_stiffness" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the stiffness of the Jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="get_jiggle_joint_use_gravity" qualifiers="const">
<return type="bool">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns a boolean that indiciates whether the joint at [code]joint_idx[/code] is using gravity or not.
</description>
</method>
<method name="get_use_colliders" qualifiers="const">
<return type="bool">
</return>
<description>
Returns whether the jiggle modifier is taking physics colliders into account when solving.
</description>
</method>
<method name="set_collision_mask">
<return type="void">
</return>
<argument index="0" name="collision_mask" type="int">
</argument>
<description>
Sets the collision mask that the Jiggle modifier will use when reacting to colliders, if the Jiggle modifier is set to take colliders into account.
</description>
</method>
<method name="set_jiggle_joint_bone2d_node">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="bone2d_node" type="NodePath">
</argument>
<description>
Sets the [Bone2D] node assigned to the Jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_jiggle_joint_bone_index">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="bone_idx" type="int">
</argument>
<description>
Sets the bone index, [code]bone_index[/code], of the Jiggle joint at [code]joint_idx[/code]. When possible, this will also update the [code]bone2d_node[/code] of the Jiggle joint based on data provided by the linked skeleton.
</description>
</method>
<method name="set_jiggle_joint_damping">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="damping" type="float">
</argument>
<description>
Sets the amount of dampening of the Jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_jiggle_joint_gravity">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="gravity" type="Vector2">
</argument>
<description>
Sets the gravity vector of the Jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_jiggle_joint_mass">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="mass" type="float">
</argument>
<description>
Sets the of mass of the Jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_jiggle_joint_override">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="override" type="bool">
</argument>
<description>
Sets whether the Jiggle joint at [code]joint_idx[/code] should override the default Jiggle joint settings. Setting this to [code]true[/code] will make the joint use its own settings rather than the default ones attached to the modification.
</description>
</method>
<method name="set_jiggle_joint_stiffness">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="stiffness" type="float">
</argument>
<description>
Sets the of stiffness of the Jiggle joint at [code]joint_idx[/code].
</description>
</method>
<method name="set_jiggle_joint_use_gravity">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="use_gravity" type="bool">
</argument>
<description>
Sets whether the Jiggle joint at [code]joint_idx[/code] should use gravity.
</description>
</method>
<method name="set_use_colliders">
<return type="void">
</return>
<argument index="0" name="use_colliders" type="bool">
</argument>
<description>
If [code]true[/code], the Jiggle modifier will take colliders into account, keeping them from entering into these collision objects.
</description>
</method>
</methods>
<members>
<member name="damping" type="float" setter="set_damping" getter="get_damping" default="0.75">
The default amount of dampening applied to the Jiggle joints, if they are not overriden. Higher values lead to more of the calculated velocity being applied.
</member>
<member name="gravity" type="Vector2" setter="set_gravity" getter="get_gravity" default="Vector2( 0, 6 )">
The default amount of gravity applied to the Jiggle joints, if they are not overriden.
</member>
<member name="jiggle_data_chain_length" type="int" setter="set_jiggle_data_chain_length" getter="get_jiggle_data_chain_length" default="0">
The amount of Jiggle joints in the Jiggle modification.
</member>
<member name="mass" type="float" setter="set_mass" getter="get_mass" default="0.75">
The default amount of mass assigned to the Jiggle joints, if they are not overriden. Higher values lead to faster movements and more overshooting.
</member>
<member name="stiffness" type="float" setter="set_stiffness" getter="get_stiffness" default="3.0">
The default amount of stiffness assigned to the Jiggle joints, if they are not overriden. Higher values act more like springs, quickly moving into the correct position.
</member>
<member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath(&quot;&quot;)">
The NodePath to the node that is the target for the Jiggle modification. This node is what the Jiggle chain will attempt to rotate the bone chain to.
</member>
<member name="use_gravity" type="bool" setter="set_use_gravity" getter="get_use_gravity" default="false">
Whether the gravity vector, [member gravity], should be applied to the Jiggle joints, assuming they are not overriding the default settings.
</member>
</members>
<constants>
</constants>
</class>

View file

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SkeletonModification2DLookAt" inherits="SkeletonModification2D" version="4.0">
<brief_description>
A modification that rotates a [Bone2D] node to look at a target.
</brief_description>
<description>
This [SkeletonModification2D] rotates a bone to look a target. This is extremely helpful for moving character's head to look at the player, rotating a turret to look at a target, or any other case where you want to make a bone rotate towards something quickly and easily.
</description>
<tutorials>
</tutorials>
<methods>
<method name="get_additional_rotation" qualifiers="const">
<return type="float">
</return>
<description>
Returns the amount of additional rotation that is applied after the LookAt modification executes.
</description>
</method>
<method name="get_constraint_angle_invert" qualifiers="const">
<return type="bool">
</return>
<description>
Returns whether the constraints to this modification are inverted or not.
</description>
</method>
<method name="get_constraint_angle_max" qualifiers="const">
<return type="float">
</return>
<description>
Returns the constraint's maximum allowed angle.
</description>
</method>
<method name="get_constraint_angle_min" qualifiers="const">
<return type="float">
</return>
<description>
Returns the constraint's minimum allowed angle.
</description>
</method>
<method name="get_enable_constraint" qualifiers="const">
<return type="bool">
</return>
<description>
Returns [code]true[/code] if the LookAt modification is using constraints.
</description>
</method>
<method name="set_additional_rotation">
<return type="void">
</return>
<argument index="0" name="rotation" type="float">
</argument>
<description>
Sets the amount of additional rotation that is to be applied after executing the modification. This allows for offsetting the results by the inputted rotation amount.
</description>
</method>
<method name="set_constraint_angle_invert">
<return type="void">
</return>
<argument index="0" name="invert" type="bool">
</argument>
<description>
When [code]true[/code], the modification will use an inverted joint constraint.
An inverted joint constraint only constraints the [Bone2D] to the angles [i]outside of[/i] the inputted minimum and maximum angles. For this reason, it is referred to as an inverted joint constraint, as it constraints the joint to the outside of the inputted values.
</description>
</method>
<method name="set_constraint_angle_max">
<return type="void">
</return>
<argument index="0" name="angle_max" type="float">
</argument>
<description>
Sets the constraint's maximum allowed angle.
</description>
</method>
<method name="set_constraint_angle_min">
<return type="void">
</return>
<argument index="0" name="angle_min" type="float">
</argument>
<description>
Sets the constraint's minimum allowed angle.
</description>
</method>
<method name="set_enable_constraint">
<return type="void">
</return>
<argument index="0" name="enable_constraint" type="bool">
</argument>
<description>
Sets whether this modification will use constraints or not. When [code]true[/code], constraints will be applied when solving the LookAt modification.
</description>
</method>
</methods>
<members>
<member name="bone2d_node" type="NodePath" setter="set_bone2d_node" getter="get_bone2d_node" default="NodePath(&quot;&quot;)">
The [Bone2D] node that the modification will operate on.
</member>
<member name="bone_index" type="int" setter="set_bone_index" getter="get_bone_index" default="-1">
The index of the [Bone2D] node that the modification will oeprate on.
</member>
<member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath(&quot;&quot;)">
The NodePath to the node that is the target for the LookAt modification. This node is what the modification will rotate the [Bone2D] to.
</member>
</members>
<constants>
</constants>
</class>

View file

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SkeletonModification2DPhysicalBones" inherits="SkeletonModification2D" version="4.0">
<brief_description>
A modification that applies the transforms of [PhysicalBone2D] nodes to [Bone2D] nodes.
</brief_description>
<description>
This modification takes the transforms of [PhysicalBone2D] nodes and applies them to [Bone2D] nodes. This allows the [Bone2D] nodes to react to physics thanks to the linked [PhysicalBone2D] nodes.
</description>
<tutorials>
</tutorials>
<methods>
<method name="fetch_physical_bones">
<return type="void">
</return>
<description>
Empties the list of [PhysicalBone2D] nodes and populates it will all [PhysicalBone2D] nodes that are children of the [Skeleton2D].
</description>
</method>
<method name="get_physical_bone_node" qualifiers="const">
<return type="NodePath">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<description>
Returns the [PhysicalBone2D] node at [code]joint_idx[/code].
</description>
</method>
<method name="set_physical_bone_node">
<return type="void">
</return>
<argument index="0" name="joint_idx" type="int">
</argument>
<argument index="1" name="physicalbone2d_node" type="NodePath">
</argument>
<description>
Sets the [PhysicalBone2D] node at [code]joint_idx[/code].
[b]Note:[/b] This is just the index used for this modification, not the bone index used in the [Skeleton2D].
</description>
</method>
<method name="start_simulation">
<return type="void">
</return>
<argument index="0" name="bones" type="StringName[]" default="[ ]">
</argument>
<description>
Tell the [PhysicalBone2D] nodes to start simulating and interacting with the physics world.
Optionally, an array of bone names can be passed to this function, and that will cause only [PhysicalBone2D] nodes with those names to start simulating.
</description>
</method>
<method name="stop_simulation">
<return type="void">
</return>
<argument index="0" name="bones" type="StringName[]" default="[ ]">
</argument>
<description>
Tell the [PhysicalBone2D] nodes to stop simulating and interacting with the physics world.
Optionally, an array of bone names can be passed to this function, and that will cause only [PhysicalBone2D] nodes with those names to stop simulating.
</description>
</method>
</methods>
<members>
<member name="physical_bone_chain_length" type="int" setter="set_physical_bone_chain_length" getter="get_physical_bone_chain_length" default="0">
The amount of [PhysicalBone2D] nodes linked in this modification.
</member>
</members>
<constants>
</constants>
</class>

View file

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SkeletonModification2DStackHolder" inherits="SkeletonModification2D" version="4.0">
<brief_description>
A modification that holds and executes a [SkeletonModificationStack2D].
</brief_description>
<description>
This [SkeletonModification2D] holds a reference to a [SkeletonModificationStack2D], allowing you to use multiple modification stacks on a single [Skeleton2D].
[b]Note:[/b] The modifications in the held [SkeletonModificationStack2D] will only be executed if their execution mode matches the execution mode of the SkeletonModification2DStackHolder.
</description>
<tutorials>
</tutorials>
<methods>
<method name="get_held_modification_stack" qualifiers="const">
<return type="SkeletonModificationStack2D">
</return>
<description>
Returns the [SkeletonModificationStack2D] that this modification is holding.
</description>
</method>
<method name="set_held_modification_stack">
<return type="void">
</return>
<argument index="0" name="held_modification_stack" type="SkeletonModificationStack2D">
</argument>
<description>
Sets the [SkeletonModificationStack2D] that this modification is holding. This modification stack will then be executed when this modification is executed.
</description>
</method>
</methods>
<constants>
</constants>
</class>

View file

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SkeletonModification2DTwoBoneIK" inherits="SkeletonModification2D" version="4.0">
<brief_description>
A modification that rotates two bones using the law of cosigns to reach the target.
</brief_description>
<description>
This [SkeletonModification2D] uses an algorithm typically called TwoBoneIK. This algorithm works by leveraging the law of cosigns and the lengths of the bones to figure out what rotation the bones currently have, and what rotation they need to make a complete triangle, where the first bone, the second bone, and the target form the three verticies of the triangle. Because the algorithm works by making a triangle, it can only opperate on two bones.
TwoBoneIK is great for arms, legs, and really any joints that can be represented by just two bones that bend to reach a target. This solver is more lightweight than [SkeletonModification2DFABRIK], but gives similar, natural looking results.
</description>
<tutorials>
</tutorials>
<methods>
<method name="get_joint_one_bone2d_node" qualifiers="const">
<return type="NodePath">
</return>
<description>
Returns the [Bone2D] node that is being used as the first bone in the TwoBoneIK modification.
</description>
</method>
<method name="get_joint_one_bone_idx" qualifiers="const">
<return type="int">
</return>
<description>
Returns the index of the [Bone2D] node that is being used as the first bone in the TwoBoneIK modification.
</description>
</method>
<method name="get_joint_two_bone2d_node" qualifiers="const">
<return type="NodePath">
</return>
<description>
Returns the [Bone2D] node that is being used as the second bone in the TwoBoneIK modification.
</description>
</method>
<method name="get_joint_two_bone_idx" qualifiers="const">
<return type="int">
</return>
<description>
Returns the index of the [Bone2D] node that is being used as the second bone in the TwoBoneIK modification.
</description>
</method>
<method name="set_joint_one_bone2d_node">
<return type="void">
</return>
<argument index="0" name="bone2d_node" type="NodePath">
</argument>
<description>
Sets the [Bone2D] node that is being used as the first bone in the TwoBoneIK modification.
</description>
</method>
<method name="set_joint_one_bone_idx">
<return type="void">
</return>
<argument index="0" name="bone_idx" type="int">
</argument>
<description>
Sets the index of the [Bone2D] node that is being used as the first bone in the TwoBoneIK modification.
</description>
</method>
<method name="set_joint_two_bone2d_node">
<return type="void">
</return>
<argument index="0" name="bone2d_node" type="NodePath">
</argument>
<description>
Sets the [Bone2D] node that is being used as the second bone in the TwoBoneIK modification.
</description>
</method>
<method name="set_joint_two_bone_idx">
<return type="void">
</return>
<argument index="0" name="bone_idx" type="int">
</argument>
<description>
Sets the index of the [Bone2D] node that is being used as the second bone in the TwoBoneIK modification.
</description>
</method>
</methods>
<members>
<member name="flip_bend_direction" type="bool" setter="set_flip_bend_direction" getter="get_flip_bend_direction" default="false">
If [code]true[/code], the bones in the modification will blend outward as opposed to inwards when contracting. If [code]false[/code], the bones will bend inwards when contracting.
</member>
<member name="target_maximum_distance" type="float" setter="set_target_maximum_distance" getter="get_target_maximum_distance" default="0.0">
The maximum distance the target can be at. If the target is farther than this distance, the modification will solve as if it's at this maximum distance. When set to [code]0[/code], the modification will solve without distance constraints.
</member>
<member name="target_minimum_distance" type="float" setter="set_target_minimum_distance" getter="get_target_minimum_distance" default="0.0">
The minimum distance the target can be at. If the target is closer than this distance, the modification will solve as if it's at this minimum distance. When set to [code]0[/code], the modification will solve without distance constraints.
</member>
<member name="target_nodepath" type="NodePath" setter="set_target_node" getter="get_target_node" default="NodePath(&quot;&quot;)">
The NodePath to the node that is the target for the TwoBoneIK modification. This node is what the modification will use when bending the [Bone2D] nodes.
</member>
</members>
<constants>
</constants>
</class>

View file

@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SkeletonModificationStack2D" inherits="Resource" version="4.0">
<brief_description>
A resource that holds a stack of [SkeletonModification2D]s.
</brief_description>
<description>
This resource is used by the Skeleton and holds a stack of [SkeletonModification2D]s.
This controls the order of the modifications and how they are applied. Modification order is especially important for full-body IK setups, as you need to execute the modifications in the correct order to get the desired results. For example, you want to execute a modification on the spine [i]before[/i] the arms on a humanoid skeleton.
This resource also controls how strongly all of the modifications are applied to the [Skeleton2D].
</description>
<tutorials>
</tutorials>
<methods>
<method name="add_modification">
<return type="void">
</return>
<argument index="0" name="modification" type="SkeletonModification2D">
</argument>
<description>
Adds the passed-in [SkeletonModification2D] to the stack.
</description>
</method>
<method name="delete_modification">
<return type="void">
</return>
<argument index="0" name="mod_idx" type="int">
</argument>
<description>
Deletes the [SkeletonModification2D] at the index position [code]mod_idx[/code], if it exists.
</description>
</method>
<method name="enable_all_modifications">
<return type="void">
</return>
<argument index="0" name="enabled" type="bool">
</argument>
<description>
Enables all [SkeletonModification2D]s in the stack.
</description>
</method>
<method name="execute">
<return type="void">
</return>
<argument index="0" name="delta" type="float">
</argument>
<argument index="1" name="execution_mode" type="int">
</argument>
<description>
Executes all of the [SkeletonModification2D]s in the stack that use the same execution mode as the passed-in [code]execution_mode[/code], starting from index [code]0[/code] to [member modification_count].
[b]Note:[/b] The order of the modifications can matter depending on the modifications. For example, modifications on a spine should operate before modifications on the arms in order to get proper results.
</description>
</method>
<method name="get_is_setup" qualifiers="const">
<return type="bool">
</return>
<description>
Returns a boolean that indiciates whether the modification stack is setup and can execute.
</description>
</method>
<method name="get_modification" qualifiers="const">
<return type="SkeletonModification2D">
</return>
<argument index="0" name="mod_idx" type="int">
</argument>
<description>
Returns the [SkeletonModification2D] at the passed-in index, [code]mod_idx[/code].
</description>
</method>
<method name="get_skeleton" qualifiers="const">
<return type="Skeleton2D">
</return>
<description>
Returns the [Skeleton2D] node that the SkeletonModificationStack2D is bound to.
</description>
</method>
<method name="set_modification">
<return type="void">
</return>
<argument index="0" name="mod_idx" type="int">
</argument>
<argument index="1" name="modification" type="SkeletonModification2D">
</argument>
<description>
Sets the modification at [code]mod_idx[/code] to the passed-in modification, [code]modification[/code].
</description>
</method>
<method name="setup">
<return type="void">
</return>
<description>
Sets up the modification stack so it can execute. This function should be called by [Skeleton2D] and shouldn't be manually called unless you know what you are doing.
</description>
</method>
</methods>
<members>
<member name="enabled" type="bool" setter="set_enabled" getter="get_enabled" default="false">
If [code]true[/code], the modification's in the stack will be called. This is handled automatically through the [Skeleton2D] node.
</member>
<member name="modification_count" type="int" setter="set_modification_count" getter="get_modification_count" default="0">
The number of modifications in the stack.
</member>
<member name="strength" type="float" setter="set_strength" getter="get_strength" default="1.0">
The interpolation strength of the modifications in stack. A value of [code]0[/code] will make it where the modifications are not applied, a strength of [code]0.5[/code] will be half applied, and a strength of [code]1[/code] will allow the modifications to be fully applied and override the [Skeleton2D] [Bone2D] poses.
</member>
</members>
<constants>
</constants>
</class>

View file

@ -129,6 +129,16 @@
Returns [code]true[/code] if this transform and [code]transform[/code] are approximately equal, by calling [code]is_equal_approx[/code] on each component.
</description>
</method>
<method name="looking_at" qualifiers="const">
<return type="Transform2D">
</return>
<argument index="0" name="target" type="Vector2" default="Transform2D( 1, 0, 0, 1, 0, 0 )">
</argument>
<description>
Returns a copy of the transform rotated such that it's rotation on the X-axis points towards the [code]target[/code] position.
Operations take place in global space.
</description>
</method>
<method name="operator !=" qualifiers="operator">
<return type="bool">
</return>
@ -138,17 +148,9 @@
</description>
</method>
<method name="operator *" qualifiers="operator">
<return type="Vector2">
<return type="PackedVector2Array">
</return>
<argument index="0" name="right" type="Vector2">
</argument>
<description>
</description>
</method>
<method name="operator *" qualifiers="operator">
<return type="Rect2">
</return>
<argument index="0" name="right" type="Rect2">
<argument index="0" name="right" type="PackedVector2Array">
</argument>
<description>
</description>
@ -162,9 +164,17 @@
</description>
</method>
<method name="operator *" qualifiers="operator">
<return type="PackedVector2Array">
<return type="Rect2">
</return>
<argument index="0" name="right" type="PackedVector2Array">
<argument index="0" name="right" type="Rect2">
</argument>
<description>
</description>
</method>
<method name="operator *" qualifiers="operator">
<return type="Vector2">
</return>
<argument index="0" name="right" type="Vector2">
</argument>
<description>
</description>
@ -210,6 +220,15 @@
Scales the transform by the given scale factor, using matrix multiplication.
</description>
</method>
<method name="set_rotation">
<return type="void">
</return>
<argument index="0" name="rotation" type="float">
</argument>
<description>
Sets the transform's rotation (in radians).
</description>
</method>
<method name="translated" qualifiers="const">
<return type="Transform2D">
</return>

View file

@ -1587,6 +1587,8 @@ void EditorNode::_save_scene(String p_file, int idx) {
return;
}
scene->propagate_notification(NOTIFICATION_EDITOR_PRE_SAVE);
editor_data.apply_changes_in_editors();
List<Ref<AnimatedValuesBackup>> anim_backups;
_reset_animation_players(scene, &anim_backups);
@ -1658,6 +1660,8 @@ void EditorNode::_save_scene(String p_file, int idx) {
} else {
_dialog_display_save_error(p_file, err);
}
scene->propagate_notification(NOTIFICATION_EDITOR_POST_SAVE);
}
void EditorNode::save_all_scenes() {

View file

@ -689,11 +689,11 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
_initial_set("editors/2d/guides_color", Color(0.6, 0.0, 0.8));
_initial_set("editors/2d/smart_snapping_line_color", Color(0.9, 0.1, 0.1));
_initial_set("editors/2d/bone_width", 5);
_initial_set("editors/2d/bone_color1", Color(1.0, 1.0, 1.0, 0.9));
_initial_set("editors/2d/bone_color2", Color(0.6, 0.6, 0.6, 0.9));
_initial_set("editors/2d/bone_selected_color", Color(0.9, 0.45, 0.45, 0.9));
_initial_set("editors/2d/bone_ik_color", Color(0.9, 0.9, 0.45, 0.9));
_initial_set("editors/2d/bone_outline_color", Color(0.35, 0.35, 0.35));
_initial_set("editors/2d/bone_color1", Color(1.0, 1.0, 1.0, 0.7));
_initial_set("editors/2d/bone_color2", Color(0.6, 0.6, 0.6, 0.7));
_initial_set("editors/2d/bone_selected_color", Color(0.9, 0.45, 0.45, 0.7));
_initial_set("editors/2d/bone_ik_color", Color(0.9, 0.9, 0.45, 0.7));
_initial_set("editors/2d/bone_outline_color", Color(0.35, 0.35, 0.35, 0.5));
_initial_set("editors/2d/bone_outline_size", 2);
_initial_set("editors/2d/viewport_border_color", Color(0.4, 0.4, 1.0, 0.4));
_initial_set("editors/2d/constrain_editor_view", true);

View file

@ -666,93 +666,6 @@ void CanvasItemEditor::_get_canvas_items_at_pos(const Point2 &p_pos, Vector<_Sel
}
}
void CanvasItemEditor::_get_bones_at_pos(const Point2 &p_pos, Vector<_SelectResult> &r_items) {
Point2 screen_pos = transform.xform(p_pos);
for (Map<BoneKey, BoneList>::Element *E = bone_list.front(); E; E = E->next()) {
Node2D *from_node = Object::cast_to<Node2D>(ObjectDB::get_instance(E->key().from));
Vector<Vector2> bone_shape;
if (!_get_bone_shape(&bone_shape, nullptr, E)) {
continue;
}
// Check if the point is inside the Polygon2D
if (Geometry2D::is_point_in_polygon(screen_pos, bone_shape)) {
// Check if the item is already in the list
bool duplicate = false;
for (int i = 0; i < r_items.size(); i++) {
if (r_items[i].item == from_node) {
duplicate = true;
break;
}
}
if (duplicate) {
continue;
}
// Else, add it
_SelectResult res;
res.item = from_node;
res.z_index = from_node ? from_node->get_z_index() : 0;
res.has_z = from_node;
r_items.push_back(res);
}
}
}
bool CanvasItemEditor::_get_bone_shape(Vector<Vector2> *shape, Vector<Vector2> *outline_shape, Map<BoneKey, BoneList>::Element *bone) {
int bone_width = EditorSettings::get_singleton()->get("editors/2d/bone_width");
int bone_outline_width = EditorSettings::get_singleton()->get("editors/2d/bone_outline_size");
Node2D *from_node = Object::cast_to<Node2D>(ObjectDB::get_instance(bone->key().from));
Node2D *to_node = Object::cast_to<Node2D>(ObjectDB::get_instance(bone->key().to));
if (!from_node) {
return false;
}
if (!from_node->is_inside_tree()) {
return false; //may have been removed
}
if (!to_node && bone->get().length == 0) {
return false;
}
Vector2 from = transform.xform(from_node->get_global_position());
Vector2 to;
if (to_node) {
to = transform.xform(to_node->get_global_position());
} else {
to = transform.xform(from_node->get_global_transform().xform(Vector2(bone->get().length, 0)));
}
Vector2 rel = to - from;
Vector2 relt = rel.orthogonal().normalized() * bone_width;
Vector2 reln = rel.normalized();
Vector2 reltn = relt.normalized();
if (shape) {
shape->clear();
shape->push_back(from);
shape->push_back(from + rel * 0.2 + relt);
shape->push_back(to);
shape->push_back(from + rel * 0.2 - relt);
}
if (outline_shape) {
outline_shape->clear();
outline_shape->push_back(from + (-reln - reltn) * bone_outline_width);
outline_shape->push_back(from + (-reln + reltn) * bone_outline_width);
outline_shape->push_back(from + rel * 0.2 + relt + reltn * bone_outline_width);
outline_shape->push_back(to + (reln + reltn) * bone_outline_width);
outline_shape->push_back(to + (reln - reltn) * bone_outline_width);
outline_shape->push_back(from + rel * 0.2 - relt - reltn * bone_outline_width);
}
return true;
}
void CanvasItemEditor::_find_canvas_items_in_rect(const Rect2 &p_rect, Node *p_node, List<CanvasItem *> *r_items, const Transform2D &p_parent_xform, const Transform2D &p_canvas_xform) {
if (!p_node) {
return;
@ -886,50 +799,6 @@ Vector2 CanvasItemEditor::_position_to_anchor(const Control *p_control, Vector2
return output;
}
void CanvasItemEditor::_save_canvas_item_ik_chain(const CanvasItem *p_canvas_item, List<float> *p_bones_length, List<Dictionary> *p_bones_state) {
if (p_bones_length) {
*p_bones_length = List<float>();
}
if (p_bones_state) {
*p_bones_state = List<Dictionary>();
}
const Node2D *bone = Object::cast_to<Node2D>(p_canvas_item);
if (bone && bone->has_meta("_edit_bone_")) {
// Check if we have an IK chain
List<const Node2D *> bone_ik_list;
bool ik_found = false;
bone = Object::cast_to<Node2D>(bone->get_parent());
while (bone) {
bone_ik_list.push_back(bone);
if (bone->has_meta("_edit_ik_")) {
ik_found = true;
break;
} else if (!bone->has_meta("_edit_bone_")) {
break;
}
bone = Object::cast_to<Node2D>(bone->get_parent());
}
//Save the bone state and length if we have an IK chain
if (ik_found) {
bone = Object::cast_to<Node2D>(p_canvas_item);
Transform2D bone_xform = bone->get_global_transform();
for (List<const Node2D *>::Element *bone_E = bone_ik_list.front(); bone_E; bone_E = bone_E->next()) {
bone_xform = bone_xform * bone->get_transform().affine_inverse();
const Node2D *parent_bone = bone_E->get();
if (p_bones_length) {
p_bones_length->push_back(parent_bone->get_global_transform().get_origin().distance_to(bone->get_global_position()));
}
if (p_bones_state) {
p_bones_state->push_back(parent_bone->_edit_get_state());
}
bone = parent_bone;
}
}
}
}
void CanvasItemEditor::_save_canvas_item_state(List<CanvasItem *> p_canvas_items, bool save_bones) {
for (List<CanvasItem *>::Element *E = p_canvas_items.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get();
@ -942,31 +811,15 @@ void CanvasItemEditor::_save_canvas_item_state(List<CanvasItem *> p_canvas_items
} else {
se->pre_drag_rect = Rect2();
}
// If we have a bone, save the state of all nodes in the IK chain
_save_canvas_item_ik_chain(canvas_item, &(se->pre_drag_bones_length), &(se->pre_drag_bones_undo_state));
}
}
}
void CanvasItemEditor::_restore_canvas_item_ik_chain(CanvasItem *p_canvas_item, const List<Dictionary> *p_bones_state) {
CanvasItem *canvas_item = p_canvas_item;
for (const List<Dictionary>::Element *E = p_bones_state->front(); E; E = E->next()) {
canvas_item = Object::cast_to<CanvasItem>(canvas_item->get_parent());
canvas_item->_edit_set_state(E->get());
}
}
void CanvasItemEditor::_restore_canvas_item_state(List<CanvasItem *> p_canvas_items, bool restore_bones) {
for (List<CanvasItem *>::Element *E = drag_selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get();
CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (se) {
canvas_item->_edit_set_state(se->undo_state);
if (restore_bones) {
_restore_canvas_item_ik_chain(canvas_item, &(se->pre_drag_bones_undo_state));
}
}
canvas_item->_edit_set_state(se->undo_state);
}
}
@ -1497,76 +1350,6 @@ bool CanvasItemEditor::_gui_input_pivot(const Ref<InputEvent> &p_event) {
return false;
}
void CanvasItemEditor::_solve_IK(Node2D *leaf_node, Point2 target_position) {
CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(leaf_node);
if (se) {
int nb_bones = se->pre_drag_bones_undo_state.size();
if (nb_bones > 0) {
// Build the node list
Point2 leaf_pos = target_position;
List<Node2D *> joints_list;
List<Point2> joints_pos;
Node2D *joint = leaf_node;
Transform2D joint_transform = leaf_node->get_global_transform_with_canvas();
for (int i = 0; i < nb_bones + 1; i++) {
joints_list.push_back(joint);
joints_pos.push_back(joint_transform.get_origin());
joint_transform = joint_transform * joint->get_transform().affine_inverse();
joint = Object::cast_to<Node2D>(joint->get_parent());
}
Point2 root_pos = joints_list.back()->get()->get_global_transform_with_canvas().get_origin();
// Restraints the node to a maximum distance is necessary
float total_len = 0;
for (List<float>::Element *E = se->pre_drag_bones_length.front(); E; E = E->next()) {
total_len += E->get();
}
if ((root_pos.distance_to(leaf_pos)) > total_len) {
Vector2 rel = leaf_pos - root_pos;
rel = rel.normalized() * total_len;
leaf_pos = root_pos + rel;
}
joints_pos[0] = leaf_pos;
// Run the solver
int solver_iterations = 64;
float solver_k = 0.3;
// Build the position list
for (int i = 0; i < solver_iterations; i++) {
// Handle the leaf joint
int node_id = 0;
for (List<float>::Element *E = se->pre_drag_bones_length.front(); E; E = E->next()) {
Vector2 direction = (joints_pos[node_id + 1] - joints_pos[node_id]).normalized();
int len = E->get();
if (E == se->pre_drag_bones_length.front()) {
joints_pos[1] = joints_pos[1].lerp(joints_pos[0] + len * direction, solver_k);
} else if (E == se->pre_drag_bones_length.back()) {
joints_pos[node_id] = joints_pos[node_id].lerp(joints_pos[node_id + 1] - len * direction, solver_k);
} else {
Vector2 center = (joints_pos[node_id + 1] + joints_pos[node_id]) / 2.0;
joints_pos[node_id] = joints_pos[node_id].lerp(center - (direction * len) / 2.0, solver_k);
joints_pos[node_id + 1] = joints_pos[node_id + 1].lerp(center + (direction * len) / 2.0, solver_k);
}
node_id++;
}
}
// Set the position
for (int node_id = joints_list.size() - 1; node_id > 0; node_id--) {
Point2 current = (joints_list[node_id - 1]->get_global_position() - joints_list[node_id]->get_global_position()).normalized();
Point2 target = (joints_pos[node_id - 1] - joints_list[node_id]->get_global_position()).normalized();
float rot = current.angle_to(target);
if (joints_list[node_id]->get_global_transform().basis_determinant() < 0) {
rot = -rot;
}
joints_list[node_id]->rotate(rot);
}
}
}
}
bool CanvasItemEditor::_gui_input_rotate(const Ref<InputEvent> &p_event) {
Ref<InputEventMouseButton> b = p_event;
Ref<InputEventMouseMotion> m = p_event;
@ -2208,14 +1991,6 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) {
if (drag_type == DRAG_MOVE || drag_type == DRAG_MOVE_X || drag_type == DRAG_MOVE_Y) {
// Move the nodes
if (m.is_valid()) {
// Save the ik chain for reapplying before IK solve
Vector<List<Dictionary>> all_bones_ik_states;
for (List<CanvasItem *>::Element *E = drag_selection.front(); E; E = E->next()) {
List<Dictionary> bones_ik_states;
_save_canvas_item_ik_chain(E->get(), nullptr, &bones_ik_states);
all_bones_ik_states.push_back(bones_ik_states);
}
_restore_canvas_item_state(drag_selection, true);
drag_to = transform.affine_inverse().xform(m->get_position());
@ -2244,25 +2019,12 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) {
}
}
bool force_no_IK = m->is_alt_pressed();
int index = 0;
for (List<CanvasItem *>::Element *E = drag_selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get();
CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (se) {
Transform2D xform = canvas_item->get_global_transform_with_canvas().affine_inverse() * canvas_item->get_transform();
Transform2D xform = canvas_item->get_global_transform_with_canvas().affine_inverse() * canvas_item->get_transform();
Node2D *node2d = Object::cast_to<Node2D>(canvas_item);
if (node2d && se->pre_drag_bones_undo_state.size() > 0 && !force_no_IK) {
real_t initial_leaf_node_rotation = node2d->get_global_transform_with_canvas().get_rotation();
_restore_canvas_item_ik_chain(node2d, &(all_bones_ik_states[index]));
real_t final_leaf_node_rotation = node2d->get_global_transform_with_canvas().get_rotation();
node2d->rotate(initial_leaf_node_rotation - final_leaf_node_rotation);
_solve_IK(node2d, new_pos);
} else {
canvas_item->_edit_set_position(canvas_item->_edit_get_position() + xform.xform(new_pos) - xform.xform(previous_pos));
}
}
canvas_item->_edit_set_position(canvas_item->_edit_get_position() + xform.xform(new_pos) - xform.xform(previous_pos));
index++;
}
return true;
@ -2325,14 +2087,6 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) {
}
if (drag_selection.size() > 0) {
// Save the ik chain for reapplying before IK solve
Vector<List<Dictionary>> all_bones_ik_states;
for (List<CanvasItem *>::Element *E = drag_selection.front(); E; E = E->next()) {
List<Dictionary> bones_ik_states;
_save_canvas_item_ik_chain(E->get(), nullptr, &bones_ik_states);
all_bones_ik_states.push_back(bones_ik_states);
}
_restore_canvas_item_state(drag_selection, true);
bool move_local_base = k->is_alt_pressed();
@ -2384,21 +2138,9 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) {
int index = 0;
for (List<CanvasItem *>::Element *E = drag_selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get();
CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (se) {
Transform2D xform = canvas_item->get_global_transform_with_canvas().affine_inverse() * canvas_item->get_transform();
Transform2D xform = canvas_item->get_global_transform_with_canvas().affine_inverse() * canvas_item->get_transform();
Node2D *node2d = Object::cast_to<Node2D>(canvas_item);
if (node2d && se->pre_drag_bones_undo_state.size() > 0) {
real_t initial_leaf_node_rotation = node2d->get_global_transform_with_canvas().get_rotation();
_restore_canvas_item_ik_chain(node2d, &(all_bones_ik_states[index]));
real_t final_leaf_node_rotation = node2d->get_global_transform_with_canvas().get_rotation();
node2d->rotate(initial_leaf_node_rotation - final_leaf_node_rotation);
_solve_IK(node2d, new_pos);
} else {
canvas_item->_edit_set_position(canvas_item->_edit_get_position() + xform.xform(new_pos) - xform.xform(previous_pos));
}
}
canvas_item->_edit_set_position(canvas_item->_edit_get_position() + xform.xform(new_pos) - xform.xform(previous_pos));
index++;
}
}
@ -2524,18 +2266,12 @@ bool CanvasItemEditor::_gui_input_select(const Ref<InputEvent> &p_event) {
// Find the item to select
CanvasItem *canvas_item = nullptr;
// Retrieve the bones
Vector<_SelectResult> selection = Vector<_SelectResult>();
_get_bones_at_pos(click, selection);
// Retrieve the canvas items
selection = Vector<_SelectResult>();
_get_canvas_items_at_pos(click, selection);
if (!selection.is_empty()) {
canvas_item = selection[0].item;
} else {
// Retrieve the canvas items
selection = Vector<_SelectResult>();
_get_canvas_items_at_pos(click, selection);
if (!selection.is_empty()) {
canvas_item = selection[0].item;
}
}
if (!canvas_item) {
@ -3734,65 +3470,6 @@ void CanvasItemEditor::_draw_axis() {
}
}
void CanvasItemEditor::_draw_bones() {
RID ci = viewport->get_canvas_item();
if (skeleton_show_bones) {
Color bone_color1 = EditorSettings::get_singleton()->get("editors/2d/bone_color1");
Color bone_color2 = EditorSettings::get_singleton()->get("editors/2d/bone_color2");
Color bone_ik_color = EditorSettings::get_singleton()->get("editors/2d/bone_ik_color");
Color bone_outline_color = EditorSettings::get_singleton()->get("editors/2d/bone_outline_color");
Color bone_selected_color = EditorSettings::get_singleton()->get("editors/2d/bone_selected_color");
for (Map<BoneKey, BoneList>::Element *E = bone_list.front(); E; E = E->next()) {
Vector<Vector2> bone_shape;
Vector<Vector2> bone_shape_outline;
if (!_get_bone_shape(&bone_shape, &bone_shape_outline, E)) {
continue;
}
Node2D *from_node = Object::cast_to<Node2D>(ObjectDB::get_instance(E->key().from));
if (!from_node->is_visible_in_tree()) {
continue;
}
Vector<Color> colors;
if (from_node->has_meta("_edit_ik_")) {
colors.push_back(bone_ik_color);
colors.push_back(bone_ik_color);
colors.push_back(bone_ik_color);
colors.push_back(bone_ik_color);
} else {
colors.push_back(bone_color1);
colors.push_back(bone_color2);
colors.push_back(bone_color1);
colors.push_back(bone_color2);
}
Vector<Color> outline_colors;
if (editor_selection->is_selected(from_node)) {
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
} else {
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
}
RenderingServer::get_singleton()->canvas_item_add_polygon(ci, bone_shape_outline, outline_colors);
RenderingServer::get_singleton()->canvas_item_add_primitive(ci, bone_shape, colors, Vector<Vector2>(), RID());
}
}
}
void CanvasItemEditor::_draw_invisible_nodes_positions(Node *p_node, const Transform2D &p_parent_xform, const Transform2D &p_canvas_xform) {
ERR_FAIL_COND(!p_node);
@ -3908,72 +3585,6 @@ void CanvasItemEditor::_draw_locks_and_groups(Node *p_node, const Transform2D &p
}
}
bool CanvasItemEditor::_build_bones_list(Node *p_node) {
ERR_FAIL_COND_V(!p_node, false);
bool has_child_bones = false;
for (int i = 0; i < p_node->get_child_count(); i++) {
if (_build_bones_list(p_node->get_child(i))) {
has_child_bones = true;
}
}
CanvasItem *canvas_item = Object::cast_to<CanvasItem>(p_node);
Node *scene = editor->get_edited_scene();
if (!canvas_item || !canvas_item->is_visible() || (canvas_item != scene && canvas_item->get_owner() != scene && canvas_item != scene->get_deepest_editable_node(canvas_item))) {
return false;
}
Node *parent = canvas_item->get_parent();
if (Object::cast_to<Bone2D>(canvas_item)) {
if (Object::cast_to<Bone2D>(parent)) {
// Add as bone->parent relationship
BoneKey bk;
bk.from = parent->get_instance_id();
bk.to = canvas_item->get_instance_id();
if (!bone_list.has(bk)) {
BoneList b;
b.length = 0;
bone_list[bk] = b;
}
bone_list[bk].last_pass = bone_last_frame;
}
if (!has_child_bones) {
// Add a last bone if the Bone2D has no Bone2D child
BoneKey bk;
bk.from = canvas_item->get_instance_id();
bk.to = ObjectID();
if (!bone_list.has(bk)) {
BoneList b;
b.length = 0;
bone_list[bk] = b;
}
bone_list[bk].last_pass = bone_last_frame;
}
return true;
}
if (canvas_item->has_meta("_edit_bone_")) {
// Add a "custom bone"
BoneKey bk;
bk.from = parent->get_instance_id();
bk.to = canvas_item->get_instance_id();
if (!bone_list.has(bk)) {
BoneList b;
b.length = 0;
bone_list[bk] = b;
}
bone_list[bk].last_pass = bone_last_frame;
}
return false;
}
void CanvasItemEditor::_draw_viewport() {
// Update the transform
transform = Transform2D();
@ -4033,7 +3644,6 @@ void CanvasItemEditor::_draw_viewport() {
force_over_plugin_list->forward_canvas_force_draw_over_viewport(viewport);
}
_draw_bones();
if (show_rulers) {
_draw_rulers();
}
@ -4159,8 +3769,8 @@ void CanvasItemEditor::_notification(int p_what) {
}
Bone2D *bone = Object::cast_to<Bone2D>(b);
if (bone && bone->get_default_length() != E->get().length) {
E->get().length = bone->get_default_length();
if (bone && bone->get_length() != E->get().length) {
E->get().length = bone->get_length();
viewport->update();
}
}
@ -4175,18 +3785,11 @@ void CanvasItemEditor::_notification(int p_what) {
AnimationPlayerEditor::singleton->get_track_editor()->connect("visibility_changed", callable_mp(this, &CanvasItemEditor::_keying_changed));
_keying_changed();
get_tree()->connect("node_added", callable_mp(this, &CanvasItemEditor::_tree_changed), varray());
get_tree()->connect("node_removed", callable_mp(this, &CanvasItemEditor::_tree_changed), varray());
} else if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
select_sb->set_texture(get_theme_icon("EditorRect2D", "EditorIcons"));
}
if (p_what == NOTIFICATION_EXIT_TREE) {
get_tree()->disconnect("node_added", callable_mp(this, &CanvasItemEditor::_tree_changed));
get_tree()->disconnect("node_removed", callable_mp(this, &CanvasItemEditor::_tree_changed));
}
if (p_what == NOTIFICATION_ENTER_TREE || p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
select_button->set_icon(get_theme_icon("ToolSelect", "EditorIcons"));
list_select_button->set_icon(get_theme_icon("ListSelect", "EditorIcons"));
@ -4321,46 +3924,6 @@ void CanvasItemEditor::edit(CanvasItem *p_canvas_item) {
}
}
void CanvasItemEditor::_queue_update_bone_list() {
if (bone_list_dirty) {
return;
}
call_deferred("_update_bone_list");
bone_list_dirty = true;
}
void CanvasItemEditor::_update_bone_list() {
bone_last_frame++;
if (editor->get_edited_scene()) {
_build_bones_list(editor->get_edited_scene());
}
List<Map<BoneKey, BoneList>::Element *> bone_to_erase;
for (Map<BoneKey, BoneList>::Element *E = bone_list.front(); E; E = E->next()) {
if (E->get().last_pass != bone_last_frame) {
bone_to_erase.push_back(E);
continue;
}
Node *node = Object::cast_to<Node>(ObjectDB::get_instance(E->key().from));
if (!node || !node->is_inside_tree() || (node != get_tree()->get_edited_scene_root() && !get_tree()->get_edited_scene_root()->is_a_parent_of(node))) {
bone_to_erase.push_back(E);
continue;
}
}
while (bone_to_erase.size()) {
bone_list.erase(bone_to_erase.front()->get());
bone_to_erase.pop_front();
}
bone_list_dirty = false;
}
void CanvasItemEditor::_tree_changed(Node *) {
_queue_update_bone_list();
}
void CanvasItemEditor::_update_scrollbars() {
updating_scroll = true;
@ -4376,8 +3939,6 @@ void CanvasItemEditor::_update_scrollbars() {
Size2 screen_rect = Size2(ProjectSettings::get_singleton()->get("display/window/size/width"), ProjectSettings::get_singleton()->get("display/window/size/height"));
Rect2 local_rect = Rect2(Point2(), viewport->get_size() - Size2(vmin.width, hmin.height));
_queue_update_bone_list();
// Calculate scrollable area.
Rect2 canvas_item_rect = Rect2(Point2(), screen_rect);
if (editor->is_inside_tree() && editor->get_edited_scene()) {
@ -4837,10 +4398,19 @@ void CanvasItemEditor::_popup_callback(int p_op) {
snap_dialog->popup_centered(Size2(220, 160) * EDSCALE);
} break;
case SKELETON_SHOW_BONES: {
skeleton_show_bones = !skeleton_show_bones;
int idx = skeleton_menu->get_popup()->get_item_index(SKELETON_SHOW_BONES);
skeleton_menu->get_popup()->set_item_checked(idx, skeleton_show_bones);
viewport->update();
List<Node *> selection = editor_selection->get_selected_node_list();
for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
// Add children nodes so they are processed
for (int child = 0; child < E->get()->get_child_count(); child++) {
selection.push_back(E->get()->get_child(child));
}
Bone2D *bone_2d = Object::cast_to<Bone2D>(E->get());
if (!bone_2d || !bone_2d->is_inside_tree()) {
continue;
}
bone_2d->_editor_set_show_bone_gizmo(!bone_2d->_editor_get_show_bone_gizmo());
}
} break;
case SHOW_HELPERS: {
show_helpers = !show_helpers;
@ -5189,107 +4759,45 @@ void CanvasItemEditor::_popup_callback(int p_op) {
} break;
case SKELETON_MAKE_BONES: {
Map<Node *, Object *> &selection = editor_selection->get_selection();
Node *editor_root = EditorNode::get_singleton()->get_edited_scene()->get_tree()->get_edited_scene_root();
undo_redo->create_action(TTR("Create Custom Bone(s) from Node(s)"));
undo_redo->create_action(TTR("Create Custom Bone2D(s) from Node(s)"));
for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
Node2D *n2d = Object::cast_to<Node2D>(E->key());
if (!n2d) {
continue;
}
if (!n2d->is_visible_in_tree()) {
continue;
}
if (!n2d->get_parent_item()) {
continue;
}
if (n2d->has_meta("_edit_bone_") && n2d->get_meta("_edit_bone_")) {
Bone2D *new_bone = memnew(Bone2D);
String new_bone_name = n2d->get_name();
new_bone_name += "Bone2D";
new_bone->set_name(new_bone_name);
new_bone->set_transform(n2d->get_transform());
Node *n2d_parent = n2d->get_parent();
if (!n2d_parent) {
continue;
}
undo_redo->add_do_method(n2d, "set_meta", "_edit_bone_", true);
undo_redo->add_undo_method(n2d, "remove_meta", "_edit_bone_");
undo_redo->add_do_method(n2d_parent, "add_child", new_bone);
undo_redo->add_do_method(n2d_parent, "remove_child", n2d);
undo_redo->add_do_method(new_bone, "add_child", n2d);
undo_redo->add_do_method(n2d, "set_transform", Transform2D());
undo_redo->add_do_method(this, "_set_owner_for_node_and_children", new_bone, editor_root);
undo_redo->add_undo_method(new_bone, "remove_child", n2d);
undo_redo->add_undo_method(n2d_parent, "add_child", n2d);
undo_redo->add_undo_method(n2d, "set_transform", new_bone->get_transform());
undo_redo->add_undo_method(new_bone, "queue_free");
undo_redo->add_undo_method(this, "_set_owner_for_node_and_children", n2d, editor_root);
}
undo_redo->add_do_method(this, "_queue_update_bone_list");
undo_redo->add_undo_method(this, "_queue_update_bone_list");
undo_redo->add_do_method(viewport, "update");
undo_redo->add_undo_method(viewport, "update");
undo_redo->commit_action();
} break;
case SKELETON_CLEAR_BONES: {
Map<Node *, Object *> &selection = editor_selection->get_selection();
}
}
undo_redo->create_action(TTR("Clear Bones"));
for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
Node2D *n2d = Object::cast_to<Node2D>(E->key());
if (!n2d) {
continue;
}
if (!n2d->is_visible_in_tree()) {
continue;
}
if (!n2d->has_meta("_edit_bone_")) {
continue;
}
undo_redo->add_do_method(n2d, "remove_meta", "_edit_bone_");
undo_redo->add_undo_method(n2d, "set_meta", "_edit_bone_", n2d->get_meta("_edit_bone_"));
}
undo_redo->add_do_method(this, "_queue_update_bone_list");
undo_redo->add_undo_method(this, "_queue_update_bone_list");
undo_redo->add_do_method(viewport, "update");
undo_redo->add_undo_method(viewport, "update");
undo_redo->commit_action();
} break;
case SKELETON_SET_IK_CHAIN: {
List<Node *> selection = editor_selection->get_selected_node_list();
undo_redo->create_action(TTR("Make IK Chain"));
for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = Object::cast_to<CanvasItem>(E->get());
if (!canvas_item || !canvas_item->is_visible_in_tree()) {
continue;
}
if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
continue;
}
if (canvas_item->has_meta("_edit_ik_") && canvas_item->get_meta("_edit_ik_")) {
continue;
}
undo_redo->add_do_method(canvas_item, "set_meta", "_edit_ik_", true);
undo_redo->add_undo_method(canvas_item, "remove_meta", "_edit_ik_");
}
undo_redo->add_do_method(viewport, "update");
undo_redo->add_undo_method(viewport, "update");
undo_redo->commit_action();
} break;
case SKELETON_CLEAR_IK_CHAIN: {
Map<Node *, Object *> &selection = editor_selection->get_selection();
undo_redo->create_action(TTR("Clear IK Chain"));
for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *n2d = Object::cast_to<CanvasItem>(E->key());
if (!n2d) {
continue;
}
if (!n2d->is_visible_in_tree()) {
continue;
}
if (!n2d->has_meta("_edit_ik_")) {
continue;
}
undo_redo->add_do_method(n2d, "remove_meta", "_edit_ik_");
undo_redo->add_undo_method(n2d, "set_meta", "_edit_ik_", n2d->get_meta("_edit_ik_"));
}
undo_redo->add_do_method(viewport, "update");
undo_redo->add_undo_method(viewport, "update");
undo_redo->commit_action();
} break;
void CanvasItemEditor::_set_owner_for_node_and_children(Node *p_node, Node *p_owner) {
p_node->set_owner(p_owner);
for (int i = 0; i < p_node->get_child_count(); i++) {
_set_owner_for_node_and_children(p_node->get_child(i), p_owner);
}
}
@ -5358,14 +4866,12 @@ void CanvasItemEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_update_override_camera_button", "game_running"), &CanvasItemEditor::_update_override_camera_button);
ClassDB::bind_method("_get_editor_data", &CanvasItemEditor::_get_editor_data);
ClassDB::bind_method("_unhandled_key_input", &CanvasItemEditor::_unhandled_key_input);
ClassDB::bind_method("_queue_update_bone_list", &CanvasItemEditor::_update_bone_list);
ClassDB::bind_method("_update_bone_list", &CanvasItemEditor::_update_bone_list);
ClassDB::bind_method("_reset_create_position", &CanvasItemEditor::_reset_create_position);
ClassDB::bind_method(D_METHOD("get_state"), &CanvasItemEditor::get_state);
ClassDB::bind_method(D_METHOD("set_state"), &CanvasItemEditor::set_state);
ClassDB::bind_method(D_METHOD("update_viewport"), &CanvasItemEditor::update_viewport);
ClassDB::bind_method(D_METHOD("_zoom_on_position"), &CanvasItemEditor::_zoom_on_position);
ClassDB::bind_method("_set_owner_for_node_and_children", &CanvasItemEditor::_set_owner_for_node_and_children);
ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
ADD_SIGNAL(MethodInfo("item_group_status_changed"));
}
@ -5402,7 +4908,6 @@ Dictionary CanvasItemEditor::get_state() const {
state["snap_scale"] = snap_scale;
state["snap_relative"] = snap_relative;
state["snap_pixel"] = snap_pixel;
state["skeleton_show_bones"] = skeleton_show_bones;
return state;
}
@ -5570,12 +5075,6 @@ void CanvasItemEditor::set_state(const Dictionary &p_state) {
snap_config_menu->get_popup()->set_item_checked(idx, snap_pixel);
}
if (state.has("skeleton_show_bones")) {
skeleton_show_bones = state["skeleton_show_bones"];
int idx = skeleton_menu->get_popup()->get_item_index(SKELETON_SHOW_BONES);
skeleton_menu->get_popup()->set_item_checked(idx, skeleton_show_bones);
}
if (update_scrollbars) {
_update_scrollbars();
}
@ -5658,8 +5157,6 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
selected_from_canvas = false;
anchors_mode = false;
skeleton_show_bones = true;
drag_type = DRAG_NONE;
drag_from = Vector2();
drag_to = Vector2();
@ -5675,7 +5172,6 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
bone_last_frame = 0;
bone_list_dirty = false;
tool = TOOL_SELECT;
undo_redo = p_editor->get_undo_redo();
editor = p_editor;
@ -5940,13 +5436,9 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
p = skeleton_menu->get_popup();
p->set_hide_on_checkable_item_selection(false);
p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_show_bones", TTR("Show Bones")), SKELETON_SHOW_BONES);
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_show_bones", TTR("Show Bones")), SKELETON_SHOW_BONES);
p->add_separator();
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_set_ik_chain", TTR("Make IK Chain")), SKELETON_SET_IK_CHAIN);
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_clear_ik_chain", TTR("Clear IK Chain")), SKELETON_CLEAR_IK_CHAIN);
p->add_separator();
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_make_bones", TTR("Make Custom Bone(s) from Node(s)"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_B), SKELETON_MAKE_BONES);
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_clear_bones", TTR("Clear Custom Bones")), SKELETON_CLEAR_BONES);
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_make_bones", TTR("Make Bone2D Node(s) from Node(s)"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_B), SKELETON_MAKE_BONES);
p->connect("id_pressed", callable_mp(this, &CanvasItemEditor::_popup_callback));
hb->add_child(memnew(VSeparator));

View file

@ -187,10 +187,7 @@ private:
VIEW_FRAME_TO_SELECTION,
PREVIEW_CANVAS_SCALE,
SKELETON_MAKE_BONES,
SKELETON_CLEAR_BONES,
SKELETON_SHOW_BONES,
SKELETON_SET_IK_CHAIN,
SKELETON_CLEAR_IK_CHAIN
SKELETON_SHOW_BONES
};
enum DragType {
@ -223,7 +220,6 @@ private:
DRAG_KEY_MOVE
};
EditorSelection *editor_selection;
bool selection_menu_additive_selection;
Tool tool;
@ -277,7 +273,6 @@ private:
bool snap_scale;
bool snap_relative;
bool snap_pixel;
bool skeleton_show_bones;
bool key_pos;
bool key_rot;
bool key_scale;
@ -412,7 +407,6 @@ private:
bool _is_node_movable(const Node *p_node, bool p_popup_warning = false);
void _find_canvas_items_at_pos(const Point2 &p_pos, Node *p_node, Vector<_SelectResult> &r_items, const Transform2D &p_parent_xform = Transform2D(), const Transform2D &p_canvas_xform = Transform2D());
void _get_canvas_items_at_pos(const Point2 &p_pos, Vector<_SelectResult> &r_items, bool p_allow_locked = false);
void _get_bones_at_pos(const Point2 &p_pos, Vector<_SelectResult> &r_items);
void _find_canvas_items_in_rect(const Rect2 &p_rect, Node *p_node, List<CanvasItem *> *r_items, const Transform2D &p_parent_xform = Transform2D(), const Transform2D &p_canvas_xform = Transform2D());
bool _select_click_on_item(CanvasItem *item, Point2 p_click_pos, bool p_append);
@ -423,9 +417,7 @@ private:
void _add_canvas_item(CanvasItem *p_canvas_item);
void _save_canvas_item_ik_chain(const CanvasItem *p_canvas_item, List<float> *p_bones_length, List<Dictionary> *p_bones_state);
void _save_canvas_item_state(List<CanvasItem *> p_canvas_items, bool save_bones = false);
void _restore_canvas_item_ik_chain(CanvasItem *p_canvas_item, const List<Dictionary> *p_bones_state);
void _restore_canvas_item_state(List<CanvasItem *> p_canvas_items, bool restore_bones = false);
void _commit_canvas_item_state(List<CanvasItem *> p_canvas_items, String action_name, bool commit_bones = false);
@ -445,8 +437,6 @@ private:
void _reset_create_position();
UndoRedo *undo_redo;
bool _build_bones_list(Node *p_node);
bool _get_bone_shape(Vector<Vector2> *shape, Vector<Vector2> *outline_shape, Map<BoneKey, BoneList>::Element *bone);
List<CanvasItem *> _get_edited_canvas_items(bool retreive_locked = false, bool remove_canvas_item_if_parent_in_selection = true);
Rect2 _get_encompassing_rect_from_list(List<CanvasItem *> p_list);
@ -476,7 +466,6 @@ private:
void _draw_control_helpers(Control *control);
void _draw_selection();
void _draw_axis();
void _draw_bones();
void _draw_invisible_nodes_positions(Node *p_node, const Transform2D &p_parent_xform = Transform2D(), const Transform2D &p_canvas_xform = Transform2D());
void _draw_locks_and_groups(Node *p_node, const Transform2D &p_parent_xform = Transform2D(), const Transform2D &p_canvas_xform = Transform2D());
void _draw_hover();
@ -503,8 +492,6 @@ private:
void _focus_selection(int p_op);
void _solve_IK(Node2D *leaf_node, Point2 target_position);
SnapTarget snap_target[2];
Transform2D snap_transform;
void _snap_if_closer_float(
@ -546,14 +533,11 @@ private:
HSplitContainer *palette_split;
VSplitContainer *bottom_split;
bool bone_list_dirty;
void _queue_update_bone_list();
void _update_bone_list();
void _tree_changed(Node *);
void _popup_warning_temporarily(Control *p_control, const float p_duration);
void _popup_warning_depop(Control *p_control);
void _set_owner_for_node_and_children(Node *p_node, Node *p_owner);
friend class CanvasItemEditorPlugin;
protected:
@ -641,6 +625,8 @@ public:
bool is_anchors_mode_enabled() { return anchors_mode; };
EditorSelection *editor_selection;
CanvasItemEditor(EditorNode *p_editor);
};

View file

@ -1144,7 +1144,7 @@ void Polygon2DEditor::_uv_draw() {
if (!found_child) {
//draw normally
Transform2D bone_xform = node->get_global_transform().affine_inverse() * (skeleton->get_global_transform() * bone->get_skeleton_rest());
Transform2D endpoint_xform = bone_xform * Transform2D(0, Vector2(bone->get_default_length(), 0));
Transform2D endpoint_xform = bone_xform * Transform2D(0, Vector2(bone->get_length(), 0));
Color color = current ? Color(1, 1, 1) : Color(0.5, 0.5, 0.5);
uv_edit_draw->draw_line(mtx.xform(bone_xform.get_origin()), mtx.xform(endpoint_xform.get_origin()), Color(0, 0, 0), Math::round((current ? 5 : 4) * EDSCALE));

View file

@ -0,0 +1,303 @@
/*************************************************************************/
/* physical_bone_2d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "physical_bone_2d.h"
void PhysicalBone2D::_notification(int p_what) {
if (p_what == NOTIFICATION_INTERNAL_PHYSICS_PROCESS) {
// Position the RigidBody in the correct position
if (follow_bone_when_simulating) {
_position_at_bone2d();
}
// Keep the child joint in the correct position.
if (child_joint && auto_configure_joint) {
child_joint->set_global_position(get_global_position());
}
} else if (p_what == NOTIFICATION_READY) {
_find_skeleton_parent();
_find_joint_child();
// Configure joint
if (child_joint && auto_configure_joint) {
_auto_configure_joint();
}
// Simulate physics if set
if (simulate_physics) {
_start_physics_simulation();
} else {
_stop_physics_simulation();
}
set_physics_process_internal(true);
}
}
void PhysicalBone2D::_position_at_bone2d() {
// Reset to Bone2D position
if (parent_skeleton) {
Bone2D *bone_to_use = parent_skeleton->get_bone(bone2d_index);
ERR_FAIL_COND_MSG(bone_to_use == nullptr, "It's not possible to position the bone with ID: " + itos(bone2d_index));
set_global_transform(bone_to_use->get_global_transform());
}
}
void PhysicalBone2D::_find_skeleton_parent() {
Node *current_parent = get_parent();
while (current_parent != nullptr) {
Skeleton2D *potential_skeleton = Object::cast_to<Skeleton2D>(current_parent);
if (potential_skeleton) {
parent_skeleton = potential_skeleton;
break;
} else {
PhysicalBone2D *potential_parent_bone = Object::cast_to<PhysicalBone2D>(current_parent);
if (potential_parent_bone) {
current_parent = potential_parent_bone->get_parent();
} else {
current_parent = nullptr;
}
}
}
}
void PhysicalBone2D::_find_joint_child() {
for (int i = 0; i < get_child_count(); i++) {
Node *child_node = get_child(i);
Joint2D *potential_joint = Object::cast_to<Joint2D>(child_node);
if (potential_joint) {
child_joint = potential_joint;
break;
}
}
}
TypedArray<String> PhysicalBone2D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (!parent_skeleton) {
warnings.push_back(TTR("A PhysicalBone2D only works with a Skeleton2D or another PhysicalBone2D as a parent node!"));
}
if (parent_skeleton && bone2d_index <= -1) {
warnings.push_back(TTR("A PhysicalBone2D needs to be assigned to a Bone2D node in order to function! Please set a Bone2D node in the inspector."));
}
if (!child_joint) {
PhysicalBone2D *parent_bone = Object::cast_to<PhysicalBone2D>(get_parent());
if (parent_bone) {
warnings.push_back(TTR("A PhysicalBone2D node should have a Joint2D-based child node to keep bones connected! Please add a Joint2D-based node as a child to this node!"));
}
}
return warnings;
}
void PhysicalBone2D::_auto_configure_joint() {
if (!auto_configure_joint) {
return;
}
if (child_joint) {
// Node A = parent | Node B = this node
Node *parent_node = get_parent();
PhysicalBone2D *potential_parent_bone = Object::cast_to<PhysicalBone2D>(parent_node);
if (potential_parent_bone) {
child_joint->set_node_a(child_joint->get_path_to(potential_parent_bone));
child_joint->set_node_b(child_joint->get_path_to(this));
} else {
WARN_PRINT("Cannot setup joint without a parent PhysicalBone2D node.");
}
// Place the child joint at this node's position.
child_joint->set_global_position(get_global_position());
}
}
void PhysicalBone2D::_start_physics_simulation() {
if (_internal_simulate_physics) {
return;
}
// Reset to Bone2D position
_position_at_bone2d();
// Apply the layers and masks
PhysicsServer2D::get_singleton()->body_set_collision_layer(get_rid(), get_collision_layer());
PhysicsServer2D::get_singleton()->body_set_collision_mask(get_rid(), get_collision_mask());
// Apply the correct mode
RigidBody2D::Mode rigid_mode = get_mode();
if (rigid_mode == RigidBody2D::MODE_STATIC) {
PhysicsServer2D::get_singleton()->body_set_mode(get_rid(), PhysicsServer2D::BodyMode::BODY_MODE_STATIC);
} else if (rigid_mode == RigidBody2D::MODE_DYNAMIC) {
PhysicsServer2D::get_singleton()->body_set_mode(get_rid(), PhysicsServer2D::BodyMode::BODY_MODE_DYNAMIC);
} else if (rigid_mode == RigidBody2D::MODE_KINEMATIC) {
PhysicsServer2D::get_singleton()->body_set_mode(get_rid(), PhysicsServer2D::BodyMode::BODY_MODE_KINEMATIC);
} else if (rigid_mode == RigidBody2D::MODE_DYNAMIC_LOCKED) {
PhysicsServer2D::get_singleton()->body_set_mode(get_rid(), PhysicsServer2D::BodyMode::BODY_MODE_DYNAMIC_LOCKED);
} else {
// Default to Rigid
PhysicsServer2D::get_singleton()->body_set_mode(get_rid(), PhysicsServer2D::BodyMode::BODY_MODE_DYNAMIC);
}
_internal_simulate_physics = true;
set_physics_process_internal(true);
}
void PhysicalBone2D::_stop_physics_simulation() {
if (_internal_simulate_physics) {
_internal_simulate_physics = false;
// Reset to Bone2D position
_position_at_bone2d();
set_physics_process_internal(false);
PhysicsServer2D::get_singleton()->body_set_collision_layer(get_rid(), 0);
PhysicsServer2D::get_singleton()->body_set_collision_mask(get_rid(), 0);
PhysicsServer2D::get_singleton()->body_set_mode(get_rid(), PhysicsServer2D::BodyMode::BODY_MODE_STATIC);
}
}
Joint2D *PhysicalBone2D::get_joint() const {
return child_joint;
}
bool PhysicalBone2D::get_auto_configure_joint() const {
return auto_configure_joint;
}
void PhysicalBone2D::set_auto_configure_joint(bool p_auto_configure) {
auto_configure_joint = p_auto_configure;
_auto_configure_joint();
}
void PhysicalBone2D::set_simulate_physics(bool p_simulate) {
if (p_simulate == simulate_physics) {
return;
}
simulate_physics = p_simulate;
if (simulate_physics) {
_start_physics_simulation();
} else {
_stop_physics_simulation();
}
}
bool PhysicalBone2D::get_simulate_physics() const {
return simulate_physics;
}
bool PhysicalBone2D::is_simulating_physics() const {
return _internal_simulate_physics;
}
void PhysicalBone2D::set_bone2d_nodepath(const NodePath &p_nodepath) {
bone2d_nodepath = p_nodepath;
notify_property_list_changed();
}
NodePath PhysicalBone2D::get_bone2d_nodepath() const {
return bone2d_nodepath;
}
void PhysicalBone2D::set_bone2d_index(int p_bone_idx) {
ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
if (!is_inside_tree()) {
bone2d_index = p_bone_idx;
return;
}
if (parent_skeleton) {
ERR_FAIL_INDEX_MSG(p_bone_idx, parent_skeleton->get_bone_count(), "Passed-in Bone index is out of range!");
bone2d_index = p_bone_idx;
bone2d_nodepath = get_path_to(parent_skeleton->get_bone(bone2d_index));
} else {
WARN_PRINT("Cannot verify bone index...");
bone2d_index = p_bone_idx;
}
notify_property_list_changed();
}
int PhysicalBone2D::get_bone2d_index() const {
return bone2d_index;
}
void PhysicalBone2D::set_follow_bone_when_simulating(bool p_follow_bone) {
follow_bone_when_simulating = p_follow_bone;
if (_internal_simulate_physics) {
_stop_physics_simulation();
_start_physics_simulation();
}
}
bool PhysicalBone2D::get_follow_bone_when_simulating() const {
return follow_bone_when_simulating;
}
void PhysicalBone2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_joint"), &PhysicalBone2D::get_joint);
ClassDB::bind_method(D_METHOD("get_auto_configure_joint"), &PhysicalBone2D::get_auto_configure_joint);
ClassDB::bind_method(D_METHOD("set_auto_configure_joint", "auto_configure_joint"), &PhysicalBone2D::set_auto_configure_joint);
ClassDB::bind_method(D_METHOD("set_simulate_physics", "simulate_physics"), &PhysicalBone2D::set_simulate_physics);
ClassDB::bind_method(D_METHOD("get_simulate_physics"), &PhysicalBone2D::get_simulate_physics);
ClassDB::bind_method(D_METHOD("is_simulating_physics"), &PhysicalBone2D::is_simulating_physics);
ClassDB::bind_method(D_METHOD("set_bone2d_nodepath", "nodepath"), &PhysicalBone2D::set_bone2d_nodepath);
ClassDB::bind_method(D_METHOD("get_bone2d_nodepath"), &PhysicalBone2D::get_bone2d_nodepath);
ClassDB::bind_method(D_METHOD("set_bone2d_index", "bone_index"), &PhysicalBone2D::set_bone2d_index);
ClassDB::bind_method(D_METHOD("get_bone2d_index"), &PhysicalBone2D::get_bone2d_index);
ClassDB::bind_method(D_METHOD("set_follow_bone_when_simulating", "follow_bone"), &PhysicalBone2D::set_follow_bone_when_simulating);
ClassDB::bind_method(D_METHOD("get_follow_bone_when_simulating"), &PhysicalBone2D::get_follow_bone_when_simulating);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "bone2d_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Bone2D"), "set_bone2d_nodepath", "get_bone2d_nodepath");
ADD_PROPERTY(PropertyInfo(Variant::INT, "bone2d_index", PROPERTY_HINT_RANGE, "-1, 1000, 1"), "set_bone2d_index", "get_bone2d_index");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "auto_configure_joint"), "set_auto_configure_joint", "get_auto_configure_joint");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "simulate_physics"), "set_simulate_physics", "get_simulate_physics");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "follow_bone_when_simulating"), "set_follow_bone_when_simulating", "get_follow_bone_when_simulating");
}
PhysicalBone2D::PhysicalBone2D() {
// Stop the RigidBody from executing its force integration.
PhysicsServer2D::get_singleton()->body_set_collision_layer(get_rid(), 0);
PhysicsServer2D::get_singleton()->body_set_collision_mask(get_rid(), 0);
PhysicsServer2D::get_singleton()->body_set_mode(get_rid(), PhysicsServer2D::BodyMode::BODY_MODE_STATIC);
child_joint = nullptr;
}
PhysicalBone2D::~PhysicalBone2D() {
}

View file

@ -0,0 +1,88 @@
/*************************************************************************/
/* physical_bone_2d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef PHYSICAL_BONE_2D_H
#define PHYSICAL_BONE_2D_H
#include "scene/2d/joints_2d.h"
#include "scene/2d/physics_body_2d.h"
#include "scene/2d/skeleton_2d.h"
class PhysicalBone2D : public RigidBody2D {
GDCLASS(PhysicalBone2D, RigidBody2D);
protected:
void _notification(int p_what);
static void _bind_methods();
private:
Skeleton2D *parent_skeleton;
int bone2d_index = -1;
NodePath bone2d_nodepath;
bool follow_bone_when_simulating = false;
Joint2D *child_joint;
bool auto_configure_joint = true;
bool simulate_physics = false;
bool _internal_simulate_physics = false;
void _find_skeleton_parent();
void _find_joint_child();
void _auto_configure_joint();
void _start_physics_simulation();
void _stop_physics_simulation();
void _position_at_bone2d();
public:
Joint2D *get_joint() const;
bool get_auto_configure_joint() const;
void set_auto_configure_joint(bool p_auto_configure);
void set_simulate_physics(bool p_simulate);
bool get_simulate_physics() const;
bool is_simulating_physics() const;
void set_bone2d_nodepath(const NodePath &p_nodepath);
NodePath get_bone2d_nodepath() const;
void set_bone2d_index(int p_bone_idx);
int get_bone2d_index() const;
void set_follow_bone_when_simulating(bool p_follow);
bool get_follow_bone_when_simulating() const;
TypedArray<String> get_configuration_warnings() const override;
PhysicalBone2D();
~PhysicalBone2D();
};
#endif // PHYSICAL_BONE_2D_H

View file

@ -30,6 +30,69 @@
#include "skeleton_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_settings.h"
#include "editor/plugins/canvas_item_editor_plugin.h"
#endif //TOOLS_ENABLED
bool Bone2D::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (path.begins_with("auto_calculate_length_and_angle")) {
set_autocalculate_length_and_angle(p_value);
} else if (path.begins_with("length")) {
set_length(p_value);
} else if (path.begins_with("bone_angle")) {
set_bone_angle(Math::deg2rad(float(p_value)));
} else if (path.begins_with("default_length")) {
set_length(p_value);
}
#ifdef TOOLS_ENABLED
if (path.begins_with("editor_settings/show_bone_gizmo")) {
_editor_set_show_bone_gizmo(p_value);
}
#endif // TOOLS_ENABLED
return true;
}
bool Bone2D::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
if (path.begins_with("auto_calculate_length_and_angle")) {
r_ret = get_autocalculate_length_and_angle();
} else if (path.begins_with("length")) {
r_ret = get_length();
} else if (path.begins_with("bone_angle")) {
r_ret = Math::rad2deg(get_bone_angle());
} else if (path.begins_with("default_length")) {
r_ret = get_length();
}
#ifdef TOOLS_ENABLED
if (path.begins_with("editor_settings/show_bone_gizmo")) {
r_ret = _editor_get_show_bone_gizmo();
}
#endif // TOOLS_ENABLED
return true;
}
void Bone2D::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::BOOL, "auto_calculate_length_and_angle", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
if (!autocalculate_length_and_angle) {
p_list->push_back(PropertyInfo(Variant::FLOAT, "length", PROPERTY_HINT_RANGE, "1, 1024, 1", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::FLOAT, "bone_angle", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT));
}
#ifdef TOOLS_ENABLED
p_list->push_back(PropertyInfo(Variant::BOOL, "editor_settings/show_bone_gizmo", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
#endif // TOOLS_ENABLED
}
void Bone2D::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE) {
Node *parent = get_parent();
@ -53,19 +116,54 @@ void Bone2D::_notification(int p_what) {
skeleton->bones.push_back(bone);
skeleton->_make_bone_setup_dirty();
}
cache_transform = get_transform();
copy_transform_to_cache = true;
#ifdef TOOLS_ENABLED
// Only draw the gizmo in the editor!
if (Engine::get_singleton()->is_editor_hint() == false) {
return;
}
update();
#endif // TOOLS_ENABLED
}
if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {
else if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {
if (skeleton) {
skeleton->_make_transform_dirty();
}
if (copy_transform_to_cache) {
cache_transform = get_transform();
}
#ifdef TOOLS_ENABLED
// Only draw the gizmo in the editor!
if (Engine::get_singleton()->is_editor_hint() == false) {
return;
}
update();
if (get_parent()) {
Bone2D *parent_bone = Object::cast_to<Bone2D>(get_parent());
if (parent_bone) {
parent_bone->update();
}
}
#endif // TOOLS_ENABLED
}
if (p_what == NOTIFICATION_MOVED_IN_PARENT) {
else if (p_what == NOTIFICATION_MOVED_IN_PARENT) {
if (skeleton) {
skeleton->_make_bone_setup_dirty();
}
if (copy_transform_to_cache) {
cache_transform = get_transform();
}
}
if (p_what == NOTIFICATION_EXIT_TREE) {
else if (p_what == NOTIFICATION_EXIT_TREE) {
if (skeleton) {
for (int i = 0; i < skeleton->bones.size(); i++) {
if (skeleton->bones[i].bone == this) {
@ -77,9 +175,200 @@ void Bone2D::_notification(int p_what) {
skeleton = nullptr;
}
parent_bone = nullptr;
set_transform(cache_transform);
}
else if (p_what == NOTIFICATION_READY) {
if (autocalculate_length_and_angle) {
calculate_length_and_rotation();
}
}
#ifdef TOOLS_ENABLED
else if (p_what == NOTIFICATION_EDITOR_PRE_SAVE || p_what == NOTIFICATION_EDITOR_POST_SAVE) {
Transform2D tmp_trans = get_transform();
set_transform(cache_transform);
cache_transform = tmp_trans;
}
// Bone2D Editor gizmo drawing:
#ifndef _MSC_VER
#warning TODO Bone2D gizmo drawing needs to be moved to an editor plugin
#endif
else if (p_what == NOTIFICATION_DRAW) {
// Only draw the gizmo in the editor!
if (Engine::get_singleton()->is_editor_hint() == false) {
return;
}
if (editor_gizmo_rid.is_null()) {
editor_gizmo_rid = RenderingServer::get_singleton()->canvas_item_create();
RenderingServer::get_singleton()->canvas_item_set_parent(editor_gizmo_rid, get_canvas_item());
RenderingServer::get_singleton()->canvas_item_set_z_as_relative_to_parent(editor_gizmo_rid, true);
RenderingServer::get_singleton()->canvas_item_set_z_index(editor_gizmo_rid, 10);
}
RenderingServer::get_singleton()->canvas_item_clear(editor_gizmo_rid);
if (!_editor_show_bone_gizmo) {
return;
}
// Undo scaling
Transform2D editor_gizmo_trans = Transform2D();
editor_gizmo_trans.set_scale(Vector2(1, 1) / get_global_scale());
RenderingServer::get_singleton()->canvas_item_set_transform(editor_gizmo_rid, editor_gizmo_trans);
Color bone_color1 = EditorSettings::get_singleton()->get("editors/2d/bone_color1");
Color bone_color2 = EditorSettings::get_singleton()->get("editors/2d/bone_color2");
Color bone_ik_color = EditorSettings::get_singleton()->get("editors/2d/bone_ik_color");
Color bone_outline_color = EditorSettings::get_singleton()->get("editors/2d/bone_outline_color");
Color bone_selected_color = EditorSettings::get_singleton()->get("editors/2d/bone_selected_color");
bool Bone2D_found = false;
for (int i = 0; i < get_child_count(); i++) {
Bone2D *child_node = nullptr;
child_node = Object::cast_to<Bone2D>(get_child(i));
if (!child_node) {
continue;
}
Bone2D_found = true;
Vector<Vector2> bone_shape;
Vector<Vector2> bone_shape_outline;
_editor_get_bone_shape(&bone_shape, &bone_shape_outline, child_node);
Vector<Color> colors;
if (has_meta("_local_pose_override_enabled_")) {
colors.push_back(bone_ik_color);
colors.push_back(bone_ik_color);
colors.push_back(bone_ik_color);
colors.push_back(bone_ik_color);
} else {
colors.push_back(bone_color1);
colors.push_back(bone_color2);
colors.push_back(bone_color1);
colors.push_back(bone_color2);
}
Vector<Color> outline_colors;
if (CanvasItemEditor::get_singleton()->editor_selection->is_selected(this)) {
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
} else {
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
}
RenderingServer::get_singleton()->canvas_item_add_polygon(editor_gizmo_rid, bone_shape_outline, outline_colors);
RenderingServer::get_singleton()->canvas_item_add_polygon(editor_gizmo_rid, bone_shape, colors);
}
if (!Bone2D_found) {
Vector<Vector2> bone_shape;
Vector<Vector2> bone_shape_outline;
_editor_get_bone_shape(&bone_shape, &bone_shape_outline, nullptr);
Vector<Color> colors;
if (has_meta("_local_pose_override_enabled_")) {
colors.push_back(bone_ik_color);
colors.push_back(bone_ik_color);
colors.push_back(bone_ik_color);
colors.push_back(bone_ik_color);
} else {
colors.push_back(bone_color1);
colors.push_back(bone_color2);
colors.push_back(bone_color1);
colors.push_back(bone_color2);
}
Vector<Color> outline_colors;
if (CanvasItemEditor::get_singleton()->editor_selection->is_selected(this)) {
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
outline_colors.push_back(bone_selected_color);
} else {
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
outline_colors.push_back(bone_outline_color);
}
RenderingServer::get_singleton()->canvas_item_add_polygon(editor_gizmo_rid, bone_shape_outline, outline_colors);
RenderingServer::get_singleton()->canvas_item_add_polygon(editor_gizmo_rid, bone_shape, colors);
}
}
#endif // TOOLS_ENALBED
}
#ifdef TOOLS_ENABLED
bool Bone2D::_editor_get_bone_shape(Vector<Vector2> *p_shape, Vector<Vector2> *p_outline_shape, Bone2D *p_other_bone) {
int bone_width = EditorSettings::get_singleton()->get("editors/2d/bone_width");
int bone_outline_width = EditorSettings::get_singleton()->get("editors/2d/bone_outline_size");
if (!is_inside_tree()) {
return false; //may have been removed
}
if (!p_other_bone && length <= 0) {
return false;
}
Vector2 rel;
if (p_other_bone) {
rel = (p_other_bone->get_global_transform().get_origin() - get_global_transform().get_origin());
rel = rel.rotated(-get_global_rotation()); // Undo Bone2D node's rotation so its drawn correctly regardless of the node's rotation
} else {
float angle_to_use = get_rotation() + bone_angle;
rel = Vector2(cos(angle_to_use), sin(angle_to_use)) * (length * MIN(get_global_scale().x, get_global_scale().y));
rel = rel.rotated(-get_rotation()); // Undo Bone2D node's rotation so its drawn correctly regardless of the node's rotation
}
Vector2 relt = rel.rotated(Math_PI * 0.5).normalized() * bone_width;
Vector2 reln = rel.normalized();
Vector2 reltn = relt.normalized();
if (p_shape) {
p_shape->clear();
p_shape->push_back(Vector2(0, 0));
p_shape->push_back(rel * 0.2 + relt);
p_shape->push_back(rel);
p_shape->push_back(rel * 0.2 - relt);
}
if (p_outline_shape) {
p_outline_shape->clear();
p_outline_shape->push_back((-reln - reltn) * bone_outline_width);
p_outline_shape->push_back((-reln + reltn) * bone_outline_width);
p_outline_shape->push_back(rel * 0.2 + relt + reltn * bone_outline_width);
p_outline_shape->push_back(rel + (reln + reltn) * bone_outline_width);
p_outline_shape->push_back(rel + (reln - reltn) * bone_outline_width);
p_outline_shape->push_back(rel * 0.2 - relt - reltn * bone_outline_width);
}
return true;
}
void Bone2D::_editor_set_show_bone_gizmo(bool p_show_gizmo) {
_editor_show_bone_gizmo = p_show_gizmo;
update();
}
bool Bone2D::_editor_get_show_bone_gizmo() const {
return _editor_show_bone_gizmo;
}
#endif // TOOLS_ENABLED
void Bone2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_rest", "rest"), &Bone2D::set_rest);
ClassDB::bind_method(D_METHOD("get_rest"), &Bone2D::get_rest);
@ -90,8 +379,14 @@ void Bone2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_default_length", "default_length"), &Bone2D::set_default_length);
ClassDB::bind_method(D_METHOD("get_default_length"), &Bone2D::get_default_length);
ClassDB::bind_method(D_METHOD("set_autocalculate_length_and_angle", "auto_calculate"), &Bone2D::set_autocalculate_length_and_angle);
ClassDB::bind_method(D_METHOD("get_autocalculate_length_and_angle"), &Bone2D::get_autocalculate_length_and_angle);
ClassDB::bind_method(D_METHOD("set_length", "length"), &Bone2D::set_length);
ClassDB::bind_method(D_METHOD("get_length"), &Bone2D::get_length);
ClassDB::bind_method(D_METHOD("set_bone_angle", "angle"), &Bone2D::set_bone_angle);
ClassDB::bind_method(D_METHOD("get_bone_angle"), &Bone2D::get_bone_angle);
ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "rest"), "set_rest", "get_rest");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "default_length", PROPERTY_HINT_RANGE, "1,1024,1"), "set_default_length", "get_default_length");
}
void Bone2D::set_rest(const Transform2D &p_rest) {
@ -119,12 +414,14 @@ void Bone2D::apply_rest() {
set_transform(rest);
}
void Bone2D::set_default_length(real_t p_length) {
default_length = p_length;
void Bone2D::set_default_length(float p_length) {
WARN_DEPRECATED_MSG("set_default_length is deprecated. Please use set_length instead!");
set_length(p_length);
}
real_t Bone2D::get_default_length() const {
return default_length;
float Bone2D::get_default_length() const {
WARN_DEPRECATED_MSG("get_default_length is deprecated. Please use get_length instead!");
return get_length();
}
int Bone2D::get_index_in_skeleton() const {
@ -150,16 +447,121 @@ TypedArray<String> Bone2D::get_configuration_warnings() const {
return warnings;
}
void Bone2D::calculate_length_and_rotation() {
// if there is at least a single child Bone2D node, we can calculate
// the length and direction. We will always just use the first Bone2D for this.
bool calculated = false;
int child_count = get_child_count();
if (child_count > 0) {
for (int i = 0; i < child_count; i++) {
Bone2D *child = Object::cast_to<Bone2D>(get_child(i));
if (child) {
Vector2 child_local_pos = to_local(child->get_global_transform().get_origin());
length = child_local_pos.length();
bone_angle = Math::atan2(child_local_pos.normalized().y, child_local_pos.normalized().x);
calculated = true;
break;
}
}
}
if (calculated) {
return; // Finished!
} else {
WARN_PRINT("No Bone2D children of node " + get_name() + ". Cannot calculate bone length or angle reliably.\nUsing transform rotation for bone angle");
bone_angle = get_transform().get_rotation();
return;
}
}
void Bone2D::set_autocalculate_length_and_angle(bool p_autocalculate) {
autocalculate_length_and_angle = p_autocalculate;
if (autocalculate_length_and_angle) {
calculate_length_and_rotation();
}
notify_property_list_changed();
}
bool Bone2D::get_autocalculate_length_and_angle() const {
return autocalculate_length_and_angle;
}
void Bone2D::set_length(float p_length) {
length = p_length;
#ifdef TOOLS_ENABLED
update();
#endif // TOOLS_ENABLED
}
float Bone2D::get_length() const {
return length;
}
void Bone2D::set_bone_angle(float p_angle) {
bone_angle = p_angle;
#ifdef TOOLS_ENABLED
update();
#endif // TOOLS_ENABLED
}
float Bone2D::get_bone_angle() const {
return bone_angle;
}
Bone2D::Bone2D() {
skeleton = nullptr;
parent_bone = nullptr;
skeleton_index = -1;
length = 16;
bone_angle = 0;
autocalculate_length_and_angle = true;
set_notify_local_transform(true);
//this is a clever hack so the bone knows no rest has been set yet, allowing to show an error.
for (int i = 0; i < 3; i++) {
rest[i] = Vector2(0, 0);
}
copy_transform_to_cache = true;
}
Bone2D::~Bone2D() {
#ifdef TOOLS_ENABLED
if (!editor_gizmo_rid.is_null()) {
RenderingServer::get_singleton()->free(editor_gizmo_rid);
}
#endif // TOOLS_ENABLED
}
//////////////////////////////////////
bool Skeleton2D::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (path.begins_with("modification_stack")) {
set_modification_stack(p_value);
return true;
}
return true;
}
bool Skeleton2D::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
if (path.begins_with("modification_stack")) {
r_ret = get_modification_stack();
return true;
}
return true;
}
void Skeleton2D::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(
PropertyInfo(Variant::OBJECT, "modification_stack",
PROPERTY_HINT_RESOURCE_TYPE,
"SkeletonModificationStack2D",
PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
}
void Skeleton2D::_make_bone_setup_dirty() {
if (bone_setup_dirty) {
return;
@ -189,6 +591,8 @@ void Skeleton2D::_update_bone_setup() {
} else {
bones.write[i].parent_index = -1;
}
bones.write[i].local_pose_override = bones[i].bone->get_skeleton_rest();
}
transform_dirty = true;
@ -257,19 +661,121 @@ void Skeleton2D::_notification(int p_what) {
if (transform_dirty) {
_update_transform();
}
request_ready();
}
if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
RS::get_singleton()->skeleton_set_base_transform_2d(skeleton, get_global_transform());
} else if (p_what == NOTIFICATION_INTERNAL_PROCESS) {
if (modification_stack.is_valid()) {
execute_modifications(get_process_delta_time(), SkeletonModificationStack2D::EXECUTION_MODE::execution_mode_process);
}
} else if (p_what == NOTIFICATION_INTERNAL_PHYSICS_PROCESS) {
if (modification_stack.is_valid()) {
execute_modifications(get_physics_process_delta_time(), SkeletonModificationStack2D::EXECUTION_MODE::execution_mode_physics_process);
}
}
#ifdef TOOLS_ENABLED
else if (p_what == NOTIFICATION_DRAW) {
if (Engine::get_singleton()->is_editor_hint()) {
if (modification_stack.is_valid()) {
modification_stack->draw_editor_gizmos();
}
}
}
#endif // TOOLS_ENABLED
}
RID Skeleton2D::get_skeleton() const {
return skeleton;
}
void Skeleton2D::set_bone_local_pose_override(int p_bone_idx, Transform2D p_override, float p_amount, bool p_persistent) {
ERR_FAIL_INDEX_MSG(p_bone_idx, bones.size(), "Bone index is out of range!");
bones.write[p_bone_idx].local_pose_override = p_override;
bones.write[p_bone_idx].local_pose_override_amount = p_amount;
bones.write[p_bone_idx].local_pose_override_persistent = p_persistent;
}
Transform2D Skeleton2D::get_bone_local_pose_override(int p_bone_idx) {
ERR_FAIL_INDEX_V_MSG(p_bone_idx, bones.size(), Transform2D(), "Bone index is out of range!");
return bones[p_bone_idx].local_pose_override;
}
void Skeleton2D::set_modification_stack(Ref<SkeletonModificationStack2D> p_stack) {
if (modification_stack.is_valid()) {
modification_stack->is_setup = false;
modification_stack->set_skeleton(nullptr);
set_process_internal(false);
set_physics_process_internal(false);
}
modification_stack = p_stack;
if (modification_stack.is_valid()) {
modification_stack->set_skeleton(this);
modification_stack->setup();
set_process_internal(true);
set_physics_process_internal(true);
#ifdef TOOLS_ENABLED
modification_stack->set_editor_gizmos_dirty(true);
#endif // TOOLS_ENABLED
}
}
Ref<SkeletonModificationStack2D> Skeleton2D::get_modification_stack() const {
return modification_stack;
}
void Skeleton2D::execute_modifications(float p_delta, int p_execution_mode) {
if (!modification_stack.is_valid()) {
return;
}
// Do not cache the transform changes caused by the modifications!
for (int i = 0; i < bones.size(); i++) {
bones[i].bone->copy_transform_to_cache = false;
}
if (modification_stack->skeleton != this) {
modification_stack->set_skeleton(this);
}
modification_stack->execute(p_delta, p_execution_mode);
// Only apply the local pose override on _process. Otherwise, just calculate the local_pose_override and reset the transform.
if (p_execution_mode == SkeletonModificationStack2D::EXECUTION_MODE::execution_mode_process) {
for (int i = 0; i < bones.size(); i++) {
if (bones[i].local_pose_override_amount > 0) {
bones[i].bone->set_meta("_local_pose_override_enabled_", true);
Transform2D final_trans = bones[i].bone->cache_transform;
final_trans = final_trans.interpolate_with(bones[i].local_pose_override, bones[i].local_pose_override_amount);
bones[i].bone->set_transform(final_trans);
bones[i].bone->propagate_call("force_update_transform");
if (bones[i].local_pose_override_persistent) {
bones.write[i].local_pose_override_amount = 0.0;
}
} else {
// TODO: see if there is a way to undo the override without having to resort to setting every bone's transform.
bones[i].bone->remove_meta("_local_pose_override_enabled_");
bones[i].bone->set_transform(bones[i].bone->cache_transform);
}
}
}
// Cache any future transform changes
for (int i = 0; i < bones.size(); i++) {
bones[i].bone->copy_transform_to_cache = true;
}
#ifdef TOOLS_ENABLED
modification_stack->set_editor_gizmos_dirty(true);
#endif // TOOLS_ENABLED
}
void Skeleton2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("_update_bone_setup"), &Skeleton2D::_update_bone_setup);
ClassDB::bind_method(D_METHOD("_update_transform"), &Skeleton2D::_update_transform);
@ -279,6 +785,13 @@ void Skeleton2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_skeleton"), &Skeleton2D::get_skeleton);
ClassDB::bind_method(D_METHOD("set_modification_stack", "modification_stack"), &Skeleton2D::set_modification_stack);
ClassDB::bind_method(D_METHOD("get_modification_stack"), &Skeleton2D::get_modification_stack);
ClassDB::bind_method(D_METHOD("execute_modifications", "execution_mode", "execution_mode"), &Skeleton2D::execute_modifications);
ClassDB::bind_method(D_METHOD("set_bone_local_pose_override", "bone_idx", "override_pose", "strength", "persistent"), &Skeleton2D::set_bone_local_pose_override);
ClassDB::bind_method(D_METHOD("get_bone_local_pose_override", "bone_idx"), &Skeleton2D::get_bone_local_pose_override);
ADD_SIGNAL(MethodInfo("bone_setup_changed"));
}

View file

@ -32,6 +32,7 @@
#define SKELETON_2D_H
#include "scene/2d/node_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
class Skeleton2D;
@ -46,15 +47,32 @@ class Bone2D : public Node2D {
Bone2D *parent_bone = nullptr;
Skeleton2D *skeleton = nullptr;
Transform2D rest;
real_t default_length = 16.0;
bool autocalculate_length_and_angle = true;
float length = 16;
float bone_angle = 0;
int skeleton_index = -1;
void calculate_length_and_rotation();
#ifdef TOOLS_ENABLED
RID editor_gizmo_rid;
bool _editor_get_bone_shape(Vector<Vector2> *p_shape, Vector<Vector2> *p_outline_shape, Bone2D *p_other_bone);
bool _editor_show_bone_gizmo = true;
#endif // TOOLS ENABLED
protected:
void _notification(int p_what);
static void _bind_methods();
bool _set(const StringName &p_path, const Variant &p_value);
bool _get(const StringName &p_path, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
Transform2D cache_transform;
bool copy_transform_to_cache = true;
void set_rest(const Transform2D &p_rest);
Transform2D get_rest() const;
void apply_rest();
@ -65,11 +83,26 @@ public:
void set_default_length(real_t p_length);
real_t get_default_length() const;
void set_autocalculate_length_and_angle(bool p_autocalculate);
bool get_autocalculate_length_and_angle() const;
void set_length(float p_length);
float get_length() const;
void set_bone_angle(float p_angle);
float get_bone_angle() const;
int get_index_in_skeleton() const;
#ifdef TOOLS_ENABLED
void _editor_set_show_bone_gizmo(bool p_show_gizmo);
bool _editor_get_show_bone_gizmo() const;
#endif // TOOLS_ENABLED
Bone2D();
~Bone2D();
};
class SkeletonModificationStack2D;
class Skeleton2D : public Node2D {
GDCLASS(Skeleton2D, Node2D);
@ -86,6 +119,11 @@ class Skeleton2D : public Node2D {
int parent_index = 0;
Transform2D accum_transform;
Transform2D rest_inverse;
//Transform2D local_pose_cache;
Transform2D local_pose_override;
float local_pose_override_amount = 0;
bool local_pose_override_persistent = false;
};
Vector<Bone> bones;
@ -100,15 +138,28 @@ class Skeleton2D : public Node2D {
RID skeleton;
Ref<SkeletonModificationStack2D> modification_stack;
protected:
void _notification(int p_what);
static void _bind_methods();
bool _set(const StringName &p_path, const Variant &p_value);
bool _get(const StringName &p_path, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
int get_bone_count() const;
Bone2D *get_bone(int p_idx);
RID get_skeleton() const;
void set_bone_local_pose_override(int p_bone_idx, Transform2D p_override, float p_amount, bool p_persistent = true);
Transform2D get_bone_local_pose_override(int p_bone_idx);
Ref<SkeletonModificationStack2D> get_modification_stack() const;
void set_modification_stack(Ref<SkeletonModificationStack2D> p_stack);
void execute_modifications(float p_delta, int p_execution_mode);
Skeleton2D();
~Skeleton2D();
};

View file

@ -2830,6 +2830,9 @@ void Node::_bind_methods() {
BIND_CONSTANT(NOTIFICATION_INTERNAL_PHYSICS_PROCESS);
BIND_CONSTANT(NOTIFICATION_POST_ENTER_TREE);
BIND_CONSTANT(NOTIFICATION_EDITOR_PRE_SAVE);
BIND_CONSTANT(NOTIFICATION_EDITOR_POST_SAVE);
BIND_CONSTANT(NOTIFICATION_WM_MOUSE_ENTER);
BIND_CONSTANT(NOTIFICATION_WM_MOUSE_EXIT);
BIND_CONSTANT(NOTIFICATION_WM_WINDOW_FOCUS_IN);

View file

@ -253,6 +253,10 @@ public:
NOTIFICATION_APPLICATION_FOCUS_IN = MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN,
NOTIFICATION_APPLICATION_FOCUS_OUT = MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT,
NOTIFICATION_TEXT_SERVER_CHANGED = MainLoop::NOTIFICATION_TEXT_SERVER_CHANGED,
// Editor specific node notifications
NOTIFICATION_EDITOR_PRE_SAVE = 9001,
NOTIFICATION_EDITOR_POST_SAVE = 9002,
};
/* NODE/TREE */

View file

@ -55,6 +55,7 @@
#include "scene/2d/parallax_background.h"
#include "scene/2d/parallax_layer.h"
#include "scene/2d/path_2d.h"
#include "scene/2d/physical_bone_2d.h"
#include "scene/2d/physics_body_2d.h"
#include "scene/2d/polygon_2d.h"
#include "scene/2d/position_2d.h"
@ -160,6 +161,15 @@
#include "scene/resources/rectangle_shape_2d.h"
#include "scene/resources/resource_format_text.h"
#include "scene/resources/segment_shape_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
#include "scene/resources/skeleton_modification_2d_ccdik.h"
#include "scene/resources/skeleton_modification_2d_fabrik.h"
#include "scene/resources/skeleton_modification_2d_jiggle.h"
#include "scene/resources/skeleton_modification_2d_lookat.h"
#include "scene/resources/skeleton_modification_2d_physicalbones.h"
#include "scene/resources/skeleton_modification_2d_stackholder.h"
#include "scene/resources/skeleton_modification_2d_twoboneik.h"
#include "scene/resources/skeleton_modification_stack_2d.h"
#include "scene/resources/sky.h"
#include "scene/resources/sky_material.h"
#include "scene/resources/sphere_shape_3d.h"
@ -662,6 +672,18 @@ void register_scene_types() {
ClassDB::register_class<TouchScreenButton>();
ClassDB::register_class<RemoteTransform2D>();
ClassDB::register_class<SkeletonModificationStack2D>();
ClassDB::register_class<SkeletonModification2D>();
ClassDB::register_class<SkeletonModification2DLookAt>();
ClassDB::register_class<SkeletonModification2DCCDIK>();
ClassDB::register_class<SkeletonModification2DFABRIK>();
ClassDB::register_class<SkeletonModification2DJiggle>();
ClassDB::register_class<SkeletonModification2DTwoBoneIK>();
ClassDB::register_class<SkeletonModification2DStackHolder>();
ClassDB::register_class<PhysicalBone2D>();
ClassDB::register_class<SkeletonModification2DPhysicalBones>();
OS::get_singleton()->yield(); //may take time to init
/* REGISTER RESOURCES */

View file

@ -0,0 +1,251 @@
/*************************************************************************/
/* skeleton_modification_2d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "skeleton_modification_2d.h"
#include "scene/2d/skeleton_2d.h"
#include "scene/2d/collision_object_2d.h"
#include "scene/2d/collision_shape_2d.h"
#include "scene/2d/physical_bone_2d.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_settings.h"
#endif // TOOLS_ENABLED
///////////////////////////////////////
// Modification2D
///////////////////////////////////////
void SkeletonModification2D::_execute(float p_delta) {
call("_execute", p_delta);
if (!enabled) {
return;
}
}
void SkeletonModification2D::_setup_modification(SkeletonModificationStack2D *p_stack) {
stack = p_stack;
if (stack) {
is_setup = true;
} else {
WARN_PRINT("Could not setup modification with name " + get_name());
}
call("_setup_modification", p_stack);
}
void SkeletonModification2D::_draw_editor_gizmo() {
call("_draw_editor_gizmo");
}
void SkeletonModification2D::set_enabled(bool p_enabled) {
enabled = p_enabled;
#ifdef TOOLS_ENABLED
if (editor_draw_gizmo) {
if (stack) {
stack->set_editor_gizmos_dirty(true);
}
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2D::get_enabled() {
return enabled;
}
float SkeletonModification2D::clamp_angle(float p_angle, float p_min_bound, float p_max_bound, bool p_invert) {
// Map to the 0 to 360 range (in radians though) instead of the -180 to 180 range.
if (p_angle < 0) {
p_angle = Math_TAU + p_angle;
}
// Make min and max in the range of 0 to 360 (in radians), and make sure they are in the right order
if (p_min_bound < 0) {
p_min_bound = Math_TAU + p_min_bound;
}
if (p_max_bound < 0) {
p_max_bound = Math_TAU + p_max_bound;
}
if (p_min_bound > p_max_bound) {
float tmp = p_min_bound;
p_min_bound = p_max_bound;
p_max_bound = tmp;
}
// Note: May not be the most optimal way to clamp, but it always constraints to the nearest angle.
if (p_invert == false) {
if (p_angle < p_min_bound || p_angle > p_max_bound) {
Vector2 min_bound_vec = Vector2(Math::cos(p_min_bound), Math::sin(p_min_bound));
Vector2 max_bound_vec = Vector2(Math::cos(p_max_bound), Math::sin(p_max_bound));
Vector2 angle_vec = Vector2(Math::cos(p_angle), Math::sin(p_angle));
if (angle_vec.distance_squared_to(min_bound_vec) <= angle_vec.distance_squared_to(max_bound_vec)) {
p_angle = p_min_bound;
} else {
p_angle = p_max_bound;
}
}
} else {
if (p_angle > p_min_bound && p_angle < p_max_bound) {
Vector2 min_bound_vec = Vector2(Math::cos(p_min_bound), Math::sin(p_min_bound));
Vector2 max_bound_vec = Vector2(Math::cos(p_max_bound), Math::sin(p_max_bound));
Vector2 angle_vec = Vector2(Math::cos(p_angle), Math::sin(p_angle));
if (angle_vec.distance_squared_to(min_bound_vec) <= angle_vec.distance_squared_to(max_bound_vec)) {
p_angle = p_min_bound;
} else {
p_angle = p_max_bound;
}
}
}
return p_angle;
}
void SkeletonModification2D::editor_draw_angle_constraints(Bone2D *p_operation_bone, float p_min_bound, float p_max_bound,
bool p_constraint_enabled, bool p_constraint_in_localspace, bool p_constraint_inverted) {
if (!p_operation_bone) {
return;
}
Color bone_ik_color = Color(1.0, 0.65, 0.0, 0.4);
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
bone_ik_color = EditorSettings::get_singleton()->get("editors/2d/bone_ik_color");
}
#endif // TOOLS_ENABLED
float arc_angle_min = p_min_bound;
float arc_angle_max = p_max_bound;
if (arc_angle_min < 0) {
arc_angle_min = (Math_PI * 2) + arc_angle_min;
}
if (arc_angle_max < 0) {
arc_angle_max = (Math_PI * 2) + arc_angle_max;
}
if (arc_angle_min > arc_angle_max) {
float tmp = arc_angle_min;
arc_angle_min = arc_angle_max;
arc_angle_max = tmp;
}
arc_angle_min += p_operation_bone->get_bone_angle();
arc_angle_max += p_operation_bone->get_bone_angle();
if (p_constraint_enabled) {
if (p_constraint_in_localspace) {
Node *operation_bone_parent = p_operation_bone->get_parent();
Bone2D *operation_bone_parent_bone = Object::cast_to<Bone2D>(operation_bone_parent);
if (operation_bone_parent_bone) {
stack->skeleton->draw_set_transform(
stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()),
operation_bone_parent_bone->get_global_rotation() - stack->skeleton->get_global_rotation());
} else {
stack->skeleton->draw_set_transform(stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()));
}
} else {
stack->skeleton->draw_set_transform(stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()));
}
if (p_constraint_inverted) {
stack->skeleton->draw_arc(Vector2(0, 0), p_operation_bone->get_length(),
arc_angle_min + (Math_PI * 2), arc_angle_max, 32, bone_ik_color, 1.0);
} else {
stack->skeleton->draw_arc(Vector2(0, 0), p_operation_bone->get_length(),
arc_angle_min, arc_angle_max, 32, bone_ik_color, 1.0);
}
stack->skeleton->draw_line(Vector2(0, 0), Vector2(Math::cos(arc_angle_min), Math::sin(arc_angle_min)) * p_operation_bone->get_length(), bone_ik_color, 1.0);
stack->skeleton->draw_line(Vector2(0, 0), Vector2(Math::cos(arc_angle_max), Math::sin(arc_angle_max)) * p_operation_bone->get_length(), bone_ik_color, 1.0);
} else {
stack->skeleton->draw_set_transform(stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()));
stack->skeleton->draw_arc(Vector2(0, 0), p_operation_bone->get_length(), 0, Math_PI * 2, 32, bone_ik_color, 1.0);
stack->skeleton->draw_line(Vector2(0, 0), Vector2(1, 0) * p_operation_bone->get_length(), bone_ik_color, 1.0);
}
}
Ref<SkeletonModificationStack2D> SkeletonModification2D::get_modification_stack() {
return stack;
}
void SkeletonModification2D::set_is_setup(bool p_setup) {
is_setup = p_setup;
}
bool SkeletonModification2D::get_is_setup() const {
return is_setup;
}
void SkeletonModification2D::set_execution_mode(int p_mode) {
execution_mode = p_mode;
}
int SkeletonModification2D::get_execution_mode() const {
return execution_mode;
}
void SkeletonModification2D::set_editor_draw_gizmo(bool p_draw_gizmo) {
editor_draw_gizmo = p_draw_gizmo;
#ifdef TOOLS_ENABLED
if (is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2D::get_editor_draw_gizmo() const {
return editor_draw_gizmo;
}
void SkeletonModification2D::_bind_methods() {
BIND_VMETHOD(MethodInfo("_execute", PropertyInfo(Variant::FLOAT, "delta")));
BIND_VMETHOD(MethodInfo("_setup_modification", PropertyInfo(Variant::OBJECT, "modification_stack", PROPERTY_HINT_RESOURCE_TYPE, "SkeletonModificationStack2D")));
BIND_VMETHOD(MethodInfo("_draw_editor_gizmo"));
ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &SkeletonModification2D::set_enabled);
ClassDB::bind_method(D_METHOD("get_enabled"), &SkeletonModification2D::get_enabled);
ClassDB::bind_method(D_METHOD("get_modification_stack"), &SkeletonModification2D::get_modification_stack);
ClassDB::bind_method(D_METHOD("set_is_setup", "is_setup"), &SkeletonModification2D::set_is_setup);
ClassDB::bind_method(D_METHOD("get_is_setup"), &SkeletonModification2D::get_is_setup);
ClassDB::bind_method(D_METHOD("set_execution_mode", "execution_mode"), &SkeletonModification2D::set_execution_mode);
ClassDB::bind_method(D_METHOD("get_execution_mode"), &SkeletonModification2D::get_execution_mode);
ClassDB::bind_method(D_METHOD("clamp_angle", "angle", "min", "max", "invert"), &SkeletonModification2D::clamp_angle);
ClassDB::bind_method(D_METHOD("set_editor_draw_gizmo", "draw_gizmo"), &SkeletonModification2D::set_editor_draw_gizmo);
ClassDB::bind_method(D_METHOD("get_editor_draw_gizmo"), &SkeletonModification2D::get_editor_draw_gizmo);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "get_enabled");
ADD_PROPERTY(PropertyInfo(Variant::INT, "execution_mode", PROPERTY_HINT_ENUM, "process, physics_process"), "set_execution_mode", "get_execution_mode");
}
SkeletonModification2D::SkeletonModification2D() {
stack = nullptr;
is_setup = false;
}

View file

@ -0,0 +1,85 @@
/*************************************************************************/
/* skeleton_modification_2d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef SKELETONMODIFICATION2D_H
#define SKELETONMODIFICATION2D_H
#include "scene/2d/skeleton_2d.h"
#include "scene/resources/skeleton_modification_stack_2d.h"
///////////////////////////////////////
// SkeletonModification2D
///////////////////////////////////////
class SkeletonModificationStack2D;
class Bone2D;
class SkeletonModification2D : public Resource {
GDCLASS(SkeletonModification2D, Resource);
friend class Skeleton2D;
friend class Bone2D;
protected:
static void _bind_methods();
SkeletonModificationStack2D *stack;
int execution_mode = 0; // 0 = process
bool enabled = true;
bool is_setup = false;
bool _print_execution_error(bool p_condition, String p_message);
public:
virtual void _execute(float _delta);
virtual void _setup_modification(SkeletonModificationStack2D *p_stack);
virtual void _draw_editor_gizmo();
bool editor_draw_gizmo = false;
void set_editor_draw_gizmo(bool p_draw_gizmo);
bool get_editor_draw_gizmo() const;
void set_enabled(bool p_enabled);
bool get_enabled();
Ref<SkeletonModificationStack2D> get_modification_stack();
void set_is_setup(bool p_setup);
bool get_is_setup() const;
void set_execution_mode(int p_mode);
int get_execution_mode() const;
float clamp_angle(float p_angle, float p_min_bound, float p_max_bound, bool p_invert_clamp = false);
void editor_draw_angle_constraints(Bone2D *p_operation_bone, float p_min_bound, float p_max_bound, bool p_constraint_enabled, bool p_constraint_in_localspace, bool p_constraint_inverted);
SkeletonModification2D();
};
#endif // SKELETONMODIFICATION2D_H

View file

@ -0,0 +1,545 @@
/*************************************************************************/
/* skeleton_modification_2d_ccdik.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "skeleton_modification_2d_ccdik.h"
#include "scene/2d/skeleton_2d.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_settings.h"
#endif // TOOLS_ENABLED
bool SkeletonModification2DCCDIK::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (path.begins_with("joint_data/")) {
int which = path.get_slicec('/', 1).to_int();
String what = path.get_slicec('/', 2);
ERR_FAIL_INDEX_V(which, ccdik_data_chain.size(), false);
if (what == "bone2d_node") {
set_ccdik_joint_bone2d_node(which, p_value);
} else if (what == "bone_index") {
set_ccdik_joint_bone_index(which, p_value);
} else if (what == "rotate_from_joint") {
set_ccdik_joint_rotate_from_joint(which, p_value);
} else if (what == "enable_constraint") {
set_ccdik_joint_enable_constraint(which, p_value);
} else if (what == "constraint_angle_min") {
set_ccdik_joint_constraint_angle_min(which, Math::deg2rad(float(p_value)));
} else if (what == "constraint_angle_max") {
set_ccdik_joint_constraint_angle_max(which, Math::deg2rad(float(p_value)));
} else if (what == "constraint_angle_invert") {
set_ccdik_joint_constraint_angle_invert(which, p_value);
} else if (what == "constraint_in_localspace") {
set_ccdik_joint_constraint_in_localspace(which, p_value);
}
#ifdef TOOLS_ENABLED
if (what.begins_with("editor_draw_gizmo")) {
set_ccdik_joint_editor_draw_gizmo(which, p_value);
}
#endif // TOOLS_ENABLED
return true;
}
#ifdef TOOLS_ENABLED
if (path.begins_with("editor/draw_gizmo")) {
set_editor_draw_gizmo(p_value);
}
#endif // TOOLS_ENABLED
return true;
}
bool SkeletonModification2DCCDIK::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
if (path.begins_with("joint_data/")) {
int which = path.get_slicec('/', 1).to_int();
String what = path.get_slicec('/', 2);
ERR_FAIL_INDEX_V(which, ccdik_data_chain.size(), false);
if (what == "bone2d_node") {
r_ret = get_ccdik_joint_bone2d_node(which);
} else if (what == "bone_index") {
r_ret = get_ccdik_joint_bone_index(which);
} else if (what == "rotate_from_joint") {
r_ret = get_ccdik_joint_rotate_from_joint(which);
} else if (what == "enable_constraint") {
r_ret = get_ccdik_joint_enable_constraint(which);
} else if (what == "constraint_angle_min") {
r_ret = Math::rad2deg(get_ccdik_joint_constraint_angle_min(which));
} else if (what == "constraint_angle_max") {
r_ret = Math::rad2deg(get_ccdik_joint_constraint_angle_max(which));
} else if (what == "constraint_angle_invert") {
r_ret = get_ccdik_joint_constraint_angle_invert(which);
} else if (what == "constraint_in_localspace") {
r_ret = get_ccdik_joint_constraint_in_localspace(which);
}
#ifdef TOOLS_ENABLED
if (what.begins_with("editor_draw_gizmo")) {
r_ret = get_ccdik_joint_editor_draw_gizmo(which);
}
#endif // TOOLS_ENABLED
return true;
}
#ifdef TOOLS_ENABLED
if (path.begins_with("editor/draw_gizmo")) {
r_ret = get_editor_draw_gizmo();
}
#endif // TOOLS_ENABLED
return true;
}
void SkeletonModification2DCCDIK::_get_property_list(List<PropertyInfo> *p_list) const {
for (int i = 0; i < ccdik_data_chain.size(); i++) {
String base_string = "joint_data/" + itos(i) + "/";
p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::NODE_PATH, base_string + "bone2d_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Bone2D", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "rotate_from_joint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "enable_constraint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
if (ccdik_data_chain[i].enable_constraint) {
p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "constraint_angle_min", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "constraint_angle_max", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "constraint_angle_invert", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "constraint_in_localspace", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "editor_draw_gizmo", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
#endif // TOOLS_ENABLED
}
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
p_list->push_back(PropertyInfo(Variant::BOOL, "editor/draw_gizmo", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
#endif // TOOLS_ENABLED
}
void SkeletonModification2DCCDIK::_execute(float p_delta) {
ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
"Modification is not setup and therefore cannot execute!");
if (!enabled) {
return;
}
if (target_node_cache.is_null()) {
WARN_PRINT_ONCE("Target cache is out of date. Attempting to update...");
update_target_cache();
return;
}
if (tip_node_cache.is_null()) {
WARN_PRINT_ONCE("Tip cache is out of date. Attempting to update...");
update_tip_cache();
return;
}
Node2D *target = Object::cast_to<Node2D>(ObjectDB::get_instance(target_node_cache));
if (!target || !target->is_inside_tree()) {
ERR_PRINT_ONCE("Target node is not in the scene tree. Cannot execute modification!");
return;
}
Node2D *tip = Object::cast_to<Node2D>(ObjectDB::get_instance(tip_node_cache));
if (!tip || !tip->is_inside_tree()) {
ERR_PRINT_ONCE("Tip node is not in the scene tree. Cannot execute modification!");
return;
}
for (int i = 0; i < ccdik_data_chain.size(); i++) {
_execute_ccdik_joint(i, target, tip);
}
}
void SkeletonModification2DCCDIK::_execute_ccdik_joint(int p_joint_idx, Node2D *p_target, Node2D *p_tip) {
CCDIK_Joint_Data2D ccdik_data = ccdik_data_chain[p_joint_idx];
if (ccdik_data.bone_idx < 0 || ccdik_data.bone_idx > stack->skeleton->get_bone_count()) {
ERR_PRINT_ONCE("2D CCDIK joint: bone index not found!");
return;
}
Bone2D *operation_bone = stack->skeleton->get_bone(ccdik_data.bone_idx);
Transform2D operation_transform = operation_bone->get_global_transform();
if (ccdik_data.rotate_from_joint) {
// To rotate from the joint, simply look at the target!
operation_transform.set_rotation(
operation_transform.looking_at(p_target->get_global_transform().get_origin()).get_rotation() - operation_bone->get_bone_angle());
} else {
// How to rotate from the tip: get the difference of rotation needed from the tip to the target, from the perspective of the joint.
// Because we are only using the offset, we do not need to account for the bone angle of the Bone2D node.
float joint_to_tip = operation_transform.get_origin().angle_to_point(p_tip->get_global_transform().get_origin());
float joint_to_target = operation_transform.get_origin().angle_to_point(p_target->get_global_transform().get_origin());
operation_transform.set_rotation(
operation_transform.get_rotation() + (joint_to_target - joint_to_tip));
}
// Reset scale
operation_transform.set_scale(operation_bone->get_global_transform().get_scale());
// Apply constraints in globalspace:
if (ccdik_data.enable_constraint && !ccdik_data.constraint_in_localspace) {
operation_transform.set_rotation(clamp_angle(operation_transform.get_rotation(), ccdik_data.constraint_angle_min, ccdik_data.constraint_angle_max, ccdik_data.constraint_angle_invert));
}
// Convert from a global transform to a delta and then apply the delta to the local transform.
operation_bone->set_global_transform(operation_transform);
operation_transform = operation_bone->get_transform();
// Apply constraints in localspace:
if (ccdik_data.enable_constraint && ccdik_data.constraint_in_localspace) {
operation_transform.set_rotation(clamp_angle(operation_transform.get_rotation(), ccdik_data.constraint_angle_min, ccdik_data.constraint_angle_max, ccdik_data.constraint_angle_invert));
}
// Set the local pose override, and to make sure child bones are also updated, set the transform of the bone.
stack->skeleton->set_bone_local_pose_override(ccdik_data.bone_idx, operation_transform, stack->strength, true);
operation_bone->set_transform(operation_transform);
operation_bone->notification(operation_bone->NOTIFICATION_TRANSFORM_CHANGED);
}
void SkeletonModification2DCCDIK::_setup_modification(SkeletonModificationStack2D *p_stack) {
stack = p_stack;
if (stack != nullptr) {
is_setup = true;
update_target_cache();
update_tip_cache();
}
}
void SkeletonModification2DCCDIK::_draw_editor_gizmo() {
if (!enabled || !is_setup) {
return;
}
for (int i = 0; i < ccdik_data_chain.size(); i++) {
if (!ccdik_data_chain[i].editor_draw_gizmo) {
continue;
}
Bone2D *operation_bone = stack->skeleton->get_bone(ccdik_data_chain[i].bone_idx);
editor_draw_angle_constraints(operation_bone, ccdik_data_chain[i].constraint_angle_min, ccdik_data_chain[i].constraint_angle_max,
ccdik_data_chain[i].enable_constraint, ccdik_data_chain[i].constraint_in_localspace, ccdik_data_chain[i].constraint_angle_invert);
}
}
void SkeletonModification2DCCDIK::update_target_cache() {
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update target cache: modification is not properly setup!");
return;
}
target_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(target_node)) {
Node *node = stack->skeleton->get_node(target_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update target cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update target cache: node is not in the scene tree!");
target_node_cache = node->get_instance_id();
}
}
}
}
void SkeletonModification2DCCDIK::update_tip_cache() {
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update tip cache: modification is not properly setup!");
return;
}
tip_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(tip_node)) {
Node *node = stack->skeleton->get_node(tip_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update tip cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update tip cache: node is not in the scene tree!");
tip_node_cache = node->get_instance_id();
}
}
}
}
void SkeletonModification2DCCDIK::ccdik_joint_update_bone2d_cache(int p_joint_idx) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "Cannot update bone2d cache: joint index out of range!");
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update CCDIK Bone2D cache: modification is not properly setup!");
return;
}
ccdik_data_chain.write[p_joint_idx].bone2d_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(ccdik_data_chain[p_joint_idx].bone2d_node)) {
Node *node = stack->skeleton->get_node(ccdik_data_chain[p_joint_idx].bone2d_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update CCDIK joint " + itos(p_joint_idx) + " Bone2D cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update CCDIK joint " + itos(p_joint_idx) + " Bone2D cache: node is not in the scene tree!");
ccdik_data_chain.write[p_joint_idx].bone2d_node_cache = node->get_instance_id();
Bone2D *bone = Object::cast_to<Bone2D>(node);
if (bone) {
ccdik_data_chain.write[p_joint_idx].bone_idx = bone->get_index_in_skeleton();
} else {
ERR_FAIL_MSG("CCDIK joint " + itos(p_joint_idx) + " Bone2D cache: Nodepath to Bone2D is not a Bone2D node!");
}
}
}
}
}
void SkeletonModification2DCCDIK::set_target_node(const NodePath &p_target_node) {
target_node = p_target_node;
update_target_cache();
}
NodePath SkeletonModification2DCCDIK::get_target_node() const {
return target_node;
}
void SkeletonModification2DCCDIK::set_tip_node(const NodePath &p_tip_node) {
tip_node = p_tip_node;
update_tip_cache();
}
NodePath SkeletonModification2DCCDIK::get_tip_node() const {
return tip_node;
}
void SkeletonModification2DCCDIK::set_ccdik_data_chain_length(int p_length) {
ccdik_data_chain.resize(p_length);
notify_property_list_changed();
}
int SkeletonModification2DCCDIK::get_ccdik_data_chain_length() {
return ccdik_data_chain.size();
}
void SkeletonModification2DCCDIK::set_ccdik_joint_bone2d_node(int p_joint_idx, const NodePath &p_target_node) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "CCDIK joint out of range!");
ccdik_data_chain.write[p_joint_idx].bone2d_node = p_target_node;
ccdik_joint_update_bone2d_cache(p_joint_idx);
notify_property_list_changed();
}
NodePath SkeletonModification2DCCDIK::get_ccdik_joint_bone2d_node(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, ccdik_data_chain.size(), NodePath(), "CCDIK joint out of range!");
return ccdik_data_chain[p_joint_idx].bone2d_node;
}
void SkeletonModification2DCCDIK::set_ccdik_joint_bone_index(int p_joint_idx, int p_bone_idx) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "CCCDIK joint out of range!");
ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
if (is_setup) {
if (stack->skeleton) {
ERR_FAIL_INDEX_MSG(p_bone_idx, stack->skeleton->get_bone_count(), "Passed-in Bone index is out of range!");
ccdik_data_chain.write[p_joint_idx].bone_idx = p_bone_idx;
ccdik_data_chain.write[p_joint_idx].bone2d_node_cache = stack->skeleton->get_bone(p_bone_idx)->get_instance_id();
ccdik_data_chain.write[p_joint_idx].bone2d_node = stack->skeleton->get_path_to(stack->skeleton->get_bone(p_bone_idx));
} else {
WARN_PRINT("Cannot verify the CCDIK joint " + itos(p_joint_idx) + " bone index for this modification...");
ccdik_data_chain.write[p_joint_idx].bone_idx = p_bone_idx;
}
} else {
WARN_PRINT("Cannot verify the CCDIK joint " + itos(p_joint_idx) + " bone index for this modification...");
ccdik_data_chain.write[p_joint_idx].bone_idx = p_bone_idx;
}
notify_property_list_changed();
}
int SkeletonModification2DCCDIK::get_ccdik_joint_bone_index(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, ccdik_data_chain.size(), -1, "CCDIK joint out of range!");
return ccdik_data_chain[p_joint_idx].bone_idx;
}
void SkeletonModification2DCCDIK::set_ccdik_joint_rotate_from_joint(int p_joint_idx, bool p_rotate_from_joint) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "CCDIK joint out of range!");
ccdik_data_chain.write[p_joint_idx].rotate_from_joint = p_rotate_from_joint;
}
bool SkeletonModification2DCCDIK::get_ccdik_joint_rotate_from_joint(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, ccdik_data_chain.size(), false, "CCDIK joint out of range!");
return ccdik_data_chain[p_joint_idx].rotate_from_joint;
}
void SkeletonModification2DCCDIK::set_ccdik_joint_enable_constraint(int p_joint_idx, bool p_constraint) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "CCDIK joint out of range!");
ccdik_data_chain.write[p_joint_idx].enable_constraint = p_constraint;
notify_property_list_changed();
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2DCCDIK::get_ccdik_joint_enable_constraint(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, ccdik_data_chain.size(), false, "CCDIK joint out of range!");
return ccdik_data_chain[p_joint_idx].enable_constraint;
}
void SkeletonModification2DCCDIK::set_ccdik_joint_constraint_angle_min(int p_joint_idx, float p_angle_min) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "CCDIK joint out of range!");
ccdik_data_chain.write[p_joint_idx].constraint_angle_min = p_angle_min;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
float SkeletonModification2DCCDIK::get_ccdik_joint_constraint_angle_min(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, ccdik_data_chain.size(), 0.0, "CCDIK joint out of range!");
return ccdik_data_chain[p_joint_idx].constraint_angle_min;
}
void SkeletonModification2DCCDIK::set_ccdik_joint_constraint_angle_max(int p_joint_idx, float p_angle_max) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "CCDIK joint out of range!");
ccdik_data_chain.write[p_joint_idx].constraint_angle_max = p_angle_max;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
float SkeletonModification2DCCDIK::get_ccdik_joint_constraint_angle_max(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, ccdik_data_chain.size(), 0.0, "CCDIK joint out of range!");
return ccdik_data_chain[p_joint_idx].constraint_angle_max;
}
void SkeletonModification2DCCDIK::set_ccdik_joint_constraint_angle_invert(int p_joint_idx, bool p_invert) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "CCDIK joint out of range!");
ccdik_data_chain.write[p_joint_idx].constraint_angle_invert = p_invert;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2DCCDIK::get_ccdik_joint_constraint_angle_invert(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, ccdik_data_chain.size(), false, "CCDIK joint out of range!");
return ccdik_data_chain[p_joint_idx].constraint_angle_invert;
}
void SkeletonModification2DCCDIK::set_ccdik_joint_constraint_in_localspace(int p_joint_idx, bool p_constraint_in_localspace) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "CCDIK joint out of range!");
ccdik_data_chain.write[p_joint_idx].constraint_in_localspace = p_constraint_in_localspace;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2DCCDIK::get_ccdik_joint_constraint_in_localspace(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, ccdik_data_chain.size(), false, "CCDIK joint out of range!");
return ccdik_data_chain[p_joint_idx].constraint_in_localspace;
}
void SkeletonModification2DCCDIK::set_ccdik_joint_editor_draw_gizmo(int p_joint_idx, bool p_draw_gizmo) {
ERR_FAIL_INDEX_MSG(p_joint_idx, ccdik_data_chain.size(), "CCDIK joint out of range!");
ccdik_data_chain.write[p_joint_idx].editor_draw_gizmo = p_draw_gizmo;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2DCCDIK::get_ccdik_joint_editor_draw_gizmo(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, ccdik_data_chain.size(), false, "CCDIK joint out of range!");
return ccdik_data_chain[p_joint_idx].editor_draw_gizmo;
}
void SkeletonModification2DCCDIK::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification2DCCDIK::set_target_node);
ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification2DCCDIK::get_target_node);
ClassDB::bind_method(D_METHOD("set_tip_node", "tip_nodepath"), &SkeletonModification2DCCDIK::set_tip_node);
ClassDB::bind_method(D_METHOD("get_tip_node"), &SkeletonModification2DCCDIK::get_tip_node);
ClassDB::bind_method(D_METHOD("set_ccdik_data_chain_length", "length"), &SkeletonModification2DCCDIK::set_ccdik_data_chain_length);
ClassDB::bind_method(D_METHOD("get_ccdik_data_chain_length"), &SkeletonModification2DCCDIK::get_ccdik_data_chain_length);
ClassDB::bind_method(D_METHOD("set_ccdik_joint_bone2d_node", "joint_idx", "bone2d_nodepath"), &SkeletonModification2DCCDIK::set_ccdik_joint_bone2d_node);
ClassDB::bind_method(D_METHOD("get_ccdik_joint_bone2d_node", "joint_idx"), &SkeletonModification2DCCDIK::get_ccdik_joint_bone2d_node);
ClassDB::bind_method(D_METHOD("set_ccdik_joint_bone_index", "joint_idx", "bone_idx"), &SkeletonModification2DCCDIK::set_ccdik_joint_bone_index);
ClassDB::bind_method(D_METHOD("get_ccdik_joint_bone_index", "joint_idx"), &SkeletonModification2DCCDIK::get_ccdik_joint_bone_index);
ClassDB::bind_method(D_METHOD("set_ccdik_joint_rotate_from_joint", "joint_idx", "rotate_from_joint"), &SkeletonModification2DCCDIK::set_ccdik_joint_rotate_from_joint);
ClassDB::bind_method(D_METHOD("get_ccdik_joint_rotate_from_joint", "joint_idx"), &SkeletonModification2DCCDIK::get_ccdik_joint_rotate_from_joint);
ClassDB::bind_method(D_METHOD("set_ccdik_joint_enable_constraint", "joint_idx", "enable_constraint"), &SkeletonModification2DCCDIK::set_ccdik_joint_enable_constraint);
ClassDB::bind_method(D_METHOD("get_ccdik_joint_enable_constraint", "joint_idx"), &SkeletonModification2DCCDIK::get_ccdik_joint_enable_constraint);
ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_angle_min", "joint_idx", "angle_min"), &SkeletonModification2DCCDIK::set_ccdik_joint_constraint_angle_min);
ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_angle_min", "joint_idx"), &SkeletonModification2DCCDIK::get_ccdik_joint_constraint_angle_min);
ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_angle_max", "joint_idx", "angle_max"), &SkeletonModification2DCCDIK::set_ccdik_joint_constraint_angle_max);
ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_angle_max", "joint_idx"), &SkeletonModification2DCCDIK::get_ccdik_joint_constraint_angle_max);
ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_angle_invert", "joint_idx", "invert"), &SkeletonModification2DCCDIK::set_ccdik_joint_constraint_angle_invert);
ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_angle_invert", "joint_idx"), &SkeletonModification2DCCDIK::get_ccdik_joint_constraint_angle_invert);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node2D"), "set_target_node", "get_target_node");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "tip_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node2D"), "set_tip_node", "get_tip_node");
ADD_PROPERTY(PropertyInfo(Variant::INT, "ccdik_data_chain_length", PROPERTY_HINT_RANGE, "0, 100, 1"), "set_ccdik_data_chain_length", "get_ccdik_data_chain_length");
}
SkeletonModification2DCCDIK::SkeletonModification2DCCDIK() {
stack = nullptr;
is_setup = false;
enabled = true;
editor_draw_gizmo = true;
}
SkeletonModification2DCCDIK::~SkeletonModification2DCCDIK() {
}

View file

@ -0,0 +1,116 @@
/*************************************************************************/
/* skeleton_modification_2d_ccdik.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef SKELETONMODIFICATION2DCCDIK_H
#define SKELETONMODIFICATION2DCCDIK_H
#include "scene/2d/skeleton_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
///////////////////////////////////////
// SkeletonModification2DCCDIK
///////////////////////////////////////
class SkeletonModification2DCCDIK : public SkeletonModification2D {
GDCLASS(SkeletonModification2DCCDIK, SkeletonModification2D);
private:
struct CCDIK_Joint_Data2D {
int bone_idx = -1;
NodePath bone2d_node;
ObjectID bone2d_node_cache;
bool rotate_from_joint = false;
bool enable_constraint = false;
float constraint_angle_min = 0;
float constraint_angle_max = (2.0 * Math_PI);
bool constraint_angle_invert = false;
bool constraint_in_localspace = true;
bool editor_draw_gizmo = true;
};
Vector<CCDIK_Joint_Data2D> ccdik_data_chain;
NodePath target_node;
ObjectID target_node_cache;
void update_target_cache();
NodePath tip_node;
ObjectID tip_node_cache;
void update_tip_cache();
void ccdik_joint_update_bone2d_cache(int p_joint_idx);
void _execute_ccdik_joint(int p_joint_idx, Node2D *p_target, Node2D *p_tip);
protected:
static void _bind_methods();
bool _set(const StringName &p_path, const Variant &p_value);
bool _get(const StringName &p_path, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
void _execute(float p_delta) override;
void _setup_modification(SkeletonModificationStack2D *p_stack) override;
void _draw_editor_gizmo() override;
void set_target_node(const NodePath &p_target_node);
NodePath get_target_node() const;
void set_tip_node(const NodePath &p_tip_node);
NodePath get_tip_node() const;
int get_ccdik_data_chain_length();
void set_ccdik_data_chain_length(int p_new_length);
void set_ccdik_joint_bone2d_node(int p_joint_idx, const NodePath &p_target_node);
NodePath get_ccdik_joint_bone2d_node(int p_joint_idx) const;
void set_ccdik_joint_bone_index(int p_joint_idx, int p_bone_idx);
int get_ccdik_joint_bone_index(int p_joint_idx) const;
void set_ccdik_joint_rotate_from_joint(int p_joint_idx, bool p_rotate_from_joint);
bool get_ccdik_joint_rotate_from_joint(int p_joint_idx) const;
void set_ccdik_joint_enable_constraint(int p_joint_idx, bool p_constraint);
bool get_ccdik_joint_enable_constraint(int p_joint_idx) const;
void set_ccdik_joint_constraint_angle_min(int p_joint_idx, float p_angle_min);
float get_ccdik_joint_constraint_angle_min(int p_joint_idx) const;
void set_ccdik_joint_constraint_angle_max(int p_joint_idx, float p_angle_max);
float get_ccdik_joint_constraint_angle_max(int p_joint_idx) const;
void set_ccdik_joint_constraint_angle_invert(int p_joint_idx, bool p_invert);
bool get_ccdik_joint_constraint_angle_invert(int p_joint_idx) const;
void set_ccdik_joint_constraint_in_localspace(int p_joint_idx, bool p_constraint_in_localspace);
bool get_ccdik_joint_constraint_in_localspace(int p_joint_idx) const;
void set_ccdik_joint_editor_draw_gizmo(int p_joint_idx, bool p_draw_gizmo);
bool get_ccdik_joint_editor_draw_gizmo(int p_joint_idx) const;
SkeletonModification2DCCDIK();
~SkeletonModification2DCCDIK();
};
#endif // SKELETONMODIFICATION2DCCDIK_H

View file

@ -0,0 +1,444 @@
/*************************************************************************/
/* skeleton_modification_2d_fabrik.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "skeleton_modification_2d_fabrik.h"
#include "scene/2d/skeleton_2d.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_settings.h"
#endif // TOOLS_ENABLED
bool SkeletonModification2DFABRIK::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (path.begins_with("joint_data/")) {
int which = path.get_slicec('/', 1).to_int();
String what = path.get_slicec('/', 2);
ERR_FAIL_INDEX_V(which, fabrik_data_chain.size(), false);
if (what == "bone2d_node") {
set_fabrik_joint_bone2d_node(which, p_value);
} else if (what == "bone_index") {
set_fabrik_joint_bone_index(which, p_value);
} else if (what == "magnet_position") {
set_fabrik_joint_magnet_position(which, p_value);
} else if (what == "use_target_rotation") {
set_fabrik_joint_use_target_rotation(which, p_value);
}
}
return true;
}
bool SkeletonModification2DFABRIK::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
if (path.begins_with("joint_data/")) {
int which = path.get_slicec('/', 1).to_int();
String what = path.get_slicec('/', 2);
ERR_FAIL_INDEX_V(which, fabrik_data_chain.size(), false);
if (what == "bone2d_node") {
r_ret = get_fabrik_joint_bone2d_node(which);
} else if (what == "bone_index") {
r_ret = get_fabrik_joint_bone_index(which);
} else if (what == "magnet_position") {
r_ret = get_fabrik_joint_magnet_position(which);
} else if (what == "use_target_rotation") {
r_ret = get_fabrik_joint_use_target_rotation(which);
}
return true;
}
return true;
}
void SkeletonModification2DFABRIK::_get_property_list(List<PropertyInfo> *p_list) const {
for (int i = 0; i < fabrik_data_chain.size(); i++) {
String base_string = "joint_data/" + itos(i) + "/";
p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::NODE_PATH, base_string + "bone2d_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Bone2D", PROPERTY_USAGE_DEFAULT));
if (i > 0) {
p_list->push_back(PropertyInfo(Variant::VECTOR2, base_string + "magnet_position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
if (i == fabrik_data_chain.size() - 1) {
p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_target_rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
}
}
void SkeletonModification2DFABRIK::_execute(float p_delta) {
ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
"Modification is not setup and therefore cannot execute!");
if (!enabled) {
return;
}
if (target_node_cache.is_null()) {
WARN_PRINT_ONCE("Target cache is out of date. Attempting to update...");
update_target_cache();
return;
}
if (fabrik_data_chain.size() <= 1) {
ERR_PRINT_ONCE("FABRIK requires at least two joints to operate! Cannot execute modification!");
return;
}
Node2D *target = Object::cast_to<Node2D>(ObjectDB::get_instance(target_node_cache));
if (!target || !target->is_inside_tree()) {
ERR_PRINT_ONCE("Target node is not in the scene tree. Cannot execute modification!");
return;
}
target_global_pose = target->get_global_transform();
if (fabrik_data_chain[0].bone2d_node_cache.is_null() && !fabrik_data_chain[0].bone2d_node.is_empty()) {
fabrik_joint_update_bone2d_cache(0);
WARN_PRINT("Bone2D cache for origin joint is out of date. Updating...");
}
Bone2D *origin_bone2d_node = Object::cast_to<Bone2D>(ObjectDB::get_instance(fabrik_data_chain[0].bone2d_node_cache));
if (!origin_bone2d_node || !origin_bone2d_node->is_inside_tree()) {
ERR_PRINT_ONCE("Origin joint's Bone2D node is not in the scene tree. Cannot execute modification!");
return;
}
origin_global_pose = origin_bone2d_node->get_global_transform();
if (fabrik_transform_chain.size() != fabrik_data_chain.size()) {
fabrik_transform_chain.resize(fabrik_data_chain.size());
}
for (int i = 0; i < fabrik_data_chain.size(); i++) {
// Update the transform chain
if (fabrik_data_chain[i].bone2d_node_cache.is_null() && !fabrik_data_chain[i].bone2d_node.is_empty()) {
WARN_PRINT_ONCE("Bone2D cache for joint " + itos(i) + " is out of date.. Attempting to update...");
fabrik_joint_update_bone2d_cache(i);
}
Bone2D *joint_bone2d_node = Object::cast_to<Bone2D>(ObjectDB::get_instance(fabrik_data_chain[i].bone2d_node_cache));
if (!joint_bone2d_node) {
ERR_PRINT_ONCE("FABRIK Joint " + itos(i) + " does not have a Bone2D node set! Cannot execute modification!");
return;
}
fabrik_transform_chain.write[i] = joint_bone2d_node->get_global_transform();
// Apply magnet positions
if (i == 0) {
continue; // The origin cannot use a magnet position!
} else {
Transform2D joint_trans = fabrik_transform_chain[i];
joint_trans.set_origin(joint_trans.get_origin() + fabrik_data_chain[i].magnet_position);
fabrik_transform_chain.write[i] = joint_trans;
}
}
Bone2D *final_bone2d_node = Object::cast_to<Bone2D>(ObjectDB::get_instance(fabrik_data_chain[fabrik_data_chain.size() - 1].bone2d_node_cache));
float final_bone2d_angle = final_bone2d_node->get_global_transform().get_rotation();
if (fabrik_data_chain[fabrik_data_chain.size() - 1].use_target_rotation) {
final_bone2d_angle = target_global_pose.get_rotation();
}
Vector2 final_bone2d_direction = Vector2(Math::cos(final_bone2d_angle), Math::sin(final_bone2d_angle));
float final_bone2d_length = final_bone2d_node->get_length() * MIN(final_bone2d_node->get_global_scale().x, final_bone2d_node->get_global_scale().y);
float target_distance = (final_bone2d_node->get_global_transform().get_origin() + (final_bone2d_direction * final_bone2d_length)).distance_to(target->get_global_transform().get_origin());
chain_iterations = 0;
while (target_distance > chain_tolarance) {
chain_backwards();
chain_forwards();
final_bone2d_angle = final_bone2d_node->get_global_transform().get_rotation();
if (fabrik_data_chain[fabrik_data_chain.size() - 1].use_target_rotation) {
final_bone2d_angle = target_global_pose.get_rotation();
}
final_bone2d_direction = Vector2(Math::cos(final_bone2d_angle), Math::sin(final_bone2d_angle));
target_distance = (final_bone2d_node->get_global_transform().get_origin() + (final_bone2d_direction * final_bone2d_length)).distance_to(target->get_global_transform().get_origin());
chain_iterations += 1;
if (chain_iterations >= chain_max_iterations) {
break;
}
}
// Apply all of the saved transforms to the Bone2D nodes
for (int i = 0; i < fabrik_data_chain.size(); i++) {
Bone2D *joint_bone2d_node = Object::cast_to<Bone2D>(ObjectDB::get_instance(fabrik_data_chain[i].bone2d_node_cache));
if (!joint_bone2d_node) {
ERR_PRINT_ONCE("FABRIK Joint " + itos(i) + " does not have a Bone2D node set!");
continue;
}
Transform2D chain_trans = fabrik_transform_chain[i];
// Apply rotation
if (i + 1 < fabrik_data_chain.size()) {
chain_trans = chain_trans.looking_at(fabrik_transform_chain[i + 1].get_origin());
} else {
if (fabrik_data_chain[i].use_target_rotation) {
chain_trans.set_rotation(target_global_pose.get_rotation());
} else {
chain_trans = chain_trans.looking_at(target_global_pose.get_origin());
}
}
// Adjust for the bone angle
chain_trans.set_rotation(chain_trans.get_rotation() - joint_bone2d_node->get_bone_angle());
// Reset scale
chain_trans.set_scale(joint_bone2d_node->get_global_transform().get_scale());
// Apply to the bone, and to the override
joint_bone2d_node->set_global_transform(chain_trans);
stack->skeleton->set_bone_local_pose_override(fabrik_data_chain[i].bone_idx, joint_bone2d_node->get_transform(), stack->strength, true);
}
}
void SkeletonModification2DFABRIK::chain_backwards() {
int final_joint_index = fabrik_data_chain.size() - 1;
Bone2D *final_bone2d_node = Object::cast_to<Bone2D>(ObjectDB::get_instance(fabrik_data_chain[final_joint_index].bone2d_node_cache));
Transform2D final_bone2d_trans = fabrik_transform_chain[final_joint_index];
// Set the rotation of the tip bone
final_bone2d_trans = final_bone2d_trans.looking_at(target_global_pose.get_origin());
// Set the position of the tip bone
float final_bone2d_angle = final_bone2d_trans.get_rotation();
if (fabrik_data_chain[final_joint_index].use_target_rotation) {
final_bone2d_angle = target_global_pose.get_rotation();
}
Vector2 final_bone2d_direction = Vector2(Math::cos(final_bone2d_angle), Math::sin(final_bone2d_angle));
float final_bone2d_length = final_bone2d_node->get_length() * MIN(final_bone2d_node->get_global_scale().x, final_bone2d_node->get_global_scale().y);
final_bone2d_trans.set_origin(target_global_pose.get_origin() - (final_bone2d_direction * final_bone2d_length));
// Save the transform
fabrik_transform_chain.write[final_joint_index] = final_bone2d_trans;
int i = final_joint_index;
while (i >= 1) {
Transform2D previous_pose = fabrik_transform_chain[i];
i -= 1;
Bone2D *current_bone2d_node = Object::cast_to<Bone2D>(ObjectDB::get_instance(fabrik_data_chain[i].bone2d_node_cache));
Transform2D current_pose = fabrik_transform_chain[i];
float current_bone2d_node_length = current_bone2d_node->get_length() * MIN(current_bone2d_node->get_global_scale().x, current_bone2d_node->get_global_scale().y);
float length = current_bone2d_node_length / (previous_pose.get_origin() - current_pose.get_origin()).length();
Vector2 finish_position = previous_pose.get_origin().lerp(current_pose.get_origin(), length);
current_pose.set_origin(finish_position);
// Save the transform
fabrik_transform_chain.write[i] = current_pose;
}
}
void SkeletonModification2DFABRIK::chain_forwards() {
Transform2D origin_bone2d_trans = fabrik_transform_chain[0];
origin_bone2d_trans.set_origin(origin_global_pose.get_origin());
// Save the position
fabrik_transform_chain.write[0] = origin_bone2d_trans;
for (int i = 0; i < fabrik_data_chain.size() - 1; i++) {
Bone2D *current_bone2d_node = Object::cast_to<Bone2D>(ObjectDB::get_instance(fabrik_data_chain[i].bone2d_node_cache));
Transform2D current_pose = fabrik_transform_chain[i];
Transform2D next_pose = fabrik_transform_chain[i + 1];
float current_bone2d_node_length = current_bone2d_node->get_length() * MIN(current_bone2d_node->get_global_scale().x, current_bone2d_node->get_global_scale().y);
float length = current_bone2d_node_length / (current_pose.get_origin() - next_pose.get_origin()).length();
Vector2 finish_position = current_pose.get_origin().lerp(next_pose.get_origin(), length);
current_pose.set_origin(finish_position);
// Apply to the bone
fabrik_transform_chain.write[i + 1] = current_pose;
}
}
void SkeletonModification2DFABRIK::_setup_modification(SkeletonModificationStack2D *p_stack) {
stack = p_stack;
if (stack != nullptr) {
is_setup = true;
update_target_cache();
}
}
void SkeletonModification2DFABRIK::update_target_cache() {
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update target cache: modification is not properly setup!");
return;
}
target_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(target_node)) {
Node *node = stack->skeleton->get_node(target_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update target cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update target cache: node is not in scene tree!");
target_node_cache = node->get_instance_id();
}
}
}
}
void SkeletonModification2DFABRIK::fabrik_joint_update_bone2d_cache(int p_joint_idx) {
ERR_FAIL_INDEX_MSG(p_joint_idx, fabrik_data_chain.size(), "Cannot update bone2d cache: joint index out of range!");
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update FABRIK Bone2D cache: modification is not properly setup!");
return;
}
fabrik_data_chain.write[p_joint_idx].bone2d_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(fabrik_data_chain[p_joint_idx].bone2d_node)) {
Node *node = stack->skeleton->get_node(fabrik_data_chain[p_joint_idx].bone2d_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update FABRIK joint " + itos(p_joint_idx) + " Bone2D cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update FABRIK joint " + itos(p_joint_idx) + " Bone2D cache: node is not in scene tree!");
fabrik_data_chain.write[p_joint_idx].bone2d_node_cache = node->get_instance_id();
Bone2D *bone = Object::cast_to<Bone2D>(node);
if (bone) {
fabrik_data_chain.write[p_joint_idx].bone_idx = bone->get_index_in_skeleton();
} else {
ERR_FAIL_MSG("FABRIK joint " + itos(p_joint_idx) + " Bone2D cache: Nodepath to Bone2D is not a Bone2D node!");
}
}
}
}
}
void SkeletonModification2DFABRIK::set_target_node(const NodePath &p_target_node) {
target_node = p_target_node;
update_target_cache();
}
NodePath SkeletonModification2DFABRIK::get_target_node() const {
return target_node;
}
void SkeletonModification2DFABRIK::set_fabrik_data_chain_length(int p_length) {
fabrik_data_chain.resize(p_length);
notify_property_list_changed();
}
int SkeletonModification2DFABRIK::get_fabrik_data_chain_length() {
return fabrik_data_chain.size();
}
void SkeletonModification2DFABRIK::set_fabrik_joint_bone2d_node(int p_joint_idx, const NodePath &p_target_node) {
ERR_FAIL_INDEX_MSG(p_joint_idx, fabrik_data_chain.size(), "FABRIK joint out of range!");
fabrik_data_chain.write[p_joint_idx].bone2d_node = p_target_node;
fabrik_joint_update_bone2d_cache(p_joint_idx);
notify_property_list_changed();
}
NodePath SkeletonModification2DFABRIK::get_fabrik_joint_bone2d_node(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, fabrik_data_chain.size(), NodePath(), "FABRIK joint out of range!");
return fabrik_data_chain[p_joint_idx].bone2d_node;
}
void SkeletonModification2DFABRIK::set_fabrik_joint_bone_index(int p_joint_idx, int p_bone_idx) {
ERR_FAIL_INDEX_MSG(p_joint_idx, fabrik_data_chain.size(), "FABRIK joint out of range!");
ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
if (is_setup) {
if (stack->skeleton) {
ERR_FAIL_INDEX_MSG(p_bone_idx, stack->skeleton->get_bone_count(), "Passed-in Bone index is out of range!");
fabrik_data_chain.write[p_joint_idx].bone_idx = p_bone_idx;
fabrik_data_chain.write[p_joint_idx].bone2d_node_cache = stack->skeleton->get_bone(p_bone_idx)->get_instance_id();
fabrik_data_chain.write[p_joint_idx].bone2d_node = stack->skeleton->get_path_to(stack->skeleton->get_bone(p_bone_idx));
} else {
WARN_PRINT("Cannot verify the FABRIK joint " + itos(p_joint_idx) + " bone index for this modification...");
fabrik_data_chain.write[p_joint_idx].bone_idx = p_bone_idx;
}
} else {
WARN_PRINT("Cannot verify the FABRIK joint " + itos(p_joint_idx) + " bone index for this modification...");
fabrik_data_chain.write[p_joint_idx].bone_idx = p_bone_idx;
}
notify_property_list_changed();
}
int SkeletonModification2DFABRIK::get_fabrik_joint_bone_index(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, fabrik_data_chain.size(), -1, "FABRIK joint out of range!");
return fabrik_data_chain[p_joint_idx].bone_idx;
}
void SkeletonModification2DFABRIK::set_fabrik_joint_magnet_position(int p_joint_idx, Vector2 p_magnet_position) {
ERR_FAIL_INDEX_MSG(p_joint_idx, fabrik_data_chain.size(), "FABRIK joint out of range!");
fabrik_data_chain.write[p_joint_idx].magnet_position = p_magnet_position;
}
Vector2 SkeletonModification2DFABRIK::get_fabrik_joint_magnet_position(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, fabrik_data_chain.size(), Vector2(), "FABRIK joint out of range!");
return fabrik_data_chain[p_joint_idx].magnet_position;
}
void SkeletonModification2DFABRIK::set_fabrik_joint_use_target_rotation(int p_joint_idx, bool p_use_target_rotation) {
ERR_FAIL_INDEX_MSG(p_joint_idx, fabrik_data_chain.size(), "FABRIK joint out of range!");
fabrik_data_chain.write[p_joint_idx].use_target_rotation = p_use_target_rotation;
}
bool SkeletonModification2DFABRIK::get_fabrik_joint_use_target_rotation(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, fabrik_data_chain.size(), false, "FABRIK joint out of range!");
return fabrik_data_chain[p_joint_idx].use_target_rotation;
}
void SkeletonModification2DFABRIK::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification2DFABRIK::set_target_node);
ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification2DFABRIK::get_target_node);
ClassDB::bind_method(D_METHOD("set_fabrik_data_chain_length", "length"), &SkeletonModification2DFABRIK::set_fabrik_data_chain_length);
ClassDB::bind_method(D_METHOD("get_fabrik_data_chain_length"), &SkeletonModification2DFABRIK::get_fabrik_data_chain_length);
ClassDB::bind_method(D_METHOD("set_fabrik_joint_bone2d_node", "joint_idx", "bone2d_nodepath"), &SkeletonModification2DFABRIK::set_fabrik_joint_bone2d_node);
ClassDB::bind_method(D_METHOD("get_fabrik_joint_bone2d_node", "joint_idx"), &SkeletonModification2DFABRIK::get_fabrik_joint_bone2d_node);
ClassDB::bind_method(D_METHOD("set_fabrik_joint_bone_index", "joint_idx", "bone_idx"), &SkeletonModification2DFABRIK::set_fabrik_joint_bone_index);
ClassDB::bind_method(D_METHOD("get_fabrik_joint_bone_index", "joint_idx"), &SkeletonModification2DFABRIK::get_fabrik_joint_bone_index);
ClassDB::bind_method(D_METHOD("set_fabrik_joint_magnet_position", "joint_idx", "magnet_position"), &SkeletonModification2DFABRIK::set_fabrik_joint_magnet_position);
ClassDB::bind_method(D_METHOD("get_fabrik_joint_magnet_position", "joint_idx"), &SkeletonModification2DFABRIK::get_fabrik_joint_magnet_position);
ClassDB::bind_method(D_METHOD("set_fabrik_joint_use_target_rotation", "joint_idx", "use_target_rotation"), &SkeletonModification2DFABRIK::set_fabrik_joint_use_target_rotation);
ClassDB::bind_method(D_METHOD("get_fabrik_joint_use_target_rotation", "joint_idx"), &SkeletonModification2DFABRIK::get_fabrik_joint_use_target_rotation);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node2D"), "set_target_node", "get_target_node");
ADD_PROPERTY(PropertyInfo(Variant::INT, "fabrik_data_chain_length", PROPERTY_HINT_RANGE, "0, 100, 1"), "set_fabrik_data_chain_length", "get_fabrik_data_chain_length");
}
SkeletonModification2DFABRIK::SkeletonModification2DFABRIK() {
stack = nullptr;
is_setup = false;
enabled = true;
editor_draw_gizmo = false;
}
SkeletonModification2DFABRIK::~SkeletonModification2DFABRIK() {
}

View file

@ -0,0 +1,108 @@
/*************************************************************************/
/* skeleton_modification_2d_fabrik.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef SKELETONMODIFICATION2DFABRIK_H
#define SKELETONMODIFICATION2DFABRIK_H
#include "scene/2d/skeleton_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
///////////////////////////////////////
// SkeletonModification2DFABRIK
///////////////////////////////////////
class SkeletonModification2DFABRIK : public SkeletonModification2D {
GDCLASS(SkeletonModification2DFABRIK, SkeletonModification2D);
private:
struct FABRIK_Joint_Data2D {
int bone_idx = -1;
NodePath bone2d_node;
ObjectID bone2d_node_cache;
Vector2 magnet_position = Vector2(0, 0);
bool use_target_rotation = false;
bool editor_draw_gizmo = true;
};
Vector<FABRIK_Joint_Data2D> fabrik_data_chain;
// Unlike in 3D, we need a vector of Transform2D objects to perform FABRIK.
// This is because FABRIK (unlike CCDIK) needs to operate on transforms that are NOT
// affected by each other, making the transforms stored in Bone2D unusable, as well as those in Skeleton2D.
// For this reason, this modification stores a vector of Transform2Ds used for the calculations, which are then applied at the end.
Vector<Transform2D> fabrik_transform_chain;
NodePath target_node;
ObjectID target_node_cache;
void update_target_cache();
float chain_tolarance = 0.01;
int chain_max_iterations = 10;
int chain_iterations = 0;
Transform2D target_global_pose = Transform2D();
Transform2D origin_global_pose = Transform2D();
void fabrik_joint_update_bone2d_cache(int p_joint_idx);
void chain_backwards();
void chain_forwards();
protected:
static void _bind_methods();
bool _set(const StringName &p_path, const Variant &p_value);
bool _get(const StringName &p_path, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
void _execute(float p_delta) override;
void _setup_modification(SkeletonModificationStack2D *p_stack) override;
void set_target_node(const NodePath &p_target_node);
NodePath get_target_node() const;
int get_fabrik_data_chain_length();
void set_fabrik_data_chain_length(int p_new_length);
void set_fabrik_joint_bone2d_node(int p_joint_idx, const NodePath &p_target_node);
NodePath get_fabrik_joint_bone2d_node(int p_joint_idx) const;
void set_fabrik_joint_bone_index(int p_joint_idx, int p_bone_idx);
int get_fabrik_joint_bone_index(int p_joint_idx) const;
void set_fabrik_joint_magnet_position(int p_joint_idx, Vector2 p_magnet_position);
Vector2 get_fabrik_joint_magnet_position(int p_joint_idx) const;
void set_fabrik_joint_use_target_rotation(int p_joint_idx, bool p_use_target_rotation);
bool get_fabrik_joint_use_target_rotation(int p_joint_idx) const;
SkeletonModification2DFABRIK();
~SkeletonModification2DFABRIK();
};
#endif // SKELETONMODIFICATION2DFABRIK_H

View file

@ -0,0 +1,564 @@
/*************************************************************************/
/* skeleton_modification_2d_jiggle.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "skeleton_modification_2d_jiggle.h"
#include "scene/2d/skeleton_2d.h"
bool SkeletonModification2DJiggle::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (path.begins_with("joint_data/")) {
int which = path.get_slicec('/', 1).to_int();
String what = path.get_slicec('/', 2);
ERR_FAIL_INDEX_V(which, jiggle_data_chain.size(), false);
if (what == "bone2d_node") {
set_jiggle_joint_bone2d_node(which, p_value);
} else if (what == "bone_index") {
set_jiggle_joint_bone_index(which, p_value);
} else if (what == "override_defaults") {
set_jiggle_joint_override(which, p_value);
} else if (what == "stiffness") {
set_jiggle_joint_stiffness(which, p_value);
} else if (what == "mass") {
set_jiggle_joint_mass(which, p_value);
} else if (what == "damping") {
set_jiggle_joint_damping(which, p_value);
} else if (what == "use_gravity") {
set_jiggle_joint_use_gravity(which, p_value);
} else if (what == "gravity") {
set_jiggle_joint_gravity(which, p_value);
}
return true;
} else {
if (path == "use_colliders") {
set_use_colliders(p_value);
} else if (path == "collision_mask") {
set_collision_mask(p_value);
}
}
return true;
}
bool SkeletonModification2DJiggle::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
if (path.begins_with("joint_data/")) {
int which = path.get_slicec('/', 1).to_int();
String what = path.get_slicec('/', 2);
ERR_FAIL_INDEX_V(which, jiggle_data_chain.size(), false);
if (what == "bone2d_node") {
r_ret = get_jiggle_joint_bone2d_node(which);
} else if (what == "bone_index") {
r_ret = get_jiggle_joint_bone_index(which);
} else if (what == "override_defaults") {
r_ret = get_jiggle_joint_override(which);
} else if (what == "stiffness") {
r_ret = get_jiggle_joint_stiffness(which);
} else if (what == "mass") {
r_ret = get_jiggle_joint_mass(which);
} else if (what == "damping") {
r_ret = get_jiggle_joint_damping(which);
} else if (what == "use_gravity") {
r_ret = get_jiggle_joint_use_gravity(which);
} else if (what == "gravity") {
r_ret = get_jiggle_joint_gravity(which);
}
return true;
} else {
if (path == "use_colliders") {
r_ret = get_use_colliders();
} else if (path == "collision_mask") {
r_ret = get_collision_mask();
}
}
return true;
}
void SkeletonModification2DJiggle::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::BOOL, "use_colliders", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
if (use_colliders) {
p_list->push_back(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS, "", PROPERTY_USAGE_DEFAULT));
}
for (int i = 0; i < jiggle_data_chain.size(); i++) {
String base_string = "joint_data/" + itos(i) + "/";
p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::NODE_PATH, base_string + "bone2d_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Bone2D", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "override_defaults", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
if (jiggle_data_chain[i].override_defaults) {
p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "stiffness", PROPERTY_HINT_RANGE, "0, 1000, 0.01", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "mass", PROPERTY_HINT_RANGE, "0, 1000, 0.01", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "damping", PROPERTY_HINT_RANGE, "0, 1, 0.01", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_gravity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
if (jiggle_data_chain[i].use_gravity) {
p_list->push_back(PropertyInfo(Variant::VECTOR2, base_string + "gravity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
}
}
}
void SkeletonModification2DJiggle::_execute(float p_delta) {
ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
"Modification is not setup and therefore cannot execute!");
if (!enabled) {
return;
}
if (target_node_cache.is_null()) {
WARN_PRINT_ONCE("Target cache is out of date. Attempting to update...");
update_target_cache();
return;
}
Node2D *target = Object::cast_to<Node2D>(ObjectDB::get_instance(target_node_cache));
if (!target || !target->is_inside_tree()) {
ERR_PRINT_ONCE("Target node is not in the scene tree. Cannot execute modification!");
return;
}
for (int i = 0; i < jiggle_data_chain.size(); i++) {
_execute_jiggle_joint(i, target, p_delta);
}
}
void SkeletonModification2DJiggle::_execute_jiggle_joint(int p_joint_idx, Node2D *p_target, float p_delta) {
// Adopted from: https://wiki.unity3d.com/index.php/JiggleBone
// With modifications by TwistedTwigleg.
if (jiggle_data_chain[p_joint_idx].bone_idx <= -1 || jiggle_data_chain[p_joint_idx].bone_idx > stack->skeleton->get_bone_count()) {
ERR_PRINT_ONCE("Jiggle joint " + itos(p_joint_idx) + " bone index is invalid. Cannot execute modification on joint...");
return;
}
if (jiggle_data_chain[p_joint_idx].bone2d_node_cache.is_null() && !jiggle_data_chain[p_joint_idx].bone2d_node.is_empty()) {
WARN_PRINT_ONCE("Bone2D cache for joint " + itos(p_joint_idx) + " is out of date. Updating...");
jiggle_joint_update_bone2d_cache(p_joint_idx);
}
Bone2D *operation_bone = stack->skeleton->get_bone(jiggle_data_chain[p_joint_idx].bone_idx);
if (!operation_bone) {
ERR_PRINT_ONCE("Jiggle joint " + itos(p_joint_idx) + " does not have a Bone2D node or it cannot be found!");
return;
}
Transform2D operation_bone_trans = operation_bone->get_global_transform();
Vector2 target_position = p_target->get_global_transform().get_origin();
jiggle_data_chain.write[p_joint_idx].force = (target_position - jiggle_data_chain[p_joint_idx].dynamic_position) * jiggle_data_chain[p_joint_idx].stiffness * p_delta;
if (jiggle_data_chain[p_joint_idx].use_gravity) {
jiggle_data_chain.write[p_joint_idx].force += jiggle_data_chain[p_joint_idx].gravity * p_delta;
}
jiggle_data_chain.write[p_joint_idx].acceleration = jiggle_data_chain[p_joint_idx].force / jiggle_data_chain[p_joint_idx].mass;
jiggle_data_chain.write[p_joint_idx].velocity += jiggle_data_chain[p_joint_idx].acceleration * (1 - jiggle_data_chain[p_joint_idx].damping);
jiggle_data_chain.write[p_joint_idx].dynamic_position += jiggle_data_chain[p_joint_idx].velocity + jiggle_data_chain[p_joint_idx].force;
jiggle_data_chain.write[p_joint_idx].dynamic_position += operation_bone_trans.get_origin() - jiggle_data_chain[p_joint_idx].last_position;
jiggle_data_chain.write[p_joint_idx].last_position = operation_bone_trans.get_origin();
// Collision detection/response
if (use_colliders) {
if (execution_mode == SkeletonModificationStack2D::EXECUTION_MODE::execution_mode_physics_process) {
Ref<World2D> world_2d = stack->skeleton->get_world_2d();
ERR_FAIL_COND(world_2d.is_null());
PhysicsDirectSpaceState2D *space_state = PhysicsServer2D::get_singleton()->space_get_direct_state(world_2d->get_space());
PhysicsDirectSpaceState2D::RayResult ray_result;
// Add exception support?
bool ray_hit = space_state->intersect_ray(operation_bone_trans.get_origin(), jiggle_data_chain[p_joint_idx].dynamic_position,
ray_result, Set<RID>(), collision_mask);
if (ray_hit) {
jiggle_data_chain.write[p_joint_idx].dynamic_position = jiggle_data_chain[p_joint_idx].last_noncollision_position;
jiggle_data_chain.write[p_joint_idx].acceleration = Vector2(0, 0);
jiggle_data_chain.write[p_joint_idx].velocity = Vector2(0, 0);
} else {
jiggle_data_chain.write[p_joint_idx].last_noncollision_position = jiggle_data_chain[p_joint_idx].dynamic_position;
}
} else {
WARN_PRINT_ONCE("Jiggle 2D modifier: You cannot detect colliders without the stack mode being set to _physics_process!");
}
}
// Rotate the bone using the dynamic position!
operation_bone_trans = operation_bone_trans.looking_at(jiggle_data_chain[p_joint_idx].dynamic_position);
operation_bone_trans.set_rotation(operation_bone_trans.get_rotation() - operation_bone->get_bone_angle());
// Reset scale
operation_bone_trans.set_scale(operation_bone->get_global_transform().get_scale());
operation_bone->set_global_transform(operation_bone_trans);
stack->skeleton->set_bone_local_pose_override(jiggle_data_chain[p_joint_idx].bone_idx, operation_bone->get_transform(), stack->strength, true);
}
void SkeletonModification2DJiggle::_update_jiggle_joint_data() {
for (int i = 0; i < jiggle_data_chain.size(); i++) {
if (!jiggle_data_chain[i].override_defaults) {
set_jiggle_joint_stiffness(i, stiffness);
set_jiggle_joint_mass(i, mass);
set_jiggle_joint_damping(i, damping);
set_jiggle_joint_use_gravity(i, use_gravity);
set_jiggle_joint_gravity(i, gravity);
}
}
}
void SkeletonModification2DJiggle::_setup_modification(SkeletonModificationStack2D *p_stack) {
stack = p_stack;
if (stack) {
is_setup = true;
if (stack->skeleton) {
for (int i = 0; i < jiggle_data_chain.size(); i++) {
int bone_idx = jiggle_data_chain[i].bone_idx;
if (bone_idx > 0 && bone_idx < stack->skeleton->get_bone_count()) {
Bone2D *bone2d_node = stack->skeleton->get_bone(bone_idx);
jiggle_data_chain.write[i].dynamic_position = bone2d_node->get_global_transform().get_origin();
}
}
}
update_target_cache();
}
}
void SkeletonModification2DJiggle::update_target_cache() {
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update target cache: modification is not properly setup!");
return;
}
target_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(target_node)) {
Node *node = stack->skeleton->get_node(target_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update target cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update target cache: node is not in scene tree!");
target_node_cache = node->get_instance_id();
}
}
}
}
void SkeletonModification2DJiggle::jiggle_joint_update_bone2d_cache(int p_joint_idx) {
ERR_FAIL_INDEX_MSG(p_joint_idx, jiggle_data_chain.size(), "Cannot update bone2d cache: joint index out of range!");
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update Jiggle " + itos(p_joint_idx) + " Bone2D cache: modification is not properly setup!");
return;
}
jiggle_data_chain.write[p_joint_idx].bone2d_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(jiggle_data_chain[p_joint_idx].bone2d_node)) {
Node *node = stack->skeleton->get_node(jiggle_data_chain[p_joint_idx].bone2d_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update Jiggle joint " + itos(p_joint_idx) + " Bone2D cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update Jiggle joint " + itos(p_joint_idx) + " Bone2D cache: node is not in scene tree!");
jiggle_data_chain.write[p_joint_idx].bone2d_node_cache = node->get_instance_id();
Bone2D *bone = Object::cast_to<Bone2D>(node);
if (bone) {
jiggle_data_chain.write[p_joint_idx].bone_idx = bone->get_index_in_skeleton();
} else {
ERR_FAIL_MSG("Jiggle joint " + itos(p_joint_idx) + " Bone2D cache: Nodepath to Bone2D is not a Bone2D node!");
}
}
}
}
}
void SkeletonModification2DJiggle::set_target_node(const NodePath &p_target_node) {
target_node = p_target_node;
update_target_cache();
}
NodePath SkeletonModification2DJiggle::get_target_node() const {
return target_node;
}
void SkeletonModification2DJiggle::set_stiffness(float p_stiffness) {
ERR_FAIL_COND_MSG(p_stiffness < 0, "Stiffness cannot be set to a negative value!");
stiffness = p_stiffness;
_update_jiggle_joint_data();
}
float SkeletonModification2DJiggle::get_stiffness() const {
return stiffness;
}
void SkeletonModification2DJiggle::set_mass(float p_mass) {
ERR_FAIL_COND_MSG(p_mass < 0, "Mass cannot be set to a negative value!");
mass = p_mass;
_update_jiggle_joint_data();
}
float SkeletonModification2DJiggle::get_mass() const {
return mass;
}
void SkeletonModification2DJiggle::set_damping(float p_damping) {
ERR_FAIL_COND_MSG(p_damping < 0, "Damping cannot be set to a negative value!");
ERR_FAIL_COND_MSG(p_damping > 1, "Damping cannot be more than one!");
damping = p_damping;
_update_jiggle_joint_data();
}
float SkeletonModification2DJiggle::get_damping() const {
return damping;
}
void SkeletonModification2DJiggle::set_use_gravity(bool p_use_gravity) {
use_gravity = p_use_gravity;
_update_jiggle_joint_data();
}
bool SkeletonModification2DJiggle::get_use_gravity() const {
return use_gravity;
}
void SkeletonModification2DJiggle::set_gravity(Vector2 p_gravity) {
gravity = p_gravity;
_update_jiggle_joint_data();
}
Vector2 SkeletonModification2DJiggle::get_gravity() const {
return gravity;
}
void SkeletonModification2DJiggle::set_use_colliders(bool p_use_colliders) {
use_colliders = p_use_colliders;
notify_property_list_changed();
}
bool SkeletonModification2DJiggle::get_use_colliders() const {
return use_colliders;
}
void SkeletonModification2DJiggle::set_collision_mask(int p_mask) {
collision_mask = p_mask;
}
int SkeletonModification2DJiggle::get_collision_mask() const {
return collision_mask;
}
// Jiggle joint data functions
int SkeletonModification2DJiggle::get_jiggle_data_chain_length() {
return jiggle_data_chain.size();
}
void SkeletonModification2DJiggle::set_jiggle_data_chain_length(int p_length) {
ERR_FAIL_COND(p_length < 0);
jiggle_data_chain.resize(p_length);
notify_property_list_changed();
}
void SkeletonModification2DJiggle::set_jiggle_joint_bone2d_node(int p_joint_idx, const NodePath &p_target_node) {
ERR_FAIL_INDEX_MSG(p_joint_idx, jiggle_data_chain.size(), "Jiggle joint out of range!");
jiggle_data_chain.write[p_joint_idx].bone2d_node = p_target_node;
jiggle_joint_update_bone2d_cache(p_joint_idx);
notify_property_list_changed();
}
NodePath SkeletonModification2DJiggle::get_jiggle_joint_bone2d_node(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, jiggle_data_chain.size(), NodePath(), "Jiggle joint out of range!");
return jiggle_data_chain[p_joint_idx].bone2d_node;
}
void SkeletonModification2DJiggle::set_jiggle_joint_bone_index(int p_joint_idx, int p_bone_idx) {
ERR_FAIL_INDEX_MSG(p_joint_idx, jiggle_data_chain.size(), "Jiggle joint out of range!");
ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
if (is_setup) {
if (stack->skeleton) {
ERR_FAIL_INDEX_MSG(p_bone_idx, stack->skeleton->get_bone_count(), "Passed-in Bone index is out of range!");
jiggle_data_chain.write[p_joint_idx].bone_idx = p_bone_idx;
jiggle_data_chain.write[p_joint_idx].bone2d_node_cache = stack->skeleton->get_bone(p_bone_idx)->get_instance_id();
jiggle_data_chain.write[p_joint_idx].bone2d_node = stack->skeleton->get_path_to(stack->skeleton->get_bone(p_bone_idx));
} else {
WARN_PRINT("Cannot verify the Jiggle joint " + itos(p_joint_idx) + " bone index for this modification...");
jiggle_data_chain.write[p_joint_idx].bone_idx = p_bone_idx;
}
} else {
WARN_PRINT("Cannot verify the Jiggle joint " + itos(p_joint_idx) + " bone index for this modification...");
jiggle_data_chain.write[p_joint_idx].bone_idx = p_bone_idx;
}
notify_property_list_changed();
}
int SkeletonModification2DJiggle::get_jiggle_joint_bone_index(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, jiggle_data_chain.size(), -1, "Jiggle joint out of range!");
return jiggle_data_chain[p_joint_idx].bone_idx;
}
void SkeletonModification2DJiggle::set_jiggle_joint_override(int p_joint_idx, bool p_override) {
ERR_FAIL_INDEX(p_joint_idx, jiggle_data_chain.size());
jiggle_data_chain.write[p_joint_idx].override_defaults = p_override;
_update_jiggle_joint_data();
notify_property_list_changed();
}
bool SkeletonModification2DJiggle::get_jiggle_joint_override(int p_joint_idx) const {
ERR_FAIL_INDEX_V(p_joint_idx, jiggle_data_chain.size(), false);
return jiggle_data_chain[p_joint_idx].override_defaults;
}
void SkeletonModification2DJiggle::set_jiggle_joint_stiffness(int p_joint_idx, float p_stiffness) {
ERR_FAIL_COND_MSG(p_stiffness < 0, "Stiffness cannot be set to a negative value!");
ERR_FAIL_INDEX(p_joint_idx, jiggle_data_chain.size());
jiggle_data_chain.write[p_joint_idx].stiffness = p_stiffness;
}
float SkeletonModification2DJiggle::get_jiggle_joint_stiffness(int p_joint_idx) const {
ERR_FAIL_INDEX_V(p_joint_idx, jiggle_data_chain.size(), -1);
return jiggle_data_chain[p_joint_idx].stiffness;
}
void SkeletonModification2DJiggle::set_jiggle_joint_mass(int p_joint_idx, float p_mass) {
ERR_FAIL_COND_MSG(p_mass < 0, "Mass cannot be set to a negative value!");
ERR_FAIL_INDEX(p_joint_idx, jiggle_data_chain.size());
jiggle_data_chain.write[p_joint_idx].mass = p_mass;
}
float SkeletonModification2DJiggle::get_jiggle_joint_mass(int p_joint_idx) const {
ERR_FAIL_INDEX_V(p_joint_idx, jiggle_data_chain.size(), -1);
return jiggle_data_chain[p_joint_idx].mass;
}
void SkeletonModification2DJiggle::set_jiggle_joint_damping(int p_joint_idx, float p_damping) {
ERR_FAIL_COND_MSG(p_damping < 0, "Damping cannot be set to a negative value!");
ERR_FAIL_INDEX(p_joint_idx, jiggle_data_chain.size());
jiggle_data_chain.write[p_joint_idx].damping = p_damping;
}
float SkeletonModification2DJiggle::get_jiggle_joint_damping(int p_joint_idx) const {
ERR_FAIL_INDEX_V(p_joint_idx, jiggle_data_chain.size(), -1);
return jiggle_data_chain[p_joint_idx].damping;
}
void SkeletonModification2DJiggle::set_jiggle_joint_use_gravity(int p_joint_idx, bool p_use_gravity) {
ERR_FAIL_INDEX(p_joint_idx, jiggle_data_chain.size());
jiggle_data_chain.write[p_joint_idx].use_gravity = p_use_gravity;
notify_property_list_changed();
}
bool SkeletonModification2DJiggle::get_jiggle_joint_use_gravity(int p_joint_idx) const {
ERR_FAIL_INDEX_V(p_joint_idx, jiggle_data_chain.size(), false);
return jiggle_data_chain[p_joint_idx].use_gravity;
}
void SkeletonModification2DJiggle::set_jiggle_joint_gravity(int p_joint_idx, Vector2 p_gravity) {
ERR_FAIL_INDEX(p_joint_idx, jiggle_data_chain.size());
jiggle_data_chain.write[p_joint_idx].gravity = p_gravity;
}
Vector2 SkeletonModification2DJiggle::get_jiggle_joint_gravity(int p_joint_idx) const {
ERR_FAIL_INDEX_V(p_joint_idx, jiggle_data_chain.size(), Vector2(0, 0));
return jiggle_data_chain[p_joint_idx].gravity;
}
void SkeletonModification2DJiggle::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification2DJiggle::set_target_node);
ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification2DJiggle::get_target_node);
ClassDB::bind_method(D_METHOD("set_jiggle_data_chain_length", "length"), &SkeletonModification2DJiggle::set_jiggle_data_chain_length);
ClassDB::bind_method(D_METHOD("get_jiggle_data_chain_length"), &SkeletonModification2DJiggle::get_jiggle_data_chain_length);
ClassDB::bind_method(D_METHOD("set_stiffness", "stiffness"), &SkeletonModification2DJiggle::set_stiffness);
ClassDB::bind_method(D_METHOD("get_stiffness"), &SkeletonModification2DJiggle::get_stiffness);
ClassDB::bind_method(D_METHOD("set_mass", "mass"), &SkeletonModification2DJiggle::set_mass);
ClassDB::bind_method(D_METHOD("get_mass"), &SkeletonModification2DJiggle::get_mass);
ClassDB::bind_method(D_METHOD("set_damping", "damping"), &SkeletonModification2DJiggle::set_damping);
ClassDB::bind_method(D_METHOD("get_damping"), &SkeletonModification2DJiggle::get_damping);
ClassDB::bind_method(D_METHOD("set_use_gravity", "use_gravity"), &SkeletonModification2DJiggle::set_use_gravity);
ClassDB::bind_method(D_METHOD("get_use_gravity"), &SkeletonModification2DJiggle::get_use_gravity);
ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &SkeletonModification2DJiggle::set_gravity);
ClassDB::bind_method(D_METHOD("get_gravity"), &SkeletonModification2DJiggle::get_gravity);
ClassDB::bind_method(D_METHOD("set_use_colliders", "use_colliders"), &SkeletonModification2DJiggle::set_use_colliders);
ClassDB::bind_method(D_METHOD("get_use_colliders"), &SkeletonModification2DJiggle::get_use_colliders);
ClassDB::bind_method(D_METHOD("set_collision_mask", "collision_mask"), &SkeletonModification2DJiggle::set_collision_mask);
ClassDB::bind_method(D_METHOD("get_collision_mask"), &SkeletonModification2DJiggle::get_collision_mask);
// Jiggle joint data functions
ClassDB::bind_method(D_METHOD("set_jiggle_joint_bone2d_node", "joint_idx", "bone2d_node"), &SkeletonModification2DJiggle::set_jiggle_joint_bone2d_node);
ClassDB::bind_method(D_METHOD("get_jiggle_joint_bone2d_node", "joint_idx"), &SkeletonModification2DJiggle::get_jiggle_joint_bone2d_node);
ClassDB::bind_method(D_METHOD("set_jiggle_joint_bone_index", "joint_idx", "bone_idx"), &SkeletonModification2DJiggle::set_jiggle_joint_bone_index);
ClassDB::bind_method(D_METHOD("get_jiggle_joint_bone_index", "joint_idx"), &SkeletonModification2DJiggle::get_jiggle_joint_bone_index);
ClassDB::bind_method(D_METHOD("set_jiggle_joint_override", "joint_idx", "override"), &SkeletonModification2DJiggle::set_jiggle_joint_override);
ClassDB::bind_method(D_METHOD("get_jiggle_joint_override", "joint_idx"), &SkeletonModification2DJiggle::get_jiggle_joint_override);
ClassDB::bind_method(D_METHOD("set_jiggle_joint_stiffness", "joint_idx", "stiffness"), &SkeletonModification2DJiggle::set_jiggle_joint_stiffness);
ClassDB::bind_method(D_METHOD("get_jiggle_joint_stiffness", "joint_idx"), &SkeletonModification2DJiggle::get_jiggle_joint_stiffness);
ClassDB::bind_method(D_METHOD("set_jiggle_joint_mass", "joint_idx", "mass"), &SkeletonModification2DJiggle::set_jiggle_joint_mass);
ClassDB::bind_method(D_METHOD("get_jiggle_joint_mass", "joint_idx"), &SkeletonModification2DJiggle::get_jiggle_joint_mass);
ClassDB::bind_method(D_METHOD("set_jiggle_joint_damping", "joint_idx", "damping"), &SkeletonModification2DJiggle::set_jiggle_joint_damping);
ClassDB::bind_method(D_METHOD("get_jiggle_joint_damping", "joint_idx"), &SkeletonModification2DJiggle::get_jiggle_joint_damping);
ClassDB::bind_method(D_METHOD("set_jiggle_joint_use_gravity", "joint_idx", "use_gravity"), &SkeletonModification2DJiggle::set_jiggle_joint_use_gravity);
ClassDB::bind_method(D_METHOD("get_jiggle_joint_use_gravity", "joint_idx"), &SkeletonModification2DJiggle::get_jiggle_joint_use_gravity);
ClassDB::bind_method(D_METHOD("set_jiggle_joint_gravity", "joint_idx", "gravity"), &SkeletonModification2DJiggle::set_jiggle_joint_gravity);
ClassDB::bind_method(D_METHOD("get_jiggle_joint_gravity", "joint_idx"), &SkeletonModification2DJiggle::get_jiggle_joint_gravity);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node2D"), "set_target_node", "get_target_node");
ADD_PROPERTY(PropertyInfo(Variant::INT, "jiggle_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_jiggle_data_chain_length", "get_jiggle_data_chain_length");
ADD_GROUP("Default Joint Settings", "");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "stiffness"), "set_stiffness", "get_stiffness");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mass"), "set_mass", "get_mass");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "damping", PROPERTY_HINT_RANGE, "0, 1, 0.01"), "set_damping", "get_damping");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_gravity"), "set_use_gravity", "get_use_gravity");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "gravity"), "set_gravity", "get_gravity");
ADD_GROUP("", "");
}
SkeletonModification2DJiggle::SkeletonModification2DJiggle() {
stack = nullptr;
is_setup = false;
jiggle_data_chain = Vector<Jiggle_Joint_Data2D>();
stiffness = 3;
mass = 0.75;
damping = 0.75;
use_gravity = false;
gravity = Vector2(0, 6.0);
enabled = true;
editor_draw_gizmo = false; // Nothing to really show in a gizmo right now.
}
SkeletonModification2DJiggle::~SkeletonModification2DJiggle() {
}

View file

@ -0,0 +1,139 @@
/*************************************************************************/
/* skeleton_modification_2d_jiggle.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef SKELETONMODIFICATION2DJIGGLE_H
#define SKELETONMODIFICATION2DJIGGLE_H
#include "scene/2d/skeleton_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
///////////////////////////////////////
// SkeletonModification2DJIGGLE
///////////////////////////////////////
class SkeletonModification2DJiggle : public SkeletonModification2D {
GDCLASS(SkeletonModification2DJiggle, SkeletonModification2D);
private:
struct Jiggle_Joint_Data2D {
int bone_idx = -1;
NodePath bone2d_node;
ObjectID bone2d_node_cache;
bool override_defaults = false;
float stiffness = 3;
float mass = 0.75;
float damping = 0.75;
bool use_gravity = false;
Vector2 gravity = Vector2(0, 6.0);
Vector2 force = Vector2(0, 0);
Vector2 acceleration = Vector2(0, 0);
Vector2 velocity = Vector2(0, 0);
Vector2 last_position = Vector2(0, 0);
Vector2 dynamic_position = Vector2(0, 0);
Vector2 last_noncollision_position = Vector2(0, 0);
};
Vector<Jiggle_Joint_Data2D> jiggle_data_chain;
NodePath target_node;
ObjectID target_node_cache;
void update_target_cache();
float stiffness = 3;
float mass = 0.75;
float damping = 0.75;
bool use_gravity = false;
Vector2 gravity = Vector2(0, 6);
bool use_colliders = false;
uint32_t collision_mask = 1;
void jiggle_joint_update_bone2d_cache(int p_joint_idx);
void _execute_jiggle_joint(int p_joint_idx, Node2D *p_target, float p_delta);
void _update_jiggle_joint_data();
protected:
static void _bind_methods();
bool _set(const StringName &p_path, const Variant &p_value);
bool _get(const StringName &p_path, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
void _execute(float p_delta) override;
void _setup_modification(SkeletonModificationStack2D *p_stack) override;
void set_target_node(const NodePath &p_target_node);
NodePath get_target_node() const;
void set_stiffness(float p_stiffness);
float get_stiffness() const;
void set_mass(float p_mass);
float get_mass() const;
void set_damping(float p_damping);
float get_damping() const;
void set_use_gravity(bool p_use_gravity);
bool get_use_gravity() const;
void set_gravity(Vector2 p_gravity);
Vector2 get_gravity() const;
void set_use_colliders(bool p_use_colliders);
bool get_use_colliders() const;
void set_collision_mask(int p_mask);
int get_collision_mask() const;
int get_jiggle_data_chain_length();
void set_jiggle_data_chain_length(int p_new_length);
void set_jiggle_joint_bone2d_node(int p_joint_idx, const NodePath &p_target_node);
NodePath get_jiggle_joint_bone2d_node(int p_joint_idx) const;
void set_jiggle_joint_bone_index(int p_joint_idx, int p_bone_idx);
int get_jiggle_joint_bone_index(int p_joint_idx) const;
void set_jiggle_joint_override(int p_joint_idx, bool p_override);
bool get_jiggle_joint_override(int p_joint_idx) const;
void set_jiggle_joint_stiffness(int p_joint_idx, float p_stiffness);
float get_jiggle_joint_stiffness(int p_joint_idx) const;
void set_jiggle_joint_mass(int p_joint_idx, float p_mass);
float get_jiggle_joint_mass(int p_joint_idx) const;
void set_jiggle_joint_damping(int p_joint_idx, float p_damping);
float get_jiggle_joint_damping(int p_joint_idx) const;
void set_jiggle_joint_use_gravity(int p_joint_idx, bool p_use_gravity);
bool get_jiggle_joint_use_gravity(int p_joint_idx) const;
void set_jiggle_joint_gravity(int p_joint_idx, Vector2 p_gravity);
Vector2 get_jiggle_joint_gravity(int p_joint_idx) const;
SkeletonModification2DJiggle();
~SkeletonModification2DJiggle();
};
#endif // SKELETONMODIFICATION2DJIGGLE_H

View file

@ -0,0 +1,407 @@
/*************************************************************************/
/* skeleton_modification_2d_lookat.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "skeleton_modification_2d_lookat.h"
#include "scene/2d/skeleton_2d.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_settings.h"
#endif // TOOLS_ENABLED
bool SkeletonModification2DLookAt::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (path.begins_with("enable_constraint")) {
set_enable_constraint(p_value);
} else if (path.begins_with("constraint_angle_min")) {
set_constraint_angle_min(Math::deg2rad(float(p_value)));
} else if (path.begins_with("constraint_angle_max")) {
set_constraint_angle_max(Math::deg2rad(float(p_value)));
} else if (path.begins_with("constraint_angle_invert")) {
set_constraint_angle_invert(p_value);
} else if (path.begins_with("constraint_in_localspace")) {
set_constraint_in_localspace(p_value);
} else if (path.begins_with("additional_rotation")) {
set_additional_rotation(Math::deg2rad(float(p_value)));
}
#ifdef TOOLS_ENABLED
if (path.begins_with("editor/draw_gizmo")) {
set_editor_draw_gizmo(p_value);
}
#endif // TOOLS_ENABLED
return true;
}
bool SkeletonModification2DLookAt::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
if (path.begins_with("enable_constraint")) {
r_ret = get_enable_constraint();
} else if (path.begins_with("constraint_angle_min")) {
r_ret = Math::rad2deg(get_constraint_angle_min());
} else if (path.begins_with("constraint_angle_max")) {
r_ret = Math::rad2deg(get_constraint_angle_max());
} else if (path.begins_with("constraint_angle_invert")) {
r_ret = get_constraint_angle_invert();
} else if (path.begins_with("constraint_in_localspace")) {
r_ret = get_constraint_in_localspace();
} else if (path.begins_with("additional_rotation")) {
r_ret = Math::rad2deg(get_additional_rotation());
}
#ifdef TOOLS_ENABLED
if (path.begins_with("editor/draw_gizmo")) {
r_ret = get_editor_draw_gizmo();
}
#endif // TOOLS_ENABLED
return true;
}
void SkeletonModification2DLookAt::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::BOOL, "enable_constraint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
if (enable_constraint) {
p_list->push_back(PropertyInfo(Variant::FLOAT, "constraint_angle_min", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::FLOAT, "constraint_angle_max", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::BOOL, "constraint_angle_invert", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::BOOL, "constraint_in_localspace", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
p_list->push_back(PropertyInfo(Variant::FLOAT, "additional_rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
p_list->push_back(PropertyInfo(Variant::BOOL, "editor/draw_gizmo", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
#endif // TOOLS_ENABLED
}
void SkeletonModification2DLookAt::_execute(float p_delta) {
ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
"Modification is not setup and therefore cannot execute!");
if (!enabled) {
return;
}
if (target_node_cache.is_null()) {
WARN_PRINT_ONCE("Target cache is out of date. Attempting to update...");
update_target_cache();
return;
}
if (bone2d_node_cache.is_null() && !bone2d_node.is_empty()) {
update_bone2d_cache();
WARN_PRINT_ONCE("Bone2D node cache is out of date. Attempting to update...");
return;
}
if (target_node_reference == nullptr) {
target_node_reference = Object::cast_to<Node2D>(ObjectDB::get_instance(target_node_cache));
}
if (!target_node_reference || !target_node_reference->is_inside_tree()) {
ERR_PRINT_ONCE("Target node is not in the scene tree. Cannot execute modification!");
return;
}
if (bone_idx <= -1) {
ERR_PRINT_ONCE("Bone index is invalid. Cannot execute modification!");
return;
}
Bone2D *operation_bone = stack->skeleton->get_bone(bone_idx);
if (operation_bone == nullptr) {
ERR_PRINT_ONCE("bone_idx for modification does not point to a valid bone! Cannot execute modification");
return;
}
Transform2D operation_transform = operation_bone->get_global_transform();
Transform2D target_trans = target_node_reference->get_global_transform();
// Look at the target!
operation_transform = operation_transform.looking_at(target_trans.get_origin());
// Apply whatever scale it had prior to looking_at
operation_transform.set_scale(operation_bone->get_global_transform().get_scale());
// Account for the direction the bone faces in:
operation_transform.set_rotation(operation_transform.get_rotation() - operation_bone->get_bone_angle());
// Apply additional rotation
operation_transform.set_rotation(operation_transform.get_rotation() + additional_rotation);
// Apply constraints in globalspace:
if (enable_constraint && !constraint_in_localspace) {
operation_transform.set_rotation(clamp_angle(operation_transform.get_rotation(), constraint_angle_min, constraint_angle_max, constraint_angle_invert));
}
// Convert from a global transform to a local transform via the Bone2D node
operation_bone->set_global_transform(operation_transform);
operation_transform = operation_bone->get_transform();
// Apply constraints in localspace:
if (enable_constraint && constraint_in_localspace) {
operation_transform.set_rotation(clamp_angle(operation_transform.get_rotation(), constraint_angle_min, constraint_angle_max, constraint_angle_invert));
}
// Set the local pose override, and to make sure child bones are also updated, set the transform of the bone.
stack->skeleton->set_bone_local_pose_override(bone_idx, operation_transform, stack->strength, true);
operation_bone->set_transform(operation_transform);
}
void SkeletonModification2DLookAt::_setup_modification(SkeletonModificationStack2D *p_stack) {
stack = p_stack;
if (stack != nullptr) {
is_setup = true;
update_target_cache();
update_bone2d_cache();
}
}
void SkeletonModification2DLookAt::_draw_editor_gizmo() {
if (!enabled || !is_setup) {
return;
}
Bone2D *operation_bone = stack->skeleton->get_bone(bone_idx);
editor_draw_angle_constraints(operation_bone, constraint_angle_min, constraint_angle_max,
enable_constraint, constraint_in_localspace, constraint_angle_invert);
}
void SkeletonModification2DLookAt::update_bone2d_cache() {
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update Bone2D cache: modification is not properly setup!");
return;
}
bone2d_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(bone2d_node)) {
Node *node = stack->skeleton->get_node(bone2d_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update Bone2D cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update Bone2D cache: node is not in the scene tree!");
bone2d_node_cache = node->get_instance_id();
Bone2D *bone = Object::cast_to<Bone2D>(node);
if (bone) {
bone_idx = bone->get_index_in_skeleton();
} else {
ERR_FAIL_MSG("Error Bone2D cache: Nodepath to Bone2D is not a Bone2D node!");
}
// Set this to null so we update it
target_node_reference = nullptr;
}
}
}
}
void SkeletonModification2DLookAt::set_bone2d_node(const NodePath &p_target_node) {
bone2d_node = p_target_node;
update_bone2d_cache();
}
NodePath SkeletonModification2DLookAt::get_bone2d_node() const {
return bone2d_node;
}
int SkeletonModification2DLookAt::get_bone_index() const {
return bone_idx;
}
void SkeletonModification2DLookAt::set_bone_index(int p_bone_idx) {
ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
if (is_setup) {
if (stack->skeleton) {
ERR_FAIL_INDEX_MSG(p_bone_idx, stack->skeleton->get_bone_count(), "Passed-in Bone index is out of range!");
bone_idx = p_bone_idx;
bone2d_node_cache = stack->skeleton->get_bone(p_bone_idx)->get_instance_id();
bone2d_node = stack->skeleton->get_path_to(stack->skeleton->get_bone(p_bone_idx));
} else {
WARN_PRINT("Cannot verify the bone index for this modification...");
bone_idx = p_bone_idx;
}
} else {
WARN_PRINT("Cannot verify the bone index for this modification...");
bone_idx = p_bone_idx;
}
notify_property_list_changed();
}
void SkeletonModification2DLookAt::update_target_cache() {
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update target cache: modification is not properly setup!");
return;
}
target_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(target_node)) {
Node *node = stack->skeleton->get_node(target_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update target cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update target cache: node is not in the scene tree!");
target_node_cache = node->get_instance_id();
}
}
}
}
void SkeletonModification2DLookAt::set_target_node(const NodePath &p_target_node) {
target_node = p_target_node;
update_target_cache();
}
NodePath SkeletonModification2DLookAt::get_target_node() const {
return target_node;
}
float SkeletonModification2DLookAt::get_additional_rotation() const {
return additional_rotation;
}
void SkeletonModification2DLookAt::set_additional_rotation(float p_rotation) {
additional_rotation = p_rotation;
}
void SkeletonModification2DLookAt::set_enable_constraint(bool p_constraint) {
enable_constraint = p_constraint;
notify_property_list_changed();
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2DLookAt::get_enable_constraint() const {
return enable_constraint;
}
void SkeletonModification2DLookAt::set_constraint_angle_min(float p_angle_min) {
constraint_angle_min = p_angle_min;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
float SkeletonModification2DLookAt::get_constraint_angle_min() const {
return constraint_angle_min;
}
void SkeletonModification2DLookAt::set_constraint_angle_max(float p_angle_max) {
constraint_angle_max = p_angle_max;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
float SkeletonModification2DLookAt::get_constraint_angle_max() const {
return constraint_angle_max;
}
void SkeletonModification2DLookAt::set_constraint_angle_invert(bool p_invert) {
constraint_angle_invert = p_invert;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2DLookAt::get_constraint_angle_invert() const {
return constraint_angle_invert;
}
void SkeletonModification2DLookAt::set_constraint_in_localspace(bool p_constraint_in_localspace) {
constraint_in_localspace = p_constraint_in_localspace;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2DLookAt::get_constraint_in_localspace() const {
return constraint_in_localspace;
}
void SkeletonModification2DLookAt::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_bone2d_node", "bone2d_nodepath"), &SkeletonModification2DLookAt::set_bone2d_node);
ClassDB::bind_method(D_METHOD("get_bone2d_node"), &SkeletonModification2DLookAt::get_bone2d_node);
ClassDB::bind_method(D_METHOD("set_bone_index", "bone_idx"), &SkeletonModification2DLookAt::set_bone_index);
ClassDB::bind_method(D_METHOD("get_bone_index"), &SkeletonModification2DLookAt::get_bone_index);
ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification2DLookAt::set_target_node);
ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification2DLookAt::get_target_node);
ClassDB::bind_method(D_METHOD("set_additional_rotation", "rotation"), &SkeletonModification2DLookAt::set_additional_rotation);
ClassDB::bind_method(D_METHOD("get_additional_rotation"), &SkeletonModification2DLookAt::get_additional_rotation);
ClassDB::bind_method(D_METHOD("set_enable_constraint", "enable_constraint"), &SkeletonModification2DLookAt::set_enable_constraint);
ClassDB::bind_method(D_METHOD("get_enable_constraint"), &SkeletonModification2DLookAt::get_enable_constraint);
ClassDB::bind_method(D_METHOD("set_constraint_angle_min", "angle_min"), &SkeletonModification2DLookAt::set_constraint_angle_min);
ClassDB::bind_method(D_METHOD("get_constraint_angle_min"), &SkeletonModification2DLookAt::get_constraint_angle_min);
ClassDB::bind_method(D_METHOD("set_constraint_angle_max", "angle_max"), &SkeletonModification2DLookAt::set_constraint_angle_max);
ClassDB::bind_method(D_METHOD("get_constraint_angle_max"), &SkeletonModification2DLookAt::get_constraint_angle_max);
ClassDB::bind_method(D_METHOD("set_constraint_angle_invert", "invert"), &SkeletonModification2DLookAt::set_constraint_angle_invert);
ClassDB::bind_method(D_METHOD("get_constraint_angle_invert"), &SkeletonModification2DLookAt::get_constraint_angle_invert);
ADD_PROPERTY(PropertyInfo(Variant::INT, "bone_index"), "set_bone_index", "get_bone_index");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "bone2d_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Bone2D"), "set_bone2d_node", "get_bone2d_node");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node2D"), "set_target_node", "get_target_node");
}
SkeletonModification2DLookAt::SkeletonModification2DLookAt() {
stack = nullptr;
is_setup = false;
bone_idx = -1;
additional_rotation = 0;
enable_constraint = false;
constraint_angle_min = 0;
constraint_angle_max = Math_PI * 2;
constraint_angle_invert = false;
enabled = true;
editor_draw_gizmo = true;
}
SkeletonModification2DLookAt::~SkeletonModification2DLookAt() {
}

View file

@ -0,0 +1,100 @@
/*************************************************************************/
/* skeleton_modification_2d_lookat.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef SKELETONMODIFICATION2DLOOKAT_H
#define SKELETONMODIFICATION2DLOOKAT_H
#include "scene/2d/skeleton_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
///////////////////////////////////////
// SkeletonModification2DLookAt
///////////////////////////////////////
class SkeletonModification2DLookAt : public SkeletonModification2D {
GDCLASS(SkeletonModification2DLookAt, SkeletonModification2D);
private:
int bone_idx = -1;
NodePath bone2d_node;
ObjectID bone2d_node_cache;
NodePath target_node;
ObjectID target_node_cache;
Node2D *target_node_reference = nullptr;
float additional_rotation = 0;
bool enable_constraint = false;
float constraint_angle_min = 0;
float constraint_angle_max = (2.0 * Math_PI);
bool constraint_angle_invert = false;
bool constraint_in_localspace = true;
void update_bone2d_cache();
void update_target_cache();
protected:
static void _bind_methods();
bool _set(const StringName &p_path, const Variant &p_value);
bool _get(const StringName &p_path, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
void _execute(float p_delta) override;
void _setup_modification(SkeletonModificationStack2D *p_stack) override;
void _draw_editor_gizmo() override;
void set_bone2d_node(const NodePath &p_target_node);
NodePath get_bone2d_node() const;
void set_bone_index(int p_idx);
int get_bone_index() const;
void set_target_node(const NodePath &p_target_node);
NodePath get_target_node() const;
void set_additional_rotation(float p_rotation);
float get_additional_rotation() const;
void set_enable_constraint(bool p_constraint);
bool get_enable_constraint() const;
void set_constraint_angle_min(float p_angle_min);
float get_constraint_angle_min() const;
void set_constraint_angle_max(float p_angle_max);
float get_constraint_angle_max() const;
void set_constraint_angle_invert(bool p_invert);
bool get_constraint_angle_invert() const;
void set_constraint_in_localspace(bool p_constraint_in_localspace);
bool get_constraint_in_localspace() const;
SkeletonModification2DLookAt();
~SkeletonModification2DLookAt();
};
#endif // SKELETONMODIFICATION2DLOOKAT_H

View file

@ -0,0 +1,297 @@
/*************************************************************************/
/* skeleton_modification_2d_physicalbones.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "skeleton_modification_2d_physicalbones.h"
#include "scene/2d/physical_bone_2d.h"
#include "scene/2d/skeleton_2d.h"
bool SkeletonModification2DPhysicalBones::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
#ifdef TOOLS_ENABLED
// Exposes a way to fetch the PhysicalBone2D nodes from the Godot editor.
if (is_setup) {
if (Engine::get_singleton()->is_editor_hint()) {
if (path.begins_with("fetch_bones")) {
fetch_physical_bones();
notify_property_list_changed();
return true;
}
}
}
#endif //TOOLS_ENABLED
if (path.begins_with("joint_")) {
int which = path.get_slicec('_', 1).to_int();
String what = path.get_slicec('_', 2);
ERR_FAIL_INDEX_V(which, physical_bone_chain.size(), false);
if (what == "nodepath") {
set_physical_bone_node(which, p_value);
}
return true;
}
return true;
}
bool SkeletonModification2DPhysicalBones::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
if (path.begins_with("fetch_bones")) {
return true; // Do nothing!
}
}
#endif //TOOLS_ENABLED
if (path.begins_with("joint_")) {
int which = path.get_slicec('_', 1).to_int();
String what = path.get_slicec('_', 2);
ERR_FAIL_INDEX_V(which, physical_bone_chain.size(), false);
if (what == "nodepath") {
r_ret = get_physical_bone_node(which);
}
return true;
}
return true;
}
void SkeletonModification2DPhysicalBones::_get_property_list(List<PropertyInfo> *p_list) const {
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
p_list->push_back(PropertyInfo(Variant::BOOL, "fetch_bones", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
#endif //TOOLS_ENABLED
for (int i = 0; i < physical_bone_chain.size(); i++) {
String base_string = "joint_" + itos(i) + "_";
p_list->push_back(PropertyInfo(Variant::NODE_PATH, base_string + "nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "PhysicalBone2D", PROPERTY_USAGE_DEFAULT));
}
}
void SkeletonModification2DPhysicalBones::_execute(float p_delta) {
ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
"Modification is not setup and therefore cannot execute!");
if (!enabled) {
return;
}
if (_simulation_state_dirty) {
_update_simulation_state();
}
for (int i = 0; i < physical_bone_chain.size(); i++) {
PhysicalBone_Data2D bone_data = physical_bone_chain[i];
if (bone_data.physical_bone_node_cache.is_null()) {
WARN_PRINT_ONCE("PhysicalBone2D cache " + itos(i) + " is out of date. Attempting to update...");
_physical_bone_update_cache(i);
continue;
}
PhysicalBone2D *physical_bone = Object::cast_to<PhysicalBone2D>(ObjectDB::get_instance(bone_data.physical_bone_node_cache));
if (!physical_bone) {
ERR_PRINT_ONCE("PhysicalBone2D not found at index " + itos(i) + "!");
return;
}
if (physical_bone->get_bone2d_index() < 0 || physical_bone->get_bone2d_index() > stack->skeleton->get_bone_count()) {
ERR_PRINT_ONCE("PhysicalBone2D at index " + itos(i) + " has invalid Bone2D!");
return;
}
Bone2D *bone_2d = stack->skeleton->get_bone(physical_bone->get_bone2d_index());
if (physical_bone->get_simulate_physics() && !physical_bone->get_follow_bone_when_simulating()) {
bone_2d->set_global_transform(physical_bone->get_global_transform());
stack->skeleton->set_bone_local_pose_override(physical_bone->get_bone2d_index(), bone_2d->get_transform(), stack->strength, true);
}
}
}
void SkeletonModification2DPhysicalBones::_setup_modification(SkeletonModificationStack2D *p_stack) {
stack = p_stack;
if (stack) {
is_setup = true;
if (stack->skeleton) {
for (int i = 0; i < physical_bone_chain.size(); i++) {
_physical_bone_update_cache(i);
}
}
}
}
void SkeletonModification2DPhysicalBones::_physical_bone_update_cache(int p_joint_idx) {
ERR_FAIL_INDEX_MSG(p_joint_idx, physical_bone_chain.size(), "Cannot update PhysicalBone2D cache: joint index out of range!");
if (!is_setup || !stack) {
if (!stack) {
ERR_PRINT_ONCE("Cannot update PhysicalBone2D cache: modification is not properly setup!");
}
return;
}
physical_bone_chain.write[p_joint_idx].physical_bone_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(physical_bone_chain[p_joint_idx].physical_bone_node)) {
Node *node = stack->skeleton->get_node(physical_bone_chain[p_joint_idx].physical_bone_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update Physical Bone2D " + itos(p_joint_idx) + " cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update Physical Bone2D " + itos(p_joint_idx) + " cache: node is not in scene tree!");
physical_bone_chain.write[p_joint_idx].physical_bone_node_cache = node->get_instance_id();
}
}
}
}
int SkeletonModification2DPhysicalBones::get_physical_bone_chain_length() {
return physical_bone_chain.size();
}
void SkeletonModification2DPhysicalBones::set_physical_bone_chain_length(int p_length) {
ERR_FAIL_COND(p_length < 0);
physical_bone_chain.resize(p_length);
notify_property_list_changed();
}
void SkeletonModification2DPhysicalBones::fetch_physical_bones() {
ERR_FAIL_COND_MSG(!stack, "No modification stack found! Cannot fetch physical bones!");
ERR_FAIL_COND_MSG(!stack->skeleton, "No skeleton found! Cannot fetch physical bones!");
physical_bone_chain.clear();
List<Node *> node_queue = List<Node *>();
node_queue.push_back(stack->skeleton);
while (node_queue.size() > 0) {
Node *node_to_process = node_queue[0];
node_queue.pop_front();
if (node_to_process != nullptr) {
PhysicalBone2D *potential_bone = Object::cast_to<PhysicalBone2D>(node_to_process);
if (potential_bone) {
PhysicalBone_Data2D new_data = PhysicalBone_Data2D();
new_data.physical_bone_node = stack->skeleton->get_path_to(potential_bone);
new_data.physical_bone_node_cache = potential_bone->get_instance_id();
physical_bone_chain.push_back(new_data);
}
for (int i = 0; i < node_to_process->get_child_count(); i++) {
node_queue.push_back(node_to_process->get_child(i));
}
}
}
}
void SkeletonModification2DPhysicalBones::start_simulation(const TypedArray<StringName> &p_bones) {
_simulation_state_dirty = true;
_simulation_state_dirty_names = p_bones;
_simulation_state_dirty_process = true;
if (is_setup) {
_update_simulation_state();
}
}
void SkeletonModification2DPhysicalBones::stop_simulation(const TypedArray<StringName> &p_bones) {
_simulation_state_dirty = true;
_simulation_state_dirty_names = p_bones;
_simulation_state_dirty_process = false;
if (is_setup) {
_update_simulation_state();
}
}
void SkeletonModification2DPhysicalBones::_update_simulation_state() {
if (!_simulation_state_dirty) {
return;
}
_simulation_state_dirty = false;
if (_simulation_state_dirty_names.size() <= 0) {
for (int i = 0; i < physical_bone_chain.size(); i++) {
PhysicalBone2D *physical_bone = Object::cast_to<PhysicalBone2D>(stack->skeleton->get_node(physical_bone_chain[i].physical_bone_node));
if (!physical_bone) {
continue;
}
physical_bone->set_simulate_physics(_simulation_state_dirty_process);
}
} else {
for (int i = 0; i < physical_bone_chain.size(); i++) {
PhysicalBone2D *physical_bone = Object::cast_to<PhysicalBone2D>(ObjectDB::get_instance(physical_bone_chain[i].physical_bone_node_cache));
if (!physical_bone) {
continue;
}
if (_simulation_state_dirty_names.has(physical_bone->get_name())) {
physical_bone->set_simulate_physics(_simulation_state_dirty_process);
}
}
}
}
void SkeletonModification2DPhysicalBones::set_physical_bone_node(int p_joint_idx, const NodePath &p_nodepath) {
ERR_FAIL_INDEX_MSG(p_joint_idx, physical_bone_chain.size(), "Joint index out of range!");
physical_bone_chain.write[p_joint_idx].physical_bone_node = p_nodepath;
_physical_bone_update_cache(p_joint_idx);
}
NodePath SkeletonModification2DPhysicalBones::get_physical_bone_node(int p_joint_idx) const {
ERR_FAIL_INDEX_V_MSG(p_joint_idx, physical_bone_chain.size(), NodePath(), "Joint index out of range!");
return physical_bone_chain[p_joint_idx].physical_bone_node;
}
void SkeletonModification2DPhysicalBones::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_physical_bone_chain_length", "length"), &SkeletonModification2DPhysicalBones::set_physical_bone_chain_length);
ClassDB::bind_method(D_METHOD("get_physical_bone_chain_length"), &SkeletonModification2DPhysicalBones::get_physical_bone_chain_length);
ClassDB::bind_method(D_METHOD("set_physical_bone_node", "joint_idx", "physicalbone2d_node"), &SkeletonModification2DPhysicalBones::set_physical_bone_node);
ClassDB::bind_method(D_METHOD("get_physical_bone_node", "joint_idx"), &SkeletonModification2DPhysicalBones::get_physical_bone_node);
ClassDB::bind_method(D_METHOD("fetch_physical_bones"), &SkeletonModification2DPhysicalBones::fetch_physical_bones);
ClassDB::bind_method(D_METHOD("start_simulation", "bones"), &SkeletonModification2DPhysicalBones::start_simulation, DEFVAL(Array()));
ClassDB::bind_method(D_METHOD("stop_simulation", "bones"), &SkeletonModification2DPhysicalBones::stop_simulation, DEFVAL(Array()));
ADD_PROPERTY(PropertyInfo(Variant::INT, "physical_bone_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_physical_bone_chain_length", "get_physical_bone_chain_length");
}
SkeletonModification2DPhysicalBones::SkeletonModification2DPhysicalBones() {
stack = nullptr;
is_setup = false;
physical_bone_chain = Vector<PhysicalBone_Data2D>();
enabled = true;
editor_draw_gizmo = false; // Nothing to really show in a gizmo right now.
}
SkeletonModification2DPhysicalBones::~SkeletonModification2DPhysicalBones() {
}

View file

@ -0,0 +1,82 @@
/*************************************************************************/
/* skeleton_modification_2d_physicalbones.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef SKELETONMODIFICATION2DPHYSICALBONES_H
#define SKELETONMODIFICATION2DPHYSICALBONES_H
#include "scene/2d/skeleton_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
///////////////////////////////////////
// SkeletonModification2DJIGGLE
///////////////////////////////////////
class SkeletonModification2DPhysicalBones : public SkeletonModification2D {
GDCLASS(SkeletonModification2DPhysicalBones, SkeletonModification2D);
private:
struct PhysicalBone_Data2D {
NodePath physical_bone_node;
ObjectID physical_bone_node_cache;
};
Vector<PhysicalBone_Data2D> physical_bone_chain;
void _physical_bone_update_cache(int p_joint_idx);
bool _simulation_state_dirty = false;
TypedArray<StringName> _simulation_state_dirty_names;
bool _simulation_state_dirty_process;
void _update_simulation_state();
protected:
static void _bind_methods();
bool _get(const StringName &p_path, Variant &r_ret) const;
bool _set(const StringName &p_path, const Variant &p_value);
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
void _execute(float p_delta) override;
void _setup_modification(SkeletonModificationStack2D *p_stack) override;
int get_physical_bone_chain_length();
void set_physical_bone_chain_length(int p_new_length);
void set_physical_bone_node(int p_joint_idx, const NodePath &p_path);
NodePath get_physical_bone_node(int p_joint_idx) const;
void fetch_physical_bones();
void start_simulation(const TypedArray<StringName> &p_bones);
void stop_simulation(const TypedArray<StringName> &p_bones);
SkeletonModification2DPhysicalBones();
~SkeletonModification2DPhysicalBones();
};
#endif // SKELETONMODIFICATION2DPHYSICALBONES_H

View file

@ -0,0 +1,131 @@
/*************************************************************************/
/* skeleton_modification_2d_stackholder.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "skeleton_modification_2d_stackholder.h"
#include "scene/2d/skeleton_2d.h"
bool SkeletonModification2DStackHolder::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (path == "held_modification_stack") {
set_held_modification_stack(p_value);
}
#ifdef TOOLS_ENABLED
if (path == "editor/draw_gizmo") {
set_editor_draw_gizmo(p_value);
}
#endif // TOOLS_ENABLED
return true;
}
bool SkeletonModification2DStackHolder::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
if (path == "held_modification_stack") {
r_ret = get_held_modification_stack();
}
#ifdef TOOLS_ENABLED
if (path == "editor/draw_gizmo") {
r_ret = get_editor_draw_gizmo();
}
#endif // TOOLS_ENABLED
return true;
}
void SkeletonModification2DStackHolder::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::OBJECT, "held_modification_stack", PROPERTY_HINT_RESOURCE_TYPE, "SkeletonModificationStack2D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
p_list->push_back(PropertyInfo(Variant::BOOL, "editor/draw_gizmo", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
#endif // TOOLS_ENABLED
}
void SkeletonModification2DStackHolder::_execute(float p_delta) {
ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
"Modification is not setup and therefore cannot execute!");
if (held_modification_stack.is_valid()) {
held_modification_stack->execute(p_delta, execution_mode);
}
}
void SkeletonModification2DStackHolder::_setup_modification(SkeletonModificationStack2D *p_stack) {
stack = p_stack;
if (stack != nullptr) {
is_setup = true;
if (held_modification_stack.is_valid()) {
held_modification_stack->set_skeleton(stack->get_skeleton());
held_modification_stack->setup();
}
}
}
void SkeletonModification2DStackHolder::_draw_editor_gizmo() {
if (stack) {
if (held_modification_stack.is_valid()) {
held_modification_stack->draw_editor_gizmos();
}
}
}
void SkeletonModification2DStackHolder::set_held_modification_stack(Ref<SkeletonModificationStack2D> p_held_stack) {
held_modification_stack = p_held_stack;
if (is_setup && held_modification_stack.is_valid()) {
held_modification_stack->set_skeleton(stack->get_skeleton());
held_modification_stack->setup();
}
}
Ref<SkeletonModificationStack2D> SkeletonModification2DStackHolder::get_held_modification_stack() const {
return held_modification_stack;
}
void SkeletonModification2DStackHolder::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_held_modification_stack", "held_modification_stack"), &SkeletonModification2DStackHolder::set_held_modification_stack);
ClassDB::bind_method(D_METHOD("get_held_modification_stack"), &SkeletonModification2DStackHolder::get_held_modification_stack);
}
SkeletonModification2DStackHolder::SkeletonModification2DStackHolder() {
stack = nullptr;
is_setup = false;
enabled = true;
}
SkeletonModification2DStackHolder::~SkeletonModification2DStackHolder() {
}

View file

@ -0,0 +1,64 @@
/*************************************************************************/
/* skeleton_modification_2d_stackholder.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef SKELETONMODIFICATION2DSTACKHOLDER_H
#define SKELETONMODIFICATION2DSTACKHOLDER_H
#include "scene/2d/skeleton_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
///////////////////////////////////////
// SkeletonModification2DJIGGLE
///////////////////////////////////////
class SkeletonModification2DStackHolder : public SkeletonModification2D {
GDCLASS(SkeletonModification2DStackHolder, SkeletonModification2D);
protected:
static void _bind_methods();
bool _get(const StringName &p_path, Variant &r_ret) const;
bool _set(const StringName &p_path, const Variant &p_value);
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
Ref<SkeletonModificationStack2D> held_modification_stack;
void _execute(float p_delta) override;
void _setup_modification(SkeletonModificationStack2D *p_stack) override;
void _draw_editor_gizmo() override;
void set_held_modification_stack(Ref<SkeletonModificationStack2D> p_held_stack);
Ref<SkeletonModificationStack2D> get_held_modification_stack() const;
SkeletonModification2DStackHolder();
~SkeletonModification2DStackHolder();
};
#endif // SKELETONMODIFICATION2DSTACKHOLDER_H

View file

@ -0,0 +1,481 @@
/*************************************************************************/
/* skeleton_modification_2d_twoboneik.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "skeleton_modification_2d_twoboneik.h"
#include "scene/2d/skeleton_2d.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_settings.h"
#endif // TOOLS_ENABLED
bool SkeletonModification2DTwoBoneIK::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (path == "joint_one_bone_idx") {
set_joint_one_bone_idx(p_value);
} else if (path == "joint_one_bone2d_node") {
set_joint_one_bone2d_node(p_value);
} else if (path == "joint_two_bone_idx") {
set_joint_two_bone_idx(p_value);
} else if (path == "joint_two_bone2d_node") {
set_joint_two_bone2d_node(p_value);
}
#ifdef TOOLS_ENABLED
if (path.begins_with("editor/draw_gizmo")) {
set_editor_draw_gizmo(p_value);
} else if (path.begins_with("editor/draw_min_max")) {
set_editor_draw_min_max(p_value);
}
#endif // TOOLS_ENABLED
return true;
}
bool SkeletonModification2DTwoBoneIK::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
if (path == "joint_one_bone_idx") {
r_ret = get_joint_one_bone_idx();
} else if (path == "joint_one_bone2d_node") {
r_ret = get_joint_one_bone2d_node();
} else if (path == "joint_two_bone_idx") {
r_ret = get_joint_two_bone_idx();
} else if (path == "joint_two_bone2d_node") {
r_ret = get_joint_two_bone2d_node();
}
#ifdef TOOLS_ENABLED
if (path.begins_with("editor/draw_gizmo")) {
r_ret = get_editor_draw_gizmo();
} else if (path.begins_with("editor/draw_min_max")) {
r_ret = get_editor_draw_min_max();
}
#endif // TOOLS_ENABLED
return true;
}
void SkeletonModification2DTwoBoneIK::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::INT, "joint_one_bone_idx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::NODE_PATH, "joint_one_bone2d_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Bone2D", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::INT, "joint_two_bone_idx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::NODE_PATH, "joint_two_bone2d_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Bone2D", PROPERTY_USAGE_DEFAULT));
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
p_list->push_back(PropertyInfo(Variant::BOOL, "editor/draw_gizmo", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
p_list->push_back(PropertyInfo(Variant::BOOL, "editor/draw_min_max", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
}
#endif // TOOLS_ENABLED
}
void SkeletonModification2DTwoBoneIK::_execute(float p_delta) {
ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
"Modification is not setup and therefore cannot execute!");
if (!enabled) {
return;
}
if (target_node_cache.is_null()) {
WARN_PRINT_ONCE("Target cache is out of date. Attempting to update...");
update_target_cache();
return;
}
if (joint_one_bone2d_node_cache.is_null() && !joint_one_bone2d_node.is_empty()) {
WARN_PRINT_ONCE("Joint one Bone2D node cache is out of date. Attempting to update...");
update_joint_one_bone2d_cache();
}
if (joint_two_bone2d_node_cache.is_null() && !joint_two_bone2d_node.is_empty()) {
WARN_PRINT_ONCE("Joint two Bone2D node cache is out of date. Attempting to update...");
update_joint_two_bone2d_cache();
}
Node2D *target = Object::cast_to<Node2D>(ObjectDB::get_instance(target_node_cache));
if (!target || !target->is_inside_tree()) {
ERR_PRINT_ONCE("Target node is not in the scene tree. Cannot execute modification!");
return;
}
Bone2D *joint_one_bone = stack->skeleton->get_bone(joint_one_bone_idx);
if (joint_one_bone == nullptr) {
ERR_PRINT_ONCE("Joint one bone_idx does not point to a valid bone! Cannot execute modification!");
return;
}
Bone2D *joint_two_bone = stack->skeleton->get_bone(joint_two_bone_idx);
if (joint_two_bone == nullptr) {
ERR_PRINT_ONCE("Joint two bone_idx does not point to a valid bone! Cannot execute modification!");
return;
}
// Adopted from the links below:
// http://theorangeduck.com/page/simple-two-joint
// https://www.alanzucconi.com/2018/05/02/ik-2d-2/
// With modifications by TwistedTwigleg
Vector2 target_difference = target->get_global_transform().get_origin() - joint_one_bone->get_global_transform().get_origin();
float joint_one_to_target = target_difference.length();
float angle_atan = Math::atan2(target_difference.y, target_difference.x);
float bone_one_length = joint_one_bone->get_length() * MIN(joint_one_bone->get_global_scale().x, joint_one_bone->get_global_scale().y);
float bone_two_length = joint_two_bone->get_length() * MIN(joint_two_bone->get_global_scale().x, joint_two_bone->get_global_scale().y);
bool override_angles_due_to_out_of_range = false;
if (joint_one_to_target < target_minimum_distance) {
joint_one_to_target = target_minimum_distance;
}
if (joint_one_to_target > target_maximum_distance && target_maximum_distance > 0.0) {
joint_one_to_target = target_maximum_distance;
}
if (bone_one_length + bone_two_length < joint_one_to_target) {
override_angles_due_to_out_of_range = true;
}
if (!override_angles_due_to_out_of_range) {
float angle_0 = Math::acos(((joint_one_to_target * joint_one_to_target) + (bone_one_length * bone_one_length) - (bone_two_length * bone_two_length)) / (2.0 * joint_one_to_target * bone_one_length));
float angle_1 = Math::acos(((bone_two_length * bone_two_length) + (bone_one_length * bone_one_length) - (joint_one_to_target * joint_one_to_target)) / (2.0 * bone_two_length * bone_one_length));
if (flip_bend_direction) {
angle_0 = -angle_0;
angle_1 = -angle_1;
}
if (isnan(angle_0) || isnan(angle_1)) {
// We cannot solve for this angle! Do nothing to avoid setting the rotation (and scale) to NaN.
} else {
joint_one_bone->set_global_rotation(angle_atan - angle_0 - joint_one_bone->get_bone_angle());
joint_two_bone->set_rotation(-Math_PI - angle_1 - joint_two_bone->get_bone_angle() + joint_one_bone->get_bone_angle());
}
} else {
joint_one_bone->set_global_rotation(angle_atan - joint_one_bone->get_bone_angle());
joint_two_bone->set_global_rotation(angle_atan - joint_two_bone->get_bone_angle());
}
stack->skeleton->set_bone_local_pose_override(joint_one_bone_idx, joint_one_bone->get_transform(), stack->strength, true);
stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, joint_two_bone->get_transform(), stack->strength, true);
}
void SkeletonModification2DTwoBoneIK::_setup_modification(SkeletonModificationStack2D *p_stack) {
stack = p_stack;
if (stack) {
is_setup = true;
update_target_cache();
update_joint_one_bone2d_cache();
update_joint_two_bone2d_cache();
}
}
void SkeletonModification2DTwoBoneIK::_draw_editor_gizmo() {
if (!enabled || !is_setup) {
return;
}
Bone2D *operation_bone_one = stack->skeleton->get_bone(joint_one_bone_idx);
if (!operation_bone_one) {
return;
}
stack->skeleton->draw_set_transform(
stack->skeleton->get_global_transform().affine_inverse().xform(operation_bone_one->get_global_position()),
operation_bone_one->get_global_rotation() - stack->skeleton->get_global_rotation());
Color bone_ik_color = Color(1.0, 0.65, 0.0, 0.4);
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
bone_ik_color = EditorSettings::get_singleton()->get("editors/2d/bone_ik_color");
}
#endif // TOOLS_ENABLED
if (flip_bend_direction) {
float angle = -(Math_PI * 0.5) + operation_bone_one->get_bone_angle();
stack->skeleton->draw_line(Vector2(0, 0), Vector2(Math::cos(angle), sin(angle)) * (operation_bone_one->get_length() * 0.5), bone_ik_color, 2.0);
} else {
float angle = (Math_PI * 0.5) + operation_bone_one->get_bone_angle();
stack->skeleton->draw_line(Vector2(0, 0), Vector2(Math::cos(angle), sin(angle)) * (operation_bone_one->get_length() * 0.5), bone_ik_color, 2.0);
}
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
if (editor_draw_min_max) {
if (target_maximum_distance != 0.0 || target_minimum_distance != 0.0) {
Vector2 target_direction = Vector2(0, 1);
if (target_node_cache.is_valid()) {
stack->skeleton->draw_set_transform(Vector2(0, 0), 0.0);
Node2D *target = Object::cast_to<Node2D>(ObjectDB::get_instance(target_node_cache));
target_direction = operation_bone_one->get_global_position().direction_to(target->get_global_position());
}
stack->skeleton->draw_circle(target_direction * target_minimum_distance, 8, bone_ik_color);
stack->skeleton->draw_circle(target_direction * target_maximum_distance, 8, bone_ik_color);
stack->skeleton->draw_line(target_direction * target_minimum_distance, target_direction * target_maximum_distance, bone_ik_color, 2.0);
}
}
}
#endif // TOOLS_ENABLED
}
void SkeletonModification2DTwoBoneIK::update_target_cache() {
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update target cache: modification is not properly setup!");
return;
}
target_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(target_node)) {
Node *node = stack->skeleton->get_node(target_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update target cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update target cache: node is not in the scene tree!");
target_node_cache = node->get_instance_id();
}
}
}
}
void SkeletonModification2DTwoBoneIK::update_joint_one_bone2d_cache() {
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update joint one Bone2D cache: modification is not properly setup!");
return;
}
joint_one_bone2d_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(joint_one_bone2d_node)) {
Node *node = stack->skeleton->get_node(joint_one_bone2d_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update update joint one Bone2D cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update update joint one Bone2D cache: node is not in the scene tree!");
joint_one_bone2d_node_cache = node->get_instance_id();
Bone2D *bone = Object::cast_to<Bone2D>(node);
if (bone) {
joint_one_bone_idx = bone->get_index_in_skeleton();
} else {
ERR_FAIL_MSG("update joint one Bone2D cache: Nodepath to Bone2D is not a Bone2D node!");
}
}
}
}
}
void SkeletonModification2DTwoBoneIK::update_joint_two_bone2d_cache() {
if (!is_setup || !stack) {
ERR_PRINT_ONCE("Cannot update joint two Bone2D cache: modification is not properly setup!");
return;
}
joint_two_bone2d_node_cache = ObjectID();
if (stack->skeleton) {
if (stack->skeleton->is_inside_tree()) {
if (stack->skeleton->has_node(joint_two_bone2d_node)) {
Node *node = stack->skeleton->get_node(joint_two_bone2d_node);
ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
"Cannot update update joint two Bone2D cache: node is this modification's skeleton or cannot be found!");
ERR_FAIL_COND_MSG(!node->is_inside_tree(),
"Cannot update update joint two Bone2D cache: node is not in scene tree!");
joint_two_bone2d_node_cache = node->get_instance_id();
Bone2D *bone = Object::cast_to<Bone2D>(node);
if (bone) {
joint_two_bone_idx = bone->get_index_in_skeleton();
} else {
ERR_FAIL_MSG("update joint two Bone2D cache: Nodepath to Bone2D is not a Bone2D node!");
}
}
}
}
}
void SkeletonModification2DTwoBoneIK::set_target_node(const NodePath &p_target_node) {
target_node = p_target_node;
update_target_cache();
}
NodePath SkeletonModification2DTwoBoneIK::get_target_node() const {
return target_node;
}
void SkeletonModification2DTwoBoneIK::set_joint_one_bone2d_node(const NodePath &p_target_node) {
joint_one_bone2d_node = p_target_node;
update_joint_one_bone2d_cache();
notify_property_list_changed();
}
void SkeletonModification2DTwoBoneIK::set_target_minimum_distance(float p_distance) {
ERR_FAIL_COND_MSG(p_distance < 0, "Target minimum distance cannot be less than zero!");
target_minimum_distance = p_distance;
}
float SkeletonModification2DTwoBoneIK::get_target_minimum_distance() const {
return target_minimum_distance;
}
void SkeletonModification2DTwoBoneIK::set_target_maximum_distance(float p_distance) {
ERR_FAIL_COND_MSG(p_distance < 0, "Target maximum distance cannot be less than zero!");
target_maximum_distance = p_distance;
}
float SkeletonModification2DTwoBoneIK::get_target_maximum_distance() const {
return target_maximum_distance;
}
void SkeletonModification2DTwoBoneIK::set_flip_bend_direction(bool p_flip_direction) {
flip_bend_direction = p_flip_direction;
#ifdef TOOLS_ENABLED
if (stack && is_setup) {
stack->set_editor_gizmos_dirty(true);
}
#endif // TOOLS_ENABLED
}
bool SkeletonModification2DTwoBoneIK::get_flip_bend_direction() const {
return flip_bend_direction;
}
NodePath SkeletonModification2DTwoBoneIK::get_joint_one_bone2d_node() const {
return joint_one_bone2d_node;
}
void SkeletonModification2DTwoBoneIK::set_joint_two_bone2d_node(const NodePath &p_target_node) {
joint_two_bone2d_node = p_target_node;
update_joint_two_bone2d_cache();
notify_property_list_changed();
}
NodePath SkeletonModification2DTwoBoneIK::get_joint_two_bone2d_node() const {
return joint_two_bone2d_node;
}
void SkeletonModification2DTwoBoneIK::set_joint_one_bone_idx(int p_bone_idx) {
ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
if (is_setup) {
if (stack->skeleton) {
ERR_FAIL_INDEX_MSG(p_bone_idx, stack->skeleton->get_bone_count(), "Passed-in Bone index is out of range!");
joint_one_bone_idx = p_bone_idx;
joint_one_bone2d_node_cache = stack->skeleton->get_bone(p_bone_idx)->get_instance_id();
joint_one_bone2d_node = stack->skeleton->get_path_to(stack->skeleton->get_bone(p_bone_idx));
} else {
WARN_PRINT("TwoBoneIK: Cannot verify the joint bone index for joint one...");
joint_one_bone_idx = p_bone_idx;
}
} else {
WARN_PRINT("TwoBoneIK: Cannot verify the joint bone index for joint one...");
joint_one_bone_idx = p_bone_idx;
}
notify_property_list_changed();
}
int SkeletonModification2DTwoBoneIK::get_joint_one_bone_idx() const {
return joint_one_bone_idx;
}
void SkeletonModification2DTwoBoneIK::set_joint_two_bone_idx(int p_bone_idx) {
ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
if (is_setup) {
if (stack->skeleton) {
ERR_FAIL_INDEX_MSG(p_bone_idx, stack->skeleton->get_bone_count(), "Passed-in Bone index is out of range!");
joint_two_bone_idx = p_bone_idx;
joint_two_bone2d_node_cache = stack->skeleton->get_bone(p_bone_idx)->get_instance_id();
joint_two_bone2d_node = stack->skeleton->get_path_to(stack->skeleton->get_bone(p_bone_idx));
} else {
WARN_PRINT("TwoBoneIK: Cannot verify the joint bone index for joint two...");
joint_two_bone_idx = p_bone_idx;
}
} else {
WARN_PRINT("TwoBoneIK: Cannot verify the joint bone index for joint two...");
joint_two_bone_idx = p_bone_idx;
}
notify_property_list_changed();
}
int SkeletonModification2DTwoBoneIK::get_joint_two_bone_idx() const {
return joint_two_bone_idx;
}
#ifdef TOOLS_ENABLED
void SkeletonModification2DTwoBoneIK::set_editor_draw_min_max(bool p_draw) {
editor_draw_min_max = p_draw;
}
bool SkeletonModification2DTwoBoneIK::get_editor_draw_min_max() const {
return editor_draw_min_max;
}
#endif // TOOLS_ENABLED
void SkeletonModification2DTwoBoneIK::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification2DTwoBoneIK::set_target_node);
ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification2DTwoBoneIK::get_target_node);
ClassDB::bind_method(D_METHOD("set_target_minimum_distance", "minimum_distance"), &SkeletonModification2DTwoBoneIK::set_target_minimum_distance);
ClassDB::bind_method(D_METHOD("get_target_minimum_distance"), &SkeletonModification2DTwoBoneIK::get_target_minimum_distance);
ClassDB::bind_method(D_METHOD("set_target_maximum_distance", "maximum_distance"), &SkeletonModification2DTwoBoneIK::set_target_maximum_distance);
ClassDB::bind_method(D_METHOD("get_target_maximum_distance"), &SkeletonModification2DTwoBoneIK::get_target_maximum_distance);
ClassDB::bind_method(D_METHOD("set_flip_bend_direction", "flip_direction"), &SkeletonModification2DTwoBoneIK::set_flip_bend_direction);
ClassDB::bind_method(D_METHOD("get_flip_bend_direction"), &SkeletonModification2DTwoBoneIK::get_flip_bend_direction);
ClassDB::bind_method(D_METHOD("set_joint_one_bone2d_node", "bone2d_node"), &SkeletonModification2DTwoBoneIK::set_joint_one_bone2d_node);
ClassDB::bind_method(D_METHOD("get_joint_one_bone2d_node"), &SkeletonModification2DTwoBoneIK::get_joint_one_bone2d_node);
ClassDB::bind_method(D_METHOD("set_joint_one_bone_idx", "bone_idx"), &SkeletonModification2DTwoBoneIK::set_joint_one_bone_idx);
ClassDB::bind_method(D_METHOD("get_joint_one_bone_idx"), &SkeletonModification2DTwoBoneIK::get_joint_one_bone_idx);
ClassDB::bind_method(D_METHOD("set_joint_two_bone2d_node", "bone2d_node"), &SkeletonModification2DTwoBoneIK::set_joint_two_bone2d_node);
ClassDB::bind_method(D_METHOD("get_joint_two_bone2d_node"), &SkeletonModification2DTwoBoneIK::get_joint_two_bone2d_node);
ClassDB::bind_method(D_METHOD("set_joint_two_bone_idx", "bone_idx"), &SkeletonModification2DTwoBoneIK::set_joint_two_bone_idx);
ClassDB::bind_method(D_METHOD("get_joint_two_bone_idx"), &SkeletonModification2DTwoBoneIK::get_joint_two_bone_idx);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node2D"), "set_target_node", "get_target_node");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "target_minimum_distance", PROPERTY_HINT_RANGE, "0, 100000000, 0.01"), "set_target_minimum_distance", "get_target_minimum_distance");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "target_maximum_distance", PROPERTY_HINT_NONE, "0, 100000000, 0.01"), "set_target_maximum_distance", "get_target_maximum_distance");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_bend_direction", PROPERTY_HINT_NONE, ""), "set_flip_bend_direction", "get_flip_bend_direction");
ADD_GROUP("", "");
}
SkeletonModification2DTwoBoneIK::SkeletonModification2DTwoBoneIK() {
stack = nullptr;
is_setup = false;
enabled = true;
editor_draw_gizmo = true;
}
SkeletonModification2DTwoBoneIK::~SkeletonModification2DTwoBoneIK() {
}

View file

@ -0,0 +1,107 @@
/*************************************************************************/
/* skeleton_modification_2d_twoboneik.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef SKELETONMODIFICATION2DTWOBONEIK_H
#define SKELETONMODIFICATION2DTWOBONEIK_H
#include "scene/2d/skeleton_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
///////////////////////////////////////
// SkeletonModification2DJIGGLE
///////////////////////////////////////
class SkeletonModification2DTwoBoneIK : public SkeletonModification2D {
GDCLASS(SkeletonModification2DTwoBoneIK, SkeletonModification2D);
private:
NodePath target_node;
ObjectID target_node_cache;
float target_minimum_distance = 0;
float target_maximum_distance = 0;
bool flip_bend_direction = false;
NodePath joint_one_bone2d_node;
ObjectID joint_one_bone2d_node_cache;
int joint_one_bone_idx = -1;
NodePath joint_two_bone2d_node;
ObjectID joint_two_bone2d_node_cache;
int joint_two_bone_idx = -1;
#ifdef TOOLS_ENABLED
bool editor_draw_min_max = false;
#endif // TOOLS_ENABLED
void update_target_cache();
void update_joint_one_bone2d_cache();
void update_joint_two_bone2d_cache();
protected:
static void _bind_methods();
bool _get(const StringName &p_path, Variant &r_ret) const;
bool _set(const StringName &p_path, const Variant &p_value);
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
void _execute(float p_delta) override;
void _setup_modification(SkeletonModificationStack2D *p_stack) override;
void _draw_editor_gizmo() override;
void set_target_node(const NodePath &p_target_node);
NodePath get_target_node() const;
void set_target_minimum_distance(float p_minimum_distance);
float get_target_minimum_distance() const;
void set_target_maximum_distance(float p_maximum_distance);
float get_target_maximum_distance() const;
void set_flip_bend_direction(bool p_flip_direction);
bool get_flip_bend_direction() const;
void set_joint_one_bone2d_node(const NodePath &p_node);
NodePath get_joint_one_bone2d_node() const;
void set_joint_one_bone_idx(int p_bone_idx);
int get_joint_one_bone_idx() const;
void set_joint_two_bone2d_node(const NodePath &p_node);
NodePath get_joint_two_bone2d_node() const;
void set_joint_two_bone_idx(int p_bone_idx);
int get_joint_two_bone_idx() const;
#ifdef TOOLS_ENABLED
void set_editor_draw_min_max(bool p_draw);
bool get_editor_draw_min_max() const;
#endif // TOOLS_ENABLED
SkeletonModification2DTwoBoneIK();
~SkeletonModification2DTwoBoneIK();
};
#endif // SKELETONMODIFICATION2DTWOBONEIK_H

View file

@ -0,0 +1,267 @@
/*************************************************************************/
/* skeleton_modification_stack_2d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "skeleton_modification_stack_2d.h"
#include "scene/2d/skeleton_2d.h"
void SkeletonModificationStack2D::_get_property_list(List<PropertyInfo> *p_list) const {
for (int i = 0; i < modifications.size(); i++) {
p_list->push_back(
PropertyInfo(Variant::OBJECT, "modifications/" + itos(i),
PROPERTY_HINT_RESOURCE_TYPE,
"SkeletonModification2D",
PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
}
}
bool SkeletonModificationStack2D::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (path.begins_with("modifications/")) {
int mod_idx = path.get_slicec('/', 1).to_int();
set_modification(mod_idx, p_value);
return true;
}
return true;
}
bool SkeletonModificationStack2D::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
if (path.begins_with("modifications/")) {
int mod_idx = path.get_slicec('/', 1).to_int();
r_ret = get_modification(mod_idx);
return true;
}
return true;
}
void SkeletonModificationStack2D::setup() {
if (is_setup) {
return;
}
if (skeleton != nullptr) {
is_setup = true;
for (int i = 0; i < modifications.size(); i++) {
if (!modifications[i].is_valid()) {
continue;
}
modifications.get(i)->_setup_modification(this);
}
#ifdef TOOLS_ENABLED
set_editor_gizmos_dirty(true);
#endif // TOOLS_ENABLED
} else {
WARN_PRINT("Cannot setup SkeletonModificationStack2D: no Skeleton2D set!");
}
}
void SkeletonModificationStack2D::execute(float p_delta, int p_execution_mode) {
ERR_FAIL_COND_MSG(!is_setup || skeleton == nullptr || is_queued_for_deletion(),
"Modification stack is not properly setup and therefore cannot execute!");
if (!skeleton->is_inside_tree()) {
ERR_PRINT_ONCE("Skeleton is not inside SceneTree! Cannot execute modification!");
return;
}
if (!enabled) {
return;
}
for (int i = 0; i < modifications.size(); i++) {
if (!modifications[i].is_valid()) {
continue;
}
if (modifications[i]->get_execution_mode() == p_execution_mode) {
modifications.get(i)->_execute(p_delta);
}
}
}
void SkeletonModificationStack2D::draw_editor_gizmos() {
if (!is_setup) {
return;
}
if (editor_gizmo_dirty) {
for (int i = 0; i < modifications.size(); i++) {
if (!modifications[i].is_valid()) {
continue;
}
if (modifications[i]->editor_draw_gizmo) {
modifications.get(i)->_draw_editor_gizmo();
}
}
skeleton->draw_set_transform(Vector2(0, 0));
editor_gizmo_dirty = false;
}
}
void SkeletonModificationStack2D::set_editor_gizmos_dirty(bool p_dirty) {
if (!is_setup) {
return;
}
if (!editor_gizmo_dirty && p_dirty) {
editor_gizmo_dirty = p_dirty;
if (skeleton) {
skeleton->update();
}
} else {
editor_gizmo_dirty = p_dirty;
}
}
void SkeletonModificationStack2D::enable_all_modifications(bool p_enabled) {
for (int i = 0; i < modifications.size(); i++) {
if (!modifications[i].is_valid()) {
continue;
}
modifications.get(i)->set_enabled(p_enabled);
}
}
Ref<SkeletonModification2D> SkeletonModificationStack2D::get_modification(int p_mod_idx) const {
ERR_FAIL_INDEX_V(p_mod_idx, modifications.size(), nullptr);
return modifications[p_mod_idx];
}
void SkeletonModificationStack2D::add_modification(Ref<SkeletonModification2D> p_mod) {
p_mod->_setup_modification(this);
modifications.push_back(p_mod);
#ifdef TOOLS_ENABLED
set_editor_gizmos_dirty(true);
#endif // TOOLS_ENABLED
}
void SkeletonModificationStack2D::delete_modification(int p_mod_idx) {
ERR_FAIL_INDEX(p_mod_idx, modifications.size());
modifications.remove(p_mod_idx);
#ifdef TOOLS_ENABLED
set_editor_gizmos_dirty(true);
#endif // TOOLS_ENABLED
}
void SkeletonModificationStack2D::set_modification(int p_mod_idx, Ref<SkeletonModification2D> p_mod) {
ERR_FAIL_INDEX(p_mod_idx, modifications.size());
if (p_mod == nullptr) {
modifications.insert(p_mod_idx, nullptr);
} else {
p_mod->_setup_modification(this);
modifications.insert(p_mod_idx, p_mod);
}
#ifdef TOOLS_ENABLED
set_editor_gizmos_dirty(true);
#endif // TOOLS_ENABLED
}
void SkeletonModificationStack2D::set_modification_count(int p_count) {
modifications.resize(p_count);
notify_property_list_changed();
#ifdef TOOLS_ENABLED
set_editor_gizmos_dirty(true);
#endif // TOOLS_ENABLED
}
int SkeletonModificationStack2D::get_modification_count() const {
return modifications.size();
}
void SkeletonModificationStack2D::set_skeleton(Skeleton2D *p_skeleton) {
skeleton = p_skeleton;
}
Skeleton2D *SkeletonModificationStack2D::get_skeleton() const {
return skeleton;
}
bool SkeletonModificationStack2D::get_is_setup() const {
return is_setup;
}
void SkeletonModificationStack2D::set_enabled(bool p_enabled) {
enabled = p_enabled;
}
bool SkeletonModificationStack2D::get_enabled() const {
return enabled;
}
void SkeletonModificationStack2D::set_strength(float p_strength) {
ERR_FAIL_COND_MSG(p_strength < 0, "Strength cannot be less than zero!");
ERR_FAIL_COND_MSG(p_strength > 1, "Strength cannot be more than one!");
strength = p_strength;
}
float SkeletonModificationStack2D::get_strength() const {
return strength;
}
void SkeletonModificationStack2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("setup"), &SkeletonModificationStack2D::setup);
ClassDB::bind_method(D_METHOD("execute", "delta", "execution_mode"), &SkeletonModificationStack2D::execute);
ClassDB::bind_method(D_METHOD("enable_all_modifications", "enabled"), &SkeletonModificationStack2D::enable_all_modifications);
ClassDB::bind_method(D_METHOD("get_modification", "mod_idx"), &SkeletonModificationStack2D::get_modification);
ClassDB::bind_method(D_METHOD("add_modification", "modification"), &SkeletonModificationStack2D::add_modification);
ClassDB::bind_method(D_METHOD("delete_modification", "mod_idx"), &SkeletonModificationStack2D::delete_modification);
ClassDB::bind_method(D_METHOD("set_modification", "mod_idx", "modification"), &SkeletonModificationStack2D::set_modification);
ClassDB::bind_method(D_METHOD("set_modification_count"), &SkeletonModificationStack2D::set_modification_count);
ClassDB::bind_method(D_METHOD("get_modification_count"), &SkeletonModificationStack2D::get_modification_count);
ClassDB::bind_method(D_METHOD("get_is_setup"), &SkeletonModificationStack2D::get_is_setup);
ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &SkeletonModificationStack2D::set_enabled);
ClassDB::bind_method(D_METHOD("get_enabled"), &SkeletonModificationStack2D::get_enabled);
ClassDB::bind_method(D_METHOD("set_strength", "strength"), &SkeletonModificationStack2D::set_strength);
ClassDB::bind_method(D_METHOD("get_strength"), &SkeletonModificationStack2D::get_strength);
ClassDB::bind_method(D_METHOD("get_skeleton"), &SkeletonModificationStack2D::get_skeleton);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "get_enabled");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "strength", PROPERTY_HINT_RANGE, "0, 1, 0.001"), "set_strength", "get_strength");
ADD_PROPERTY(PropertyInfo(Variant::INT, "modification_count", PROPERTY_HINT_RANGE, "0, 100, 1"), "set_modification_count", "get_modification_count");
}
SkeletonModificationStack2D::SkeletonModificationStack2D() {
}

View file

@ -0,0 +1,99 @@
/*************************************************************************/
/* skeleton_modification_stack_2d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef SKELETONMODIFICATIONSTACK2D_H
#define SKELETONMODIFICATIONSTACK2D_H
#include "scene/2d/skeleton_2d.h"
#include "scene/resources/skeleton_modification_2d.h"
///////////////////////////////////////
// SkeletonModificationStack2D
///////////////////////////////////////
class Skeleton2D;
class SkeletonModification2D;
class Bone2D;
class SkeletonModificationStack2D : public Resource {
GDCLASS(SkeletonModificationStack2D, Resource);
friend class Skeleton2D;
friend class SkeletonModification2D;
protected:
static void _bind_methods();
void _get_property_list(List<PropertyInfo> *p_list) const;
bool _set(const StringName &p_path, const Variant &p_value);
bool _get(const StringName &p_path, Variant &r_ret) const;
public:
Skeleton2D *skeleton = nullptr;
bool is_setup = false;
bool enabled = false;
float strength = 1.0;
enum EXECUTION_MODE {
execution_mode_process,
execution_mode_physics_process
};
Vector<Ref<SkeletonModification2D>> modifications = Vector<Ref<SkeletonModification2D>>();
void setup();
void execute(float p_delta, int p_execution_mode);
bool editor_gizmo_dirty = false;
void draw_editor_gizmos();
void set_editor_gizmos_dirty(bool p_dirty);
void enable_all_modifications(bool p_enable);
Ref<SkeletonModification2D> get_modification(int p_mod_idx) const;
void add_modification(Ref<SkeletonModification2D> p_mod);
void delete_modification(int p_mod_idx);
void set_modification(int p_mod_idx, Ref<SkeletonModification2D> p_mod);
void set_modification_count(int p_count);
int get_modification_count() const;
void set_skeleton(Skeleton2D *p_skeleton);
Skeleton2D *get_skeleton() const;
bool get_is_setup() const;
void set_enabled(bool p_enabled);
bool get_enabled() const;
void set_strength(float p_strength);
float get_strength() const;
SkeletonModificationStack2D();
};
#endif // SKELETONMODIFICATION2D_H