Path: blob/master/modules/godot_physics_2d/godot_body_pair_2d.cpp
10277 views
/**************************************************************************/1/* godot_body_pair_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_body_pair_2d.h"3132#include "godot_collision_solver_2d.h"33#include "godot_space_2d.h"3435#define ACCUMULATE_IMPULSES3637#define MIN_VELOCITY 0.00138#define MAX_BIAS_ROTATION (Math::PI / 8)3940void GodotBodyPair2D::_add_contact(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_self) {41GodotBodyPair2D *self = static_cast<GodotBodyPair2D *>(p_self);4243self->_contact_added_callback(p_point_A, p_point_B);44}4546void GodotBodyPair2D::_contact_added_callback(const Vector2 &p_point_A, const Vector2 &p_point_B) {47Vector2 local_A = A->get_inv_transform().basis_xform(p_point_A);48Vector2 local_B = B->get_inv_transform().basis_xform(p_point_B - offset_B);4950int new_index = contact_count;5152ERR_FAIL_COND(new_index >= (MAX_CONTACTS + 1));5354Contact contact;55contact.local_A = local_A;56contact.local_B = local_B;57contact.normal = (p_point_A - p_point_B).normalized();58contact.used = true;5960// Attempt to determine if the contact will be reused.61real_t recycle_radius_2 = space->get_contact_recycle_radius() * space->get_contact_recycle_radius();6263for (int i = 0; i < contact_count; i++) {64Contact &c = contacts[i];65if (c.local_A.distance_squared_to(local_A) < (recycle_radius_2) &&66c.local_B.distance_squared_to(local_B) < (recycle_radius_2)) {67contact.acc_normal_impulse = c.acc_normal_impulse;68contact.acc_tangent_impulse = c.acc_tangent_impulse;69contact.acc_bias_impulse = c.acc_bias_impulse;70contact.acc_bias_impulse_center_of_mass = c.acc_bias_impulse_center_of_mass;71c = contact;72return;73}74}7576// Figure out if the contact amount must be reduced to fit the new contact.77if (new_index == MAX_CONTACTS) {78// Remove the contact with the minimum depth.7980const Transform2D &transform_A = A->get_transform();81const Transform2D &transform_B = B->get_transform();8283int least_deep = -1;84real_t min_depth;8586// Start with depth for new contact.87{88Vector2 global_A = transform_A.basis_xform(contact.local_A);89Vector2 global_B = transform_B.basis_xform(contact.local_B) + offset_B;9091Vector2 axis = global_A - global_B;92min_depth = axis.dot(contact.normal);93}9495for (int i = 0; i < contact_count; i++) {96const Contact &c = contacts[i];97Vector2 global_A = transform_A.basis_xform(c.local_A);98Vector2 global_B = transform_B.basis_xform(c.local_B) + offset_B;99100Vector2 axis = global_A - global_B;101real_t depth = axis.dot(c.normal);102103if (depth < min_depth) {104min_depth = depth;105least_deep = i;106}107}108109if (least_deep > -1) {110// Replace the least deep contact by the new one.111contacts[least_deep] = contact;112}113114return;115}116117contacts[new_index] = contact;118contact_count++;119}120121void GodotBodyPair2D::_validate_contacts() {122// Make sure to erase contacts that are no longer valid.123real_t max_separation = space->get_contact_max_separation();124real_t max_separation2 = max_separation * max_separation;125126const Transform2D &transform_A = A->get_transform();127const Transform2D &transform_B = B->get_transform();128129for (int i = 0; i < contact_count; i++) {130Contact &c = contacts[i];131132bool erase = false;133if (!c.used) {134// Was left behind in previous frame.135erase = true;136} else {137c.used = false;138139Vector2 global_A = transform_A.basis_xform(c.local_A);140Vector2 global_B = transform_B.basis_xform(c.local_B) + offset_B;141Vector2 axis = global_A - global_B;142real_t depth = axis.dot(c.normal);143144if (depth < -max_separation || (global_B + c.normal * depth - global_A).length_squared() > max_separation2) {145erase = true;146}147}148149if (erase) {150// Contact no longer needed, remove.151152if ((i + 1) < contact_count) {153// Swap with the last one.154SWAP(contacts[i], contacts[contact_count - 1]);155}156157i--;158contact_count--;159}160}161}162163// `_test_ccd` prevents tunneling by slowing down a high velocity body that is about to collide so164// that next frame it will be at an appropriate location to collide (i.e. slight overlap).165// WARNING: The way velocity is adjusted down to cause a collision means the momentum will be166// weaker than it should for a bounce!167// Process: Only proceed if body A's motion is high relative to its size.168// Cast forward along motion vector to see if A is going to enter/pass B's collider next frame, only proceed if it does.169// Adjust the velocity of A down so that it will just slightly intersect the collider instead of blowing right past it.170bool GodotBodyPair2D::_test_ccd(real_t p_step, GodotBody2D *p_A, int p_shape_A, const Transform2D &p_xform_A, GodotBody2D *p_B, int p_shape_B, const Transform2D &p_xform_B) {171Vector2 motion = p_A->get_linear_velocity() * p_step;172real_t mlen = motion.length();173if (mlen < CMP_EPSILON) {174return false;175}176177Vector2 mnormal = motion / mlen;178179real_t min = 0.0, max = 0.0;180p_A->get_shape(p_shape_A)->project_rangev(mnormal, p_xform_A, min, max);181182// Did it move enough in this direction to even attempt raycast?183// Let's say it should move more than 1/3 the size of the object in that axis.184bool fast_object = mlen > (max - min) * 0.3;185if (!fast_object) {186return false;187}188189// A is moving fast enough that tunneling might occur. See if it's really about to collide.190191// Roughly predict body B's position in the next frame (ignoring collisions).192Transform2D predicted_xform_B = p_xform_B.translated(p_B->get_linear_velocity() * p_step);193194// Cast a segment from support in motion normal, in the same direction of motion by motion length.195// Support point will the farthest forward collision point along the movement vector.196// i.e. the point that should hit B first if any collision does occur.197198// convert mnormal into body A's local xform because get_support requires (and returns) local coordinates.199int a;200Vector2 s[2];201p_A->get_shape(p_shape_A)->get_supports(p_xform_A.basis_xform_inv(mnormal).normalized(), s, a);202Vector2 from = p_xform_A.xform(s[0]);203// Back up 10% of the per-frame motion behind the support point and use that as the beginning of our cast.204// This should ensure the calculated new velocity will really cause a bit of overlap instead of just getting us very close.205Vector2 to = from + motion;206207Transform2D from_inv = predicted_xform_B.affine_inverse();208209// Back up 10% of the per-frame motion behind the support point and use that as the beginning of our cast.210// At high speeds, this may mean we're actually casting from well behind the body instead of inside it, which is odd. But it still works out.211Vector2 local_from = from_inv.xform(from - motion * 0.1);212Vector2 local_to = from_inv.xform(to);213214Vector2 rpos, rnorm;215if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from, local_to, rpos, rnorm)) {216// there was no hit. Since the segment is the length of per-frame motion, this means the bodies will not217// actually collide yet on next frame. We'll probably check again next frame once they're closer.218return false;219}220221// Check one-way collision based on motion direction.222if (p_A->get_shape(p_shape_A)->allows_one_way_collision() && p_B->is_shape_set_as_one_way_collision(p_shape_B)) {223Vector2 direction = predicted_xform_B.columns[1].normalized();224if (direction.dot(mnormal) < CMP_EPSILON) {225collided = false;226oneway_disabled = true;227return false;228}229}230231// Shorten the linear velocity so it does not hit, but gets close enough,232// next frame will hit softly or soft enough.233Vector2 hitpos = predicted_xform_B.xform(rpos);234235real_t newlen = hitpos.distance_to(from) + (max - min) * 0.01; // adding 1% of body length to the distance between collision and support point should cause body A's support point to arrive just within B's collider next frame.236p_A->set_linear_velocity(mnormal * (newlen / p_step));237238return true;239}240241real_t combine_bounce(GodotBody2D *A, GodotBody2D *B) {242return CLAMP(A->get_bounce() + B->get_bounce(), 0, 1);243}244245real_t combine_friction(GodotBody2D *A, GodotBody2D *B) {246return Math::abs(MIN(A->get_friction(), B->get_friction()));247}248249bool GodotBodyPair2D::setup(real_t p_step) {250check_ccd = false;251252if (!A->interacts_with(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self())) {253collided = false;254return false;255}256257collide_A = (A->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC) && A->collides_with(B);258collide_B = (B->get_mode() > PhysicsServer2D::BODY_MODE_KINEMATIC) && B->collides_with(A);259260report_contacts_only = false;261if (!collide_A && !collide_B) {262if ((A->get_max_contacts_reported() > 0) || (B->get_max_contacts_reported() > 0)) {263report_contacts_only = true;264} else {265collided = false;266return false;267}268}269270//use local A coordinates to avoid numerical issues on collision detection271offset_B = B->get_transform().get_origin() - A->get_transform().get_origin();272273_validate_contacts();274275const Vector2 &offset_A = A->get_transform().get_origin();276Transform2D xform_Au = A->get_transform().untranslated();277Transform2D xform_A = xform_Au * A->get_shape_transform(shape_A);278279Transform2D xform_Bu = B->get_transform();280xform_Bu.columns[2] -= offset_A;281Transform2D xform_B = xform_Bu * B->get_shape_transform(shape_B);282283GodotShape2D *shape_A_ptr = A->get_shape(shape_A);284GodotShape2D *shape_B_ptr = B->get_shape(shape_B);285286Vector2 motion_A, motion_B;287288if (A->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_SHAPE) {289motion_A = A->get_motion();290}291if (B->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_SHAPE) {292motion_B = B->get_motion();293}294295bool prev_collided = collided;296297collided = GodotCollisionSolver2D::solve(shape_A_ptr, xform_A, motion_A, shape_B_ptr, xform_B, motion_B, _add_contact, this, &sep_axis);298if (!collided) {299oneway_disabled = false;300301if (A->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_RAY && collide_A) {302check_ccd = true;303return true;304}305306if (B->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_RAY && collide_B) {307check_ccd = true;308return true;309}310311return false;312}313314if (oneway_disabled) {315return false;316}317318if (!prev_collided) {319if (shape_B_ptr->allows_one_way_collision() && A->is_shape_set_as_one_way_collision(shape_A)) {320Vector2 direction = xform_A.columns[1].normalized();321bool valid = false;322for (int i = 0; i < contact_count; i++) {323Contact &c = contacts[i];324if (c.normal.dot(direction) > -CMP_EPSILON) { // Greater (normal inverted).325continue;326}327valid = true;328break;329}330if (!valid) {331collided = false;332oneway_disabled = true;333return false;334}335}336337if (shape_A_ptr->allows_one_way_collision() && B->is_shape_set_as_one_way_collision(shape_B)) {338Vector2 direction = xform_B.columns[1].normalized();339bool valid = false;340for (int i = 0; i < contact_count; i++) {341Contact &c = contacts[i];342if (c.normal.dot(direction) < CMP_EPSILON) { // Less (normal ok).343continue;344}345valid = true;346break;347}348if (!valid) {349collided = false;350oneway_disabled = true;351return false;352}353}354}355356return true;357}358359bool GodotBodyPair2D::pre_solve(real_t p_step) {360if (oneway_disabled) {361return false;362}363364if (!collided) {365if (check_ccd) {366const Vector2 &offset_A = A->get_transform().get_origin();367Transform2D xform_Au = A->get_transform().untranslated();368Transform2D xform_A = xform_Au * A->get_shape_transform(shape_A);369370Transform2D xform_Bu = B->get_transform();371xform_Bu.columns[2] -= offset_A;372Transform2D xform_B = xform_Bu * B->get_shape_transform(shape_B);373374if (A->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_RAY && collide_A) {375_test_ccd(p_step, A, shape_A, xform_A, B, shape_B, xform_B);376}377378if (B->get_continuous_collision_detection_mode() == PhysicsServer2D::CCD_MODE_CAST_RAY && collide_B) {379_test_ccd(p_step, B, shape_B, xform_B, A, shape_A, xform_A);380}381}382383return false;384}385386real_t max_penetration = space->get_contact_max_allowed_penetration();387388real_t bias = space->get_contact_bias();389390GodotShape2D *shape_A_ptr = A->get_shape(shape_A);391GodotShape2D *shape_B_ptr = B->get_shape(shape_B);392393if (shape_A_ptr->get_custom_bias() || shape_B_ptr->get_custom_bias()) {394if (shape_A_ptr->get_custom_bias() == 0) {395bias = shape_B_ptr->get_custom_bias();396} else if (shape_B_ptr->get_custom_bias() == 0) {397bias = shape_A_ptr->get_custom_bias();398} else {399bias = (shape_B_ptr->get_custom_bias() + shape_A_ptr->get_custom_bias()) * 0.5;400}401}402403real_t inv_dt = 1.0 / p_step;404405bool do_process = false;406407const Vector2 &offset_A = A->get_transform().get_origin();408const Transform2D &transform_A = A->get_transform();409const Transform2D &transform_B = B->get_transform();410411real_t inv_inertia_A = collide_A ? A->get_inv_inertia() : 0.0;412real_t inv_inertia_B = collide_B ? B->get_inv_inertia() : 0.0;413414real_t inv_mass_A = collide_A ? A->get_inv_mass() : 0.0;415real_t inv_mass_B = collide_B ? B->get_inv_mass() : 0.0;416417for (int i = 0; i < contact_count; i++) {418Contact &c = contacts[i];419c.active = false;420421Vector2 global_A = transform_A.basis_xform(c.local_A);422Vector2 global_B = transform_B.basis_xform(c.local_B) + offset_B;423424Vector2 axis = global_A - global_B;425real_t depth = axis.dot(c.normal);426427if (depth <= 0.0) {428continue;429}430431#ifdef DEBUG_ENABLED432if (space->is_debugging_contacts()) {433space->add_debug_contact(global_A + offset_A);434space->add_debug_contact(global_B + offset_A);435}436#endif437438c.rA = global_A - A->get_center_of_mass();439c.rB = global_B - B->get_center_of_mass() - offset_B;440441// Precompute normal mass, tangent mass, and bias.442real_t rnA = c.rA.dot(c.normal);443real_t rnB = c.rB.dot(c.normal);444real_t kNormal = inv_mass_A + inv_mass_B;445kNormal += inv_inertia_A * (c.rA.dot(c.rA) - rnA * rnA) + inv_inertia_B * (c.rB.dot(c.rB) - rnB * rnB);446c.mass_normal = 1.0f / kNormal;447448Vector2 tangent = c.normal.orthogonal();449real_t rtA = c.rA.dot(tangent);450real_t rtB = c.rB.dot(tangent);451real_t kTangent = inv_mass_A + inv_mass_B;452kTangent += inv_inertia_A * (c.rA.dot(c.rA) - rtA * rtA) + inv_inertia_B * (c.rB.dot(c.rB) - rtB * rtB);453c.mass_tangent = 1.0f / kTangent;454455c.bias = -bias * inv_dt * MIN(0.0f, -depth + max_penetration);456c.depth = depth;457458Vector2 P = c.acc_normal_impulse * c.normal + c.acc_tangent_impulse * tangent;459460c.acc_impulse -= P;461462if (A->can_report_contacts() || B->can_report_contacts()) {463Vector2 crB = Vector2(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x) + B->get_linear_velocity();464Vector2 crA = Vector2(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x) + A->get_linear_velocity();465if (A->can_report_contacts()) {466A->add_contact(global_A + offset_A, -c.normal, depth, shape_A, crA, global_B + offset_A, shape_B, B->get_instance_id(), B->get_self(), crB, c.acc_impulse);467}468if (B->can_report_contacts()) {469B->add_contact(global_B + offset_A, c.normal, depth, shape_B, crB, global_A + offset_A, shape_A, A->get_instance_id(), A->get_self(), crA, c.acc_impulse);470}471}472473if (report_contacts_only) {474collided = false;475continue;476}477478#ifdef ACCUMULATE_IMPULSES479{480// Apply normal + friction impulse481if (collide_A) {482A->apply_impulse(-P, c.rA + A->get_center_of_mass());483}484if (collide_B) {485B->apply_impulse(P, c.rB + B->get_center_of_mass());486}487}488#endif489490c.bounce = combine_bounce(A, B);491if (c.bounce) {492Vector2 crA(-A->get_prev_angular_velocity() * c.rA.y, A->get_prev_angular_velocity() * c.rA.x);493Vector2 crB(-B->get_prev_angular_velocity() * c.rB.y, B->get_prev_angular_velocity() * c.rB.x);494Vector2 dv = B->get_prev_linear_velocity() + crB - A->get_prev_linear_velocity() - crA;495c.bounce = c.bounce * dv.dot(c.normal);496}497498c.active = true;499do_process = true;500}501502return do_process;503}504505void GodotBodyPair2D::solve(real_t p_step) {506if (!collided || oneway_disabled) {507return;508}509510const real_t max_bias_av = MAX_BIAS_ROTATION / p_step;511512real_t inv_mass_A = collide_A ? A->get_inv_mass() : 0.0;513real_t inv_mass_B = collide_B ? B->get_inv_mass() : 0.0;514515for (int i = 0; i < contact_count; ++i) {516Contact &c = contacts[i];517518if (!c.active) {519continue;520}521522// Relative velocity at contact523524Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x);525Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x);526Vector2 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA;527528Vector2 crbA(-A->get_biased_angular_velocity() * c.rA.y, A->get_biased_angular_velocity() * c.rA.x);529Vector2 crbB(-B->get_biased_angular_velocity() * c.rB.y, B->get_biased_angular_velocity() * c.rB.x);530Vector2 dbv = B->get_biased_linear_velocity() + crbB - A->get_biased_linear_velocity() - crbA;531532real_t vn = dv.dot(c.normal);533real_t vbn = dbv.dot(c.normal);534535Vector2 tangent = c.normal.orthogonal();536real_t vt = dv.dot(tangent);537538real_t jbn = (c.bias - vbn) * c.mass_normal;539real_t jbnOld = c.acc_bias_impulse;540c.acc_bias_impulse = MAX(jbnOld + jbn, 0.0f);541542Vector2 jb = c.normal * (c.acc_bias_impulse - jbnOld);543544if (collide_A) {545A->apply_bias_impulse(-jb, c.rA + A->get_center_of_mass(), max_bias_av);546}547if (collide_B) {548B->apply_bias_impulse(jb, c.rB + B->get_center_of_mass(), max_bias_av);549}550551crbA = Vector2(-A->get_biased_angular_velocity() * c.rA.y, A->get_biased_angular_velocity() * c.rA.x);552crbB = Vector2(-B->get_biased_angular_velocity() * c.rB.y, B->get_biased_angular_velocity() * c.rB.x);553dbv = B->get_biased_linear_velocity() + crbB - A->get_biased_linear_velocity() - crbA;554555vbn = dbv.dot(c.normal);556557if (Math::abs(-vbn + c.bias) > MIN_VELOCITY) {558real_t jbn_com = (-vbn + c.bias) / (inv_mass_A + inv_mass_B);559real_t jbnOld_com = c.acc_bias_impulse_center_of_mass;560c.acc_bias_impulse_center_of_mass = MAX(jbnOld_com + jbn_com, 0.0f);561562Vector2 jb_com = c.normal * (c.acc_bias_impulse_center_of_mass - jbnOld_com);563564if (collide_A) {565A->apply_bias_impulse(-jb_com, A->get_center_of_mass(), 0.0f);566}567if (collide_B) {568B->apply_bias_impulse(jb_com, B->get_center_of_mass(), 0.0f);569}570}571572real_t jn = -(c.bounce + vn) * c.mass_normal;573real_t jnOld = c.acc_normal_impulse;574c.acc_normal_impulse = MAX(jnOld + jn, 0.0f);575576real_t friction = combine_friction(A, B);577578real_t jtMax = friction * c.acc_normal_impulse;579real_t jt = -vt * c.mass_tangent;580real_t jtOld = c.acc_tangent_impulse;581c.acc_tangent_impulse = CLAMP(jtOld + jt, -jtMax, jtMax);582583Vector2 j = c.normal * (c.acc_normal_impulse - jnOld) + tangent * (c.acc_tangent_impulse - jtOld);584585if (collide_A) {586A->apply_impulse(-j, c.rA + A->get_center_of_mass());587}588if (collide_B) {589B->apply_impulse(j, c.rB + B->get_center_of_mass());590}591c.acc_impulse -= j;592}593}594595GodotBodyPair2D::GodotBodyPair2D(GodotBody2D *p_A, int p_shape_A, GodotBody2D *p_B, int p_shape_B) :596GodotConstraint2D(_arr, 2) {597A = p_A;598B = p_B;599shape_A = p_shape_A;600shape_B = p_shape_B;601space = A->get_space();602A->add_constraint(this, 0);603B->add_constraint(this, 1);604}605606GodotBodyPair2D::~GodotBodyPair2D() {607A->remove_constraint(this, 0);608B->remove_constraint(this, 1);609}610611612