Debian Codegraph @

scene/2d/physics/shape_cast_2d.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* shape_cast_2d.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "shape_cast_2d.h"
32
33 #include "core/config/engine.h"
34 #include "scene/2d/physics/collision_object_2d.h"
35 #include "scene/resources/world_2d.h"
36 #include "servers/physics_2d/physics_server_2d.h"
37
38 void ShapeCast2D::set_target_position(const Vector2 &p_point) {
39 target_position = p_point;
40 if (is_inside_tree() && (Engine::get_singleton()->is_editor_hint() || get_tree()->is_debugging_collisions_hint())) {
41 queue_redraw();
42 }
43 }
44
45 Vector2 ShapeCast2D::get_target_position() const {
46 return target_position;
47 }
48
49 void ShapeCast2D::set_margin(real_t p_margin) {
50 margin = p_margin;
51 }
52
53 real_t ShapeCast2D::get_margin() const {
54 return margin;
55 }
56
57 void ShapeCast2D::set_max_results(int p_max_results) {
58 max_results = p_max_results;
59 }
60
61 int ShapeCast2D::get_max_results() const {
62 return max_results;
63 }
64
65 void ShapeCast2D::set_collision_mask(uint32_t p_mask) {
66 collision_mask = p_mask;
67 }
68
69 uint32_t ShapeCast2D::get_collision_mask() const {
70 return collision_mask;
71 }
72
73 void ShapeCast2D::set_collision_mask_value(int p_layer_number, bool p_value) {
74 ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");
75 ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");
76 uint32_t mask = get_collision_mask();
77 if (p_value) {
78 mask |= 1 << (p_layer_number - 1);
79 } else {
80 mask &= ~(1 << (p_layer_number - 1));
81 }
82 set_collision_mask(mask);
83 }
84
85 bool ShapeCast2D::get_collision_mask_value(int p_layer_number) const {
86 ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");
87 ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");
88 return get_collision_mask() & (1 << (p_layer_number - 1));
89 }
90
91 int ShapeCast2D::get_collision_count() const {
92 return result.size();
93 }
94
95 bool ShapeCast2D::is_colliding() const {
96 return collided;
97 }
98
99 Object *ShapeCast2D::get_collider(int p_idx) const {
100 ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), nullptr, "No collider found.");
101
102 if (result[p_idx].collider_id.is_null()) {
103 return nullptr;
104 }
105 return ObjectDB::get_instance(result[p_idx].collider_id);
106 }
107
108 RID ShapeCast2D::get_collider_rid(int p_idx) const {
109 ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), RID(), "No collider RID found.");
110 return result[p_idx].rid;
111 }
112
113 int ShapeCast2D::get_collider_shape(int p_idx) const {
114 ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), -1, "No collider shape found.");
115 return result[p_idx].shape;
116 }
117
118 Vector2 ShapeCast2D::get_collision_point(int p_idx) const {
119 ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), Vector2(), "No collision point found.");
120 return result[p_idx].point;
121 }
122
123 Vector2 ShapeCast2D::get_collision_normal(int p_idx) const {
124 ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), Vector2(), "No collision normal found.");
125 return result[p_idx].normal;
126 }
127
128 real_t ShapeCast2D::get_closest_collision_safe_fraction() const {
129 return collision_safe_fraction;
130 }
131
132 real_t ShapeCast2D::get_closest_collision_unsafe_fraction() const {
133 return collision_unsafe_fraction;
134 }
135
136 void ShapeCast2D::set_enabled(bool p_enabled) {
137 enabled = p_enabled;
138 queue_redraw();
139 if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) {
140 set_physics_process_internal(p_enabled);
141 }
142 if (!p_enabled) {
143 collided = false;
144 }
145 }
146
147 bool ShapeCast2D::is_enabled() const {
148 return enabled;
149 }
150
151 void ShapeCast2D::set_shape(const Ref<Shape2D> &p_shape) {
152 if (p_shape == shape) {
153 return;
154 }
155 if (shape.is_valid()) {
156 shape->disconnect_changed(callable_mp(this, &ShapeCast2D::_shape_changed));
157 }
158 shape = p_shape;
159 if (shape.is_valid()) {
160 shape->connect_changed(callable_mp(this, &ShapeCast2D::_shape_changed));
161 shape_rid = shape->get_rid();
162 }
163
164 update_configuration_warnings();
165 queue_redraw();
166 }
167
168 Ref<Shape2D> ShapeCast2D::get_shape() const {
169 return shape;
170 }
171
172 void ShapeCast2D::set_exclude_parent_body(bool p_exclude_parent_body) {
173 if (exclude_parent_body == p_exclude_parent_body) {
174 return;
175 }
176 exclude_parent_body = p_exclude_parent_body;
177
178 if (!is_inside_tree()) {
179 return;
180 }
181 if (Object::cast_to<CollisionObject2D>(get_parent())) {
182 if (exclude_parent_body) {
183 exclude.insert(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());
184 } else {
185 exclude.erase(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());
186 }
187 }
188 }
189
190 bool ShapeCast2D::get_exclude_parent_body() const {
191 return exclude_parent_body;
192 }
193
194 void ShapeCast2D::_shape_changed() {
195 queue_redraw();
196 }
197
198 void ShapeCast2D::_notification(int p_what) {
199 switch (p_what) {
200 case NOTIFICATION_ENTER_TREE: {
201 if (enabled && !Engine::get_singleton()->is_editor_hint()) {
202 set_physics_process_internal(true);
203 } else {
204 set_physics_process_internal(false);
205 }
206 if (Object::cast_to<CollisionObject2D>(get_parent())) {
207 if (exclude_parent_body) {
208 exclude.insert(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());
209 } else {
210 exclude.erase(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());
211 }
212 }
213 } break;
214
215 case NOTIFICATION_EXIT_TREE: {
216 if (enabled) {
217 set_physics_process_internal(false);
218 }
219 } break;
220
221 case NOTIFICATION_DRAW: {
222 #ifdef TOOLS_ENABLED
223 ERR_FAIL_COND(!is_inside_tree());
224 if (!Engine::get_singleton()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) {
225 break;
226 }
227 if (shape.is_null()) {
228 break;
229 }
230 Color draw_col = collided ? Color(1.0, 0.01, 0) : get_tree()->get_debug_collisions_color();
231 if (!enabled) {
232 float g = draw_col.get_v();
233 draw_col.r = g;
234 draw_col.g = g;
235 draw_col.b = g;
236 }
237 // Draw continuous chain of shapes along the cast.
238 const int steps = MAX(2, target_position.length() / shape->get_rect().get_size().length() * 4);
239 for (int i = 0; i <= steps; ++i) {
240 Vector2 t = (real_t(i) / steps) * target_position;
241 draw_set_transform(t, 0.0, Size2(1, 1));
242 shape->draw(get_canvas_item(), draw_col);
243 }
244 draw_set_transform(Vector2(), 0.0, Size2(1, 1));
245
246 // Draw an arrow indicating where the ShapeCast is pointing to.
247 if (target_position != Vector2()) {
248 const real_t max_arrow_size = 6;
249 const real_t line_width = 1.4;
250 bool no_line = target_position.length() < line_width;
251 real_t arrow_size = CLAMP(target_position.length() * 2 / 3, line_width, max_arrow_size);
252
253 if (no_line) {
254 arrow_size = target_position.length();
255 } else {
256 draw_line(Vector2(), target_position - target_position.normalized() * arrow_size, draw_col, line_width);
257 }
258
259 Transform2D xf;
260 xf.rotate(target_position.angle());
261 xf.translate_local(Vector2(no_line ? 0 : target_position.length() - arrow_size, 0));
262
263 Vector<Vector2> pts = {
264 xf.xform(Vector2(arrow_size, 0)),
265 xf.xform(Vector2(0, 0.5 * arrow_size)),
266 xf.xform(Vector2(0, -0.5 * arrow_size))
267 };
268
269 Vector<Color> cols = { draw_col, draw_col, draw_col };
270
271 draw_primitive(pts, cols, Vector<Vector2>());
272 }
273 #endif
274 } break;
275
276 case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
277 if (!enabled) {
278 break;
279 }
280 _update_shapecast_state();
281 } break;
282 }
283 }
284
285 void ShapeCast2D::_update_shapecast_state() {
286 result.clear();
287
288 ERR_FAIL_COND_MSG(shape.is_null(), "Invalid shape.");
289
290 Ref<World2D> w2d = get_world_2d();
291 ERR_FAIL_COND(w2d.is_null());
292
293 PhysicsDirectSpaceState2D *dss = PhysicsServer2D::get_singleton()->space_get_direct_state(w2d->get_space());
294 ERR_FAIL_NULL(dss);
295
296 Transform2D gt = get_global_transform();
297
298 PhysicsDirectSpaceState2D::ShapeParameters params;
299 params.shape_rid = shape_rid;
300 params.transform = gt;
301 params.motion = gt.basis_xform(target_position);
302 params.margin = margin;
303 params.exclude = exclude;
304 params.collision_mask = collision_mask;
305 params.collide_with_bodies = collide_with_bodies;
306 params.collide_with_areas = collide_with_areas;
307
308 collision_safe_fraction = 0.0;
309 collision_unsafe_fraction = 0.0;
310
311 bool prev_collision_state = collided;
312
313 if (target_position != Vector2()) {
314 dss->cast_motion(params, collision_safe_fraction, collision_unsafe_fraction);
315 if (collision_unsafe_fraction < 1.0) {
316 // Move shape transform to the point of impact,
317 // so we can collect contact info at that point.
318 gt.set_origin(gt.get_origin() + params.motion * (collision_unsafe_fraction + CMP_EPSILON));
319 params.transform = gt;
320 }
321 }
322 // Regardless of whether the shape is stuck or it's moved along
323 // the motion vector, we'll only consider static collisions from now on.
324 params.motion = Vector2();
325
326 bool intersected = true;
327 while (intersected && result.size() < max_results) {
328 PhysicsDirectSpaceState2D::ShapeRestInfo info;
329 intersected = dss->rest_info(params, &info);
330 if (intersected) {
331 result.push_back(info);
332 params.exclude.insert(info.rid);
333 }
334 }
335 collided = !result.is_empty();
336
337 if (prev_collision_state != collided) {
338 queue_redraw();
339 }
340 }
341
342 void ShapeCast2D::force_shapecast_update() {
343 _update_shapecast_state();
344 }
345
346 void ShapeCast2D::add_exception_rid(const RID &p_rid) {
347 exclude.insert(p_rid);
348 }
349
350 void ShapeCast2D::add_exception(RequiredParam<const CollisionObject2D> rp_node) {
351 EXTRACT_PARAM_OR_FAIL_MSG(p_node, rp_node, "The passed Node must be an instance of CollisionObject2D.");
352 add_exception_rid(p_node->get_rid());
353 }
354
355 void ShapeCast2D::remove_exception_rid(const RID &p_rid) {
356 exclude.erase(p_rid);
357 }
358
359 void ShapeCast2D::remove_exception(RequiredParam<const CollisionObject2D> rp_node) {
360 EXTRACT_PARAM_OR_FAIL_MSG(p_node, rp_node, "The passed Node must be an instance of CollisionObject2D.");
361 remove_exception_rid(p_node->get_rid());
362 }
363
364 void ShapeCast2D::clear_exceptions() {
365 exclude.clear();
366 }
367
368 void ShapeCast2D::set_collide_with_areas(bool p_clip) {
369 collide_with_areas = p_clip;
370 }
371
372 bool ShapeCast2D::is_collide_with_areas_enabled() const {
373 return collide_with_areas;
374 }
375
376 void ShapeCast2D::set_collide_with_bodies(bool p_clip) {
377 collide_with_bodies = p_clip;
378 }
379
380 bool ShapeCast2D::is_collide_with_bodies_enabled() const {
381 return collide_with_bodies;
382 }
383
384 Array ShapeCast2D::get_collision_result() const {
385 Array ret;
386
387 for (int i = 0; i < result.size(); ++i) {
388 const PhysicsDirectSpaceState2D::ShapeRestInfo &sri = result[i];
389
390 Dictionary col;
391 col["point"] = sri.point;
392 col["normal"] = sri.normal;
393 col["rid"] = sri.rid;
394 col["collider"] = ObjectDB::get_instance(sri.collider_id);
395 col["collider_id"] = sri.collider_id;
396 col["shape"] = sri.shape;
397 col["linear_velocity"] = sri.linear_velocity;
398
399 ret.push_back(col);
400 }
401 return ret;
402 }
403
404 PackedStringArray ShapeCast2D::get_configuration_warnings() const {
405 PackedStringArray warnings = Node2D::get_configuration_warnings();
406
407 if (shape.is_null()) {
408 warnings.push_back(RTR("This node cannot interact with other objects unless a Shape2D is assigned."));
409 }
410 return warnings;
411 }
412
413 void ShapeCast2D::_bind_methods() {
414 ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &ShapeCast2D::set_enabled);
415 ClassDB::bind_method(D_METHOD("is_enabled"), &ShapeCast2D::is_enabled);
416
417 ClassDB::bind_method(D_METHOD("set_shape", "shape"), &ShapeCast2D::set_shape);
418 ClassDB::bind_method(D_METHOD("get_shape"), &ShapeCast2D::get_shape);
419
420 ClassDB::bind_method(D_METHOD("set_target_position", "local_point"), &ShapeCast2D::set_target_position);
421 ClassDB::bind_method(D_METHOD("get_target_position"), &ShapeCast2D::get_target_position);
422
423 ClassDB::bind_method(D_METHOD("set_margin", "margin"), &ShapeCast2D::set_margin);
424 ClassDB::bind_method(D_METHOD("get_margin"), &ShapeCast2D::get_margin);
425
426 ClassDB::bind_method(D_METHOD("set_max_results", "max_results"), &ShapeCast2D::set_max_results);
427 ClassDB::bind_method(D_METHOD("get_max_results"), &ShapeCast2D::get_max_results);
428
429 ClassDB::bind_method(D_METHOD("is_colliding"), &ShapeCast2D::is_colliding);
430 ClassDB::bind_method(D_METHOD("get_collision_count"), &ShapeCast2D::get_collision_count);
431
432 ClassDB::bind_method(D_METHOD("force_shapecast_update"), &ShapeCast2D::force_shapecast_update);
433
434 ClassDB::bind_method(D_METHOD("get_collider", "index"), &ShapeCast2D::get_collider);
435 ClassDB::bind_method(D_METHOD("get_collider_rid", "index"), &ShapeCast2D::get_collider_rid);
436 ClassDB::bind_method(D_METHOD("get_collider_shape", "index"), &ShapeCast2D::get_collider_shape);
437 ClassDB::bind_method(D_METHOD("get_collision_point", "index"), &ShapeCast2D::get_collision_point);
438 ClassDB::bind_method(D_METHOD("get_collision_normal", "index"), &ShapeCast2D::get_collision_normal);
439
440 ClassDB::bind_method(D_METHOD("get_closest_collision_safe_fraction"), &ShapeCast2D::get_closest_collision_safe_fraction);
441 ClassDB::bind_method(D_METHOD("get_closest_collision_unsafe_fraction"), &ShapeCast2D::get_closest_collision_unsafe_fraction);
442
443 ClassDB::bind_method(D_METHOD("add_exception_rid", "rid"), &ShapeCast2D::add_exception_rid);
444 ClassDB::bind_method(D_METHOD("add_exception", "node"), &ShapeCast2D::add_exception);
445
446 ClassDB::bind_method(D_METHOD("remove_exception_rid", "rid"), &ShapeCast2D::remove_exception_rid);
447 ClassDB::bind_method(D_METHOD("remove_exception", "node"), &ShapeCast2D::remove_exception);
448
449 ClassDB::bind_method(D_METHOD("clear_exceptions"), &ShapeCast2D::clear_exceptions);
450
451 ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &ShapeCast2D::set_collision_mask);
452 ClassDB::bind_method(D_METHOD("get_collision_mask"), &ShapeCast2D::get_collision_mask);
453
454 ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &ShapeCast2D::set_collision_mask_value);
455 ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &ShapeCast2D::get_collision_mask_value);
456
457 ClassDB::bind_method(D_METHOD("set_exclude_parent_body", "mask"), &ShapeCast2D::set_exclude_parent_body);
458 ClassDB::bind_method(D_METHOD("get_exclude_parent_body"), &ShapeCast2D::get_exclude_parent_body);
459
460 ClassDB::bind_method(D_METHOD("set_collide_with_areas", "enable"), &ShapeCast2D::set_collide_with_areas);
461 ClassDB::bind_method(D_METHOD("is_collide_with_areas_enabled"), &ShapeCast2D::is_collide_with_areas_enabled);
462
463 ClassDB::bind_method(D_METHOD("set_collide_with_bodies", "enable"), &ShapeCast2D::set_collide_with_bodies);
464 ClassDB::bind_method(D_METHOD("is_collide_with_bodies_enabled"), &ShapeCast2D::is_collide_with_bodies_enabled);
465
466 ClassDB::bind_method(D_METHOD("get_collision_result"), &ShapeCast2D::get_collision_result);
467
468 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
469 ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D"), "set_shape", "get_shape");
470 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "exclude_parent"), "set_exclude_parent_body", "get_exclude_parent_body");
471 ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "target_position", PROPERTY_HINT_NONE, "suffix:px"), "set_target_position", "get_target_position");
472 ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "margin", PROPERTY_HINT_RANGE, "0,100,0.01,suffix:px"), "set_margin", "get_margin");
473 ADD_PROPERTY(PropertyInfo(Variant::INT, "max_results"), "set_max_results", "get_max_results");
474 ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_mask", "get_collision_mask");
475 ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "collision_result", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "", "get_collision_result");
476 ADD_GROUP("Collide With", "collide_with");
477 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with_areas"), "set_collide_with_areas", "is_collide_with_areas_enabled");
478 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with_bodies"), "set_collide_with_bodies", "is_collide_with_bodies_enabled");
479 }
480
481 ShapeCast2D::ShapeCast2D() {
482 set_hide_clip_children(true);
483 }