Path: blob/master/modules/jolt_physics/objects/jolt_area_3d.cpp
10278 views
/**************************************************************************/1/* jolt_area_3d.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 "jolt_area_3d.h"3132#include "../jolt_project_settings.h"33#include "../misc/jolt_math_funcs.h"34#include "../misc/jolt_type_conversions.h"35#include "../shapes/jolt_shape_3d.h"36#include "../spaces/jolt_broad_phase_layer.h"37#include "../spaces/jolt_space_3d.h"38#include "jolt_body_3d.h"39#include "jolt_group_filter.h"40#include "jolt_soft_body_3d.h"4142namespace {4344constexpr double AREA_DEFAULT_WIND_MAGNITUDE = 0.0;45constexpr double AREA_DEFAULT_WIND_ATTENUATION = 0.0;4647const Vector3 AREA_DEFAULT_WIND_SOURCE = Vector3();48const Vector3 AREA_DEFAULT_WIND_DIRECTION = Vector3();4950} // namespace5152JPH::BroadPhaseLayer JoltArea3D::_get_broad_phase_layer() const {53return monitorable ? JoltBroadPhaseLayer::AREA_DETECTABLE : JoltBroadPhaseLayer::AREA_UNDETECTABLE;54}5556JPH::ObjectLayer JoltArea3D::_get_object_layer() const {57ERR_FAIL_NULL_V(space, 0);5859if (jolt_shape == nullptr || jolt_shape->GetType() == JPH::EShapeType::Empty) {60// No point doing collision checks against a shapeless object.61return space->map_to_object_layer(_get_broad_phase_layer(), 0, 0);62}6364return space->map_to_object_layer(_get_broad_phase_layer(), collision_layer, collision_mask);65}6667void JoltArea3D::_add_to_space() {68jolt_shape = build_shapes(true);6970JPH::CollisionGroup::GroupID group_id = 0;71JPH::CollisionGroup::SubGroupID sub_group_id = 0;72JoltGroupFilter::encode_object(this, group_id, sub_group_id);7374jolt_settings->mUserData = reinterpret_cast<JPH::uint64>(this);75jolt_settings->mObjectLayer = _get_object_layer();76jolt_settings->mCollisionGroup = JPH::CollisionGroup(nullptr, group_id, sub_group_id);77jolt_settings->mMotionType = _get_motion_type();78jolt_settings->mIsSensor = true;79jolt_settings->mCollideKinematicVsNonDynamic = true;80jolt_settings->mUseManifoldReduction = false;81jolt_settings->mOverrideMassProperties = JPH::EOverrideMassProperties::MassAndInertiaProvided;82jolt_settings->mMassPropertiesOverride.mMass = 1.0f;83jolt_settings->mMassPropertiesOverride.mInertia = JPH::Mat44::sIdentity();8485jolt_settings->SetShape(jolt_shape);8687JPH::Body *new_jolt_body = space->add_object(*this, *jolt_settings, _should_sleep());88if (new_jolt_body == nullptr) {89return;90}9192jolt_body = new_jolt_body;9394delete jolt_settings;95jolt_settings = nullptr;96}9798void JoltArea3D::_enqueue_call_queries() {99if (space != nullptr) {100space->enqueue_call_queries(&call_queries_element);101}102}103104void JoltArea3D::_dequeue_call_queries() {105if (space != nullptr) {106space->dequeue_call_queries(&call_queries_element);107}108}109110void JoltArea3D::_add_shape_pair(Overlap &p_overlap, const JPH::BodyID &p_body_id, const JPH::SubShapeID &p_other_shape_id, const JPH::SubShapeID &p_self_shape_id) {111const JoltShapedObject3D *other_object = space->try_get_shaped(p_body_id);112ERR_FAIL_NULL(other_object);113114p_overlap.rid = other_object->get_rid();115p_overlap.instance_id = other_object->get_instance_id();116117HashMap<ShapeIDPair, ShapeIndexPair, ShapeIDPair>::Iterator shape_pair = p_overlap.shape_pairs.find(ShapeIDPair(p_other_shape_id, p_self_shape_id));118if (shape_pair == p_overlap.shape_pairs.end()) {119const int other_shape_index = other_object->find_shape_index(p_other_shape_id);120const int self_shape_index = find_shape_index(p_self_shape_id);121shape_pair = p_overlap.shape_pairs.insert(ShapeIDPair(p_other_shape_id, p_self_shape_id), ShapeIndexPair(other_shape_index, self_shape_index));122}123124p_overlap.pending_added.push_back(shape_pair->value);125126_events_changed();127}128129bool JoltArea3D::_remove_shape_pair(Overlap &p_overlap, const JPH::SubShapeID &p_other_shape_id, const JPH::SubShapeID &p_self_shape_id) {130HashMap<ShapeIDPair, ShapeIndexPair, ShapeIDPair>::Iterator shape_pair = p_overlap.shape_pairs.find(ShapeIDPair(p_other_shape_id, p_self_shape_id));131132if (shape_pair == p_overlap.shape_pairs.end()) {133return false;134}135136p_overlap.pending_removed.push_back(shape_pair->value);137p_overlap.shape_pairs.remove(shape_pair);138139_events_changed();140141return true;142}143144void JoltArea3D::_flush_events(OverlapsById &p_objects, const Callable &p_callback) {145for (OverlapsById::Iterator E = p_objects.begin(); E;) {146Overlap &overlap = E->value;147148if (p_callback.is_valid()) {149for (const ShapeIndexPair &shape_indices : overlap.pending_added) {150int &ref_count = overlap.ref_counts[shape_indices];151if (ref_count++ == 0) {152_report_event(p_callback, PhysicsServer3D::AREA_BODY_ADDED, overlap.rid, overlap.instance_id, shape_indices.other, shape_indices.self);153}154}155156for (const ShapeIndexPair &shape_indices : overlap.pending_removed) {157int &ref_count = overlap.ref_counts[shape_indices];158ERR_CONTINUE(ref_count <= 0);159if (--ref_count == 0) {160_report_event(p_callback, PhysicsServer3D::AREA_BODY_REMOVED, overlap.rid, overlap.instance_id, shape_indices.other, shape_indices.self);161overlap.ref_counts.erase(shape_indices);162}163}164}165166overlap.pending_removed.clear();167overlap.pending_added.clear();168169OverlapsById::Iterator next = E;170++next;171172if (overlap.shape_pairs.is_empty()) {173p_objects.remove(E);174}175176E = next;177}178}179180void JoltArea3D::_report_event(const Callable &p_callback, PhysicsServer3D::AreaBodyStatus p_status, const RID &p_other_rid, ObjectID p_other_instance_id, int p_other_shape_index, int p_self_shape_index) const {181ERR_FAIL_COND(!p_callback.is_valid());182183const Variant arg1 = p_status;184const Variant arg2 = p_other_rid;185const Variant arg3 = p_other_instance_id;186const Variant arg4 = p_other_shape_index;187const Variant arg5 = p_self_shape_index;188const Variant *args[5] = { &arg1, &arg2, &arg3, &arg4, &arg5 };189190Callable::CallError ce;191Variant ret;192p_callback.callp(args, 5, ret, ce);193194if (unlikely(ce.error != Callable::CallError::CALL_OK)) {195ERR_PRINT_ONCE(vformat("Failed to call area monitor callback for '%s'. It returned the following error: '%s'.", to_string(), Variant::get_callable_error_text(p_callback, args, 5, ce)));196}197}198199void JoltArea3D::_notify_body_entered(const JPH::BodyID &p_body_id) {200if (JoltBody3D *other_body = space->try_get_body(p_body_id)) {201other_body->add_area(this);202}203}204205void JoltArea3D::_notify_body_exited(const JPH::BodyID &p_body_id) {206if (JoltBody3D *other_body = space->try_get_body(p_body_id)) {207other_body->remove_area(this);208}209}210211void JoltArea3D::_remove_all_overlaps() {212for (KeyValue<JPH::BodyID, Overlap> &E : bodies_by_id) {213_notify_body_exited(E.key);214}215216bodies_by_id.clear();217areas_by_id.clear();218}219220void JoltArea3D::_update_sleeping() {221if (!in_space()) {222return;223}224225space->set_is_object_sleeping(jolt_body->GetID(), _should_sleep());226}227228void JoltArea3D::_update_group_filter() {229if (!in_space()) {230return;231}232233jolt_body->GetCollisionGroup().SetGroupFilter(JoltGroupFilter::instance);234}235236void JoltArea3D::_update_default_gravity() {237if (is_default_area()) {238space->get_physics_system().SetGravity(to_jolt(gravity_vector) * gravity);239}240}241242void JoltArea3D::_space_changing() {243JoltShapedObject3D::_space_changing();244245_remove_all_overlaps();246_dequeue_call_queries();247}248249void JoltArea3D::_space_changed() {250JoltShapedObject3D::_space_changed();251252_update_group_filter();253_update_default_gravity();254}255256void JoltArea3D::_events_changed() {257_enqueue_call_queries();258}259260void JoltArea3D::_body_monitoring_changed() {261_update_sleeping();262}263264void JoltArea3D::_area_monitoring_changed() {265_update_sleeping();266}267268void JoltArea3D::_monitorable_changed() {269_update_object_layer();270}271272void JoltArea3D::_gravity_changed() {273_update_default_gravity();274}275276JoltArea3D::JoltArea3D() :277JoltShapedObject3D(OBJECT_TYPE_AREA),278call_queries_element(this) {279}280281bool JoltArea3D::is_default_area() const {282return space != nullptr && space->get_default_area() == this;283}284285void JoltArea3D::set_default_area(bool p_value) {286if (p_value) {287_update_default_gravity();288}289}290291void JoltArea3D::set_transform(Transform3D p_transform) {292JOLT_ENSURE_SCALE_NOT_ZERO(p_transform, vformat("An invalid transform was passed to area '%s'.", to_string()));293294Vector3 new_scale;295JoltMath::decompose(p_transform, new_scale);296297// Ideally we would do an exact comparison here, but due to floating-point precision this would be invalidated very often.298if (!scale.is_equal_approx(new_scale)) {299scale = new_scale;300_shapes_changed();301}302303if (!in_space()) {304jolt_settings->mPosition = to_jolt_r(p_transform.origin);305jolt_settings->mRotation = to_jolt(p_transform.basis);306} else {307space->get_body_iface().SetPositionAndRotation(jolt_body->GetID(), to_jolt_r(p_transform.origin), to_jolt(p_transform.basis), JPH::EActivation::DontActivate);308}309}310311Variant JoltArea3D::get_param(PhysicsServer3D::AreaParameter p_param) const {312switch (p_param) {313case PhysicsServer3D::AREA_PARAM_GRAVITY_OVERRIDE_MODE: {314return get_gravity_mode();315}316case PhysicsServer3D::AREA_PARAM_GRAVITY: {317return get_gravity();318}319case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: {320return get_gravity_vector();321}322case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: {323return is_point_gravity();324}325case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_UNIT_DISTANCE: {326return get_point_gravity_distance();327}328case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP_OVERRIDE_MODE: {329return get_linear_damp_mode();330}331case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: {332return get_linear_damp();333}334case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP_OVERRIDE_MODE: {335return get_angular_damp_mode();336}337case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: {338return get_angular_damp();339}340case PhysicsServer3D::AREA_PARAM_PRIORITY: {341return get_priority();342}343case PhysicsServer3D::AREA_PARAM_WIND_FORCE_MAGNITUDE: {344return AREA_DEFAULT_WIND_MAGNITUDE;345}346case PhysicsServer3D::AREA_PARAM_WIND_SOURCE: {347return AREA_DEFAULT_WIND_SOURCE;348}349case PhysicsServer3D::AREA_PARAM_WIND_DIRECTION: {350return AREA_DEFAULT_WIND_DIRECTION;351}352case PhysicsServer3D::AREA_PARAM_WIND_ATTENUATION_FACTOR: {353return AREA_DEFAULT_WIND_ATTENUATION;354}355default: {356ERR_FAIL_V_MSG(Variant(), vformat("Unhandled area parameter: '%d'. This should not happen. Please report this.", p_param));357}358}359}360361void JoltArea3D::set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value) {362switch (p_param) {363case PhysicsServer3D::AREA_PARAM_GRAVITY_OVERRIDE_MODE: {364set_gravity_mode((OverrideMode)(int)p_value);365} break;366case PhysicsServer3D::AREA_PARAM_GRAVITY: {367set_gravity(p_value);368} break;369case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: {370set_gravity_vector(p_value);371} break;372case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: {373set_point_gravity(p_value);374} break;375case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_UNIT_DISTANCE: {376set_point_gravity_distance(p_value);377} break;378case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP_OVERRIDE_MODE: {379set_linear_damp_mode((OverrideMode)(int)p_value);380} break;381case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: {382set_area_linear_damp(p_value);383} break;384case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP_OVERRIDE_MODE: {385set_angular_damp_mode((OverrideMode)(int)p_value);386} break;387case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: {388set_area_angular_damp(p_value);389} break;390case PhysicsServer3D::AREA_PARAM_PRIORITY: {391set_priority(p_value);392} break;393case PhysicsServer3D::AREA_PARAM_WIND_FORCE_MAGNITUDE: {394if (!Math::is_equal_approx((double)p_value, AREA_DEFAULT_WIND_MAGNITUDE)) {395WARN_PRINT(vformat("Invalid wind force magnitude for '%s'. Area wind force magnitude is not supported when using Jolt Physics. Any such value will be ignored.", to_string()));396}397} break;398case PhysicsServer3D::AREA_PARAM_WIND_SOURCE: {399if (!((Vector3)p_value).is_equal_approx(AREA_DEFAULT_WIND_SOURCE)) {400WARN_PRINT(vformat("Invalid wind source for '%s'. Area wind source is not supported when using Jolt Physics. Any such value will be ignored.", to_string()));401}402} break;403case PhysicsServer3D::AREA_PARAM_WIND_DIRECTION: {404if (!((Vector3)p_value).is_equal_approx(AREA_DEFAULT_WIND_DIRECTION)) {405WARN_PRINT(vformat("Invalid wind direction for '%s'. Area wind direction is not supported when using Jolt Physics. Any such value will be ignored.", to_string()));406}407} break;408case PhysicsServer3D::AREA_PARAM_WIND_ATTENUATION_FACTOR: {409if (!Math::is_equal_approx((double)p_value, AREA_DEFAULT_WIND_ATTENUATION)) {410WARN_PRINT(vformat("Invalid wind attenuation for '%s'. Area wind attenuation is not supported when using Jolt Physics. Any such value will be ignored.", to_string()));411}412} break;413default: {414ERR_FAIL_MSG(vformat("Unhandled area parameter: '%d'. This should not happen. Please report this.", p_param));415} break;416}417}418419void JoltArea3D::set_body_monitor_callback(const Callable &p_callback) {420if (p_callback == body_monitor_callback) {421return;422}423424body_monitor_callback = p_callback;425426_body_monitoring_changed();427}428429void JoltArea3D::set_area_monitor_callback(const Callable &p_callback) {430if (p_callback == area_monitor_callback) {431return;432}433434area_monitor_callback = p_callback;435436_area_monitoring_changed();437}438439void JoltArea3D::set_monitorable(bool p_monitorable) {440if (p_monitorable == monitorable) {441return;442}443444monitorable = p_monitorable;445446_monitorable_changed();447}448449bool JoltArea3D::can_monitor(const JoltBody3D &p_other) const {450return is_monitoring_bodies() && (collision_mask & p_other.get_collision_layer()) != 0;451}452453bool JoltArea3D::can_monitor(const JoltSoftBody3D &p_other) const {454return false;455}456457bool JoltArea3D::can_monitor(const JoltArea3D &p_other) const {458return is_monitoring_areas() && p_other.is_monitorable() && (collision_mask & p_other.get_collision_layer()) != 0;459}460461bool JoltArea3D::can_interact_with(const JoltBody3D &p_other) const {462return can_monitor(p_other);463}464465bool JoltArea3D::can_interact_with(const JoltSoftBody3D &p_other) const {466return false;467}468469bool JoltArea3D::can_interact_with(const JoltArea3D &p_other) const {470return can_monitor(p_other) || p_other.can_monitor(*this);471}472473Vector3 JoltArea3D::get_velocity_at_position(const Vector3 &p_position) const {474return Vector3();475}476477void JoltArea3D::set_point_gravity(bool p_enabled) {478if (point_gravity == p_enabled) {479return;480}481482point_gravity = p_enabled;483484_gravity_changed();485}486487void JoltArea3D::set_gravity(float p_gravity) {488if (gravity == p_gravity) {489return;490}491492gravity = p_gravity;493494_gravity_changed();495}496497void JoltArea3D::set_point_gravity_distance(float p_distance) {498if (point_gravity_distance == p_distance) {499return;500}501502point_gravity_distance = p_distance;503504_gravity_changed();505}506507void JoltArea3D::set_gravity_mode(OverrideMode p_mode) {508if (gravity_mode == p_mode) {509return;510}511512gravity_mode = p_mode;513514_gravity_changed();515}516517void JoltArea3D::set_gravity_vector(const Vector3 &p_vector) {518if (gravity_vector == p_vector) {519return;520}521522gravity_vector = p_vector;523524_gravity_changed();525}526527Vector3 JoltArea3D::compute_gravity(const Vector3 &p_position) const {528if (!point_gravity) {529return gravity_vector * gravity;530}531532const Vector3 point = get_transform_scaled().xform(gravity_vector);533const Vector3 to_point = point - p_position;534const real_t to_point_dist_sq = MAX(to_point.length_squared(), (real_t)CMP_EPSILON);535const Vector3 to_point_dir = to_point / Math::sqrt(to_point_dist_sq);536537if (point_gravity_distance == 0.0f) {538return to_point_dir * gravity;539}540541const float gravity_dist_sq = point_gravity_distance * point_gravity_distance;542543return to_point_dir * (gravity * gravity_dist_sq / to_point_dist_sq);544}545546void JoltArea3D::body_shape_entered(const JPH::BodyID &p_body_id, const JPH::SubShapeID &p_other_shape_id, const JPH::SubShapeID &p_self_shape_id) {547Overlap &overlap = bodies_by_id[p_body_id];548549if (overlap.shape_pairs.is_empty()) {550_notify_body_entered(p_body_id);551}552553_add_shape_pair(overlap, p_body_id, p_other_shape_id, p_self_shape_id);554}555556bool JoltArea3D::body_shape_exited(const JPH::BodyID &p_body_id, const JPH::SubShapeID &p_other_shape_id, const JPH::SubShapeID &p_self_shape_id) {557Overlap *overlap = bodies_by_id.getptr(p_body_id);558if (overlap == nullptr) {559return false;560}561562if (!_remove_shape_pair(*overlap, p_other_shape_id, p_self_shape_id)) {563return false;564}565566if (overlap->shape_pairs.is_empty()) {567_notify_body_exited(p_body_id);568}569570return true;571}572573void JoltArea3D::area_shape_entered(const JPH::BodyID &p_body_id, const JPH::SubShapeID &p_other_shape_id, const JPH::SubShapeID &p_self_shape_id) {574_add_shape_pair(areas_by_id[p_body_id], p_body_id, p_other_shape_id, p_self_shape_id);575}576577bool JoltArea3D::area_shape_exited(const JPH::BodyID &p_body_id, const JPH::SubShapeID &p_other_shape_id, const JPH::SubShapeID &p_self_shape_id) {578Overlap *overlap = areas_by_id.getptr(p_body_id);579if (overlap == nullptr) {580return false;581}582583return _remove_shape_pair(*overlap, p_other_shape_id, p_self_shape_id);584}585586bool JoltArea3D::shape_exited(const JPH::BodyID &p_body_id, const JPH::SubShapeID &p_other_shape_id, const JPH::SubShapeID &p_self_shape_id) {587return body_shape_exited(p_body_id, p_other_shape_id, p_self_shape_id) || area_shape_exited(p_body_id, p_other_shape_id, p_self_shape_id);588}589590void JoltArea3D::body_exited(const JPH::BodyID &p_body_id, bool p_notify) {591Overlap *overlap = bodies_by_id.getptr(p_body_id);592if (unlikely(overlap == nullptr)) {593return;594}595596if (unlikely(overlap->shape_pairs.is_empty())) {597return;598}599600for (const KeyValue<ShapeIDPair, ShapeIndexPair> &E : overlap->shape_pairs) {601overlap->pending_added.erase(E.value);602overlap->pending_removed.push_back(E.value);603}604605_events_changed();606607overlap->shape_pairs.clear();608609if (p_notify) {610_notify_body_exited(p_body_id);611}612}613614void JoltArea3D::area_exited(const JPH::BodyID &p_body_id) {615Overlap *overlap = areas_by_id.getptr(p_body_id);616if (unlikely(overlap == nullptr)) {617return;618}619620if (unlikely(overlap->shape_pairs.is_empty())) {621return;622}623624for (const KeyValue<ShapeIDPair, ShapeIndexPair> &E : overlap->shape_pairs) {625overlap->pending_added.erase(E.value);626overlap->pending_removed.push_back(E.value);627}628629_events_changed();630631overlap->shape_pairs.clear();632}633634void JoltArea3D::call_queries() {635_flush_events(bodies_by_id, body_monitor_callback);636_flush_events(areas_by_id, area_monitor_callback);637}638639640