Path: blob/master/modules/godot_physics_2d/godot_joints_2d.cpp
10277 views
/**************************************************************************/1/* godot_joints_2d.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "godot_joints_2d.h"3132#include "godot_space_2d.h"3334//based on chipmunk joint constraints3536/* Copyright (c) 2007 Scott Lembcke37*38* Permission is hereby granted, free of charge, to any person obtaining a copy39* of this software and associated documentation files (the "Software"), to deal40* in the Software without restriction, including without limitation the rights41* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell42* copies of the Software, and to permit persons to whom the Software is43* furnished to do so, subject to the following conditions:44*45* The above copyright notice and this permission notice shall be included in46* all copies or substantial portions of the Software.47*48* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR49* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,50* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE51* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER52* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,53* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE54* SOFTWARE.55*/5657void GodotJoint2D::copy_settings_from(GodotJoint2D *p_joint) {58set_self(p_joint->get_self());59set_max_force(p_joint->get_max_force());60set_bias(p_joint->get_bias());61set_max_bias(p_joint->get_max_bias());62disable_collisions_between_bodies(p_joint->is_disabled_collisions_between_bodies());63}6465static inline real_t k_scalar(GodotBody2D *a, GodotBody2D *b, const Vector2 &rA, const Vector2 &rB, const Vector2 &n) {66real_t value = 0.0;6768{69value += a->get_inv_mass();70real_t rcn = (rA - a->get_center_of_mass()).cross(n);71value += a->get_inv_inertia() * rcn * rcn;72}7374if (b) {75value += b->get_inv_mass();76real_t rcn = (rB - b->get_center_of_mass()).cross(n);77value += b->get_inv_inertia() * rcn * rcn;78}7980return value;81}8283static inline Vector284relative_velocity(GodotBody2D *a, GodotBody2D *b, Vector2 rA, Vector2 rB) {85Vector2 sum = a->get_linear_velocity() - (rA - a->get_center_of_mass()).orthogonal() * a->get_angular_velocity();86if (b) {87return (b->get_linear_velocity() - (rB - b->get_center_of_mass()).orthogonal() * b->get_angular_velocity()) - sum;88} else {89return -sum;90}91}9293static inline real_t94normal_relative_velocity(GodotBody2D *a, GodotBody2D *b, Vector2 rA, Vector2 rB, Vector2 n) {95return relative_velocity(a, b, rA, rB).dot(n);96}9798bool GodotPinJoint2D::setup(real_t p_step) {99dynamic_A = (A->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC);100dynamic_B = (B->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC);101102if (!dynamic_A && !dynamic_B) {103return false;104}105106GodotSpace2D *space = A->get_space();107ERR_FAIL_NULL_V(space, false);108109rA = A->get_transform().basis_xform(anchor_A);110rB = B ? B->get_transform().basis_xform(anchor_B) : anchor_B;111112real_t B_inv_mass = B ? B->get_inv_mass() : 0.0;113114Transform2D K1;115K1[0].x = A->get_inv_mass() + B_inv_mass;116K1[1].x = 0.0f;117K1[0].y = 0.0f;118K1[1].y = A->get_inv_mass() + B_inv_mass;119120Vector2 r1 = rA - A->get_center_of_mass();121122Transform2D K2;123K2[0].x = A->get_inv_inertia() * r1.y * r1.y;124K2[1].x = -A->get_inv_inertia() * r1.x * r1.y;125K2[0].y = -A->get_inv_inertia() * r1.x * r1.y;126K2[1].y = A->get_inv_inertia() * r1.x * r1.x;127128Transform2D K;129K[0] = K1[0] + K2[0];130K[1] = K1[1] + K2[1];131132if (B) {133Vector2 r2 = rB - B->get_center_of_mass();134135Transform2D K3;136K3[0].x = B->get_inv_inertia() * r2.y * r2.y;137K3[1].x = -B->get_inv_inertia() * r2.x * r2.y;138K3[0].y = -B->get_inv_inertia() * r2.x * r2.y;139K3[1].y = B->get_inv_inertia() * r2.x * r2.x;140141K[0] += K3[0];142K[1] += K3[1];143}144145K[0].x += softness;146K[1].y += softness;147148M = K.affine_inverse();149150Vector2 gA = rA + A->get_transform().get_origin();151Vector2 gB = B ? rB + B->get_transform().get_origin() : rB;152153Vector2 delta = gB - gA;154155bias = delta * -(get_bias() == 0 ? space->get_constraint_bias() : get_bias()) * (1.0 / p_step);156157// Compute max impulse.158jn_max = get_max_force() * p_step;159160return true;161}162163inline Vector2 custom_cross(const Vector2 &p_vec, real_t p_other) {164return Vector2(p_other * p_vec.y, -p_other * p_vec.x);165}166167bool GodotPinJoint2D::pre_solve(real_t p_step) {168// Apply accumulated impulse.169if (dynamic_A) {170A->apply_impulse(-P, rA);171}172if (B && dynamic_B) {173B->apply_impulse(P, rB);174}175// Angle limits joint pre_solve step taken from https://github.com/slembcke/Chipmunk2D/blob/d0239ef4599b3688a5a336373f7d0a68426414ba/src/cpRotaryLimitJoint.c176real_t i_sum_local = A->get_inv_inertia();177if (B) {178i_sum_local += B->get_inv_inertia();179}180i_sum = 1.0 / (i_sum_local);181if (angular_limit_enabled && B) {182Vector2 diff_vector = B->get_transform().get_origin() - A->get_transform().get_origin();183diff_vector = diff_vector.rotated(-initial_angle);184real_t dist = diff_vector.angle();185real_t pdist = 0.0;186if (dist > angular_limit_upper) {187pdist = dist - angular_limit_upper;188} else if (dist < angular_limit_lower) {189pdist = dist - angular_limit_lower;190}191real_t error_bias = Math::pow(1.0 - 0.15, 60.0);192// Calculate bias velocity.193bias_velocity = -CLAMP((-1.0 - Math::pow(error_bias, p_step)) * pdist / p_step, -get_max_bias(), get_max_bias());194// If the bias velocity is 0, the joint is not at a limit.195if (bias_velocity >= -CMP_EPSILON && bias_velocity <= CMP_EPSILON) {196j_acc = 0;197is_joint_at_limit = false;198} else {199is_joint_at_limit = true;200}201} else {202bias_velocity = 0.0;203}204205return true;206}207208void GodotPinJoint2D::solve(real_t p_step) {209// Compute relative velocity.210Vector2 vA = A->get_linear_velocity() - custom_cross(rA - A->get_center_of_mass(), A->get_angular_velocity());211212Vector2 rel_vel;213if (B) {214rel_vel = B->get_linear_velocity() - custom_cross(rB - B->get_center_of_mass(), B->get_angular_velocity()) - vA;215} else {216rel_vel = -vA;217}218// Angle limits joint solve step taken from https://github.com/slembcke/Chipmunk2D/blob/d0239ef4599b3688a5a336373f7d0a68426414ba/src/cpRotaryLimitJoint.c219if ((angular_limit_enabled || motor_enabled) && B) {220// Compute relative rotational velocity.221real_t wr = B->get_angular_velocity() - A->get_angular_velocity();222// Motor solve part taken from https://github.com/slembcke/Chipmunk2D/blob/d0239ef4599b3688a5a336373f7d0a68426414ba/src/cpSimpleMotor.c223if (motor_enabled) {224wr -= motor_target_velocity;225}226real_t j_max = jn_max;227228// Compute normal impulse.229real_t j = -(bias_velocity + wr) * i_sum;230real_t j_old = j_acc;231// Only enable the limits if we have to.232if (angular_limit_enabled && is_joint_at_limit) {233if (bias_velocity < 0.0) {234j_acc = CLAMP(j_old + j, 0.0, j_max);235} else {236j_acc = CLAMP(j_old + j, -j_max, 0.0);237}238} else {239j_acc = CLAMP(j_old + j, -j_max, j_max);240}241j = j_acc - j_old;242A->apply_torque_impulse(-j * A->get_inv_inertia());243B->apply_torque_impulse(j * B->get_inv_inertia());244}245246Vector2 impulse = M.basis_xform(bias - rel_vel - Vector2(softness, softness) * P);247248if (dynamic_A) {249A->apply_impulse(-impulse, rA);250}251if (B && dynamic_B) {252B->apply_impulse(impulse, rB);253}254255P += impulse;256}257258void GodotPinJoint2D::set_param(PhysicsServer2D::PinJointParam p_param, real_t p_value) {259switch (p_param) {260case PhysicsServer2D::PIN_JOINT_SOFTNESS: {261softness = p_value;262} break;263case PhysicsServer2D::PIN_JOINT_LIMIT_UPPER: {264angular_limit_upper = p_value;265} break;266case PhysicsServer2D::PIN_JOINT_LIMIT_LOWER: {267angular_limit_lower = p_value;268} break;269case PhysicsServer2D::PIN_JOINT_MOTOR_TARGET_VELOCITY: {270motor_target_velocity = p_value;271} break;272}273}274275real_t GodotPinJoint2D::get_param(PhysicsServer2D::PinJointParam p_param) const {276switch (p_param) {277case PhysicsServer2D::PIN_JOINT_SOFTNESS: {278return softness;279}280case PhysicsServer2D::PIN_JOINT_LIMIT_UPPER: {281return angular_limit_upper;282}283case PhysicsServer2D::PIN_JOINT_LIMIT_LOWER: {284return angular_limit_lower;285}286case PhysicsServer2D::PIN_JOINT_MOTOR_TARGET_VELOCITY: {287return motor_target_velocity;288}289}290ERR_FAIL_V(0);291}292293void GodotPinJoint2D::set_flag(PhysicsServer2D::PinJointFlag p_flag, bool p_enabled) {294switch (p_flag) {295case PhysicsServer2D::PIN_JOINT_FLAG_ANGULAR_LIMIT_ENABLED: {296angular_limit_enabled = p_enabled;297} break;298case PhysicsServer2D::PIN_JOINT_FLAG_MOTOR_ENABLED: {299motor_enabled = p_enabled;300} break;301}302}303304bool GodotPinJoint2D::get_flag(PhysicsServer2D::PinJointFlag p_flag) const {305switch (p_flag) {306case PhysicsServer2D::PIN_JOINT_FLAG_ANGULAR_LIMIT_ENABLED: {307return angular_limit_enabled;308}309case PhysicsServer2D::PIN_JOINT_FLAG_MOTOR_ENABLED: {310return motor_enabled;311}312}313ERR_FAIL_V(false);314}315316GodotPinJoint2D::GodotPinJoint2D(const Vector2 &p_pos, GodotBody2D *p_body_a, GodotBody2D *p_body_b) :317GodotJoint2D(_arr, p_body_b ? 2 : 1) {318A = p_body_a;319B = p_body_b;320anchor_A = p_body_a->get_inv_transform().xform(p_pos);321anchor_B = p_body_b ? p_body_b->get_inv_transform().xform(p_pos) : p_pos;322323p_body_a->add_constraint(this, 0);324if (p_body_b) {325p_body_b->add_constraint(this, 1);326initial_angle = A->get_transform().get_origin().angle_to_point(B->get_transform().get_origin());327}328}329330//////////////////////////////////////////////331//////////////////////////////////////////////332//////////////////////////////////////////////333334static inline void335k_tensor(GodotBody2D *a, GodotBody2D *b, Vector2 r1, Vector2 r2, Vector2 *k1, Vector2 *k2) {336// calculate mass matrix337// If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross...338real_t k11, k12, k21, k22;339real_t m_sum = a->get_inv_mass() + b->get_inv_mass();340341// start with I*m_sum342k11 = m_sum;343k12 = 0.0f;344k21 = 0.0f;345k22 = m_sum;346347r1 -= a->get_center_of_mass();348r2 -= b->get_center_of_mass();349350// add the influence from r1351real_t a_i_inv = a->get_inv_inertia();352real_t r1xsq = r1.x * r1.x * a_i_inv;353real_t r1ysq = r1.y * r1.y * a_i_inv;354real_t r1nxy = -r1.x * r1.y * a_i_inv;355k11 += r1ysq;356k12 += r1nxy;357k21 += r1nxy;358k22 += r1xsq;359360// add the influence from r2361real_t b_i_inv = b->get_inv_inertia();362real_t r2xsq = r2.x * r2.x * b_i_inv;363real_t r2ysq = r2.y * r2.y * b_i_inv;364real_t r2nxy = -r2.x * r2.y * b_i_inv;365k11 += r2ysq;366k12 += r2nxy;367k21 += r2nxy;368k22 += r2xsq;369370// invert371real_t determinant = k11 * k22 - k12 * k21;372ERR_FAIL_COND(determinant == 0.0);373374real_t det_inv = 1.0f / determinant;375*k1 = Vector2(k22 * det_inv, -k12 * det_inv);376*k2 = Vector2(-k21 * det_inv, k11 * det_inv);377}378379static _FORCE_INLINE_ Vector2380mult_k(const Vector2 &vr, const Vector2 &k1, const Vector2 &k2) {381return Vector2(vr.dot(k1), vr.dot(k2));382}383384bool GodotGrooveJoint2D::setup(real_t p_step) {385dynamic_A = (A->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC);386dynamic_B = (B->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC);387388if (!dynamic_A && !dynamic_B) {389return false;390}391392GodotSpace2D *space = A->get_space();393ERR_FAIL_NULL_V(space, false);394395// calculate endpoints in worldspace396Vector2 ta = A->get_transform().xform(A_groove_1);397Vector2 tb = A->get_transform().xform(A_groove_2);398399// calculate axis400Vector2 n = -(tb - ta).orthogonal().normalized();401real_t d = ta.dot(n);402403xf_normal = n;404rB = B->get_transform().basis_xform(B_anchor);405406// calculate tangential distance along the axis of rB407real_t td = (B->get_transform().get_origin() + rB).cross(n);408// calculate clamping factor and rB409if (td <= ta.cross(n)) {410clamp = 1.0f;411rA = ta - A->get_transform().get_origin();412} else if (td >= tb.cross(n)) {413clamp = -1.0f;414rA = tb - A->get_transform().get_origin();415} else {416clamp = 0.0f;417//joint->r1 = cpvsub(cpvadd(cpvmult(cpvperp(n), -td), cpvmult(n, d)), a->p);418rA = ((-n.orthogonal() * -td) + n * d) - A->get_transform().get_origin();419}420421// Calculate mass tensor422k_tensor(A, B, rA, rB, &k1, &k2);423424// compute max impulse425jn_max = get_max_force() * p_step;426427// calculate bias velocity428//cpVect delta = cpvsub(cpvadd(b->p, joint->r2), cpvadd(a->p, joint->r1));429//joint->bias = cpvclamp(cpvmult(delta, -joint->constraint.biasCoef*dt_inv), joint->constraint.maxBias);430431Vector2 delta = (B->get_transform().get_origin() + rB) - (A->get_transform().get_origin() + rA);432433real_t _b = get_bias();434gbias = (delta * -(_b == 0 ? space->get_constraint_bias() : _b) * (1.0 / p_step)).limit_length(get_max_bias());435436correct = true;437return true;438}439440bool GodotGrooveJoint2D::pre_solve(real_t p_step) {441// Apply accumulated impulse.442if (dynamic_A) {443A->apply_impulse(-jn_acc, rA);444}445if (dynamic_B) {446B->apply_impulse(jn_acc, rB);447}448449return true;450}451452void GodotGrooveJoint2D::solve(real_t p_step) {453// compute impulse454Vector2 vr = relative_velocity(A, B, rA, rB);455456Vector2 j = mult_k(gbias - vr, k1, k2);457Vector2 jOld = jn_acc;458j += jOld;459460jn_acc = (((clamp * j.cross(xf_normal)) > 0) ? j : j.project(xf_normal)).limit_length(jn_max);461462j = jn_acc - jOld;463464if (dynamic_A) {465A->apply_impulse(-j, rA);466}467if (dynamic_B) {468B->apply_impulse(j, rB);469}470}471472GodotGrooveJoint2D::GodotGrooveJoint2D(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, GodotBody2D *p_body_a, GodotBody2D *p_body_b) :473GodotJoint2D(_arr, 2) {474A = p_body_a;475B = p_body_b;476477A_groove_1 = A->get_inv_transform().xform(p_a_groove1);478A_groove_2 = A->get_inv_transform().xform(p_a_groove2);479B_anchor = B->get_inv_transform().xform(p_b_anchor);480A_groove_normal = -(A_groove_2 - A_groove_1).normalized().orthogonal();481482A->add_constraint(this, 0);483B->add_constraint(this, 1);484}485486//////////////////////////////////////////////487//////////////////////////////////////////////488//////////////////////////////////////////////489490bool GodotDampedSpringJoint2D::setup(real_t p_step) {491dynamic_A = (A->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC);492dynamic_B = (B->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC);493494if (!dynamic_A && !dynamic_B) {495return false;496}497498rA = A->get_transform().basis_xform(anchor_A);499rB = B->get_transform().basis_xform(anchor_B);500501Vector2 delta = (B->get_transform().get_origin() + rB) - (A->get_transform().get_origin() + rA);502real_t dist = delta.length();503504if (dist) {505n = delta / dist;506} else {507n = Vector2();508}509510real_t k = k_scalar(A, B, rA, rB, n);511n_mass = 1.0f / k;512513target_vrn = 0.0f;514v_coef = 1.0f - Math::exp(-damping * (p_step)*k);515516// Calculate spring force.517real_t f_spring = (rest_length - dist) * stiffness;518j = n * f_spring * (p_step);519520return true;521}522523bool GodotDampedSpringJoint2D::pre_solve(real_t p_step) {524// Apply spring force.525if (dynamic_A) {526A->apply_impulse(-j, rA);527}528if (dynamic_B) {529B->apply_impulse(j, rB);530}531532return true;533}534535void GodotDampedSpringJoint2D::solve(real_t p_step) {536// compute relative velocity537real_t vrn = normal_relative_velocity(A, B, rA, rB, n) - target_vrn;538539// compute velocity loss from drag540// not 100% certain this is derived correctly, though it makes sense541real_t v_damp = -vrn * v_coef;542target_vrn = vrn + v_damp;543Vector2 j_new = n * v_damp * n_mass;544545if (dynamic_A) {546A->apply_impulse(-j_new, rA);547}548if (dynamic_B) {549B->apply_impulse(j_new, rB);550}551}552553void GodotDampedSpringJoint2D::set_param(PhysicsServer2D::DampedSpringParam p_param, real_t p_value) {554switch (p_param) {555case PhysicsServer2D::DAMPED_SPRING_REST_LENGTH: {556rest_length = p_value;557} break;558case PhysicsServer2D::DAMPED_SPRING_DAMPING: {559damping = p_value;560} break;561case PhysicsServer2D::DAMPED_SPRING_STIFFNESS: {562stiffness = p_value;563} break;564}565}566567real_t GodotDampedSpringJoint2D::get_param(PhysicsServer2D::DampedSpringParam p_param) const {568switch (p_param) {569case PhysicsServer2D::DAMPED_SPRING_REST_LENGTH: {570return rest_length;571} break;572case PhysicsServer2D::DAMPED_SPRING_DAMPING: {573return damping;574} break;575case PhysicsServer2D::DAMPED_SPRING_STIFFNESS: {576return stiffness;577} break;578}579580ERR_FAIL_V(0);581}582583GodotDampedSpringJoint2D::GodotDampedSpringJoint2D(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, GodotBody2D *p_body_a, GodotBody2D *p_body_b) :584GodotJoint2D(_arr, 2) {585A = p_body_a;586B = p_body_b;587anchor_A = A->get_inv_transform().xform(p_anchor_a);588anchor_B = B->get_inv_transform().xform(p_anchor_b);589590rest_length = p_anchor_a.distance_to(p_anchor_b);591592A->add_constraint(this, 0);593B->add_constraint(this, 1);594}595596597