From 5dbf1809c6e3e905b94b8764e99491e608122261 Mon Sep 17 00:00:00 2001 From: Rémi Verschelde Date: Sun, 5 Mar 2017 16:44:50 +0100 Subject: A Whole New World (clang-format edition) I can show you the code Pretty, with proper whitespace Tell me, coder, now when did You last write readable code? I can open your eyes Make you see your bad indent Force you to respect the style The core devs agreed upon A whole new world A new fantastic code format A de facto standard With some sugar Enforced with clang-format A whole new world A dazzling style we all dreamed of And when we read it through It's crystal clear That now we're in a whole new world of code --- scene/2d/animated_sprite.cpp | 408 ++-- scene/2d/animated_sprite.h | 86 +- scene/2d/area_2d.cpp | 489 ++-- scene/2d/area_2d.h | 45 +- scene/2d/back_buffer_copy.cpp | 50 +- scene/2d/back_buffer_copy.h | 9 +- scene/2d/camera_2d.cpp | 452 ++-- scene/2d/camera_2d.h | 19 +- scene/2d/canvas_item.cpp | 651 +++-- scene/2d/canvas_item.h | 112 +- scene/2d/canvas_modulate.cpp | 56 +- scene/2d/canvas_modulate.h | 7 +- scene/2d/collision_object_2d.cpp | 228 +- scene/2d/collision_object_2d.h | 30 +- scene/2d/collision_polygon_2d.cpp | 203 +- scene/2d/collision_polygon_2d.h | 19 +- scene/2d/collision_shape_2d.cpp | 107 +- scene/2d/collision_shape_2d.h | 7 +- scene/2d/joints_2d.cpp | 265 +-- scene/2d/joints_2d.h | 31 +- scene/2d/light_2d.cpp | 363 ++- scene/2d/light_2d.h | 51 +- scene/2d/light_occluder_2d.cpp | 132 +- scene/2d/light_occluder_2d.h | 19 +- scene/2d/line_2d.cpp | 105 +- scene/2d/line_2d.h | 10 +- scene/2d/line_builder.cpp | 214 +- scene/2d/line_builder.h | 6 +- scene/2d/navigation2d.cpp | 556 ++--- scene/2d/navigation2d.h | 79 +- scene/2d/navigation_polygon.cpp | 291 ++- scene/2d/navigation_polygon.h | 34 +- scene/2d/node_2d.cpp | 289 +-- scene/2d/node_2d.h | 38 +- scene/2d/parallax_background.cpp | 128 +- scene/2d/parallax_background.h | 22 +- scene/2d/parallax_layer.cpp | 89 +- scene/2d/parallax_layer.h | 12 +- scene/2d/particles_2d.cpp | 814 +++---- scene/2d/particles_2d.h | 54 +- scene/2d/path_2d.cpp | 230 +- scene/2d/path_2d.h | 29 +- scene/2d/path_texture.cpp | 40 +- scene/2d/path_texture.h | 10 +- scene/2d/physics_body_2d.cpp | 1030 ++++---- scene/2d/physics_body_2d.h | 86 +- scene/2d/polygon_2d.cpp | 300 ++- scene/2d/polygon_2d.h | 23 +- scene/2d/position_2d.cpp | 13 +- scene/2d/position_2d.h | 7 +- scene/2d/ray_cast_2d.cpp | 178 +- scene/2d/ray_cast_2d.h | 18 +- scene/2d/remote_transform_2d.cpp | 32 +- scene/2d/remote_transform_2d.h | 7 +- scene/2d/screen_button.cpp | 240 +- scene/2d/screen_button.h | 25 +- scene/2d/sprite.cpp | 190 +- scene/2d/sprite.h | 17 +- scene/2d/tile_map.cpp | 923 ++++--- scene/2d/tile_map.h | 114 +- scene/2d/visibility_notifier_2d.cpp | 218 +- scene/2d/visibility_notifier_2d.h | 34 +- scene/2d/y_sort.cpp | 19 +- scene/2d/y_sort.h | 4 +- scene/3d/area.cpp | 488 ++-- scene/3d/area.h | 46 +- scene/3d/baked_light_instance.cpp | 1437 ++++++----- scene/3d/baked_light_instance.h | 70 +- scene/3d/body_shape.cpp | 166 +- scene/3d/body_shape.h | 10 +- scene/3d/bone_attachment.cpp | 65 +- scene/3d/bone_attachment.h | 13 +- scene/3d/camera.cpp | 448 ++-- scene/3d/camera.h | 46 +- scene/3d/character_camera.cpp | 1 - scene/3d/character_camera.h | 1 - scene/3d/collision_object.cpp | 232 +- scene/3d/collision_object.h | 36 +- scene/3d/collision_polygon.cpp | 134 +- scene/3d/collision_polygon.h | 18 +- scene/3d/gi_probe.cpp | 1317 +++++----- scene/3d/gi_probe.h | 72 +- scene/3d/immediate_geometry.cpp | 120 +- scene/3d/immediate_geometry.h | 27 +- scene/3d/interpolated_camera.cpp | 66 +- scene/3d/interpolated_camera.h | 8 +- scene/3d/light.cpp | 366 ++- scene/3d/light.h | 45 +- scene/3d/listener.cpp | 62 +- scene/3d/listener.h | 15 +- scene/3d/mesh_instance.cpp | 166 +- scene/3d/mesh_instance.h | 28 +- scene/3d/multimesh_instance.cpp | 22 +- scene/3d/multimesh_instance.h | 10 +- scene/3d/navigation.cpp | 577 +++-- scene/3d/navigation.h | 94 +- scene/3d/navigation_mesh.cpp | 240 +- scene/3d/navigation_mesh.h | 28 +- scene/3d/particles.cpp | 2 +- scene/3d/particles.h | 4 +- scene/3d/path.cpp | 242 +- scene/3d/path.h | 25 +- scene/3d/physics_body.cpp | 942 ++++---- scene/3d/physics_body.h | 89 +- scene/3d/physics_joint.cpp | 1080 ++++----- scene/3d/physics_joint.h | 210 +- scene/3d/portal.cpp | 158 +- scene/3d/portal.h | 17 +- scene/3d/position_3d.cpp | 4 +- scene/3d/position_3d.h | 6 +- scene/3d/proximity_group.cpp | 45 +- scene/3d/proximity_group.h | 8 +- scene/3d/quad.cpp | 153 +- scene/3d/quad.h | 13 +- scene/3d/ray_cast.cpp | 139 +- scene/3d/ray_cast.h | 16 +- scene/3d/reflection_probe.cpp | 226 +- scene/3d/reflection_probe.h | 20 +- scene/3d/remote_transform.cpp | 30 +- scene/3d/remote_transform.h | 19 +- scene/3d/room_instance.cpp | 92 +- scene/3d/room_instance.h | 25 +- scene/3d/scenario_fx.cpp | 46 +- scene/3d/scenario_fx.h | 9 +- scene/3d/skeleton.cpp | 393 ++- scene/3d/skeleton.h | 50 +- scene/3d/spatial.cpp | 407 ++-- scene/3d/spatial.h | 81 +- scene/3d/spatial_indexer.cpp | 2 +- scene/3d/sprite_3d.cpp | 721 +++--- scene/3d/sprite_3d.h | 67 +- scene/3d/test_cube.cpp | 8 +- scene/3d/test_cube.h | 9 +- scene/3d/vehicle_body.cpp | 743 +++--- scene/3d/vehicle_body.h | 98 +- scene/3d/visibility_notifier.cpp | 176 +- scene/3d/visibility_notifier.h | 33 +- scene/3d/visual_instance.cpp | 232 +- scene/3d/visual_instance.h | 62 +- scene/animation/animation_cache.cpp | 206 +- scene/animation/animation_cache.h | 29 +- scene/animation/animation_player.cpp | 911 ++++--- scene/animation/animation_player.h | 162 +- scene/animation/animation_tree_player.cpp | 1485 ++++++------ scene/animation/animation_tree_player.h | 286 ++- scene/animation/tween.cpp | 1038 ++++---- scene/animation/tween.h | 167 +- scene/animation/tween_interpolaters.cpp | 450 ++-- scene/audio/audio_player.cpp | 184 +- scene/audio/audio_player.h | 16 +- scene/gui/base_button.cpp | 299 ++- scene/gui/base_button.h | 39 +- scene/gui/box_container.cpp | 181 +- scene/gui/box_container.h | 27 +- scene/gui/button.cpp | 167 +- scene/gui/button.h | 23 +- scene/gui/button_array.cpp | 472 ++-- scene/gui/button_array.h | 46 +- scene/gui/center_container.cpp | 33 +- scene/gui/center_container.h | 7 +- scene/gui/check_box.cpp | 45 +- scene/gui/check_box.h | 15 +- scene/gui/check_button.cpp | 27 +- scene/gui/check_button.h | 6 +- scene/gui/color_picker.cpp | 406 ++-- scene/gui/color_picker.h | 45 +- scene/gui/color_ramp_edit.cpp | 292 ++- scene/gui/color_ramp_edit.h | 15 +- scene/gui/color_rect.cpp | 19 +- scene/gui/color_rect.h | 10 +- scene/gui/container.cpp | 65 +- scene/gui/container.h | 9 +- scene/gui/control.cpp | 1831 +++++++------- scene/gui/control.h | 204 +- scene/gui/dialogs.cpp | 216 +- scene/gui/dialogs.h | 56 +- scene/gui/file_dialog.cpp | 593 +++-- scene/gui/file_dialog.h | 46 +- scene/gui/graph_edit.cpp | 862 +++---- scene/gui/graph_edit.h | 68 +- scene/gui/graph_node.cpp | 556 ++--- scene/gui/graph_node.h | 47 +- scene/gui/grid_container.cpp | 149 +- scene/gui/grid_container.h | 6 +- scene/gui/input_action.cpp | 70 +- scene/gui/input_action.h | 10 +- scene/gui/item_list.cpp | 1094 ++++----- scene/gui/item_list.h | 51 +- scene/gui/label.cpp | 565 +++-- scene/gui/label.h | 28 +- scene/gui/line_edit.cpp | 648 +++-- scene/gui/line_edit.h | 15 +- scene/gui/link_button.cpp | 73 +- scene/gui/link_button.h | 12 +- scene/gui/margin_container.cpp | 18 +- scene/gui/margin_container.h | 4 +- scene/gui/menu_button.cpp | 39 +- scene/gui/menu_button.h | 11 +- scene/gui/option_button.cpp | 212 +- scene/gui/option_button.h | 26 +- scene/gui/panel.cpp | 10 +- scene/gui/panel.h | 10 +- scene/gui/panel_container.cpp | 46 +- scene/gui/panel_container.h | 5 +- scene/gui/patch_9_rect.cpp | 88 +- scene/gui/patch_9_rect.h | 12 +- scene/gui/popup.cpp | 160 +- scene/gui/popup.h | 26 +- scene/gui/popup_menu.cpp | 812 +++---- scene/gui/popup_menu.h | 83 +- scene/gui/progress_bar.cpp | 38 +- scene/gui/progress_bar.h | 6 +- scene/gui/range.cpp | 162 +- scene/gui/range.h | 17 +- scene/gui/reference_rect.cpp | 7 +- scene/gui/reference_rect.h | 4 +- scene/gui/rich_text_label.cpp | 1704 +++++++------ scene/gui/rich_text_label.h | 127 +- scene/gui/scroll_bar.cpp | 519 ++-- scene/gui/scroll_bar.h | 32 +- scene/gui/scroll_container.cpp | 310 ++- scene/gui/scroll_container.h | 9 +- scene/gui/separator.cpp | 29 +- scene/gui/separator.h | 15 +- scene/gui/slider.cpp | 155 +- scene/gui/slider.h | 23 +- scene/gui/spin_box.cpp | 169 +- scene/gui/spin_box.h | 20 +- scene/gui/split_container.cpp | 290 +-- scene/gui/split_container.h | 32 +- scene/gui/tab_container.cpp | 75 +- scene/gui/tab_container.h | 28 +- scene/gui/tabs.cpp | 491 ++-- scene/gui/tabs.h | 25 +- scene/gui/text_edit.cpp | 2903 +++++++++++------------ scene/gui/text_edit.h | 154 +- scene/gui/texture_button.cpp | 141 +- scene/gui/texture_button.h | 21 +- scene/gui/texture_progress.cpp | 319 ++- scene/gui/texture_progress.h | 14 +- scene/gui/texture_rect.cpp | 104 +- scene/gui/texture_rect.h | 13 +- scene/gui/tool_button.h | 3 +- scene/gui/tree.cpp | 2713 ++++++++++----------- scene/gui/tree.h | 223 +- scene/gui/video_player.cpp | 168 +- scene/gui/video_player.h | 21 +- scene/gui/viewport_container.cpp | 41 +- scene/gui/viewport_container.h | 6 +- scene/io/resource_format_image.cpp | 4 +- scene/main/canvas_layer.cpp | 167 +- scene/main/canvas_layer.h | 15 +- scene/main/http_request.cpp | 377 ++- scene/main/http_request.h | 21 +- scene/main/instance_placeholder.cpp | 51 +- scene/main/instance_placeholder.h | 13 +- scene/main/node.cpp | 1848 +++++++-------- scene/main/node.h | 209 +- scene/main/resource_preloader.cpp | 101 +- scene/main/resource_preloader.h | 21 +- scene/main/scene_main_loop.cpp | 1417 +++++------ scene/main/scene_main_loop.h | 246 +- scene/main/timer.cpp | 82 +- scene/main/timer.h | 7 +- scene/main/viewport.cpp | 1515 +++++------- scene/main/viewport.h | 157 +- scene/register_scene_types.cpp | 271 +-- scene/resources/animation.cpp | 1562 ++++++------ scene/resources/animation.h | 149 +- scene/resources/audio_stream_resampled.cpp | 1 - scene/resources/audio_stream_sample.cpp | 435 ++-- scene/resources/audio_stream_sample.h | 36 +- scene/resources/baked_light.cpp | 1 - scene/resources/baked_light.h | 2 - scene/resources/bit_mask.cpp | 145 +- scene/resources/bit_mask.h | 21 +- scene/resources/bounds.cpp | 16 +- scene/resources/bounds.h | 8 +- scene/resources/box_shape.cpp | 32 +- scene/resources/box_shape.h | 6 +- scene/resources/canvas.cpp | 4 +- scene/resources/canvas.h | 4 +- scene/resources/capsule_shape.cpp | 70 +- scene/resources/capsule_shape.h | 6 +- scene/resources/capsule_shape_2d.cpp | 50 +- scene/resources/capsule_shape_2d.h | 10 +- scene/resources/circle_shape_2d.cpp | 31 +- scene/resources/circle_shape_2d.h | 9 +- scene/resources/color_ramp.cpp | 86 +- scene/resources/color_ramp.h | 59 +- scene/resources/concave_polygon_shape.cpp | 62 +- scene/resources/concave_polygon_shape.h | 33 +- scene/resources/concave_polygon_shape_2d.cpp | 42 +- scene/resources/concave_polygon_shape_2d.h | 12 +- scene/resources/convex_polygon_shape.cpp | 37 +- scene/resources/convex_polygon_shape.h | 7 +- scene/resources/convex_polygon_shape_2d.cpp | 53 +- scene/resources/convex_polygon_shape_2d.h | 14 +- scene/resources/curve.cpp | 824 +++---- scene/resources/curve.h | 57 +- scene/resources/default_theme/default_theme.cpp | 1166 +++++---- scene/resources/default_theme/default_theme.h | 2 +- scene/resources/dynamic_font.cpp | 702 +++--- scene/resources/dynamic_font.h | 103 +- scene/resources/dynamic_font_stb.cpp | 334 ++- scene/resources/dynamic_font_stb.h | 70 +- scene/resources/environment.cpp | 966 ++++---- scene/resources/environment.h | 33 +- scene/resources/font.cpp | 407 ++-- scene/resources/font.h | 73 +- scene/resources/material.cpp | 1110 +++++---- scene/resources/material.h | 106 +- scene/resources/mesh.cpp | 716 +++--- scene/resources/mesh.h | 133 +- scene/resources/mesh_data_tool.cpp | 485 ++-- scene/resources/mesh_data_tool.h | 42 +- scene/resources/mesh_library.cpp | 175 +- scene/resources/mesh_library.h | 32 +- scene/resources/multimesh.cpp | 183 +- scene/resources/multimesh.h | 24 +- scene/resources/packed_scene.cpp | 1128 ++++----- scene/resources/packed_scene.h | 81 +- scene/resources/plane_shape.cpp | 31 +- scene/resources/plane_shape.h | 5 +- scene/resources/polygon_path_finder.cpp | 487 ++-- scene/resources/polygon_path_finder.h | 38 +- scene/resources/ray_shape.cpp | 17 +- scene/resources/ray_shape.h | 5 +- scene/resources/rectangle_shape_2d.cpp | 31 +- scene/resources/rectangle_shape_2d.h | 12 +- scene/resources/room.cpp | 22 +- scene/resources/room.h | 13 +- scene/resources/scene_format_text.cpp | 873 +++---- scene/resources/scene_format_text.h | 71 +- scene/resources/segment_shape_2d.cpp | 101 +- scene/resources/segment_shape_2d.h | 23 +- scene/resources/shader.cpp | 77 +- scene/resources/shader.h | 56 +- scene/resources/shader_graph.cpp | 47 +- scene/resources/shader_graph.h | 1 - scene/resources/shape.cpp | 39 +- scene/resources/shape.h | 10 +- scene/resources/shape_2d.cpp | 82 +- scene/resources/shape_2d.h | 21 +- scene/resources/shape_line_2d.cpp | 52 +- scene/resources/shape_line_2d.h | 10 +- scene/resources/sky_box.cpp | 134 +- scene/resources/sky_box.h | 19 +- scene/resources/space_2d.cpp | 18 +- scene/resources/space_2d.h | 10 +- scene/resources/sphere_shape.cpp | 40 +- scene/resources/sphere_shape.h | 6 +- scene/resources/style_box.cpp | 290 +-- scene/resources/style_box.h | 55 +- scene/resources/surface_tool.cpp | 737 +++--- scene/resources/surface_tool.h | 87 +- scene/resources/texture.cpp | 1111 ++++----- scene/resources/texture.h | 237 +- scene/resources/theme.cpp | 690 +++--- scene/resources/theme.h | 171 +- scene/resources/tile_set.cpp | 373 ++- scene/resources/tile_set.h | 51 +- scene/resources/video_stream.cpp | 6 +- scene/resources/video_stream.h | 50 +- scene/resources/world.cpp | 190 +- scene/resources/world.h | 29 +- scene/resources/world_2d.cpp | 234 +- scene/resources/world_2d.h | 28 +- scene/scene_string_names.cpp | 186 +- scene/scene_string_names.h | 22 +- 370 files changed, 34422 insertions(+), 41571 deletions(-) (limited to 'scene') diff --git a/scene/2d/animated_sprite.cpp b/scene/2d/animated_sprite.cpp index faecbf3e6..f10bd2f30 100644 --- a/scene/2d/animated_sprite.cpp +++ b/scene/2d/animated_sprite.cpp @@ -27,24 +27,19 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "animated_sprite.h" -#include "scene/scene_string_names.h" #include "os/os.h" #include "scene/scene_string_names.h" - - - +#include "scene/scene_string_names.h" //////////////////////////// +void SpriteFrames::add_frame(const StringName &p_anim, const Ref &p_frame, int p_at_pos) { - -void SpriteFrames::add_frame(const StringName &p_anim, const Ref& p_frame, int p_at_pos) { - - Map::Element *E=animations.find(p_anim); + Map::Element *E = animations.find(p_anim); ERR_FAIL_COND(!E); - if (p_at_pos>=0 && p_at_posget().frames.size()) - E->get().frames.insert(p_at_pos,p_frame); + if (p_at_pos >= 0 && p_at_pos < E->get().frames.size()) + E->get().frames.insert(p_at_pos, p_frame); else E->get().frames.push_back(p_frame); @@ -52,15 +47,15 @@ void SpriteFrames::add_frame(const StringName &p_anim, const Ref& p_fra } int SpriteFrames::get_frame_count(const StringName &p_anim) const { - const Map::Element *E=animations.find(p_anim); - ERR_FAIL_COND_V(!E,0); + const Map::Element *E = animations.find(p_anim); + ERR_FAIL_COND_V(!E, 0); return E->get().frames.size(); } void SpriteFrames::remove_frame(const StringName &p_anim, int p_idx) { - Map::Element *E=animations.find(p_anim); + Map::Element *E = animations.find(p_anim); ERR_FAIL_COND(!E); E->get().frames.remove(p_idx); @@ -68,7 +63,7 @@ void SpriteFrames::remove_frame(const StringName &p_anim, int p_idx) { } void SpriteFrames::clear(const StringName &p_anim) { - Map::Element *E=animations.find(p_anim); + Map::Element *E = animations.find(p_anim); ERR_FAIL_COND(!E); E->get().frames.clear(); @@ -81,33 +76,30 @@ void SpriteFrames::clear_all() { add_animation("default"); } - - -void SpriteFrames::add_animation(const StringName& p_anim) { +void SpriteFrames::add_animation(const StringName &p_anim) { ERR_FAIL_COND(animations.has(p_anim)); - animations[p_anim]=Anim(); + animations[p_anim] = Anim(); } -bool SpriteFrames::has_animation(const StringName& p_anim) const{ +bool SpriteFrames::has_animation(const StringName &p_anim) const { return animations.has(p_anim); } -void SpriteFrames::remove_animation(const StringName& p_anim){ +void SpriteFrames::remove_animation(const StringName &p_anim) { animations.erase(p_anim); } -void SpriteFrames::rename_animation(const StringName& p_prev,const StringName& p_next) { +void SpriteFrames::rename_animation(const StringName &p_prev, const StringName &p_next) { ERR_FAIL_COND(!animations.has(p_prev)); ERR_FAIL_COND(animations.has(p_next)); Anim anim = animations[p_prev]; animations.erase(p_prev); - animations[p_next]=anim; - + animations[p_next] = anim; } Vector SpriteFrames::_get_animation_list() const { @@ -115,7 +107,7 @@ Vector SpriteFrames::_get_animation_list() const { Vector ret; List al; get_animation_list(&al); - for(List::Element *E=al.front();E;E=E->next()) { + for (List::Element *E = al.front(); E; E = E->next()) { ret.push_back(E->get()); } @@ -123,49 +115,47 @@ Vector SpriteFrames::_get_animation_list() const { return ret; } -void SpriteFrames::get_animation_list(List *r_animations) const{ +void SpriteFrames::get_animation_list(List *r_animations) const { - for (const Map::Element *E=animations.front();E;E=E->next()) { + for (const Map::Element *E = animations.front(); E; E = E->next()) { r_animations->push_back(E->key()); } } -void SpriteFrames::set_animation_speed(const StringName& p_anim,float p_fps){ +void SpriteFrames::set_animation_speed(const StringName &p_anim, float p_fps) { - ERR_FAIL_COND(p_fps<0); - Map::Element *E=animations.find(p_anim); + ERR_FAIL_COND(p_fps < 0); + Map::Element *E = animations.find(p_anim); ERR_FAIL_COND(!E); - E->get().speed=p_fps; + E->get().speed = p_fps; } -float SpriteFrames::get_animation_speed(const StringName& p_anim) const{ +float SpriteFrames::get_animation_speed(const StringName &p_anim) const { - const Map::Element *E=animations.find(p_anim); - ERR_FAIL_COND_V(!E,0); + const Map::Element *E = animations.find(p_anim); + ERR_FAIL_COND_V(!E, 0); return E->get().speed; } -void SpriteFrames::set_animation_loop(const StringName& p_anim,bool p_loop){ - Map::Element *E=animations.find(p_anim); +void SpriteFrames::set_animation_loop(const StringName &p_anim, bool p_loop) { + Map::Element *E = animations.find(p_anim); ERR_FAIL_COND(!E); - E->get().loop=p_loop; + E->get().loop = p_loop; } -bool SpriteFrames::get_animation_loop(const StringName& p_anim) const{ - const Map::Element *E=animations.find(p_anim); - ERR_FAIL_COND_V(!E,false); +bool SpriteFrames::get_animation_loop(const StringName &p_anim) const { + const Map::Element *E = animations.find(p_anim); + ERR_FAIL_COND_V(!E, false); return E->get().loop; - } -void SpriteFrames::_set_frames(const Array& p_frames) { +void SpriteFrames::_set_frames(const Array &p_frames) { clear_all(); - Map::Element *E=animations.find(SceneStringNames::get_singleton()->_default); + Map::Element *E = animations.find(SceneStringNames::get_singleton()->_default); ERR_FAIL_COND(!E); E->get().frames.resize(p_frames.size()); - for(int i=0;iget().frames.size();i++) - E->get().frames[i]=p_frames[i]; - + for (int i = 0; i < E->get().frames.size(); i++) + E->get().frames[i] = p_frames[i]; } Array SpriteFrames::_get_frames() const { @@ -175,27 +165,27 @@ Array SpriteFrames::_get_frames() const { Array SpriteFrames::_get_animations() const { Array anims; - for (Map::Element *E=animations.front();E;E=E->next()) { + for (Map::Element *E = animations.front(); E; E = E->next()) { Dictionary d; - d["name"]=E->key(); - d["speed"]=E->get().speed; - d["loop"]=E->get().loop; + d["name"] = E->key(); + d["speed"] = E->get().speed; + d["loop"] = E->get().loop; Array frames; - for(int i=0;iget().frames.size();i++) { + for (int i = 0; i < E->get().frames.size(); i++) { frames.push_back(E->get().frames[i]); } - d["frames"]=frames; + d["frames"] = frames; anims.push_back(d); } return anims; } -void SpriteFrames::_set_animations(const Array& p_animations) { +void SpriteFrames::_set_animations(const Array &p_animations) { animations.clear(); - for(int i=0;i_default); - } - - - - - -void AnimatedSprite::edit_set_pivot(const Point2& p_pivot) { +void AnimatedSprite::edit_set_pivot(const Point2 &p_pivot) { set_offset(p_pivot); } @@ -281,88 +257,85 @@ bool AnimatedSprite::edit_has_pivot() const { return true; } - -void AnimatedSprite::_validate_property(PropertyInfo& property) const { +void AnimatedSprite::_validate_property(PropertyInfo &property) const { if (!frames.is_valid()) return; - if (property.name=="animation") { + if (property.name == "animation") { - property.hint=PROPERTY_HINT_ENUM; + property.hint = PROPERTY_HINT_ENUM; List names; frames->get_animation_list(&names); names.sort_custom(); - bool current_found=false; + bool current_found = false; - for (List::Element *E=names.front();E;E=E->next()) { + for (List::Element *E = names.front(); E; E = E->next()) { if (E->prev()) { - property.hint_string+=","; + property.hint_string += ","; } - property.hint_string+=String(E->get()); - if (animation==E->get()) { - current_found=true; + property.hint_string += String(E->get()); + if (animation == E->get()) { + current_found = true; } } if (!current_found) { - if (property.hint_string==String()) { - property.hint_string=String(animation); + if (property.hint_string == String()) { + property.hint_string = String(animation); } else { - property.hint_string=String(animation)+","+property.hint_string; + property.hint_string = String(animation) + "," + property.hint_string; } } } + if (property.name == "frame") { - if (property.name=="frame") { - - property.hint=PROPERTY_HINT_SPRITE_FRAME; + property.hint = PROPERTY_HINT_SPRITE_FRAME; if (frames->has_animation(animation)) { - property.hint_string="0,"+itos(frames->get_frame_count(animation)-1)+",1"; + property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1"; } else { - property.hint_string="0,0,0"; + property.hint_string = "0,0,0"; } } - } void AnimatedSprite::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_INTERNAL_PROCESS: { if (frames.is_null()) return; if (!frames->has_animation(animation)) return; - if (frame<0) + if (frame < 0) return; float speed = frames->get_animation_speed(animation); - if (speed==0) + if (speed == 0) return; //do nothing float remaining = get_process_delta_time(); - while(remaining) { + while (remaining) { - if (timeout<=0) { + if (timeout <= 0) { - timeout=1.0/speed; + timeout = 1.0 / speed; int fc = frames->get_frame_count(animation); - if (frame>=fc-1) { + if (frame >= fc - 1) { if (frames->get_animation_loop(animation)) { - frame=0; + frame = 0; } else { - frame=fc-1; + frame = fc - 1; } } else { frame++; - if (frame==fc-1) { + if (frame == fc - 1) { emit_signal(SceneStringNames::get_singleton()->animation_finished); } } @@ -371,9 +344,9 @@ void AnimatedSprite::_notification(int p_what) { _change_notify("frame"); } - float to_process = MIN(timeout,remaining); - remaining-=to_process; - timeout-=to_process; + float to_process = MIN(timeout, remaining); + remaining -= to_process; + timeout -= to_process; } } break; @@ -384,19 +357,17 @@ void AnimatedSprite::_notification(int p_what) { return; } - if (frame<0) { + if (frame < 0) { print_line("no draw frame <0"); return; } if (!frames->has_animation(animation)) { - print_line("no draw no anim: "+String(animation)); + print_line("no draw no anim: " + String(animation)); return; } - - - Ref texture = frames->get_frame(animation,frame); + Ref texture = frames->get_frame(animation, frame); if (texture.is_null()) { print_line("no draw texture is null"); return; @@ -413,50 +384,46 @@ void AnimatedSprite::_notification(int p_what) { Size2i s; s = texture->get_size(); - Point2 ofs=offset; + Point2 ofs = offset; if (centered) - ofs-=s/2; + ofs -= s / 2; if (Engine::get_singleton()->get_use_pixel_snap()) { - ofs=ofs.floor(); + ofs = ofs.floor(); } - Rect2 dst_rect(ofs,s); + Rect2 dst_rect(ofs, s); if (hflip) - dst_rect.size.x=-dst_rect.size.x; + dst_rect.size.x = -dst_rect.size.x; if (vflip) - dst_rect.size.y=-dst_rect.size.y; + dst_rect.size.y = -dst_rect.size.y; //texture->draw_rect(ci,dst_rect,false,modulate); - texture->draw_rect_region(ci,dst_rect,Rect2(Vector2(),texture->get_size())); + texture->draw_rect_region(ci, dst_rect, Rect2(Vector2(), texture->get_size())); //VisualServer::get_singleton()->canvas_item_add_texture_rect_region(ci,dst_rect,texture->get_rid(),src_rect,modulate); } break; } - } void AnimatedSprite::set_sprite_frames(const Ref &p_frames) { if (frames.is_valid()) - frames->disconnect("changed",this,"_res_changed"); - frames=p_frames; + frames->disconnect("changed", this, "_res_changed"); + frames = p_frames; if (frames.is_valid()) - frames->connect("changed",this,"_res_changed"); + frames->connect("changed", this, "_res_changed"); if (!frames.is_valid()) { - frame=0; + frame = 0; } else { set_frame(frame); } - - _change_notify(); _reset_timeout(); update(); update_configuration_warning(); - } Ref AnimatedSprite::get_sprite_frames() const { @@ -472,36 +439,30 @@ void AnimatedSprite::set_frame(int p_frame) { if (frames->has_animation(animation)) { int limit = frames->get_frame_count(animation); - if (p_frame>=limit) - p_frame=limit-1; - + if (p_frame >= limit) + p_frame = limit - 1; } - if (p_frame<0) - p_frame=0; + if (p_frame < 0) + p_frame = 0; - - if (frame==p_frame) + if (frame == p_frame) return; - frame=p_frame; + frame = p_frame; _reset_timeout(); update(); _change_notify("frame"); emit_signal(SceneStringNames::get_singleton()->frame_changed); - - - } int AnimatedSprite::get_frame() const { return frame; } - void AnimatedSprite::set_centered(bool p_center) { - centered=p_center; + centered = p_center; update(); item_rect_changed(); } @@ -511,9 +472,9 @@ bool AnimatedSprite::is_centered() const { return centered; } -void AnimatedSprite::set_offset(const Point2& p_offset) { +void AnimatedSprite::set_offset(const Point2 &p_offset) { - offset=p_offset; + offset = p_offset; update(); item_rect_changed(); _change_notify("offset"); @@ -525,7 +486,7 @@ Point2 AnimatedSprite::get_offset() const { void AnimatedSprite::set_flip_h(bool p_flip) { - hflip=p_flip; + hflip = p_flip; update(); } bool AnimatedSprite::is_flipped_h() const { @@ -535,7 +496,7 @@ bool AnimatedSprite::is_flipped_h() const { void AnimatedSprite::set_flip_v(bool p_flip) { - vflip=p_flip; + vflip = p_flip; update(); } bool AnimatedSprite::is_flipped_v() const { @@ -543,29 +504,27 @@ bool AnimatedSprite::is_flipped_v() const { return vflip; } - - Rect2 AnimatedSprite::get_item_rect() const { - if (!frames.is_valid() || !frames->has_animation(animation) || frame<0 || frame>=frames->get_frame_count(animation)) { + if (!frames.is_valid() || !frames->has_animation(animation) || frame < 0 || frame >= frames->get_frame_count(animation)) { return Node2D::get_item_rect(); } Ref t; if (animation) - t = frames->get_frame(animation,frame); + t = frames->get_frame(animation, frame); if (t.is_null()) return Node2D::get_item_rect(); Size2i s = t->get_size(); - Point2 ofs=offset; + Point2 ofs = offset; if (centered) - ofs-=s/2; + ofs -= s / 2; - if (s==Size2(0,0)) - s=Size2(1,1); + if (s == Size2(0, 0)) + s = Size2(1, 1); - return Rect2(ofs,s); + return Rect2(ofs, s); } void AnimatedSprite::_res_changed() { @@ -578,9 +537,9 @@ void AnimatedSprite::_res_changed() { void AnimatedSprite::_set_playing(bool p_playing) { - if (playing==p_playing) + if (playing == p_playing) return; - playing=p_playing; + playing = p_playing; _reset_timeout(); set_process_internal(playing); } @@ -590,14 +549,14 @@ bool AnimatedSprite::_is_playing() const { return playing; } -void AnimatedSprite::play(const StringName& p_animation) { +void AnimatedSprite::play(const StringName &p_animation) { if (p_animation) set_animation(p_animation); _set_playing(true); } -void AnimatedSprite::stop(){ +void AnimatedSprite::stop() { _set_playing(false); } @@ -614,29 +573,28 @@ void AnimatedSprite::_reset_timeout() { if (frames.is_valid() && frames->has_animation(animation)) { float speed = frames->get_animation_speed(animation); - if (speed>0) { - timeout=1.0/speed; + if (speed > 0) { + timeout = 1.0 / speed; } else { - timeout=0; + timeout = 0; } } else { - timeout=0; + timeout = 0; } - } -void AnimatedSprite::set_animation(const StringName& p_animation){ +void AnimatedSprite::set_animation(const StringName &p_animation) { - if (animation==p_animation) + if (animation == p_animation) return; - animation=p_animation; + animation = p_animation; _reset_timeout(); set_frame(0); _change_notify(); update(); } -StringName AnimatedSprite::get_animation() const{ +StringName AnimatedSprite::get_animation() const { return animation; } @@ -652,65 +610,57 @@ String AnimatedSprite::get_configuration_warning() const { void AnimatedSprite::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_sprite_frames", "sprite_frames:SpriteFrames"), &AnimatedSprite::set_sprite_frames); + ClassDB::bind_method(D_METHOD("get_sprite_frames:SpriteFrames"), &AnimatedSprite::get_sprite_frames); - ClassDB::bind_method(D_METHOD("set_sprite_frames","sprite_frames:SpriteFrames"),&AnimatedSprite::set_sprite_frames); - ClassDB::bind_method(D_METHOD("get_sprite_frames:SpriteFrames"),&AnimatedSprite::get_sprite_frames); - - ClassDB::bind_method(D_METHOD("set_animation","animation"),&AnimatedSprite::set_animation); - ClassDB::bind_method(D_METHOD("get_animation"),&AnimatedSprite::get_animation); - - ClassDB::bind_method(D_METHOD("_set_playing","playing"),&AnimatedSprite::_set_playing); - ClassDB::bind_method(D_METHOD("_is_playing"),&AnimatedSprite::_is_playing); + ClassDB::bind_method(D_METHOD("set_animation", "animation"), &AnimatedSprite::set_animation); + ClassDB::bind_method(D_METHOD("get_animation"), &AnimatedSprite::get_animation); - ClassDB::bind_method(D_METHOD("play","anim"),&AnimatedSprite::play,DEFVAL(StringName())); - ClassDB::bind_method(D_METHOD("stop"),&AnimatedSprite::stop); - ClassDB::bind_method(D_METHOD("is_playing"),&AnimatedSprite::is_playing); + ClassDB::bind_method(D_METHOD("_set_playing", "playing"), &AnimatedSprite::_set_playing); + ClassDB::bind_method(D_METHOD("_is_playing"), &AnimatedSprite::_is_playing); - ClassDB::bind_method(D_METHOD("set_centered","centered"),&AnimatedSprite::set_centered); - ClassDB::bind_method(D_METHOD("is_centered"),&AnimatedSprite::is_centered); + ClassDB::bind_method(D_METHOD("play", "anim"), &AnimatedSprite::play, DEFVAL(StringName())); + ClassDB::bind_method(D_METHOD("stop"), &AnimatedSprite::stop); + ClassDB::bind_method(D_METHOD("is_playing"), &AnimatedSprite::is_playing); - ClassDB::bind_method(D_METHOD("set_offset","offset"),&AnimatedSprite::set_offset); - ClassDB::bind_method(D_METHOD("get_offset"),&AnimatedSprite::get_offset); + ClassDB::bind_method(D_METHOD("set_centered", "centered"), &AnimatedSprite::set_centered); + ClassDB::bind_method(D_METHOD("is_centered"), &AnimatedSprite::is_centered); - ClassDB::bind_method(D_METHOD("set_flip_h","flip_h"),&AnimatedSprite::set_flip_h); - ClassDB::bind_method(D_METHOD("is_flipped_h"),&AnimatedSprite::is_flipped_h); + ClassDB::bind_method(D_METHOD("set_offset", "offset"), &AnimatedSprite::set_offset); + ClassDB::bind_method(D_METHOD("get_offset"), &AnimatedSprite::get_offset); - ClassDB::bind_method(D_METHOD("set_flip_v","flip_v"),&AnimatedSprite::set_flip_v); - ClassDB::bind_method(D_METHOD("is_flipped_v"),&AnimatedSprite::is_flipped_v); + ClassDB::bind_method(D_METHOD("set_flip_h", "flip_h"), &AnimatedSprite::set_flip_h); + ClassDB::bind_method(D_METHOD("is_flipped_h"), &AnimatedSprite::is_flipped_h); - ClassDB::bind_method(D_METHOD("set_frame","frame"),&AnimatedSprite::set_frame); - ClassDB::bind_method(D_METHOD("get_frame"),&AnimatedSprite::get_frame); + ClassDB::bind_method(D_METHOD("set_flip_v", "flip_v"), &AnimatedSprite::set_flip_v); + ClassDB::bind_method(D_METHOD("is_flipped_v"), &AnimatedSprite::is_flipped_v); + ClassDB::bind_method(D_METHOD("set_frame", "frame"), &AnimatedSprite::set_frame); + ClassDB::bind_method(D_METHOD("get_frame"), &AnimatedSprite::get_frame); - ClassDB::bind_method(D_METHOD("_res_changed"),&AnimatedSprite::_res_changed); + ClassDB::bind_method(D_METHOD("_res_changed"), &AnimatedSprite::_res_changed); ADD_SIGNAL(MethodInfo("frame_changed")); ADD_SIGNAL(MethodInfo("animation_finished")); - ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "frames",PROPERTY_HINT_RESOURCE_TYPE,"SpriteFrames"), "set_sprite_frames","get_sprite_frames"); - ADD_PROPERTY( PropertyInfo( Variant::STRING, "animation"), "set_animation","get_animation"); - ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "frame",PROPERTY_HINT_SPRITE_FRAME), "set_frame","get_frame"); - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "playing"), "_set_playing","_is_playing"); - ADD_PROPERTYNO( PropertyInfo( Variant::BOOL, "centered"), "set_centered","is_centered"); - ADD_PROPERTYNZ( PropertyInfo( Variant::VECTOR2, "offset"), "set_offset","get_offset"); - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "flip_h"), "set_flip_h","is_flipped_h"); - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "flip_v"), "set_flip_v","is_flipped_v"); - - + ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "animation"), "set_animation", "get_animation"); + ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "frame", PROPERTY_HINT_SPRITE_FRAME), "set_frame", "get_frame"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "playing"), "_set_playing", "_is_playing"); + ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered"); + ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v"); } AnimatedSprite::AnimatedSprite() { - centered=true; - hflip=false; - vflip=false; - - frame=0; - playing=false; - animation="default"; - timeout=0; - + centered = true; + hflip = false; + vflip = false; + frame = 0; + playing = false; + animation = "default"; + timeout = 0; } - - diff --git a/scene/2d/animated_sprite.h b/scene/2d/animated_sprite.h index fbeea7f69..bc0e85b0c 100644 --- a/scene/2d/animated_sprite.h +++ b/scene/2d/animated_sprite.h @@ -32,84 +32,80 @@ #include "scene/2d/node_2d.h" #include "scene/resources/texture.h" - class SpriteFrames : public Resource { - GDCLASS(SpriteFrames,Resource); + GDCLASS(SpriteFrames, Resource); struct Anim { float speed; bool loop; - Vector< Ref > frames; + Vector > frames; - Anim() { loop=true; speed=5; } + Anim() { + loop = true; + speed = 5; + } }; - Map animations; + Map animations; Array _get_frames() const; - void _set_frames(const Array& p_frames); + void _set_frames(const Array &p_frames); Array _get_animations() const; - void _set_animations(const Array& p_animations); + void _set_animations(const Array &p_animations); Vector _get_animation_list() const; protected: - static void _bind_methods(); public: - - void add_animation(const StringName& p_anim); - bool has_animation(const StringName& p_anim) const; - void remove_animation(const StringName& p_anim); - void rename_animation(const StringName& p_prev,const StringName& p_next); + void add_animation(const StringName &p_anim); + bool has_animation(const StringName &p_anim) const; + void remove_animation(const StringName &p_anim); + void rename_animation(const StringName &p_prev, const StringName &p_next); void get_animation_list(List *r_animations) const; - void set_animation_speed(const StringName& p_anim,float p_fps); - float get_animation_speed(const StringName& p_anim) const; + void set_animation_speed(const StringName &p_anim, float p_fps); + float get_animation_speed(const StringName &p_anim) const; - void set_animation_loop(const StringName& p_anim,bool p_loop); - bool get_animation_loop(const StringName& p_anim) const; + void set_animation_loop(const StringName &p_anim, bool p_loop); + bool get_animation_loop(const StringName &p_anim) const; - void add_frame(const StringName& p_anim,const Ref& p_frame,int p_at_pos=-1); - int get_frame_count(const StringName& p_anim) const; - _FORCE_INLINE_ Ref get_frame(const StringName& p_anim,int p_idx) const { + void add_frame(const StringName &p_anim, const Ref &p_frame, int p_at_pos = -1); + int get_frame_count(const StringName &p_anim) const; + _FORCE_INLINE_ Ref get_frame(const StringName &p_anim, int p_idx) const { - const Map::Element *E=animations.find(p_anim); - ERR_FAIL_COND_V(!E,Ref()); - ERR_FAIL_COND_V(p_idx<0,Ref()); - if (p_idx>=E->get().frames.size()) + const Map::Element *E = animations.find(p_anim); + ERR_FAIL_COND_V(!E, Ref()); + ERR_FAIL_COND_V(p_idx < 0, Ref()); + if (p_idx >= E->get().frames.size()) return Ref(); return E->get().frames[p_idx]; } - void set_frame(const StringName& p_anim,int p_idx,const Ref& p_frame){ - Map::Element *E=animations.find(p_anim); + void set_frame(const StringName &p_anim, int p_idx, const Ref &p_frame) { + Map::Element *E = animations.find(p_anim); ERR_FAIL_COND(!E); - ERR_FAIL_COND(p_idx<0); - if (p_idx>=E->get().frames.size()) + ERR_FAIL_COND(p_idx < 0); + if (p_idx >= E->get().frames.size()) return; - E->get().frames[p_idx]=p_frame; + E->get().frames[p_idx] = p_frame; } - void remove_frame(const StringName& p_anim,int p_idx); - void clear(const StringName& p_anim); + void remove_frame(const StringName &p_anim, int p_idx); + void clear(const StringName &p_anim); void clear_all(); - SpriteFrames(); - }; - - class AnimatedSprite : public Node2D { - GDCLASS(AnimatedSprite,Node2D); + GDCLASS(AnimatedSprite, Node2D); Ref frames; bool playing; @@ -124,35 +120,30 @@ class AnimatedSprite : public Node2D { bool hflip; bool vflip; - void _res_changed(); void _reset_timeout(); void _set_playing(bool p_playing); bool _is_playing() const; - protected: - static void _bind_methods(); void _notification(int p_what); - virtual void _validate_property(PropertyInfo& property) const; + virtual void _validate_property(PropertyInfo &property) const; public: - - - virtual void edit_set_pivot(const Point2& p_pivot); + virtual void edit_set_pivot(const Point2 &p_pivot); virtual Point2 edit_get_pivot() const; virtual bool edit_has_pivot() const; void set_sprite_frames(const Ref &p_frames); Ref get_sprite_frames() const; - void play(const StringName& p_animation=StringName()); + void play(const StringName &p_animation = StringName()); void stop(); bool is_playing() const; - void set_animation(const StringName& p_animation); + void set_animation(const StringName &p_animation); StringName get_animation() const; void set_frame(int p_frame); @@ -161,7 +152,7 @@ public: void set_centered(bool p_center); bool is_centered() const; - void set_offset(const Point2& p_offset); + void set_offset(const Point2 &p_offset); Point2 get_offset() const; void set_flip_h(bool p_flip); @@ -170,7 +161,7 @@ public: void set_flip_v(bool p_flip); bool is_flipped_v() const; - void set_modulate(const Color& p_color); + void set_modulate(const Color &p_color); Color get_modulate() const; virtual Rect2 get_item_rect() const; @@ -179,5 +170,4 @@ public: AnimatedSprite(); }; - #endif // ANIMATED_SPRITE_H diff --git a/scene/2d/area_2d.cpp b/scene/2d/area_2d.cpp index 55c7716b6..61e8ee16a 100644 --- a/scene/2d/area_2d.cpp +++ b/scene/2d/area_2d.cpp @@ -31,108 +31,101 @@ #include "servers/physics_2d_server.h" void Area2D::set_space_override_mode(SpaceOverride p_mode) { - space_override=p_mode; - Physics2DServer::get_singleton()->area_set_space_override_mode(get_rid(),Physics2DServer::AreaSpaceOverrideMode(p_mode)); - - + space_override = p_mode; + Physics2DServer::get_singleton()->area_set_space_override_mode(get_rid(), Physics2DServer::AreaSpaceOverrideMode(p_mode)); } -Area2D::SpaceOverride Area2D::get_space_override_mode() const{ +Area2D::SpaceOverride Area2D::get_space_override_mode() const { return space_override; } -void Area2D::set_gravity_is_point(bool p_enabled){ - - gravity_is_point=p_enabled; - Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT,p_enabled); +void Area2D::set_gravity_is_point(bool p_enabled) { + gravity_is_point = p_enabled; + Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT, p_enabled); } -bool Area2D::is_gravity_a_point() const{ +bool Area2D::is_gravity_a_point() const { return gravity_is_point; } -void Area2D::set_gravity_distance_scale(real_t p_scale){ - - gravity_distance_scale=p_scale; - Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE,p_scale); +void Area2D::set_gravity_distance_scale(real_t p_scale) { + gravity_distance_scale = p_scale; + Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE, p_scale); } -real_t Area2D::get_gravity_distance_scale() const{ +real_t Area2D::get_gravity_distance_scale() const { return gravity_distance_scale; } -void Area2D::set_gravity_vector(const Vector2& p_vec){ - - gravity_vec=p_vec; - Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_GRAVITY_VECTOR,p_vec); +void Area2D::set_gravity_vector(const Vector2 &p_vec) { + gravity_vec = p_vec; + Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_GRAVITY_VECTOR, p_vec); } -Vector2 Area2D::get_gravity_vector() const{ +Vector2 Area2D::get_gravity_vector() const { return gravity_vec; } -void Area2D::set_gravity(real_t p_gravity){ +void Area2D::set_gravity(real_t p_gravity) { - gravity=p_gravity; - Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_GRAVITY,p_gravity); + gravity = p_gravity; + Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_GRAVITY, p_gravity); } -real_t Area2D::get_gravity() const{ +real_t Area2D::get_gravity() const { return gravity; } -void Area2D::set_linear_damp(real_t p_linear_damp){ +void Area2D::set_linear_damp(real_t p_linear_damp) { - linear_damp=p_linear_damp; - Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_LINEAR_DAMP,p_linear_damp); + linear_damp = p_linear_damp; + Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_LINEAR_DAMP, p_linear_damp); } -real_t Area2D::get_linear_damp() const{ +real_t Area2D::get_linear_damp() const { return linear_damp; } -void Area2D::set_angular_damp(real_t p_angular_damp){ +void Area2D::set_angular_damp(real_t p_angular_damp) { - angular_damp=p_angular_damp; - Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_ANGULAR_DAMP,p_angular_damp); + angular_damp = p_angular_damp; + Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_ANGULAR_DAMP, p_angular_damp); } -real_t Area2D::get_angular_damp() const{ +real_t Area2D::get_angular_damp() const { return angular_damp; } -void Area2D::set_priority(real_t p_priority){ +void Area2D::set_priority(real_t p_priority) { - priority=p_priority; - Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_PRIORITY,p_priority); + priority = p_priority; + Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_PRIORITY, p_priority); } -real_t Area2D::get_priority() const{ +real_t Area2D::get_priority() const { return priority; } - void Area2D::_body_enter_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=body_map.find(p_id); + Map::Element *E = body_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(E->get().in_tree); - E->get().in_tree=true; - emit_signal(SceneStringNames::get_singleton()->body_entered,node); - for(int i=0;iget().shapes.size();i++) { + E->get().in_tree = true; + emit_signal(SceneStringNames::get_singleton()->body_entered, node); + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_entered,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_entered, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape); } - } void Area2D::_body_exit_tree(ObjectID p_id) { @@ -140,54 +133,51 @@ void Area2D::_body_exit_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=body_map.find(p_id); + Map::Element *E = body_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(!E->get().in_tree); - E->get().in_tree=false; - emit_signal(SceneStringNames::get_singleton()->body_exited,node); - for(int i=0;iget().shapes.size();i++) { + E->get().in_tree = false; + emit_signal(SceneStringNames::get_singleton()->body_exited, node); + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape); } - } -void Area2D::_body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape) { +void Area2D::_body_inout(int p_status, const RID &p_body, int p_instance, int p_body_shape, int p_area_shape) { - bool body_in = p_status==Physics2DServer::AREA_BODY_ADDED; - ObjectID objid=p_instance; + bool body_in = p_status == Physics2DServer::AREA_BODY_ADDED; + ObjectID objid = p_instance; Object *obj = ObjectDB::get_instance(objid); Node *node = obj ? obj->cast_to() : NULL; - Map::Element *E=body_map.find(objid); + Map::Element *E = body_map.find(objid); ERR_FAIL_COND(!body_in && !E); - locked=true; + locked = true; if (body_in) { if (!E) { - E = body_map.insert(objid,BodyState()); - E->get().rc=0; - E->get().in_tree=node && node->is_inside_tree(); + E = body_map.insert(objid, BodyState()); + E->get().rc = 0; + E->get().in_tree = node && node->is_inside_tree(); if (node) { - node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree,make_binds(objid)); - node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree,make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree, make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree, make_binds(objid)); if (E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->body_entered,node); + emit_signal(SceneStringNames::get_singleton()->body_entered, node); } } - } E->get().rc++; if (node) - E->get().shapes.insert(ShapePair(p_body_shape,p_area_shape)); - + E->get().shapes.insert(ShapePair(p_body_shape, p_area_shape)); if (!node || E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->body_shape_entered,objid,node,p_body_shape,p_area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_entered, objid, node, p_body_shape, p_area_shape); } } else { @@ -195,56 +185,48 @@ void Area2D::_body_inout(int p_status,const RID& p_body, int p_instance, int p_b E->get().rc--; if (node) - E->get().shapes.erase(ShapePair(p_body_shape,p_area_shape)); + E->get().shapes.erase(ShapePair(p_body_shape, p_area_shape)); - bool eraseit=false; + bool eraseit = false; - if (E->get().rc==0) { + if (E->get().rc == 0) { if (node) { - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree); if (E->get().in_tree) - emit_signal(SceneStringNames::get_singleton()->body_exited,obj); - + emit_signal(SceneStringNames::get_singleton()->body_exited, obj); } - eraseit=true; - + eraseit = true; } if (!node || E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,objid,obj,p_body_shape,p_area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, objid, obj, p_body_shape, p_area_shape); } if (eraseit) body_map.erase(E); - } - locked=false; - - + locked = false; } - - void Area2D::_area_enter_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=area_map.find(p_id); + Map::Element *E = area_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(E->get().in_tree); - E->get().in_tree=true; - emit_signal(SceneStringNames::get_singleton()->area_entered,node); - for(int i=0;iget().shapes.size();i++) { + E->get().in_tree = true; + emit_signal(SceneStringNames::get_singleton()->area_entered, node); + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->area_shape_entered,p_id,node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_entered, p_id, node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape); } - } void Area2D::_area_exit_tree(ObjectID p_id) { @@ -252,54 +234,51 @@ void Area2D::_area_exit_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=area_map.find(p_id); + Map::Element *E = area_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(!E->get().in_tree); - E->get().in_tree=false; - emit_signal(SceneStringNames::get_singleton()->area_exited,node); - for(int i=0;iget().shapes.size();i++) { + E->get().in_tree = false; + emit_signal(SceneStringNames::get_singleton()->area_exited, node); + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->area_shape_exited,p_id,node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_exited, p_id, node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape); } - } -void Area2D::_area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape) { +void Area2D::_area_inout(int p_status, const RID &p_area, int p_instance, int p_area_shape, int p_self_shape) { - bool area_in = p_status==Physics2DServer::AREA_BODY_ADDED; - ObjectID objid=p_instance; + bool area_in = p_status == Physics2DServer::AREA_BODY_ADDED; + ObjectID objid = p_instance; Object *obj = ObjectDB::get_instance(objid); Node *node = obj ? obj->cast_to() : NULL; - Map::Element *E=area_map.find(objid); + Map::Element *E = area_map.find(objid); ERR_FAIL_COND(!area_in && !E); - locked=true; + locked = true; if (area_in) { if (!E) { - E = area_map.insert(objid,AreaState()); - E->get().rc=0; - E->get().in_tree=node && node->is_inside_tree(); + E = area_map.insert(objid, AreaState()); + E->get().rc = 0; + E->get().in_tree = node && node->is_inside_tree(); if (node) { - node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree,make_binds(objid)); - node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree,make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree, make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree, make_binds(objid)); if (E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->area_entered,node); + emit_signal(SceneStringNames::get_singleton()->area_entered, node); } } - } E->get().rc++; if (node) - E->get().shapes.insert(AreaShapePair(p_area_shape,p_self_shape)); - + E->get().shapes.insert(AreaShapePair(p_area_shape, p_self_shape)); if (!node || E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->area_shape_entered,objid,node,p_area_shape,p_self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_entered, objid, node, p_area_shape, p_self_shape); } } else { @@ -307,39 +286,32 @@ void Area2D::_area_inout(int p_status,const RID& p_area, int p_instance, int p_a E->get().rc--; if (node) - E->get().shapes.erase(AreaShapePair(p_area_shape,p_self_shape)); + E->get().shapes.erase(AreaShapePair(p_area_shape, p_self_shape)); - bool eraseit=false; + bool eraseit = false; - if (E->get().rc==0) { + if (E->get().rc == 0) { if (node) { - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree); if (E->get().in_tree) - emit_signal(SceneStringNames::get_singleton()->area_exited,obj); - + emit_signal(SceneStringNames::get_singleton()->area_exited, obj); } - eraseit=true; - + eraseit = true; } if (!node || E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->area_shape_exited,objid,obj,p_area_shape,p_self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_exited, objid, obj, p_area_shape, p_self_shape); } if (eraseit) area_map.erase(E); - } - locked=false; - - + locked = false; } - - void Area2D::_clear_monitoring() { if (locked) { @@ -348,39 +320,38 @@ void Area2D::_clear_monitoring() { ERR_FAIL_COND(locked); { - Map bmcopy = body_map; + Map bmcopy = body_map; body_map.clear(); //disconnect all monitored stuff - for (Map::Element *E=bmcopy.front();E;E=E->next()) { + for (Map::Element *E = bmcopy.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); Node *node = obj ? obj->cast_to() : NULL; ERR_CONTINUE(!node); - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree); if (!E->get().in_tree) continue; - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,E->key(),node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, E->key(), node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape); } - emit_signal(SceneStringNames::get_singleton()->body_exited,obj); + emit_signal(SceneStringNames::get_singleton()->body_exited, obj); } - } { - Map bmcopy = area_map; + Map bmcopy = area_map; area_map.clear(); //disconnect all monitored stuff - for (Map::Element *E=bmcopy.front();E;E=E->next()) { + for (Map::Element *E = bmcopy.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); Node *node = obj ? obj->cast_to() : NULL; @@ -389,58 +360,53 @@ void Area2D::_clear_monitoring() { continue; //ERR_CONTINUE(!node); - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree); if (!E->get().in_tree) continue; - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->area_shape_exited,E->key(),node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_exited, E->key(), node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape); } - emit_signal(SceneStringNames::get_singleton()->area_exited,obj); + emit_signal(SceneStringNames::get_singleton()->area_exited, obj); } } - } void Area2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_EXIT_TREE: { _clear_monitoring(); } break; } - } - void Area2D::set_monitoring(bool p_enable) { - - if (p_enable==monitoring) + if (p_enable == monitoring) return; if (locked) { ERR_EXPLAIN("Function blocked during in/out signal. Use call_deferred(\"set_enable_monitoring\",true/false)"); } ERR_FAIL_COND(locked); - monitoring=p_enable; + monitoring = p_enable; if (monitoring) { - Physics2DServer::get_singleton()->area_set_monitor_callback(get_rid(),this,SceneStringNames::get_singleton()->_body_inout); - Physics2DServer::get_singleton()->area_set_area_monitor_callback(get_rid(),this,SceneStringNames::get_singleton()->_area_inout); + Physics2DServer::get_singleton()->area_set_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_body_inout); + Physics2DServer::get_singleton()->area_set_area_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_area_inout); } else { - Physics2DServer::get_singleton()->area_set_monitor_callback(get_rid(),NULL,StringName()); - Physics2DServer::get_singleton()->area_set_area_monitor_callback(get_rid(),NULL,StringName()); + Physics2DServer::get_singleton()->area_set_monitor_callback(get_rid(), NULL, StringName()); + Physics2DServer::get_singleton()->area_set_area_monitor_callback(get_rid(), NULL, StringName()); _clear_monitoring(); - } } @@ -456,12 +422,12 @@ void Area2D::set_monitorable(bool p_enable) { } ERR_FAIL_COND(locked); - if (p_enable==monitorable) + if (p_enable == monitorable) return; - monitorable=p_enable; + monitorable = p_enable; - Physics2DServer::get_singleton()->area_set_monitorable(get_rid(),monitorable); + Physics2DServer::get_singleton()->area_set_monitorable(get_rid(), monitorable); } bool Area2D::is_monitorable() const { @@ -471,18 +437,17 @@ bool Area2D::is_monitorable() const { Array Area2D::get_overlapping_bodies() const { - ERR_FAIL_COND_V(!monitoring,Array()); + ERR_FAIL_COND_V(!monitoring, Array()); Array ret; ret.resize(body_map.size()); - int idx=0; - for (const Map::Element *E=body_map.front();E;E=E->next()) { + int idx = 0; + for (const Map::Element *E = body_map.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); if (!obj) { - ret.resize( ret.size() -1 ); //ops + ret.resize(ret.size() - 1); //ops } else { - ret[idx++]=obj; + ret[idx++] = obj; } - } return ret; @@ -490,49 +455,44 @@ Array Area2D::get_overlapping_bodies() const { Array Area2D::get_overlapping_areas() const { - ERR_FAIL_COND_V(!monitoring,Array()); + ERR_FAIL_COND_V(!monitoring, Array()); Array ret; ret.resize(area_map.size()); - int idx=0; - for (const Map::Element *E=area_map.front();E;E=E->next()) { + int idx = 0; + for (const Map::Element *E = area_map.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); if (!obj) { - ret.resize( ret.size() -1 ); //ops + ret.resize(ret.size() - 1); //ops } else { - ret[idx++]=obj; + ret[idx++] = obj; } - } return ret; } -bool Area2D::overlaps_area(Node* p_area) const { +bool Area2D::overlaps_area(Node *p_area) const { - ERR_FAIL_NULL_V(p_area,false); - const Map::Element *E=area_map.find(p_area->get_instance_ID()); + ERR_FAIL_NULL_V(p_area, false); + const Map::Element *E = area_map.find(p_area->get_instance_ID()); if (!E) return false; return E->get().in_tree; - - - } -bool Area2D::overlaps_body(Node* p_body) const{ +bool Area2D::overlaps_body(Node *p_body) const { - ERR_FAIL_NULL_V(p_body,false); - const Map::Element *E=body_map.find(p_body->get_instance_ID()); + ERR_FAIL_NULL_V(p_body, false); + const Map::Element *E = body_map.find(p_body->get_instance_ID()); if (!E) return false; return E->get().in_tree; - } void Area2D::set_collision_mask(uint32_t p_mask) { - collision_mask=p_mask; - Physics2DServer::get_singleton()->area_set_collision_mask(get_rid(),p_mask); + collision_mask = p_mask; + Physics2DServer::get_singleton()->area_set_collision_mask(get_rid(), p_mask); } uint32_t Area2D::get_collision_mask() const { @@ -540,11 +500,10 @@ uint32_t Area2D::get_collision_mask() const { return collision_mask; } - void Area2D::set_layer_mask(uint32_t p_mask) { - layer_mask=p_mask; - Physics2DServer::get_singleton()->area_set_layer_mask(get_rid(),p_mask); + layer_mask = p_mask; + Physics2DServer::get_singleton()->area_set_layer_mask(get_rid(), p_mask); } uint32_t Area2D::get_layer_mask() const { @@ -556,143 +515,135 @@ void Area2D::set_collision_mask_bit(int p_bit, bool p_value) { uint32_t mask = get_collision_mask(); if (p_value) - mask|=1<area_create(),true) { +Area2D::Area2D() + : CollisionObject2D(Physics2DServer::get_singleton()->area_create(), true) { - space_override=SPACE_OVERRIDE_DISABLED; + space_override = SPACE_OVERRIDE_DISABLED; set_gravity(98); - set_gravity_vector(Vector2(0,1)); - gravity_is_point=false; - gravity_distance_scale=0; - linear_damp=0.1; - angular_damp=1; - locked=false; - priority=0; - monitoring=false; - monitorable=false; - collision_mask=1; - layer_mask=1; + set_gravity_vector(Vector2(0, 1)); + gravity_is_point = false; + gravity_distance_scale = 0; + linear_damp = 0.1; + angular_damp = 1; + locked = false; + priority = 0; + monitoring = false; + monitorable = false; + collision_mask = 1; + layer_mask = 1; set_monitoring(true); set_monitorable(true); } Area2D::~Area2D() { - - } diff --git a/scene/2d/area_2d.h b/scene/2d/area_2d.h index 68bada707..2402ff763 100644 --- a/scene/2d/area_2d.h +++ b/scene/2d/area_2d.h @@ -34,9 +34,9 @@ class Area2D : public CollisionObject2D { - GDCLASS( Area2D, CollisionObject2D ); -public: + GDCLASS(Area2D, CollisionObject2D); +public: enum SpaceOverride { SPACE_OVERRIDE_DISABLED, SPACE_OVERRIDE_COMBINE, @@ -44,9 +44,8 @@ public: SPACE_OVERRIDE_REPLACE, SPACE_OVERRIDE_REPLACE_COMBINE }; -private: - +private: SpaceOverride space_override; Vector2 gravity_vec; real_t gravity; @@ -61,7 +60,7 @@ private: bool monitorable; bool locked; - void _body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape); + void _body_inout(int p_status, const RID &p_body, int p_instance, int p_body_shape, int p_area_shape); void _body_enter_tree(ObjectID p_id); void _body_exit_tree(ObjectID p_id); @@ -70,15 +69,18 @@ private: int body_shape; int area_shape; - bool operator<(const ShapePair& p_sp) const { - if (body_shape==p_sp.body_shape) + bool operator<(const ShapePair &p_sp) const { + if (body_shape == p_sp.body_shape) return area_shape < p_sp.area_shape; else return body_shape < p_sp.body_shape; } ShapePair() {} - ShapePair(int p_bs, int p_as) { body_shape=p_bs; area_shape=p_as; } + ShapePair(int p_bs, int p_as) { + body_shape = p_bs; + area_shape = p_as; + } }; struct BodyState { @@ -88,11 +90,9 @@ private: VSet shapes; }; - Map body_map; - + Map body_map; - - void _area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape); + void _area_inout(int p_status, const RID &p_area, int p_instance, int p_area_shape, int p_self_shape); void _area_enter_tree(ObjectID p_id); void _area_exit_tree(ObjectID p_id); @@ -101,15 +101,18 @@ private: int area_shape; int self_shape; - bool operator<(const AreaShapePair& p_sp) const { - if (area_shape==p_sp.area_shape) + bool operator<(const AreaShapePair &p_sp) const { + if (area_shape == p_sp.area_shape) return self_shape < p_sp.self_shape; else return area_shape < p_sp.area_shape; } AreaShapePair() {} - AreaShapePair(int p_bs, int p_as) { area_shape=p_bs; self_shape=p_as; } + AreaShapePair(int p_bs, int p_as) { + area_shape = p_bs; + self_shape = p_as; + } }; struct AreaState { @@ -119,16 +122,14 @@ private: VSet shapes; }; - Map area_map; + Map area_map; void _clear_monitoring(); - protected: - void _notification(int p_what); static void _bind_methods(); -public: +public: void set_space_override_mode(SpaceOverride p_mode); SpaceOverride get_space_override_mode() const; @@ -138,7 +139,7 @@ public: void set_gravity_distance_scale(real_t p_scale); real_t get_gravity_distance_scale() const; - void set_gravity_vector(const Vector2& p_vec); + void set_gravity_vector(const Vector2 &p_vec); Vector2 get_gravity_vector() const; void set_gravity(real_t p_gravity); @@ -174,8 +175,8 @@ public: Array get_overlapping_bodies() const; //function for script Array get_overlapping_areas() const; //function for script - bool overlaps_area(Node* p_area) const; - bool overlaps_body(Node* p_body) const; + bool overlaps_area(Node *p_area) const; + bool overlaps_body(Node *p_body) const; Area2D(); ~Area2D(); diff --git a/scene/2d/back_buffer_copy.cpp b/scene/2d/back_buffer_copy.cpp index eaa33fe70..5a79cee6d 100644 --- a/scene/2d/back_buffer_copy.cpp +++ b/scene/2d/back_buffer_copy.cpp @@ -30,22 +30,21 @@ void BackBufferCopy::_update_copy_mode() { - switch(copy_mode) { + switch (copy_mode) { case COPY_MODE_DISABLED: { - VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(),false,Rect2()); + VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(), false, Rect2()); } break; case COPY_MODE_RECT: { - VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(),true,rect); + VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(), true, rect); } break; case COPY_MODE_VIEWPORT: { - VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(),true,Rect2()); + VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(), true, Rect2()); } break; - } } @@ -54,50 +53,47 @@ Rect2 BackBufferCopy::get_item_rect() const { return rect; } -void BackBufferCopy::set_rect(const Rect2& p_rect) { +void BackBufferCopy::set_rect(const Rect2 &p_rect) { - rect=p_rect; + rect = p_rect; _update_copy_mode(); } -Rect2 BackBufferCopy::get_rect() const{ +Rect2 BackBufferCopy::get_rect() const { return rect; } -void BackBufferCopy::set_copy_mode(CopyMode p_mode){ +void BackBufferCopy::set_copy_mode(CopyMode p_mode) { - copy_mode=p_mode; + copy_mode = p_mode; _update_copy_mode(); } -BackBufferCopy::CopyMode BackBufferCopy::get_copy_mode() const{ +BackBufferCopy::CopyMode BackBufferCopy::get_copy_mode() const { return copy_mode; } - void BackBufferCopy::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_rect","rect"),&BackBufferCopy::set_rect); - ClassDB::bind_method(D_METHOD("get_rect"),&BackBufferCopy::get_rect); + ClassDB::bind_method(D_METHOD("set_rect", "rect"), &BackBufferCopy::set_rect); + ClassDB::bind_method(D_METHOD("get_rect"), &BackBufferCopy::get_rect); - ClassDB::bind_method(D_METHOD("set_copy_mode","copy_mode"),&BackBufferCopy::set_copy_mode); - ClassDB::bind_method(D_METHOD("get_copy_mode"),&BackBufferCopy::get_copy_mode); + ClassDB::bind_method(D_METHOD("set_copy_mode", "copy_mode"), &BackBufferCopy::set_copy_mode); + ClassDB::bind_method(D_METHOD("get_copy_mode"), &BackBufferCopy::get_copy_mode); - ADD_PROPERTY( PropertyInfo(Variant::INT,"copy_mode",PROPERTY_HINT_ENUM,"Disabled,Rect,Viewport"),"set_copy_mode","get_copy_mode"); - ADD_PROPERTY( PropertyInfo(Variant::RECT2,"rect"),"set_rect","get_rect"); - - BIND_CONSTANT( COPY_MODE_DISABLED ); - BIND_CONSTANT( COPY_MODE_RECT ); - BIND_CONSTANT( COPY_MODE_VIEWPORT ); + ADD_PROPERTY(PropertyInfo(Variant::INT, "copy_mode", PROPERTY_HINT_ENUM, "Disabled,Rect,Viewport"), "set_copy_mode", "get_copy_mode"); + ADD_PROPERTY(PropertyInfo(Variant::RECT2, "rect"), "set_rect", "get_rect"); + BIND_CONSTANT(COPY_MODE_DISABLED); + BIND_CONSTANT(COPY_MODE_RECT); + BIND_CONSTANT(COPY_MODE_VIEWPORT); } -BackBufferCopy::BackBufferCopy(){ +BackBufferCopy::BackBufferCopy() { - rect=Rect2(-100,-100,200,200); - copy_mode=COPY_MODE_RECT; + rect = Rect2(-100, -100, 200, 200); + copy_mode = COPY_MODE_RECT; _update_copy_mode(); } -BackBufferCopy::~BackBufferCopy(){ - +BackBufferCopy::~BackBufferCopy() { } diff --git a/scene/2d/back_buffer_copy.h b/scene/2d/back_buffer_copy.h index 22387f3e9..b4f83e7db 100644 --- a/scene/2d/back_buffer_copy.h +++ b/scene/2d/back_buffer_copy.h @@ -32,27 +32,26 @@ #include "scene/2d/node_2d.h" class BackBufferCopy : public Node2D { - GDCLASS( BackBufferCopy,Node2D); + GDCLASS(BackBufferCopy, Node2D); + public: enum CopyMode { COPY_MODE_DISABLED, COPY_MODE_RECT, COPY_MODE_VIEWPORT }; -private: +private: Rect2 rect; CopyMode copy_mode; void _update_copy_mode(); protected: - static void _bind_methods(); public: - - void set_rect(const Rect2& p_rect); + void set_rect(const Rect2 &p_rect); Rect2 get_rect() const; void set_copy_mode(CopyMode p_mode); diff --git a/scene/2d/camera_2d.cpp b/scene/2d/camera_2d.cpp index 9ae231586..f8388cdcc 100644 --- a/scene/2d/camera_2d.cpp +++ b/scene/2d/camera_2d.cpp @@ -27,14 +27,13 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "camera_2d.h" +#include "core/math/math_funcs.h" #include "scene/scene_string_names.h" #include "servers/visual_server.h" -#include "core/math/math_funcs.h" #include void Camera2D::_update_scroll() { - if (!is_inside_tree()) return; @@ -45,16 +44,15 @@ void Camera2D::_update_scroll() { if (current) { - ERR_FAIL_COND( custom_viewport && !ObjectDB::get_instance(custom_viewport_id) ); + ERR_FAIL_COND(custom_viewport && !ObjectDB::get_instance(custom_viewport_id)); Transform2D xform = get_camera_transform(); if (viewport) { - viewport->set_canvas_transform( xform ); + viewport->set_canvas_transform(xform); } - get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME,group_name,"_camera_moved",xform); + get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_camera_moved", xform); }; - } void Camera2D::set_zoom(const Vector2 &p_zoom) { @@ -70,31 +68,28 @@ Vector2 Camera2D::get_zoom() const { return zoom; }; - -Transform2D Camera2D::get_camera_transform() { +Transform2D Camera2D::get_camera_transform() { if (!get_tree()) return Transform2D(); - ERR_FAIL_COND_V( custom_viewport && !ObjectDB::get_instance(custom_viewport_id), Transform2D() ); + ERR_FAIL_COND_V(custom_viewport && !ObjectDB::get_instance(custom_viewport_id), Transform2D()); Size2 screen_size = viewport->get_visible_rect().size; - Point2 new_camera_pos = get_global_transform().get_origin(); Point2 ret_camera_pos; if (!first) { - - if (anchor_mode==ANCHOR_MODE_DRAG_CENTER) { + if (anchor_mode == ANCHOR_MODE_DRAG_CENTER) { if (h_drag_enabled && !get_tree()->is_editor_hint()) { - camera_pos.x = MIN( camera_pos.x, (new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT])); - camera_pos.x = MAX( camera_pos.x, (new_camera_pos.x - screen_size.x * 0.5 * drag_margin[MARGIN_LEFT])); + camera_pos.x = MIN(camera_pos.x, (new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT])); + camera_pos.x = MAX(camera_pos.x, (new_camera_pos.x - screen_size.x * 0.5 * drag_margin[MARGIN_LEFT])); } else { - if (h_ofs<0) { + if (h_ofs < 0) { camera_pos.x = new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT] * h_ofs; } else { camera_pos.x = new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_LEFT] * h_ofs; @@ -103,33 +98,33 @@ Transform2D Camera2D::get_camera_transform() { if (v_drag_enabled && !get_tree()->is_editor_hint()) { - camera_pos.y = MIN( camera_pos.y, (new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM])); - camera_pos.y = MAX( camera_pos.y, (new_camera_pos.y - screen_size.y * 0.5 * drag_margin[MARGIN_TOP])); + camera_pos.y = MIN(camera_pos.y, (new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM])); + camera_pos.y = MAX(camera_pos.y, (new_camera_pos.y - screen_size.y * 0.5 * drag_margin[MARGIN_TOP])); } else { - if (v_ofs<0) { + if (v_ofs < 0) { camera_pos.y = new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_TOP] * v_ofs; } else { camera_pos.y = new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM] * v_ofs; } } - } else if (anchor_mode==ANCHOR_MODE_FIXED_TOP_LEFT){ + } else if (anchor_mode == ANCHOR_MODE_FIXED_TOP_LEFT) { - camera_pos=new_camera_pos; + camera_pos = new_camera_pos; } - Point2 screen_offset = (anchor_mode==ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2()); - Rect2 screen_rect(-screen_offset+camera_pos,screen_size*zoom); - - if (offset!=Vector2()) - screen_rect.pos+=offset; - + Point2 screen_offset = (anchor_mode == ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2()); + Rect2 screen_rect(-screen_offset + camera_pos, screen_size * zoom); + + if (offset != Vector2()) + screen_rect.pos += offset; + if (limit_smoothing_enabled) { if (screen_rect.pos.x < limit[MARGIN_LEFT]) camera_pos.x -= screen_rect.pos.x - limit[MARGIN_LEFT]; - + if (screen_rect.pos.x + screen_rect.size.x > limit[MARGIN_RIGHT]) camera_pos.x -= screen_rect.pos.x + screen_rect.size.x - limit[MARGIN_RIGHT]; @@ -142,35 +137,31 @@ Transform2D Camera2D::get_camera_transform() { if (smoothing_enabled && !get_tree()->is_editor_hint()) { - float c = smoothing*get_fixed_process_delta_time(); - smoothed_camera_pos = ((camera_pos-smoothed_camera_pos)*c)+smoothed_camera_pos; - ret_camera_pos=smoothed_camera_pos; + float c = smoothing * get_fixed_process_delta_time(); + smoothed_camera_pos = ((camera_pos - smoothed_camera_pos) * c) + smoothed_camera_pos; + ret_camera_pos = smoothed_camera_pos; //camera_pos=camera_pos*(1.0-smoothing)+new_camera_pos*smoothing; } else { - ret_camera_pos=smoothed_camera_pos=camera_pos; - + ret_camera_pos = smoothed_camera_pos = camera_pos; } - - } else { - ret_camera_pos=smoothed_camera_pos=camera_pos=new_camera_pos; - first=false; + ret_camera_pos = smoothed_camera_pos = camera_pos = new_camera_pos; + first = false; } - - Point2 screen_offset = (anchor_mode==ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2()); + Point2 screen_offset = (anchor_mode == ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2()); float angle = get_global_transform().get_rotation(); - if(rotating){ + if (rotating) { screen_offset = screen_offset.rotated(angle); } - Rect2 screen_rect(-screen_offset+ret_camera_pos,screen_size*zoom); + Rect2 screen_rect(-screen_offset + ret_camera_pos, screen_size * zoom); if (screen_rect.pos.x < limit[MARGIN_LEFT]) screen_rect.pos.x = limit[MARGIN_LEFT]; - + if (screen_rect.pos.x + screen_rect.size.x > limit[MARGIN_RIGHT]) screen_rect.pos.x = limit[MARGIN_RIGHT] - screen_rect.size.x; @@ -178,38 +169,34 @@ Transform2D Camera2D::get_camera_transform() { screen_rect.pos.y = limit[MARGIN_BOTTOM] - screen_rect.size.y; if (screen_rect.pos.y < limit[MARGIN_TOP]) - screen_rect.pos.y =limit[MARGIN_TOP]; - - - if (offset!=Vector2()) { + screen_rect.pos.y = limit[MARGIN_TOP]; - screen_rect.pos+=offset; + if (offset != Vector2()) { + + screen_rect.pos += offset; if (screen_rect.pos.x + screen_rect.size.x > limit[MARGIN_RIGHT]) screen_rect.pos.x = limit[MARGIN_RIGHT] - screen_rect.size.x; if (screen_rect.pos.y + screen_rect.size.y > limit[MARGIN_BOTTOM]) screen_rect.pos.y = limit[MARGIN_BOTTOM] - screen_rect.size.y; - if (screen_rect.pos.x < limit[MARGIN_LEFT]) - screen_rect.pos.x=limit[MARGIN_LEFT]; + screen_rect.pos.x = limit[MARGIN_LEFT]; if (screen_rect.pos.y < limit[MARGIN_TOP]) - screen_rect.pos.y =limit[MARGIN_TOP]; - + screen_rect.pos.y = limit[MARGIN_TOP]; } - camera_screen_center=screen_rect.pos+screen_rect.size*0.5; + camera_screen_center = screen_rect.pos + screen_rect.size * 0.5; Transform2D xform; - if(rotating){ + if (rotating) { xform.set_rotation(angle); } xform.scale_basis(zoom); - xform.set_origin(screen_rect.pos/*.floor()*/); + xform.set_origin(screen_rect.pos /*.floor()*/); - -/* + /* if (0) { xform = get_global_transform() * xform; @@ -219,15 +206,12 @@ Transform2D Camera2D::get_camera_transform() { } */ - return (xform).affine_inverse(); } - - void Camera2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_FIXED_PROCESS: { @@ -236,48 +220,45 @@ void Camera2D::_notification(int p_what) { } break; case NOTIFICATION_TRANSFORM_CHANGED: { - if (!is_fixed_processing()) _update_scroll(); } break; case NOTIFICATION_ENTER_TREE: { - if (custom_viewport && ObjectDB::get_instance(custom_viewport_id)) { - viewport=custom_viewport; + viewport = custom_viewport; } else { - viewport=get_viewport(); + viewport = get_viewport(); } canvas = get_canvas(); RID vp = viewport->get_viewport_rid(); - group_name = "__cameras_"+itos(vp.get_id()); - canvas_group_name ="__cameras_c"+itos(canvas.get_id()); + group_name = "__cameras_" + itos(vp.get_id()); + canvas_group_name = "__cameras_c" + itos(canvas.get_id()); add_to_group(group_name); add_to_group(canvas_group_name); - if(get_tree()->is_editor_hint()) { + if (get_tree()->is_editor_hint()) { set_fixed_process(false); } _update_scroll(); - first=true; - + first = true; } break; case NOTIFICATION_EXIT_TREE: { - if (is_current()) { + if (is_current()) { if (viewport && !(custom_viewport && !ObjectDB::get_instance(custom_viewport_id))) { - viewport->set_canvas_transform( Transform2D() ); + viewport->set_canvas_transform(Transform2D()); } } remove_from_group(group_name); remove_from_group(canvas_group_name); - viewport=NULL; + viewport = NULL; } break; case NOTIFICATION_DRAW: { @@ -287,44 +268,43 @@ void Camera2D::_notification(int p_what) { Color area_axis_color(0.5, 0.42, 0.87, 0.63); float area_axis_width = 1; - if(current) + if (current) area_axis_width = 3; Transform2D inv_camera_transform = get_camera_transform().affine_inverse(); Size2 screen_size = get_viewport_rect().size; - Vector2 screen_endpoints[4]= { + Vector2 screen_endpoints[4] = { inv_camera_transform.xform(Vector2(0, 0)), - inv_camera_transform.xform(Vector2(screen_size.width,0)), + inv_camera_transform.xform(Vector2(screen_size.width, 0)), inv_camera_transform.xform(Vector2(screen_size.width, screen_size.height)), inv_camera_transform.xform(Vector2(0, screen_size.height)) }; Transform2D inv_transform = get_global_transform().affine_inverse(); // undo global space - for(int i=0;i<4;i++) { - draw_line(inv_transform.xform(screen_endpoints[i]), inv_transform.xform(screen_endpoints[(i+1)%4]), area_axis_color, area_axis_width); + for (int i = 0; i < 4; i++) { + draw_line(inv_transform.xform(screen_endpoints[i]), inv_transform.xform(screen_endpoints[(i + 1) % 4]), area_axis_color, area_axis_width); } } break; } } -void Camera2D::set_offset(const Vector2& p_offset) { +void Camera2D::set_offset(const Vector2 &p_offset) { - offset=p_offset; + offset = p_offset; _update_scroll(); - } -Vector2 Camera2D::get_offset() const{ +Vector2 Camera2D::get_offset() const { return offset; } -void Camera2D::set_anchor_mode(AnchorMode p_anchor_mode){ +void Camera2D::set_anchor_mode(AnchorMode p_anchor_mode) { - anchor_mode=p_anchor_mode; + anchor_mode = p_anchor_mode; _update_scroll(); } @@ -333,9 +313,9 @@ Camera2D::AnchorMode Camera2D::get_anchor_mode() const { return anchor_mode; } -void Camera2D::set_rotating(bool p_rotating){ +void Camera2D::set_rotating(bool p_rotating) { - rotating=p_rotating; + rotating = p_rotating; _update_scroll(); } @@ -344,25 +324,23 @@ bool Camera2D::is_rotating() const { return rotating; } - void Camera2D::_make_current(Object *p_which) { - if (p_which==this) { + if (p_which == this) { - current=true; + current = true; _update_scroll(); } else { - current=false; + current = false; } } - void Camera2D::_set_current(bool p_current) { if (p_current) make_current(); - current=p_current; + current = p_current; } bool Camera2D::is_current() const { @@ -373,33 +351,30 @@ bool Camera2D::is_current() const { void Camera2D::make_current() { if (!is_inside_tree()) { - current=true; + current = true; } else { - get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME,group_name,"_make_current",this); + get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_make_current", this); } } void Camera2D::clear_current() { - current=false; + current = false; if (is_inside_tree()) { - get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME,group_name,"_make_current",(Object*)(NULL)); + get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_make_current", (Object *)(NULL)); } - } +void Camera2D::set_limit(Margin p_margin, int p_limit) { -void Camera2D::set_limit(Margin p_margin,int p_limit) { - - ERR_FAIL_INDEX(p_margin,4); - limit[p_margin]=p_limit; + ERR_FAIL_INDEX(p_margin, 4); + limit[p_margin] = p_limit; } -int Camera2D::get_limit(Margin p_margin) const{ +int Camera2D::get_limit(Margin p_margin) const { - ERR_FAIL_INDEX_V(p_margin,4,0); + ERR_FAIL_INDEX_V(p_margin, 4, 0); return limit[p_margin]; - } void Camera2D::set_limit_smoothing_enabled(bool enable) { @@ -408,34 +383,30 @@ void Camera2D::set_limit_smoothing_enabled(bool enable) { _update_scroll(); } -bool Camera2D::is_limit_smoothing_enabled() const{ +bool Camera2D::is_limit_smoothing_enabled() const { return limit_smoothing_enabled; } -void Camera2D::set_drag_margin(Margin p_margin,float p_drag_margin) { +void Camera2D::set_drag_margin(Margin p_margin, float p_drag_margin) { - ERR_FAIL_INDEX(p_margin,4); - drag_margin[p_margin]=p_drag_margin; + ERR_FAIL_INDEX(p_margin, 4); + drag_margin[p_margin] = p_drag_margin; } -float Camera2D::get_drag_margin(Margin p_margin) const{ +float Camera2D::get_drag_margin(Margin p_margin) const { - ERR_FAIL_INDEX_V(p_margin,4,0); + ERR_FAIL_INDEX_V(p_margin, 4, 0); return drag_margin[p_margin]; - } - Vector2 Camera2D::get_camera_pos() const { - return camera_pos; } void Camera2D::force_update_scroll() { - _update_scroll(); } @@ -447,25 +418,25 @@ void Camera2D::reset_smoothing() { void Camera2D::align() { - ERR_FAIL_COND( custom_viewport && !ObjectDB::get_instance(custom_viewport_id) ); + ERR_FAIL_COND(custom_viewport && !ObjectDB::get_instance(custom_viewport_id)); Size2 screen_size = viewport->get_visible_rect().size; Point2 current_camera_pos = get_global_transform().get_origin(); - if (anchor_mode==ANCHOR_MODE_DRAG_CENTER) { - if (h_ofs<0) { + if (anchor_mode == ANCHOR_MODE_DRAG_CENTER) { + if (h_ofs < 0) { camera_pos.x = current_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT] * h_ofs; } else { camera_pos.x = current_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_LEFT] * h_ofs; } - if (v_ofs<0) { + if (v_ofs < 0) { camera_pos.y = current_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_TOP] * v_ofs; } else { camera_pos.y = current_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM] * v_ofs; } - } else if (anchor_mode==ANCHOR_MODE_FIXED_TOP_LEFT){ + } else if (anchor_mode == ANCHOR_MODE_FIXED_TOP_LEFT) { - camera_pos=current_camera_pos; + camera_pos = current_camera_pos; } _update_scroll(); @@ -473,77 +444,73 @@ void Camera2D::align() { void Camera2D::set_follow_smoothing(float p_speed) { - smoothing=p_speed; - if (smoothing>0 && !(is_inside_tree() && get_tree()->is_editor_hint())) + smoothing = p_speed; + if (smoothing > 0 && !(is_inside_tree() && get_tree()->is_editor_hint())) set_fixed_process(true); else set_fixed_process(false); } -float Camera2D::get_follow_smoothing() const{ +float Camera2D::get_follow_smoothing() const { return smoothing; } Point2 Camera2D::get_camera_screen_center() const { - return camera_screen_center; + return camera_screen_center; } - void Camera2D::set_h_drag_enabled(bool p_enabled) { - h_drag_enabled=p_enabled; + h_drag_enabled = p_enabled; } -bool Camera2D::is_h_drag_enabled() const{ +bool Camera2D::is_h_drag_enabled() const { - return h_drag_enabled; + return h_drag_enabled; } -void Camera2D::set_v_drag_enabled(bool p_enabled){ +void Camera2D::set_v_drag_enabled(bool p_enabled) { - v_drag_enabled=p_enabled; + v_drag_enabled = p_enabled; } -bool Camera2D::is_v_drag_enabled() const{ +bool Camera2D::is_v_drag_enabled() const { - return v_drag_enabled; + return v_drag_enabled; } void Camera2D::set_v_offset(float p_offset) { - v_ofs=p_offset; + v_ofs = p_offset; } -float Camera2D::get_v_offset() const{ +float Camera2D::get_v_offset() const { - return v_ofs; + return v_ofs; } -void Camera2D::set_h_offset(float p_offset){ +void Camera2D::set_h_offset(float p_offset) { - h_ofs=p_offset; + h_ofs = p_offset; } -float Camera2D::get_h_offset() const{ +float Camera2D::get_h_offset() const { - return h_ofs; + return h_ofs; } - void Camera2D::_set_old_smoothing(float p_val) { //compatibility - if (p_val>0) { - smoothing_enabled=true; + if (p_val > 0) { + smoothing_enabled = true; set_follow_smoothing(p_val); } - } void Camera2D::set_enable_follow_smoothing(bool p_enabled) { - smoothing_enabled=p_enabled; - + smoothing_enabled = p_enabled; } bool Camera2D::is_follow_smoothing_enabled() const { @@ -558,161 +525,154 @@ void Camera2D::set_custom_viewport(Node *p_viewport) { remove_from_group(canvas_group_name); } - custom_viewport=p_viewport->cast_to(); + custom_viewport = p_viewport->cast_to(); if (custom_viewport) { - custom_viewport_id=custom_viewport->get_instance_ID(); + custom_viewport_id = custom_viewport->get_instance_ID(); } else { - custom_viewport_id=0; + custom_viewport_id = 0; } if (is_inside_tree()) { if (custom_viewport) - viewport=custom_viewport; + viewport = custom_viewport; else - viewport=get_viewport(); + viewport = get_viewport(); RID vp = viewport->get_viewport_rid(); - group_name = "__cameras_"+itos(vp.get_id()); - canvas_group_name ="__cameras_c"+itos(canvas.get_id()); + group_name = "__cameras_" + itos(vp.get_id()); + canvas_group_name = "__cameras_c" + itos(canvas.get_id()); add_to_group(group_name); add_to_group(canvas_group_name); } - } -Node* Camera2D::get_custom_viewport() const { +Node *Camera2D::get_custom_viewport() const { return custom_viewport; } - void Camera2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_offset","offset"),&Camera2D::set_offset); - ClassDB::bind_method(D_METHOD("get_offset"),&Camera2D::get_offset); + ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Camera2D::set_offset); + ClassDB::bind_method(D_METHOD("get_offset"), &Camera2D::get_offset); - ClassDB::bind_method(D_METHOD("set_anchor_mode","anchor_mode"),&Camera2D::set_anchor_mode); - ClassDB::bind_method(D_METHOD("get_anchor_mode"),&Camera2D::get_anchor_mode); + ClassDB::bind_method(D_METHOD("set_anchor_mode", "anchor_mode"), &Camera2D::set_anchor_mode); + ClassDB::bind_method(D_METHOD("get_anchor_mode"), &Camera2D::get_anchor_mode); - ClassDB::bind_method(D_METHOD("set_rotating","rotating"),&Camera2D::set_rotating); - ClassDB::bind_method(D_METHOD("is_rotating"),&Camera2D::is_rotating); + ClassDB::bind_method(D_METHOD("set_rotating", "rotating"), &Camera2D::set_rotating); + ClassDB::bind_method(D_METHOD("is_rotating"), &Camera2D::is_rotating); - ClassDB::bind_method(D_METHOD("make_current"),&Camera2D::make_current); - ClassDB::bind_method(D_METHOD("clear_current"),&Camera2D::clear_current); - ClassDB::bind_method(D_METHOD("_make_current"),&Camera2D::_make_current); + ClassDB::bind_method(D_METHOD("make_current"), &Camera2D::make_current); + ClassDB::bind_method(D_METHOD("clear_current"), &Camera2D::clear_current); + ClassDB::bind_method(D_METHOD("_make_current"), &Camera2D::_make_current); - ClassDB::bind_method(D_METHOD("_update_scroll"),&Camera2D::_update_scroll); + ClassDB::bind_method(D_METHOD("_update_scroll"), &Camera2D::_update_scroll); - ClassDB::bind_method(D_METHOD("_set_current","current"),&Camera2D::_set_current); - ClassDB::bind_method(D_METHOD("is_current"),&Camera2D::is_current); + ClassDB::bind_method(D_METHOD("_set_current", "current"), &Camera2D::_set_current); + ClassDB::bind_method(D_METHOD("is_current"), &Camera2D::is_current); - ClassDB::bind_method(D_METHOD("set_limit","margin","limit"),&Camera2D::set_limit); - ClassDB::bind_method(D_METHOD("get_limit","margin"),&Camera2D::get_limit); + ClassDB::bind_method(D_METHOD("set_limit", "margin", "limit"), &Camera2D::set_limit); + ClassDB::bind_method(D_METHOD("get_limit", "margin"), &Camera2D::get_limit); - ClassDB::bind_method(D_METHOD("set_limit_smoothing_enabled","limit_smoothing_enabled"),&Camera2D::set_limit_smoothing_enabled); - ClassDB::bind_method(D_METHOD("is_limit_smoothing_enabled"),&Camera2D::is_limit_smoothing_enabled); + ClassDB::bind_method(D_METHOD("set_limit_smoothing_enabled", "limit_smoothing_enabled"), &Camera2D::set_limit_smoothing_enabled); + ClassDB::bind_method(D_METHOD("is_limit_smoothing_enabled"), &Camera2D::is_limit_smoothing_enabled); - ClassDB::bind_method(D_METHOD("set_v_drag_enabled","enabled"),&Camera2D::set_v_drag_enabled); - ClassDB::bind_method(D_METHOD("is_v_drag_enabled"),&Camera2D::is_v_drag_enabled); + ClassDB::bind_method(D_METHOD("set_v_drag_enabled", "enabled"), &Camera2D::set_v_drag_enabled); + ClassDB::bind_method(D_METHOD("is_v_drag_enabled"), &Camera2D::is_v_drag_enabled); - ClassDB::bind_method(D_METHOD("set_h_drag_enabled","enabled"),&Camera2D::set_h_drag_enabled); - ClassDB::bind_method(D_METHOD("is_h_drag_enabled"),&Camera2D::is_h_drag_enabled); + ClassDB::bind_method(D_METHOD("set_h_drag_enabled", "enabled"), &Camera2D::set_h_drag_enabled); + ClassDB::bind_method(D_METHOD("is_h_drag_enabled"), &Camera2D::is_h_drag_enabled); - ClassDB::bind_method(D_METHOD("set_v_offset","ofs"),&Camera2D::set_v_offset); - ClassDB::bind_method(D_METHOD("get_v_offset"),&Camera2D::get_v_offset); + ClassDB::bind_method(D_METHOD("set_v_offset", "ofs"), &Camera2D::set_v_offset); + ClassDB::bind_method(D_METHOD("get_v_offset"), &Camera2D::get_v_offset); - ClassDB::bind_method(D_METHOD("set_h_offset","ofs"),&Camera2D::set_h_offset); - ClassDB::bind_method(D_METHOD("get_h_offset"),&Camera2D::get_h_offset); + ClassDB::bind_method(D_METHOD("set_h_offset", "ofs"), &Camera2D::set_h_offset); + ClassDB::bind_method(D_METHOD("get_h_offset"), &Camera2D::get_h_offset); - ClassDB::bind_method(D_METHOD("set_drag_margin","margin","drag_margin"),&Camera2D::set_drag_margin); - ClassDB::bind_method(D_METHOD("get_drag_margin","margin"),&Camera2D::get_drag_margin); + ClassDB::bind_method(D_METHOD("set_drag_margin", "margin", "drag_margin"), &Camera2D::set_drag_margin); + ClassDB::bind_method(D_METHOD("get_drag_margin", "margin"), &Camera2D::get_drag_margin); - ClassDB::bind_method(D_METHOD("get_camera_pos"),&Camera2D::get_camera_pos); - ClassDB::bind_method(D_METHOD("get_camera_screen_center"),&Camera2D::get_camera_screen_center); + ClassDB::bind_method(D_METHOD("get_camera_pos"), &Camera2D::get_camera_pos); + ClassDB::bind_method(D_METHOD("get_camera_screen_center"), &Camera2D::get_camera_screen_center); - ClassDB::bind_method(D_METHOD("set_zoom","zoom"),&Camera2D::set_zoom); - ClassDB::bind_method(D_METHOD("get_zoom"),&Camera2D::get_zoom); + ClassDB::bind_method(D_METHOD("set_zoom", "zoom"), &Camera2D::set_zoom); + ClassDB::bind_method(D_METHOD("get_zoom"), &Camera2D::get_zoom); - ClassDB::bind_method(D_METHOD("set_custom_viewport","viewport:Viewport"),&Camera2D::set_custom_viewport); - ClassDB::bind_method(D_METHOD("get_custom_viewport:Viewport"),&Camera2D::get_custom_viewport); + ClassDB::bind_method(D_METHOD("set_custom_viewport", "viewport:Viewport"), &Camera2D::set_custom_viewport); + ClassDB::bind_method(D_METHOD("get_custom_viewport:Viewport"), &Camera2D::get_custom_viewport); - ClassDB::bind_method(D_METHOD("set_follow_smoothing","follow_smoothing"),&Camera2D::set_follow_smoothing); - ClassDB::bind_method(D_METHOD("get_follow_smoothing"),&Camera2D::get_follow_smoothing); + ClassDB::bind_method(D_METHOD("set_follow_smoothing", "follow_smoothing"), &Camera2D::set_follow_smoothing); + ClassDB::bind_method(D_METHOD("get_follow_smoothing"), &Camera2D::get_follow_smoothing); - ClassDB::bind_method(D_METHOD("set_enable_follow_smoothing","follow_smoothing"),&Camera2D::set_enable_follow_smoothing); - ClassDB::bind_method(D_METHOD("is_follow_smoothing_enabled"),&Camera2D::is_follow_smoothing_enabled); + ClassDB::bind_method(D_METHOD("set_enable_follow_smoothing", "follow_smoothing"), &Camera2D::set_enable_follow_smoothing); + ClassDB::bind_method(D_METHOD("is_follow_smoothing_enabled"), &Camera2D::is_follow_smoothing_enabled); - ClassDB::bind_method(D_METHOD("force_update_scroll"),&Camera2D::force_update_scroll); - ClassDB::bind_method(D_METHOD("reset_smoothing"),&Camera2D::reset_smoothing); - ClassDB::bind_method(D_METHOD("align"),&Camera2D::align); + ClassDB::bind_method(D_METHOD("force_update_scroll"), &Camera2D::force_update_scroll); + ClassDB::bind_method(D_METHOD("reset_smoothing"), &Camera2D::reset_smoothing); + ClassDB::bind_method(D_METHOD("align"), &Camera2D::align); - ClassDB::bind_method(D_METHOD("_set_old_smoothing","follow_smoothing"),&Camera2D::_set_old_smoothing); + ClassDB::bind_method(D_METHOD("_set_old_smoothing", "follow_smoothing"), &Camera2D::_set_old_smoothing); - ADD_PROPERTYNZ( PropertyInfo(Variant::VECTOR2,"offset"),"set_offset","get_offset"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"anchor_mode",PROPERTY_HINT_ENUM,"Fixed TopLeft,Drag Center"),"set_anchor_mode","get_anchor_mode"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"rotating"),"set_rotating","is_rotating"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"current"),"_set_current","is_current"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"zoom"),"set_zoom","get_zoom") ; + ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "anchor_mode", PROPERTY_HINT_ENUM, "Fixed TopLeft,Drag Center"), "set_anchor_mode", "get_anchor_mode"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "rotating"), "set_rotating", "is_rotating"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "current"), "_set_current", "is_current"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "zoom"), "set_zoom", "get_zoom"); - ADD_GROUP("Limit","limit_"); - ADD_PROPERTYI( PropertyInfo(Variant::INT,"limit_left"),"set_limit","get_limit",MARGIN_LEFT); - ADD_PROPERTYI( PropertyInfo(Variant::INT,"limit_top"),"set_limit","get_limit",MARGIN_TOP); - ADD_PROPERTYI( PropertyInfo(Variant::INT,"limit_right"),"set_limit","get_limit",MARGIN_RIGHT); - ADD_PROPERTYI( PropertyInfo(Variant::INT,"limit_bottom"),"set_limit","get_limit",MARGIN_BOTTOM); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"limit_smoothed"),"set_limit_smoothing_enabled","is_limit_smoothing_enabled") ; + ADD_GROUP("Limit", "limit_"); + ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_left"), "set_limit", "get_limit", MARGIN_LEFT); + ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_top"), "set_limit", "get_limit", MARGIN_TOP); + ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_right"), "set_limit", "get_limit", MARGIN_RIGHT); + ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_bottom"), "set_limit", "get_limit", MARGIN_BOTTOM); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "limit_smoothed"), "set_limit_smoothing_enabled", "is_limit_smoothing_enabled"); - ADD_GROUP("Draw Margin","draw_margin_"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"drag_margin_h_enabled"),"set_h_drag_enabled","is_h_drag_enabled") ; - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"drag_margin_v_enabled"),"set_v_drag_enabled","is_v_drag_enabled") ; + ADD_GROUP("Draw Margin", "draw_margin_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "drag_margin_h_enabled"), "set_h_drag_enabled", "is_h_drag_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "drag_margin_v_enabled"), "set_v_drag_enabled", "is_v_drag_enabled"); - ADD_GROUP("Smoothing","smoothing_"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"smoothing_enabled"),"set_enable_follow_smoothing","is_follow_smoothing_enabled") ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"smoothing_speed"),"set_follow_smoothing","get_follow_smoothing") ; + ADD_GROUP("Smoothing", "smoothing_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smoothing_enabled"), "set_enable_follow_smoothing", "is_follow_smoothing_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "smoothing_speed"), "set_follow_smoothing", "get_follow_smoothing"); - ADD_GROUP("Drag Margin","drag_margin_"); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"drag_margin_left",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drag_margin","get_drag_margin",MARGIN_LEFT); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"drag_margin_top",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drag_margin","get_drag_margin",MARGIN_TOP); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"drag_margin_right",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drag_margin","get_drag_margin",MARGIN_RIGHT); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"drag_margin_bottom",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drag_margin","get_drag_margin",MARGIN_BOTTOM); - - - BIND_CONSTANT( ANCHOR_MODE_DRAG_CENTER ); - BIND_CONSTANT( ANCHOR_MODE_FIXED_TOP_LEFT ); + ADD_GROUP("Drag Margin", "drag_margin_"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_left", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_LEFT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_top", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_TOP); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_right", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_RIGHT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_bottom", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_BOTTOM); + BIND_CONSTANT(ANCHOR_MODE_DRAG_CENTER); + BIND_CONSTANT(ANCHOR_MODE_FIXED_TOP_LEFT); } Camera2D::Camera2D() { - - - anchor_mode=ANCHOR_MODE_DRAG_CENTER; - rotating=false; - current=false; - limit[MARGIN_LEFT]=-10000000; - limit[MARGIN_TOP]=-10000000; - limit[MARGIN_RIGHT]=10000000; - limit[MARGIN_BOTTOM]=10000000; - - drag_margin[MARGIN_LEFT]=0.2; - drag_margin[MARGIN_TOP]=0.2; - drag_margin[MARGIN_RIGHT]=0.2; - drag_margin[MARGIN_BOTTOM]=0.2; - camera_pos=Vector2(); - first=true; - smoothing_enabled=false; - limit_smoothing_enabled=false; - custom_viewport=NULL; - custom_viewport_id=0; - - smoothing=5.0; + anchor_mode = ANCHOR_MODE_DRAG_CENTER; + rotating = false; + current = false; + limit[MARGIN_LEFT] = -10000000; + limit[MARGIN_TOP] = -10000000; + limit[MARGIN_RIGHT] = 10000000; + limit[MARGIN_BOTTOM] = 10000000; + + drag_margin[MARGIN_LEFT] = 0.2; + drag_margin[MARGIN_TOP] = 0.2; + drag_margin[MARGIN_RIGHT] = 0.2; + drag_margin[MARGIN_BOTTOM] = 0.2; + camera_pos = Vector2(); + first = true; + smoothing_enabled = false; + limit_smoothing_enabled = false; + custom_viewport = NULL; + custom_viewport_id = 0; + + smoothing = 5.0; zoom = Vector2(1, 1); - h_drag_enabled=true; - v_drag_enabled=true; - h_ofs=0; - v_ofs=0; + h_drag_enabled = true; + v_drag_enabled = true; + h_ofs = 0; + v_ofs = 0; set_notify_transform(true); - } diff --git a/scene/2d/camera_2d.h b/scene/2d/camera_2d.h index 85d90b225..44cdb5cd9 100644 --- a/scene/2d/camera_2d.h +++ b/scene/2d/camera_2d.h @@ -32,12 +32,11 @@ #include "scene/2d/node_2d.h" #include "scene/main/viewport.h" - class Camera2D : public Node2D { - GDCLASS( Camera2D, Node2D ); -public: + GDCLASS(Camera2D, Node2D); +public: enum AnchorMode { ANCHOR_MODE_FIXED_TOP_LEFT, ANCHOR_MODE_DRAG_CENTER @@ -78,14 +77,14 @@ protected: void _set_current(bool p_current); void _set_old_smoothing(float p_enable); -protected: +protected: virtual Transform2D get_camera_transform(); void _notification(int p_what); static void _bind_methods(); -public: - void set_offset(const Vector2& p_offset); +public: + void set_offset(const Vector2 &p_offset); Vector2 get_offset() const; void set_anchor_mode(AnchorMode p_anchor_mode); @@ -94,7 +93,7 @@ public: void set_rotating(bool p_rotating); bool is_rotating() const; - void set_limit(Margin p_margin,int p_limit); + void set_limit(Margin p_margin, int p_limit); int get_limit(Margin p_margin) const; void set_limit_smoothing_enabled(bool enable); @@ -106,7 +105,7 @@ public: void set_v_drag_enabled(bool p_enabled); bool is_v_drag_enabled() const; - void set_drag_margin(Margin p_margin,float p_drag_margin); + void set_drag_margin(Margin p_margin, float p_drag_margin); float get_drag_margin(Margin p_margin) const; void set_v_offset(float p_offset); @@ -125,13 +124,13 @@ public: void clear_current(); bool is_current() const; - void set_zoom(const Vector2& p_zoom); + void set_zoom(const Vector2 &p_zoom); Vector2 get_zoom() const; Point2 get_camera_screen_center() const; void set_custom_viewport(Node *p_viewport); - Node* get_custom_viewport() const; + Node *get_custom_viewport() const; Vector2 get_camera_pos() const; void force_update_scroll(); diff --git a/scene/2d/canvas_item.cpp b/scene/2d/canvas_item.cpp index 4f7acf7f9..b52dd8d66 100644 --- a/scene/2d/canvas_item.cpp +++ b/scene/2d/canvas_item.cpp @@ -27,35 +27,34 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "canvas_item.h" -#include "servers/visual_server.h" -#include "scene/main/viewport.h" -#include "scene/main/canvas_layer.h" #include "message_queue.h" -#include "scene/scene_string_names.h" +#include "os/input.h" +#include "scene/main/canvas_layer.h" +#include "scene/main/viewport.h" #include "scene/resources/font.h" -#include "scene/resources/texture.h" #include "scene/resources/style_box.h" -#include "os/input.h" +#include "scene/resources/texture.h" +#include "scene/scene_string_names.h" +#include "servers/visual_server.h" -bool CanvasItemMaterial::_set(const StringName& p_name, const Variant& p_value) { +bool CanvasItemMaterial::_set(const StringName &p_name, const Variant &p_value) { - if (p_name==SceneStringNames::get_singleton()->shader_shader) { + if (p_name == SceneStringNames::get_singleton()->shader_shader) { set_shader(p_value); return true; } else { if (shader.is_valid()) { - StringName pr = shader->remap_param(p_name); if (!pr) { String n = p_name; - if (n.find("param/")==0) { //backwards compatibility - pr = n.substr(6,n.length()); + if (n.find("param/") == 0) { //backwards compatibility + pr = n.substr(6, n.length()); } } if (pr) { - VisualServer::get_singleton()->material_set_param(_get_material(),pr,p_value); + VisualServer::get_singleton()->material_set_param(_get_material(), pr, p_value); return true; } } @@ -64,12 +63,11 @@ bool CanvasItemMaterial::_set(const StringName& p_name, const Variant& p_value) return false; } -bool CanvasItemMaterial::_get(const StringName& p_name,Variant &r_ret) const { +bool CanvasItemMaterial::_get(const StringName &p_name, Variant &r_ret) const { + if (p_name == SceneStringNames::get_singleton()->shader_shader) { - if (p_name==SceneStringNames::get_singleton()->shader_shader) { - - r_ret=get_shader(); + r_ret = get_shader(); return true; } else { @@ -78,128 +76,103 @@ bool CanvasItemMaterial::_get(const StringName& p_name,Variant &r_ret) const { StringName pr = shader->remap_param(p_name); if (pr) { - r_ret=VisualServer::get_singleton()->material_get_param(_get_material(),pr); + r_ret = VisualServer::get_singleton()->material_get_param(_get_material(), pr); return true; } } - } - return false; } +void CanvasItemMaterial::_get_property_list(List *p_list) const { -void CanvasItemMaterial::_get_property_list( List *p_list) const { - - p_list->push_back( PropertyInfo( Variant::OBJECT, "shader/shader", PROPERTY_HINT_RESOURCE_TYPE,"CanvasItemShader,CanvasItemShaderGraph" ) ); + p_list->push_back(PropertyInfo(Variant::OBJECT, "shader/shader", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemShader,CanvasItemShaderGraph")); if (!shader.is_null()) { shader->get_param_list(p_list); } - } -void CanvasItemMaterial::set_shader(const Ref& p_shader) { +void CanvasItemMaterial::set_shader(const Ref &p_shader) { - ERR_FAIL_COND(p_shader.is_valid() && p_shader->get_mode()!=Shader::MODE_CANVAS_ITEM); + ERR_FAIL_COND(p_shader.is_valid() && p_shader->get_mode() != Shader::MODE_CANVAS_ITEM); - shader=p_shader; + shader = p_shader; RID rid; if (shader.is_valid()) - rid=shader->get_rid(); + rid = shader->get_rid(); - VS::get_singleton()->material_set_shader(_get_material(),rid); + VS::get_singleton()->material_set_shader(_get_material(), rid); _change_notify(); //properties for shader exposed emit_changed(); } -Ref CanvasItemMaterial::get_shader() const{ +Ref CanvasItemMaterial::get_shader() const { return shader; } -void CanvasItemMaterial::set_shader_param(const StringName& p_param,const Variant& p_value){ +void CanvasItemMaterial::set_shader_param(const StringName &p_param, const Variant &p_value) { - VS::get_singleton()->material_set_param(_get_material(),p_param,p_value); + VS::get_singleton()->material_set_param(_get_material(), p_param, p_value); } -Variant CanvasItemMaterial::get_shader_param(const StringName& p_param) const{ +Variant CanvasItemMaterial::get_shader_param(const StringName &p_param) const { - return VS::get_singleton()->material_get_param(_get_material(),p_param); + return VS::get_singleton()->material_get_param(_get_material(), p_param); } - - void CanvasItemMaterial::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_shader","shader:Shader"),&CanvasItemMaterial::set_shader); - ClassDB::bind_method(D_METHOD("get_shader:Shader"),&CanvasItemMaterial::get_shader); - ClassDB::bind_method(D_METHOD("set_shader_param","param","value"),&CanvasItemMaterial::set_shader_param); - ClassDB::bind_method(D_METHOD("get_shader_param","param"),&CanvasItemMaterial::get_shader_param); - - - + ClassDB::bind_method(D_METHOD("set_shader", "shader:Shader"), &CanvasItemMaterial::set_shader); + ClassDB::bind_method(D_METHOD("get_shader:Shader"), &CanvasItemMaterial::get_shader); + ClassDB::bind_method(D_METHOD("set_shader_param", "param", "value"), &CanvasItemMaterial::set_shader_param); + ClassDB::bind_method(D_METHOD("get_shader_param", "param"), &CanvasItemMaterial::get_shader_param); } -void CanvasItemMaterial::get_argument_options(const StringName& p_function,int p_idx,List*r_options) const { +void CanvasItemMaterial::get_argument_options(const StringName &p_function, int p_idx, List *r_options) const { String f = p_function.operator String(); - if ((f=="get_shader_param" || f=="set_shader_param") && p_idx==0) { + if ((f == "get_shader_param" || f == "set_shader_param") && p_idx == 0) { if (shader.is_valid()) { List pl; shader->get_param_list(&pl); - for (List::Element *E=pl.front();E;E=E->next()) { - r_options->push_back("\""+E->get().name.replace_first("shader_param/","")+"\""); + for (List::Element *E = pl.front(); E; E = E->next()) { + r_options->push_back("\"" + E->get().name.replace_first("shader_param/", "") + "\""); } } } - Resource::get_argument_options(p_function,p_idx,r_options); + Resource::get_argument_options(p_function, p_idx, r_options); } CanvasItemMaterial::CanvasItemMaterial() { - - - } -CanvasItemMaterial::~CanvasItemMaterial(){ - - +CanvasItemMaterial::~CanvasItemMaterial() { } - - - - - - - /////////////////////////////////////////////////////////////////// - - bool CanvasItem::is_visible_in_tree() const { if (!is_inside_tree()) return false; - const CanvasItem *p=this; + const CanvasItem *p = this; - while(p) { + while (p) { if (!p->visible) return false; - p=p->get_parent_item(); + p = p->get_parent_item(); } - return true; } - void CanvasItem::_propagate_visibility_changed(bool p_visible) { notification(NOTIFICATION_VISIBILITY_CHANGED); @@ -210,16 +183,15 @@ void CanvasItem::_propagate_visibility_changed(bool p_visible) { emit_signal(SceneStringNames::get_singleton()->hide); _block(); - for(int i=0;icast_to(); + CanvasItem *c = get_child(i)->cast_to(); if (c && c->visible) //should the toplevels stop propagation? i think so but.. c->_propagate_visibility_changed(p_visible); } _unblock(); - } void CanvasItem::show() { @@ -227,8 +199,8 @@ void CanvasItem::show() { if (visible) return; - visible=true; - VisualServer::get_singleton()->canvas_item_set_visible(canvas_item,true); + visible = true; + VisualServer::get_singleton()->canvas_item_set_visible(canvas_item, true); if (!is_inside_tree()) return; @@ -237,14 +209,13 @@ void CanvasItem::show() { _change_notify("visibility/visible"); } - void CanvasItem::hide() { if (!visible) return; - visible=false; - VisualServer::get_singleton()->canvas_item_set_visible(canvas_item,false); + visible = false; + VisualServer::get_singleton()->canvas_item_set_visible(canvas_item, false); if (!is_inside_tree()) return; @@ -255,35 +226,28 @@ void CanvasItem::hide() { Variant CanvasItem::edit_get_state() const { - return Variant(); } -void CanvasItem::edit_set_state(const Variant& p_state) { - - +void CanvasItem::edit_set_state(const Variant &p_state) { } -void CanvasItem::edit_set_rect(const Rect2& p_edit_rect) { +void CanvasItem::edit_set_rect(const Rect2 &p_edit_rect) { //used by editors, implement at will } void CanvasItem::edit_rotate(float p_rot) { - - } Size2 CanvasItem::edit_get_minimum_size() const { - return Size2(-1,-1); //no limit + return Size2(-1, -1); //no limit } void CanvasItem::_update_callback() { - - if (!is_inside_tree()) { - pending_update=false; + pending_update = false; return; } @@ -292,33 +256,32 @@ void CanvasItem::_update_callback() { if (is_visible_in_tree()) { //todo optimize this!! if (first_draw) { notification(NOTIFICATION_VISIBILITY_CHANGED); - first_draw=false; + first_draw = false; } - drawing=true; + drawing = true; notification(NOTIFICATION_DRAW); emit_signal(SceneStringNames::get_singleton()->draw); if (get_script_instance()) { Variant::CallError err; - get_script_instance()->call_multilevel_reversed(SceneStringNames::get_singleton()->_draw,NULL,0); + get_script_instance()->call_multilevel_reversed(SceneStringNames::get_singleton()->_draw, NULL, 0); } - drawing=false; - + drawing = false; } //todo updating = false - pending_update=false; // don't change to false until finished drawing (avoid recursive update) + pending_update = false; // don't change to false until finished drawing (avoid recursive update) } Transform2D CanvasItem::get_global_transform_with_canvas() const { const CanvasItem *ci = this; Transform2D xform; - const CanvasItem *last_valid=NULL; + const CanvasItem *last_valid = NULL; - while(ci) { + while (ci) { - last_valid=ci; + last_valid = ci; xform = ci->get_transform() * xform; - ci=ci->get_parent_item(); + ci = ci->get_parent_item(); } if (last_valid->canvas_layer) @@ -331,7 +294,6 @@ Transform2D CanvasItem::get_global_transform_with_canvas() const { Transform2D CanvasItem::get_global_transform() const { - if (global_invalid) { const CanvasItem *pi = get_parent_item(); @@ -340,11 +302,10 @@ Transform2D CanvasItem::get_global_transform() const { else global_transform = get_transform(); - global_invalid=false; + global_invalid = false; } return global_transform; - } void CanvasItem::_toplevel_raise_self() { @@ -353,40 +314,37 @@ void CanvasItem::_toplevel_raise_self() { return; if (canvas_layer) - VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item,canvas_layer->get_sort_index()); + VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item, canvas_layer->get_sort_index()); else - VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item,get_viewport()->gui_get_canvas_sort_index()); - - + VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item, get_viewport()->gui_get_canvas_sort_index()); } - void CanvasItem::_enter_canvas() { if ((!get_parent() || !get_parent()->cast_to()) || toplevel) { Node *n = this; - canvas_layer=NULL; + canvas_layer = NULL; - while(n) { + while (n) { canvas_layer = n->cast_to(); if (canvas_layer) { break; } - n=n->get_parent(); + n = n->get_parent(); } RID canvas; if (canvas_layer) - canvas=canvas_layer->get_world_2d()->get_canvas(); + canvas = canvas_layer->get_world_2d()->get_canvas(); else - canvas=get_viewport()->find_world_2d()->get_canvas(); + canvas = get_viewport()->find_world_2d()->get_canvas(); - VisualServer::get_singleton()->canvas_item_set_parent(canvas_item,canvas); + VisualServer::get_singleton()->canvas_item_set_parent(canvas_item, canvas); - group = "root_canvas"+itos(canvas.get_id()); + group = "root_canvas" + itos(canvas.get_id()); add_to_group(group); if (canvas_layer) @@ -394,44 +352,40 @@ void CanvasItem::_enter_canvas() { else get_viewport()->gui_reset_canvas_sort_index(); - get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE,group,"_toplevel_raise_self"); + get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE, group, "_toplevel_raise_self"); } else { CanvasItem *parent = get_parent_item(); - canvas_layer=parent->canvas_layer; - VisualServer::get_singleton()->canvas_item_set_parent(canvas_item,parent->get_canvas_item()); - VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item,get_index()); + canvas_layer = parent->canvas_layer; + VisualServer::get_singleton()->canvas_item_set_parent(canvas_item, parent->get_canvas_item()); + VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item, get_index()); } - pending_update=false; + pending_update = false; update(); notification(NOTIFICATION_ENTER_CANVAS); - } void CanvasItem::_exit_canvas() { - notification(NOTIFICATION_EXIT_CANVAS,true); //reverse the notification - VisualServer::get_singleton()->canvas_item_set_parent(canvas_item,RID()); - canvas_layer=NULL; - group=""; - + notification(NOTIFICATION_EXIT_CANVAS, true); //reverse the notification + VisualServer::get_singleton()->canvas_item_set_parent(canvas_item, RID()); + canvas_layer = NULL; + group = ""; } - void CanvasItem::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - first_draw=true; + first_draw = true; if (get_parent()) { CanvasItem *ci = get_parent()->cast_to(); if (ci) - C=ci->children_items.push_back(this); + C = ci->children_items.push_back(this); } _enter_canvas(); if (!block_transform_notify && !xform_change.in_list()) { @@ -443,15 +397,14 @@ void CanvasItem::_notification(int p_what) { if (!is_inside_tree()) break; - if (group!="") { - get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE,group,"_toplevel_raise_self"); + if (group != "") { + get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE, group, "_toplevel_raise_self"); } else { CanvasItem *p = get_parent_item(); ERR_FAIL_COND(!p); - VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item,get_index()); + VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item, get_index()); } - } break; case NOTIFICATION_EXIT_TREE: { if (xform_change.in_list()) @@ -459,22 +412,20 @@ void CanvasItem::_notification(int p_what) { _exit_canvas(); if (C) { get_parent()->cast_to()->children_items.erase(C); - C=NULL; + C = NULL; } - global_invalid=true; + global_invalid = true; } break; case NOTIFICATION_DRAW: { } break; case NOTIFICATION_TRANSFORM_CHANGED: { - } break; case NOTIFICATION_VISIBILITY_CHANGED: { emit_signal(SceneStringNames::get_singleton()->visibility_changed); } break; - } } @@ -490,7 +441,6 @@ bool CanvasItem::is_visible() const { return visible; } - void CanvasItem::update() { if (!is_inside_tree()) @@ -498,35 +448,33 @@ void CanvasItem::update() { if (pending_update) return; - pending_update=true; + pending_update = true; - MessageQueue::get_singleton()->push_call(this,"_update_callback"); + MessageQueue::get_singleton()->push_call(this, "_update_callback"); } -void CanvasItem::set_modulate(const Color& p_modulate) { - - modulate=p_modulate; - VisualServer::get_singleton()->canvas_item_set_modulate(canvas_item,modulate); +void CanvasItem::set_modulate(const Color &p_modulate) { + modulate = p_modulate; + VisualServer::get_singleton()->canvas_item_set_modulate(canvas_item, modulate); } Color CanvasItem::get_modulate() const { return modulate; } - void CanvasItem::set_as_toplevel(bool p_toplevel) { - if (toplevel==p_toplevel) + if (toplevel == p_toplevel) return; if (!is_inside_tree()) { - toplevel=p_toplevel; + toplevel = p_toplevel; return; } _exit_canvas(); - toplevel=p_toplevel; + toplevel = p_toplevel; _enter_canvas(); } @@ -547,31 +495,27 @@ CanvasItem *CanvasItem::get_parent_item() const { return parent->cast_to(); } +void CanvasItem::set_self_modulate(const Color &p_self_modulate) { -void CanvasItem::set_self_modulate(const Color& p_self_modulate) { - - self_modulate=p_self_modulate; - VisualServer::get_singleton()->canvas_item_set_self_modulate(canvas_item,self_modulate); - + self_modulate = p_self_modulate; + VisualServer::get_singleton()->canvas_item_set_self_modulate(canvas_item, self_modulate); } Color CanvasItem::get_self_modulate() const { return self_modulate; } - void CanvasItem::set_light_mask(int p_light_mask) { - light_mask=p_light_mask; - VS::get_singleton()->canvas_item_set_light_mask(canvas_item,p_light_mask); + light_mask = p_light_mask; + VS::get_singleton()->canvas_item_set_light_mask(canvas_item, p_light_mask); } -int CanvasItem::get_light_mask() const{ +int CanvasItem::get_light_mask() const { return light_mask; } - void CanvasItem::item_rect_changed(bool p_size_changed) { if (p_size_changed) @@ -579,40 +523,37 @@ void CanvasItem::item_rect_changed(bool p_size_changed) { emit_signal(SceneStringNames::get_singleton()->item_rect_changed); } - -void CanvasItem::draw_line(const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width,bool p_antialiased) { +void CanvasItem::draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width, bool p_antialiased) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); ERR_FAIL(); } - VisualServer::get_singleton()->canvas_item_add_line(canvas_item,p_from,p_to,p_color,p_width,p_antialiased); + VisualServer::get_singleton()->canvas_item_add_line(canvas_item, p_from, p_to, p_color, p_width, p_antialiased); } -void CanvasItem::draw_rect(const Rect2& p_rect, const Color& p_color) { +void CanvasItem::draw_rect(const Rect2 &p_rect, const Color &p_color) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); ERR_FAIL(); } - VisualServer::get_singleton()->canvas_item_add_rect(canvas_item,p_rect,p_color); - + VisualServer::get_singleton()->canvas_item_add_rect(canvas_item, p_rect, p_color); } -void CanvasItem::draw_circle(const Point2& p_pos, float p_radius, const Color& p_color) { +void CanvasItem::draw_circle(const Point2 &p_pos, float p_radius, const Color &p_color) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); ERR_FAIL(); } - VisualServer::get_singleton()->canvas_item_add_circle(canvas_item,p_pos,p_radius,p_color); - + VisualServer::get_singleton()->canvas_item_add_circle(canvas_item, p_pos, p_radius, p_color); } -void CanvasItem::draw_texture(const Ref& p_texture,const Point2& p_pos,const Color& p_modulate) { +void CanvasItem::draw_texture(const Ref &p_texture, const Point2 &p_pos, const Color &p_modulate) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); @@ -621,10 +562,10 @@ void CanvasItem::draw_texture(const Ref& p_texture,const Point2& p_pos, ERR_FAIL_COND(p_texture.is_null()); - p_texture->draw(canvas_item,p_pos,p_modulate); + p_texture->draw(canvas_item, p_pos, p_modulate); } -void CanvasItem::draw_texture_rect(const Ref& p_texture,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) { +void CanvasItem::draw_texture_rect(const Ref &p_texture, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); @@ -632,20 +573,19 @@ void CanvasItem::draw_texture_rect(const Ref& p_texture,const Rect2& p_ } ERR_FAIL_COND(p_texture.is_null()); - p_texture->draw_rect(canvas_item,p_rect,p_tile,p_modulate,p_transpose); - + p_texture->draw_rect(canvas_item, p_rect, p_tile, p_modulate, p_transpose); } -void CanvasItem::draw_texture_rect_region(const Ref& p_texture,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) { +void CanvasItem::draw_texture_rect_region(const Ref &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); ERR_FAIL(); } ERR_FAIL_COND(p_texture.is_null()); - p_texture->draw_rect_region(canvas_item,p_rect,p_src_rect,p_modulate,p_transpose); + p_texture->draw_rect_region(canvas_item, p_rect, p_src_rect, p_modulate, p_transpose); } -void CanvasItem::draw_style_box(const Ref& p_style_box,const Rect2& p_rect) { +void CanvasItem::draw_style_box(const Ref &p_style_box, const Rect2 &p_rect) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); ERR_FAIL(); @@ -653,10 +593,9 @@ void CanvasItem::draw_style_box(const Ref& p_style_box,const Rect2& p_ ERR_FAIL_COND(p_style_box.is_null()); - p_style_box->draw(canvas_item,p_rect); - + p_style_box->draw(canvas_item, p_rect); } -void CanvasItem::draw_primitive(const Vector& p_points, const Vector& p_colors,const Vector& p_uvs, Ref p_texture,float p_width) { +void CanvasItem::draw_primitive(const Vector &p_points, const Vector &p_colors, const Vector &p_uvs, Ref p_texture, float p_width) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); @@ -665,32 +604,31 @@ void CanvasItem::draw_primitive(const Vector& p_points, const Vectorget_rid() : RID(); - VisualServer::get_singleton()->canvas_item_add_primitive(canvas_item,p_points,p_colors,p_uvs,rid,p_width); + VisualServer::get_singleton()->canvas_item_add_primitive(canvas_item, p_points, p_colors, p_uvs, rid, p_width); } -void CanvasItem::draw_set_transform(const Point2& p_offset, float p_rot, const Size2& p_scale) { +void CanvasItem::draw_set_transform(const Point2 &p_offset, float p_rot, const Size2 &p_scale) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); ERR_FAIL(); } - Transform2D xform(p_rot,p_offset); + Transform2D xform(p_rot, p_offset); xform.scale_basis(p_scale); - VisualServer::get_singleton()->canvas_item_add_set_transform(canvas_item,xform); + VisualServer::get_singleton()->canvas_item_add_set_transform(canvas_item, xform); } -void CanvasItem::draw_set_transform_matrix(const Transform2D& p_matrix) { +void CanvasItem::draw_set_transform_matrix(const Transform2D &p_matrix) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); ERR_FAIL(); } - VisualServer::get_singleton()->canvas_item_add_set_transform(canvas_item,p_matrix); - + VisualServer::get_singleton()->canvas_item_add_set_transform(canvas_item, p_matrix); } -void CanvasItem::draw_polygon(const Vector& p_points, const Vector& p_colors,const Vector& p_uvs, Ref p_texture) { +void CanvasItem::draw_polygon(const Vector &p_points, const Vector &p_colors, const Vector &p_uvs, Ref p_texture) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); @@ -699,12 +637,10 @@ void CanvasItem::draw_polygon(const Vector& p_points, const Vectorget_rid() : RID(); - VisualServer::get_singleton()->canvas_item_add_polygon(canvas_item,p_points,p_colors,p_uvs,rid); - - + VisualServer::get_singleton()->canvas_item_add_polygon(canvas_item, p_points, p_colors, p_uvs, rid); } -void CanvasItem::draw_colored_polygon(const Vector& p_points, const Color& p_color,const Vector& p_uvs, Ref p_texture) { +void CanvasItem::draw_colored_polygon(const Vector &p_points, const Color &p_color, const Vector &p_uvs, Ref p_texture) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); @@ -715,10 +651,10 @@ void CanvasItem::draw_colored_polygon(const Vector& p_points, const Colo colors.push_back(p_color); RID rid = p_texture.is_valid() ? p_texture->get_rid() : RID(); - VisualServer::get_singleton()->canvas_item_add_polygon(canvas_item,p_points,colors,p_uvs,rid); + VisualServer::get_singleton()->canvas_item_add_polygon(canvas_item, p_points, colors, p_uvs, rid); } -void CanvasItem::draw_string(const Ref& p_font,const Point2& p_pos, const String& p_text,const Color& p_modulate,int p_clip_w) { +void CanvasItem::draw_string(const Ref &p_font, const Point2 &p_pos, const String &p_text, const Color &p_modulate, int p_clip_w) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); @@ -726,31 +662,28 @@ void CanvasItem::draw_string(const Ref& p_font,const Point2& p_pos, const } ERR_FAIL_COND(p_font.is_null()); - p_font->draw(canvas_item,p_pos,p_text,p_modulate,p_clip_w); - + p_font->draw(canvas_item, p_pos, p_text, p_modulate, p_clip_w); } -float CanvasItem::draw_char(const Ref& p_font,const Point2& p_pos, const String& p_char,const String& p_next,const Color& p_modulate) { +float CanvasItem::draw_char(const Ref &p_font, const Point2 &p_pos, const String &p_char, const String &p_next, const Color &p_modulate) { if (!drawing) { ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); ERR_FAIL_V(0); } - ERR_FAIL_COND_V(p_char.length()!=1,0); - ERR_FAIL_COND_V(p_font.is_null(),0); - - return p_font->draw_char(canvas_item,p_pos,p_char[0],p_next.c_str()[0],p_modulate); + ERR_FAIL_COND_V(p_char.length() != 1, 0); + ERR_FAIL_COND_V(p_font.is_null(), 0); + return p_font->draw_char(canvas_item, p_pos, p_char[0], p_next.c_str()[0], p_modulate); } - void CanvasItem::_notify_transform(CanvasItem *p_node) { if (/*p_node->xform_change.in_list() &&*/ p_node->global_invalid) return; //nothing to do - p_node->global_invalid=true; + p_node->global_invalid = true; if (p_node->notify_transform && !p_node->xform_change.in_list()) { if (!p_node->block_transform_notify) { @@ -759,51 +692,46 @@ void CanvasItem::_notify_transform(CanvasItem *p_node) { } } + for (List::Element *E = p_node->children_items.front(); E; E = E->next()) { - for(List::Element *E=p_node->children_items.front();E;E=E->next()) { - - CanvasItem* ci=E->get(); + CanvasItem *ci = E->get(); if (ci->toplevel) continue; _notify_transform(ci); } } - Rect2 CanvasItem::get_viewport_rect() const { - ERR_FAIL_COND_V(!is_inside_tree(),Rect2()); + ERR_FAIL_COND_V(!is_inside_tree(), Rect2()); return get_viewport()->get_visible_rect(); } RID CanvasItem::get_canvas() const { - ERR_FAIL_COND_V(!is_inside_tree(),RID()); + ERR_FAIL_COND_V(!is_inside_tree(), RID()); if (canvas_layer) return canvas_layer->get_world_2d()->get_canvas(); else return get_viewport()->find_world_2d()->get_canvas(); - - } CanvasItem *CanvasItem::get_toplevel() const { - CanvasItem *ci=const_cast(this); - while(!ci->toplevel && ci->get_parent() && ci->get_parent()->cast_to()) { - ci=ci->get_parent()->cast_to(); + CanvasItem *ci = const_cast(this); + while (!ci->toplevel && ci->get_parent() && ci->get_parent()->cast_to()) { + ci = ci->get_parent()->cast_to(); } return ci; } - Ref CanvasItem::get_world_2d() const { - ERR_FAIL_COND_V(!is_inside_tree(),Ref()); + ERR_FAIL_COND_V(!is_inside_tree(), Ref()); - CanvasItem *tl=get_toplevel(); + CanvasItem *tl = get_toplevel(); if (tl->canvas_layer) { return tl->canvas_layer->get_world_2d(); @@ -812,17 +740,16 @@ Ref CanvasItem::get_world_2d() const { } else { return Ref(); } - } RID CanvasItem::get_viewport_rid() const { - ERR_FAIL_COND_V(!is_inside_tree(),RID()); + ERR_FAIL_COND_V(!is_inside_tree(), RID()); return get_viewport()->get_viewport_rid(); } void CanvasItem::set_block_transform_notify(bool p_enable) { - block_transform_notify=p_enable; + block_transform_notify = p_enable; } bool CanvasItem::is_block_transform_notify_enabled() const { @@ -832,205 +759,196 @@ bool CanvasItem::is_block_transform_notify_enabled() const { void CanvasItem::set_draw_behind_parent(bool p_enable) { - if (behind==p_enable) + if (behind == p_enable) return; - behind=p_enable; - VisualServer::get_singleton()->canvas_item_set_draw_behind_parent(canvas_item,behind); - + behind = p_enable; + VisualServer::get_singleton()->canvas_item_set_draw_behind_parent(canvas_item, behind); } -bool CanvasItem::is_draw_behind_parent_enabled() const{ +bool CanvasItem::is_draw_behind_parent_enabled() const { return behind; } -void CanvasItem::set_material(const Ref& p_material) { - +void CanvasItem::set_material(const Ref &p_material) { - material=p_material; + material = p_material; RID rid; if (material.is_valid()) - rid=material->get_rid(); - VS::get_singleton()->canvas_item_set_material(canvas_item,rid); + rid = material->get_rid(); + VS::get_singleton()->canvas_item_set_material(canvas_item, rid); _change_notify(); //properties for material exposed } void CanvasItem::set_use_parent_material(bool p_use_parent_material) { - use_parent_material=p_use_parent_material; - VS::get_singleton()->canvas_item_set_use_parent_material(canvas_item,p_use_parent_material); + use_parent_material = p_use_parent_material; + VS::get_singleton()->canvas_item_set_use_parent_material(canvas_item, p_use_parent_material); } -bool CanvasItem::get_use_parent_material() const{ +bool CanvasItem::get_use_parent_material() const { return use_parent_material; } -Ref CanvasItem::get_material() const{ +Ref CanvasItem::get_material() const { return material; } -Vector2 CanvasItem::make_canvas_pos_local(const Vector2& screen_point) const { +Vector2 CanvasItem::make_canvas_pos_local(const Vector2 &screen_point) const { - ERR_FAIL_COND_V(!is_inside_tree(),screen_point); + ERR_FAIL_COND_V(!is_inside_tree(), screen_point); - Transform2D local_matrix = (get_canvas_transform() * - get_global_transform()).affine_inverse(); + Transform2D local_matrix = (get_canvas_transform() * + get_global_transform()) + .affine_inverse(); return local_matrix.xform(screen_point); } -InputEvent CanvasItem::make_input_local(const InputEvent& p_event) const { - - ERR_FAIL_COND_V(!is_inside_tree(),p_event); +InputEvent CanvasItem::make_input_local(const InputEvent &p_event) const { - return p_event.xform_by( (get_canvas_transform() * get_global_transform()).affine_inverse() ); + ERR_FAIL_COND_V(!is_inside_tree(), p_event); + return p_event.xform_by((get_canvas_transform() * get_global_transform()).affine_inverse()); } - Vector2 CanvasItem::get_global_mouse_pos() const { - ERR_FAIL_COND_V(!get_viewport(),Vector2()); - return get_canvas_transform().affine_inverse().xform( get_viewport()->get_mouse_pos() ); + ERR_FAIL_COND_V(!get_viewport(), Vector2()); + return get_canvas_transform().affine_inverse().xform(get_viewport()->get_mouse_pos()); } -Vector2 CanvasItem::get_local_mouse_pos() const{ +Vector2 CanvasItem::get_local_mouse_pos() const { - ERR_FAIL_COND_V(!get_viewport(),Vector2()); + ERR_FAIL_COND_V(!get_viewport(), Vector2()); - return get_global_transform().affine_inverse().xform( get_global_mouse_pos() ); + return get_global_transform().affine_inverse().xform(get_global_mouse_pos()); } - void CanvasItem::_bind_methods() { - ClassDB::bind_method(D_METHOD("_toplevel_raise_self"),&CanvasItem::_toplevel_raise_self); - ClassDB::bind_method(D_METHOD("_update_callback"),&CanvasItem::_update_callback); + ClassDB::bind_method(D_METHOD("_toplevel_raise_self"), &CanvasItem::_toplevel_raise_self); + ClassDB::bind_method(D_METHOD("_update_callback"), &CanvasItem::_update_callback); - ClassDB::bind_method(D_METHOD("edit_set_state","state"),&CanvasItem::edit_set_state); - ClassDB::bind_method(D_METHOD("edit_get_state:Variant"),&CanvasItem::edit_get_state); - ClassDB::bind_method(D_METHOD("edit_set_rect","rect"),&CanvasItem::edit_set_rect); - ClassDB::bind_method(D_METHOD("edit_rotate","degrees"),&CanvasItem::edit_rotate); + ClassDB::bind_method(D_METHOD("edit_set_state", "state"), &CanvasItem::edit_set_state); + ClassDB::bind_method(D_METHOD("edit_get_state:Variant"), &CanvasItem::edit_get_state); + ClassDB::bind_method(D_METHOD("edit_set_rect", "rect"), &CanvasItem::edit_set_rect); + ClassDB::bind_method(D_METHOD("edit_rotate", "degrees"), &CanvasItem::edit_rotate); - ClassDB::bind_method(D_METHOD("get_item_rect"),&CanvasItem::get_item_rect); - ClassDB::bind_method(D_METHOD("get_item_and_children_rect"),&CanvasItem::get_item_and_children_rect); + ClassDB::bind_method(D_METHOD("get_item_rect"), &CanvasItem::get_item_rect); + ClassDB::bind_method(D_METHOD("get_item_and_children_rect"), &CanvasItem::get_item_and_children_rect); //ClassDB::bind_method(D_METHOD("get_transform"),&CanvasItem::get_transform); - ClassDB::bind_method(D_METHOD("get_canvas_item"),&CanvasItem::get_canvas_item); + ClassDB::bind_method(D_METHOD("get_canvas_item"), &CanvasItem::get_canvas_item); - ClassDB::bind_method(D_METHOD("set_visible"),&CanvasItem::set_visible); - ClassDB::bind_method(D_METHOD("is_visible"),&CanvasItem::is_visible); - ClassDB::bind_method(D_METHOD("is_visible_in_tree"),&CanvasItem::is_visible_in_tree); - ClassDB::bind_method(D_METHOD("show"),&CanvasItem::show); - ClassDB::bind_method(D_METHOD("hide"),&CanvasItem::hide); + ClassDB::bind_method(D_METHOD("set_visible"), &CanvasItem::set_visible); + ClassDB::bind_method(D_METHOD("is_visible"), &CanvasItem::is_visible); + ClassDB::bind_method(D_METHOD("is_visible_in_tree"), &CanvasItem::is_visible_in_tree); + ClassDB::bind_method(D_METHOD("show"), &CanvasItem::show); + ClassDB::bind_method(D_METHOD("hide"), &CanvasItem::hide); - ClassDB::bind_method(D_METHOD("update"),&CanvasItem::update); + ClassDB::bind_method(D_METHOD("update"), &CanvasItem::update); - ClassDB::bind_method(D_METHOD("set_as_toplevel","enable"),&CanvasItem::set_as_toplevel); - ClassDB::bind_method(D_METHOD("is_set_as_toplevel"),&CanvasItem::is_set_as_toplevel); + ClassDB::bind_method(D_METHOD("set_as_toplevel", "enable"), &CanvasItem::set_as_toplevel); + ClassDB::bind_method(D_METHOD("is_set_as_toplevel"), &CanvasItem::is_set_as_toplevel); - ClassDB::bind_method(D_METHOD("set_light_mask","light_mask"),&CanvasItem::set_light_mask); - ClassDB::bind_method(D_METHOD("get_light_mask"),&CanvasItem::get_light_mask); + ClassDB::bind_method(D_METHOD("set_light_mask", "light_mask"), &CanvasItem::set_light_mask); + ClassDB::bind_method(D_METHOD("get_light_mask"), &CanvasItem::get_light_mask); - ClassDB::bind_method(D_METHOD("set_modulate","modulate"),&CanvasItem::set_modulate); - ClassDB::bind_method(D_METHOD("get_modulate"),&CanvasItem::get_modulate); - ClassDB::bind_method(D_METHOD("set_self_modulate","self_modulate"),&CanvasItem::set_self_modulate); - ClassDB::bind_method(D_METHOD("get_self_modulate"),&CanvasItem::get_self_modulate); + ClassDB::bind_method(D_METHOD("set_modulate", "modulate"), &CanvasItem::set_modulate); + ClassDB::bind_method(D_METHOD("get_modulate"), &CanvasItem::get_modulate); + ClassDB::bind_method(D_METHOD("set_self_modulate", "self_modulate"), &CanvasItem::set_self_modulate); + ClassDB::bind_method(D_METHOD("get_self_modulate"), &CanvasItem::get_self_modulate); - ClassDB::bind_method(D_METHOD("set_draw_behind_parent","enable"),&CanvasItem::set_draw_behind_parent); - ClassDB::bind_method(D_METHOD("is_draw_behind_parent_enabled"),&CanvasItem::is_draw_behind_parent_enabled); + ClassDB::bind_method(D_METHOD("set_draw_behind_parent", "enable"), &CanvasItem::set_draw_behind_parent); + ClassDB::bind_method(D_METHOD("is_draw_behind_parent_enabled"), &CanvasItem::is_draw_behind_parent_enabled); - ClassDB::bind_method(D_METHOD("_set_on_top","on_top"),&CanvasItem::_set_on_top); - ClassDB::bind_method(D_METHOD("_is_on_top"),&CanvasItem::_is_on_top); + ClassDB::bind_method(D_METHOD("_set_on_top", "on_top"), &CanvasItem::_set_on_top); + ClassDB::bind_method(D_METHOD("_is_on_top"), &CanvasItem::_is_on_top); //ClassDB::bind_method(D_METHOD("get_transform"),&CanvasItem::get_transform); - ClassDB::bind_method(D_METHOD("draw_line","from","to","color","width","antialiased"),&CanvasItem::draw_line,DEFVAL(1.0),DEFVAL(false)); - ClassDB::bind_method(D_METHOD("draw_rect","rect","color"),&CanvasItem::draw_rect); - ClassDB::bind_method(D_METHOD("draw_circle","pos","radius","color"),&CanvasItem::draw_circle); - ClassDB::bind_method(D_METHOD("draw_texture","texture:Texture","pos","modulate"),&CanvasItem::draw_texture,DEFVAL(Color(1,1,1,1))); - ClassDB::bind_method(D_METHOD("draw_texture_rect","texture:Texture","rect","tile","modulate","transpose"),&CanvasItem::draw_texture_rect,DEFVAL(Color(1,1,1)),DEFVAL(false)); - ClassDB::bind_method(D_METHOD("draw_texture_rect_region","texture:Texture","rect","src_rect","modulate","transpose"),&CanvasItem::draw_texture_rect_region,DEFVAL(Color(1,1,1)),DEFVAL(false)); - ClassDB::bind_method(D_METHOD("draw_style_box","style_box:StyleBox","rect"),&CanvasItem::draw_style_box); - ClassDB::bind_method(D_METHOD("draw_primitive","points","colors","uvs","texture:Texture","width"),&CanvasItem::draw_primitive,DEFVAL(Variant()),DEFVAL(1.0)); - ClassDB::bind_method(D_METHOD("draw_polygon","points","colors","uvs","texture:Texture"),&CanvasItem::draw_polygon,DEFVAL(PoolVector2Array()),DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("draw_colored_polygon","points","color","uvs","texture:Texture"),&CanvasItem::draw_colored_polygon,DEFVAL(PoolVector2Array()),DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("draw_string","font:Font","pos","text","modulate","clip_w"),&CanvasItem::draw_string,DEFVAL(Color(1,1,1)),DEFVAL(-1)); - ClassDB::bind_method(D_METHOD("draw_char","font:Font","pos","char","next","modulate"),&CanvasItem::draw_char,DEFVAL(Color(1,1,1))); - - ClassDB::bind_method(D_METHOD("draw_set_transform","pos","rot","scale"),&CanvasItem::draw_set_transform); - ClassDB::bind_method(D_METHOD("draw_set_transform_matrix","xform"),&CanvasItem::draw_set_transform_matrix); - ClassDB::bind_method(D_METHOD("get_transform"),&CanvasItem::get_transform); - ClassDB::bind_method(D_METHOD("get_global_transform"),&CanvasItem::get_global_transform); - ClassDB::bind_method(D_METHOD("get_global_transform_with_canvas"),&CanvasItem::get_global_transform_with_canvas); - ClassDB::bind_method(D_METHOD("get_viewport_transform"),&CanvasItem::get_viewport_transform); - ClassDB::bind_method(D_METHOD("get_viewport_rect"),&CanvasItem::get_viewport_rect); - ClassDB::bind_method(D_METHOD("get_canvas_transform"),&CanvasItem::get_canvas_transform); - ClassDB::bind_method(D_METHOD("get_local_mouse_pos"),&CanvasItem::get_local_mouse_pos); - ClassDB::bind_method(D_METHOD("get_global_mouse_pos"),&CanvasItem::get_global_mouse_pos); - ClassDB::bind_method(D_METHOD("get_canvas"),&CanvasItem::get_canvas); - ClassDB::bind_method(D_METHOD("get_world_2d"),&CanvasItem::get_world_2d); + ClassDB::bind_method(D_METHOD("draw_line", "from", "to", "color", "width", "antialiased"), &CanvasItem::draw_line, DEFVAL(1.0), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("draw_rect", "rect", "color"), &CanvasItem::draw_rect); + ClassDB::bind_method(D_METHOD("draw_circle", "pos", "radius", "color"), &CanvasItem::draw_circle); + ClassDB::bind_method(D_METHOD("draw_texture", "texture:Texture", "pos", "modulate"), &CanvasItem::draw_texture, DEFVAL(Color(1, 1, 1, 1))); + ClassDB::bind_method(D_METHOD("draw_texture_rect", "texture:Texture", "rect", "tile", "modulate", "transpose"), &CanvasItem::draw_texture_rect, DEFVAL(Color(1, 1, 1)), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("draw_texture_rect_region", "texture:Texture", "rect", "src_rect", "modulate", "transpose"), &CanvasItem::draw_texture_rect_region, DEFVAL(Color(1, 1, 1)), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("draw_style_box", "style_box:StyleBox", "rect"), &CanvasItem::draw_style_box); + ClassDB::bind_method(D_METHOD("draw_primitive", "points", "colors", "uvs", "texture:Texture", "width"), &CanvasItem::draw_primitive, DEFVAL(Variant()), DEFVAL(1.0)); + ClassDB::bind_method(D_METHOD("draw_polygon", "points", "colors", "uvs", "texture:Texture"), &CanvasItem::draw_polygon, DEFVAL(PoolVector2Array()), DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("draw_colored_polygon", "points", "color", "uvs", "texture:Texture"), &CanvasItem::draw_colored_polygon, DEFVAL(PoolVector2Array()), DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("draw_string", "font:Font", "pos", "text", "modulate", "clip_w"), &CanvasItem::draw_string, DEFVAL(Color(1, 1, 1)), DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("draw_char", "font:Font", "pos", "char", "next", "modulate"), &CanvasItem::draw_char, DEFVAL(Color(1, 1, 1))); + + ClassDB::bind_method(D_METHOD("draw_set_transform", "pos", "rot", "scale"), &CanvasItem::draw_set_transform); + ClassDB::bind_method(D_METHOD("draw_set_transform_matrix", "xform"), &CanvasItem::draw_set_transform_matrix); + ClassDB::bind_method(D_METHOD("get_transform"), &CanvasItem::get_transform); + ClassDB::bind_method(D_METHOD("get_global_transform"), &CanvasItem::get_global_transform); + ClassDB::bind_method(D_METHOD("get_global_transform_with_canvas"), &CanvasItem::get_global_transform_with_canvas); + ClassDB::bind_method(D_METHOD("get_viewport_transform"), &CanvasItem::get_viewport_transform); + ClassDB::bind_method(D_METHOD("get_viewport_rect"), &CanvasItem::get_viewport_rect); + ClassDB::bind_method(D_METHOD("get_canvas_transform"), &CanvasItem::get_canvas_transform); + ClassDB::bind_method(D_METHOD("get_local_mouse_pos"), &CanvasItem::get_local_mouse_pos); + ClassDB::bind_method(D_METHOD("get_global_mouse_pos"), &CanvasItem::get_global_mouse_pos); + ClassDB::bind_method(D_METHOD("get_canvas"), &CanvasItem::get_canvas); + ClassDB::bind_method(D_METHOD("get_world_2d"), &CanvasItem::get_world_2d); //ClassDB::bind_method(D_METHOD("get_viewport"),&CanvasItem::get_viewport); - ClassDB::bind_method(D_METHOD("set_material","material:CanvasItemMaterial"),&CanvasItem::set_material); - ClassDB::bind_method(D_METHOD("get_material:CanvasItemMaterial"),&CanvasItem::get_material); + ClassDB::bind_method(D_METHOD("set_material", "material:CanvasItemMaterial"), &CanvasItem::set_material); + ClassDB::bind_method(D_METHOD("get_material:CanvasItemMaterial"), &CanvasItem::get_material); - ClassDB::bind_method(D_METHOD("set_use_parent_material","enable"),&CanvasItem::set_use_parent_material); - ClassDB::bind_method(D_METHOD("get_use_parent_material"),&CanvasItem::get_use_parent_material); + ClassDB::bind_method(D_METHOD("set_use_parent_material", "enable"), &CanvasItem::set_use_parent_material); + ClassDB::bind_method(D_METHOD("get_use_parent_material"), &CanvasItem::get_use_parent_material); - ClassDB::bind_method(D_METHOD("set_notify_local_transform","enable"),&CanvasItem::set_notify_local_transform); - ClassDB::bind_method(D_METHOD("is_local_transform_notification_enabled"),&CanvasItem::is_local_transform_notification_enabled); + ClassDB::bind_method(D_METHOD("set_notify_local_transform", "enable"), &CanvasItem::set_notify_local_transform); + ClassDB::bind_method(D_METHOD("is_local_transform_notification_enabled"), &CanvasItem::is_local_transform_notification_enabled); - ClassDB::bind_method(D_METHOD("set_notify_transform","enable"),&CanvasItem::set_notify_transform); - ClassDB::bind_method(D_METHOD("is_transform_notification_enabled"),&CanvasItem::is_transform_notification_enabled); + ClassDB::bind_method(D_METHOD("set_notify_transform", "enable"), &CanvasItem::set_notify_transform); + ClassDB::bind_method(D_METHOD("is_transform_notification_enabled"), &CanvasItem::is_transform_notification_enabled); - ClassDB::bind_method(D_METHOD("make_canvas_pos_local","screen_point"), + ClassDB::bind_method(D_METHOD("make_canvas_pos_local", "screen_point"), &CanvasItem::make_canvas_pos_local); - ClassDB::bind_method(D_METHOD("make_input_local","event"),&CanvasItem::make_input_local); + ClassDB::bind_method(D_METHOD("make_input_local", "event"), &CanvasItem::make_input_local); BIND_VMETHOD(MethodInfo("_draw")); - ADD_GROUP("Visibility",""); - ADD_PROPERTYNO( PropertyInfo(Variant::BOOL,"visible"), "set_visible","is_visible") ; - ADD_PROPERTYNO( PropertyInfo(Variant::COLOR,"modulate"), "set_modulate","get_modulate") ; - ADD_PROPERTYNO( PropertyInfo(Variant::COLOR,"self_modulate"), "set_self_modulate","get_self_modulate") ; - ADD_PROPERTYNZ( PropertyInfo(Variant::BOOL,"show_behind_parent"), "set_draw_behind_parent","is_draw_behind_parent_enabled") ; - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"show_on_top",PROPERTY_HINT_NONE,"",0), "_set_on_top","_is_on_top") ; //compatibility - ADD_PROPERTYNO( PropertyInfo(Variant::INT,"light_mask",PROPERTY_HINT_LAYERS_2D_RENDER), "set_light_mask","get_light_mask") ; - - ADD_GROUP("Material",""); - ADD_PROPERTYNZ( PropertyInfo(Variant::OBJECT,"material",PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial"), "set_material","get_material") ; - ADD_PROPERTYNZ( PropertyInfo(Variant::BOOL,"use_parent_material"), "set_use_parent_material","get_use_parent_material") ; + ADD_GROUP("Visibility", ""); + ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "visible"), "set_visible", "is_visible"); + ADD_PROPERTYNO(PropertyInfo(Variant::COLOR, "modulate"), "set_modulate", "get_modulate"); + ADD_PROPERTYNO(PropertyInfo(Variant::COLOR, "self_modulate"), "set_self_modulate", "get_self_modulate"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "show_behind_parent"), "set_draw_behind_parent", "is_draw_behind_parent_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_on_top", PROPERTY_HINT_NONE, "", 0), "_set_on_top", "_is_on_top"); //compatibility + ADD_PROPERTYNO(PropertyInfo(Variant::INT, "light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_light_mask", "get_light_mask"); + + ADD_GROUP("Material", ""); + ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial"), "set_material", "get_material"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "use_parent_material"), "set_use_parent_material", "get_use_parent_material"); //exporting these two things doesn't really make much sense i think //ADD_PROPERTY( PropertyInfo(Variant::BOOL,"transform/toplevel"), "set_as_toplevel","is_set_as_toplevel") ; //ADD_PROPERTY(PropertyInfo(Variant::BOOL,"transform/notify"),"set_transform_notify","is_transform_notify_enabled"); - ADD_SIGNAL( MethodInfo("draw") ); - ADD_SIGNAL( MethodInfo("visibility_changed") ); - ADD_SIGNAL( MethodInfo("hide") ); - ADD_SIGNAL( MethodInfo("item_rect_changed") ); - - - - BIND_CONSTANT( BLEND_MODE_MIX ); - BIND_CONSTANT( BLEND_MODE_ADD ); - BIND_CONSTANT( BLEND_MODE_SUB ); - BIND_CONSTANT( BLEND_MODE_MUL ); - BIND_CONSTANT( BLEND_MODE_PREMULT_ALPHA ); - - - BIND_CONSTANT( NOTIFICATION_DRAW); - BIND_CONSTANT( NOTIFICATION_VISIBILITY_CHANGED ); - BIND_CONSTANT( NOTIFICATION_ENTER_CANVAS ); - BIND_CONSTANT( NOTIFICATION_EXIT_CANVAS ); - BIND_CONSTANT( NOTIFICATION_TRANSFORM_CHANGED ); + ADD_SIGNAL(MethodInfo("draw")); + ADD_SIGNAL(MethodInfo("visibility_changed")); + ADD_SIGNAL(MethodInfo("hide")); + ADD_SIGNAL(MethodInfo("item_rect_changed")); + BIND_CONSTANT(BLEND_MODE_MIX); + BIND_CONSTANT(BLEND_MODE_ADD); + BIND_CONSTANT(BLEND_MODE_SUB); + BIND_CONSTANT(BLEND_MODE_MUL); + BIND_CONSTANT(BLEND_MODE_PREMULT_ALPHA); + BIND_CONSTANT(NOTIFICATION_DRAW); + BIND_CONSTANT(NOTIFICATION_VISIBILITY_CHANGED); + BIND_CONSTANT(NOTIFICATION_ENTER_CANVAS); + BIND_CONSTANT(NOTIFICATION_EXIT_CANVAS); + BIND_CONSTANT(NOTIFICATION_TRANSFORM_CHANGED); } Transform2D CanvasItem::get_canvas_transform() const { - ERR_FAIL_COND_V(!is_inside_tree(),Transform2D()); + ERR_FAIL_COND_V(!is_inside_tree(), Transform2D()); if (canvas_layer) return canvas_layer->get_transform(); @@ -1038,12 +956,11 @@ Transform2D CanvasItem::get_canvas_transform() const { return get_parent()->cast_to()->get_canvas_transform(); else return get_viewport()->get_canvas_transform(); - } Transform2D CanvasItem::get_viewport_transform() const { - ERR_FAIL_COND_V(!is_inside_tree(),Transform2D()); + ERR_FAIL_COND_V(!is_inside_tree(), Transform2D()); if (canvas_layer) { @@ -1056,21 +973,18 @@ Transform2D CanvasItem::get_viewport_transform() const { } else { return get_viewport()->get_final_transform() * get_viewport()->get_canvas_transform(); } - } - void CanvasItem::set_notify_local_transform(bool p_enable) { - notify_local_transform=p_enable; + notify_local_transform = p_enable; } bool CanvasItem::is_local_transform_notification_enabled() const { return notify_local_transform; } - void CanvasItem::set_notify_transform(bool p_enable) { - notify_transform=p_enable; + notify_transform = p_enable; } bool CanvasItem::is_transform_notification_enabled() const { @@ -1085,14 +999,12 @@ int CanvasItem::get_canvas_layer() const { return 0; } - Rect2 CanvasItem::get_item_and_children_rect() const { Rect2 rect = get_item_rect(); - - for(int i=0;icast_to(); + for (int i = 0; i < get_child_count(); i++) { + CanvasItem *c = get_child(i)->cast_to(); if (c) { Rect2 sir = c->get_transform().xform(c->get_item_and_children_rect()); rect = rect.merge(sir); @@ -1102,29 +1014,28 @@ Rect2 CanvasItem::get_item_and_children_rect() const { return rect; } -CanvasItem::CanvasItem() : xform_change(this) { +CanvasItem::CanvasItem() + : xform_change(this) { - - canvas_item=VisualServer::get_singleton()->canvas_item_create(); - visible=true; - pending_update=false; - modulate=Color(1,1,1,1); - self_modulate=Color(1,1,1,1); - toplevel=false; - first_draw=false; - drawing=false; - behind=false; - block_transform_notify=false; + canvas_item = VisualServer::get_singleton()->canvas_item_create(); + visible = true; + pending_update = false; + modulate = Color(1, 1, 1, 1); + self_modulate = Color(1, 1, 1, 1); + toplevel = false; + first_draw = false; + drawing = false; + behind = false; + block_transform_notify = false; //viewport=NULL; - canvas_layer=NULL; - use_parent_material=false; - global_invalid=true; - notify_local_transform=false; - notify_transform=false; - light_mask=1; - - C=NULL; - + canvas_layer = NULL; + use_parent_material = false; + global_invalid = true; + notify_local_transform = false; + notify_transform = false; + light_mask = 1; + + C = NULL; } CanvasItem::~CanvasItem() { diff --git a/scene/2d/canvas_item.h b/scene/2d/canvas_item.h index 9688b873c..a188ce495 100644 --- a/scene/2d/canvas_item.h +++ b/scene/2d/canvas_item.h @@ -30,10 +30,10 @@ #define CANVAS_ITEM_H #include "scene/main/node.h" -#include "scene/resources/texture.h" #include "scene/main/scene_main_loop.h" -#include "scene/resources/shader.h" #include "scene/resources/material.h" +#include "scene/resources/shader.h" +#include "scene/resources/texture.h" class CanvasLayer; class Viewport; @@ -43,8 +43,9 @@ class StyleBox; class CanvasItemMaterial : public Material { - GDCLASS(CanvasItemMaterial,Material); + GDCLASS(CanvasItemMaterial, Material); Ref shader; + public: /*enum ShadingMode { SHADING_NORMAL, @@ -53,34 +54,30 @@ public: };*/ protected: - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; static void _bind_methods(); - void get_argument_options(const StringName& p_function,int p_idx,List*r_options) const; + void get_argument_options(const StringName &p_function, int p_idx, List *r_options) const; public: - - void set_shader(const Ref& p_shader); + void set_shader(const Ref &p_shader); Ref get_shader() const; - void set_shader_param(const StringName& p_param,const Variant& p_value); - Variant get_shader_param(const StringName& p_param) const; + void set_shader_param(const StringName &p_param, const Variant &p_value); + Variant get_shader_param(const StringName &p_param) const; CanvasItemMaterial(); ~CanvasItemMaterial(); }; - - - class CanvasItem : public Node { - GDCLASS( CanvasItem, Node ); -public: + GDCLASS(CanvasItem, Node); +public: enum BlendMode { BLEND_MODE_MIX, //default @@ -91,20 +88,18 @@ public: }; private: - mutable SelfList xform_change; RID canvas_item; String group; - CanvasLayer *canvas_layer; Color modulate; Color self_modulate; - List children_items; - List::Element *C; + List children_items; + List::Element *C; int light_mask; @@ -124,12 +119,10 @@ private: mutable Transform2D global_transform; mutable bool global_invalid; - void _toplevel_raise_self(); void _propagate_visibility_changed(bool p_visible); - void _update_callback(); void _enter_canvas(); @@ -141,32 +134,34 @@ private: bool _is_on_top() const { return !is_draw_behind_parent_enabled(); } protected: + _FORCE_INLINE_ void _notify_transform() { + if (!is_inside_tree()) return; + _notify_transform(this); + if (!block_transform_notify && notify_local_transform) notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED); + } - _FORCE_INLINE_ void _notify_transform() { if (!is_inside_tree()) return; _notify_transform(this); if (!block_transform_notify && notify_local_transform) notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED); } - - void item_rect_changed(bool p_size_changed=true); + void item_rect_changed(bool p_size_changed = true); void _notification(int p_what); static void _bind_methods(); -public: - +public: enum { - NOTIFICATION_TRANSFORM_CHANGED=SceneTree::NOTIFICATION_TRANSFORM_CHANGED, //unique - NOTIFICATION_DRAW=30, - NOTIFICATION_VISIBILITY_CHANGED=31, - NOTIFICATION_ENTER_CANVAS=32, - NOTIFICATION_EXIT_CANVAS=33, - NOTIFICATION_LOCAL_TRANSFORM_CHANGED=35, - NOTIFICATION_WORLD_2D_CHANGED=36, + NOTIFICATION_TRANSFORM_CHANGED = SceneTree::NOTIFICATION_TRANSFORM_CHANGED, //unique + NOTIFICATION_DRAW = 30, + NOTIFICATION_VISIBILITY_CHANGED = 31, + NOTIFICATION_ENTER_CANVAS = 32, + NOTIFICATION_EXIT_CANVAS = 33, + NOTIFICATION_LOCAL_TRANSFORM_CHANGED = 35, + NOTIFICATION_WORLD_2D_CHANGED = 36, }; /* EDITOR */ virtual Variant edit_get_state() const; - virtual void edit_set_state(const Variant& p_state); - virtual void edit_set_rect(const Rect2& p_edit_rect); + virtual void edit_set_state(const Variant &p_state); + virtual void edit_set_rect(const Rect2 &p_edit_rect); virtual void edit_rotate(float p_rot); virtual Size2 edit_get_minimum_size() const; @@ -183,30 +178,30 @@ public: virtual void set_light_mask(int p_light_mask); int get_light_mask() const; - void set_modulate(const Color& p_modulate); + void set_modulate(const Color &p_modulate); Color get_modulate() const; - void set_self_modulate(const Color& p_self_modulate); + void set_self_modulate(const Color &p_self_modulate); Color get_self_modulate() const; /* DRAWING API */ - void draw_line(const Point2& p_from, const Point2& p_to, const Color& p_color, float p_width=1.0, bool p_antialiased=false); - void draw_rect(const Rect2& p_rect, const Color& p_color); - void draw_circle(const Point2& p_pos, float p_radius, const Color& p_color); - void draw_texture(const Ref& p_texture, const Point2& p_pos, const Color &p_modulate=Color(1,1,1,1)); - void draw_texture_rect(const Ref& p_texture, const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false); - void draw_texture_rect_region(const Ref& p_texture,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false); - void draw_style_box(const Ref& p_style_box,const Rect2& p_rect); - void draw_primitive(const Vector& p_points, const Vector& p_colors,const Vector& p_uvs, Ref p_texture=Ref(),float p_width=1); - void draw_polygon(const Vector& p_points, const Vector& p_colors,const Vector& p_uvs=Vector(), Ref p_texture=Ref()); - void draw_colored_polygon(const Vector& p_points, const Color& p_color,const Vector& p_uvs=Vector(), Ref p_texture=Ref()); + void draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0, bool p_antialiased = false); + void draw_rect(const Rect2 &p_rect, const Color &p_color); + void draw_circle(const Point2 &p_pos, float p_radius, const Color &p_color); + void draw_texture(const Ref &p_texture, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1, 1)); + void draw_texture_rect(const Ref &p_texture, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false); + void draw_texture_rect_region(const Ref &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false); + void draw_style_box(const Ref &p_style_box, const Rect2 &p_rect); + void draw_primitive(const Vector &p_points, const Vector &p_colors, const Vector &p_uvs, Ref p_texture = Ref(), float p_width = 1); + void draw_polygon(const Vector &p_points, const Vector &p_colors, const Vector &p_uvs = Vector(), Ref p_texture = Ref()); + void draw_colored_polygon(const Vector &p_points, const Color &p_color, const Vector &p_uvs = Vector(), Ref p_texture = Ref()); - void draw_string(const Ref& p_font, const Point2& p_pos, const String& p_text,const Color& p_modulate=Color(1,1,1),int p_clip_w=-1); - float draw_char(const Ref& p_font,const Point2& p_pos, const String& p_char,const String& p_next="",const Color& p_modulate=Color(1,1,1)); + void draw_string(const Ref &p_font, const Point2 &p_pos, const String &p_text, const Color &p_modulate = Color(1, 1, 1), int p_clip_w = -1); + float draw_char(const Ref &p_font, const Point2 &p_pos, const String &p_char, const String &p_next = "", const Color &p_modulate = Color(1, 1, 1)); - void draw_set_transform(const Point2& p_offset, float p_rot, const Size2& p_scale); - void draw_set_transform_matrix(const Transform2D& p_matrix); + void draw_set_transform(const Point2 &p_offset, float p_rot, const Size2 &p_scale); + void draw_set_transform_matrix(const Transform2D &p_matrix); /* RECT / TRANSFORM */ @@ -218,8 +213,8 @@ public: CanvasItem *get_parent_item() const; - virtual Rect2 get_item_rect() const=0; - virtual Transform2D get_transform() const=0; + virtual Rect2 get_item_rect() const = 0; + virtual Transform2D get_transform() const = 0; virtual Transform2D get_global_transform() const; virtual Transform2D get_global_transform_with_canvas() const; @@ -232,7 +227,6 @@ public: void set_block_transform_notify(bool p_enable); bool is_block_transform_notify_enabled() const; - Transform2D get_canvas_transform() const; Transform2D get_viewport_transform() const; Rect2 get_viewport_rect() const; @@ -240,14 +234,14 @@ public: RID get_canvas() const; Ref get_world_2d() const; - void set_material(const Ref& p_material); + void set_material(const Ref &p_material); Ref get_material() const; void set_use_parent_material(bool p_use_parent_material); bool get_use_parent_material() const; - InputEvent make_input_local(const InputEvent& pevent) const; - Vector2 make_canvas_pos_local(const Vector2& screen_point) const; + InputEvent make_input_local(const InputEvent &pevent) const; + Vector2 make_canvas_pos_local(const Vector2 &screen_point) const; Vector2 get_global_mouse_pos() const; Vector2 get_local_mouse_pos() const; @@ -264,6 +258,6 @@ public: ~CanvasItem(); }; -VARIANT_ENUM_CAST( CanvasItem::BlendMode ); +VARIANT_ENUM_CAST(CanvasItem::BlendMode); #endif // CANVAS_ITEM_H diff --git a/scene/2d/canvas_modulate.cpp b/scene/2d/canvas_modulate.cpp index ecc11ea60..a0e3061c8 100644 --- a/scene/2d/canvas_modulate.cpp +++ b/scene/2d/canvas_modulate.cpp @@ -28,52 +28,48 @@ /*************************************************************************/ #include "canvas_modulate.h" - void CanvasModulate::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_CANVAS) { + if (p_what == NOTIFICATION_ENTER_CANVAS) { if (is_visible_in_tree()) { - VS::get_singleton()->canvas_set_modulate(get_canvas(),color); - add_to_group("_canvas_modulate_"+itos(get_canvas().get_id())); + VS::get_singleton()->canvas_set_modulate(get_canvas(), color); + add_to_group("_canvas_modulate_" + itos(get_canvas().get_id())); } - - - } else if (p_what==NOTIFICATION_EXIT_CANVAS) { + } else if (p_what == NOTIFICATION_EXIT_CANVAS) { if (is_visible_in_tree()) { - VS::get_singleton()->canvas_set_modulate(get_canvas(),Color(1,1,1,1)); - remove_from_group("_canvas_modulate_"+itos(get_canvas().get_id())); + VS::get_singleton()->canvas_set_modulate(get_canvas(), Color(1, 1, 1, 1)); + remove_from_group("_canvas_modulate_" + itos(get_canvas().get_id())); } - } else if (p_what==NOTIFICATION_VISIBILITY_CHANGED) { + } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { if (is_visible_in_tree()) { - VS::get_singleton()->canvas_set_modulate(get_canvas(),color); - add_to_group("_canvas_modulate_"+itos(get_canvas().get_id())); + VS::get_singleton()->canvas_set_modulate(get_canvas(), color); + add_to_group("_canvas_modulate_" + itos(get_canvas().get_id())); } else { - VS::get_singleton()->canvas_set_modulate(get_canvas(),Color(1,1,1,1)); - remove_from_group("_canvas_modulate_"+itos(get_canvas().get_id())); + VS::get_singleton()->canvas_set_modulate(get_canvas(), Color(1, 1, 1, 1)); + remove_from_group("_canvas_modulate_" + itos(get_canvas().get_id())); } update_configuration_warning(); } } -void CanvasModulate::_bind_methods(){ +void CanvasModulate::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_color","color"),&CanvasModulate::set_color); - ClassDB::bind_method(D_METHOD("get_color"),&CanvasModulate::get_color); + ClassDB::bind_method(D_METHOD("set_color", "color"), &CanvasModulate::set_color); + ClassDB::bind_method(D_METHOD("get_color"), &CanvasModulate::get_color); - ADD_PROPERTY(PropertyInfo(Variant::COLOR,"color"),"set_color","get_color"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color"); } +void CanvasModulate::set_color(const Color &p_color) { -void CanvasModulate::set_color(const Color& p_color){ - - color=p_color; + color = p_color; if (is_inside_tree()) { - VS::get_singleton()->canvas_set_modulate(get_canvas(),color); + VS::get_singleton()->canvas_set_modulate(get_canvas(), color); } } Color CanvasModulate::get_color() const { @@ -86,23 +82,19 @@ String CanvasModulate::get_configuration_warning() const { if (!is_visible_in_tree() || !is_inside_tree()) return String(); - List nodes; - get_tree()->get_nodes_in_group("_canvas_modulate_"+itos(get_canvas().get_id()),&nodes); + List nodes; + get_tree()->get_nodes_in_group("_canvas_modulate_" + itos(get_canvas().get_id()), &nodes); - if (nodes.size()>1) { + if (nodes.size() > 1) { return TTR("Only one visible CanvasModulate is allowed per scene (or set of instanced scenes). The first created one will work, while the rest will be ignored."); } return String(); } -CanvasModulate::CanvasModulate() -{ - color=Color(1,1,1,1); +CanvasModulate::CanvasModulate() { + color = Color(1, 1, 1, 1); } -CanvasModulate::~CanvasModulate() -{ - +CanvasModulate::~CanvasModulate() { } - diff --git a/scene/2d/canvas_modulate.h b/scene/2d/canvas_modulate.h index a0bb27b1c..8e62b5ccb 100644 --- a/scene/2d/canvas_modulate.h +++ b/scene/2d/canvas_modulate.h @@ -33,15 +33,16 @@ class CanvasModulate : public Node2D { - GDCLASS(CanvasModulate,Node2D); + GDCLASS(CanvasModulate, Node2D); Color color; + protected: void _notification(int p_what); static void _bind_methods(); -public: - void set_color(const Color& p_color); +public: + void set_color(const Color &p_color); Color get_color() const; String get_configuration_warning() const; diff --git a/scene/2d/collision_object_2d.cpp b/scene/2d/collision_object_2d.cpp index f9e1cc0bd..1242599d4 100644 --- a/scene/2d/collision_object_2d.cpp +++ b/scene/2d/collision_object_2d.cpp @@ -27,16 +27,16 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "collision_object_2d.h" -#include "servers/physics_2d_server.h" #include "scene/scene_string_names.h" +#include "servers/physics_2d_server.h" void CollisionObject2D::_update_shapes_from_children() { shapes.clear(); - for(int i=0;icall("_add_to_collision_object",this); + Node *n = get_child(i); + n->call("_add_to_collision_object", this); } _update_shapes(); @@ -44,24 +44,24 @@ void CollisionObject2D::_update_shapes_from_children() { void CollisionObject2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { if (area) - Physics2DServer::get_singleton()->area_set_transform(rid,get_global_transform()); + Physics2DServer::get_singleton()->area_set_transform(rid, get_global_transform()); else - Physics2DServer::get_singleton()->body_set_state(rid,Physics2DServer::BODY_STATE_TRANSFORM,get_global_transform()); + Physics2DServer::get_singleton()->body_set_state(rid, Physics2DServer::BODY_STATE_TRANSFORM, get_global_transform()); RID space = get_world_2d()->get_space(); if (area) { - Physics2DServer::get_singleton()->area_set_space(rid,space); + Physics2DServer::get_singleton()->area_set_space(rid, space); } else - Physics2DServer::get_singleton()->body_set_space(rid,space); + Physics2DServer::get_singleton()->body_set_space(rid, space); _update_pickable(); - //get space + //get space } case NOTIFICATION_VISIBILITY_CHANGED: { @@ -71,17 +71,17 @@ void CollisionObject2D::_notification(int p_what) { case NOTIFICATION_TRANSFORM_CHANGED: { if (area) - Physics2DServer::get_singleton()->area_set_transform(rid,get_global_transform()); + Physics2DServer::get_singleton()->area_set_transform(rid, get_global_transform()); else - Physics2DServer::get_singleton()->body_set_state(rid,Physics2DServer::BODY_STATE_TRANSFORM,get_global_transform()); + Physics2DServer::get_singleton()->body_set_state(rid, Physics2DServer::BODY_STATE_TRANSFORM, get_global_transform()); } break; case NOTIFICATION_EXIT_TREE: { if (area) { - Physics2DServer::get_singleton()->area_set_space(rid,RID()); + Physics2DServer::get_singleton()->area_set_space(rid, RID()); } else - Physics2DServer::get_singleton()->body_set_space(rid,RID()); + Physics2DServer::get_singleton()->body_set_space(rid, RID()); } break; } @@ -97,84 +97,80 @@ void CollisionObject2D::_update_shapes() { else Physics2DServer::get_singleton()->body_clear_shapes(rid); - for(int i=0;iarea_add_shape(rid,shapes[i].shape->get_rid(),shapes[i].xform); + Physics2DServer::get_singleton()->area_add_shape(rid, shapes[i].shape->get_rid(), shapes[i].xform); else { - Physics2DServer::get_singleton()->body_add_shape(rid,shapes[i].shape->get_rid(),shapes[i].xform); + Physics2DServer::get_singleton()->body_add_shape(rid, shapes[i].shape->get_rid(), shapes[i].xform); if (shapes[i].trigger) - Physics2DServer::get_singleton()->body_set_shape_as_trigger(rid,i,shapes[i].trigger); + Physics2DServer::get_singleton()->body_set_shape_as_trigger(rid, i, shapes[i].trigger); } } } - -bool CollisionObject2D::_set(const StringName& p_name, const Variant& p_value) { - String name=p_name; +bool CollisionObject2D::_set(const StringName &p_name, const Variant &p_value) { + String name = p_name; if (name.begins_with("shapes/")) { - int idx=name.get_slicec('/',1).to_int(); - String what=name.get_slicec('/',2); - if (what=="shape") { - if (idx>=shapes.size()) + int idx = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); + if (what == "shape") { + if (idx >= shapes.size()) add_shape(RefPtr(p_value)); else - set_shape(idx,RefPtr(p_value)); - } else if (what=="transform") - set_shape_transform(idx,p_value); - else if (what=="trigger") - set_shape_as_trigger(idx,p_value); + set_shape(idx, RefPtr(p_value)); + } else if (what == "transform") + set_shape_transform(idx, p_value); + else if (what == "trigger") + set_shape_as_trigger(idx, p_value); } else return false; return true; - - } -bool CollisionObject2D::_get(const StringName& p_name,Variant &r_ret) const { +bool CollisionObject2D::_get(const StringName &p_name, Variant &r_ret) const { - String name=p_name; + String name = p_name; if (name.begins_with("shapes/")) { - int idx=name.get_slicec('/',1).to_int(); - String what=name.get_slicec('/',2); - if (what=="shape") - r_ret= get_shape(idx); - else if (what=="transform") - r_ret= get_shape_transform(idx); - else if (what=="trigger") - r_ret= is_shape_set_as_trigger(idx); + int idx = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); + if (what == "shape") + r_ret = get_shape(idx); + else if (what == "transform") + r_ret = get_shape_transform(idx); + else if (what == "trigger") + r_ret = is_shape_set_as_trigger(idx); } else return false; return true; } -void CollisionObject2D::_get_property_list( List *p_list) const { +void CollisionObject2D::_get_property_list(List *p_list) const { //p_list->push_back( PropertyInfo(Variant::INT,"shape_count",PROPERTY_HINT_RANGE,"0,256,1",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) ); - for(int i=0;ipush_back( PropertyInfo(Variant::OBJECT,path+"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape2D",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) ); - p_list->push_back( PropertyInfo(Variant::TRANSFORM,path+"transform",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) ); - p_list->push_back( PropertyInfo(Variant::BOOL,path+"trigger",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) ); + for (int i = 0; i < shapes.size(); i++) { + String path = "shapes/" + itos(i) + "/"; + p_list->push_back(PropertyInfo(Variant::OBJECT, path + "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE)); + p_list->push_back(PropertyInfo(Variant::TRANSFORM, path + "transform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE)); + p_list->push_back(PropertyInfo(Variant::BOOL, path + "trigger", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE)); } } - void CollisionObject2D::set_pickable(bool p_enabled) { - if (pickable==p_enabled) + if (pickable == p_enabled) return; - pickable=p_enabled; + pickable = p_enabled; _update_pickable(); } @@ -183,12 +179,12 @@ bool CollisionObject2D::is_pickable() const { return pickable; } -void CollisionObject2D::_input_event(Node *p_viewport, const InputEvent& p_input_event, int p_shape) { +void CollisionObject2D::_input_event(Node *p_viewport, const InputEvent &p_input_event, int p_shape) { if (get_script_instance()) { - get_script_instance()->call(SceneStringNames::get_singleton()->_input_event,p_viewport,p_input_event,p_shape); + get_script_instance()->call(SceneStringNames::get_singleton()->_input_event, p_viewport, p_input_event, p_shape); } - emit_signal(SceneStringNames::get_singleton()->input_event,p_viewport,p_input_event,p_shape); + emit_signal(SceneStringNames::get_singleton()->input_event, p_viewport, p_input_event, p_shape); } void CollisionObject2D::_mouse_enter() { @@ -199,14 +195,12 @@ void CollisionObject2D::_mouse_enter() { emit_signal(SceneStringNames::get_singleton()->mouse_entered); } - void CollisionObject2D::_mouse_exit() { if (get_script_instance()) { get_script_instance()->call(SceneStringNames::get_singleton()->_mouse_exit); } emit_signal(SceneStringNames::get_singleton()->mouse_exited); - } void CollisionObject2D::_update_pickable() { @@ -214,105 +208,99 @@ void CollisionObject2D::_update_pickable() { return; bool pickable = this->pickable && is_inside_tree() && is_visible_in_tree(); if (area) - Physics2DServer::get_singleton()->area_set_pickable(rid,pickable); + Physics2DServer::get_singleton()->area_set_pickable(rid, pickable); else - Physics2DServer::get_singleton()->body_set_pickable(rid,pickable); + Physics2DServer::get_singleton()->body_set_pickable(rid, pickable); } void CollisionObject2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_shape","shape:Shape2D","transform"),&CollisionObject2D::add_shape,DEFVAL(Transform2D())); - ClassDB::bind_method(D_METHOD("get_shape_count"),&CollisionObject2D::get_shape_count); - ClassDB::bind_method(D_METHOD("set_shape","shape_idx","shape:Shape"),&CollisionObject2D::set_shape); - ClassDB::bind_method(D_METHOD("set_shape_transform","shape_idx","transform"),&CollisionObject2D::set_shape_transform); - ClassDB::bind_method(D_METHOD("set_shape_as_trigger","shape_idx","enable"),&CollisionObject2D::set_shape_as_trigger); - ClassDB::bind_method(D_METHOD("get_shape:Shape2D","shape_idx"),&CollisionObject2D::get_shape); - ClassDB::bind_method(D_METHOD("get_shape_transform","shape_idx"),&CollisionObject2D::get_shape_transform); - ClassDB::bind_method(D_METHOD("is_shape_set_as_trigger","shape_idx"),&CollisionObject2D::is_shape_set_as_trigger); - ClassDB::bind_method(D_METHOD("remove_shape","shape_idx"),&CollisionObject2D::remove_shape); - ClassDB::bind_method(D_METHOD("clear_shapes"),&CollisionObject2D::clear_shapes); - ClassDB::bind_method(D_METHOD("get_rid"),&CollisionObject2D::get_rid); - - ClassDB::bind_method(D_METHOD("set_pickable","enabled"),&CollisionObject2D::set_pickable); - ClassDB::bind_method(D_METHOD("is_pickable"),&CollisionObject2D::is_pickable); - - BIND_VMETHOD( MethodInfo("_input_event",PropertyInfo(Variant::OBJECT,"viewport"),PropertyInfo(Variant::INPUT_EVENT,"event"),PropertyInfo(Variant::INT,"shape_idx"))); - - ADD_SIGNAL( MethodInfo("input_event",PropertyInfo(Variant::OBJECT,"viewport"),PropertyInfo(Variant::INPUT_EVENT,"event"),PropertyInfo(Variant::INT,"shape_idx"))); - ADD_SIGNAL( MethodInfo("mouse_entered")); - ADD_SIGNAL( MethodInfo("mouse_exited")); - - ADD_GROUP("Pickable","input_"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"input_pickable"),"set_pickable","is_pickable"); - ADD_GROUP("",""); - + ClassDB::bind_method(D_METHOD("add_shape", "shape:Shape2D", "transform"), &CollisionObject2D::add_shape, DEFVAL(Transform2D())); + ClassDB::bind_method(D_METHOD("get_shape_count"), &CollisionObject2D::get_shape_count); + ClassDB::bind_method(D_METHOD("set_shape", "shape_idx", "shape:Shape"), &CollisionObject2D::set_shape); + ClassDB::bind_method(D_METHOD("set_shape_transform", "shape_idx", "transform"), &CollisionObject2D::set_shape_transform); + ClassDB::bind_method(D_METHOD("set_shape_as_trigger", "shape_idx", "enable"), &CollisionObject2D::set_shape_as_trigger); + ClassDB::bind_method(D_METHOD("get_shape:Shape2D", "shape_idx"), &CollisionObject2D::get_shape); + ClassDB::bind_method(D_METHOD("get_shape_transform", "shape_idx"), &CollisionObject2D::get_shape_transform); + ClassDB::bind_method(D_METHOD("is_shape_set_as_trigger", "shape_idx"), &CollisionObject2D::is_shape_set_as_trigger); + ClassDB::bind_method(D_METHOD("remove_shape", "shape_idx"), &CollisionObject2D::remove_shape); + ClassDB::bind_method(D_METHOD("clear_shapes"), &CollisionObject2D::clear_shapes); + ClassDB::bind_method(D_METHOD("get_rid"), &CollisionObject2D::get_rid); + + ClassDB::bind_method(D_METHOD("set_pickable", "enabled"), &CollisionObject2D::set_pickable); + ClassDB::bind_method(D_METHOD("is_pickable"), &CollisionObject2D::is_pickable); + + BIND_VMETHOD(MethodInfo("_input_event", PropertyInfo(Variant::OBJECT, "viewport"), PropertyInfo(Variant::INPUT_EVENT, "event"), PropertyInfo(Variant::INT, "shape_idx"))); + + ADD_SIGNAL(MethodInfo("input_event", PropertyInfo(Variant::OBJECT, "viewport"), PropertyInfo(Variant::INPUT_EVENT, "event"), PropertyInfo(Variant::INT, "shape_idx"))); + ADD_SIGNAL(MethodInfo("mouse_entered")); + ADD_SIGNAL(MethodInfo("mouse_exited")); + + ADD_GROUP("Pickable", "input_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_pickable"), "set_pickable", "is_pickable"); + ADD_GROUP("", ""); } - -void CollisionObject2D::add_shape(const Ref& p_shape, const Transform2D& p_transform) { +void CollisionObject2D::add_shape(const Ref &p_shape, const Transform2D &p_transform) { ERR_FAIL_COND(p_shape.is_null()); ShapeData sdata; - sdata.shape=p_shape; - sdata.xform=p_transform; - sdata.trigger=false; + sdata.shape = p_shape; + sdata.xform = p_transform; + sdata.trigger = false; if (area) - Physics2DServer::get_singleton()->area_add_shape(get_rid(),p_shape->get_rid(),p_transform); + Physics2DServer::get_singleton()->area_add_shape(get_rid(), p_shape->get_rid(), p_transform); else - Physics2DServer::get_singleton()->body_add_shape(get_rid(),p_shape->get_rid(),p_transform); + Physics2DServer::get_singleton()->body_add_shape(get_rid(), p_shape->get_rid(), p_transform); shapes.push_back(sdata); - } int CollisionObject2D::get_shape_count() const { return shapes.size(); - } -void CollisionObject2D::set_shape(int p_shape_idx, const Ref& p_shape) { +void CollisionObject2D::set_shape(int p_shape_idx, const Ref &p_shape) { - ERR_FAIL_INDEX(p_shape_idx,shapes.size()); + ERR_FAIL_INDEX(p_shape_idx, shapes.size()); ERR_FAIL_COND(p_shape.is_null()); - shapes[p_shape_idx].shape=p_shape; + shapes[p_shape_idx].shape = p_shape; if (area) - Physics2DServer::get_singleton()->area_set_shape(get_rid(),p_shape_idx,p_shape->get_rid()); + Physics2DServer::get_singleton()->area_set_shape(get_rid(), p_shape_idx, p_shape->get_rid()); else - Physics2DServer::get_singleton()->body_set_shape(get_rid(),p_shape_idx,p_shape->get_rid()); + Physics2DServer::get_singleton()->body_set_shape(get_rid(), p_shape_idx, p_shape->get_rid()); //_update_shapes(); } -void CollisionObject2D::set_shape_transform(int p_shape_idx, const Transform2D& p_transform) { +void CollisionObject2D::set_shape_transform(int p_shape_idx, const Transform2D &p_transform) { - ERR_FAIL_INDEX(p_shape_idx,shapes.size()); - shapes[p_shape_idx].xform=p_transform; + ERR_FAIL_INDEX(p_shape_idx, shapes.size()); + shapes[p_shape_idx].xform = p_transform; if (area) - Physics2DServer::get_singleton()->area_set_shape_transform(get_rid(),p_shape_idx,p_transform); + Physics2DServer::get_singleton()->area_set_shape_transform(get_rid(), p_shape_idx, p_transform); else - Physics2DServer::get_singleton()->body_set_shape_transform(get_rid(),p_shape_idx,p_transform); + Physics2DServer::get_singleton()->body_set_shape_transform(get_rid(), p_shape_idx, p_transform); //_update_shapes(); } Ref CollisionObject2D::get_shape(int p_shape_idx) const { - ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),Ref()); + ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), Ref()); return shapes[p_shape_idx].shape; - } Transform2D CollisionObject2D::get_shape_transform(int p_shape_idx) const { - ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),Transform2D()); + ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), Transform2D()); return shapes[p_shape_idx].xform; - } void CollisionObject2D::remove_shape(int p_shape_idx) { - ERR_FAIL_INDEX(p_shape_idx,shapes.size()); + ERR_FAIL_INDEX(p_shape_idx, shapes.size()); shapes.remove(p_shape_idx); _update_shapes(); @@ -320,18 +308,17 @@ void CollisionObject2D::remove_shape(int p_shape_idx) { void CollisionObject2D::set_shape_as_trigger(int p_shape_idx, bool p_trigger) { - ERR_FAIL_INDEX(p_shape_idx,shapes.size()); - shapes[p_shape_idx].trigger=p_trigger; + ERR_FAIL_INDEX(p_shape_idx, shapes.size()); + shapes[p_shape_idx].trigger = p_trigger; if (!area && rid.is_valid()) { - Physics2DServer::get_singleton()->body_set_shape_as_trigger(rid,p_shape_idx,p_trigger); - + Physics2DServer::get_singleton()->body_set_shape_as_trigger(rid, p_shape_idx, p_trigger); } } bool CollisionObject2D::is_shape_set_as_trigger(int p_shape_idx) const { - ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),false); + ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), false); return shapes[p_shape_idx].trigger; } @@ -342,32 +329,25 @@ void CollisionObject2D::clear_shapes() { _update_shapes(); } - CollisionObject2D::CollisionObject2D(RID p_rid, bool p_area) { - rid=p_rid; - area=p_area; - pickable=true; + rid = p_rid; + area = p_area; + pickable = true; set_notify_transform(true); if (p_area) { - Physics2DServer::get_singleton()->area_attach_object_instance_ID(rid,get_instance_ID()); + Physics2DServer::get_singleton()->area_attach_object_instance_ID(rid, get_instance_ID()); } else { - Physics2DServer::get_singleton()->body_attach_object_instance_ID(rid,get_instance_ID()); + Physics2DServer::get_singleton()->body_attach_object_instance_ID(rid, get_instance_ID()); } - - } - CollisionObject2D::CollisionObject2D() { - //owner= set_notify_transform(true); - - } CollisionObject2D::~CollisionObject2D() { diff --git a/scene/2d/collision_object_2d.h b/scene/2d/collision_object_2d.h index 429b4fafe..e6ea0f42d 100644 --- a/scene/2d/collision_object_2d.h +++ b/scene/2d/collision_object_2d.h @@ -34,7 +34,7 @@ class CollisionObject2D : public Node2D { - GDCLASS( CollisionObject2D, Node2D ); + GDCLASS(CollisionObject2D, Node2D); bool area; RID rid; @@ -46,42 +46,38 @@ class CollisionObject2D : public Node2D { bool trigger; ShapeData() { - trigger=false; + trigger = false; } }; - Vector shapes; void _update_shapes(); -friend class CollisionShape2D; -friend class CollisionPolygon2D; + friend class CollisionShape2D; + friend class CollisionPolygon2D; void _update_shapes_from_children(); -protected: +protected: CollisionObject2D(RID p_rid, bool p_area); void _notification(int p_what); - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; static void _bind_methods(); void _update_pickable(); -friend class Viewport; - void _input_event(Node *p_viewport, const InputEvent& p_input_event, int p_shape); + friend class Viewport; + void _input_event(Node *p_viewport, const InputEvent &p_input_event, int p_shape); void _mouse_enter(); void _mouse_exit(); public: - - - - void add_shape(const Ref& p_shape, const Transform2D& p_transform=Transform2D()); + void add_shape(const Ref &p_shape, const Transform2D &p_transform = Transform2D()); int get_shape_count() const; - void set_shape(int p_shape_idx, const Ref& p_shape); - void set_shape_transform(int p_shape_idx, const Transform2D& p_transform); + void set_shape(int p_shape_idx, const Ref &p_shape); + void set_shape_transform(int p_shape_idx, const Transform2D &p_transform); Ref get_shape(int p_shape_idx) const; Transform2D get_shape_transform(int p_shape_idx) const; void set_shape_as_trigger(int p_shape_idx, bool p_trigger); diff --git a/scene/2d/collision_polygon_2d.cpp b/scene/2d/collision_polygon_2d.cpp index 85241a79e..abc044f10 100644 --- a/scene/2d/collision_polygon_2d.cpp +++ b/scene/2d/collision_polygon_2d.cpp @@ -39,57 +39,54 @@ void CollisionPolygon2D::_add_to_collision_object(Object *p_obj) { CollisionObject2D *co = p_obj->cast_to(); ERR_FAIL_COND(!co); - if (polygon.size()==0) + if (polygon.size() == 0) return; - bool solids=build_mode==BUILD_SOLIDS; + bool solids = build_mode == BUILD_SOLIDS; if (solids) { //here comes the sun, lalalala //decompose concave into multiple convex polygons and add them - Vector< Vector > decomp = _decompose_in_convex(); - shape_from=co->get_shape_count(); - for(int i=0;i convex = memnew( ConvexPolygonShape2D ); + Vector > decomp = _decompose_in_convex(); + shape_from = co->get_shape_count(); + for (int i = 0; i < decomp.size(); i++) { + Ref convex = memnew(ConvexPolygonShape2D); convex->set_points(decomp[i]); - co->add_shape(convex,get_transform()); + co->add_shape(convex, get_transform()); if (trigger) - co->set_shape_as_trigger(co->get_shape_count()-1,true); - + co->set_shape_as_trigger(co->get_shape_count() - 1, true); } - shape_to=co->get_shape_count()-1; - if (shape_toget_shape_count() - 1; + if (shape_to < shape_from) { + shape_from = -1; + shape_to = -1; } } else { - Ref concave = memnew( ConcavePolygonShape2D ); + Ref concave = memnew(ConcavePolygonShape2D); PoolVector segments; - segments.resize(polygon.size()*2); - PoolVector::Write w=segments.write(); + segments.resize(polygon.size() * 2); + PoolVector::Write w = segments.write(); - for(int i=0;i::Write(); + w = PoolVector::Write(); concave->set_segments(segments); - co->add_shape(concave,get_transform()); + co->add_shape(concave, get_transform()); if (trigger) - co->set_shape_as_trigger(co->get_shape_count()-1,true); - - shape_from=co->get_shape_count()-1; - shape_to=co->get_shape_count()-1; + co->set_shape_as_trigger(co->get_shape_count() - 1, true); + shape_from = co->get_shape_count() - 1; + shape_to = co->get_shape_count() - 1; } - //co->add_shape(shape,get_transform()); } @@ -106,41 +103,41 @@ void CollisionPolygon2D::_update_parent() { co->_update_shapes_from_children(); } -Vector< Vector > CollisionPolygon2D::_decompose_in_convex() { +Vector > CollisionPolygon2D::_decompose_in_convex() { - Vector< Vector > decomp; + Vector > decomp; #if 0 //fast but imprecise triangulator, gave us problems decomp = Geometry::decompose_polygon(polygon); #else - List in_poly,out_poly; + List in_poly, out_poly; TriangulatorPoly inp; inp.Init(polygon.size()); - for(int i=0;i::Element*I = out_poly.front();I;I=I->next()) { + for (List::Element *I = out_poly.front(); I; I = I->next()) { - TriangulatorPoly& tp = I->get(); + TriangulatorPoly &tp = I->get(); decomp[idx].resize(tp.GetNumPoints()); - for(int i=0;i > CollisionPolygon2D::_decompose_in_convex() { void CollisionPolygon2D::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - unparenting=false; - can_update_body=get_tree()->is_editor_hint(); + unparenting = false; + can_update_body = get_tree()->is_editor_hint(); if (!get_tree()->is_editor_hint()) { //display above all else set_z_as_relative(false); - set_z(VS::CANVAS_ITEM_Z_MAX-1); + set_z(VS::CANVAS_ITEM_Z_MAX - 1); } } break; case NOTIFICATION_EXIT_TREE: { - can_update_body=false; + can_update_body = false; } break; case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: { @@ -174,14 +170,13 @@ void CollisionPolygon2D::_notification(int p_what) { break; if (can_update_body) { _update_parent(); - } else if (shape_from>=0 && shape_to>=0) { + } else if (shape_from >= 0 && shape_to >= 0) { CollisionObject2D *co = get_parent()->cast_to(); - for(int i=shape_from;i<=shape_to;i++) { - co->set_shape_transform(i,get_transform()); + for (int i = shape_from; i <= shape_to; i++) { + co->set_shape_transform(i, get_transform()); } } - } break; case NOTIFICATION_DRAW: { @@ -190,55 +185,52 @@ void CollisionPolygon2D::_notification(int p_what) { break; } - - for(int i=0;i > decomp = _decompose_in_convex(); + Vector > decomp = _decompose_in_convex(); - Color c(0.4,0.9,0.1); - for(int i=0;iget_debug_collisions_color()); + draw_colored_polygon(polygon, get_tree()->get_debug_collisions_color()); #endif - } break; case NOTIFICATION_UNPARENTED: { unparenting = true; _update_parent(); } break; - } } -void CollisionPolygon2D::set_polygon(const Vector& p_polygon) { +void CollisionPolygon2D::set_polygon(const Vector &p_polygon) { - polygon=p_polygon; + polygon = p_polygon; if (can_update_body) { - for(int i=0;i CollisionPolygon2D::get_polygon() const { void CollisionPolygon2D::set_build_mode(BuildMode p_mode) { - ERR_FAIL_INDEX(p_mode,2); - build_mode=p_mode; + ERR_FAIL_INDEX(p_mode, 2); + build_mode = p_mode; _update_parent(); } -CollisionPolygon2D::BuildMode CollisionPolygon2D::get_build_mode() const{ +CollisionPolygon2D::BuildMode CollisionPolygon2D::get_build_mode() const { return build_mode; } @@ -270,32 +262,30 @@ Rect2 CollisionPolygon2D::get_item_rect() const { void CollisionPolygon2D::set_trigger(bool p_trigger) { - trigger=p_trigger; + trigger = p_trigger; _update_parent(); - if (!can_update_body && is_inside_tree() && shape_from>=0 && shape_to>=0) { + if (!can_update_body && is_inside_tree() && shape_from >= 0 && shape_to >= 0) { CollisionObject2D *co = get_parent()->cast_to(); - for(int i=shape_from;i<=shape_to;i++) { - co->set_shape_as_trigger(i,p_trigger); + for (int i = shape_from; i <= shape_to; i++) { + co->set_shape_as_trigger(i, p_trigger); } - } } -bool CollisionPolygon2D::is_trigger() const{ +bool CollisionPolygon2D::is_trigger() const { return trigger; } +void CollisionPolygon2D::_set_shape_range(const Vector2 &p_range) { -void CollisionPolygon2D::_set_shape_range(const Vector2& p_range) { - - shape_from=p_range.x; - shape_to=p_range.y; + shape_from = p_range.x; + shape_to = p_range.y; } Vector2 CollisionPolygon2D::_get_shape_range() const { - return Vector2(shape_from,shape_to); + return Vector2(shape_from, shape_to); } String CollisionPolygon2D::get_configuration_warning() const { @@ -306,7 +296,6 @@ String CollisionPolygon2D::get_configuration_warning() const { if (polygon.empty()) { return TTR("An empty CollisionPolygon2D has no effect on collision."); - } return String(); @@ -314,38 +303,36 @@ String CollisionPolygon2D::get_configuration_warning() const { void CollisionPolygon2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("_add_to_collision_object"),&CollisionPolygon2D::_add_to_collision_object); - ClassDB::bind_method(D_METHOD("set_polygon","polygon"),&CollisionPolygon2D::set_polygon); - ClassDB::bind_method(D_METHOD("get_polygon"),&CollisionPolygon2D::get_polygon); - - ClassDB::bind_method(D_METHOD("set_build_mode","build_mode"),&CollisionPolygon2D::set_build_mode); - ClassDB::bind_method(D_METHOD("get_build_mode"),&CollisionPolygon2D::get_build_mode); + ClassDB::bind_method(D_METHOD("_add_to_collision_object"), &CollisionPolygon2D::_add_to_collision_object); + ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &CollisionPolygon2D::set_polygon); + ClassDB::bind_method(D_METHOD("get_polygon"), &CollisionPolygon2D::get_polygon); - ClassDB::bind_method(D_METHOD("set_trigger","trigger"),&CollisionPolygon2D::set_trigger); - ClassDB::bind_method(D_METHOD("is_trigger"),&CollisionPolygon2D::is_trigger); + ClassDB::bind_method(D_METHOD("set_build_mode", "build_mode"), &CollisionPolygon2D::set_build_mode); + ClassDB::bind_method(D_METHOD("get_build_mode"), &CollisionPolygon2D::get_build_mode); - ClassDB::bind_method(D_METHOD("_set_shape_range","shape_range"),&CollisionPolygon2D::_set_shape_range); - ClassDB::bind_method(D_METHOD("_get_shape_range"),&CollisionPolygon2D::_get_shape_range); + ClassDB::bind_method(D_METHOD("set_trigger", "trigger"), &CollisionPolygon2D::set_trigger); + ClassDB::bind_method(D_METHOD("is_trigger"), &CollisionPolygon2D::is_trigger); - ClassDB::bind_method(D_METHOD("get_collision_object_first_shape"),&CollisionPolygon2D::get_collision_object_first_shape); - ClassDB::bind_method(D_METHOD("get_collision_object_last_shape"),&CollisionPolygon2D::get_collision_object_last_shape); + ClassDB::bind_method(D_METHOD("_set_shape_range", "shape_range"), &CollisionPolygon2D::_set_shape_range); + ClassDB::bind_method(D_METHOD("_get_shape_range"), &CollisionPolygon2D::_get_shape_range); - ADD_PROPERTY( PropertyInfo(Variant::INT,"build_mode",PROPERTY_HINT_ENUM,"Solids,Segments"),"set_build_mode","get_build_mode"); - ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"polygon"),"set_polygon","get_polygon"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"shape_range",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_shape_range","_get_shape_range"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"trigger"),"set_trigger","is_trigger"); + ClassDB::bind_method(D_METHOD("get_collision_object_first_shape"), &CollisionPolygon2D::get_collision_object_first_shape); + ClassDB::bind_method(D_METHOD("get_collision_object_last_shape"), &CollisionPolygon2D::get_collision_object_last_shape); + ADD_PROPERTY(PropertyInfo(Variant::INT, "build_mode", PROPERTY_HINT_ENUM, "Solids,Segments"), "set_build_mode", "get_build_mode"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "shape_range", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_shape_range", "_get_shape_range"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "trigger"), "set_trigger", "is_trigger"); } CollisionPolygon2D::CollisionPolygon2D() { - aabb=Rect2(-10,-10,20,20); - build_mode=BUILD_SOLIDS; - trigger=false; - unparenting=false; - shape_from=-1; - shape_to=-1; - can_update_body=false; + aabb = Rect2(-10, -10, 20, 20); + build_mode = BUILD_SOLIDS; + trigger = false; + unparenting = false; + shape_from = -1; + shape_to = -1; + can_update_body = false; set_notify_local_transform(true); - } diff --git a/scene/2d/collision_polygon_2d.h b/scene/2d/collision_polygon_2d.h index dda850b41..f1f31a285 100644 --- a/scene/2d/collision_polygon_2d.h +++ b/scene/2d/collision_polygon_2d.h @@ -32,21 +32,17 @@ #include "scene/2d/node_2d.h" #include "scene/resources/shape_2d.h" - - class CollisionPolygon2D : public Node2D { - GDCLASS(CollisionPolygon2D,Node2D); -public: + GDCLASS(CollisionPolygon2D, Node2D); +public: enum BuildMode { BUILD_SOLIDS, BUILD_SEGMENTS, }; protected: - - Rect2 aabb; BuildMode build_mode; Vector polygon; @@ -60,24 +56,23 @@ protected: int shape_from; int shape_to; - void _set_shape_range(const Vector2& p_range); + void _set_shape_range(const Vector2 &p_range); Vector2 _get_shape_range() const; - Vector< Vector > _decompose_in_convex(); + Vector > _decompose_in_convex(); protected: - void _notification(int p_what); static void _bind_methods(); -public: +public: void set_trigger(bool p_trigger); bool is_trigger() const; void set_build_mode(BuildMode p_mode); BuildMode get_build_mode() const; - void set_polygon(const Vector& p_polygon); + void set_polygon(const Vector &p_polygon); Vector get_polygon() const; virtual Rect2 get_item_rect() const; @@ -90,6 +85,6 @@ public: CollisionPolygon2D(); }; -VARIANT_ENUM_CAST( CollisionPolygon2D::BuildMode ); +VARIANT_ENUM_CAST(CollisionPolygon2D::BuildMode); #endif // COLLISION_POLYGON_2D_H diff --git a/scene/2d/collision_shape_2d.cpp b/scene/2d/collision_shape_2d.cpp index 37a49577b..39e0017e9 100644 --- a/scene/2d/collision_shape_2d.cpp +++ b/scene/2d/collision_shape_2d.cpp @@ -28,14 +28,13 @@ /*************************************************************************/ #include "collision_shape_2d.h" #include "collision_object_2d.h" -#include "scene/resources/segment_shape_2d.h" -#include "scene/resources/shape_line_2d.h" -#include "scene/resources/circle_shape_2d.h" -#include "scene/resources/rectangle_shape_2d.h" #include "scene/resources/capsule_shape_2d.h" -#include "scene/resources/convex_polygon_shape_2d.h" +#include "scene/resources/circle_shape_2d.h" #include "scene/resources/concave_polygon_shape_2d.h" - +#include "scene/resources/convex_polygon_shape_2d.h" +#include "scene/resources/rectangle_shape_2d.h" +#include "scene/resources/segment_shape_2d.h" +#include "scene/resources/shape_line_2d.h" void CollisionShape2D::_add_to_collision_object(Object *p_obj) { @@ -44,12 +43,10 @@ void CollisionShape2D::_add_to_collision_object(Object *p_obj) { CollisionObject2D *co = p_obj->cast_to(); ERR_FAIL_COND(!co); - update_shape_index=co->get_shape_count(); - co->add_shape(shape,get_transform()); + update_shape_index = co->get_shape_count(); + co->add_shape(shape, get_transform()); if (trigger) - co->set_shape_as_trigger(co->get_shape_count()-1,true); - - + co->set_shape_as_trigger(co->get_shape_count() - 1, true); } void CollisionShape2D::_shape_changed() { @@ -60,7 +57,6 @@ void CollisionShape2D::_shape_changed() { void CollisionShape2D::_update_parent() { - Node *parent = get_parent(); if (!parent) return; @@ -72,15 +68,15 @@ void CollisionShape2D::_update_parent() { void CollisionShape2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - unparenting=false; - can_update_body=get_tree()->is_editor_hint(); + unparenting = false; + can_update_body = get_tree()->is_editor_hint(); if (!get_tree()->is_editor_hint()) { //display above all else set_z_as_relative(false); - set_z(VS::CANVAS_ITEM_Z_MAX-1); + set_z(VS::CANVAS_ITEM_Z_MAX - 1); } } break; @@ -90,18 +86,17 @@ void CollisionShape2D::_notification(int p_what) { break; if (can_update_body) { _update_parent(); - } else if (update_shape_index>=0){ + } else if (update_shape_index >= 0) { CollisionObject2D *co = get_parent()->cast_to(); if (co) { - co->set_shape_transform(update_shape_index,get_transform()); + co->set_shape_transform(update_shape_index, get_transform()); } - } } break; case NOTIFICATION_EXIT_TREE: { - can_update_body=false; + can_update_body = false; } break; /* @@ -122,16 +117,13 @@ void CollisionShape2D::_notification(int p_what) { break; } - rect=Rect2(); - - - - Color draw_col=get_tree()->get_debug_collisions_color(); - shape->draw(get_canvas_item(),draw_col); + rect = Rect2(); + Color draw_col = get_tree()->get_debug_collisions_color(); + shape->draw(get_canvas_item(), draw_col); - rect=shape->get_rect(); - rect=rect.grow(3); + rect = shape->get_rect(); + rect = rect.grow(3); } break; case NOTIFICATION_UNPARENTED: { @@ -139,25 +131,24 @@ void CollisionShape2D::_notification(int p_what) { _update_parent(); } break; } - } -void CollisionShape2D::set_shape(const Ref& p_shape) { +void CollisionShape2D::set_shape(const Ref &p_shape) { if (shape.is_valid()) - shape->disconnect("changed",this,"_shape_changed"); - shape=p_shape; + shape->disconnect("changed", this, "_shape_changed"); + shape = p_shape; update(); if (is_inside_tree() && can_update_body) _update_parent(); - if (is_inside_tree() && !can_update_body && update_shape_index>=0) { + if (is_inside_tree() && !can_update_body && update_shape_index >= 0) { CollisionObject2D *co = get_parent()->cast_to(); if (co) { - co->set_shape(update_shape_index,p_shape); + co->set_shape(update_shape_index, p_shape); } } if (shape.is_valid()) - shape->connect("changed",this,"_shape_changed"); + shape->connect("changed", this, "_shape_changed"); update_configuration_warning(); } @@ -174,30 +165,28 @@ Rect2 CollisionShape2D::get_item_rect() const { void CollisionShape2D::set_trigger(bool p_trigger) { - trigger=p_trigger; + trigger = p_trigger; if (can_update_body) { _update_parent(); - } else if (is_inside_tree() && update_shape_index>=0){ + } else if (is_inside_tree() && update_shape_index >= 0) { CollisionObject2D *co = get_parent()->cast_to(); if (co) { - co->set_shape_as_trigger(update_shape_index,p_trigger); + co->set_shape_as_trigger(update_shape_index, p_trigger); } } } -bool CollisionShape2D::is_trigger() const{ +bool CollisionShape2D::is_trigger() const { return trigger; } - void CollisionShape2D::_set_update_shape_index(int p_index) { - - update_shape_index=p_index; + update_shape_index = p_index; } -int CollisionShape2D::_get_update_shape_index() const{ +int CollisionShape2D::_get_update_shape_index() const { return update_shape_index; } @@ -215,33 +204,31 @@ String CollisionShape2D::get_configuration_warning() const { return String(); } - void CollisionShape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_shape","shape"),&CollisionShape2D::set_shape); - ClassDB::bind_method(D_METHOD("get_shape"),&CollisionShape2D::get_shape); - ClassDB::bind_method(D_METHOD("_shape_changed"),&CollisionShape2D::_shape_changed); - ClassDB::bind_method(D_METHOD("_add_to_collision_object"),&CollisionShape2D::_add_to_collision_object); - ClassDB::bind_method(D_METHOD("set_trigger","enable"),&CollisionShape2D::set_trigger); - ClassDB::bind_method(D_METHOD("is_trigger"),&CollisionShape2D::is_trigger); - - ClassDB::bind_method(D_METHOD("_set_update_shape_index","index"),&CollisionShape2D::_set_update_shape_index); - ClassDB::bind_method(D_METHOD("_get_update_shape_index"),&CollisionShape2D::_get_update_shape_index); + ClassDB::bind_method(D_METHOD("set_shape", "shape"), &CollisionShape2D::set_shape); + ClassDB::bind_method(D_METHOD("get_shape"), &CollisionShape2D::get_shape); + ClassDB::bind_method(D_METHOD("_shape_changed"), &CollisionShape2D::_shape_changed); + ClassDB::bind_method(D_METHOD("_add_to_collision_object"), &CollisionShape2D::_add_to_collision_object); + ClassDB::bind_method(D_METHOD("set_trigger", "enable"), &CollisionShape2D::set_trigger); + ClassDB::bind_method(D_METHOD("is_trigger"), &CollisionShape2D::is_trigger); - ClassDB::bind_method(D_METHOD("get_collision_object_shape_index"),&CollisionShape2D::get_collision_object_shape_index); + ClassDB::bind_method(D_METHOD("_set_update_shape_index", "index"), &CollisionShape2D::_set_update_shape_index); + ClassDB::bind_method(D_METHOD("_get_update_shape_index"), &CollisionShape2D::_get_update_shape_index); - ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape2D"),"set_shape","get_shape"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"trigger"),"set_trigger","is_trigger"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "_update_shape_index", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR), "_set_update_shape_index", "_get_update_shape_index"); + ClassDB::bind_method(D_METHOD("get_collision_object_shape_index"), &CollisionShape2D::get_collision_object_shape_index); + ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D"), "set_shape", "get_shape"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "trigger"), "set_trigger", "is_trigger"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "_update_shape_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_update_shape_index", "_get_update_shape_index"); } CollisionShape2D::CollisionShape2D() { - rect=Rect2(-Point2(10,10),Point2(20,20)); + rect = Rect2(-Point2(10, 10), Point2(20, 20)); set_notify_local_transform(true); - trigger=false; + trigger = false; unparenting = false; can_update_body = false; - update_shape_index=-1; + update_shape_index = -1; } diff --git a/scene/2d/collision_shape_2d.h b/scene/2d/collision_shape_2d.h index b5cc78941..a3395cdc1 100644 --- a/scene/2d/collision_shape_2d.h +++ b/scene/2d/collision_shape_2d.h @@ -34,7 +34,7 @@ class CollisionShape2D : public Node2D { - GDCLASS(CollisionShape2D,Node2D); + GDCLASS(CollisionShape2D, Node2D); Ref shape; Rect2 rect; bool trigger; @@ -47,15 +47,14 @@ class CollisionShape2D : public Node2D { int _get_update_shape_index() const; protected: - void _update_parent(); void _notification(int p_what); static void _bind_methods(); void _add_to_collision_object(Object *p_obj); -public: - void set_shape(const Ref& p_shape); +public: + void set_shape(const Ref &p_shape); Ref get_shape() const; virtual Rect2 get_item_rect() const; void set_trigger(bool p_trigger); diff --git a/scene/2d/joints_2d.cpp b/scene/2d/joints_2d.cpp index 6754eb398..96ef714f1 100644 --- a/scene/2d/joints_2d.cpp +++ b/scene/2d/joints_2d.cpp @@ -27,8 +27,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "joints_2d.h" -#include "servers/physics_2d_server.h" #include "physics_body_2d.h" +#include "servers/physics_2d_server.h" void Joint2D::_update_joint() { @@ -39,49 +39,41 @@ void Joint2D::_update_joint() { Physics2DServer::get_singleton()->free(joint); } - joint=RID(); - + joint = RID(); joint = _configure_joint(); - Physics2DServer::get_singleton()->get_singleton()->joint_set_param(joint,Physics2DServer::JOINT_PARAM_BIAS,bias); - - + Physics2DServer::get_singleton()->get_singleton()->joint_set_param(joint, Physics2DServer::JOINT_PARAM_BIAS, bias); } +void Joint2D::set_node_a(const NodePath &p_node_a) { -void Joint2D::set_node_a(const NodePath& p_node_a) { - - - if (a==p_node_a) + if (a == p_node_a) return; - a=p_node_a; + a = p_node_a; _update_joint(); } -NodePath Joint2D::get_node_a() const{ +NodePath Joint2D::get_node_a() const { return a; } -void Joint2D::set_node_b(const NodePath& p_node_b){ +void Joint2D::set_node_b(const NodePath &p_node_b) { - if (b==p_node_b) + if (b == p_node_b) return; - b=p_node_b; + b = p_node_b; _update_joint(); - } -NodePath Joint2D::get_node_b() const{ - +NodePath Joint2D::get_node_b() const { return b; } - void Joint2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_READY: { _update_joint(); @@ -90,70 +82,61 @@ void Joint2D::_notification(int p_what) { if (joint.is_valid()) { Physics2DServer::get_singleton()->free(joint); - joint=RID(); + joint = RID(); } } break; - } - } void Joint2D::set_bias(real_t p_bias) { - bias=p_bias; + bias = p_bias; if (joint.is_valid()) - Physics2DServer::get_singleton()->get_singleton()->joint_set_param(joint,Physics2DServer::JOINT_PARAM_BIAS,bias); + Physics2DServer::get_singleton()->get_singleton()->joint_set_param(joint, Physics2DServer::JOINT_PARAM_BIAS, bias); } -real_t Joint2D::get_bias() const{ - +real_t Joint2D::get_bias() const { return bias; } void Joint2D::set_exclude_nodes_from_collision(bool p_enable) { - if (exclude_from_collision==p_enable) + if (exclude_from_collision == p_enable) return; - exclude_from_collision=p_enable; + exclude_from_collision = p_enable; _update_joint(); } -bool Joint2D::get_exclude_nodes_from_collision() const{ +bool Joint2D::get_exclude_nodes_from_collision() const { return exclude_from_collision; } - void Joint2D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_node_a", "node"), &Joint2D::set_node_a); + ClassDB::bind_method(D_METHOD("get_node_a"), &Joint2D::get_node_a); - ClassDB::bind_method( D_METHOD("set_node_a","node"), &Joint2D::set_node_a ); - ClassDB::bind_method( D_METHOD("get_node_a"), &Joint2D::get_node_a ); - - ClassDB::bind_method( D_METHOD("set_node_b","node"), &Joint2D::set_node_b ); - ClassDB::bind_method( D_METHOD("get_node_b"), &Joint2D::get_node_b ); + ClassDB::bind_method(D_METHOD("set_node_b", "node"), &Joint2D::set_node_b); + ClassDB::bind_method(D_METHOD("get_node_b"), &Joint2D::get_node_b); - ClassDB::bind_method( D_METHOD("set_bias","bias"), &Joint2D::set_bias ); - ClassDB::bind_method( D_METHOD("get_bias"), &Joint2D::get_bias ); - - ClassDB::bind_method( D_METHOD("set_exclude_nodes_from_collision","enable"), &Joint2D::set_exclude_nodes_from_collision ); - ClassDB::bind_method( D_METHOD("get_exclude_nodes_from_collision"), &Joint2D::get_exclude_nodes_from_collision ); - - ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "node_a"), "set_node_a","get_node_a") ; - ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "node_b"), "set_node_b","get_node_b") ; - ADD_PROPERTY( PropertyInfo( Variant::REAL, "bias",PROPERTY_HINT_RANGE,"0,0.9,0.001"), "set_bias","get_bias") ; - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "disable_collision"), "set_exclude_nodes_from_collision","get_exclude_nodes_from_collision") ; + ClassDB::bind_method(D_METHOD("set_bias", "bias"), &Joint2D::set_bias); + ClassDB::bind_method(D_METHOD("get_bias"), &Joint2D::get_bias); + ClassDB::bind_method(D_METHOD("set_exclude_nodes_from_collision", "enable"), &Joint2D::set_exclude_nodes_from_collision); + ClassDB::bind_method(D_METHOD("get_exclude_nodes_from_collision"), &Joint2D::get_exclude_nodes_from_collision); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_a"), "set_node_a", "get_node_a"); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_b"), "set_node_b", "get_node_b"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_RANGE, "0,0.9,0.001"), "set_bias", "get_bias"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "disable_collision"), "set_exclude_nodes_from_collision", "get_exclude_nodes_from_collision"); } - - Joint2D::Joint2D() { - bias=0; - exclude_from_collision=true; + bias = 0; + exclude_from_collision = true; } /////////////////////////////////////////////////////////////////////////////// @@ -162,7 +145,7 @@ Joint2D::Joint2D() { void PinJoint2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_DRAW: { if (!is_inside_tree()) @@ -172,50 +155,46 @@ void PinJoint2D::_notification(int p_what) { break; } - - draw_line(Point2(-10,0),Point2(+10,0),Color(0.7,0.6,0.0,0.5),3); - draw_line(Point2(0,-10),Point2(0,+10),Color(0.7,0.6,0.0,0.5),3); + draw_line(Point2(-10, 0), Point2(+10, 0), Color(0.7, 0.6, 0.0, 0.5), 3); + draw_line(Point2(0, -10), Point2(0, +10), Color(0.7, 0.6, 0.0, 0.5), 3); } break; } - } RID PinJoint2D::_configure_joint() { - Node *node_a = has_node( get_node_a() ) ? get_node( get_node_a() ) : (Node*)NULL; - Node *node_b = has_node( get_node_b() ) ? get_node( get_node_b() ) : (Node*)NULL; + Node *node_a = has_node(get_node_a()) ? get_node(get_node_a()) : (Node *)NULL; + Node *node_b = has_node(get_node_b()) ? get_node(get_node_b()) : (Node *)NULL; if (!node_a && !node_b) return RID(); - PhysicsBody2D *body_a=node_a ? node_a->cast_to() : (PhysicsBody2D*)NULL; - PhysicsBody2D *body_b=node_b ? node_b->cast_to() : (PhysicsBody2D*)NULL; + PhysicsBody2D *body_a = node_a ? node_a->cast_to() : (PhysicsBody2D *)NULL; + PhysicsBody2D *body_b = node_b ? node_b->cast_to() : (PhysicsBody2D *)NULL; if (!body_a && !body_b) return RID(); if (!body_a) { - SWAP(body_a,body_b); + SWAP(body_a, body_b); } else if (body_b) { //add a collision exception between both if (get_exclude_nodes_from_collision()) - Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid()); + Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid()); else - Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(),body_b->get_rid()); + Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(), body_b->get_rid()); } - RID pj = Physics2DServer::get_singleton()->pin_joint_create(get_global_transform().get_origin(),body_a->get_rid(),body_b?body_b->get_rid():RID()); + RID pj = Physics2DServer::get_singleton()->pin_joint_create(get_global_transform().get_origin(), body_a->get_rid(), body_b ? body_b->get_rid() : RID()); Physics2DServer::get_singleton()->pin_joint_set_param(pj, Physics2DServer::PIN_JOINT_SOFTNESS, softness); return pj; - } void PinJoint2D::set_softness(real_t p_softness) { - softness=p_softness; + softness = p_softness; update(); if (get_joint().is_valid()) Physics2DServer::get_singleton()->pin_joint_set_param(get_joint(), Physics2DServer::PIN_JOINT_SOFTNESS, p_softness); - } real_t PinJoint2D::get_softness() const { @@ -225,10 +204,10 @@ real_t PinJoint2D::get_softness() const { void PinJoint2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_softness","softness"), &PinJoint2D::set_softness); + ClassDB::bind_method(D_METHOD("set_softness", "softness"), &PinJoint2D::set_softness); ClassDB::bind_method(D_METHOD("get_softness"), &PinJoint2D::get_softness); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "softness", PROPERTY_HINT_EXP_RANGE,"0.00,16,0.01"), "set_softness", "get_softness"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "softness", PROPERTY_HINT_EXP_RANGE, "0.00,16,0.01"), "set_softness", "get_softness"); } PinJoint2D::PinJoint2D() { @@ -236,16 +215,13 @@ PinJoint2D::PinJoint2D() { softness = 0; } - - /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// - void GrooveJoint2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_DRAW: { if (!is_inside_tree()) break; @@ -254,48 +230,44 @@ void GrooveJoint2D::_notification(int p_what) { break; } - draw_line(Point2(-10,0),Point2(+10,0),Color(0.7,0.6,0.0,0.5),3); - draw_line(Point2(-10,length),Point2(+10,length),Color(0.7,0.6,0.0,0.5),3); - draw_line(Point2(0,0),Point2(0,length),Color(0.7,0.6,0.0,0.5),3); - draw_line(Point2(-10,initial_offset),Point2(+10,initial_offset),Color(0.8,0.8,0.9,0.5),5); + draw_line(Point2(-10, 0), Point2(+10, 0), Color(0.7, 0.6, 0.0, 0.5), 3); + draw_line(Point2(-10, length), Point2(+10, length), Color(0.7, 0.6, 0.0, 0.5), 3); + draw_line(Point2(0, 0), Point2(0, length), Color(0.7, 0.6, 0.0, 0.5), 3); + draw_line(Point2(-10, initial_offset), Point2(+10, initial_offset), Color(0.8, 0.8, 0.9, 0.5), 5); } break; } } -RID GrooveJoint2D::_configure_joint(){ +RID GrooveJoint2D::_configure_joint() { - - Node *node_a = has_node( get_node_a() ) ? get_node( get_node_a() ) : (Node*)NULL; - Node *node_b = has_node( get_node_b() ) ? get_node( get_node_b() ) : (Node*)NULL; + Node *node_a = has_node(get_node_a()) ? get_node(get_node_a()) : (Node *)NULL; + Node *node_b = has_node(get_node_b()) ? get_node(get_node_b()) : (Node *)NULL; if (!node_a || !node_b) return RID(); - PhysicsBody2D *body_a=node_a->cast_to(); - PhysicsBody2D *body_b=node_b->cast_to(); + PhysicsBody2D *body_a = node_a->cast_to(); + PhysicsBody2D *body_b = node_b->cast_to(); if (!body_a || !body_b) return RID(); - if (get_exclude_nodes_from_collision()) - Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid()); + Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid()); else - Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(),body_b->get_rid()); + Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(), body_b->get_rid()); Transform2D gt = get_global_transform(); Vector2 groove_A1 = gt.get_origin(); - Vector2 groove_A2 = gt.xform( Vector2(0,length) ); - Vector2 anchor_B = gt.xform( Vector2(0,initial_offset) ); - + Vector2 groove_A2 = gt.xform(Vector2(0, length)); + Vector2 anchor_B = gt.xform(Vector2(0, initial_offset)); - return Physics2DServer::get_singleton()->groove_joint_create(groove_A1,groove_A2,anchor_B,body_a->get_rid(),body_b->get_rid()); + return Physics2DServer::get_singleton()->groove_joint_create(groove_A1, groove_A2, anchor_B, body_a->get_rid(), body_b->get_rid()); } - void GrooveJoint2D::set_length(real_t p_length) { - length=p_length; + length = p_length; update(); } @@ -304,10 +276,9 @@ real_t GrooveJoint2D::get_length() const { return length; } - void GrooveJoint2D::set_initial_offset(real_t p_initial_offset) { - initial_offset=p_initial_offset; + initial_offset = p_initial_offset; update(); } @@ -316,38 +287,30 @@ real_t GrooveJoint2D::get_initial_offset() const { return initial_offset; } - - void GrooveJoint2D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_length", "length"), &GrooveJoint2D::set_length); + ClassDB::bind_method(D_METHOD("get_length"), &GrooveJoint2D::get_length); + ClassDB::bind_method(D_METHOD("set_initial_offset", "offset"), &GrooveJoint2D::set_initial_offset); + ClassDB::bind_method(D_METHOD("get_initial_offset"), &GrooveJoint2D::get_initial_offset); - ClassDB::bind_method(D_METHOD("set_length","length"),&GrooveJoint2D::set_length); - ClassDB::bind_method(D_METHOD("get_length"),&GrooveJoint2D::get_length); - ClassDB::bind_method(D_METHOD("set_initial_offset","offset"),&GrooveJoint2D::set_initial_offset); - ClassDB::bind_method(D_METHOD("get_initial_offset"),&GrooveJoint2D::get_initial_offset); - - ADD_PROPERTY( PropertyInfo( Variant::REAL, "length", PROPERTY_HINT_EXP_RANGE,"1,65535,1"), "set_length","get_length"); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "initial_offset", PROPERTY_HINT_EXP_RANGE,"1,65535,1"), "set_initial_offset","get_initial_offset"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "length", PROPERTY_HINT_EXP_RANGE, "1,65535,1"), "set_length", "get_length"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "initial_offset", PROPERTY_HINT_EXP_RANGE, "1,65535,1"), "set_initial_offset", "get_initial_offset"); } GrooveJoint2D::GrooveJoint2D() { - length=50; - initial_offset=25; + length = 50; + initial_offset = 25; } - - - /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// - - void DampedSpringJoint2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_DRAW: { if (!is_inside_tree()) @@ -357,50 +320,48 @@ void DampedSpringJoint2D::_notification(int p_what) { break; } - draw_line(Point2(-10,0),Point2(+10,0),Color(0.7,0.6,0.0,0.5),3); - draw_line(Point2(-10,length),Point2(+10,length),Color(0.7,0.6,0.0,0.5),3); - draw_line(Point2(0,0),Point2(0,length),Color(0.7,0.6,0.0,0.5),3); + draw_line(Point2(-10, 0), Point2(+10, 0), Color(0.7, 0.6, 0.0, 0.5), 3); + draw_line(Point2(-10, length), Point2(+10, length), Color(0.7, 0.6, 0.0, 0.5), 3); + draw_line(Point2(0, 0), Point2(0, length), Color(0.7, 0.6, 0.0, 0.5), 3); } break; } } -RID DampedSpringJoint2D::_configure_joint(){ - +RID DampedSpringJoint2D::_configure_joint() { - Node *node_a = has_node( get_node_a() ) ? get_node( get_node_a() ) : (Node*)NULL; - Node *node_b = has_node( get_node_b() ) ? get_node( get_node_b() ) : (Node*)NULL; + Node *node_a = has_node(get_node_a()) ? get_node(get_node_a()) : (Node *)NULL; + Node *node_b = has_node(get_node_b()) ? get_node(get_node_b()) : (Node *)NULL; if (!node_a || !node_b) return RID(); - PhysicsBody2D *body_a=node_a->cast_to(); - PhysicsBody2D *body_b=node_b->cast_to(); + PhysicsBody2D *body_a = node_a->cast_to(); + PhysicsBody2D *body_b = node_b->cast_to(); if (!body_a || !body_b) return RID(); if (get_exclude_nodes_from_collision()) - Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid()); + Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid()); else - Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(),body_b->get_rid()); + Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(), body_b->get_rid()); Transform2D gt = get_global_transform(); Vector2 anchor_A = gt.get_origin(); - Vector2 anchor_B = gt.xform( Vector2(0,length) ); + Vector2 anchor_B = gt.xform(Vector2(0, length)); - RID dsj = Physics2DServer::get_singleton()->damped_spring_joint_create(anchor_A,anchor_B,body_a->get_rid(),body_b->get_rid()); + RID dsj = Physics2DServer::get_singleton()->damped_spring_joint_create(anchor_A, anchor_B, body_a->get_rid(), body_b->get_rid()); if (rest_length) - Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj,Physics2DServer::DAMPED_STRING_REST_LENGTH,rest_length); - Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj,Physics2DServer::DAMPED_STRING_STIFFNESS,stiffness); - Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj,Physics2DServer::DAMPED_STRING_DAMPING,damping); + Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj, Physics2DServer::DAMPED_STRING_REST_LENGTH, rest_length); + Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj, Physics2DServer::DAMPED_STRING_STIFFNESS, stiffness); + Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj, Physics2DServer::DAMPED_STRING_DAMPING, damping); return dsj; } - void DampedSpringJoint2D::set_length(real_t p_length) { - length=p_length; + length = p_length; update(); } @@ -411,11 +372,10 @@ real_t DampedSpringJoint2D::get_length() const { void DampedSpringJoint2D::set_rest_length(real_t p_rest_length) { - rest_length=p_rest_length; + rest_length = p_rest_length; update(); if (get_joint().is_valid()) - Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(),Physics2DServer::DAMPED_STRING_REST_LENGTH,p_rest_length?p_rest_length:length); - + Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(), Physics2DServer::DAMPED_STRING_REST_LENGTH, p_rest_length ? p_rest_length : length); } real_t DampedSpringJoint2D::get_rest_length() const { @@ -425,10 +385,10 @@ real_t DampedSpringJoint2D::get_rest_length() const { void DampedSpringJoint2D::set_stiffness(real_t p_stiffness) { - stiffness=p_stiffness; + stiffness = p_stiffness; update(); if (get_joint().is_valid()) - Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(),Physics2DServer::DAMPED_STRING_STIFFNESS,p_stiffness); + Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(), Physics2DServer::DAMPED_STRING_STIFFNESS, p_stiffness); } real_t DampedSpringJoint2D::get_stiffness() const { @@ -438,10 +398,10 @@ real_t DampedSpringJoint2D::get_stiffness() const { void DampedSpringJoint2D::set_damping(real_t p_damping) { - damping=p_damping; + damping = p_damping; update(); if (get_joint().is_valid()) - Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(),Physics2DServer::DAMPED_STRING_DAMPING,p_damping); + Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(), Physics2DServer::DAMPED_STRING_DAMPING, p_damping); } real_t DampedSpringJoint2D::get_damping() const { @@ -449,30 +409,27 @@ real_t DampedSpringJoint2D::get_damping() const { return damping; } - void DampedSpringJoint2D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_length", "length"), &DampedSpringJoint2D::set_length); + ClassDB::bind_method(D_METHOD("get_length"), &DampedSpringJoint2D::get_length); + ClassDB::bind_method(D_METHOD("set_rest_length", "rest_length"), &DampedSpringJoint2D::set_rest_length); + ClassDB::bind_method(D_METHOD("get_rest_length"), &DampedSpringJoint2D::get_rest_length); + ClassDB::bind_method(D_METHOD("set_stiffness", "stiffness"), &DampedSpringJoint2D::set_stiffness); + ClassDB::bind_method(D_METHOD("get_stiffness"), &DampedSpringJoint2D::get_stiffness); + ClassDB::bind_method(D_METHOD("set_damping", "damping"), &DampedSpringJoint2D::set_damping); + ClassDB::bind_method(D_METHOD("get_damping"), &DampedSpringJoint2D::get_damping); - ClassDB::bind_method(D_METHOD("set_length","length"),&DampedSpringJoint2D::set_length); - ClassDB::bind_method(D_METHOD("get_length"),&DampedSpringJoint2D::get_length); - ClassDB::bind_method(D_METHOD("set_rest_length","rest_length"),&DampedSpringJoint2D::set_rest_length); - ClassDB::bind_method(D_METHOD("get_rest_length"),&DampedSpringJoint2D::get_rest_length); - ClassDB::bind_method(D_METHOD("set_stiffness","stiffness"),&DampedSpringJoint2D::set_stiffness); - ClassDB::bind_method(D_METHOD("get_stiffness"),&DampedSpringJoint2D::get_stiffness); - ClassDB::bind_method(D_METHOD("set_damping","damping"),&DampedSpringJoint2D::set_damping); - ClassDB::bind_method(D_METHOD("get_damping"),&DampedSpringJoint2D::get_damping); - - ADD_PROPERTY( PropertyInfo( Variant::REAL, "length", PROPERTY_HINT_EXP_RANGE,"1,65535,1"), "set_length","get_length"); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "rest_length", PROPERTY_HINT_EXP_RANGE,"0,65535,1"), "set_rest_length","get_rest_length"); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "stiffness", PROPERTY_HINT_EXP_RANGE,"0.1,64,0.1"), "set_stiffness","get_stiffness"); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "damping", PROPERTY_HINT_EXP_RANGE,"0.01,16,0.01"), "set_damping","get_damping"); - + ADD_PROPERTY(PropertyInfo(Variant::REAL, "length", PROPERTY_HINT_EXP_RANGE, "1,65535,1"), "set_length", "get_length"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "rest_length", PROPERTY_HINT_EXP_RANGE, "0,65535,1"), "set_rest_length", "get_rest_length"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "stiffness", PROPERTY_HINT_EXP_RANGE, "0.1,64,0.1"), "set_stiffness", "get_stiffness"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping", PROPERTY_HINT_EXP_RANGE, "0.01,16,0.01"), "set_damping", "get_damping"); } DampedSpringJoint2D::DampedSpringJoint2D() { - length=50; - rest_length=0; - stiffness=20; - damping=1; + length = 50; + rest_length = 0; + stiffness = 20; + damping = 1; } diff --git a/scene/2d/joints_2d.h b/scene/2d/joints_2d.h index 3b3eec6bd..c17262046 100644 --- a/scene/2d/joints_2d.h +++ b/scene/2d/joints_2d.h @@ -29,12 +29,11 @@ #ifndef JOINTS_2D_H #define JOINTS_2D_H - #include "node_2d.h" class Joint2D : public Node2D { - GDCLASS(Joint2D,Node2D); + GDCLASS(Joint2D, Node2D); RID joint; @@ -44,21 +43,19 @@ class Joint2D : public Node2D { bool exclude_from_collision; - protected: - void _update_joint(); void _notification(int p_what); - virtual RID _configure_joint()=0; + virtual RID _configure_joint() = 0; static void _bind_methods(); -public: - void set_node_a(const NodePath& p_node_a); +public: + void set_node_a(const NodePath &p_node_a); NodePath get_node_a() const; - void set_node_b(const NodePath& p_node_b); + void set_node_b(const NodePath &p_node_b); NodePath get_node_b() const; void set_bias(real_t p_bias); @@ -69,23 +66,20 @@ public: RID get_joint() const { return joint; } Joint2D(); - }; - class PinJoint2D : public Joint2D { - GDCLASS(PinJoint2D,Joint2D); + GDCLASS(PinJoint2D, Joint2D); real_t softness; protected: - void _notification(int p_what); virtual RID _configure_joint(); static void _bind_methods(); -public: +public: void set_softness(real_t p_stiffness); real_t get_softness() const; @@ -94,18 +88,17 @@ public: class GrooveJoint2D : public Joint2D { - GDCLASS(GrooveJoint2D,Joint2D); + GDCLASS(GrooveJoint2D, Joint2D); real_t length; real_t initial_offset; protected: - void _notification(int p_what); virtual RID _configure_joint(); static void _bind_methods(); -public: +public: void set_length(real_t p_length); real_t get_length() const; @@ -117,7 +110,7 @@ public: class DampedSpringJoint2D : public Joint2D { - GDCLASS(DampedSpringJoint2D,Joint2D); + GDCLASS(DampedSpringJoint2D, Joint2D); real_t stiffness; real_t damping; @@ -125,12 +118,11 @@ class DampedSpringJoint2D : public Joint2D { real_t length; protected: - void _notification(int p_what); virtual RID _configure_joint(); static void _bind_methods(); -public: +public: void set_length(real_t p_length); real_t get_length() const; @@ -146,5 +138,4 @@ public: DampedSpringJoint2D(); }; - #endif // JOINTS_2D_H diff --git a/scene/2d/light_2d.cpp b/scene/2d/light_2d.cpp index d7f5a890e..7cf98c8c0 100644 --- a/scene/2d/light_2d.cpp +++ b/scene/2d/light_2d.cpp @@ -29,10 +29,9 @@ #include "light_2d.h" #include "servers/visual_server.h" -void Light2D::edit_set_pivot(const Point2& p_pivot) { +void Light2D::edit_set_pivot(const Point2 &p_pivot) { set_texture_offset(p_pivot); - } Point2 Light2D::edit_get_pivot() const { @@ -47,49 +46,47 @@ bool Light2D::edit_has_pivot() const { Rect2 Light2D::get_item_rect() const { if (texture.is_null()) - return Rect2(0,0,1,1); + return Rect2(0, 0, 1, 1); Size2i s; - s = texture->get_size()*_scale; - Point2i ofs=texture_offset; - ofs-=s/2; + s = texture->get_size() * _scale; + Point2i ofs = texture_offset; + ofs -= s / 2; - if (s==Size2(0,0)) - s=Size2(1,1); + if (s == Size2(0, 0)) + s = Size2(1, 1); - return Rect2(ofs,s); + return Rect2(ofs, s); } - void Light2D::_update_light_visibility() { if (!is_inside_tree()) return; - bool editor_ok=true; + bool editor_ok = true; #ifdef TOOLS_ENABLED if (editor_only) { if (!get_tree()->is_editor_hint()) { - editor_ok=false; + editor_ok = false; } else { - editor_ok = (get_tree()->get_edited_scene_root() && (this==get_tree()->get_edited_scene_root() || get_owner()==get_tree()->get_edited_scene_root())); + editor_ok = (get_tree()->get_edited_scene_root() && (this == get_tree()->get_edited_scene_root() || get_owner() == get_tree()->get_edited_scene_root())); } } #else if (editor_only) { - editor_ok=false; + editor_ok = false; } #endif - VS::get_singleton()->canvas_light_set_enabled(canvas_light,enabled && is_visible_in_tree() && editor_ok); + VS::get_singleton()->canvas_light_set_enabled(canvas_light, enabled && is_visible_in_tree() && editor_ok); } -void Light2D::set_enabled( bool p_enabled) { - +void Light2D::set_enabled(bool p_enabled) { - enabled=p_enabled; + enabled = p_enabled; _update_light_visibility(); } @@ -100,22 +97,22 @@ bool Light2D::is_enabled() const { void Light2D::set_editor_only(bool p_editor_only) { - editor_only=p_editor_only; + editor_only = p_editor_only; _update_light_visibility(); } -bool Light2D::is_editor_only() const{ +bool Light2D::is_editor_only() const { return editor_only; } -void Light2D::set_texture( const Ref& p_texture) { +void Light2D::set_texture(const Ref &p_texture) { - texture=p_texture; + texture = p_texture; if (texture.is_valid()) - VS::get_singleton()->canvas_light_set_texture(canvas_light,texture->get_rid()); + VS::get_singleton()->canvas_light_set_texture(canvas_light, texture->get_rid()); else - VS::get_singleton()->canvas_light_set_texture(canvas_light,RID()); + VS::get_singleton()->canvas_light_set_texture(canvas_light, RID()); update_configuration_warning(); } @@ -125,12 +122,11 @@ Ref Light2D::get_texture() const { return texture; } -void Light2D::set_texture_offset( const Vector2& p_offset) { +void Light2D::set_texture_offset(const Vector2 &p_offset) { - texture_offset=p_offset; - VS::get_singleton()->canvas_light_set_texture_offset(canvas_light,texture_offset); + texture_offset = p_offset; + VS::get_singleton()->canvas_light_set_texture_offset(canvas_light, texture_offset); item_rect_changed(); - } Vector2 Light2D::get_texture_offset() const { @@ -138,108 +134,94 @@ Vector2 Light2D::get_texture_offset() const { return texture_offset; } -void Light2D::set_color( const Color& p_color) { - - color=p_color; - VS::get_singleton()->canvas_light_set_color(canvas_light,color); +void Light2D::set_color(const Color &p_color) { + color = p_color; + VS::get_singleton()->canvas_light_set_color(canvas_light, color); } Color Light2D::get_color() const { return color; } -void Light2D::set_height( float p_height) { - - height=p_height; - VS::get_singleton()->canvas_light_set_height(canvas_light,height); +void Light2D::set_height(float p_height) { + height = p_height; + VS::get_singleton()->canvas_light_set_height(canvas_light, height); } - float Light2D::get_height() const { return height; } -void Light2D::set_energy( float p_energy) { - - energy=p_energy; - VS::get_singleton()->canvas_light_set_energy(canvas_light,energy); +void Light2D::set_energy(float p_energy) { + energy = p_energy; + VS::get_singleton()->canvas_light_set_energy(canvas_light, energy); } - float Light2D::get_energy() const { return energy; } +void Light2D::set_texture_scale(float p_scale) { - -void Light2D::set_texture_scale( float p_scale) { - - _scale=p_scale; - VS::get_singleton()->canvas_light_set_scale(canvas_light,_scale); + _scale = p_scale; + VS::get_singleton()->canvas_light_set_scale(canvas_light, _scale); item_rect_changed(); - } - float Light2D::get_texture_scale() const { return _scale; } -void Light2D::set_z_range_min( int p_min_z) { - - z_min=p_min_z; - VS::get_singleton()->canvas_light_set_z_range(canvas_light,z_min,z_max); +void Light2D::set_z_range_min(int p_min_z) { + z_min = p_min_z; + VS::get_singleton()->canvas_light_set_z_range(canvas_light, z_min, z_max); } int Light2D::get_z_range_min() const { return z_min; } -void Light2D::set_z_range_max( int p_max_z) { - - z_max=p_max_z; - VS::get_singleton()->canvas_light_set_z_range(canvas_light,z_min,z_max); +void Light2D::set_z_range_max(int p_max_z) { + z_max = p_max_z; + VS::get_singleton()->canvas_light_set_z_range(canvas_light, z_min, z_max); } int Light2D::get_z_range_max() const { return z_max; } -void Light2D::set_layer_range_min( int p_min_layer) { - - layer_min=p_min_layer; - VS::get_singleton()->canvas_light_set_layer_range(canvas_light,layer_min,layer_max); +void Light2D::set_layer_range_min(int p_min_layer) { + layer_min = p_min_layer; + VS::get_singleton()->canvas_light_set_layer_range(canvas_light, layer_min, layer_max); } int Light2D::get_layer_range_min() const { return layer_min; } -void Light2D::set_layer_range_max( int p_max_layer) { - - layer_max=p_max_layer; - VS::get_singleton()->canvas_light_set_layer_range(canvas_light,layer_min,layer_max); +void Light2D::set_layer_range_max(int p_max_layer) { + layer_max = p_max_layer; + VS::get_singleton()->canvas_light_set_layer_range(canvas_light, layer_min, layer_max); } int Light2D::get_layer_range_max() const { return layer_max; } -void Light2D::set_item_cull_mask( int p_mask) { - - item_mask=p_mask; - VS::get_singleton()->canvas_light_set_item_cull_mask(canvas_light,item_mask); +void Light2D::set_item_cull_mask(int p_mask) { + item_mask = p_mask; + VS::get_singleton()->canvas_light_set_item_cull_mask(canvas_light, item_mask); } int Light2D::get_item_cull_mask() const { @@ -247,11 +229,10 @@ int Light2D::get_item_cull_mask() const { return item_mask; } -void Light2D::set_item_shadow_cull_mask( int p_mask) { - - item_shadow_mask=p_mask; - VS::get_singleton()->canvas_light_set_item_shadow_cull_mask(canvas_light,item_shadow_mask); +void Light2D::set_item_shadow_cull_mask(int p_mask) { + item_shadow_mask = p_mask; + VS::get_singleton()->canvas_light_set_item_shadow_cull_mask(canvas_light, item_shadow_mask); } int Light2D::get_item_shadow_cull_mask() const { @@ -259,10 +240,10 @@ int Light2D::get_item_shadow_cull_mask() const { return item_shadow_mask; } -void Light2D::set_mode( Mode p_mode ) { +void Light2D::set_mode(Mode p_mode) { - mode=p_mode; - VS::get_singleton()->canvas_light_set_mode(canvas_light,VS::CanvasLightMode(p_mode)); + mode = p_mode; + VS::get_singleton()->canvas_light_set_mode(canvas_light, VS::CanvasLightMode(p_mode)); } Light2D::Mode Light2D::get_mode() const { @@ -270,21 +251,20 @@ Light2D::Mode Light2D::get_mode() const { return mode; } -void Light2D::set_shadow_enabled( bool p_enabled) { - - shadow=p_enabled; - VS::get_singleton()->canvas_light_set_shadow_enabled(canvas_light,shadow); +void Light2D::set_shadow_enabled(bool p_enabled) { + shadow = p_enabled; + VS::get_singleton()->canvas_light_set_shadow_enabled(canvas_light, shadow); } bool Light2D::is_shadow_enabled() const { return shadow; } -void Light2D::set_shadow_buffer_size( int p_size ) { +void Light2D::set_shadow_buffer_size(int p_size) { - shadow_buffer_size=p_size; - VS::get_singleton()->canvas_light_set_shadow_buffer_size(canvas_light,shadow_buffer_size); + shadow_buffer_size = p_size; + VS::get_singleton()->canvas_light_set_shadow_buffer_size(canvas_light, shadow_buffer_size); } int Light2D::get_shadow_buffer_size() const { @@ -292,21 +272,20 @@ int Light2D::get_shadow_buffer_size() const { return shadow_buffer_size; } -void Light2D::set_shadow_gradient_length( float p_multiplier) { +void Light2D::set_shadow_gradient_length(float p_multiplier) { - shadow_gradient_length=p_multiplier; - VS::get_singleton()->canvas_light_set_shadow_gradient_length(canvas_light,p_multiplier); + shadow_gradient_length = p_multiplier; + VS::get_singleton()->canvas_light_set_shadow_gradient_length(canvas_light, p_multiplier); } -float Light2D::get_shadow_gradient_length() const{ +float Light2D::get_shadow_gradient_length() const { return shadow_gradient_length; } - -void Light2D::set_shadow_filter( ShadowFilter p_filter) { - shadow_filter=p_filter; - VS::get_singleton()->canvas_light_set_shadow_filter(canvas_light,VS::CanvasLightShadowFilter(p_filter )); +void Light2D::set_shadow_filter(ShadowFilter p_filter) { + shadow_filter = p_filter; + VS::get_singleton()->canvas_light_set_shadow_filter(canvas_light, VS::CanvasLightShadowFilter(p_filter)); } Light2D::ShadowFilter Light2D::get_shadow_filter() const { @@ -314,42 +293,37 @@ Light2D::ShadowFilter Light2D::get_shadow_filter() const { return shadow_filter; } - - -void Light2D::set_shadow_color( const Color& p_shadow_color) { - shadow_color=p_shadow_color; - VS::get_singleton()->canvas_light_set_shadow_color(canvas_light,shadow_color); +void Light2D::set_shadow_color(const Color &p_shadow_color) { + shadow_color = p_shadow_color; + VS::get_singleton()->canvas_light_set_shadow_color(canvas_light, shadow_color); } Color Light2D::get_shadow_color() const { return shadow_color; } - - void Light2D::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_TREE) { + if (p_what == NOTIFICATION_ENTER_TREE) { - VS::get_singleton()->canvas_light_attach_to_canvas( canvas_light, get_canvas() ); + VS::get_singleton()->canvas_light_attach_to_canvas(canvas_light, get_canvas()); _update_light_visibility(); } - if (p_what==NOTIFICATION_TRANSFORM_CHANGED) { + if (p_what == NOTIFICATION_TRANSFORM_CHANGED) { - VS::get_singleton()->canvas_light_set_transform( canvas_light, get_global_transform()); + VS::get_singleton()->canvas_light_set_transform(canvas_light, get_global_transform()); } - if (p_what==NOTIFICATION_VISIBILITY_CHANGED) { + if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { _update_light_visibility(); } - if (p_what==NOTIFICATION_EXIT_TREE) { + if (p_what == NOTIFICATION_EXIT_TREE) { - VS::get_singleton()->canvas_light_attach_to_canvas( canvas_light, RID() ); + VS::get_singleton()->canvas_light_attach_to_canvas(canvas_light, RID()); _update_light_visibility(); } - } String Light2D::get_configuration_warning() const { @@ -361,126 +335,119 @@ String Light2D::get_configuration_warning() const { return String(); } - void Light2D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &Light2D::set_enabled); + ClassDB::bind_method(D_METHOD("is_enabled"), &Light2D::is_enabled); - ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&Light2D::set_enabled); - ClassDB::bind_method(D_METHOD("is_enabled"),&Light2D::is_enabled); - - ClassDB::bind_method(D_METHOD("set_editor_only","editor_only"), &Light2D::set_editor_only ); - ClassDB::bind_method(D_METHOD("is_editor_only"), &Light2D::is_editor_only ); - - ClassDB::bind_method(D_METHOD("set_texture","texture"),&Light2D::set_texture); - ClassDB::bind_method(D_METHOD("get_texture"),&Light2D::get_texture); - - ClassDB::bind_method(D_METHOD("set_texture_offset","texture_offset"),&Light2D::set_texture_offset); - ClassDB::bind_method(D_METHOD("get_texture_offset"),&Light2D::get_texture_offset); - - ClassDB::bind_method(D_METHOD("set_color","color"),&Light2D::set_color); - ClassDB::bind_method(D_METHOD("get_color"),&Light2D::get_color); - - ClassDB::bind_method(D_METHOD("set_height","height"),&Light2D::set_height); - ClassDB::bind_method(D_METHOD("get_height"),&Light2D::get_height); - - ClassDB::bind_method(D_METHOD("set_energy","energy"),&Light2D::set_energy); - ClassDB::bind_method(D_METHOD("get_energy"),&Light2D::get_energy); + ClassDB::bind_method(D_METHOD("set_editor_only", "editor_only"), &Light2D::set_editor_only); + ClassDB::bind_method(D_METHOD("is_editor_only"), &Light2D::is_editor_only); - ClassDB::bind_method(D_METHOD("set_texture_scale","texture_scale"),&Light2D::set_texture_scale); - ClassDB::bind_method(D_METHOD("get_texture_scale"),&Light2D::get_texture_scale); + ClassDB::bind_method(D_METHOD("set_texture", "texture"), &Light2D::set_texture); + ClassDB::bind_method(D_METHOD("get_texture"), &Light2D::get_texture); + ClassDB::bind_method(D_METHOD("set_texture_offset", "texture_offset"), &Light2D::set_texture_offset); + ClassDB::bind_method(D_METHOD("get_texture_offset"), &Light2D::get_texture_offset); - ClassDB::bind_method(D_METHOD("set_z_range_min","z"),&Light2D::set_z_range_min); - ClassDB::bind_method(D_METHOD("get_z_range_min"),&Light2D::get_z_range_min); + ClassDB::bind_method(D_METHOD("set_color", "color"), &Light2D::set_color); + ClassDB::bind_method(D_METHOD("get_color"), &Light2D::get_color); - ClassDB::bind_method(D_METHOD("set_z_range_max","z"),&Light2D::set_z_range_max); - ClassDB::bind_method(D_METHOD("get_z_range_max"),&Light2D::get_z_range_max); + ClassDB::bind_method(D_METHOD("set_height", "height"), &Light2D::set_height); + ClassDB::bind_method(D_METHOD("get_height"), &Light2D::get_height); - ClassDB::bind_method(D_METHOD("set_layer_range_min","layer"),&Light2D::set_layer_range_min); - ClassDB::bind_method(D_METHOD("get_layer_range_min"),&Light2D::get_layer_range_min); + ClassDB::bind_method(D_METHOD("set_energy", "energy"), &Light2D::set_energy); + ClassDB::bind_method(D_METHOD("get_energy"), &Light2D::get_energy); - ClassDB::bind_method(D_METHOD("set_layer_range_max","layer"),&Light2D::set_layer_range_max); - ClassDB::bind_method(D_METHOD("get_layer_range_max"),&Light2D::get_layer_range_max); + ClassDB::bind_method(D_METHOD("set_texture_scale", "texture_scale"), &Light2D::set_texture_scale); + ClassDB::bind_method(D_METHOD("get_texture_scale"), &Light2D::get_texture_scale); + ClassDB::bind_method(D_METHOD("set_z_range_min", "z"), &Light2D::set_z_range_min); + ClassDB::bind_method(D_METHOD("get_z_range_min"), &Light2D::get_z_range_min); - ClassDB::bind_method(D_METHOD("set_item_cull_mask","item_cull_mask"),&Light2D::set_item_cull_mask); - ClassDB::bind_method(D_METHOD("get_item_cull_mask"),&Light2D::get_item_cull_mask); + ClassDB::bind_method(D_METHOD("set_z_range_max", "z"), &Light2D::set_z_range_max); + ClassDB::bind_method(D_METHOD("get_z_range_max"), &Light2D::get_z_range_max); - ClassDB::bind_method(D_METHOD("set_item_shadow_cull_mask","item_shadow_cull_mask"),&Light2D::set_item_shadow_cull_mask); - ClassDB::bind_method(D_METHOD("get_item_shadow_cull_mask"),&Light2D::get_item_shadow_cull_mask); + ClassDB::bind_method(D_METHOD("set_layer_range_min", "layer"), &Light2D::set_layer_range_min); + ClassDB::bind_method(D_METHOD("get_layer_range_min"), &Light2D::get_layer_range_min); - ClassDB::bind_method(D_METHOD("set_mode","mode"),&Light2D::set_mode); - ClassDB::bind_method(D_METHOD("get_mode"),&Light2D::get_mode); + ClassDB::bind_method(D_METHOD("set_layer_range_max", "layer"), &Light2D::set_layer_range_max); + ClassDB::bind_method(D_METHOD("get_layer_range_max"), &Light2D::get_layer_range_max); - ClassDB::bind_method(D_METHOD("set_shadow_enabled","enabled"),&Light2D::set_shadow_enabled); - ClassDB::bind_method(D_METHOD("is_shadow_enabled"),&Light2D::is_shadow_enabled); + ClassDB::bind_method(D_METHOD("set_item_cull_mask", "item_cull_mask"), &Light2D::set_item_cull_mask); + ClassDB::bind_method(D_METHOD("get_item_cull_mask"), &Light2D::get_item_cull_mask); - ClassDB::bind_method(D_METHOD("set_shadow_buffer_size","size"),&Light2D::set_shadow_buffer_size); - ClassDB::bind_method(D_METHOD("get_shadow_buffer_size"),&Light2D::get_shadow_buffer_size); + ClassDB::bind_method(D_METHOD("set_item_shadow_cull_mask", "item_shadow_cull_mask"), &Light2D::set_item_shadow_cull_mask); + ClassDB::bind_method(D_METHOD("get_item_shadow_cull_mask"), &Light2D::get_item_shadow_cull_mask); - ClassDB::bind_method(D_METHOD("set_shadow_gradient_length","multiplier"),&Light2D::set_shadow_gradient_length); - ClassDB::bind_method(D_METHOD("get_shadow_gradient_length"),&Light2D::get_shadow_gradient_length); + ClassDB::bind_method(D_METHOD("set_mode", "mode"), &Light2D::set_mode); + ClassDB::bind_method(D_METHOD("get_mode"), &Light2D::get_mode); - ClassDB::bind_method(D_METHOD("set_shadow_filter","filter"),&Light2D::set_shadow_filter); - ClassDB::bind_method(D_METHOD("get_shadow_filter"),&Light2D::get_shadow_filter); + ClassDB::bind_method(D_METHOD("set_shadow_enabled", "enabled"), &Light2D::set_shadow_enabled); + ClassDB::bind_method(D_METHOD("is_shadow_enabled"), &Light2D::is_shadow_enabled); - ClassDB::bind_method(D_METHOD("set_shadow_color","shadow_color"),&Light2D::set_shadow_color); - ClassDB::bind_method(D_METHOD("get_shadow_color"),&Light2D::get_shadow_color); + ClassDB::bind_method(D_METHOD("set_shadow_buffer_size", "size"), &Light2D::set_shadow_buffer_size); + ClassDB::bind_method(D_METHOD("get_shadow_buffer_size"), &Light2D::get_shadow_buffer_size); + ClassDB::bind_method(D_METHOD("set_shadow_gradient_length", "multiplier"), &Light2D::set_shadow_gradient_length); + ClassDB::bind_method(D_METHOD("get_shadow_gradient_length"), &Light2D::get_shadow_gradient_length); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL, "editor_only"),"set_editor_only","is_editor_only"); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"offset"),"set_texture_offset","get_texture_offset"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"scale",PROPERTY_HINT_RANGE,"0.01,50,0.01"),"set_texture_scale","get_texture_scale"); - ADD_PROPERTY( PropertyInfo(Variant::COLOR,"color"),"set_color","get_color"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"energy",PROPERTY_HINT_RANGE,"0.01,100,0.01"),"set_energy","get_energy"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Add,Sub,Mix,Mask"),"set_mode","get_mode"); - ADD_GROUP("Range","range_"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"range_height",PROPERTY_HINT_RANGE,"-100,100,0.1"),"set_height","get_height"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"range_z_min",PROPERTY_HINT_RANGE,itos(VS::CANVAS_ITEM_Z_MIN)+","+itos(VS::CANVAS_ITEM_Z_MAX)+",1"),"set_z_range_min","get_z_range_min"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"range_z_max",PROPERTY_HINT_RANGE,itos(VS::CANVAS_ITEM_Z_MIN)+","+itos(VS::CANVAS_ITEM_Z_MAX)+",1"),"set_z_range_max","get_z_range_max"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"range_layer_min",PROPERTY_HINT_RANGE,"-512,512,1"),"set_layer_range_min","get_layer_range_min"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"range_layer_max",PROPERTY_HINT_RANGE,"-512,512,1"),"set_layer_range_max","get_layer_range_max"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"range_item_cull_mask",PROPERTY_HINT_LAYERS_2D_RENDER),"set_item_cull_mask","get_item_cull_mask"); + ClassDB::bind_method(D_METHOD("set_shadow_filter", "filter"), &Light2D::set_shadow_filter); + ClassDB::bind_method(D_METHOD("get_shadow_filter"), &Light2D::get_shadow_filter); - ADD_GROUP("Shadow","shadow_"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"shadow_enabled"),"set_shadow_enabled","is_shadow_enabled"); - ADD_PROPERTY( PropertyInfo(Variant::COLOR,"shadow_color"),"set_shadow_color","get_shadow_color"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"shadow_buffer_size",PROPERTY_HINT_RANGE,"32,16384,1"),"set_shadow_buffer_size","get_shadow_buffer_size"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"shadow_gradient_length",PROPERTY_HINT_RANGE,"1,4096,0.1"),"set_shadow_gradient_length","get_shadow_gradient_length"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"shadow_filter",PROPERTY_HINT_ENUM,"None,PCF3,PCF5,PCF9,PCF13"),"set_shadow_filter","get_shadow_filter"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"shadow_item_cull_mask",PROPERTY_HINT_LAYERS_2D_RENDER),"set_item_shadow_cull_mask","get_item_shadow_cull_mask"); + ClassDB::bind_method(D_METHOD("set_shadow_color", "shadow_color"), &Light2D::set_shadow_color); + ClassDB::bind_method(D_METHOD("get_shadow_color"), &Light2D::get_shadow_color); - BIND_CONSTANT( MODE_ADD ); - BIND_CONSTANT( MODE_SUB ); - BIND_CONSTANT( MODE_MIX ); - BIND_CONSTANT( MODE_MASK ); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editor_only"), "set_editor_only", "is_editor_only"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_texture_offset", "get_texture_offset"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "scale", PROPERTY_HINT_RANGE, "0.01,50,0.01"), "set_texture_scale", "get_texture_scale"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "energy", PROPERTY_HINT_RANGE, "0.01,100,0.01"), "set_energy", "get_energy"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Add,Sub,Mix,Mask"), "set_mode", "get_mode"); + ADD_GROUP("Range", "range_"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "range_height", PROPERTY_HINT_RANGE, "-100,100,0.1"), "set_height", "get_height"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "range_z_min", PROPERTY_HINT_RANGE, itos(VS::CANVAS_ITEM_Z_MIN) + "," + itos(VS::CANVAS_ITEM_Z_MAX) + ",1"), "set_z_range_min", "get_z_range_min"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "range_z_max", PROPERTY_HINT_RANGE, itos(VS::CANVAS_ITEM_Z_MIN) + "," + itos(VS::CANVAS_ITEM_Z_MAX) + ",1"), "set_z_range_max", "get_z_range_max"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "range_layer_min", PROPERTY_HINT_RANGE, "-512,512,1"), "set_layer_range_min", "get_layer_range_min"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "range_layer_max", PROPERTY_HINT_RANGE, "-512,512,1"), "set_layer_range_max", "get_layer_range_max"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "range_item_cull_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_item_cull_mask", "get_item_cull_mask"); + ADD_GROUP("Shadow", "shadow_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shadow_enabled"), "set_shadow_enabled", "is_shadow_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "shadow_color"), "set_shadow_color", "get_shadow_color"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "shadow_buffer_size", PROPERTY_HINT_RANGE, "32,16384,1"), "set_shadow_buffer_size", "get_shadow_buffer_size"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "shadow_gradient_length", PROPERTY_HINT_RANGE, "1,4096,0.1"), "set_shadow_gradient_length", "get_shadow_gradient_length"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "shadow_filter", PROPERTY_HINT_ENUM, "None,PCF3,PCF5,PCF9,PCF13"), "set_shadow_filter", "get_shadow_filter"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "shadow_item_cull_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_item_shadow_cull_mask", "get_item_shadow_cull_mask"); + BIND_CONSTANT(MODE_ADD); + BIND_CONSTANT(MODE_SUB); + BIND_CONSTANT(MODE_MIX); + BIND_CONSTANT(MODE_MASK); } Light2D::Light2D() { - canvas_light=VisualServer::get_singleton()->canvas_light_create(); - enabled=true; - editor_only=false; - shadow=false; - color=Color(1,1,1); - height=0; - _scale=1.0; - z_min=-1024; - z_max=1024; - layer_min=0; - layer_max=0; - item_mask=1; - item_shadow_mask=1; - mode=MODE_ADD; - shadow_buffer_size=2048; - shadow_gradient_length=0; - energy=1.0; - shadow_color=Color(0,0,0,0); - shadow_filter=SHADOW_FILTER_NONE; + canvas_light = VisualServer::get_singleton()->canvas_light_create(); + enabled = true; + editor_only = false; + shadow = false; + color = Color(1, 1, 1); + height = 0; + _scale = 1.0; + z_min = -1024; + z_max = 1024; + layer_min = 0; + layer_max = 0; + item_mask = 1; + item_shadow_mask = 1; + mode = MODE_ADD; + shadow_buffer_size = 2048; + shadow_gradient_length = 0; + energy = 1.0; + shadow_color = Color(0, 0, 0, 0); + shadow_filter = SHADOW_FILTER_NONE; set_notify_transform(true); } diff --git a/scene/2d/light_2d.h b/scene/2d/light_2d.h index 2bdcca5d0..e9f0e069d 100644 --- a/scene/2d/light_2d.h +++ b/scene/2d/light_2d.h @@ -33,7 +33,8 @@ class Light2D : public Node2D { - GDCLASS(Light2D,Node2D); + GDCLASS(Light2D, Node2D); + public: enum Mode { MODE_ADD, @@ -73,80 +74,77 @@ private: Vector2 texture_offset; ShadowFilter shadow_filter; - void _update_light_visibility(); -protected: +protected: void _notification(int p_what); static void _bind_methods(); -public: - - virtual void edit_set_pivot(const Point2& p_pivot); +public: + virtual void edit_set_pivot(const Point2 &p_pivot); virtual Point2 edit_get_pivot() const; virtual bool edit_has_pivot() const; - void set_enabled( bool p_enabled); + void set_enabled(bool p_enabled); bool is_enabled() const; void set_editor_only(bool p_editor_only); bool is_editor_only() const; - void set_texture( const Ref& p_texture); + void set_texture(const Ref &p_texture); Ref get_texture() const; - void set_texture_offset( const Vector2& p_offset); + void set_texture_offset(const Vector2 &p_offset); Vector2 get_texture_offset() const; - void set_color( const Color& p_color); + void set_color(const Color &p_color); Color get_color() const; - void set_height( float p_height); + void set_height(float p_height); float get_height() const; - void set_energy( float p_energy); + void set_energy(float p_energy); float get_energy() const; - void set_texture_scale( float p_scale); + void set_texture_scale(float p_scale); float get_texture_scale() const; - void set_z_range_min( int p_min_z); + void set_z_range_min(int p_min_z); int get_z_range_min() const; - void set_z_range_max( int p_max_z); + void set_z_range_max(int p_max_z); int get_z_range_max() const; - void set_layer_range_min( int p_min_layer); + void set_layer_range_min(int p_min_layer); int get_layer_range_min() const; - void set_layer_range_max( int p_max_layer); + void set_layer_range_max(int p_max_layer); int get_layer_range_max() const; - void set_item_cull_mask( int p_mask); + void set_item_cull_mask(int p_mask); int get_item_cull_mask() const; - void set_item_shadow_cull_mask( int p_mask); + void set_item_shadow_cull_mask(int p_mask); int get_item_shadow_cull_mask() const; - void set_mode( Mode p_mode ); + void set_mode(Mode p_mode); Mode get_mode() const; - void set_shadow_enabled( bool p_enabled); + void set_shadow_enabled(bool p_enabled); bool is_shadow_enabled() const; - void set_shadow_buffer_size( int p_size ); + void set_shadow_buffer_size(int p_size); int get_shadow_buffer_size() const; - void set_shadow_gradient_length( float p_multiplier); + void set_shadow_gradient_length(float p_multiplier); float get_shadow_gradient_length() const; - void set_shadow_filter( ShadowFilter p_filter); + void set_shadow_filter(ShadowFilter p_filter); ShadowFilter get_shadow_filter() const; - void set_shadow_color( const Color& p_shadow_color); + void set_shadow_color(const Color &p_shadow_color); Color get_shadow_color() const; - virtual Rect2 get_item_rect() const; String get_configuration_warning() const; @@ -158,5 +156,4 @@ public: VARIANT_ENUM_CAST(Light2D::Mode); VARIANT_ENUM_CAST(Light2D::ShadowFilter); - #endif // LIGHT_2D_H diff --git a/scene/2d/light_occluder_2d.cpp b/scene/2d/light_occluder_2d.cpp index 6a024fe33..401bbcedb 100644 --- a/scene/2d/light_occluder_2d.cpp +++ b/scene/2d/light_occluder_2d.cpp @@ -28,80 +28,74 @@ /*************************************************************************/ #include "light_occluder_2d.h" +void OccluderPolygon2D::set_polygon(const PoolVector &p_polygon) { -void OccluderPolygon2D::set_polygon(const PoolVector& p_polygon) { - - polygon=p_polygon; - VS::get_singleton()->canvas_occluder_polygon_set_shape(occ_polygon,p_polygon,closed); + polygon = p_polygon; + VS::get_singleton()->canvas_occluder_polygon_set_shape(occ_polygon, p_polygon, closed); emit_changed(); } -PoolVector OccluderPolygon2D::get_polygon() const{ +PoolVector OccluderPolygon2D::get_polygon() const { return polygon; } void OccluderPolygon2D::set_closed(bool p_closed) { - if (closed==p_closed) + if (closed == p_closed) return; - closed=p_closed; + closed = p_closed; if (polygon.size()) - VS::get_singleton()->canvas_occluder_polygon_set_shape(occ_polygon,polygon,closed); + VS::get_singleton()->canvas_occluder_polygon_set_shape(occ_polygon, polygon, closed); emit_changed(); } -bool OccluderPolygon2D::is_closed() const{ +bool OccluderPolygon2D::is_closed() const { return closed; } -void OccluderPolygon2D::set_cull_mode(CullMode p_mode){ +void OccluderPolygon2D::set_cull_mode(CullMode p_mode) { - cull=p_mode; - VS::get_singleton()->canvas_occluder_polygon_set_cull_mode(occ_polygon,VS::CanvasOccluderPolygonCullMode(p_mode)); + cull = p_mode; + VS::get_singleton()->canvas_occluder_polygon_set_cull_mode(occ_polygon, VS::CanvasOccluderPolygonCullMode(p_mode)); } -OccluderPolygon2D::CullMode OccluderPolygon2D::get_cull_mode() const{ +OccluderPolygon2D::CullMode OccluderPolygon2D::get_cull_mode() const { return cull; } - RID OccluderPolygon2D::get_rid() const { return occ_polygon; } - - void OccluderPolygon2D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_closed", "closed"), &OccluderPolygon2D::set_closed); + ClassDB::bind_method(D_METHOD("is_closed"), &OccluderPolygon2D::is_closed); - ClassDB::bind_method(D_METHOD("set_closed","closed"),&OccluderPolygon2D::set_closed); - ClassDB::bind_method(D_METHOD("is_closed"),&OccluderPolygon2D::is_closed); + ClassDB::bind_method(D_METHOD("set_cull_mode", "cull_mode"), &OccluderPolygon2D::set_cull_mode); + ClassDB::bind_method(D_METHOD("get_cull_mode"), &OccluderPolygon2D::get_cull_mode); - ClassDB::bind_method(D_METHOD("set_cull_mode","cull_mode"),&OccluderPolygon2D::set_cull_mode); - ClassDB::bind_method(D_METHOD("get_cull_mode"),&OccluderPolygon2D::get_cull_mode); + ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &OccluderPolygon2D::set_polygon); + ClassDB::bind_method(D_METHOD("get_polygon"), &OccluderPolygon2D::get_polygon); - ClassDB::bind_method(D_METHOD("set_polygon","polygon"),&OccluderPolygon2D::set_polygon); - ClassDB::bind_method(D_METHOD("get_polygon"),&OccluderPolygon2D::get_polygon); - - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"closed"),"set_closed","is_closed"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"cull_mode",PROPERTY_HINT_ENUM,"Disabled,ClockWise,CounterClockWise"),"set_cull_mode","get_cull_mode"); - ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"polygon"),"set_polygon","get_polygon"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "closed"), "set_closed", "is_closed"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "cull_mode", PROPERTY_HINT_ENUM, "Disabled,ClockWise,CounterClockWise"), "set_cull_mode", "get_cull_mode"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon"); BIND_CONSTANT(CULL_DISABLED); BIND_CONSTANT(CULL_CLOCKWISE); BIND_CONSTANT(CULL_COUNTER_CLOCKWISE); } - OccluderPolygon2D::OccluderPolygon2D() { - occ_polygon=VS::get_singleton()->canvas_occluder_polygon_create(); - closed=true; - cull=CULL_DISABLED; + occ_polygon = VS::get_singleton()->canvas_occluder_polygon_create(); + closed = true; + cull = CULL_DISABLED; } OccluderPolygon2D::~OccluderPolygon2D() { @@ -116,26 +110,24 @@ void LightOccluder2D::_poly_changed() { } #endif - void LightOccluder2D::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_CANVAS) { - - VS::get_singleton()->canvas_light_occluder_attach_to_canvas(occluder,get_canvas()); - VS::get_singleton()->canvas_light_occluder_set_transform(occluder,get_global_transform()); - VS::get_singleton()->canvas_light_occluder_set_enabled(occluder,is_visible_in_tree()); + if (p_what == NOTIFICATION_ENTER_CANVAS) { + VS::get_singleton()->canvas_light_occluder_attach_to_canvas(occluder, get_canvas()); + VS::get_singleton()->canvas_light_occluder_set_transform(occluder, get_global_transform()); + VS::get_singleton()->canvas_light_occluder_set_enabled(occluder, is_visible_in_tree()); } - if (p_what==NOTIFICATION_TRANSFORM_CHANGED) { + if (p_what == NOTIFICATION_TRANSFORM_CHANGED) { - VS::get_singleton()->canvas_light_occluder_set_transform(occluder,get_global_transform()); + VS::get_singleton()->canvas_light_occluder_set_transform(occluder, get_global_transform()); } - if (p_what==NOTIFICATION_VISIBILITY_CHANGED) { + if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { - VS::get_singleton()->canvas_light_occluder_set_enabled(occluder,is_visible_in_tree()); + VS::get_singleton()->canvas_light_occluder_set_enabled(occluder, is_visible_in_tree()); } - if (p_what==NOTIFICATION_DRAW) { + if (p_what == NOTIFICATION_DRAW) { if (get_tree()->is_editor_hint()) { @@ -146,15 +138,15 @@ void LightOccluder2D::_notification(int p_what) { if (poly.size()) { if (occluder_polygon->is_closed()) { Vector color; - color.push_back(Color(0,0,0,0.6)); - draw_polygon(Variant(poly),color); + color.push_back(Color(0, 0, 0, 0.6)); + draw_polygon(Variant(poly), color); } else { - int ps=poly.size(); + int ps = poly.size(); PoolVector::Read r = poly.read(); - for(int i=0;icanvas_light_occluder_attach_to_canvas(occluder,RID()); + VS::get_singleton()->canvas_light_occluder_attach_to_canvas(occluder, RID()); } - - } -void LightOccluder2D::set_occluder_polygon(const Ref& p_polygon) { +void LightOccluder2D::set_occluder_polygon(const Ref &p_polygon) { #ifdef DEBUG_ENABLED if (occluder_polygon.is_valid()) - occluder_polygon->disconnect("changed",this,"_poly_changed"); + occluder_polygon->disconnect("changed", this, "_poly_changed"); #endif - occluder_polygon=p_polygon; + occluder_polygon = p_polygon; if (occluder_polygon.is_valid()) - VS::get_singleton()->canvas_light_occluder_set_polygon(occluder,occluder_polygon->get_rid()); + VS::get_singleton()->canvas_light_occluder_set_polygon(occluder, occluder_polygon->get_rid()); else - VS::get_singleton()->canvas_light_occluder_set_polygon(occluder,RID()); + VS::get_singleton()->canvas_light_occluder_set_polygon(occluder, RID()); #ifdef DEBUG_ENABLED if (occluder_polygon.is_valid()) - occluder_polygon->connect("changed",this,"_poly_changed"); + occluder_polygon->connect("changed", this, "_poly_changed"); update(); #endif - } Ref LightOccluder2D::get_occluder_polygon() const { @@ -199,23 +187,22 @@ Ref LightOccluder2D::get_occluder_polygon() const { void LightOccluder2D::set_occluder_light_mask(int p_mask) { - mask=p_mask; - VS::get_singleton()->canvas_light_occluder_set_light_mask(occluder,mask); + mask = p_mask; + VS::get_singleton()->canvas_light_occluder_set_light_mask(occluder, mask); } -int LightOccluder2D::get_occluder_light_mask() const{ +int LightOccluder2D::get_occluder_light_mask() const { return mask; } - String LightOccluder2D::get_configuration_warning() const { if (!occluder_polygon.is_valid()) { return TTR("An occluder polygon must be set (or drawn) for this occluder to take effect."); } - if (occluder_polygon.is_valid() && occluder_polygon->get_polygon().size()==0) { + if (occluder_polygon.is_valid() && occluder_polygon->get_polygon().size() == 0) { return TTR("The occluder polygon for this occluder is empty. Please draw a polygon!"); } @@ -224,24 +211,24 @@ String LightOccluder2D::get_configuration_warning() const { void LightOccluder2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_occluder_polygon","polygon:OccluderPolygon2D"),&LightOccluder2D::set_occluder_polygon); - ClassDB::bind_method(D_METHOD("get_occluder_polygon:OccluderPolygon2D"),&LightOccluder2D::get_occluder_polygon); + ClassDB::bind_method(D_METHOD("set_occluder_polygon", "polygon:OccluderPolygon2D"), &LightOccluder2D::set_occluder_polygon); + ClassDB::bind_method(D_METHOD("get_occluder_polygon:OccluderPolygon2D"), &LightOccluder2D::get_occluder_polygon); - ClassDB::bind_method(D_METHOD("set_occluder_light_mask","mask"),&LightOccluder2D::set_occluder_light_mask); - ClassDB::bind_method(D_METHOD("get_occluder_light_mask"),&LightOccluder2D::get_occluder_light_mask); + ClassDB::bind_method(D_METHOD("set_occluder_light_mask", "mask"), &LightOccluder2D::set_occluder_light_mask); + ClassDB::bind_method(D_METHOD("get_occluder_light_mask"), &LightOccluder2D::get_occluder_light_mask); #ifdef DEBUG_ENABLED - ClassDB::bind_method("_poly_changed",&LightOccluder2D::_poly_changed); + ClassDB::bind_method("_poly_changed", &LightOccluder2D::_poly_changed); #endif - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"occluder",PROPERTY_HINT_RESOURCE_TYPE,"OccluderPolygon2D"),"set_occluder_polygon","get_occluder_polygon"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"light_mask",PROPERTY_HINT_LAYERS_2D_RENDER),"set_occluder_light_mask","get_occluder_light_mask"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "occluder", PROPERTY_HINT_RESOURCE_TYPE, "OccluderPolygon2D"), "set_occluder_polygon", "get_occluder_polygon"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_occluder_light_mask", "get_occluder_light_mask"); } LightOccluder2D::LightOccluder2D() { - occluder=VS::get_singleton()->canvas_light_occluder_create(); - mask=1; + occluder = VS::get_singleton()->canvas_light_occluder_create(); + mask = 1; set_notify_transform(true); } @@ -249,4 +236,3 @@ LightOccluder2D::~LightOccluder2D() { VS::get_singleton()->free(occluder); } - diff --git a/scene/2d/light_occluder_2d.h b/scene/2d/light_occluder_2d.h index 777785cd1..26135334f 100644 --- a/scene/2d/light_occluder_2d.h +++ b/scene/2d/light_occluder_2d.h @@ -33,28 +33,26 @@ class OccluderPolygon2D : public Resource { - GDCLASS(OccluderPolygon2D,Resource); -public: + GDCLASS(OccluderPolygon2D, Resource); +public: enum CullMode { CULL_DISABLED, CULL_CLOCKWISE, CULL_COUNTER_CLOCKWISE }; -private: - +private: RID occ_polygon; PoolVector polygon; bool closed; CullMode cull; protected: - static void _bind_methods(); -public: - void set_polygon(const PoolVector& p_polygon); +public: + void set_polygon(const PoolVector &p_polygon); PoolVector get_polygon() const; void set_closed(bool p_closed); @@ -66,13 +64,12 @@ public: virtual RID get_rid() const; OccluderPolygon2D(); ~OccluderPolygon2D(); - }; VARIANT_ENUM_CAST(OccluderPolygon2D::CullMode); class LightOccluder2D : public Node2D { - GDCLASS(LightOccluder2D,Node2D); + GDCLASS(LightOccluder2D, Node2D); RID occluder; bool enabled; @@ -86,9 +83,9 @@ class LightOccluder2D : public Node2D { protected: void _notification(int p_what); static void _bind_methods(); -public: - void set_occluder_polygon(const Ref& p_polygon); +public: + void set_occluder_polygon(const Ref &p_polygon); Ref get_occluder_polygon() const; void set_occluder_light_mask(int p_mask); diff --git a/scene/2d/line_2d.cpp b/scene/2d/line_2d.cpp index 059711549..cd9b8e8cb 100644 --- a/scene/2d/line_2d.cpp +++ b/scene/2d/line_2d.cpp @@ -30,19 +30,18 @@ #include "core_string_names.h" - // Needed so we can bind functions VARIANT_ENUM_CAST(LineJointMode) VARIANT_ENUM_CAST(LineCapMode) VARIANT_ENUM_CAST(LineTextureMode) - -Line2D::Line2D() : Node2D() { +Line2D::Line2D() + : Node2D() { _joint_mode = LINE_JOINT_SHARP; _begin_cap_mode = LINE_CAP_NONE; _end_cap_mode = LINE_CAP_NONE; _width = 10; - _default_color = Color(0.4,0.5,1); + _default_color = Color(0.4, 0.5, 1); _sharp_limit = 2.f; _round_precision = 8; } @@ -53,7 +52,7 @@ void Line2D::set_points(const PoolVector &p_points) { } void Line2D::set_width(float width) { - if(width < 0.0) + if (width < 0.0) width = 0.0; _width = width; update(); @@ -99,17 +98,17 @@ Color Line2D::get_default_color() const { return _default_color; } -void Line2D::set_gradient(const Ref& gradient) { +void Line2D::set_gradient(const Ref &gradient) { // Cleanup previous connection if any - if(_gradient.is_valid()) { + if (_gradient.is_valid()) { (**_gradient).disconnect(CoreStringNames::get_singleton()->changed, this, "_gradient_changed"); } _gradient = gradient; // Connect to the gradient so the line will update when the ColorRamp is changed - if(_gradient.is_valid()) { + if (_gradient.is_valid()) { (**_gradient).connect(CoreStringNames::get_singleton()->changed, this, "_gradient_changed"); } @@ -120,7 +119,7 @@ Ref Line2D::get_gradient() const { return _gradient; } -void Line2D::set_texture(const Ref& texture) { +void Line2D::set_texture(const Ref &texture) { _texture = texture; update(); } @@ -166,15 +165,15 @@ LineCapMode Line2D::get_end_cap_mode() const { } void Line2D::_notification(int p_what) { - switch(p_what) { - case NOTIFICATION_DRAW: - _draw(); - break; + switch (p_what) { + case NOTIFICATION_DRAW: + _draw(); + break; } } void Line2D::set_sharp_limit(float limit) { - if(limit < 0.f) + if (limit < 0.f) limit = 0.f; _sharp_limit = limit; update(); @@ -185,7 +184,7 @@ float Line2D::get_sharp_limit() const { } void Line2D::set_round_precision(int precision) { - if(precision < 1) + if (precision < 1) precision = 1; _round_precision = precision; update(); @@ -196,16 +195,17 @@ int Line2D::get_round_precision() const { } void Line2D::_draw() { - if(_points.size() <= 1 || _width == 0.f) + if (_points.size() <= 1 || _width == 0.f) return; // TODO Is this really needed? // Copy points for faster access Vector points; points.resize(_points.size()); - int len = points.size(); { + int len = points.size(); + { PoolVector::Read points_read = _points.read(); - for(int i = 0; i < len; ++i) { + for (int i = 0; i < len; ++i) { points[i] = points_read[i]; } } @@ -226,36 +226,36 @@ void Line2D::_draw() { lb.build(); RID texture_rid; - if(_texture.is_valid()) + if (_texture.is_valid()) texture_rid = (**_texture).get_rid(); VS::get_singleton()->canvas_item_add_triangle_array( - get_canvas_item(), - lb.indices, - lb.vertices, - lb.colors, - lb.uvs, - texture_rid); + get_canvas_item(), + lb.indices, + lb.vertices, + lb.colors, + lb.uvs, + texture_rid); // DEBUG // Draw wireframe -// if(lb.indices.size() % 3 == 0) { -// Color col(0,0,0); -// for(int i = 0; i < lb.indices.size(); i += 3) { -// int vi = lb.indices[i]; -// int lbvsize = lb.vertices.size(); -// Vector2 a = lb.vertices[lb.indices[i]]; -// Vector2 b = lb.vertices[lb.indices[i+1]]; -// Vector2 c = lb.vertices[lb.indices[i+2]]; -// draw_line(a, b, col); -// draw_line(b, c, col); -// draw_line(c, a, col); -// } -// for(int i = 0; i < lb.vertices.size(); ++i) { -// Vector2 p = lb.vertices[i]; -// draw_rect(Rect2(p.x-1, p.y-1, 2, 2), Color(0,0,0,0.5)); -// } -// } + // if(lb.indices.size() % 3 == 0) { + // Color col(0,0,0); + // for(int i = 0; i < lb.indices.size(); i += 3) { + // int vi = lb.indices[i]; + // int lbvsize = lb.vertices.size(); + // Vector2 a = lb.vertices[lb.indices[i]]; + // Vector2 b = lb.vertices[lb.indices[i+1]]; + // Vector2 c = lb.vertices[lb.indices[i+2]]; + // draw_line(a, b, col); + // draw_line(b, c, col); + // draw_line(c, a, col); + // } + // for(int i = 0; i < lb.vertices.size(); ++i) { + // Vector2 p = lb.vertices[i]; + // draw_rect(Rect2(p.x-1, p.y-1, 2, 2), Color(0,0,0,0.5)); + // } + // } } void Line2D::_gradient_changed() { @@ -265,10 +265,10 @@ void Line2D::_gradient_changed() { // static void Line2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_points","points"), &Line2D::set_points); + ClassDB::bind_method(D_METHOD("set_points", "points"), &Line2D::set_points); ClassDB::bind_method(D_METHOD("get_points"), &Line2D::get_points); - ClassDB::bind_method(D_METHOD("set_point_pos","i", "pos"), &Line2D::set_point_pos); + ClassDB::bind_method(D_METHOD("set_point_pos", "i", "pos"), &Line2D::set_point_pos); ClassDB::bind_method(D_METHOD("get_point_pos", "i"), &Line2D::get_point_pos); ClassDB::bind_method(D_METHOD("get_point_count"), &Line2D::get_point_count); @@ -276,7 +276,7 @@ void Line2D::_bind_methods() { ClassDB::bind_method(D_METHOD("add_point", "pos"), &Line2D::add_point); ClassDB::bind_method(D_METHOD("remove_point", "i"), &Line2D::remove_point); - ClassDB::bind_method(D_METHOD("set_width","width"), &Line2D::set_width); + ClassDB::bind_method(D_METHOD("set_width", "width"), &Line2D::set_width); ClassDB::bind_method(D_METHOD("get_width"), &Line2D::get_width); ClassDB::bind_method(D_METHOD("set_default_color", "color"), &Line2D::set_default_color); @@ -309,12 +309,12 @@ void Line2D::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "points"), "set_points", "get_points"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "width"), "set_width", "get_width"); ADD_PROPERTY(PropertyInfo(Variant::COLOR, "default_color"), "set_default_color", "get_default_color"); - ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "gradient", PROPERTY_HINT_RESOURCE_TYPE, "ColorRamp"), "set_gradient", "get_gradient"); - ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); - ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "texture_mode", PROPERTY_HINT_ENUM, "None,Tile" ), "set_texture_mode","get_texture_mode"); - ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "joint_mode", PROPERTY_HINT_ENUM, "Sharp,Bevel,Round" ), "set_joint_mode","get_joint_mode"); - ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "begin_cap_mode", PROPERTY_HINT_ENUM, "None,Box,Round" ), "set_begin_cap_mode","get_begin_cap_mode"); - ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "end_cap_mode", PROPERTY_HINT_ENUM, "None,Box,Round" ), "set_end_cap_mode","get_end_cap_mode"); + ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "gradient", PROPERTY_HINT_RESOURCE_TYPE, "ColorRamp"), "set_gradient", "get_gradient"); + ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); + ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "texture_mode", PROPERTY_HINT_ENUM, "None,Tile"), "set_texture_mode", "get_texture_mode"); + ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "joint_mode", PROPERTY_HINT_ENUM, "Sharp,Bevel,Round"), "set_joint_mode", "get_joint_mode"); + ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "begin_cap_mode", PROPERTY_HINT_ENUM, "None,Box,Round"), "set_begin_cap_mode", "get_begin_cap_mode"); + ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "end_cap_mode", PROPERTY_HINT_ENUM, "None,Box,Round"), "set_end_cap_mode", "get_end_cap_mode"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "sharp_limit"), "set_sharp_limit", "get_sharp_limit"); ADD_PROPERTY(PropertyInfo(Variant::INT, "round_precision"), "set_round_precision", "get_round_precision"); @@ -330,7 +330,4 @@ void Line2D::_bind_methods() { BIND_CONSTANT(LINE_TEXTURE_TILE); ClassDB::bind_method(D_METHOD("_gradient_changed"), &Line2D::_gradient_changed); - } - - diff --git a/scene/2d/line_2d.h b/scene/2d/line_2d.h index 5435c7489..2cd71e972 100644 --- a/scene/2d/line_2d.h +++ b/scene/2d/line_2d.h @@ -29,9 +29,8 @@ #ifndef LINE2D_H #define LINE2D_H -#include "node_2d.h" #include "line_builder.h" - +#include "node_2d.h" class Line2D : public Node2D { @@ -40,7 +39,7 @@ class Line2D : public Node2D { public: Line2D(); - void set_points(const PoolVector & p_points); + void set_points(const PoolVector &p_points); PoolVector get_points() const; void set_point_pos(int i, Vector2 pos); @@ -57,10 +56,10 @@ public: void set_default_color(Color color); Color get_default_color() const; - void set_gradient(const Ref& gradient); + void set_gradient(const Ref &gradient); Ref get_gradient() const; - void set_texture(const Ref& texture); + void set_texture(const Ref &texture); Ref get_texture() const; void set_texture_mode(const LineTextureMode mode); @@ -102,7 +101,6 @@ private: LineTextureMode _texture_mode; float _sharp_limit; int _round_precision; - }; #endif // LINE2D_H diff --git a/scene/2d/line_builder.cpp b/scene/2d/line_builder.cpp index 69543f004..0912f6cfe 100644 --- a/scene/2d/line_builder.cpp +++ b/scene/2d/line_builder.cpp @@ -40,19 +40,18 @@ enum SegmentIntersectionResult { static SegmentIntersectionResult segment_intersection( Vector2 a, Vector2 b, Vector2 c, Vector2 d, - Vector2 * out_intersection) -{ + Vector2 *out_intersection) { // http://paulbourke.net/geometry/pointlineplane/ <-- Good stuff Vector2 cd = d - c; Vector2 ab = b - a; - float div = cd.y*ab.x - cd.x*ab.y; + float div = cd.y * ab.x - cd.x * ab.y; - if(Math::abs(div) > 0.001f) { - float ua = (cd.x * (a.y-c.y) - cd.y * (a.x-c.x)) / div; - float ub = (ab.x * (a.y-c.y) - ab.y * (a.x-c.x)) / div; + if (Math::abs(div) > 0.001f) { + float ua = (cd.x * (a.y - c.y) - cd.y * (a.x - c.x)) / div; + float ub = (ab.x * (a.y - c.y) - ab.y * (a.x - c.x)) / div; *out_intersection = a + ua * ab; - if(ua >= 0.f && ua <= 1.f && - ub >= 0.f && ub <= 1.f) + if (ua >= 0.f && ua <= 1.f && + ub >= 0.f && ub <= 1.f) return SEGMENT_INTERSECT; return SEGMENT_NO_INTERSECT; } @@ -62,30 +61,29 @@ static SegmentIntersectionResult segment_intersection( // TODO I'm pretty sure there is an even faster way to swap things template -static inline void swap(T & a, T & b) { +static inline void swap(T &a, T &b) { T tmp = a; a = b; b = tmp; } -static float calculate_total_distance(const Vector & points) { +static float calculate_total_distance(const Vector &points) { float d = 0.f; - for(int i = 1; i < points.size(); ++i) { - d += points[i].distance_to(points[i-1]); + for (int i = 1; i < points.size(); ++i) { + d += points[i].distance_to(points[i - 1]); } return d; } -static inline Vector2 rotate90(const Vector2 & v) { +static inline Vector2 rotate90(const Vector2 &v) { // Note: the 2D referential is X-right, Y-down return Vector2(v.y, -v.x); } -static inline Vector2 interpolate(const Rect2 & r, const Vector2 & v) { +static inline Vector2 interpolate(const Rect2 &r, const Vector2 &v) { return Vector2( - Math::lerp(r.get_pos().x, r.get_pos().x + r.get_size().x, v.x), - Math::lerp(r.get_pos().y, r.get_pos().y + r.get_size().y, v.y) - ); + Math::lerp(r.get_pos().x, r.get_pos().x + r.get_size().x, v.x), + Math::lerp(r.get_pos().y, r.get_pos().y + r.get_size().y, v.y)); } //---------------------------------------------------------------------------- @@ -95,7 +93,7 @@ static inline Vector2 interpolate(const Rect2 & r, const Vector2 & v) { LineBuilder::LineBuilder() { joint_mode = LINE_JOINT_SHARP; width = 10; - default_color = Color(0.4,0.5,1); + default_color = Color(0.4, 0.5, 1); gradient = NULL; sharp_limit = 2.f; round_precision = 8; @@ -107,7 +105,6 @@ LineBuilder::LineBuilder() { _last_index[1] = 0; } - void LineBuilder::clear_output() { vertices.clear(); colors.clear(); @@ -117,13 +114,13 @@ void LineBuilder::clear_output() { void LineBuilder::build() { // Need at least 2 points to draw a line - if(points.size() < 2) { + if (points.size() < 2) { clear_output(); return; } const float hw = width / 2.f; - const float hw_sq = hw*hw; + const float hw_sq = hw * hw; const float sharp_limit_sq = sharp_limit * sharp_limit; const int len = points.size(); @@ -144,9 +141,9 @@ void LineBuilder::build() { float total_distance; _interpolate_color = gradient != NULL; bool distance_required = _interpolate_color || texture_mode == LINE_TEXTURE_TILE; - if(distance_required) + if (distance_required) total_distance = calculate_total_distance(points); - if(_interpolate_color) + if (_interpolate_color) color0 = gradient->get_color(0); else colors.push_back(default_color); @@ -155,7 +152,7 @@ void LineBuilder::build() { float uvx1 = 0.f; // Begin cap - if(begin_cap_mode == LINE_CAP_BOX) { + if (begin_cap_mode == LINE_CAP_BOX) { // Push back first vertices a little bit pos_up0 -= f0 * hw; pos_down0 -= f0 * hw; @@ -163,9 +160,8 @@ void LineBuilder::build() { total_distance += width; current_distance0 += hw; current_distance1 = current_distance0; - } - else if(begin_cap_mode == LINE_CAP_ROUND) { - if(texture_mode == LINE_TEXTURE_TILE) { + } else if (begin_cap_mode == LINE_CAP_ROUND) { + if (texture_mode == LINE_TEXTURE_TILE) { uvx0 = 0.5f; } new_arc(pos0, pos_up0 - pos0, -Math_PI, color0, Rect2(0.f, 0.f, 1.f, 1.f)); @@ -188,10 +184,10 @@ void LineBuilder::build() { // (not the same implementation but visuals help a lot) // For each additional segment - for(int i = 1; i < len-1; ++i) { + for (int i = 1; i < len - 1; ++i) { pos1 = points[i]; - Vector2 pos2 = points[i+1]; + Vector2 pos2 = points[i + 1]; Vector2 f1 = (pos2 - pos1).normalized(); Vector2 u1 = rotate90(f1); @@ -201,11 +197,10 @@ void LineBuilder::build() { const Orientation orientation = (dp > 0.f ? UP : DOWN); Vector2 inner_normal0, inner_normal1; - if(orientation == UP) { + if (orientation == UP) { inner_normal0 = u0 * hw; inner_normal1 = u1 * hw; - } - else { + } else { inner_normal0 = -u0 * hw; inner_normal1 = -u1 * hw; } @@ -225,11 +220,11 @@ void LineBuilder::build() { // Find inner intersection at the joint Vector2 corner_pos_in, corner_pos_out; SegmentIntersectionResult intersection_result = segment_intersection( - pos0 + inner_normal0, pos1 + inner_normal0, - pos1 + inner_normal1, pos2 + inner_normal1, - &corner_pos_in); + pos0 + inner_normal0, pos1 + inner_normal0, + pos1 + inner_normal1, pos2 + inner_normal1, + &corner_pos_in); - if(intersection_result == SEGMENT_INTERSECT) + if (intersection_result == SEGMENT_INTERSECT) // Inner parts of the segments intersect corner_pos_out = 2.f * pos1 - corner_pos_in; else { @@ -239,11 +234,10 @@ void LineBuilder::build() { } Vector2 corner_pos_up, corner_pos_down; - if(orientation == UP) { + if (orientation == UP) { corner_pos_up = corner_pos_in; corner_pos_down = corner_pos_out; - } - else { + } else { corner_pos_up = corner_pos_out; corner_pos_down = corner_pos_in; } @@ -251,30 +245,27 @@ void LineBuilder::build() { LineJointMode current_joint_mode = joint_mode; Vector2 pos_up1, pos_down1; - if(intersection_result == SEGMENT_INTERSECT) { + if (intersection_result == SEGMENT_INTERSECT) { // Fallback on bevel if sharp angle is too high (because it would produce very long miters) - if(current_joint_mode == LINE_JOINT_SHARP && corner_pos_out.distance_squared_to(pos1) / hw_sq > sharp_limit_sq) { + if (current_joint_mode == LINE_JOINT_SHARP && corner_pos_out.distance_squared_to(pos1) / hw_sq > sharp_limit_sq) { current_joint_mode = LINE_JOINT_BEVEL; } - if(current_joint_mode == LINE_JOINT_SHARP) { + if (current_joint_mode == LINE_JOINT_SHARP) { // In this case, we won't create joint geometry, // The previous and next line quads will directly share an edge. pos_up1 = corner_pos_up; pos_down1 = corner_pos_down; - } - else { + } else { // Bevel or round - if(orientation == UP) { + if (orientation == UP) { pos_up1 = corner_pos_up; pos_down1 = pos1 - u0 * hw; - } - else { + } else { pos_up1 = pos1 + u0 * hw; pos_down1 = corner_pos_down; } } - } - else { + } else { // No intersection: fallback pos_up1 = corner_pos_up; pos_down1 = corner_pos_down; @@ -282,13 +273,13 @@ void LineBuilder::build() { // Add current line body quad // Triangles are clockwise - if(distance_required) { + if (distance_required) { current_distance1 += pos0.distance_to(pos1); } - if(_interpolate_color) { + if (_interpolate_color) { color1 = gradient->get_color_at_offset(current_distance1 / total_distance); } - if(texture_mode == LINE_TEXTURE_TILE) { + if (texture_mode == LINE_TEXTURE_TILE) { uvx0 = current_distance0 / width; uvx1 = current_distance1 / width; } @@ -301,30 +292,27 @@ void LineBuilder::build() { f0 = f1; pos0 = pos1; current_distance0 = current_distance1; - if(intersection_result == SEGMENT_INTERSECT) { - if(current_joint_mode == LINE_JOINT_SHARP) { + if (intersection_result == SEGMENT_INTERSECT) { + if (current_joint_mode == LINE_JOINT_SHARP) { pos_up0 = pos_up1; pos_down0 = pos_down1; - } - else { - if(orientation == UP) { + } else { + if (orientation == UP) { pos_up0 = corner_pos_up; pos_down0 = pos1 - u1 * hw; - } - else { + } else { pos_up0 = pos1 + u1 * hw; pos_down0 = corner_pos_down; } } - } - else { + } else { pos_up0 = pos1 + u1 * hw; pos_down0 = pos1 - u1 * hw; } // From this point, bu0 and bd0 concern the next segment // Add joint geometry - if(current_joint_mode != LINE_JOINT_SHARP) { + if (current_joint_mode != LINE_JOINT_SHARP) { // ________________ cbegin // / \ @@ -335,25 +323,23 @@ void LineBuilder::build() { // | | Vector2 cbegin, cend; - if(orientation == UP) { + if (orientation == UP) { cbegin = pos_down1; cend = pos_down0; - } - else { + } else { cbegin = pos_up1; cend = pos_up0; } - if(current_joint_mode == LINE_JOINT_BEVEL) { + if (current_joint_mode == LINE_JOINT_BEVEL) { strip_add_tri(cend, orientation); - } - else if(current_joint_mode == LINE_JOINT_ROUND) { + } else if (current_joint_mode == LINE_JOINT_ROUND) { Vector2 vbegin = cbegin - pos1; Vector2 vend = cend - pos1; strip_add_arc(pos1, vend.angle_to(vbegin), orientation); } - if(intersection_result != SEGMENT_INTERSECT) + if (intersection_result != SEGMENT_INTERSECT) // In this case the joint is too fucked up to be re-used, // start again the strip with fallback points strip_begin(pos_up0, pos_down0, color1, uvx1); @@ -362,34 +348,34 @@ void LineBuilder::build() { // Last (or only) segment - pos1 = points[points.size()-1]; + pos1 = points[points.size() - 1]; Vector2 pos_up1 = pos1 + u0 * hw; Vector2 pos_down1 = pos1 - u0 * hw; // End cap (box) - if(end_cap_mode == LINE_CAP_BOX) { + if (end_cap_mode == LINE_CAP_BOX) { pos_up1 += f0 * hw; pos_down1 += f0 * hw; } - if(distance_required) { + if (distance_required) { current_distance1 += pos0.distance_to(pos1); } - if(_interpolate_color) { - color1 = gradient->get_color(gradient->get_points_count()-1); + if (_interpolate_color) { + color1 = gradient->get_color(gradient->get_points_count() - 1); } - if(texture_mode == LINE_TEXTURE_TILE) { + if (texture_mode == LINE_TEXTURE_TILE) { uvx1 = current_distance1 / width; } strip_add_quad(pos_up1, pos_down1, color1, uvx1); // End cap (round) - if(end_cap_mode == LINE_CAP_ROUND) { + if (end_cap_mode == LINE_CAP_ROUND) { // Note: color is not used in case we don't interpolate... - Color color = _interpolate_color ? gradient->get_color(gradient->get_points_count()-1) : Color(0,0,0); - new_arc(pos1, pos_up1 - pos1, Math_PI, color, Rect2(uvx1-0.5f, 0.f, 1.f, 1.f)); + Color color = _interpolate_color ? gradient->get_color(gradient->get_points_count() - 1) : Color(0, 0, 0); + new_arc(pos1, pos_up1 - pos1, Math_PI, color, Rect2(uvx1 - 0.5f, 0.f, 1.f, 1.f)); } } @@ -399,18 +385,18 @@ void LineBuilder::strip_begin(Vector2 up, Vector2 down, Color color, float uvx) vertices.push_back(up); vertices.push_back(down); - if(_interpolate_color) { + if (_interpolate_color) { colors.push_back(color); colors.push_back(color); } - if(texture_mode != LINE_TEXTURE_NONE) { + if (texture_mode != LINE_TEXTURE_NONE) { uvs.push_back(Vector2(uvx, 0.f)); uvs.push_back(Vector2(uvx, 1.f)); } _last_index[UP] = vi; - _last_index[DOWN] = vi+1; + _last_index[DOWN] = vi + 1; } void LineBuilder::strip_new_quad(Vector2 up, Vector2 down, Color color, float uvx) { @@ -421,14 +407,14 @@ void LineBuilder::strip_new_quad(Vector2 up, Vector2 down, Color color, float uv vertices.push_back(up); vertices.push_back(down); - if(_interpolate_color) { + if (_interpolate_color) { colors.push_back(color); colors.push_back(color); colors.push_back(color); colors.push_back(color); } - if(texture_mode != LINE_TEXTURE_NONE) { + if (texture_mode != LINE_TEXTURE_NONE) { uvs.push_back(uvs[_last_index[UP]]); uvs.push_back(uvs[_last_index[DOWN]]); uvs.push_back(Vector2(uvx, UP)); @@ -436,14 +422,14 @@ void LineBuilder::strip_new_quad(Vector2 up, Vector2 down, Color color, float uv } indices.push_back(vi); - indices.push_back(vi+3); - indices.push_back(vi+1); + indices.push_back(vi + 3); + indices.push_back(vi + 1); indices.push_back(vi); - indices.push_back(vi+2); - indices.push_back(vi+3); + indices.push_back(vi + 2); + indices.push_back(vi + 3); - _last_index[UP] = vi+2; - _last_index[DOWN] = vi+3; + _last_index[UP] = vi + 2; + _last_index[DOWN] = vi + 3; } void LineBuilder::strip_add_quad(Vector2 up, Vector2 down, Color color, float uvx) { @@ -452,25 +438,25 @@ void LineBuilder::strip_add_quad(Vector2 up, Vector2 down, Color color, float uv vertices.push_back(up); vertices.push_back(down); - if(_interpolate_color) { + if (_interpolate_color) { colors.push_back(color); colors.push_back(color); } - if(texture_mode != LINE_TEXTURE_NONE) { + if (texture_mode != LINE_TEXTURE_NONE) { uvs.push_back(Vector2(uvx, 0.f)); uvs.push_back(Vector2(uvx, 1.f)); } indices.push_back(_last_index[UP]); - indices.push_back(vi+1); + indices.push_back(vi + 1); indices.push_back(_last_index[DOWN]); indices.push_back(_last_index[UP]); indices.push_back(vi); - indices.push_back(vi+1); + indices.push_back(vi + 1); _last_index[UP] = vi; - _last_index[DOWN] = vi+1; + _last_index[DOWN] = vi + 1; } void LineBuilder::strip_add_tri(Vector2 up, Orientation orientation) { @@ -478,13 +464,13 @@ void LineBuilder::strip_add_tri(Vector2 up, Orientation orientation) { vertices.push_back(up); - if(_interpolate_color) { - colors.push_back(colors[colors.size()-1]); + if (_interpolate_color) { + colors.push_back(colors[colors.size() - 1]); } Orientation opposite_orientation = orientation == UP ? DOWN : UP; - if(texture_mode != LINE_TEXTURE_NONE) { + if (texture_mode != LINE_TEXTURE_NONE) { // UVs are just one slice of the texture all along // (otherwise we can't share the bottom vertice) uvs.push_back(uvs[_last_index[opposite_orientation]]); @@ -508,15 +494,15 @@ void LineBuilder::strip_add_arc(Vector2 center, float angle_delta, Orientation o float angle_step = Math_PI / static_cast(round_precision); float steps = Math::abs(angle_delta) / angle_step; - if(angle_delta < 0.f) + if (angle_delta < 0.f) angle_step = -angle_step; float t = vbegin.angle_to(Vector2(1, 0)); float end_angle = t + angle_delta; - Vector2 rpos(0,0); + Vector2 rpos(0, 0); // Arc vertices - for(int ti = 0; ti < steps; ++ti, t += angle_step) { + for (int ti = 0; ti < steps; ++ti, t += angle_step) { rpos = center + Vector2(Math::cos(t), Math::sin(t)) * radius; strip_add_tri(rpos, orientation); } @@ -535,34 +521,34 @@ void LineBuilder::new_arc(Vector2 center, Vector2 vbegin, float angle_delta, Col float angle_step = Math_PI / static_cast(round_precision); float steps = Math::abs(angle_delta) / angle_step; - if(angle_delta < 0.f) + if (angle_delta < 0.f) angle_step = -angle_step; float t = vbegin.angle_to(Vector2(1, 0)); float end_angle = t + angle_delta; - Vector2 rpos(0,0); + Vector2 rpos(0, 0); float tt_begin = -Math_PI / 2.f; float tt = tt_begin; // Center vertice int vi = vertices.size(); vertices.push_back(center); - if(_interpolate_color) + if (_interpolate_color) colors.push_back(color); - if(texture_mode != LINE_TEXTURE_NONE) + if (texture_mode != LINE_TEXTURE_NONE) uvs.push_back(interpolate(uv_rect, Vector2(0.5f, 0.5f))); // Arc vertices - for(int ti = 0; ti < steps; ++ti, t += angle_step) { + for (int ti = 0; ti < steps; ++ti, t += angle_step) { Vector2 sc = Vector2(Math::cos(t), Math::sin(t)); rpos = center + sc * radius; vertices.push_back(rpos); - if(_interpolate_color) + if (_interpolate_color) colors.push_back(color); - if(texture_mode != LINE_TEXTURE_NONE) { + if (texture_mode != LINE_TEXTURE_NONE) { Vector2 tsc = Vector2(Math::cos(tt), Math::sin(tt)); - uvs.push_back(interpolate(uv_rect, 0.5f*(tsc+Vector2(1.f,1.f)))); + uvs.push_back(interpolate(uv_rect, 0.5f * (tsc + Vector2(1.f, 1.f)))); tt += angle_step; } } @@ -571,21 +557,19 @@ void LineBuilder::new_arc(Vector2 center, Vector2 vbegin, float angle_delta, Col Vector2 sc = Vector2(Math::cos(end_angle), Math::sin(end_angle)); rpos = center + sc * radius; vertices.push_back(rpos); - if(_interpolate_color) + if (_interpolate_color) colors.push_back(color); - if(texture_mode != LINE_TEXTURE_NONE) { + if (texture_mode != LINE_TEXTURE_NONE) { tt = tt_begin + angle_delta; Vector2 tsc = Vector2(Math::cos(tt), Math::sin(tt)); - uvs.push_back(interpolate(uv_rect, 0.5f*(tsc+Vector2(1.f,1.f)))); + uvs.push_back(interpolate(uv_rect, 0.5f * (tsc + Vector2(1.f, 1.f)))); } // Make up triangles int vi0 = vi; - for(int ti = 0; ti < steps; ++ti) { + for (int ti = 0; ti < steps; ++ti) { indices.push_back(vi0); indices.push_back(++vi); - indices.push_back(vi+1); + indices.push_back(vi + 1); } } - - diff --git a/scene/2d/line_builder.h b/scene/2d/line_builder.h index 3fc9e4bb8..43fd281d9 100644 --- a/scene/2d/line_builder.h +++ b/scene/2d/line_builder.h @@ -29,8 +29,8 @@ #ifndef LINE_BUILDER_H #define LINE_BUILDER_H -#include "math_2d.h" #include "color.h" +#include "math_2d.h" #include "scene/resources/color_ramp.h" enum LineJointMode { @@ -61,7 +61,7 @@ public: LineCapMode end_cap_mode; float width; Color default_color; - ColorRamp* gradient; + ColorRamp *gradient; LineTextureMode texture_mode; float sharp_limit; int round_precision; @@ -97,8 +97,6 @@ private: private: bool _interpolate_color; int _last_index[2]; // Index of last up and down vertices of the strip - }; - #endif // LINE_BUILDER_H diff --git a/scene/2d/navigation2d.cpp b/scene/2d/navigation2d.cpp index 7f48749dc..f0280a2f8 100644 --- a/scene/2d/navigation2d.cpp +++ b/scene/2d/navigation2d.cpp @@ -33,61 +33,59 @@ void Navigation2D::_navpoly_link(int p_id) { ERR_FAIL_COND(!navpoly_map.has(p_id)); - NavMesh &nm=navpoly_map[p_id]; + NavMesh &nm = navpoly_map[p_id]; ERR_FAIL_COND(nm.linked); - PoolVector vertices=nm.navpoly->get_vertices(); + PoolVector vertices = nm.navpoly->get_vertices(); int len = vertices.size(); - if (len==0) + if (len == 0) return; - PoolVector::Read r=vertices.read(); + PoolVector::Read r = vertices.read(); - for(int i=0;iget_polygon_count();i++) { + for (int i = 0; i < nm.navpoly->get_polygon_count(); i++) { //build - List::Element *P=nm.polygons.push_back(Polygon()); - Polygon &p=P->get(); - p.owner=&nm; + List::Element *P = nm.polygons.push_back(Polygon()); + Polygon &p = P->get(); + p.owner = &nm; Vector poly = nm.navpoly->get_polygon(i); - int plen=poly.size(); - const int *indices=poly.ptr(); - bool valid=true; + int plen = poly.size(); + const int *indices = poly.ptr(); + bool valid = true; p.edges.resize(plen); Vector2 center; - float sum=0; + float sum = 0; - for(int j=0;j=len) { - valid=false; + if (idx < 0 || idx >= len) { + valid = false; break; } Polygon::Edge e; - Vector2 ep=nm.xform.xform(r[idx]); - center+=ep; - e.point=_get_point(ep); - p.edges[j]=e; - - int idxn = indices[(j+1)%plen]; - if (idxn<0 || idxn>=len) { - valid=false; + Vector2 ep = nm.xform.xform(r[idx]); + center += ep; + e.point = _get_point(ep); + p.edges[j] = e; + + int idxn = indices[(j + 1) % plen]; + if (idxn < 0 || idxn >= len) { + valid = false; break; } Vector2 epn = nm.xform.xform(r[idxn]); - sum+=(epn.x-ep.x)*(epn.y+ep.y); - - + sum += (epn.x - ep.x) * (epn.y + ep.y); } - p.clockwise=sum>0; + p.clockwise = sum > 0; if (!valid) { nm.polygons.pop_back(); @@ -95,106 +93,103 @@ void Navigation2D::_navpoly_link(int p_id) { continue; } - p.center=center/plen; + p.center = center / plen; //connect - for(int j=0;j::Element *C=connections.find(ek); + Map::Element *C = connections.find(ek); if (!C) { Connection c; - c.A=&p; - c.A_edge=j; - c.B=NULL; - c.B_edge=-1; - connections[ek]=c; + c.A = &p; + c.A_edge = j; + c.B = NULL; + c.B_edge = -1; + connections[ek] = c; } else { - if (C->get().B!=NULL) { + if (C->get().B != NULL) { ConnectionPending pending; - pending.polygon=&p; - pending.edge=j; - p.edges[j].P=C->get().pending.push_back(pending); + pending.polygon = &p; + pending.edge = j; + p.edges[j].P = C->get().pending.push_back(pending); continue; //print_line(String()+_get_vertex(ek.a)+" -> "+_get_vertex(ek.b)); } - C->get().B=&p; - C->get().B_edge=j; - C->get().A->edges[C->get().A_edge].C=&p; - C->get().A->edges[C->get().A_edge].C_edge=j; - p.edges[j].C=C->get().A; - p.edges[j].C_edge=C->get().A_edge; + C->get().B = &p; + C->get().B_edge = j; + C->get().A->edges[C->get().A_edge].C = &p; + C->get().A->edges[C->get().A_edge].C_edge = j; + p.edges[j].C = C->get().A; + p.edges[j].C_edge = C->get().A_edge; //connection successful. } } } - nm.linked=true; - + nm.linked = true; } - void Navigation2D::_navpoly_unlink(int p_id) { ERR_FAIL_COND(!navpoly_map.has(p_id)); - NavMesh &nm=navpoly_map[p_id]; + NavMesh &nm = navpoly_map[p_id]; ERR_FAIL_COND(!nm.linked); //print_line("UNLINK"); - for (List::Element *E=nm.polygons.front();E;E=E->next()) { - + for (List::Element *E = nm.polygons.front(); E; E = E->next()) { - Polygon &p=E->get(); + Polygon &p = E->get(); int ec = p.edges.size(); - Polygon::Edge *edges=p.edges.ptr(); + Polygon::Edge *edges = p.edges.ptr(); - for(int i=0;i::Element *C=connections.find(ek); + EdgeKey ek(edges[i].point, edges[next].point); + Map::Element *C = connections.find(ek); ERR_CONTINUE(!C); if (edges[i].P) { C->get().pending.erase(edges[i].P); - edges[i].P=NULL; + edges[i].P = NULL; } else if (C->get().B) { //disconnect - C->get().B->edges[C->get().B_edge].C=NULL; - C->get().B->edges[C->get().B_edge].C_edge=-1; - C->get().A->edges[C->get().A_edge].C=NULL; - C->get().A->edges[C->get().A_edge].C_edge=-1; + C->get().B->edges[C->get().B_edge].C = NULL; + C->get().B->edges[C->get().B_edge].C_edge = -1; + C->get().A->edges[C->get().A_edge].C = NULL; + C->get().A->edges[C->get().A_edge].C_edge = -1; - if (C->get().A==&E->get()) { + if (C->get().A == &E->get()) { - C->get().A=C->get().B; - C->get().A_edge=C->get().B_edge; + C->get().A = C->get().B; + C->get().A_edge = C->get().B_edge; } - C->get().B=NULL; - C->get().B_edge=-1; + C->get().B = NULL; + C->get().B_edge = -1; if (C->get().pending.size()) { //reconnect if something is pending ConnectionPending cp = C->get().pending.front()->get(); C->get().pending.pop_front(); - C->get().B=cp.polygon; - C->get().B_edge=cp.edge; - C->get().A->edges[C->get().A_edge].C=cp.polygon; - C->get().A->edges[C->get().A_edge].C_edge=cp.edge; - cp.polygon->edges[cp.edge].C=C->get().A; - cp.polygon->edges[cp.edge].C_edge=C->get().A_edge; - cp.polygon->edges[cp.edge].P=NULL; + C->get().B = cp.polygon; + C->get().B_edge = cp.edge; + C->get().A->edges[C->get().A_edge].C = cp.polygon; + C->get().A->edges[C->get().A_edge].C_edge = cp.edge; + cp.polygon->edges[cp.edge].C = C->get().A; + cp.polygon->edges[cp.edge].C_edge = C->get().A_edge; + cp.polygon->edges[cp.edge].P = NULL; } } else { @@ -206,46 +201,39 @@ void Navigation2D::_navpoly_unlink(int p_id) { nm.polygons.clear(); - nm.linked=false; - - + nm.linked = false; } - -int Navigation2D::navpoly_create(const Ref& p_mesh, const Transform2D& p_xform, Object *p_owner) { +int Navigation2D::navpoly_create(const Ref &p_mesh, const Transform2D &p_xform, Object *p_owner) { int id = last_id++; NavMesh nm; - nm.linked=false; - nm.navpoly=p_mesh; - nm.xform=p_xform; - nm.owner=p_owner; - navpoly_map[id]=nm; + nm.linked = false; + nm.navpoly = p_mesh; + nm.xform = p_xform; + nm.owner = p_owner; + navpoly_map[id] = nm; _navpoly_link(id); return id; } -void Navigation2D::navpoly_set_transform(int p_id, const Transform2D& p_xform){ +void Navigation2D::navpoly_set_transform(int p_id, const Transform2D &p_xform) { ERR_FAIL_COND(!navpoly_map.has(p_id)); - NavMesh &nm=navpoly_map[p_id]; - if (nm.xform==p_xform) + NavMesh &nm = navpoly_map[p_id]; + if (nm.xform == p_xform) return; //bleh _navpoly_unlink(p_id); - nm.xform=p_xform; + nm.xform = p_xform; _navpoly_link(p_id); - - - } -void Navigation2D::navpoly_remove(int p_id){ +void Navigation2D::navpoly_remove(int p_id) { ERR_FAIL_COND(!navpoly_map.has(p_id)); _navpoly_unlink(p_id); navpoly_map.erase(p_id); - } #if 0 void Navigation2D::_clip_path(Vector& path, Polygon *from_poly, const Vector2& p_to_point, Polygon* p_to_poly) { @@ -284,96 +272,91 @@ void Navigation2D::_clip_path(Vector& path, Polygon *from_poly, const V } #endif -Vector Navigation2D::get_simple_path(const Vector2& p_start, const Vector2& p_end, bool p_optimize) { +Vector Navigation2D::get_simple_path(const Vector2 &p_start, const Vector2 &p_end, bool p_optimize) { - - Polygon *begin_poly=NULL; - Polygon *end_poly=NULL; + Polygon *begin_poly = NULL; + Polygon *end_poly = NULL; Vector2 begin_point; Vector2 end_point; - float begin_d=1e20; - float end_d=1e20; + float begin_d = 1e20; + float end_d = 1e20; //look for point inside triangle - for (Map::Element*E=navpoly_map.front();E;E=E->next()) { + for (Map::Element *E = navpoly_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { - + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); + Polygon &p = F->get(); if (begin_d || end_d) { - for(int i=2;i0) { + if (begin_d > 0) { - if (Geometry::is_point_in_triangle(p_start,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) { + if (Geometry::is_point_in_triangle(p_start, _get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point))) { - begin_poly=&p; - begin_point=p_start; - begin_d=0; - if (end_d==0) + begin_poly = &p; + begin_point = p_start; + begin_d = 0; + if (end_d == 0) break; - } } - if (end_d>0) { + if (end_d > 0) { - if (Geometry::is_point_in_triangle(p_end,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) { + if (Geometry::is_point_in_triangle(p_end, _get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point))) { - end_poly=&p; - end_point=p_end; - end_d=0; - if (begin_d==0) + end_poly = &p; + end_point = p_end; + end_d = 0; + if (begin_d == 0) break; } } - } } - p.prev_edge=-1; + p.prev_edge = -1; } } //start or end not inside triangle.. look for closest segment :| if (begin_d || end_d) { - for (Map::Element*E=navpoly_map.front();E;E=E->next()) { + for (Map::Element *E = navpoly_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); + Polygon &p = F->get(); int es = p.edges.size(); - for(int i=0;i0) { - Vector2 spoint=Geometry::get_closest_point_to_segment_2d(p_start,edge); + if (begin_d > 0) { + Vector2 spoint = Geometry::get_closest_point_to_segment_2d(p_start, edge); float d = spoint.distance_to(p_start); - if (d0) { - Vector2 spoint=Geometry::get_closest_point_to_segment_2d(p_end,edge); + if (end_d > 0) { + Vector2 spoint = Geometry::get_closest_point_to_segment_2d(p_end, edge); float d = spoint.distance_to(p_end); - if (d Navigation2D::get_simple_path(const Vector2& p_start, const Vect return Vector(); //no path } - if (begin_poly==end_poly) { + if (begin_poly == end_poly) { Vector path; path.resize(2); - path[0]=begin_point; - path[1]=end_point; + path[0] = begin_point; + path[1] = end_point; //print_line("Direct Path"); return path; } + bool found_route = false; - bool found_route=false; - - List open_list; + List open_list; - begin_poly->entry=p_start; + begin_poly->entry = p_start; - for(int i=0;iedges.size();i++) { + for (int i = 0; i < begin_poly->edges.size(); i++) { if (begin_poly->edges[i].C) { - begin_poly->edges[i].C->prev_edge=begin_poly->edges[i].C_edge; + begin_poly->edges[i].C->prev_edge = begin_poly->edges[i].C_edge; #ifdef USE_ENTRY_POINT - Vector2 edge[2]={ + Vector2 edge[2] = { _get_vertex(begin_poly->edges[i].point), - _get_vertex(begin_poly->edges[(i+1)%begin_poly->edges.size()].point) + _get_vertex(begin_poly->edges[(i + 1) % begin_poly->edges.size()].point) }; - Vector2 entry = Geometry::get_closest_point_to_segment_2d(begin_poly->entry,edge); + Vector2 entry = Geometry::get_closest_point_to_segment_2d(begin_poly->entry, edge); begin_poly->edges[i].C->distance = begin_poly->entry.distance_to(entry); - begin_poly->edges[i].C->entry=entry; + begin_poly->edges[i].C->entry = entry; #else - begin_poly->edges[i].C->distance=begin_poly->center.distance_to(begin_poly->edges[i].C->center); + begin_poly->edges[i].C->distance = begin_poly->center.distance_to(begin_poly->edges[i].C->center); #endif open_list.push_back(begin_poly->edges[i].C); - if (begin_poly->edges[i].C==end_poly) { - found_route=true; + if (begin_poly->edges[i].C == end_poly) { + found_route = true; } } } + while (!found_route) { - while(!found_route) { - - if (open_list.size()==0) { + if (open_list.size() == 0) { //print_line("NOU OPEN LIST"); break; } //check open list - List::Element *least_cost_poly=NULL; - float least_cost=1e30; + List::Element *least_cost_poly = NULL; + float least_cost = 1e30; //this could be faster (cache previous results) - for (List::Element *E=open_list.front();E;E=E->next()) { - - Polygon *p=E->get(); + for (List::Element *E = open_list.front(); E; E = E->next()) { + Polygon *p = E->get(); - float cost=p->distance; - cost+=p->center.distance_to(end_point); + float cost = p->distance; + cost += p->center.distance_to(end_point); - if (costget(); + Polygon *p = least_cost_poly->get(); //open the neighbours for search int es = p->edges.size(); - for(int i=0;iedges[i]; + Polygon::Edge &e = p->edges[i]; if (!e.C) continue; #ifdef USE_ENTRY_POINT - Vector2 edge[2]={ + Vector2 edge[2] = { _get_vertex(p->edges[i].point), - _get_vertex(p->edges[(i+1)%es].point) + _get_vertex(p->edges[(i + 1) % es].point) }; - Vector2 edge_entry = Geometry::get_closest_point_to_segment_2d(p->entry,edge); + Vector2 edge_entry = Geometry::get_closest_point_to_segment_2d(p->entry, edge); float distance = p->entry.distance_to(edge_entry) + p->distance; #else @@ -484,36 +462,33 @@ Vector Navigation2D::get_simple_path(const Vector2& p_start, const Vect #endif - - if (e.C->prev_edge!=-1) { + if (e.C->prev_edge != -1) { //oh this was visited already, can we win the cost? - if (e.C->distance>distance) { + if (e.C->distance > distance) { - e.C->prev_edge=e.C_edge; - e.C->distance=distance; + e.C->prev_edge = e.C_edge; + e.C->distance = distance; #ifdef USE_ENTRY_POINT - e.C->entry=edge_entry; + e.C->entry = edge_entry; #endif } } else { //add to open neighbours - e.C->prev_edge=e.C_edge; - e.C->distance=distance; + e.C->prev_edge = e.C_edge; + e.C->distance = distance; #ifdef USE_ENTRY_POINT - e.C->entry=edge_entry; + e.C->entry = edge_entry; #endif open_list.push_back(e.C); - if (e.C==end_poly) { + if (e.C == end_poly) { //oh my reached end! stop algorithm - found_route=true; + found_route = true; break; - } - } } @@ -552,40 +527,40 @@ debug path if (p_optimize) { //string pulling - Vector2 apex_point=end_point; - Vector2 portal_left=apex_point; - Vector2 portal_right=apex_point; - Polygon *left_poly=end_poly; - Polygon *right_poly=end_poly; - Polygon *p=end_poly; + Vector2 apex_point = end_point; + Vector2 portal_left = apex_point; + Vector2 portal_right = apex_point; + Polygon *left_poly = end_poly; + Polygon *right_poly = end_poly; + Polygon *p = end_poly; path.push_back(end_point); - while(p) { + while (p) { Vector2 left; Vector2 right; //#define CLOCK_TANGENT(m_a,m_b,m_c) ( ((m_a)-(m_c)).cross((m_a)-(m_b)) ) -#define CLOCK_TANGENT(m_a,m_b,m_c) ((((m_a).x - (m_c).x) * ((m_b).y - (m_c).y) - ((m_b).x - (m_c).x) * ((m_a).y - (m_c).y))) +#define CLOCK_TANGENT(m_a, m_b, m_c) ((((m_a).x - (m_c).x) * ((m_b).y - (m_c).y) - ((m_b).x - (m_c).x) * ((m_a).y - (m_c).y))) - if (p==begin_poly) { - left=begin_point; - right=begin_point; + if (p == begin_poly) { + left = begin_point; + right = begin_point; } else { int prev = p->prev_edge; - int prev_n = (p->prev_edge+1)%p->edges.size(); + int prev_n = (p->prev_edge + 1) % p->edges.size(); left = _get_vertex(p->edges[prev].point); right = _get_vertex(p->edges[prev_n].point); if (p->clockwise) { - SWAP(left,right); + SWAP(left, right); } /*if (CLOCK_TANGENT(apex_point,left,(left+right)*0.5) < 0){ SWAP(left,right); }*/ } - bool skip=false; + bool skip = false; /* print_line("-----\nAPEX: "+(apex_point-end_point)); @@ -603,221 +578,202 @@ debug path print_line("\tRight Test: "+rtos(CLOCK_TANGENT(apex_point,right,portal_left))); */ - - if (CLOCK_TANGENT(apex_point,portal_left,left) >= 0){ + if (CLOCK_TANGENT(apex_point, portal_left, left) >= 0) { //process - if (portal_left.distance_squared_to(apex_point) 0) { - left_poly=p; - portal_left=left; + if (portal_left.distance_squared_to(apex_point) < CMP_EPSILON || CLOCK_TANGENT(apex_point, left, portal_right) > 0) { + left_poly = p; + portal_left = left; //print_line("***ADVANCE LEFT"); } else { - apex_point=portal_right; - p=right_poly; - left_poly=p; - portal_left=apex_point; - portal_right=apex_point; - if (path[path.size()-1].distance_to(apex_point)>CMP_EPSILON) + apex_point = portal_right; + p = right_poly; + left_poly = p; + portal_left = apex_point; + portal_right = apex_point; + if (path[path.size() - 1].distance_to(apex_point) > CMP_EPSILON) path.push_back(apex_point); - skip=true; + skip = true; //print_line("addpoint left"); //print_line("***CLIP LEFT"); } } - if (!skip && CLOCK_TANGENT(apex_point,portal_right,right) <= 0){ + if (!skip && CLOCK_TANGENT(apex_point, portal_right, right) <= 0) { //process - if (portal_right.distance_squared_to(apex_point)CMP_EPSILON) + apex_point = portal_left; + p = left_poly; + right_poly = p; + portal_right = apex_point; + portal_left = apex_point; + if (path[path.size() - 1].distance_to(apex_point) > CMP_EPSILON) path.push_back(apex_point); //print_line("addpoint right"); //print_line("***CLIP RIGHT"); - } } - if (p!=begin_poly) - p=p->edges[p->prev_edge].C; + if (p != begin_poly) + p = p->edges[p->prev_edge].C; else - p=NULL; - + p = NULL; } - if (path[path.size()-1].distance_to(begin_point)>CMP_EPSILON) + if (path[path.size() - 1].distance_to(begin_point) > CMP_EPSILON) path.push_back(begin_point); path.invert(); - - - } else { //midpoints - Polygon *p=end_poly; + Polygon *p = end_poly; path.push_back(end_point); - while(true) { + while (true) { int prev = p->prev_edge; - int prev_n = (p->prev_edge+1)%p->edges.size(); - Vector2 point = (_get_vertex(p->edges[prev].point) + _get_vertex(p->edges[prev_n].point))*0.5; + int prev_n = (p->prev_edge + 1) % p->edges.size(); + Vector2 point = (_get_vertex(p->edges[prev].point) + _get_vertex(p->edges[prev_n].point)) * 0.5; path.push_back(point); p = p->edges[prev].C; - if (p==begin_poly) + if (p == begin_poly) break; } path.push_back(begin_point); - path.invert(); } return path; } - return Vector(); - } +Vector2 Navigation2D::get_closest_point(const Vector2 &p_point) { -Vector2 Navigation2D::get_closest_point(const Vector2& p_point) { - - Vector2 closest_point=Vector2(); - float closest_point_d=1e20; + Vector2 closest_point = Vector2(); + float closest_point_d = 1e20; - for (Map::Element*E=navpoly_map.front();E;E=E->next()) { + for (Map::Element *E = navpoly_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); - for(int i=2;iget(); + for (int i = 2; i < p.edges.size(); i++) { - if (Geometry::is_point_in_triangle(p_point,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) { + if (Geometry::is_point_in_triangle(p_point, _get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point))) { return p_point; //inside triangle, nothing else to discuss } - } } } - for (Map::Element*E=navpoly_map.front();E;E=E->next()) { + for (Map::Element *E = navpoly_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); + Polygon &p = F->get(); int es = p.edges.size(); - for(int i=0;i::Element*E=navpoly_map.front();E;E=E->next()) { + for (Map::Element *E = navpoly_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); - for(int i=2;iget(); + for (int i = 2; i < p.edges.size(); i++) { - if (Geometry::is_point_in_triangle(p_point,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) { + if (Geometry::is_point_in_triangle(p_point, _get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point))) { E->get().owner; } - } } } - for (Map::Element*E=navpoly_map.front();E;E=E->next()) { + for (Map::Element *E = navpoly_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); + Polygon &p = F->get(); int es = p.edges.size(); - for(int i=0;iget().owner; + closest_point = spoint; + closest_point_d = d; + owner = E->get().owner; } } } } return owner; - } - void Navigation2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("navpoly_create","mesh:NavigationPolygon","xform","owner"),&Navigation2D::navpoly_create,DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("navpoly_set_transform","id","xform"),&Navigation2D::navpoly_set_transform); - ClassDB::bind_method(D_METHOD("navpoly_remove","id"),&Navigation2D::navpoly_remove); - - ClassDB::bind_method(D_METHOD("get_simple_path","start","end","optimize"),&Navigation2D::get_simple_path,DEFVAL(true)); - ClassDB::bind_method(D_METHOD("get_closest_point","to_point"),&Navigation2D::get_closest_point); - ClassDB::bind_method(D_METHOD("get_closest_point_owner","to_point"),&Navigation2D::get_closest_point_owner); + ClassDB::bind_method(D_METHOD("navpoly_create", "mesh:NavigationPolygon", "xform", "owner"), &Navigation2D::navpoly_create, DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("navpoly_set_transform", "id", "xform"), &Navigation2D::navpoly_set_transform); + ClassDB::bind_method(D_METHOD("navpoly_remove", "id"), &Navigation2D::navpoly_remove); + ClassDB::bind_method(D_METHOD("get_simple_path", "start", "end", "optimize"), &Navigation2D::get_simple_path, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("get_closest_point", "to_point"), &Navigation2D::get_closest_point); + ClassDB::bind_method(D_METHOD("get_closest_point_owner", "to_point"), &Navigation2D::get_closest_point_owner); } Navigation2D::Navigation2D() { - ERR_FAIL_COND( sizeof(Point)!=8 ); - cell_size=1; // one pixel - last_id=1; - + ERR_FAIL_COND(sizeof(Point) != 8); + cell_size = 1; // one pixel + last_id = 1; } diff --git a/scene/2d/navigation2d.h b/scene/2d/navigation2d.h index 63827ebb6..afa565518 100644 --- a/scene/2d/navigation2d.h +++ b/scene/2d/navigation2d.h @@ -29,45 +29,42 @@ #ifndef NAVIGATION_2D_H #define NAVIGATION_2D_H -#include "scene/2d/node_2d.h" #include "scene/2d/navigation_polygon.h" +#include "scene/2d/node_2d.h" class Navigation2D : public Node2D { - GDCLASS( Navigation2D, Node2D); - + GDCLASS(Navigation2D, Node2D); union Point { struct { - int64_t x:32; - int64_t y:32; + int64_t x : 32; + int64_t y : 32; }; uint64_t key; - bool operator<(const Point& p_key) const { return key < p_key.key; } + bool operator<(const Point &p_key) const { return key < p_key.key; } }; - struct EdgeKey { Point a; Point b; - bool operator<(const EdgeKey& p_key) const { - return (a.key==p_key.a.key)?(b.key b.key) { - SWAP(a,b); + SWAP(a, b); } } }; - struct NavMesh; struct Polygon; @@ -84,7 +81,11 @@ class Navigation2D : public Node2D { Polygon *C; //connection int C_edge; List::Element *P; - Edge() { C=NULL; C_edge=-1; P=NULL; } + Edge() { + C = NULL; + C_edge = -1; + P = NULL; + } }; Vector edges; @@ -100,7 +101,6 @@ class Navigation2D : public Node2D { NavMesh *owner; }; - struct Connection { Polygon *A; @@ -110,11 +110,15 @@ class Navigation2D : public Node2D { List pending; - Connection() { A=NULL; B=NULL; A_edge=-1; B_edge=-1;} + Connection() { + A = NULL; + B = NULL; + A_edge = -1; + B_edge = -1; + } }; - Map connections; - + Map connections; struct NavMesh { @@ -123,57 +127,48 @@ class Navigation2D : public Node2D { bool linked; Ref navpoly; List polygons; - }; + _FORCE_INLINE_ Point _get_point(const Vector2 &p_pos) const { - - _FORCE_INLINE_ Point _get_point(const Vector2& p_pos) const { - - int x = int(Math::floor(p_pos.x/cell_size)); - int y = int(Math::floor(p_pos.y/cell_size)); + int x = int(Math::floor(p_pos.x / cell_size)); + int y = int(Math::floor(p_pos.y / cell_size)); Point p; - p.key=0; - p.x=x; - p.y=y; + p.key = 0; + p.x = x; + p.y = y; return p; - } - _FORCE_INLINE_ Vector2 _get_vertex(const Point& p_point) const { + _FORCE_INLINE_ Vector2 _get_vertex(const Point &p_point) const { - return Vector2(p_point.x,p_point.y)*cell_size; + return Vector2(p_point.x, p_point.y) * cell_size; } - - void _navpoly_link(int p_id); void _navpoly_unlink(int p_id); float cell_size; - Map navpoly_map; + Map navpoly_map; int last_id; #if 0 void _clip_path(Vector& path,Polygon *from_poly, const Vector2& p_to_point, Polygon* p_to_poly); #endif protected: - static void _bind_methods(); public: - //API should be as dynamic as possible - int navpoly_create(const Ref& p_mesh,const Transform2D& p_xform,Object* p_owner=NULL); - void navpoly_set_transform(int p_id, const Transform2D& p_xform); + int navpoly_create(const Ref &p_mesh, const Transform2D &p_xform, Object *p_owner = NULL); + void navpoly_set_transform(int p_id, const Transform2D &p_xform); void navpoly_remove(int p_id); - Vector get_simple_path(const Vector2& p_start, const Vector2& p_end,bool p_optimize=true); - Vector2 get_closest_point(const Vector2& p_point); - Object* get_closest_point_owner(const Vector2& p_point); + Vector get_simple_path(const Vector2 &p_start, const Vector2 &p_end, bool p_optimize = true); + Vector2 get_closest_point(const Vector2 &p_point); + Object *get_closest_point_owner(const Vector2 &p_point); Navigation2D(); }; - #endif // Navigation2D2D_H diff --git a/scene/2d/navigation_polygon.cpp b/scene/2d/navigation_polygon.cpp index 9dbbd34ae..570bd00a5 100644 --- a/scene/2d/navigation_polygon.cpp +++ b/scene/2d/navigation_polygon.cpp @@ -27,26 +27,25 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "navigation_polygon.h" +#include "core_string_names.h" #include "navigation2d.h" #include "triangulator.h" -#include "core_string_names.h" -void NavigationPolygon::set_vertices(const PoolVector& p_vertices) { +void NavigationPolygon::set_vertices(const PoolVector &p_vertices) { - vertices=p_vertices; + vertices = p_vertices; } -PoolVector NavigationPolygon::get_vertices() const{ +PoolVector NavigationPolygon::get_vertices() const { return vertices; } - -void NavigationPolygon::_set_polygons(const Array& p_array) { +void NavigationPolygon::_set_polygons(const Array &p_array) { polygons.resize(p_array.size()); - for(int i=0;i& p_polygon){ +void NavigationPolygon::add_polygon(const Vector &p_polygon) { Polygon polygon; - polygon.indices=p_polygon; + polygon.indices = p_polygon; polygons.push_back(polygon); - } -void NavigationPolygon::add_outline_at_index(const PoolVector& p_outline,int p_index) { +void NavigationPolygon::add_outline_at_index(const PoolVector &p_outline, int p_index) { - outlines.insert(p_index,p_outline); + outlines.insert(p_index, p_outline); } -int NavigationPolygon::get_polygon_count() const{ +int NavigationPolygon::get_polygon_count() const { return polygons.size(); } -Vector NavigationPolygon::get_polygon(int p_idx){ +Vector NavigationPolygon::get_polygon(int p_idx) { - ERR_FAIL_INDEX_V(p_idx,polygons.size(),Vector()); + ERR_FAIL_INDEX_V(p_idx, polygons.size(), Vector()); return polygons[p_idx].indices; } -void NavigationPolygon::clear_polygons(){ +void NavigationPolygon::clear_polygons() { polygons.clear(); } -void NavigationPolygon::add_outline(const PoolVector& p_outline) { +void NavigationPolygon::add_outline(const PoolVector &p_outline) { outlines.push_back(p_outline); } -int NavigationPolygon::get_outline_count() const{ +int NavigationPolygon::get_outline_count() const { return outlines.size(); } -void NavigationPolygon::set_outline(int p_idx,const PoolVector& p_outline) { - ERR_FAIL_INDEX(p_idx,outlines.size()); - outlines[p_idx]=p_outline; +void NavigationPolygon::set_outline(int p_idx, const PoolVector &p_outline) { + ERR_FAIL_INDEX(p_idx, outlines.size()); + outlines[p_idx] = p_outline; } void NavigationPolygon::remove_outline(int p_idx) { - ERR_FAIL_INDEX(p_idx,outlines.size()); + ERR_FAIL_INDEX(p_idx, outlines.size()); outlines.remove(p_idx); - } PoolVector NavigationPolygon::get_outline(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,outlines.size(),PoolVector()); + ERR_FAIL_INDEX_V(p_idx, outlines.size(), PoolVector()); return outlines[p_idx]; } -void NavigationPolygon::clear_outlines(){ +void NavigationPolygon::clear_outlines() { outlines.clear(); } -void NavigationPolygon::make_polygons_from_outlines(){ +void NavigationPolygon::make_polygons_from_outlines() { - List in_poly,out_poly; + List in_poly, out_poly; - Vector2 outside_point(-1e10,-1e10); + Vector2 outside_point(-1e10, -1e10); - for(int i=0;i ol = outlines[i]; int olsize = ol.size(); - if (olsize<3) + if (olsize < 3) continue; - PoolVector::Read r=ol.read(); - for(int j=0;j::Read r = ol.read(); + for (int j = 0; j < olsize; j++) { + outside_point.x = MAX(r[j].x, outside_point.x); + outside_point.y = MAX(r[j].y, outside_point.y); } - } - outside_point+=Vector2(0.7239784,0.819238); //avoid precision issues + outside_point += Vector2(0.7239784, 0.819238); //avoid precision issues - - - for(int i=0;i ol = outlines[i]; int olsize = ol.size(); - if (olsize<3) + if (olsize < 3) continue; - PoolVector::Read r=ol.read(); + PoolVector::Read r = ol.read(); - int interscount=0; + int interscount = 0; //test if this is an outer outline - for(int k=0;k ol2 = outlines[k]; int olsize2 = ol2.size(); - if (olsize2<3) + if (olsize2 < 3) continue; - PoolVector::Read r2=ol2.read(); + PoolVector::Read r2 = ol2.read(); - for(int l=0;l points; - for(List::Element*I = out_poly.front();I;I=I->next()) { + Map points; + for (List::Element *I = out_poly.front(); I; I = I->next()) { - TriangulatorPoly& tp = I->get(); + TriangulatorPoly &tp = I->get(); struct Polygon p; - for(int i=0;i::Element *E=points.find(tp[i]); + Map::Element *E = points.find(tp[i]); if (!E) { - E=points.insert(tp[i],vertices.size()); + E = points.insert(tp[i], vertices.size()); vertices.push_back(tp[i]); } p.indices.push_back(E->get()); @@ -244,56 +235,53 @@ void NavigationPolygon::make_polygons_from_outlines(){ emit_signal(CoreStringNames::get_singleton()->changed); } - void NavigationPolygon::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_vertices","vertices"),&NavigationPolygon::set_vertices); - ClassDB::bind_method(D_METHOD("get_vertices"),&NavigationPolygon::get_vertices); + ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &NavigationPolygon::set_vertices); + ClassDB::bind_method(D_METHOD("get_vertices"), &NavigationPolygon::get_vertices); - ClassDB::bind_method(D_METHOD("add_polygon","polygon"),&NavigationPolygon::add_polygon); - ClassDB::bind_method(D_METHOD("get_polygon_count"),&NavigationPolygon::get_polygon_count); - ClassDB::bind_method(D_METHOD("get_polygon","idx"),&NavigationPolygon::get_polygon); - ClassDB::bind_method(D_METHOD("clear_polygons"),&NavigationPolygon::clear_polygons); + ClassDB::bind_method(D_METHOD("add_polygon", "polygon"), &NavigationPolygon::add_polygon); + ClassDB::bind_method(D_METHOD("get_polygon_count"), &NavigationPolygon::get_polygon_count); + ClassDB::bind_method(D_METHOD("get_polygon", "idx"), &NavigationPolygon::get_polygon); + ClassDB::bind_method(D_METHOD("clear_polygons"), &NavigationPolygon::clear_polygons); - ClassDB::bind_method(D_METHOD("add_outline","outline"),&NavigationPolygon::add_outline); - ClassDB::bind_method(D_METHOD("add_outline_at_index","outline","index"),&NavigationPolygon::add_outline_at_index); - ClassDB::bind_method(D_METHOD("get_outline_count"),&NavigationPolygon::get_outline_count); - ClassDB::bind_method(D_METHOD("set_outline","idx","outline"),&NavigationPolygon::set_outline); - ClassDB::bind_method(D_METHOD("get_outline","idx"),&NavigationPolygon::get_outline); - ClassDB::bind_method(D_METHOD("remove_outline","idx"),&NavigationPolygon::remove_outline); - ClassDB::bind_method(D_METHOD("clear_outlines"),&NavigationPolygon::clear_outlines); - ClassDB::bind_method(D_METHOD("make_polygons_from_outlines"),&NavigationPolygon::make_polygons_from_outlines); + ClassDB::bind_method(D_METHOD("add_outline", "outline"), &NavigationPolygon::add_outline); + ClassDB::bind_method(D_METHOD("add_outline_at_index", "outline", "index"), &NavigationPolygon::add_outline_at_index); + ClassDB::bind_method(D_METHOD("get_outline_count"), &NavigationPolygon::get_outline_count); + ClassDB::bind_method(D_METHOD("set_outline", "idx", "outline"), &NavigationPolygon::set_outline); + ClassDB::bind_method(D_METHOD("get_outline", "idx"), &NavigationPolygon::get_outline); + ClassDB::bind_method(D_METHOD("remove_outline", "idx"), &NavigationPolygon::remove_outline); + ClassDB::bind_method(D_METHOD("clear_outlines"), &NavigationPolygon::clear_outlines); + ClassDB::bind_method(D_METHOD("make_polygons_from_outlines"), &NavigationPolygon::make_polygons_from_outlines); - ClassDB::bind_method(D_METHOD("_set_polygons","polygons"),&NavigationPolygon::_set_polygons); - ClassDB::bind_method(D_METHOD("_get_polygons"),&NavigationPolygon::_get_polygons); + ClassDB::bind_method(D_METHOD("_set_polygons", "polygons"), &NavigationPolygon::_set_polygons); + ClassDB::bind_method(D_METHOD("_get_polygons"), &NavigationPolygon::_get_polygons); - ClassDB::bind_method(D_METHOD("_set_outlines","outlines"),&NavigationPolygon::_set_outlines); - ClassDB::bind_method(D_METHOD("_get_outlines"),&NavigationPolygon::_get_outlines); + ClassDB::bind_method(D_METHOD("_set_outlines", "outlines"), &NavigationPolygon::_set_outlines); + ClassDB::bind_method(D_METHOD("_get_outlines"), &NavigationPolygon::_get_outlines); - ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY,"vertices",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_vertices","get_vertices"); - ADD_PROPERTY(PropertyInfo(Variant::ARRAY,"polygons",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_polygons","_get_polygons"); - ADD_PROPERTY(PropertyInfo(Variant::ARRAY,"outlines",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_outlines","_get_outlines"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_vertices", "get_vertices"); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "polygons", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_polygons", "_get_polygons"); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "outlines", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_outlines", "_get_outlines"); } NavigationPolygon::NavigationPolygon() { - - } void NavigationPolygonInstance::set_enabled(bool p_enabled) { - if (enabled==p_enabled) + if (enabled == p_enabled) return; - enabled=p_enabled; + enabled = p_enabled; if (!is_inside_tree()) return; if (!enabled) { - if (nav_id!=-1) { + if (nav_id != -1) { navigation->navpoly_remove(nav_id); - nav_id=-1; + nav_id = -1; } } else { @@ -301,10 +289,9 @@ void NavigationPolygonInstance::set_enabled(bool p_enabled) { if (navpoly.is_valid()) { - nav_id = navigation->navpoly_create(navpoly,get_relative_transform_to_parent(navigation),this); + nav_id = navigation->navpoly_create(navpoly, get_relative_transform_to_parent(navigation), this); } } - } if (get_tree()->is_editor_hint() || get_tree()->is_debugging_navigation_hint()) @@ -315,41 +302,37 @@ void NavigationPolygonInstance::set_enabled(bool p_enabled) { bool NavigationPolygonInstance::is_enabled() const { - return enabled; } - ///////////////////////////// - void NavigationPolygonInstance::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - Node2D *c=this; - while(c) { + Node2D *c = this; + while (c) { - navigation=c->cast_to(); + navigation = c->cast_to(); if (navigation) { if (enabled && navpoly.is_valid()) { - nav_id = navigation->navpoly_create(navpoly,get_relative_transform_to_parent(navigation),this); + nav_id = navigation->navpoly_create(navpoly, get_relative_transform_to_parent(navigation), this); } break; } - c=c->get_parent()->cast_to(); + c = c->get_parent()->cast_to(); } } break; case NOTIFICATION_TRANSFORM_CHANGED: { - if (navigation && nav_id!=-1) { - navigation->navpoly_set_transform(nav_id,get_relative_transform_to_parent(navigation)); + if (navigation && nav_id != -1) { + navigation->navpoly_set_transform(nav_id, get_relative_transform_to_parent(navigation)); } } break; @@ -357,28 +340,27 @@ void NavigationPolygonInstance::_notification(int p_what) { if (navigation) { - if (nav_id!=-1) { + if (nav_id != -1) { navigation->navpoly_remove(nav_id); - nav_id=-1; + nav_id = -1; } } - navigation=NULL; + navigation = NULL; } break; case NOTIFICATION_DRAW: { if (is_inside_tree() && (get_tree()->is_editor_hint() || get_tree()->is_debugging_navigation_hint()) && navpoly.is_valid()) { - PoolVector verts=navpoly->get_vertices(); + PoolVector verts = navpoly->get_vertices(); int vsize = verts.size(); - if (vsize<3) + if (vsize < 3) return; - Color color; if (enabled) { - color=get_tree()->get_debug_navigation_color(); + color = get_tree()->get_debug_navigation_color(); } else { - color=get_tree()->get_debug_navigation_disabled_color(); + color = get_tree()->get_debug_navigation_disabled_color(); } Vector colors; Vector vertices; @@ -386,66 +368,61 @@ void NavigationPolygonInstance::_notification(int p_what) { colors.resize(vsize); { PoolVector::Read vr = verts.read(); - for(int i=0;i indices; - - for(int i=0;iget_polygon_count();i++) { + for (int i = 0; i < navpoly->get_polygon_count(); i++) { Vector polygon = navpoly->get_polygon(i); - for(int j=2;jcanvas_item_add_triangle_array(get_canvas_item(),indices,vertices,colors); - + VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(), indices, vertices, colors); } } break; - } } +void NavigationPolygonInstance::set_navigation_polygon(const Ref &p_navpoly) { -void NavigationPolygonInstance::set_navigation_polygon(const Ref& p_navpoly) { - - if (p_navpoly==navpoly) + if (p_navpoly == navpoly) return; - if (navigation && nav_id!=-1) { + if (navigation && nav_id != -1) { navigation->navpoly_remove(nav_id); - nav_id=-1; + nav_id = -1; } if (navpoly.is_valid()) { - navpoly->disconnect(CoreStringNames::get_singleton()->changed,this,"_navpoly_changed"); + navpoly->disconnect(CoreStringNames::get_singleton()->changed, this, "_navpoly_changed"); } - navpoly=p_navpoly; + navpoly = p_navpoly; if (navpoly.is_valid()) { - navpoly->connect(CoreStringNames::get_singleton()->changed,this,"_navpoly_changed"); + navpoly->connect(CoreStringNames::get_singleton()->changed, this, "_navpoly_changed"); } if (navigation && navpoly.is_valid() && enabled) { - nav_id = navigation->navpoly_create(navpoly,get_relative_transform_to_parent(navigation),this); + nav_id = navigation->navpoly_create(navpoly, get_relative_transform_to_parent(navigation), this); } //update_gizmo(); _change_notify("navpoly"); update_configuration_warning(); - } -Ref NavigationPolygonInstance::get_navigation_polygon() const{ +Ref NavigationPolygonInstance::get_navigation_polygon() const { return navpoly; } @@ -456,7 +433,6 @@ void NavigationPolygonInstance::_navpoly_changed() { update(); } - String NavigationPolygonInstance::get_configuration_warning() const { if (!is_visible_in_tree() || !is_inside_tree()) @@ -465,14 +441,14 @@ String NavigationPolygonInstance::get_configuration_warning() const { if (!navpoly.is_valid()) { return TTR("A NavigationPolygon resource must be set or created for this node to work. Please set a property or draw a polygon."); } - const Node2D *c=this; - while(c) { + const Node2D *c = this; + while (c) { if (c->cast_to()) { return String(); } - c=c->get_parent()->cast_to(); + c = c->get_parent()->cast_to(); } return TTR("NavigationPolygonInstance must be a child or grandchild to a Navigation2D node. It only provides navigation data."); @@ -480,23 +456,22 @@ String NavigationPolygonInstance::get_configuration_warning() const { void NavigationPolygonInstance::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_navigation_polygon","navpoly:NavigationPolygon"),&NavigationPolygonInstance::set_navigation_polygon); - ClassDB::bind_method(D_METHOD("get_navigation_polygon:NavigationPolygon"),&NavigationPolygonInstance::get_navigation_polygon); + ClassDB::bind_method(D_METHOD("set_navigation_polygon", "navpoly:NavigationPolygon"), &NavigationPolygonInstance::set_navigation_polygon); + ClassDB::bind_method(D_METHOD("get_navigation_polygon:NavigationPolygon"), &NavigationPolygonInstance::get_navigation_polygon); - ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&NavigationPolygonInstance::set_enabled); - ClassDB::bind_method(D_METHOD("is_enabled"),&NavigationPolygonInstance::is_enabled); + ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationPolygonInstance::set_enabled); + ClassDB::bind_method(D_METHOD("is_enabled"), &NavigationPolygonInstance::is_enabled); - ClassDB::bind_method(D_METHOD("_navpoly_changed"),&NavigationPolygonInstance::_navpoly_changed); + ClassDB::bind_method(D_METHOD("_navpoly_changed"), &NavigationPolygonInstance::_navpoly_changed); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"navpoly",PROPERTY_HINT_RESOURCE_TYPE,"NavigationPolygon"),"set_navigation_polygon","get_navigation_polygon"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navpoly", PROPERTY_HINT_RESOURCE_TYPE, "NavigationPolygon"), "set_navigation_polygon", "get_navigation_polygon"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); } NavigationPolygonInstance::NavigationPolygonInstance() { - navigation=NULL; - nav_id=-1; - enabled=true; + navigation = NULL; + nav_id = -1; + enabled = true; set_notify_transform(true); - } diff --git a/scene/2d/navigation_polygon.h b/scene/2d/navigation_polygon.h index 7f1762b6f..6bc3b903c 100644 --- a/scene/2d/navigation_polygon.h +++ b/scene/2d/navigation_polygon.h @@ -31,41 +31,36 @@ #include "scene/2d/node_2d.h" +class NavigationPolygon : public Resource { -class NavigationPolygon : public Resource { - - GDCLASS( NavigationPolygon, Resource ); + GDCLASS(NavigationPolygon, Resource); PoolVector vertices; struct Polygon { Vector indices; }; Vector polygons; - Vector< PoolVector > outlines; + Vector > outlines; protected: - static void _bind_methods(); - void _set_polygons(const Array& p_array); + void _set_polygons(const Array &p_array); Array _get_polygons() const; - void _set_outlines(const Array& p_array); + void _set_outlines(const Array &p_array); Array _get_outlines() const; public: - - - - void set_vertices(const PoolVector& p_vertices); + void set_vertices(const PoolVector &p_vertices); PoolVector get_vertices() const; - void add_polygon(const Vector& p_polygon); + void add_polygon(const Vector &p_polygon); int get_polygon_count() const; - void add_outline(const PoolVector& p_outline); - void add_outline_at_index(const PoolVector& p_outline,int p_index); - void set_outline(int p_idx,const PoolVector& p_outline); + void add_outline(const PoolVector &p_outline); + void add_outline_at_index(const PoolVector &p_outline, int p_index); + void set_outline(int p_idx, const PoolVector &p_outline); PoolVector get_outline(int p_idx) const; void remove_outline(int p_idx); int get_outline_count() const; @@ -79,12 +74,11 @@ public: NavigationPolygon(); }; - class Navigation2D; class NavigationPolygonInstance : public Node2D { - GDCLASS(NavigationPolygonInstance,Node2D); + GDCLASS(NavigationPolygonInstance, Node2D); bool enabled; int nav_id; @@ -94,15 +88,14 @@ class NavigationPolygonInstance : public Node2D { void _navpoly_changed(); protected: - void _notification(int p_what); static void _bind_methods(); -public: +public: void set_enabled(bool p_enabled); bool is_enabled() const; - void set_navigation_polygon(const Ref& p_navpoly); + void set_navigation_polygon(const Ref &p_navpoly); Ref get_navigation_polygon() const; String get_configuration_warning() const; @@ -110,5 +103,4 @@ public: NavigationPolygonInstance(); }; - #endif // NAVIGATIONPOLYGON_H diff --git a/scene/2d/node_2d.cpp b/scene/2d/node_2d.cpp index 710f9731c..1ba6ec46c 100644 --- a/scene/2d/node_2d.cpp +++ b/scene/2d/node_2d.cpp @@ -28,15 +28,12 @@ /*************************************************************************/ #include "node_2d.h" -#include "servers/visual_server.h" +#include "message_queue.h" #include "scene/gui/control.h" #include "scene/main/viewport.h" -#include "message_queue.h" - - -void Node2D::edit_set_pivot(const Point2& p_pivot) { - +#include "servers/visual_server.h" +void Node2D::edit_set_pivot(const Point2 &p_pivot) { } Point2 Node2D::edit_get_pivot() const { @@ -56,12 +53,11 @@ Variant Node2D::edit_get_state() const { state.push_back(get_scale()); return state; - } -void Node2D::edit_set_state(const Variant& p_state) { +void Node2D::edit_set_state(const Variant &p_state) { Array state = p_state; - ERR_FAIL_COND( state.size() != 3); + ERR_FAIL_COND(state.size() != 3); pos = state[0]; angle = state[1]; @@ -70,89 +66,82 @@ void Node2D::edit_set_state(const Variant& p_state) { _change_notify("transform/rot"); _change_notify("transform/scale"); _change_notify("transform/pos"); - } -void Node2D::edit_set_rect(const Rect2& p_edit_rect) { +void Node2D::edit_set_rect(const Rect2 &p_edit_rect) { Rect2 r = get_item_rect(); Vector2 zero_offset; - if (r.size.x!=0) + if (r.size.x != 0) zero_offset.x = -r.pos.x / r.size.x; - if (r.size.y!=0) + if (r.size.y != 0) zero_offset.y = -r.pos.y / r.size.y; - Size2 new_scale(1,1); + Size2 new_scale(1, 1); - if (r.size.x!=0) + if (r.size.x != 0) new_scale.x = p_edit_rect.size.x / r.size.x; - if (r.size.y!=0) + if (r.size.y != 0) new_scale.y = p_edit_rect.size.y / r.size.y; - Point2 new_pos = p_edit_rect.pos + p_edit_rect.size*zero_offset;//p_edit_rect.pos - r.pos; + Point2 new_pos = p_edit_rect.pos + p_edit_rect.size * zero_offset; //p_edit_rect.pos - r.pos; Transform2D postxf; - postxf.set_rotation_and_scale(angle,_scale); + postxf.set_rotation_and_scale(angle, _scale); new_pos = postxf.xform(new_pos); - pos+=new_pos; - _scale*=new_scale; + pos += new_pos; + _scale *= new_scale; _update_transform(); _change_notify("transform/scale"); _change_notify("transform/pos"); - } - void Node2D::edit_rotate(float p_rot) { - angle+=p_rot; + angle += p_rot; _update_transform(); _change_notify("transform/rot"); } - void Node2D::_update_xform_values() { - pos=_mat.elements[2]; - angle=_mat.get_rotation(); - _scale=_mat.get_scale(); - _xform_dirty=false; + pos = _mat.elements[2]; + angle = _mat.get_rotation(); + _scale = _mat.get_scale(); + _xform_dirty = false; } void Node2D::_update_transform() { - Transform2D mat(angle,pos); - _mat.set_rotation_and_scale(angle,_scale); - _mat.elements[2]=pos; + Transform2D mat(angle, pos); + _mat.set_rotation_and_scale(angle, _scale); + _mat.elements[2] = pos; - VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(),_mat); + VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(), _mat); if (!is_inside_tree()) return; - _notify_transform(); } -void Node2D::set_position(const Point2& p_pos) { +void Node2D::set_position(const Point2 &p_pos) { if (_xform_dirty) - ((Node2D*)this)->_update_xform_values(); - pos=p_pos; + ((Node2D *)this)->_update_xform_values(); + pos = p_pos; _update_transform(); _change_notify("transform/pos"); - - } void Node2D::set_rotation(float p_radians) { if (_xform_dirty) - ((Node2D*)this)->_update_xform_values(); - angle=p_radians; + ((Node2D *)this)->_update_xform_values(); + angle = p_radians; _update_transform(); _change_notify("transform/rot"); } @@ -170,29 +159,28 @@ void Node2D::_set_rotd(float p_degrees) { set_rotation_in_degrees(p_degrees); } -void Node2D::set_scale(const Size2& p_scale) { +void Node2D::set_scale(const Size2 &p_scale) { if (_xform_dirty) - ((Node2D*)this)->_update_xform_values(); - _scale=p_scale; - if (_scale.x==0) - _scale.x=CMP_EPSILON; - if (_scale.y==0) - _scale.y=CMP_EPSILON; + ((Node2D *)this)->_update_xform_values(); + _scale = p_scale; + if (_scale.x == 0) + _scale.x = CMP_EPSILON; + if (_scale.y == 0) + _scale.y = CMP_EPSILON; _update_transform(); _change_notify("transform/scale"); - } Point2 Node2D::get_position() const { if (_xform_dirty) - ((Node2D*)this)->_update_xform_values(); + ((Node2D *)this)->_update_xform_values(); return pos; } float Node2D::get_rotation() const { if (_xform_dirty) - ((Node2D*)this)->_update_xform_values(); + ((Node2D *)this)->_update_xform_values(); return angle; } @@ -209,16 +197,14 @@ float Node2D::_get_rotd() const { } Size2 Node2D::get_scale() const { if (_xform_dirty) - ((Node2D*)this)->_update_xform_values(); + ((Node2D *)this)->_update_xform_values(); return _scale; } - void Node2D::_notification(int p_what) { - switch(p_what) { - + switch (p_what) { } } @@ -231,59 +217,57 @@ Rect2 Node2D::get_item_rect() const { if (get_script_instance()) { Variant::CallError err; - Rect2 r = get_script_instance()->call("_get_item_rect",NULL,0,err); - if (err.error==Variant::CallError::CALL_OK) + Rect2 r = get_script_instance()->call("_get_item_rect", NULL, 0, err); + if (err.error == Variant::CallError::CALL_OK) return r; } - return Rect2(Point2(-32,-32),Size2(64,64)); + return Rect2(Point2(-32, -32), Size2(64, 64)); } void Node2D::rotate(float p_radians) { - set_rotation( get_rotation() + p_radians); + set_rotation(get_rotation() + p_radians); } -void Node2D::translate(const Vector2& p_amount) { +void Node2D::translate(const Vector2 &p_amount) { - set_position( get_position() + p_amount ); + set_position(get_position() + p_amount); } -void Node2D::global_translate(const Vector2& p_amount) { +void Node2D::global_translate(const Vector2 &p_amount) { - set_global_position( get_global_position() + p_amount ); + set_global_position(get_global_position() + p_amount); } -void Node2D::scale(const Size2& p_amount) { +void Node2D::scale(const Size2 &p_amount) { - set_scale( get_scale() * p_amount ); + set_scale(get_scale() * p_amount); } - -void Node2D::move_x(float p_delta,bool p_scaled){ +void Node2D::move_x(float p_delta, bool p_scaled) { Transform2D t = get_transform(); Vector2 m = t[0]; if (!p_scaled) m.normalize(); - set_position(t[2]+m*p_delta); + set_position(t[2] + m * p_delta); } -void Node2D::move_y(float p_delta,bool p_scaled){ +void Node2D::move_y(float p_delta, bool p_scaled) { Transform2D t = get_transform(); Vector2 m = t[1]; if (!p_scaled) m.normalize(); - set_position(t[2]+m*p_delta); + set_position(t[2] + m * p_delta); } - Point2 Node2D::get_global_position() const { return get_global_transform().get_origin(); } -void Node2D::set_global_position(const Point2& p_pos) { +void Node2D::set_global_position(const Point2 &p_pos) { Transform2D inv; CanvasItem *pi = get_parent_item(); @@ -295,7 +279,6 @@ void Node2D::set_global_position(const Point2& p_pos) { } } - float Node2D::get_global_rotation() const { return get_global_transform().get_rotation(); @@ -312,7 +295,6 @@ void Node2D::set_global_rotation(float p_radians) { } } - float Node2D::get_global_rotation_in_degrees() const { return Math::rad2deg(get_global_rotation()); @@ -323,13 +305,12 @@ void Node2D::set_global_rotation_in_degrees(float p_degrees) { set_global_rotation(Math::deg2rad(p_degrees)); } - Size2 Node2D::get_global_scale() const { return get_global_transform().get_scale(); } -void Node2D::set_global_scale(const Size2& p_scale) { +void Node2D::set_global_scale(const Size2 &p_scale) { CanvasItem *pi = get_parent_item(); if (pi) { @@ -338,16 +319,14 @@ void Node2D::set_global_scale(const Size2& p_scale) { } else { set_scale(p_scale); } - } +void Node2D::set_transform(const Transform2D &p_transform) { -void Node2D::set_transform(const Transform2D& p_transform) { + _mat = p_transform; + _xform_dirty = true; - _mat=p_transform; - _xform_dirty=true; - - VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(),_mat); + VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(), _mat); if (!is_inside_tree()) return; @@ -355,32 +334,29 @@ void Node2D::set_transform(const Transform2D& p_transform) { _notify_transform(); } -void Node2D::set_global_transform(const Transform2D& p_transform) { +void Node2D::set_global_transform(const Transform2D &p_transform) { CanvasItem *pi = get_parent_item(); if (pi) - set_transform( pi->get_global_transform().affine_inverse() * p_transform); + set_transform(pi->get_global_transform().affine_inverse() * p_transform); else set_transform(p_transform); - - } void Node2D::set_z(int p_z) { - ERR_FAIL_COND(p_zVS::CANVAS_ITEM_Z_MAX); - z=p_z; - VS::get_singleton()->canvas_item_set_z(get_canvas_item(),z); - + ERR_FAIL_COND(p_z < VS::CANVAS_ITEM_Z_MIN); + ERR_FAIL_COND(p_z > VS::CANVAS_ITEM_Z_MAX); + z = p_z; + VS::get_singleton()->canvas_item_set_z(get_canvas_item(), z); } void Node2D::set_z_as_relative(bool p_enabled) { - if (z_relative==p_enabled) + if (z_relative == p_enabled) return; - z_relative=p_enabled; - VS::get_singleton()->canvas_item_set_z_as_relative_to_parent(get_canvas_item(),p_enabled); + z_relative = p_enabled; + VS::get_singleton()->canvas_item_set_z_as_relative_to_parent(get_canvas_item(), p_enabled); } bool Node2D::is_z_relative() const { @@ -388,115 +364,106 @@ bool Node2D::is_z_relative() const { return z_relative; } - -int Node2D::get_z() const{ +int Node2D::get_z() const { return z; } Transform2D Node2D::get_relative_transform_to_parent(const Node *p_parent) const { - if (p_parent==this) + if (p_parent == this) return Transform2D(); Node2D *parent_2d = get_parent()->cast_to(); - ERR_FAIL_COND_V(!parent_2d,Transform2D()); - if (p_parent==parent_2d) + ERR_FAIL_COND_V(!parent_2d, Transform2D()); + if (p_parent == parent_2d) return get_transform(); else return parent_2d->get_relative_transform_to_parent(p_parent) * get_transform(); } - -void Node2D::look_at(const Vector2& p_pos) { +void Node2D::look_at(const Vector2 &p_pos) { rotate(get_angle_to(p_pos)); } -float Node2D::get_angle_to(const Vector2& p_pos) const { +float Node2D::get_angle_to(const Vector2 &p_pos) const { return (get_global_transform().affine_inverse().xform(p_pos)).angle(); } void Node2D::_bind_methods() { - // TODO: Obsolete those two methods (old name) properly (GH-4397) - ClassDB::bind_method(D_METHOD("_get_rotd"),&Node2D::_get_rotd); - ClassDB::bind_method(D_METHOD("_set_rotd","degrees"),&Node2D::_set_rotd); - - ClassDB::bind_method(D_METHOD("set_position","pos"),&Node2D::set_position); - ClassDB::bind_method(D_METHOD("set_rotation","radians"),&Node2D::set_rotation); - ClassDB::bind_method(D_METHOD("set_rotation_in_degrees","degrees"),&Node2D::set_rotation_in_degrees); - ClassDB::bind_method(D_METHOD("set_scale","scale"),&Node2D::set_scale); - - ClassDB::bind_method(D_METHOD("get_position"),&Node2D::get_position); - ClassDB::bind_method(D_METHOD("get_rotation"),&Node2D::get_rotation); - ClassDB::bind_method(D_METHOD("get_rotation_in_degrees"),&Node2D::get_rotation_in_degrees); - ClassDB::bind_method(D_METHOD("get_scale"),&Node2D::get_scale); + ClassDB::bind_method(D_METHOD("_get_rotd"), &Node2D::_get_rotd); + ClassDB::bind_method(D_METHOD("_set_rotd", "degrees"), &Node2D::_set_rotd); - ClassDB::bind_method(D_METHOD("rotate","radians"),&Node2D::rotate); - ClassDB::bind_method(D_METHOD("move_local_x","delta","scaled"),&Node2D::move_x,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("move_local_y","delta","scaled"),&Node2D::move_y,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("translate","offset"),&Node2D::translate); - ClassDB::bind_method(D_METHOD("global_translate","offset"),&Node2D::global_translate); - ClassDB::bind_method(D_METHOD("scale","ratio"),&Node2D::scale); + ClassDB::bind_method(D_METHOD("set_position", "pos"), &Node2D::set_position); + ClassDB::bind_method(D_METHOD("set_rotation", "radians"), &Node2D::set_rotation); + ClassDB::bind_method(D_METHOD("set_rotation_in_degrees", "degrees"), &Node2D::set_rotation_in_degrees); + ClassDB::bind_method(D_METHOD("set_scale", "scale"), &Node2D::set_scale); - ClassDB::bind_method(D_METHOD("set_global_position","pos"),&Node2D::set_global_position); - ClassDB::bind_method(D_METHOD("get_global_position"),&Node2D::get_global_position); - ClassDB::bind_method(D_METHOD("set_global_rotation","radians"),&Node2D::set_global_rotation); - ClassDB::bind_method(D_METHOD("get_global_rotation"),&Node2D::get_global_rotation); - ClassDB::bind_method(D_METHOD("set_global_rotation_in_degrees","degrees"),&Node2D::set_global_rotation_in_degrees); - ClassDB::bind_method(D_METHOD("get_global_rotation_in_degrees"),&Node2D::get_global_rotation_in_degrees); - ClassDB::bind_method(D_METHOD("set_global_scale","scale"),&Node2D::set_global_scale); - ClassDB::bind_method(D_METHOD("get_global_scale"),&Node2D::get_global_scale); + ClassDB::bind_method(D_METHOD("get_position"), &Node2D::get_position); + ClassDB::bind_method(D_METHOD("get_rotation"), &Node2D::get_rotation); + ClassDB::bind_method(D_METHOD("get_rotation_in_degrees"), &Node2D::get_rotation_in_degrees); + ClassDB::bind_method(D_METHOD("get_scale"), &Node2D::get_scale); - ClassDB::bind_method(D_METHOD("set_transform","xform"),&Node2D::set_transform); - ClassDB::bind_method(D_METHOD("set_global_transform","xform"),&Node2D::set_global_transform); + ClassDB::bind_method(D_METHOD("rotate", "radians"), &Node2D::rotate); + ClassDB::bind_method(D_METHOD("move_local_x", "delta", "scaled"), &Node2D::move_x, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("move_local_y", "delta", "scaled"), &Node2D::move_y, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("translate", "offset"), &Node2D::translate); + ClassDB::bind_method(D_METHOD("global_translate", "offset"), &Node2D::global_translate); + ClassDB::bind_method(D_METHOD("scale", "ratio"), &Node2D::scale); - ClassDB::bind_method(D_METHOD("look_at","point"),&Node2D::look_at); - ClassDB::bind_method(D_METHOD("get_angle_to","point"),&Node2D::get_angle_to); + ClassDB::bind_method(D_METHOD("set_global_position", "pos"), &Node2D::set_global_position); + ClassDB::bind_method(D_METHOD("get_global_position"), &Node2D::get_global_position); + ClassDB::bind_method(D_METHOD("set_global_rotation", "radians"), &Node2D::set_global_rotation); + ClassDB::bind_method(D_METHOD("get_global_rotation"), &Node2D::get_global_rotation); + ClassDB::bind_method(D_METHOD("set_global_rotation_in_degrees", "degrees"), &Node2D::set_global_rotation_in_degrees); + ClassDB::bind_method(D_METHOD("get_global_rotation_in_degrees"), &Node2D::get_global_rotation_in_degrees); + ClassDB::bind_method(D_METHOD("set_global_scale", "scale"), &Node2D::set_global_scale); + ClassDB::bind_method(D_METHOD("get_global_scale"), &Node2D::get_global_scale); - ClassDB::bind_method(D_METHOD("set_z","z"),&Node2D::set_z); - ClassDB::bind_method(D_METHOD("get_z"),&Node2D::get_z); + ClassDB::bind_method(D_METHOD("set_transform", "xform"), &Node2D::set_transform); + ClassDB::bind_method(D_METHOD("set_global_transform", "xform"), &Node2D::set_global_transform); - ClassDB::bind_method(D_METHOD("set_z_as_relative","enable"),&Node2D::set_z_as_relative); - ClassDB::bind_method(D_METHOD("is_z_relative"),&Node2D::is_z_relative); + ClassDB::bind_method(D_METHOD("look_at", "point"), &Node2D::look_at); + ClassDB::bind_method(D_METHOD("get_angle_to", "point"), &Node2D::get_angle_to); - ClassDB::bind_method(D_METHOD("edit_set_pivot","pivot"),&Node2D::edit_set_pivot); + ClassDB::bind_method(D_METHOD("set_z", "z"), &Node2D::set_z); + ClassDB::bind_method(D_METHOD("get_z"), &Node2D::get_z); - ClassDB::bind_method(D_METHOD("get_relative_transform_to_parent","parent"),&Node2D::get_relative_transform_to_parent); + ClassDB::bind_method(D_METHOD("set_z_as_relative", "enable"), &Node2D::set_z_as_relative); + ClassDB::bind_method(D_METHOD("is_z_relative"), &Node2D::is_z_relative); - ADD_GROUP("Transform",""); - ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2,"position"),"set_position","get_position"); - ADD_PROPERTYNZ(PropertyInfo(Variant::REAL,"rotation",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_rotation","get_rotation"); - ADD_PROPERTYNZ(PropertyInfo(Variant::REAL,"rotation_deg",PROPERTY_HINT_RANGE,"-1440,1440,0.1",PROPERTY_USAGE_EDITOR),"set_rotation_in_degrees","get_rotation_in_degrees"); - ADD_PROPERTYNO(PropertyInfo(Variant::VECTOR2,"scale"),"set_scale","get_scale"); - ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D,"transform",PROPERTY_HINT_NONE,"",0),"set_transform","get_transform"); + ClassDB::bind_method(D_METHOD("edit_set_pivot", "pivot"), &Node2D::edit_set_pivot); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"global_position",PROPERTY_HINT_NONE,"",0),"set_global_position","get_global_position"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"global_rotation",PROPERTY_HINT_NONE,"",0),"set_global_rotation","get_global_rotation"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"global_rotation_deg",PROPERTY_HINT_NONE,"",0),"set_global_rotation_in_degrees","get_global_rotation_in_degrees"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"global_scale",PROPERTY_HINT_NONE,"",0),"set_global_scale","get_global_scale"); - ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D,"global_transform",PROPERTY_HINT_NONE,"",0),"set_global_transform","get_global_transform"); + ClassDB::bind_method(D_METHOD("get_relative_transform_to_parent", "parent"), &Node2D::get_relative_transform_to_parent); - ADD_GROUP("Z",""); - ADD_PROPERTYNZ(PropertyInfo(Variant::INT,"z",PROPERTY_HINT_RANGE,itos(VS::CANVAS_ITEM_Z_MIN)+","+itos(VS::CANVAS_ITEM_Z_MAX)+",1"),"set_z","get_z"); - ADD_PROPERTYNO(PropertyInfo(Variant::BOOL,"z_as_relative"),"set_z_as_relative","is_z_relative"); + ADD_GROUP("Transform", ""); + ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "position"), "set_position", "get_position"); + ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_rotation", "get_rotation"); + ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "rotation_deg", PROPERTY_HINT_RANGE, "-1440,1440,0.1", PROPERTY_USAGE_EDITOR), "set_rotation_in_degrees", "get_rotation_in_degrees"); + ADD_PROPERTYNO(PropertyInfo(Variant::VECTOR2, "scale"), "set_scale", "get_scale"); + ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "transform", PROPERTY_HINT_NONE, "", 0), "set_transform", "get_transform"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "global_position", PROPERTY_HINT_NONE, "", 0), "set_global_position", "get_global_position"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "global_rotation", PROPERTY_HINT_NONE, "", 0), "set_global_rotation", "get_global_rotation"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "global_rotation_deg", PROPERTY_HINT_NONE, "", 0), "set_global_rotation_in_degrees", "get_global_rotation_in_degrees"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "global_scale", PROPERTY_HINT_NONE, "", 0), "set_global_scale", "get_global_scale"); + ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "global_transform", PROPERTY_HINT_NONE, "", 0), "set_global_transform", "get_global_transform"); + ADD_GROUP("Z", ""); + ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "z", PROPERTY_HINT_RANGE, itos(VS::CANVAS_ITEM_Z_MIN) + "," + itos(VS::CANVAS_ITEM_Z_MAX) + ",1"), "set_z", "get_z"); + ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "z_as_relative"), "set_z_as_relative", "is_z_relative"); } - Node2D::Node2D() { - - angle=0; - _scale=Vector2(1,1); - _xform_dirty=false; - z=0; - z_relative=true; - + angle = 0; + _scale = Vector2(1, 1); + _xform_dirty = false; + z = 0; + z_relative = true; } - diff --git a/scene/2d/node_2d.h b/scene/2d/node_2d.h index 2cceef0f0..b9c689433 100644 --- a/scene/2d/node_2d.h +++ b/scene/2d/node_2d.h @@ -33,7 +33,7 @@ class Node2D : public CanvasItem { - GDCLASS(Node2D, CanvasItem ); + GDCLASS(Node2D, CanvasItem); Point2 pos; float angle; @@ -54,32 +54,30 @@ class Node2D : public CanvasItem { void _update_xform_values(); protected: - - void _notification(int p_what); static void _bind_methods(); -public: +public: virtual Variant edit_get_state() const; - virtual void edit_set_state(const Variant& p_state); - virtual void edit_set_rect(const Rect2& p_edit_rect); + virtual void edit_set_state(const Variant &p_state); + virtual void edit_set_rect(const Rect2 &p_edit_rect); virtual void edit_rotate(float p_rot); - virtual void edit_set_pivot(const Point2& p_pivot); + virtual void edit_set_pivot(const Point2 &p_pivot); virtual Point2 edit_get_pivot() const; virtual bool edit_has_pivot() const; - void set_position(const Point2& p_pos); + void set_position(const Point2 &p_pos); void set_rotation(float p_radians); void set_rotation_in_degrees(float p_degrees); - void set_scale(const Size2& p_scale); + void set_scale(const Size2 &p_scale); void rotate(float p_radians); - void move_x(float p_delta,bool p_scaled=false); - void move_y(float p_delta,bool p_scaled=false); - void translate(const Vector2& p_amount); - void global_translate(const Vector2& p_amount); - void scale(const Size2& p_amount); + void move_x(float p_delta, bool p_scaled = false); + void move_y(float p_delta, bool p_scaled = false); + void translate(const Vector2 &p_amount); + void global_translate(const Vector2 &p_amount); + void scale(const Size2 &p_amount); Point2 get_position() const; float get_rotation() const; @@ -92,18 +90,18 @@ public: Size2 get_global_scale() const; virtual Rect2 get_item_rect() const; - void set_transform(const Transform2D& p_transform); - void set_global_transform(const Transform2D& p_transform); - void set_global_position(const Point2& p_pos); + void set_transform(const Transform2D &p_transform); + void set_global_transform(const Transform2D &p_transform); + void set_global_position(const Point2 &p_pos); void set_global_rotation(float p_radians); void set_global_rotation_in_degrees(float p_degrees); - void set_global_scale(const Size2& p_scale); + void set_global_scale(const Size2 &p_scale); void set_z(int p_z); int get_z() const; - void look_at(const Vector2& p_pos); - float get_angle_to(const Vector2& p_pos) const; + void look_at(const Vector2 &p_pos); + float get_angle_to(const Vector2 &p_pos) const; void set_z_as_relative(bool p_enabled); bool is_z_relative() const; diff --git a/scene/2d/parallax_background.cpp b/scene/2d/parallax_background.cpp index 9336dc51a..17bc26aa7 100644 --- a/scene/2d/parallax_background.cpp +++ b/scene/2d/parallax_background.cpp @@ -29,16 +29,13 @@ #include "parallax_background.h" #include "parallax_layer.h" - - void ParallaxBackground::_notification(int p_what) { - switch(p_what) { - + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - group_name = "__cameras_"+itos(get_viewport().get_id()); + group_name = "__cameras_" + itos(get_viewport().get_id()); add_to_group(group_name); } break; @@ -47,31 +44,27 @@ void ParallaxBackground::_notification(int p_what) { remove_from_group(group_name); } break; } - } -void ParallaxBackground::_camera_moved(const Transform2D& p_transform) { - +void ParallaxBackground::_camera_moved(const Transform2D &p_transform) { set_scroll_offset(p_transform.get_origin()); - set_scroll_scale(p_transform.get_scale().dot(Vector2(0.5,0.5))); + set_scroll_scale(p_transform.get_scale().dot(Vector2(0.5, 0.5))); } - void ParallaxBackground::set_scroll_scale(float p_scale) { - scale=p_scale; + scale = p_scale; } -float ParallaxBackground::get_scroll_scale() const{ +float ParallaxBackground::get_scroll_scale() const { return scale; } +void ParallaxBackground::set_scroll_offset(const Point2 &p_ofs) { -void ParallaxBackground::set_scroll_offset(const Point2& p_ofs) { - - offset=p_ofs; + offset = p_ofs; _update_scroll(); } @@ -81,7 +74,7 @@ void ParallaxBackground::_update_scroll() { if (!is_inside_tree()) return; - Vector2 ofs = base_offset+offset*base_scale; + Vector2 ofs = base_offset + offset * base_scale; Size2 vps = get_viewport_size(); @@ -89,26 +82,25 @@ void ParallaxBackground::_update_scroll() { if (limit_begin.x < limit_end.x) { if (ofs.x < limit_begin.x) - ofs.x=limit_begin.x; - else if (ofs.x+vps.x > limit_end.x) - ofs.x=limit_end.x-vps.x; + ofs.x = limit_begin.x; + else if (ofs.x + vps.x > limit_end.x) + ofs.x = limit_end.x - vps.x; } - if (limit_begin.y < limit_end.y) { if (ofs.y < limit_begin.y) - ofs.y=limit_begin.y; - else if (ofs.y+vps.y > limit_end.y) - ofs.y=limit_end.y-vps.y; + ofs.y = limit_begin.y; + else if (ofs.y + vps.y > limit_end.y) + ofs.y = limit_end.y - vps.y; } ofs = -ofs; - final_offset=ofs; + final_offset = ofs; - for(int i=0;icast_to(); + ParallaxLayer *l = get_child(i)->cast_to(); if (!l) continue; @@ -124,32 +116,31 @@ Point2 ParallaxBackground::get_scroll_offset() const { return offset; } -void ParallaxBackground::set_scroll_base_offset(const Point2& p_ofs) { +void ParallaxBackground::set_scroll_base_offset(const Point2 &p_ofs) { - base_offset=p_ofs; + base_offset = p_ofs; _update_scroll(); } -Point2 ParallaxBackground::get_scroll_base_offset() const{ +Point2 ParallaxBackground::get_scroll_base_offset() const { return base_offset; } -void ParallaxBackground::set_scroll_base_scale(const Point2& p_ofs) { +void ParallaxBackground::set_scroll_base_scale(const Point2 &p_ofs) { - base_scale=p_ofs; + base_scale = p_ofs; _update_scroll(); } -Point2 ParallaxBackground::get_scroll_base_scale() const{ +Point2 ParallaxBackground::get_scroll_base_scale() const { return base_scale; } +void ParallaxBackground::set_limit_begin(const Point2 &p_ofs) { -void ParallaxBackground::set_limit_begin(const Point2& p_ofs) { - - limit_begin=p_ofs; + limit_begin = p_ofs; _update_scroll(); } @@ -158,11 +149,10 @@ Point2 ParallaxBackground::get_limit_begin() const { return limit_begin; } -void ParallaxBackground::set_limit_end(const Point2& p_ofs) { +void ParallaxBackground::set_limit_end(const Point2 &p_ofs) { - limit_end=p_ofs; + limit_end = p_ofs; _update_scroll(); - } Point2 ParallaxBackground::get_limit_end() const { @@ -170,16 +160,14 @@ Point2 ParallaxBackground::get_limit_end() const { return limit_end; } -void ParallaxBackground::set_ignore_camera_zoom(bool ignore){ - - ignore_camera_zoom = ignore; +void ParallaxBackground::set_ignore_camera_zoom(bool ignore) { + ignore_camera_zoom = ignore; } -bool ParallaxBackground::is_ignore_camera_zoom(){ - - return ignore_camera_zoom; +bool ParallaxBackground::is_ignore_camera_zoom() { + return ignore_camera_zoom; } Vector2 ParallaxBackground::get_final_offset() const { @@ -189,38 +177,32 @@ Vector2 ParallaxBackground::get_final_offset() const { void ParallaxBackground::_bind_methods() { - ClassDB::bind_method(D_METHOD("_camera_moved"),&ParallaxBackground::_camera_moved); - ClassDB::bind_method(D_METHOD("set_scroll_offset","ofs"),&ParallaxBackground::set_scroll_offset); - ClassDB::bind_method(D_METHOD("get_scroll_offset"),&ParallaxBackground::get_scroll_offset); - ClassDB::bind_method(D_METHOD("set_scroll_base_offset","ofs"),&ParallaxBackground::set_scroll_base_offset); - ClassDB::bind_method(D_METHOD("get_scroll_base_offset"),&ParallaxBackground::get_scroll_base_offset); - ClassDB::bind_method(D_METHOD("set_scroll_base_scale","scale"),&ParallaxBackground::set_scroll_base_scale); - ClassDB::bind_method(D_METHOD("get_scroll_base_scale"),&ParallaxBackground::get_scroll_base_scale); - ClassDB::bind_method(D_METHOD("set_limit_begin","ofs"),&ParallaxBackground::set_limit_begin); - ClassDB::bind_method(D_METHOD("get_limit_begin"),&ParallaxBackground::get_limit_begin); - ClassDB::bind_method(D_METHOD("set_limit_end","ofs"),&ParallaxBackground::set_limit_end); - ClassDB::bind_method(D_METHOD("get_limit_end"),&ParallaxBackground::get_limit_end); - ClassDB::bind_method(D_METHOD("set_ignore_camera_zoom","ignore"), &ParallaxBackground::set_ignore_camera_zoom); - ClassDB::bind_method(D_METHOD("is_ignore_camera_zoom"), &ParallaxBackground::is_ignore_camera_zoom); - - - ADD_GROUP("Scroll","scroll_"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_offset"),"set_scroll_offset","get_scroll_offset"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_base_offset"),"set_scroll_base_offset","get_scroll_base_offset"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_base_scale"),"set_scroll_base_scale","get_scroll_base_scale"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_limit_begin"),"set_limit_begin","get_limit_begin"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_limit_end"),"set_limit_end","get_limit_end"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL, "scroll_ignore_camera_zoom"), "set_ignore_camera_zoom", "is_ignore_camera_zoom"); - + ClassDB::bind_method(D_METHOD("_camera_moved"), &ParallaxBackground::_camera_moved); + ClassDB::bind_method(D_METHOD("set_scroll_offset", "ofs"), &ParallaxBackground::set_scroll_offset); + ClassDB::bind_method(D_METHOD("get_scroll_offset"), &ParallaxBackground::get_scroll_offset); + ClassDB::bind_method(D_METHOD("set_scroll_base_offset", "ofs"), &ParallaxBackground::set_scroll_base_offset); + ClassDB::bind_method(D_METHOD("get_scroll_base_offset"), &ParallaxBackground::get_scroll_base_offset); + ClassDB::bind_method(D_METHOD("set_scroll_base_scale", "scale"), &ParallaxBackground::set_scroll_base_scale); + ClassDB::bind_method(D_METHOD("get_scroll_base_scale"), &ParallaxBackground::get_scroll_base_scale); + ClassDB::bind_method(D_METHOD("set_limit_begin", "ofs"), &ParallaxBackground::set_limit_begin); + ClassDB::bind_method(D_METHOD("get_limit_begin"), &ParallaxBackground::get_limit_begin); + ClassDB::bind_method(D_METHOD("set_limit_end", "ofs"), &ParallaxBackground::set_limit_end); + ClassDB::bind_method(D_METHOD("get_limit_end"), &ParallaxBackground::get_limit_end); + ClassDB::bind_method(D_METHOD("set_ignore_camera_zoom", "ignore"), &ParallaxBackground::set_ignore_camera_zoom); + ClassDB::bind_method(D_METHOD("is_ignore_camera_zoom"), &ParallaxBackground::is_ignore_camera_zoom); + + ADD_GROUP("Scroll", "scroll_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_offset"), "set_scroll_offset", "get_scroll_offset"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_base_offset"), "set_scroll_base_offset", "get_scroll_base_offset"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_base_scale"), "set_scroll_base_scale", "get_scroll_base_scale"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_limit_begin"), "set_limit_begin", "get_limit_begin"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_limit_end"), "set_limit_end", "get_limit_end"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "scroll_ignore_camera_zoom"), "set_ignore_camera_zoom", "is_ignore_camera_zoom"); } - - - - ParallaxBackground::ParallaxBackground() { - base_scale=Vector2(1,1); - scale=1.0; + base_scale = Vector2(1, 1); + scale = 1.0; set_layer(-1); //behind all by default } diff --git a/scene/2d/parallax_background.h b/scene/2d/parallax_background.h index caef4962e..5914c21c9 100644 --- a/scene/2d/parallax_background.h +++ b/scene/2d/parallax_background.h @@ -29,13 +29,13 @@ #ifndef PARALLAX_BACKGROUND_H #define PARALLAX_BACKGROUND_H -#include "scene/main/canvas_layer.h" -#include "scene/2d/node_2d.h" #include "scene/2d/camera_2d.h" +#include "scene/2d/node_2d.h" +#include "scene/main/canvas_layer.h" class ParallaxBackground : public CanvasLayer { - GDCLASS( ParallaxBackground, CanvasLayer ); + GDCLASS(ParallaxBackground, CanvasLayer); Point2 offset; float scale; @@ -48,30 +48,30 @@ class ParallaxBackground : public CanvasLayer { bool ignore_camera_zoom; void _update_scroll(); -protected: - void _camera_moved(const Transform2D& p_transform); +protected: + void _camera_moved(const Transform2D &p_transform); void _notification(int p_what); static void _bind_methods(); -public: - void set_scroll_offset(const Point2& p_ofs); +public: + void set_scroll_offset(const Point2 &p_ofs); Point2 get_scroll_offset() const; void set_scroll_scale(float p_ofs); float get_scroll_scale() const; - void set_scroll_base_offset(const Point2& p_ofs); + void set_scroll_base_offset(const Point2 &p_ofs); Point2 get_scroll_base_offset() const; - void set_scroll_base_scale(const Point2& p_ofs); + void set_scroll_base_scale(const Point2 &p_ofs); Point2 get_scroll_base_scale() const; - void set_limit_begin(const Point2& p_ofs); + void set_limit_begin(const Point2 &p_ofs); Point2 get_limit_begin() const; - void set_limit_end(const Point2& p_ofs); + void set_limit_end(const Point2 &p_ofs); Point2 get_limit_end() const; void set_ignore_camera_zoom(bool ignore); diff --git a/scene/2d/parallax_layer.cpp b/scene/2d/parallax_layer.cpp index 37d8fb52f..238723460 100644 --- a/scene/2d/parallax_layer.cpp +++ b/scene/2d/parallax_layer.cpp @@ -29,42 +29,38 @@ #include "parallax_layer.h" #include "parallax_background.h" -void ParallaxLayer::set_motion_scale(const Size2& p_scale) { - - motion_scale=p_scale; +void ParallaxLayer::set_motion_scale(const Size2 &p_scale) { + motion_scale = p_scale; ParallaxBackground *pb = get_parent()->cast_to(); if (is_inside_tree() && pb) { Vector2 ofs = pb->get_final_offset(); float scale = pb->get_scroll_scale(); - set_base_offset_and_scale(ofs,scale); + set_base_offset_and_scale(ofs, scale); } - } Size2 ParallaxLayer::get_motion_scale() const { return motion_scale; - } -void ParallaxLayer::set_motion_offset(const Size2& p_offset) { +void ParallaxLayer::set_motion_offset(const Size2 &p_offset) { - motion_offset=p_offset; + motion_offset = p_offset; ParallaxBackground *pb = get_parent()->cast_to(); if (is_inside_tree() && pb) { Vector2 ofs = pb->get_final_offset(); float scale = pb->get_scroll_scale(); - set_base_offset_and_scale(ofs,scale); + set_base_offset_and_scale(ofs, scale); } } Size2 ParallaxLayer::get_motion_offset() const { return motion_offset; - } void ParallaxLayer::_update_mirroring() { @@ -77,68 +73,61 @@ void ParallaxLayer::_update_mirroring() { RID c = pb->get_world_2d()->get_canvas(); RID ci = get_canvas_item(); - VisualServer::get_singleton()->canvas_set_item_mirroring(c,ci,mirroring); + VisualServer::get_singleton()->canvas_set_item_mirroring(c, ci, mirroring); } - } -void ParallaxLayer::set_mirroring(const Size2& p_mirroring) { +void ParallaxLayer::set_mirroring(const Size2 &p_mirroring) { - mirroring=p_mirroring; - if (mirroring.x<0) - mirroring.x=0; - if (mirroring.y<0) - mirroring.y=0; + mirroring = p_mirroring; + if (mirroring.x < 0) + mirroring.x = 0; + if (mirroring.y < 0) + mirroring.y = 0; _update_mirroring(); - } -Size2 ParallaxLayer::get_mirroring() const{ +Size2 ParallaxLayer::get_mirroring() const { return mirroring; } - - void ParallaxLayer::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - orig_offset=get_position(); - orig_scale=get_scale(); + orig_offset = get_position(); + orig_scale = get_scale(); _update_mirroring(); } break; } } -void ParallaxLayer::set_base_offset_and_scale(const Point2& p_offset,float p_scale) { +void ParallaxLayer::set_base_offset_and_scale(const Point2 &p_offset, float p_scale) { if (!is_inside_tree()) return; if (get_tree()->is_editor_hint()) return; - Point2 new_ofs = ((orig_offset+p_offset)*motion_scale)*p_scale+motion_offset; + Point2 new_ofs = ((orig_offset + p_offset) * motion_scale) * p_scale + motion_offset; if (mirroring.x) { - double den = mirroring.x*p_scale; - new_ofs.x -= den*ceil(new_ofs.x/den); + double den = mirroring.x * p_scale; + new_ofs.x -= den * ceil(new_ofs.x / den); } if (mirroring.y) { - double den = mirroring.y*p_scale; - new_ofs.y -= den*ceil(new_ofs.y/den); + double den = mirroring.y * p_scale; + new_ofs.y -= den * ceil(new_ofs.y / den); } set_position(new_ofs); - set_scale(Vector2(1,1)*p_scale); - - + set_scale(Vector2(1, 1) * p_scale); } - String ParallaxLayer::get_configuration_warning() const { if (!get_parent() || !get_parent()->cast_to()) { @@ -150,23 +139,19 @@ String ParallaxLayer::get_configuration_warning() const { void ParallaxLayer::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_motion_scale","scale"),&ParallaxLayer::set_motion_scale); - ClassDB::bind_method(D_METHOD("get_motion_scale"),&ParallaxLayer::get_motion_scale); - ClassDB::bind_method(D_METHOD("set_motion_offset","offset"),&ParallaxLayer::set_motion_offset); - ClassDB::bind_method(D_METHOD("get_motion_offset"),&ParallaxLayer::get_motion_offset); - ClassDB::bind_method(D_METHOD("set_mirroring","mirror"),&ParallaxLayer::set_mirroring); - ClassDB::bind_method(D_METHOD("get_mirroring"),&ParallaxLayer::get_mirroring); - - ADD_GROUP("Motion","motion_"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"motion_scale"),"set_motion_scale","get_motion_scale"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"motion_offset"),"set_motion_offset","get_motion_offset"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"motion_mirroring"),"set_mirroring","get_mirroring"); - + ClassDB::bind_method(D_METHOD("set_motion_scale", "scale"), &ParallaxLayer::set_motion_scale); + ClassDB::bind_method(D_METHOD("get_motion_scale"), &ParallaxLayer::get_motion_scale); + ClassDB::bind_method(D_METHOD("set_motion_offset", "offset"), &ParallaxLayer::set_motion_offset); + ClassDB::bind_method(D_METHOD("get_motion_offset"), &ParallaxLayer::get_motion_offset); + ClassDB::bind_method(D_METHOD("set_mirroring", "mirror"), &ParallaxLayer::set_mirroring); + ClassDB::bind_method(D_METHOD("get_mirroring"), &ParallaxLayer::get_mirroring); + + ADD_GROUP("Motion", "motion_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "motion_scale"), "set_motion_scale", "get_motion_scale"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "motion_offset"), "set_motion_offset", "get_motion_offset"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "motion_mirroring"), "set_mirroring", "get_mirroring"); } - - -ParallaxLayer::ParallaxLayer() -{ - motion_scale=Size2(1,1); +ParallaxLayer::ParallaxLayer() { + motion_scale = Size2(1, 1); } diff --git a/scene/2d/parallax_layer.h b/scene/2d/parallax_layer.h index 1b3d67af5..01293e85a 100644 --- a/scene/2d/parallax_layer.h +++ b/scene/2d/parallax_layer.h @@ -33,7 +33,7 @@ class ParallaxLayer : public Node2D { - GDCLASS( ParallaxLayer, Node2D ); + GDCLASS(ParallaxLayer, Node2D); Point2 orig_offset; Point2 orig_scale; @@ -43,22 +43,20 @@ class ParallaxLayer : public Node2D { void _update_mirroring(); protected: - void _notification(int p_what); static void _bind_methods(); public: - - void set_motion_offset(const Size2& p_scale); + void set_motion_offset(const Size2 &p_scale); Size2 get_motion_offset() const; - void set_motion_scale(const Size2& p_scale); + void set_motion_scale(const Size2 &p_scale); Size2 get_motion_scale() const; - void set_mirroring(const Size2& p_mirroring); + void set_mirroring(const Size2 &p_mirroring); Size2 get_mirroring() const; - void set_base_offset_and_scale(const Point2& p_offsetf,float p_scale); + void set_base_offset_and_scale(const Point2 &p_offsetf, float p_scale); virtual String get_configuration_warning() const; ParallaxLayer(); diff --git a/scene/2d/particles_2d.cpp b/scene/2d/particles_2d.cpp index 77ace0348..c9d5bebe5 100644 --- a/scene/2d/particles_2d.cpp +++ b/scene/2d/particles_2d.cpp @@ -29,11 +29,9 @@ #include "particles_2d.h" #include "scene/scene_string_names.h" - - void ParticleAttractor2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { @@ -46,16 +44,16 @@ void ParticleAttractor2D::_notification(int p_what) { return; Vector2 pv; - float dr = MIN(disable_radius,radius); - for(int i=0;i<=32;i++) { - Vector2 v(Math::sin(i/32.0*Math_PI*2),Math::cos(i/32.0*Math_PI*2)); - if (i>0) { - draw_line(pv*radius,v*radius,Color(0,0,0.5,0.9)); - if (dr>0) { - draw_line(pv*dr,v*dr,Color(0.5,0,0.0,0.9)); + float dr = MIN(disable_radius, radius); + for (int i = 0; i <= 32; i++) { + Vector2 v(Math::sin(i / 32.0 * Math_PI * 2), Math::cos(i / 32.0 * Math_PI * 2)); + if (i > 0) { + draw_line(pv * radius, v * radius, Color(0, 0, 0.5, 0.9)); + if (dr > 0) { + draw_line(pv * dr, v * dr, Color(0.5, 0, 0.0, 0.9)); } } - pv=v; + pv = v; } } break; @@ -72,7 +70,7 @@ void ParticleAttractor2D::_owner_exited() { ERR_FAIL_COND(!owner); owner->attractors.erase(this); - owner=NULL; + owner = NULL; } void ParticleAttractor2D::_update_owner() { @@ -93,63 +91,59 @@ void ParticleAttractor2D::_update_owner() { _set_owner(pn); } -void ParticleAttractor2D::_set_owner(Particles2D* p_owner) { +void ParticleAttractor2D::_set_owner(Particles2D *p_owner) { - if (owner==p_owner) + if (owner == p_owner) return; if (owner) { - owner->disconnect("tree_exited",this,"_owner_exited"); + owner->disconnect("tree_exited", this, "_owner_exited"); owner->attractors.erase(this); - owner=NULL; + owner = NULL; } - owner=p_owner; + owner = p_owner; if (owner) { - owner->connect("tree_exited",this,"_owner_exited",varray(),CONNECT_ONESHOT); + owner->connect("tree_exited", this, "_owner_exited", varray(), CONNECT_ONESHOT); owner->attractors.insert(this); } } void ParticleAttractor2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&ParticleAttractor2D::set_enabled); - ClassDB::bind_method(D_METHOD("is_enabled"),&ParticleAttractor2D::is_enabled); - - ClassDB::bind_method(D_METHOD("set_radius","radius"),&ParticleAttractor2D::set_radius); - ClassDB::bind_method(D_METHOD("get_radius"),&ParticleAttractor2D::get_radius); - - ClassDB::bind_method(D_METHOD("set_disable_radius","radius"),&ParticleAttractor2D::set_disable_radius); - ClassDB::bind_method(D_METHOD("get_disable_radius"),&ParticleAttractor2D::get_disable_radius); + ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &ParticleAttractor2D::set_enabled); + ClassDB::bind_method(D_METHOD("is_enabled"), &ParticleAttractor2D::is_enabled); - ClassDB::bind_method(D_METHOD("set_gravity","gravity"),&ParticleAttractor2D::set_gravity); - ClassDB::bind_method(D_METHOD("get_gravity"),&ParticleAttractor2D::get_gravity); + ClassDB::bind_method(D_METHOD("set_radius", "radius"), &ParticleAttractor2D::set_radius); + ClassDB::bind_method(D_METHOD("get_radius"), &ParticleAttractor2D::get_radius); - ClassDB::bind_method(D_METHOD("set_absorption","absorption"),&ParticleAttractor2D::set_absorption); - ClassDB::bind_method(D_METHOD("get_absorption"),&ParticleAttractor2D::get_absorption); + ClassDB::bind_method(D_METHOD("set_disable_radius", "radius"), &ParticleAttractor2D::set_disable_radius); + ClassDB::bind_method(D_METHOD("get_disable_radius"), &ParticleAttractor2D::get_disable_radius); - ClassDB::bind_method(D_METHOD("set_particles_path","path"),&ParticleAttractor2D::set_particles_path); - ClassDB::bind_method(D_METHOD("get_particles_path"),&ParticleAttractor2D::get_particles_path); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"radius",PROPERTY_HINT_RANGE,"0.1,16000,0.1"),"set_radius","get_radius"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"disable_radius",PROPERTY_HINT_RANGE,"0.1,16000,0.1"),"set_disable_radius","get_disable_radius"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"gravity",PROPERTY_HINT_RANGE,"-512,512,0.01"),"set_gravity","get_gravity"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"absorption",PROPERTY_HINT_RANGE,"0,512,0.01"),"set_absorption","get_absorption"); - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH,"particles_path",PROPERTY_HINT_RESOURCE_TYPE,"Particles2D"),"set_particles_path","get_particles_path"); + ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &ParticleAttractor2D::set_gravity); + ClassDB::bind_method(D_METHOD("get_gravity"), &ParticleAttractor2D::get_gravity); + ClassDB::bind_method(D_METHOD("set_absorption", "absorption"), &ParticleAttractor2D::set_absorption); + ClassDB::bind_method(D_METHOD("get_absorption"), &ParticleAttractor2D::get_absorption); + ClassDB::bind_method(D_METHOD("set_particles_path", "path"), &ParticleAttractor2D::set_particles_path); + ClassDB::bind_method(D_METHOD("get_particles_path"), &ParticleAttractor2D::get_particles_path); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0.1,16000,0.1"), "set_radius", "get_radius"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "disable_radius", PROPERTY_HINT_RANGE, "0.1,16000,0.1"), "set_disable_radius", "get_disable_radius"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity", PROPERTY_HINT_RANGE, "-512,512,0.01"), "set_gravity", "get_gravity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "absorption", PROPERTY_HINT_RANGE, "0,512,0.01"), "set_absorption", "get_absorption"); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "particles_path", PROPERTY_HINT_RESOURCE_TYPE, "Particles2D"), "set_particles_path", "get_particles_path"); } - void ParticleAttractor2D::set_enabled(bool p_enabled) { - enabled=p_enabled; + enabled = p_enabled; } -bool ParticleAttractor2D::is_enabled() const{ +bool ParticleAttractor2D::is_enabled() const { return enabled; } @@ -177,8 +171,7 @@ float ParticleAttractor2D::get_disable_radius() const { void ParticleAttractor2D::set_gravity(float p_gravity) { - gravity=p_gravity; - + gravity = p_gravity; } float ParticleAttractor2D::get_gravity() const { @@ -187,8 +180,7 @@ float ParticleAttractor2D::get_gravity() const { void ParticleAttractor2D::set_absorption(float p_absorption) { - absorption=p_absorption; - + absorption = p_absorption; } float ParticleAttractor2D::get_absorption() const { @@ -197,7 +189,7 @@ float ParticleAttractor2D::get_absorption() const { void ParticleAttractor2D::set_particles_path(NodePath p_path) { - path=p_path; + path = p_path; _update_owner(); update_configuration_warning(); } @@ -217,13 +209,13 @@ String ParticleAttractor2D::get_configuration_warning() const { ParticleAttractor2D::ParticleAttractor2D() { - owner=NULL; - radius=50; - disable_radius=0; - gravity=100; - absorption=0; - path=String(".."); - enabled=true; + owner = NULL; + radius = 50; + disable_radius = 0; + gravity = 100; + absorption = 0; + path = String(".."); + enabled = true; } /****************************************/ @@ -236,12 +228,12 @@ _FORCE_INLINE_ static float _rand_from_seed(uint64_t *seed) { void Particles2D::_process_particles(float p_delta) { - if (particles.size()==0 || lifetime==0) + if (particles.size() == 0 || lifetime == 0) return; - p_delta*=time_scale; + p_delta *= time_scale; - float frame_time=p_delta; + float frame_time = p_delta; if (emit_timeout > 0) { time_to_live -= frame_time; @@ -252,114 +244,110 @@ void Particles2D::_process_particles(float p_delta) { }; }; - float next_time = time+frame_time; + float next_time = time + frame_time; if (next_time > lifetime) - next_time=Math::fmod(next_time,lifetime); - + next_time = Math::fmod(next_time, lifetime); - Particle *pdata=&particles[0]; - int particle_count=particles.size(); + Particle *pdata = &particles[0]; + int particle_count = particles.size(); Transform2D xform; if (!local_space) - xform=get_global_transform(); + xform = get_global_transform(); - active_count=0; + active_count = 0; PoolVector::Read r; - int emission_point_count=0; + int emission_point_count = 0; if (emission_points.size()) { - emission_point_count=emission_points.size(); - r=emission_points.read(); + emission_point_count = emission_points.size(); + r = emission_points.read(); } - int attractor_count=0; - AttractorCache *attractor_ptr=NULL; + int attractor_count = 0; + AttractorCache *attractor_ptr = NULL; if (attractors.size()) { - if (attractors.size()!=attractor_cache.size()) { + if (attractors.size() != attractor_cache.size()) { attractor_cache.resize(attractors.size()); } - int idx=0; + int idx = 0; Transform2D m; if (local_space) { - m= get_global_transform().affine_inverse(); + m = get_global_transform().affine_inverse(); } - for (Set::Element *E=attractors.front();E;E=E->next()) { + for (Set::Element *E = attractors.front(); E; E = E->next()) { - attractor_cache[idx].pos=m.xform( E->get()->get_global_position() ); - attractor_cache[idx].attractor=E->get(); + attractor_cache[idx].pos = m.xform(E->get()->get_global_position()); + attractor_cache[idx].attractor = E->get(); idx++; } - attractor_ptr=attractor_cache.ptr(); - attractor_count=attractor_cache.size(); + attractor_ptr = attractor_cache.ptr(); + attractor_count = attractor_cache.size(); } - for(int i=0;i time || restart_time < next_time ) - restart=true; + if (restart_time > time || restart_time < next_time) + restart = true; - } else if (restart_time > time && restart_time < next_time ) { - restart=true; + } else if (restart_time > time && restart_time < next_time) { + restart = true; } if (restart) { - if (emitting) { - p.pos=emissor_offset; + p.pos = emissor_offset; if (emission_point_count) { - - Vector2 ep = r[Math::rand()%emission_point_count]; + Vector2 ep = r[Math::rand() % emission_point_count]; if (!local_space) { - p.pos=xform.xform(p.pos+ep*extents); + p.pos = xform.xform(p.pos + ep * extents); } else { - p.pos+=ep*extents; + p.pos += ep * extents; } } else { if (!local_space) { - p.pos=xform.xform(p.pos+Vector2(Math::random(-extents.x,extents.x),Math::random(-extents.y,extents.y))); + p.pos = xform.xform(p.pos + Vector2(Math::random(-extents.x, extents.x), Math::random(-extents.y, extents.y))); } else { - p.pos+=Vector2(Math::random(-extents.x,extents.x),Math::random(-extents.y,extents.y)); + p.pos += Vector2(Math::random(-extents.x, extents.x), Math::random(-extents.y, extents.y)); } } - p.seed=Math::rand() % 12345678; - uint64_t rand_seed=p.seed*(i+1); + p.seed = Math::rand() % 12345678; + uint64_t rand_seed = p.seed * (i + 1); - float angle = Math::deg2rad(param[PARAM_DIRECTION]+_rand_from_seed(&rand_seed)*param[PARAM_SPREAD]); + float angle = Math::deg2rad(param[PARAM_DIRECTION] + _rand_from_seed(&rand_seed) * param[PARAM_SPREAD]); - p.velocity=Vector2( Math::sin(angle), Math::cos(angle) ); + p.velocity = Vector2(Math::sin(angle), Math::cos(angle)); if (!local_space) { p.velocity = xform.basis_xform(p.velocity).normalized(); } - p.velocity*=param[PARAM_LINEAR_VELOCITY]+param[PARAM_LINEAR_VELOCITY]*_rand_from_seed(&rand_seed)*randomness[PARAM_LINEAR_VELOCITY]; - p.velocity+=initial_velocity; - p.active=true; - p.rot=Math::deg2rad(param[PARAM_INITIAL_ANGLE]+param[PARAM_INITIAL_ANGLE]*randomness[PARAM_INITIAL_ANGLE]*_rand_from_seed(&rand_seed)); + p.velocity *= param[PARAM_LINEAR_VELOCITY] + param[PARAM_LINEAR_VELOCITY] * _rand_from_seed(&rand_seed) * randomness[PARAM_LINEAR_VELOCITY]; + p.velocity += initial_velocity; + p.active = true; + p.rot = Math::deg2rad(param[PARAM_INITIAL_ANGLE] + param[PARAM_INITIAL_ANGLE] * randomness[PARAM_INITIAL_ANGLE] * _rand_from_seed(&rand_seed)); active_count++; - p.frame=Math::fmod(param[PARAM_ANIM_INITIAL_POS]+randomness[PARAM_ANIM_INITIAL_POS]*_rand_from_seed(&rand_seed),1.0f); - + p.frame = Math::fmod(param[PARAM_ANIM_INITIAL_POS] + randomness[PARAM_ANIM_INITIAL_POS] * _rand_from_seed(&rand_seed), 1.0f); } else { - p.active=false; + p.active = false; } } else { @@ -367,136 +355,122 @@ void Particles2D::_process_particles(float p_delta) { if (!p.active) continue; - uint64_t rand_seed=p.seed*(i+1); + uint64_t rand_seed = p.seed * (i + 1); Vector2 force; //apply gravity - float gravity_dir = Math::deg2rad( param[PARAM_GRAVITY_DIRECTION]+180*randomness[PARAM_GRAVITY_DIRECTION]*_rand_from_seed(&rand_seed)); - force+=Vector2( Math::sin(gravity_dir), Math::cos(gravity_dir) ) * (param[PARAM_GRAVITY_STRENGTH]+param[PARAM_GRAVITY_STRENGTH]*randomness[PARAM_GRAVITY_STRENGTH]*_rand_from_seed(&rand_seed)); + float gravity_dir = Math::deg2rad(param[PARAM_GRAVITY_DIRECTION] + 180 * randomness[PARAM_GRAVITY_DIRECTION] * _rand_from_seed(&rand_seed)); + force += Vector2(Math::sin(gravity_dir), Math::cos(gravity_dir)) * (param[PARAM_GRAVITY_STRENGTH] + param[PARAM_GRAVITY_STRENGTH] * randomness[PARAM_GRAVITY_STRENGTH] * _rand_from_seed(&rand_seed)); //apply radial Vector2 rvec = (p.pos - emissor_offset).normalized(); - force+=rvec*(param[PARAM_RADIAL_ACCEL]+param[PARAM_RADIAL_ACCEL]*randomness[PARAM_RADIAL_ACCEL]*_rand_from_seed(&rand_seed)); + force += rvec * (param[PARAM_RADIAL_ACCEL] + param[PARAM_RADIAL_ACCEL] * randomness[PARAM_RADIAL_ACCEL] * _rand_from_seed(&rand_seed)); //apply orbit - float orbitvel = (param[PARAM_ORBIT_VELOCITY]+param[PARAM_ORBIT_VELOCITY]*randomness[PARAM_ORBIT_VELOCITY]*_rand_from_seed(&rand_seed)); - if (orbitvel!=0) { + float orbitvel = (param[PARAM_ORBIT_VELOCITY] + param[PARAM_ORBIT_VELOCITY] * randomness[PARAM_ORBIT_VELOCITY] * _rand_from_seed(&rand_seed)); + if (orbitvel != 0) { Vector2 rel = p.pos - xform.elements[2]; - Transform2D rot(orbitvel*frame_time,Vector2()); + Transform2D rot(orbitvel * frame_time, Vector2()); p.pos = rot.xform(rel) + xform.elements[2]; - } - Vector2 tvec=rvec.tangent(); - force+=tvec*(param[PARAM_TANGENTIAL_ACCEL]+param[PARAM_TANGENTIAL_ACCEL]*randomness[PARAM_TANGENTIAL_ACCEL]*_rand_from_seed(&rand_seed)); + Vector2 tvec = rvec.tangent(); + force += tvec * (param[PARAM_TANGENTIAL_ACCEL] + param[PARAM_TANGENTIAL_ACCEL] * randomness[PARAM_TANGENTIAL_ACCEL] * _rand_from_seed(&rand_seed)); - for(int j=0;jenabled || vl==0 || vl > attractor_ptr[j].attractor->radius) + if (!attractor_ptr[j].attractor->enabled || vl == 0 || vl > attractor_ptr[j].attractor->radius) continue; - - - force+=vec*attractor_ptr[j].attractor->gravity; + force += vec * attractor_ptr[j].attractor->gravity; float fvl = p.velocity.length(); if (fvl && attractor_ptr[j].attractor->absorption) { Vector2 target = vec.normalized(); - p.velocity = p.velocity.normalized().linear_interpolate(target,MIN(frame_time*attractor_ptr[j].attractor->absorption,1))*fvl; + p.velocity = p.velocity.normalized().linear_interpolate(target, MIN(frame_time * attractor_ptr[j].attractor->absorption, 1)) * fvl; } if (attractor_ptr[j].attractor->disable_radius && vl < attractor_ptr[j].attractor->disable_radius) { - p.active=false; + p.active = false; } } - p.velocity+=force*frame_time; + p.velocity += force * frame_time; if (param[PARAM_DAMPING]) { - float dmp = param[PARAM_DAMPING]+param[PARAM_DAMPING]*randomness[PARAM_DAMPING]*_rand_from_seed(&rand_seed); + float dmp = param[PARAM_DAMPING] + param[PARAM_DAMPING] * randomness[PARAM_DAMPING] * _rand_from_seed(&rand_seed); float v = p.velocity.length(); v -= dmp * frame_time; - if (v<=0) { - p.velocity=Vector2(); + if (v <= 0) { + p.velocity = Vector2(); } else { - p.velocity=p.velocity.normalized() * v; + p.velocity = p.velocity.normalized() * v; } - } - p.pos+=p.velocity*frame_time; - p.rot+=Math::lerp(param[PARAM_SPIN_VELOCITY],param[PARAM_SPIN_VELOCITY]*randomness[PARAM_SPIN_VELOCITY]*_rand_from_seed(&rand_seed),randomness[PARAM_SPIN_VELOCITY])*frame_time; - float anim_spd=param[PARAM_ANIM_SPEED_SCALE]+param[PARAM_ANIM_SPEED_SCALE]*randomness[PARAM_ANIM_SPEED_SCALE]*_rand_from_seed(&rand_seed); - p.frame=Math::fposmod(p.frame+(frame_time/lifetime)*anim_spd,1.0f); + p.pos += p.velocity * frame_time; + p.rot += Math::lerp(param[PARAM_SPIN_VELOCITY], param[PARAM_SPIN_VELOCITY] * randomness[PARAM_SPIN_VELOCITY] * _rand_from_seed(&rand_seed), randomness[PARAM_SPIN_VELOCITY]) * frame_time; + float anim_spd = param[PARAM_ANIM_SPEED_SCALE] + param[PARAM_ANIM_SPEED_SCALE] * randomness[PARAM_ANIM_SPEED_SCALE] * _rand_from_seed(&rand_seed); + p.frame = Math::fposmod(p.frame + (frame_time / lifetime) * anim_spd, 1.0f); active_count++; - } - - } - - - time=Math::fmod( time+frame_time, lifetime ); - if (!emitting && active_count==0) { + time = Math::fmod(time + frame_time, lifetime); + if (!emitting && active_count == 0) { emit_signal(SceneStringNames::get_singleton()->emission_finished); set_process(false); set_fixed_process(false); } update(); - - } - void Particles2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_PROCESS: { - _process_particles( get_process_delta_time() ); + _process_particles(get_process_delta_time()); } break; case NOTIFICATION_FIXED_PROCESS: { - _process_particles( get_fixed_process_delta_time() ); + _process_particles(get_fixed_process_delta_time()); } break; case NOTIFICATION_ENTER_TREE: { - float ppt=preprocess; - while(ppt>0) { + float ppt = preprocess; + while (ppt > 0) { _process_particles(0.1); - ppt-=0.1; + ppt -= 0.1; } } break; case NOTIFICATION_DRAW: { - - if (particles.size()==0 || lifetime==0) + if (particles.size() == 0 || lifetime == 0) return; - RID ci=get_canvas_item(); - Size2 size(1,1); + RID ci = get_canvas_item(); + Size2 size(1, 1); Point2 center; - int total_frames=1; + int total_frames = 1; if (!texture.is_null()) { - size=texture->get_size(); - size.x/=h_frames; - size.y/=v_frames; - total_frames=h_frames*v_frames; + size = texture->get_size(); + size.x /= h_frames; + size.y /= v_frames; + total_frames = h_frames * v_frames; } + float time_pos = (time / lifetime); - float time_pos=(time/lifetime); - - Particle *pdata=&particles[0]; - int particle_count=particles.size(); + Particle *pdata = &particles[0]; + int particle_count = particles.size(); RID texrid; @@ -505,64 +479,61 @@ void Particles2D::_notification(int p_what) { Transform2D invxform; if (!local_space) - invxform=get_global_transform().affine_inverse(); + invxform = get_global_transform().affine_inverse(); int start_particle = (int)(time * (float)particle_count / lifetime); - for (int id=0;id= particle_count) { i -= particle_count; } - Particle &p=pdata[i]; + Particle &p = pdata[i]; if (!p.active) continue; - float ptime = ((float)i / particle_count)*explosiveness; + float ptime = ((float)i / particle_count) * explosiveness; - if (ptimeget_color_at_offset(ptime); - } else - { + } else { color = default_color; } - { - float huerand=_rand_from_seed(&rand_seed); + float huerand = _rand_from_seed(&rand_seed); float huerot = param[PARAM_HUE_VARIATION] + randomness[PARAM_HUE_VARIATION] * huerand; if (Math::abs(huerot) > CMP_EPSILON) { - float h=color.get_h(); - float s=color.get_s(); - float v=color.get_v(); - float a=color.a; + float h = color.get_h(); + float s = color.get_s(); + float v = color.get_v(); + float a = color.a; //float preh=h; - h+=huerot; - h=Math::abs(Math::fposmod(h,1.0f)); + h += huerot; + h = Math::abs(Math::fposmod(h, 1.0f)); //print_line("rand: "+rtos(randomness[PARAM_HUE_VARIATION])+" rand: "+rtos(huerand)); //print_line(itos(i)+":hue: "+rtos(preh)+" + "+rtos(huerot)+" = "+rtos(h)); - color.set_hsv(h,s,v); - color.a=a; + color.set_hsv(h, s, v); + color.a = a; } } - float initial_size = param[PARAM_INITIAL_SIZE]+param[PARAM_INITIAL_SIZE]*_rand_from_seed(&rand_seed)*randomness[PARAM_INITIAL_SIZE]; - float final_size = param[PARAM_FINAL_SIZE]+param[PARAM_FINAL_SIZE]*_rand_from_seed(&rand_seed)*randomness[PARAM_FINAL_SIZE]; + float initial_size = param[PARAM_INITIAL_SIZE] + param[PARAM_INITIAL_SIZE] * _rand_from_seed(&rand_seed) * randomness[PARAM_INITIAL_SIZE]; + float final_size = param[PARAM_FINAL_SIZE] + param[PARAM_FINAL_SIZE] * _rand_from_seed(&rand_seed) * randomness[PARAM_FINAL_SIZE]; - float size_mult=initial_size*(1.0-ptime) + final_size*ptime; + float size_mult = initial_size * (1.0 - ptime) + final_size * ptime; //Size2 rectsize=size * size_mult; //rectsize=rectsize.floor(); @@ -574,57 +545,49 @@ void Particles2D::_notification(int p_what) { if (p.rot) { xform.set_rotation(p.rot); - xform.translate(-size*size_mult/2.0); - xform.elements[2]+=p.pos; + xform.translate(-size * size_mult / 2.0); + xform.elements[2] += p.pos; } else { - xform.elements[2]=-size*size_mult/2.0; - xform.elements[2]+=p.pos; + xform.elements[2] = -size * size_mult / 2.0; + xform.elements[2] += p.pos; } if (!local_space) { xform = invxform * xform; } + xform.scale_basis(Size2(size_mult, size_mult)); - xform.scale_basis(Size2(size_mult,size_mult)); - - - VisualServer::get_singleton()->canvas_item_add_set_transform(ci,xform); - + VisualServer::get_singleton()->canvas_item_add_set_transform(ci, xform); if (texrid.is_valid()) { Rect2 src_rect; - src_rect.size=size; + src_rect.size = size; - if (total_frames>1) { - int frame = Math::fast_ftoi(Math::floor(p.frame*total_frames)) % total_frames; - src_rect.pos.x = size.x * (frame%h_frames); - src_rect.pos.y = size.y * (frame/h_frames); + if (total_frames > 1) { + int frame = Math::fast_ftoi(Math::floor(p.frame * total_frames)) % total_frames; + src_rect.pos.x = size.x * (frame % h_frames); + src_rect.pos.y = size.y * (frame / h_frames); } if (flip_h) - src_rect.size.x=-src_rect.size.x; + src_rect.size.x = -src_rect.size.x; if (flip_v) - src_rect.size.y=-src_rect.size.y; + src_rect.size.y = -src_rect.size.y; - texture->draw_rect_region(ci,Rect2(Point2(),size),src_rect,color); + texture->draw_rect_region(ci, Rect2(Point2(), size), src_rect, color); //VisualServer::get_singleton()->canvas_item_add_texture_rect(ci,r,texrid,false,color); } else { - VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2(),size),color); - + VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(), size), color); } - } - } break; - } - } -static const char* _particlesframe_property_names[Particles2D::PARAM_MAX]={ +static const char *_particlesframe_property_names[Particles2D::PARAM_MAX] = { "params/direction", "params/spread", "params/linear_velocity", @@ -643,7 +606,7 @@ static const char* _particlesframe_property_names[Particles2D::PARAM_MAX]={ "params/anim_initial_pos", }; -static const char* _particlesframe_property_rnames[Particles2D::PARAM_MAX]={ +static const char *_particlesframe_property_rnames[Particles2D::PARAM_MAX] = { "randomness/direction", "randomness/spread", "randomness/linear_velocity", @@ -662,7 +625,7 @@ static const char* _particlesframe_property_rnames[Particles2D::PARAM_MAX]={ "randomness/anim_initial_pos", }; -static const char* _particlesframe_property_ranges[Particles2D::PARAM_MAX]={ +static const char *_particlesframe_property_ranges[Particles2D::PARAM_MAX] = { "0,360,0.01", "0,180,0.01", "-1024,1024,0.01", @@ -681,21 +644,20 @@ static const char* _particlesframe_property_ranges[Particles2D::PARAM_MAX]={ "0,1,0.01", }; - void Particles2D::set_emitting(bool p_emitting) { - if (emitting==p_emitting) + if (emitting == p_emitting) return; if (p_emitting) { - if (active_count==0) - time=0; - set_process(process_mode==PROCESS_IDLE); - set_fixed_process(process_mode==PROCESS_FIXED); + if (active_count == 0) + time = 0; + set_process(process_mode == PROCESS_IDLE); + set_fixed_process(process_mode == PROCESS_FIXED); time_to_live = emit_timeout; }; - emitting=p_emitting; + emitting = p_emitting; _change_notify("config/emitting"); } @@ -706,10 +668,10 @@ bool Particles2D::is_emitting() const { void Particles2D::set_process_mode(ProcessMode p_mode) { - process_mode=p_mode; - const bool should_process=emitting || active_count!=0; - set_process(should_process && process_mode==PROCESS_IDLE); - set_fixed_process(should_process && process_mode==PROCESS_FIXED); + process_mode = p_mode; + const bool should_process = emitting || active_count != 0; + set_process(should_process && process_mode == PROCESS_IDLE); + set_fixed_process(should_process && process_mode == PROCESS_FIXED); } Particles2D::ProcessMode Particles2D::get_process_mode() const { @@ -719,7 +681,7 @@ Particles2D::ProcessMode Particles2D::get_process_mode() const { void Particles2D::set_amount(int p_amount) { - ERR_FAIL_INDEX(p_amount,1024+1); + ERR_FAIL_INDEX(p_amount, 1024 + 1); particles.resize(p_amount); } @@ -741,9 +703,9 @@ float Particles2D::get_emit_timeout() const { void Particles2D::set_lifetime(float p_lifetime) { - ERR_FAIL_INDEX(p_lifetime,3600+1); + ERR_FAIL_INDEX(p_lifetime, 3600 + 1); - lifetime=p_lifetime; + lifetime = p_lifetime; } float Particles2D::get_lifetime() const { @@ -752,7 +714,7 @@ float Particles2D::get_lifetime() const { void Particles2D::set_time_scale(float p_time_scale) { - time_scale=p_time_scale; + time_scale = p_time_scale; } float Particles2D::get_time_scale() const { @@ -761,42 +723,39 @@ float Particles2D::get_time_scale() const { void Particles2D::set_pre_process_time(float p_pre_process_time) { - preprocess=p_pre_process_time; + preprocess = p_pre_process_time; } -float Particles2D::get_pre_process_time() const{ +float Particles2D::get_pre_process_time() const { return preprocess; } - void Particles2D::set_param(Parameter p_param, float p_value) { - ERR_FAIL_INDEX(p_param,PARAM_MAX); - param[p_param]=p_value; + ERR_FAIL_INDEX(p_param, PARAM_MAX); + param[p_param] = p_value; } float Particles2D::get_param(Parameter p_param) const { - ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); + ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return param[p_param]; } void Particles2D::set_randomness(Parameter p_param, float p_value) { - ERR_FAIL_INDEX(p_param,PARAM_MAX); - randomness[p_param]=p_value; - + ERR_FAIL_INDEX(p_param, PARAM_MAX); + randomness[p_param] = p_value; } -float Particles2D::get_randomness(Parameter p_param) const { +float Particles2D::get_randomness(Parameter p_param) const { - ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); + ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return randomness[p_param]; - } -void Particles2D::set_texture(const Ref& p_texture) { +void Particles2D::set_texture(const Ref &p_texture) { - texture=p_texture; + texture = p_texture; } Ref Particles2D::get_texture() const { @@ -804,7 +763,7 @@ Ref Particles2D::get_texture() const { return texture; } -void Particles2D::set_color(const Color& p_color) { +void Particles2D::set_color(const Color &p_color) { default_color = p_color; } @@ -814,10 +773,9 @@ Color Particles2D::get_color() const { return default_color; } +void Particles2D::set_color_ramp(const Ref &p_color_ramp) { -void Particles2D::set_color_ramp(const Ref& p_color_ramp) { - - color_ramp=p_color_ramp; + color_ramp = p_color_ramp; } Ref Particles2D::get_color_ramp() const { @@ -825,9 +783,9 @@ Ref Particles2D::get_color_ramp() const { return color_ramp; } -void Particles2D::set_emissor_offset(const Point2& p_offset) { +void Particles2D::set_emissor_offset(const Point2 &p_offset) { - emissor_offset=p_offset; + emissor_offset = p_offset; } Point2 Particles2D::get_emissor_offset() const { @@ -835,10 +793,9 @@ Point2 Particles2D::get_emissor_offset() const { return emissor_offset; } - void Particles2D::set_use_local_space(bool p_use) { - local_space=p_use; + local_space = p_use; } bool Particles2D::is_using_local_space() const { @@ -851,12 +808,10 @@ void Particles2D::set_color_phases(int p_phases) { //Create color ramp if we have 2 or more phases. //Otherwise first phase phase will be assigned to default color. - if(p_phases > 1 && color_ramp.is_null()) - { - color_ramp = Ref(memnew (ColorRamp())); + if (p_phases > 1 && color_ramp.is_null()) { + color_ramp = Ref(memnew(ColorRamp())); } - if(color_ramp.is_valid()) - { + if (color_ramp.is_valid()) { color_ramp->get_points().resize(p_phases); } } @@ -864,24 +819,21 @@ void Particles2D::set_color_phases(int p_phases) { //Deprecated. int Particles2D::get_color_phases() const { - if(color_ramp.is_valid()) - { + if (color_ramp.is_valid()) { return color_ramp->get_points_count(); } return 0; } //Deprecated. Converts color phases to color ramp -void Particles2D::set_color_phase_color(int p_phase,const Color& p_color) { +void Particles2D::set_color_phase_color(int p_phase, const Color &p_color) { - ERR_FAIL_INDEX(p_phase,MAX_COLOR_PHASES); - if(color_ramp.is_valid()) - { - if(color_ramp->get_points_count() > p_phase) + ERR_FAIL_INDEX(p_phase, MAX_COLOR_PHASES); + if (color_ramp.is_valid()) { + if (color_ramp->get_points_count() > p_phase) color_ramp->set_color(p_phase, p_color); - } else - { - if(p_phase == 0) + } else { + if (p_phase == 0) default_color = p_color; } } @@ -889,20 +841,18 @@ void Particles2D::set_color_phase_color(int p_phase,const Color& p_color) { //Deprecated. Color Particles2D::get_color_phase_color(int p_phase) const { - ERR_FAIL_INDEX_V(p_phase,MAX_COLOR_PHASES,Color()); - if(color_ramp.is_valid()) - { + ERR_FAIL_INDEX_V(p_phase, MAX_COLOR_PHASES, Color()); + if (color_ramp.is_valid()) { return color_ramp->get_color(p_phase); } - return Color(0,0,0,1); + return Color(0, 0, 0, 1); } //Deprecated. Converts color phases to color ramp -void Particles2D::set_color_phase_pos(int p_phase,float p_pos) { - ERR_FAIL_INDEX(p_phase,MAX_COLOR_PHASES); - ERR_FAIL_COND(p_pos<0.0 || p_pos>1.0); - if(color_ramp.is_valid() && color_ramp->get_points_count() > p_phase) - { +void Particles2D::set_color_phase_pos(int p_phase, float p_pos) { + ERR_FAIL_INDEX(p_phase, MAX_COLOR_PHASES); + ERR_FAIL_COND(p_pos < 0.0 || p_pos > 1.0); + if (color_ramp.is_valid() && color_ramp->get_points_count() > p_phase) { return color_ramp->set_offset(p_phase, p_pos); } } @@ -910,17 +860,16 @@ void Particles2D::set_color_phase_pos(int p_phase,float p_pos) { //Deprecated. float Particles2D::get_color_phase_pos(int p_phase) const { - ERR_FAIL_INDEX_V(p_phase,MAX_COLOR_PHASES,0); - if(color_ramp.is_valid()) - { + ERR_FAIL_INDEX_V(p_phase, MAX_COLOR_PHASES, 0); + if (color_ramp.is_valid()) { return color_ramp->get_offset(p_phase); } return 0; } -void Particles2D::set_emission_half_extents(const Vector2& p_extents) { +void Particles2D::set_emission_half_extents(const Vector2 &p_extents) { - extents=p_extents; + extents = p_extents; } Vector2 Particles2D::get_emission_half_extents() const { @@ -928,278 +877,269 @@ Vector2 Particles2D::get_emission_half_extents() const { return extents; } -void Particles2D::set_initial_velocity(const Vector2& p_velocity) { - +void Particles2D::set_initial_velocity(const Vector2 &p_velocity) { - initial_velocity=p_velocity; + initial_velocity = p_velocity; } -Vector2 Particles2D::get_initial_velocity() const{ +Vector2 Particles2D::get_initial_velocity() const { return initial_velocity; } - void Particles2D::pre_process(float p_delta) { _process_particles(p_delta); } - void Particles2D::set_explosiveness(float p_value) { - explosiveness=p_value; + explosiveness = p_value; } -float Particles2D::get_explosiveness() const{ +float Particles2D::get_explosiveness() const { return explosiveness; } void Particles2D::set_flip_h(bool p_flip) { - flip_h=p_flip; + flip_h = p_flip; } -bool Particles2D::is_flipped_h() const{ +bool Particles2D::is_flipped_h() const { return flip_h; } -void Particles2D::set_flip_v(bool p_flip){ +void Particles2D::set_flip_v(bool p_flip) { - flip_v=p_flip; + flip_v = p_flip; } -bool Particles2D::is_flipped_v() const{ +bool Particles2D::is_flipped_v() const { return flip_v; } void Particles2D::set_h_frames(int p_frames) { - ERR_FAIL_COND(p_frames<1); - h_frames=p_frames; + ERR_FAIL_COND(p_frames < 1); + h_frames = p_frames; } -int Particles2D::get_h_frames() const{ +int Particles2D::get_h_frames() const { return h_frames; } -void Particles2D::set_v_frames(int p_frames){ +void Particles2D::set_v_frames(int p_frames) { - ERR_FAIL_COND(p_frames<1); - v_frames=p_frames; + ERR_FAIL_COND(p_frames < 1); + v_frames = p_frames; } -int Particles2D::get_v_frames() const{ +int Particles2D::get_v_frames() const { return v_frames; } +void Particles2D::set_emission_points(const PoolVector &p_points) { - -void Particles2D::set_emission_points(const PoolVector& p_points) { - - emission_points=p_points; + emission_points = p_points; } -PoolVector Particles2D::get_emission_points() const{ +PoolVector Particles2D::get_emission_points() const { return emission_points; } void Particles2D::reset() { - for(int i=0;i particles; @@ -170,17 +171,15 @@ private: Ref color_ramp; void _process_particles(float p_delta); -friend class ParticleAttractor2D; + friend class ParticleAttractor2D; - Set attractors; + Set attractors; protected: - void _notification(int p_what); static void _bind_methods(); public: - void set_emitting(bool p_emitting); bool is_emitting() const; @@ -202,7 +201,7 @@ public: void set_emit_timeout(float p_timeout); float get_emit_timeout() const; - void set_emission_half_extents(const Vector2& p_extents); + void set_emission_half_extents(const Vector2 &p_extents); Vector2 get_emission_half_extents() const; void set_param(Parameter p_param, float p_value); @@ -220,7 +219,6 @@ public: void set_flip_v(bool p_flip); bool is_flipped_v() const; - void set_h_frames(int p_frames); int get_h_frames() const; @@ -230,31 +228,31 @@ public: void set_color_phases(int p_phases); int get_color_phases() const; - void set_color_phase_color(int p_phase,const Color& p_color); + void set_color_phase_color(int p_phase, const Color &p_color); Color get_color_phase_color(int p_phase) const; - void set_color_phase_pos(int p_phase,float p_pos); + void set_color_phase_pos(int p_phase, float p_pos); float get_color_phase_pos(int p_phase) const; - void set_texture(const Ref& p_texture); + void set_texture(const Ref &p_texture); Ref get_texture() const; - void set_color(const Color& p_color); + void set_color(const Color &p_color); Color get_color() const; - void set_color_ramp(const Ref& p_texture); + void set_color_ramp(const Ref &p_texture); Ref get_color_ramp() const; - void set_emissor_offset(const Point2& p_offset); + void set_emissor_offset(const Point2 &p_offset); Point2 get_emissor_offset() const; void set_use_local_space(bool p_use); bool is_using_local_space() const; - void set_initial_velocity(const Vector2& p_velocity); + void set_initial_velocity(const Vector2 &p_velocity); Vector2 get_initial_velocity() const; - void set_emission_points(const PoolVector& p_points); + void set_emission_points(const PoolVector &p_points); PoolVector get_emission_points() const; void pre_process(float p_delta); @@ -263,7 +261,7 @@ public: Particles2D(); }; -VARIANT_ENUM_CAST( Particles2D::ProcessMode ); -VARIANT_ENUM_CAST( Particles2D::Parameter ); +VARIANT_ENUM_CAST(Particles2D::ProcessMode); +VARIANT_ENUM_CAST(Particles2D::Parameter); #endif // PARTICLES_FRAME_H diff --git a/scene/2d/path_2d.cpp b/scene/2d/path_2d.cpp index 63531ae59..9e8be7fa1 100644 --- a/scene/2d/path_2d.cpp +++ b/scene/2d/path_2d.cpp @@ -31,23 +31,23 @@ void Path2D::_notification(int p_what) { - if (p_what==NOTIFICATION_DRAW && curve.is_valid()) { + if (p_what == NOTIFICATION_DRAW && curve.is_valid()) { //draw the curve!! if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_navigation_hint()) { return; } - for(int i=0;iget_point_count();i++) { + for (int i = 0; i < curve->get_point_count(); i++) { - Vector2 prev_p=curve->get_point_pos(i); + Vector2 prev_p = curve->get_point_pos(i); - for(int j=1;j<=8;j++) { + for (int j = 1; j <= 8; j++) { - real_t frac = j/8.0; - Vector2 p = curve->interpolate(i,frac); - draw_line(prev_p,p,Color(0.5,0.6,1.0,0.7),2); - prev_p=p; + real_t frac = j / 8.0; + Vector2 p = curve->interpolate(i, frac); + draw_line(prev_p, p, Color(0.5, 0.6, 1.0, 0.7), 2); + prev_p = p; } } } @@ -55,98 +55,89 @@ void Path2D::_notification(int p_what) { void Path2D::_curve_changed() { - if (is_inside_tree() && get_tree()->is_editor_hint()) update(); - } - -void Path2D::set_curve(const Ref& p_curve) { +void Path2D::set_curve(const Ref &p_curve) { if (curve.is_valid()) { - curve->disconnect("changed",this,"_curve_changed"); + curve->disconnect("changed", this, "_curve_changed"); } - curve=p_curve; + curve = p_curve; if (curve.is_valid()) { - curve->connect("changed",this,"_curve_changed"); + curve->connect("changed", this, "_curve_changed"); } _curve_changed(); - } -Ref Path2D::get_curve() const{ +Ref Path2D::get_curve() const { return curve; } void Path2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_curve","curve:Curve2D"),&Path2D::set_curve); - ClassDB::bind_method(D_METHOD("get_curve:Curve2D","curve"),&Path2D::get_curve); - ClassDB::bind_method(D_METHOD("_curve_changed"),&Path2D::_curve_changed); + ClassDB::bind_method(D_METHOD("set_curve", "curve:Curve2D"), &Path2D::set_curve); + ClassDB::bind_method(D_METHOD("get_curve:Curve2D", "curve"), &Path2D::get_curve); + ClassDB::bind_method(D_METHOD("_curve_changed"), &Path2D::_curve_changed); - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve2D"), "set_curve","get_curve"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve2D"), "set_curve", "get_curve"); } Path2D::Path2D() { - set_curve(Ref( memnew( Curve2D ))); //create one by default + set_curve(Ref(memnew(Curve2D))); //create one by default } ///////////////////////////////////////////////////////////////////////////////// - void PathFollow2D::_update_transform() { - if (!path) return; - Ref c =path->get_curve(); + Ref c = path->get_curve(); if (!c.is_valid()) return; - float o = offset; if (loop) - o=Math::fposmod(o,c->get_baked_length()); + o = Math::fposmod(o, c->get_baked_length()); - Vector2 pos = c->interpolate_baked(o,cubic); + Vector2 pos = c->interpolate_baked(o, cubic); if (rotate) { - Vector2 n = (c->interpolate_baked(o+lookahead,cubic)-pos).normalized(); + Vector2 n = (c->interpolate_baked(o + lookahead, cubic) - pos).normalized(); Vector2 t = -n.tangent(); - pos+=n*h_offset; - pos+=t*v_offset; + pos += n * h_offset; + pos += t * v_offset; set_rotation(t.angle()); } else { - pos.x+=h_offset; - pos.y+=v_offset; + pos.x += h_offset; + pos.y += v_offset; } set_position(pos); - } void PathFollow2D::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - Node *parent=get_parent(); + Node *parent = get_parent(); if (parent) { - path=parent->cast_to(); + path = parent->cast_to(); if (path) { _update_transform(); } @@ -155,16 +146,14 @@ void PathFollow2D::_notification(int p_what) { } break; case NOTIFICATION_EXIT_TREE: { - - path=NULL; + path = NULL; } break; } - } void PathFollow2D::set_cubic_interpolation(bool p_enable) { - cubic=p_enable; + cubic = p_enable; } bool PathFollow2D::get_cubic_interpolation() const { @@ -172,24 +161,23 @@ bool PathFollow2D::get_cubic_interpolation() const { return cubic; } +bool PathFollow2D::_set(const StringName &p_name, const Variant &p_value) { -bool PathFollow2D::_set(const StringName& p_name, const Variant& p_value) { - - if (p_name==SceneStringNames::get_singleton()->offset) { + if (p_name == SceneStringNames::get_singleton()->offset) { set_offset(p_value); - } else if (p_name==SceneStringNames::get_singleton()->unit_offset) { + } else if (p_name == SceneStringNames::get_singleton()->unit_offset) { set_unit_offset(p_value); - } else if (p_name==SceneStringNames::get_singleton()->rotate) { + } else if (p_name == SceneStringNames::get_singleton()->rotate) { set_rotate(p_value); - } else if (p_name==SceneStringNames::get_singleton()->v_offset) { + } else if (p_name == SceneStringNames::get_singleton()->v_offset) { set_v_offset(p_value); - } else if (p_name==SceneStringNames::get_singleton()->h_offset) { + } else if (p_name == SceneStringNames::get_singleton()->h_offset) { set_h_offset(p_value); - } else if (String(p_name)=="cubic_interp") { + } else if (String(p_name) == "cubic_interp") { set_cubic_interpolation(p_value); - } else if (String(p_name)=="loop") { + } else if (String(p_name) == "loop") { set_loop(p_value); - } else if (String(p_name)=="lookahead") { + } else if (String(p_name) == "lookahead") { set_lookahead(p_value); } else return false; @@ -197,46 +185,44 @@ bool PathFollow2D::_set(const StringName& p_name, const Variant& p_value) { return true; } -bool PathFollow2D::_get(const StringName& p_name,Variant &r_ret) const{ - - if (p_name==SceneStringNames::get_singleton()->offset) { - r_ret=get_offset(); - } else if (p_name==SceneStringNames::get_singleton()->unit_offset) { - r_ret=get_unit_offset(); - } else if (p_name==SceneStringNames::get_singleton()->rotate) { - r_ret=is_rotating(); - } else if (p_name==SceneStringNames::get_singleton()->v_offset) { - r_ret=get_v_offset(); - } else if (p_name==SceneStringNames::get_singleton()->h_offset) { - r_ret=get_h_offset(); - } else if (String(p_name)=="cubic_interp") { - r_ret=cubic; - } else if (String(p_name)=="loop") { - r_ret=loop; - } else if (String(p_name)=="lookahead") { - r_ret=lookahead; +bool PathFollow2D::_get(const StringName &p_name, Variant &r_ret) const { + + if (p_name == SceneStringNames::get_singleton()->offset) { + r_ret = get_offset(); + } else if (p_name == SceneStringNames::get_singleton()->unit_offset) { + r_ret = get_unit_offset(); + } else if (p_name == SceneStringNames::get_singleton()->rotate) { + r_ret = is_rotating(); + } else if (p_name == SceneStringNames::get_singleton()->v_offset) { + r_ret = get_v_offset(); + } else if (p_name == SceneStringNames::get_singleton()->h_offset) { + r_ret = get_h_offset(); + } else if (String(p_name) == "cubic_interp") { + r_ret = cubic; + } else if (String(p_name) == "loop") { + r_ret = loop; + } else if (String(p_name) == "lookahead") { + r_ret = lookahead; } else return false; return true; - } -void PathFollow2D::_get_property_list( List *p_list) const{ +void PathFollow2D::_get_property_list(List *p_list) const { - float max=10000; + float max = 10000; if (path && path->get_curve().is_valid()) - max=path->get_curve()->get_baked_length(); - p_list->push_back( PropertyInfo( Variant::REAL, "offset", PROPERTY_HINT_RANGE,"0,"+rtos(max)+",0.01")); - p_list->push_back( PropertyInfo( Variant::REAL, "unit_offset", PROPERTY_HINT_RANGE,"0,1,0.0001",PROPERTY_USAGE_EDITOR)); - p_list->push_back( PropertyInfo( Variant::REAL, "h_offset") ); - p_list->push_back( PropertyInfo( Variant::REAL, "v_offset") ); - p_list->push_back( PropertyInfo( Variant::BOOL, "rotate") ); - p_list->push_back( PropertyInfo( Variant::BOOL, "cubic_interp")); - p_list->push_back( PropertyInfo( Variant::BOOL, "loop")); - p_list->push_back( PropertyInfo( Variant::REAL, "lookahead",PROPERTY_HINT_RANGE,"0.001,1024.0,0.001")); + max = path->get_curve()->get_baked_length(); + p_list->push_back(PropertyInfo(Variant::REAL, "offset", PROPERTY_HINT_RANGE, "0," + rtos(max) + ",0.01")); + p_list->push_back(PropertyInfo(Variant::REAL, "unit_offset", PROPERTY_HINT_RANGE, "0,1,0.0001", PROPERTY_USAGE_EDITOR)); + p_list->push_back(PropertyInfo(Variant::REAL, "h_offset")); + p_list->push_back(PropertyInfo(Variant::REAL, "v_offset")); + p_list->push_back(PropertyInfo(Variant::BOOL, "rotate")); + p_list->push_back(PropertyInfo(Variant::BOOL, "cubic_interp")); + p_list->push_back(PropertyInfo(Variant::BOOL, "loop")); + p_list->push_back(PropertyInfo(Variant::REAL, "lookahead", PROPERTY_HINT_RANGE, "0.001,1024.0,0.001")); } - String PathFollow2D::get_configuration_warning() const { if (!is_visible_in_tree() || !is_inside_tree()) @@ -247,51 +233,46 @@ String PathFollow2D::get_configuration_warning() const { } return String(); - } void PathFollow2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_offset","offset"),&PathFollow2D::set_offset); - ClassDB::bind_method(D_METHOD("get_offset"),&PathFollow2D::get_offset); + ClassDB::bind_method(D_METHOD("set_offset", "offset"), &PathFollow2D::set_offset); + ClassDB::bind_method(D_METHOD("get_offset"), &PathFollow2D::get_offset); - ClassDB::bind_method(D_METHOD("set_h_offset","h_offset"),&PathFollow2D::set_h_offset); - ClassDB::bind_method(D_METHOD("get_h_offset"),&PathFollow2D::get_h_offset); + ClassDB::bind_method(D_METHOD("set_h_offset", "h_offset"), &PathFollow2D::set_h_offset); + ClassDB::bind_method(D_METHOD("get_h_offset"), &PathFollow2D::get_h_offset); - ClassDB::bind_method(D_METHOD("set_v_offset","v_offset"),&PathFollow2D::set_v_offset); - ClassDB::bind_method(D_METHOD("get_v_offset"),&PathFollow2D::get_v_offset); + ClassDB::bind_method(D_METHOD("set_v_offset", "v_offset"), &PathFollow2D::set_v_offset); + ClassDB::bind_method(D_METHOD("get_v_offset"), &PathFollow2D::get_v_offset); - ClassDB::bind_method(D_METHOD("set_unit_offset","unit_offset"),&PathFollow2D::set_unit_offset); - ClassDB::bind_method(D_METHOD("get_unit_offset"),&PathFollow2D::get_unit_offset); + ClassDB::bind_method(D_METHOD("set_unit_offset", "unit_offset"), &PathFollow2D::set_unit_offset); + ClassDB::bind_method(D_METHOD("get_unit_offset"), &PathFollow2D::get_unit_offset); - ClassDB::bind_method(D_METHOD("set_rotate","enable"),&PathFollow2D::set_rotate); - ClassDB::bind_method(D_METHOD("is_rotating"),&PathFollow2D::is_rotating); - - ClassDB::bind_method(D_METHOD("set_cubic_interpolation","enable"),&PathFollow2D::set_cubic_interpolation); - ClassDB::bind_method(D_METHOD("get_cubic_interpolation"),&PathFollow2D::get_cubic_interpolation); - - ClassDB::bind_method(D_METHOD("set_loop","loop"),&PathFollow2D::set_loop); - ClassDB::bind_method(D_METHOD("has_loop"),&PathFollow2D::has_loop); + ClassDB::bind_method(D_METHOD("set_rotate", "enable"), &PathFollow2D::set_rotate); + ClassDB::bind_method(D_METHOD("is_rotating"), &PathFollow2D::is_rotating); + ClassDB::bind_method(D_METHOD("set_cubic_interpolation", "enable"), &PathFollow2D::set_cubic_interpolation); + ClassDB::bind_method(D_METHOD("get_cubic_interpolation"), &PathFollow2D::get_cubic_interpolation); + ClassDB::bind_method(D_METHOD("set_loop", "loop"), &PathFollow2D::set_loop); + ClassDB::bind_method(D_METHOD("has_loop"), &PathFollow2D::has_loop); } void PathFollow2D::set_offset(float p_offset) { - offset=p_offset; + offset = p_offset; if (path) _update_transform(); _change_notify("offset"); _change_notify("unit_offset"); - } void PathFollow2D::set_h_offset(float p_h_offset) { - h_offset=p_h_offset; + h_offset = p_h_offset; if (path) _update_transform(); - } float PathFollow2D::get_h_offset() const { @@ -301,10 +282,9 @@ float PathFollow2D::get_h_offset() const { void PathFollow2D::set_v_offset(float p_v_offset) { - v_offset=p_v_offset; + v_offset = p_v_offset; if (path) _update_transform(); - } float PathFollow2D::get_v_offset() const { @@ -312,8 +292,7 @@ float PathFollow2D::get_v_offset() const { return v_offset; } - -float PathFollow2D::get_offset() const{ +float PathFollow2D::get_offset() const { return offset; } @@ -321,32 +300,30 @@ float PathFollow2D::get_offset() const{ void PathFollow2D::set_unit_offset(float p_unit_offset) { if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) - set_offset(p_unit_offset*path->get_curve()->get_baked_length()); - + set_offset(p_unit_offset * path->get_curve()->get_baked_length()); } -float PathFollow2D::get_unit_offset() const{ +float PathFollow2D::get_unit_offset() const { if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) - return get_offset()/path->get_curve()->get_baked_length(); + return get_offset() / path->get_curve()->get_baked_length(); else return 0; } void PathFollow2D::set_lookahead(float p_lookahead) { - lookahead=p_lookahead; - + lookahead = p_lookahead; } -float PathFollow2D::get_lookahead() const{ +float PathFollow2D::get_lookahead() const { return lookahead; } void PathFollow2D::set_rotate(bool p_rotate) { - rotate=p_rotate; + rotate = p_rotate; _update_transform(); } @@ -357,23 +334,22 @@ bool PathFollow2D::is_rotating() const { void PathFollow2D::set_loop(bool p_loop) { - loop=p_loop; + loop = p_loop; } -bool PathFollow2D::has_loop() const{ +bool PathFollow2D::has_loop() const { return loop; } - PathFollow2D::PathFollow2D() { - offset=0; - h_offset=0; - v_offset=0; - path=NULL; - rotate=true; - cubic=true; - loop=true; - lookahead=4; + offset = 0; + h_offset = 0; + v_offset = 0; + path = NULL; + rotate = true; + cubic = true; + loop = true; + lookahead = 4; } diff --git a/scene/2d/path_2d.h b/scene/2d/path_2d.h index 4fc26dbf9..7357b6810 100644 --- a/scene/2d/path_2d.h +++ b/scene/2d/path_2d.h @@ -29,39 +29,33 @@ #ifndef PATH_2D_H #define PATH_2D_H -#include "scene/resources/curve.h" #include "scene/2d/node_2d.h" +#include "scene/resources/curve.h" class Path2D : public Node2D { - GDCLASS( Path2D, Node2D ); + GDCLASS(Path2D, Node2D); Ref curve; void _curve_changed(); - protected: - void _notification(int p_what); static void _bind_methods(); -public: - void set_curve(const Ref& p_curve); +public: + void set_curve(const Ref &p_curve); Ref get_curve() const; - Path2D(); }; - - class PathFollow2D : public Node2D { - GDCLASS(PathFollow2D,Node2D); -public: - + GDCLASS(PathFollow2D, Node2D); +public: private: Path2D *path; real_t offset; @@ -74,17 +68,15 @@ private: void _update_transform(); - protected: - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); -public: +public: void set_offset(float p_offset); float get_offset() const; @@ -114,5 +106,4 @@ public: PathFollow2D(); }; - #endif // PATH_2D_H diff --git a/scene/2d/path_texture.cpp b/scene/2d/path_texture.cpp index 626928a24..60efccec3 100644 --- a/scene/2d/path_texture.cpp +++ b/scene/2d/path_texture.cpp @@ -28,65 +28,61 @@ /*************************************************************************/ #include "path_texture.h" +void PathTexture::set_begin_texture(const Ref &p_texture) { -void PathTexture::set_begin_texture(const Ref& p_texture) { - - begin=p_texture; + begin = p_texture; update(); } -Ref PathTexture::get_begin_texture() const{ +Ref PathTexture::get_begin_texture() const { return begin; } -void PathTexture::set_repeat_texture(const Ref& p_texture){ +void PathTexture::set_repeat_texture(const Ref &p_texture) { - repeat=p_texture; + repeat = p_texture; update(); - } -Ref PathTexture::get_repeat_texture() const{ +Ref PathTexture::get_repeat_texture() const { return repeat; } -void PathTexture::set_end_texture(const Ref& p_texture){ +void PathTexture::set_end_texture(const Ref &p_texture) { - end=p_texture; + end = p_texture; update(); } -Ref PathTexture::get_end_texture() const{ +Ref PathTexture::get_end_texture() const { return end; } -void PathTexture::set_subdivisions(int p_amount){ +void PathTexture::set_subdivisions(int p_amount) { - ERR_FAIL_INDEX(p_amount,32); - subdivs=p_amount; + ERR_FAIL_INDEX(p_amount, 32); + subdivs = p_amount; update(); - } -int PathTexture::get_subdivisions() const{ +int PathTexture::get_subdivisions() const { return subdivs; } -void PathTexture::set_overlap(int p_amount){ +void PathTexture::set_overlap(int p_amount) { - overlap=p_amount; + overlap = p_amount; update(); } -int PathTexture::get_overlap() const{ +int PathTexture::get_overlap() const { return overlap; } - PathTexture::PathTexture() { - overlap=0; - subdivs=1; + overlap = 0; + subdivs = 1; } diff --git a/scene/2d/path_texture.h b/scene/2d/path_texture.h index cc502a2fa..8d5adc49c 100644 --- a/scene/2d/path_texture.h +++ b/scene/2d/path_texture.h @@ -32,22 +32,22 @@ #include "scene/2d/node_2d.h" class PathTexture : public Node2D { - GDCLASS( PathTexture, Node2D ); + GDCLASS(PathTexture, Node2D); Ref begin; Ref repeat; Ref end; int subdivs; bool overlap; -public: - void set_begin_texture(const Ref& p_texture); +public: + void set_begin_texture(const Ref &p_texture); Ref get_begin_texture() const; - void set_repeat_texture(const Ref& p_texture); + void set_repeat_texture(const Ref &p_texture); Ref get_repeat_texture() const; - void set_end_texture(const Ref& p_texture); + void set_end_texture(const Ref &p_texture); Ref get_end_texture() const; void set_subdivisions(int p_amount); diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp index 0ffaf81e3..88845a729 100644 --- a/scene/2d/physics_body_2d.cpp +++ b/scene/2d/physics_body_2d.cpp @@ -31,7 +31,7 @@ void PhysicsBody2D::_notification(int p_what) { -/* + /* switch(p_what) { case NOTIFICATION_TRANSFORM_CHANGED: { @@ -43,78 +43,74 @@ void PhysicsBody2D::_notification(int p_what) { */ } -void PhysicsBody2D::set_one_way_collision_direction(const Vector2& p_dir) { +void PhysicsBody2D::set_one_way_collision_direction(const Vector2 &p_dir) { - one_way_collision_direction=p_dir; - Physics2DServer::get_singleton()->body_set_one_way_collision_direction(get_rid(),p_dir); + one_way_collision_direction = p_dir; + Physics2DServer::get_singleton()->body_set_one_way_collision_direction(get_rid(), p_dir); } -Vector2 PhysicsBody2D::get_one_way_collision_direction() const{ +Vector2 PhysicsBody2D::get_one_way_collision_direction() const { return one_way_collision_direction; } - void PhysicsBody2D::set_one_way_collision_max_depth(float p_depth) { - one_way_collision_max_depth=p_depth; - Physics2DServer::get_singleton()->body_set_one_way_collision_max_depth(get_rid(),p_depth); - + one_way_collision_max_depth = p_depth; + Physics2DServer::get_singleton()->body_set_one_way_collision_max_depth(get_rid(), p_depth); } -float PhysicsBody2D::get_one_way_collision_max_depth() const{ +float PhysicsBody2D::get_one_way_collision_max_depth() const { return one_way_collision_max_depth; } - void PhysicsBody2D::_set_layers(uint32_t p_mask) { set_collision_layer(p_mask); set_collision_mask(p_mask); } -uint32_t PhysicsBody2D::_get_layers() const{ +uint32_t PhysicsBody2D::_get_layers() const { return get_collision_layer(); } void PhysicsBody2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_collision_layer","mask"),&PhysicsBody2D::set_collision_layer); - ClassDB::bind_method(D_METHOD("get_collision_layer"),&PhysicsBody2D::get_collision_layer); - ClassDB::bind_method(D_METHOD("set_collision_mask","mask"),&PhysicsBody2D::set_collision_mask); - ClassDB::bind_method(D_METHOD("get_collision_mask"),&PhysicsBody2D::get_collision_mask); + ClassDB::bind_method(D_METHOD("set_collision_layer", "mask"), &PhysicsBody2D::set_collision_layer); + ClassDB::bind_method(D_METHOD("get_collision_layer"), &PhysicsBody2D::get_collision_layer); + ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &PhysicsBody2D::set_collision_mask); + ClassDB::bind_method(D_METHOD("get_collision_mask"), &PhysicsBody2D::get_collision_mask); + ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &PhysicsBody2D::set_collision_mask_bit); + ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &PhysicsBody2D::get_collision_mask_bit); - ClassDB::bind_method(D_METHOD("set_collision_mask_bit","bit","value"),&PhysicsBody2D::set_collision_mask_bit); - ClassDB::bind_method(D_METHOD("get_collision_mask_bit","bit"),&PhysicsBody2D::get_collision_mask_bit); + ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &PhysicsBody2D::set_collision_layer_bit); + ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &PhysicsBody2D::get_collision_layer_bit); - ClassDB::bind_method(D_METHOD("set_collision_layer_bit","bit","value"),&PhysicsBody2D::set_collision_layer_bit); - ClassDB::bind_method(D_METHOD("get_collision_layer_bit","bit"),&PhysicsBody2D::get_collision_layer_bit); + ClassDB::bind_method(D_METHOD("_set_layers", "mask"), &PhysicsBody2D::_set_layers); + ClassDB::bind_method(D_METHOD("_get_layers"), &PhysicsBody2D::_get_layers); + ClassDB::bind_method(D_METHOD("set_one_way_collision_direction", "dir"), &PhysicsBody2D::set_one_way_collision_direction); + ClassDB::bind_method(D_METHOD("get_one_way_collision_direction"), &PhysicsBody2D::get_one_way_collision_direction); + ClassDB::bind_method(D_METHOD("set_one_way_collision_max_depth", "depth"), &PhysicsBody2D::set_one_way_collision_max_depth); + ClassDB::bind_method(D_METHOD("get_one_way_collision_max_depth"), &PhysicsBody2D::get_one_way_collision_max_depth); + ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body:PhysicsBody2D"), &PhysicsBody2D::add_collision_exception_with); + ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body:PhysicsBody2D"), &PhysicsBody2D::remove_collision_exception_with); + ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_2D_PHYSICS, "", 0), "_set_layers", "_get_layers"); //for backwards compat - ClassDB::bind_method(D_METHOD("_set_layers","mask"),&PhysicsBody2D::_set_layers); - ClassDB::bind_method(D_METHOD("_get_layers"),&PhysicsBody2D::_get_layers); - ClassDB::bind_method(D_METHOD("set_one_way_collision_direction","dir"),&PhysicsBody2D::set_one_way_collision_direction); - ClassDB::bind_method(D_METHOD("get_one_way_collision_direction"),&PhysicsBody2D::get_one_way_collision_direction); - ClassDB::bind_method(D_METHOD("set_one_way_collision_max_depth","depth"),&PhysicsBody2D::set_one_way_collision_max_depth); - ClassDB::bind_method(D_METHOD("get_one_way_collision_max_depth"),&PhysicsBody2D::get_one_way_collision_max_depth); - ClassDB::bind_method(D_METHOD("add_collision_exception_with","body:PhysicsBody2D"),&PhysicsBody2D::add_collision_exception_with); - ClassDB::bind_method(D_METHOD("remove_collision_exception_with","body:PhysicsBody2D"),&PhysicsBody2D::remove_collision_exception_with); - ADD_PROPERTY(PropertyInfo(Variant::INT,"layers",PROPERTY_HINT_LAYERS_2D_PHYSICS,"",0),"_set_layers","_get_layers"); //for backwards compat - - ADD_GROUP("Collision","collision_"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"collision_layer",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_collision_layer","get_collision_layer"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"collision_mask",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_collision_mask","get_collision_mask"); - ADD_GROUP("",""); - ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2,"one_way_collision/direction"),"set_one_way_collision_direction","get_one_way_collision_direction"); - ADD_PROPERTYNZ(PropertyInfo(Variant::REAL,"one_way_collision/max_depth"),"set_one_way_collision_max_depth","get_one_way_collision_max_depth"); + ADD_GROUP("Collision", "collision_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_layer", "get_collision_layer"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_mask", "get_collision_mask"); + ADD_GROUP("", ""); + ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "one_way_collision/direction"), "set_one_way_collision_direction", "get_one_way_collision_direction"); + ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "one_way_collision/max_depth"), "set_one_way_collision_max_depth", "get_one_way_collision_max_depth"); } void PhysicsBody2D::set_collision_layer(uint32_t p_mask) { - mask=p_mask; - Physics2DServer::get_singleton()->body_set_layer_mask(get_rid(),p_mask); + mask = p_mask; + Physics2DServer::get_singleton()->body_set_layer_mask(get_rid(), p_mask); } uint32_t PhysicsBody2D::get_collision_layer() const { @@ -124,8 +120,8 @@ uint32_t PhysicsBody2D::get_collision_layer() const { void PhysicsBody2D::set_collision_mask(uint32_t p_mask) { - collision_mask=p_mask; - Physics2DServer::get_singleton()->body_set_collision_mask(get_rid(),p_mask); + collision_mask = p_mask; + Physics2DServer::get_singleton()->body_set_collision_mask(get_rid(), p_mask); } uint32_t PhysicsBody2D::get_collision_mask() const { @@ -137,44 +133,41 @@ void PhysicsBody2D::set_collision_mask_bit(int p_bit, bool p_value) { uint32_t mask = get_collision_mask(); if (p_value) - mask|=1<body_create(p_mode), false) { +PhysicsBody2D::PhysicsBody2D(Physics2DServer::BodyMode p_mode) + : CollisionObject2D(Physics2DServer::get_singleton()->body_create(p_mode), false) { - mask=1; - collision_mask=1; + mask = 1; + collision_mask = 1; set_one_way_collision_max_depth(0); set_pickable(false); - } -void PhysicsBody2D::add_collision_exception_with(Node* p_node) { +void PhysicsBody2D::add_collision_exception_with(Node *p_node) { ERR_FAIL_NULL(p_node); PhysicsBody2D *physics_body = p_node->cast_to(); @@ -182,11 +175,10 @@ void PhysicsBody2D::add_collision_exception_with(Node* p_node) { ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type"); } ERR_FAIL_COND(!physics_body); - Physics2DServer::get_singleton()->body_add_collision_exception(get_rid(),physics_body->get_rid()); - + Physics2DServer::get_singleton()->body_add_collision_exception(get_rid(), physics_body->get_rid()); } -void PhysicsBody2D::remove_collision_exception_with(Node* p_node) { +void PhysicsBody2D::remove_collision_exception_with(Node *p_node) { ERR_FAIL_NULL(p_node); PhysicsBody2D *physics_body = p_node->cast_to(); @@ -194,20 +186,19 @@ void PhysicsBody2D::remove_collision_exception_with(Node* p_node) { ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type"); } ERR_FAIL_COND(!physics_body); - Physics2DServer::get_singleton()->body_remove_collision_exception(get_rid(),physics_body->get_rid()); + Physics2DServer::get_singleton()->body_remove_collision_exception(get_rid(), physics_body->get_rid()); } -void StaticBody2D::set_constant_linear_velocity(const Vector2& p_vel) { - - constant_linear_velocity=p_vel; - Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_LINEAR_VELOCITY,constant_linear_velocity); +void StaticBody2D::set_constant_linear_velocity(const Vector2 &p_vel) { + constant_linear_velocity = p_vel; + Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_LINEAR_VELOCITY, constant_linear_velocity); } void StaticBody2D::set_constant_angular_velocity(real_t p_vel) { - constant_angular_velocity=p_vel; - Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_ANGULAR_VELOCITY,constant_angular_velocity); + constant_angular_velocity = p_vel; + Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_ANGULAR_VELOCITY, constant_angular_velocity); } Vector2 StaticBody2D::get_constant_linear_velocity() const { @@ -242,91 +233,80 @@ void StaticBody2D::_update_xform() { } #endif +void StaticBody2D::set_friction(real_t p_friction) { -void StaticBody2D::set_friction(real_t p_friction){ - - ERR_FAIL_COND(p_friction<0 || p_friction>1); - - friction=p_friction; - Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_FRICTION,friction); + ERR_FAIL_COND(p_friction < 0 || p_friction > 1); + friction = p_friction; + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, friction); } -real_t StaticBody2D::get_friction() const{ +real_t StaticBody2D::get_friction() const { return friction; } -void StaticBody2D::set_bounce(real_t p_bounce){ +void StaticBody2D::set_bounce(real_t p_bounce) { - ERR_FAIL_COND(p_bounce<0 || p_bounce>1); - - bounce=p_bounce; - Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_BOUNCE,bounce); + ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1); + bounce = p_bounce; + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, bounce); } -real_t StaticBody2D::get_bounce() const{ +real_t StaticBody2D::get_bounce() const { return bounce; } void StaticBody2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_constant_linear_velocity","vel"),&StaticBody2D::set_constant_linear_velocity); - ClassDB::bind_method(D_METHOD("set_constant_angular_velocity","vel"),&StaticBody2D::set_constant_angular_velocity); - ClassDB::bind_method(D_METHOD("get_constant_linear_velocity"),&StaticBody2D::get_constant_linear_velocity); - ClassDB::bind_method(D_METHOD("get_constant_angular_velocity"),&StaticBody2D::get_constant_angular_velocity); - ClassDB::bind_method(D_METHOD("set_friction","friction"),&StaticBody2D::set_friction); - ClassDB::bind_method(D_METHOD("get_friction"),&StaticBody2D::get_friction); + ClassDB::bind_method(D_METHOD("set_constant_linear_velocity", "vel"), &StaticBody2D::set_constant_linear_velocity); + ClassDB::bind_method(D_METHOD("set_constant_angular_velocity", "vel"), &StaticBody2D::set_constant_angular_velocity); + ClassDB::bind_method(D_METHOD("get_constant_linear_velocity"), &StaticBody2D::get_constant_linear_velocity); + ClassDB::bind_method(D_METHOD("get_constant_angular_velocity"), &StaticBody2D::get_constant_angular_velocity); + ClassDB::bind_method(D_METHOD("set_friction", "friction"), &StaticBody2D::set_friction); + ClassDB::bind_method(D_METHOD("get_friction"), &StaticBody2D::get_friction); - ClassDB::bind_method(D_METHOD("set_bounce","bounce"),&StaticBody2D::set_bounce); - ClassDB::bind_method(D_METHOD("get_bounce"),&StaticBody2D::get_bounce); + ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &StaticBody2D::set_bounce); + ClassDB::bind_method(D_METHOD("get_bounce"), &StaticBody2D::get_bounce); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"constant_linear_velocity"),"set_constant_linear_velocity","get_constant_linear_velocity"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"constant_angular_velocity"),"set_constant_angular_velocity","get_constant_angular_velocity"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_friction","get_friction"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_bounce","get_bounce"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "constant_linear_velocity"), "set_constant_linear_velocity", "get_constant_linear_velocity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "constant_angular_velocity"), "set_constant_angular_velocity", "get_constant_angular_velocity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce"); } -StaticBody2D::StaticBody2D() : PhysicsBody2D(Physics2DServer::BODY_MODE_STATIC) { - - constant_angular_velocity=0; - bounce=0; - friction=1; - +StaticBody2D::StaticBody2D() + : PhysicsBody2D(Physics2DServer::BODY_MODE_STATIC) { + constant_angular_velocity = 0; + bounce = 0; + friction = 1; } StaticBody2D::~StaticBody2D() { - } - - - void RigidBody2D::_body_enter_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=contact_monitor->body_map.find(p_id); + Map::Element *E = contact_monitor->body_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(E->get().in_scene); - contact_monitor->locked=true; - - E->get().in_scene=true; - emit_signal(SceneStringNames::get_singleton()->body_entered,node); + contact_monitor->locked = true; + E->get().in_scene = true; + emit_signal(SceneStringNames::get_singleton()->body_entered, node); - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_entered,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].local_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_entered, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape); } - contact_monitor->locked=false; - - + contact_monitor->locked = false; } void RigidBody2D::_body_exit_tree(ObjectID p_id) { @@ -334,33 +314,32 @@ void RigidBody2D::_body_exit_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=contact_monitor->body_map.find(p_id); + Map::Element *E = contact_monitor->body_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(!E->get().in_scene); - E->get().in_scene=false; + E->get().in_scene = false; - contact_monitor->locked=true; + contact_monitor->locked = true; - emit_signal(SceneStringNames::get_singleton()->body_exited,node); + emit_signal(SceneStringNames::get_singleton()->body_exited, node); - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].local_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape); } - contact_monitor->locked=false; - + contact_monitor->locked = false; } -void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shape,int p_local_shape) { +void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shape, int p_local_shape) { - bool body_in = p_status==1; - ObjectID objid=p_instance; + bool body_in = p_status == 1; + ObjectID objid = p_instance; Object *obj = ObjectDB::get_instance(objid); Node *node = obj ? obj->cast_to() : NULL; - Map::Element *E=contact_monitor->body_map.find(objid); + Map::Element *E = contact_monitor->body_map.find(objid); /*if (obj) { if (body_in) @@ -374,14 +353,14 @@ void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shap if (body_in) { if (!E) { - E = contact_monitor->body_map.insert(objid,BodyState()); + E = contact_monitor->body_map.insert(objid, BodyState()); //E->get().rc=0; - E->get().in_scene=node && node->is_inside_tree(); + E->get().in_scene = node && node->is_inside_tree(); if (node) { - node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree,make_binds(objid)); - node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree,make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree, make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree, make_binds(objid)); if (E->get().in_scene) { - emit_signal(SceneStringNames::get_singleton()->body_entered,node); + emit_signal(SceneStringNames::get_singleton()->body_entered, node); } } @@ -389,11 +368,10 @@ void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shap } if (node) - E->get().shapes.insert(ShapePair(p_body_shape,p_local_shape)); - + E->get().shapes.insert(ShapePair(p_body_shape, p_local_shape)); if (E->get().in_scene) { - emit_signal(SceneStringNames::get_singleton()->body_shape_entered,objid,node,p_body_shape,p_local_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_entered, objid, node, p_body_shape, p_local_shape); } } else { @@ -401,31 +379,27 @@ void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shap //E->get().rc--; if (node) - E->get().shapes.erase(ShapePair(p_body_shape,p_local_shape)); + E->get().shapes.erase(ShapePair(p_body_shape, p_local_shape)); bool in_scene = E->get().in_scene; if (E->get().shapes.empty()) { if (node) { - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree); if (in_scene) - emit_signal(SceneStringNames::get_singleton()->body_exited,obj); - + emit_signal(SceneStringNames::get_singleton()->body_exited, obj); } contact_monitor->body_map.erase(E); } if (node && in_scene) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,objid,obj,p_body_shape,p_local_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, objid, obj, p_body_shape, p_local_shape); } - } - } - struct _RigidBody2DInOut { ObjectID id; @@ -433,62 +407,60 @@ struct _RigidBody2DInOut { int local_shape; }; +bool RigidBody2D::_test_motion(const Vector2 &p_motion, float p_margin, const Ref &p_result) { -bool RigidBody2D::_test_motion(const Vector2& p_motion,float p_margin,const Ref& p_result) { - - Physics2DServer::MotionResult *r=NULL; + Physics2DServer::MotionResult *r = NULL; if (p_result.is_valid()) - r=p_result->get_result_ptr(); - return Physics2DServer::get_singleton()->body_test_motion(get_rid(),get_global_transform(),p_motion,p_margin,r); - + r = p_result->get_result_ptr(); + return Physics2DServer::get_singleton()->body_test_motion(get_rid(), get_global_transform(), p_motion, p_margin, r); } void RigidBody2D::_direct_state_changed(Object *p_state) { - //eh.. fuck +//eh.. fuck #ifdef DEBUG_ENABLED - state=p_state->cast_to(); + state = p_state->cast_to(); #else - state=(Physics2DDirectBodyState*)p_state; //trust it + state = (Physics2DDirectBodyState *)p_state; //trust it #endif set_block_transform_notify(true); // don't want notify (would feedback loop) - if (mode!=MODE_KINEMATIC) + if (mode != MODE_KINEMATIC) set_global_transform(state->get_transform()); - linear_velocity=state->get_linear_velocity(); - angular_velocity=state->get_angular_velocity(); - if(sleeping!=state->is_sleeping()) { - sleeping=state->is_sleeping(); + linear_velocity = state->get_linear_velocity(); + angular_velocity = state->get_angular_velocity(); + if (sleeping != state->is_sleeping()) { + sleeping = state->is_sleeping(); emit_signal(SceneStringNames::get_singleton()->sleeping_state_changed); } if (get_script_instance()) - get_script_instance()->call("_integrate_forces",state); + get_script_instance()->call("_integrate_forces", state); set_block_transform_notify(false); // want it back if (contact_monitor) { - contact_monitor->locked=true; + contact_monitor->locked = true; //untag all - int rc=0; - for( Map::Element *E=contact_monitor->body_map.front();E;E=E->next()) { + int rc = 0; + for (Map::Element *E = contact_monitor->body_map.front(); E; E = E->next()) { - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - E->get().shapes[i].tagged=false; + E->get().shapes[i].tagged = false; rc++; } } - _RigidBody2DInOut *toadd=(_RigidBody2DInOut*)alloca(state->get_contact_count()*sizeof(_RigidBody2DInOut)); - int toadd_count=0;//state->get_contact_count(); - RigidBody2D_RemoveAction *toremove=(RigidBody2D_RemoveAction*)alloca(rc*sizeof(RigidBody2D_RemoveAction)); - int toremove_count=0; + _RigidBody2DInOut *toadd = (_RigidBody2DInOut *)alloca(state->get_contact_count() * sizeof(_RigidBody2DInOut)); + int toadd_count = 0; //state->get_contact_count(); + RigidBody2D_RemoveAction *toremove = (RigidBody2D_RemoveAction *)alloca(rc * sizeof(RigidBody2D_RemoveAction)); + int toremove_count = 0; //put the ones to add - for(int i=0;iget_contact_count();i++) { + for (int i = 0; i < state->get_contact_count(); i++) { ObjectID obj = state->get_contact_collider_id(i); int local_shape = state->get_contact_local_shape(i); @@ -496,270 +468,250 @@ void RigidBody2D::_direct_state_changed(Object *p_state) { //bool found=false; - Map::Element *E=contact_monitor->body_map.find(obj); + Map::Element *E = contact_monitor->body_map.find(obj); if (!E) { - toadd[toadd_count].local_shape=local_shape; - toadd[toadd_count].id=obj; - toadd[toadd_count].shape=shape; + toadd[toadd_count].local_shape = local_shape; + toadd[toadd_count].id = obj; + toadd[toadd_count].shape = shape; toadd_count++; continue; } - ShapePair sp( shape,local_shape ); + ShapePair sp(shape, local_shape); int idx = E->get().shapes.find(sp); - if (idx==-1) { + if (idx == -1) { - toadd[toadd_count].local_shape=local_shape; - toadd[toadd_count].id=obj; - toadd[toadd_count].shape=shape; + toadd[toadd_count].local_shape = local_shape; + toadd[toadd_count].id = obj; + toadd[toadd_count].shape = shape; toadd_count++; continue; } - E->get().shapes[idx].tagged=true; + E->get().shapes[idx].tagged = true; } //put the ones to remove - for( Map::Element *E=contact_monitor->body_map.front();E;E=E->next()) { + for (Map::Element *E = contact_monitor->body_map.front(); E; E = E->next()) { - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { if (!E->get().shapes[i].tagged) { - toremove[toremove_count].body_id=E->key(); - toremove[toremove_count].pair=E->get().shapes[i]; + toremove[toremove_count].body_id = E->key(); + toremove[toremove_count].pair = E->get().shapes[i]; toremove_count++; } } } - //process remotions + for (int i = 0; i < toremove_count; i++) { - for(int i=0;ilocked=false; - + contact_monitor->locked = false; } - - - state=NULL; + state = NULL; } - void RigidBody2D::set_mode(Mode p_mode) { - mode=p_mode; - switch(p_mode) { + mode = p_mode; + switch (p_mode) { case MODE_RIGID: { - Physics2DServer::get_singleton()->body_set_mode(get_rid(),Physics2DServer::BODY_MODE_RIGID); + Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_RIGID); } break; case MODE_STATIC: { - Physics2DServer::get_singleton()->body_set_mode(get_rid(),Physics2DServer::BODY_MODE_STATIC); + Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_STATIC); } break; case MODE_KINEMATIC: { - Physics2DServer::get_singleton()->body_set_mode(get_rid(),Physics2DServer::BODY_MODE_KINEMATIC); + Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_KINEMATIC); } break; case MODE_CHARACTER: { - Physics2DServer::get_singleton()->body_set_mode(get_rid(),Physics2DServer::BODY_MODE_CHARACTER); + Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_CHARACTER); } break; - } } -RigidBody2D::Mode RigidBody2D::get_mode() const{ +RigidBody2D::Mode RigidBody2D::get_mode() const { return mode; } -void RigidBody2D::set_mass(real_t p_mass){ +void RigidBody2D::set_mass(real_t p_mass) { - ERR_FAIL_COND(p_mass<=0); - mass=p_mass; + ERR_FAIL_COND(p_mass <= 0); + mass = p_mass; _change_notify("mass"); _change_notify("weight"); - Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_MASS,mass); - + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_MASS, mass); } -real_t RigidBody2D::get_mass() const{ +real_t RigidBody2D::get_mass() const { return mass; } void RigidBody2D::set_inertia(real_t p_inertia) { - ERR_FAIL_COND(p_inertia<=0); - Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_INERTIA,p_inertia); + ERR_FAIL_COND(p_inertia <= 0); + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_INERTIA, p_inertia); } -real_t RigidBody2D::get_inertia() const{ +real_t RigidBody2D::get_inertia() const { - return Physics2DServer::get_singleton()->body_get_param(get_rid(),Physics2DServer::BODY_PARAM_INERTIA); + return Physics2DServer::get_singleton()->body_get_param(get_rid(), Physics2DServer::BODY_PARAM_INERTIA); } -void RigidBody2D::set_weight(real_t p_weight){ +void RigidBody2D::set_weight(real_t p_weight) { - set_mass(p_weight/9.8); + set_mass(p_weight / 9.8); } -real_t RigidBody2D::get_weight() const{ +real_t RigidBody2D::get_weight() const { - return mass*9.8; + return mass * 9.8; } +void RigidBody2D::set_friction(real_t p_friction) { -void RigidBody2D::set_friction(real_t p_friction){ - - ERR_FAIL_COND(p_friction<0 || p_friction>1); - - friction=p_friction; - Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_FRICTION,friction); + ERR_FAIL_COND(p_friction < 0 || p_friction > 1); + friction = p_friction; + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, friction); } -real_t RigidBody2D::get_friction() const{ +real_t RigidBody2D::get_friction() const { return friction; } -void RigidBody2D::set_bounce(real_t p_bounce){ +void RigidBody2D::set_bounce(real_t p_bounce) { - ERR_FAIL_COND(p_bounce<0 || p_bounce>1); - - bounce=p_bounce; - Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_BOUNCE,bounce); + ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1); + bounce = p_bounce; + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, bounce); } -real_t RigidBody2D::get_bounce() const{ +real_t RigidBody2D::get_bounce() const { return bounce; } +void RigidBody2D::set_gravity_scale(real_t p_gravity_scale) { -void RigidBody2D::set_gravity_scale(real_t p_gravity_scale){ - - gravity_scale=p_gravity_scale; - Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_GRAVITY_SCALE,gravity_scale); - + gravity_scale = p_gravity_scale; + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_GRAVITY_SCALE, gravity_scale); } -real_t RigidBody2D::get_gravity_scale() const{ +real_t RigidBody2D::get_gravity_scale() const { return gravity_scale; } -void RigidBody2D::set_linear_damp(real_t p_linear_damp){ - - ERR_FAIL_COND(p_linear_damp<-1); - linear_damp=p_linear_damp; - Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_LINEAR_DAMP,linear_damp); +void RigidBody2D::set_linear_damp(real_t p_linear_damp) { + ERR_FAIL_COND(p_linear_damp < -1); + linear_damp = p_linear_damp; + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_LINEAR_DAMP, linear_damp); } -real_t RigidBody2D::get_linear_damp() const{ +real_t RigidBody2D::get_linear_damp() const { return linear_damp; } -void RigidBody2D::set_angular_damp(real_t p_angular_damp){ - - ERR_FAIL_COND(p_angular_damp<-1); - angular_damp=p_angular_damp; - Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_ANGULAR_DAMP,angular_damp); +void RigidBody2D::set_angular_damp(real_t p_angular_damp) { + ERR_FAIL_COND(p_angular_damp < -1); + angular_damp = p_angular_damp; + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_ANGULAR_DAMP, angular_damp); } -real_t RigidBody2D::get_angular_damp() const{ +real_t RigidBody2D::get_angular_damp() const { return angular_damp; } -void RigidBody2D::set_axis_velocity(const Vector2& p_axis) { +void RigidBody2D::set_axis_velocity(const Vector2 &p_axis) { - Vector2 v = state? state->get_linear_velocity() : linear_velocity; + Vector2 v = state ? state->get_linear_velocity() : linear_velocity; Vector2 axis = p_axis.normalized(); - v-=axis*axis.dot(v); - v+=p_axis; + v -= axis * axis.dot(v); + v += p_axis; if (state) { set_linear_velocity(v); } else { - Physics2DServer::get_singleton()->body_set_axis_velocity(get_rid(),p_axis); - linear_velocity=v; + Physics2DServer::get_singleton()->body_set_axis_velocity(get_rid(), p_axis); + linear_velocity = v; } } -void RigidBody2D::set_linear_velocity(const Vector2& p_velocity){ +void RigidBody2D::set_linear_velocity(const Vector2 &p_velocity) { - linear_velocity=p_velocity; + linear_velocity = p_velocity; if (state) state->set_linear_velocity(linear_velocity); else { - Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_LINEAR_VELOCITY,linear_velocity); + Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_LINEAR_VELOCITY, linear_velocity); } - } -Vector2 RigidBody2D::get_linear_velocity() const{ +Vector2 RigidBody2D::get_linear_velocity() const { return linear_velocity; } -void RigidBody2D::set_angular_velocity(real_t p_velocity){ +void RigidBody2D::set_angular_velocity(real_t p_velocity) { - angular_velocity=p_velocity; + angular_velocity = p_velocity; if (state) state->set_angular_velocity(angular_velocity); else - Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_ANGULAR_VELOCITY,angular_velocity); + Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_ANGULAR_VELOCITY, angular_velocity); } -real_t RigidBody2D::get_angular_velocity() const{ +real_t RigidBody2D::get_angular_velocity() const { return angular_velocity; } -void RigidBody2D::set_use_custom_integrator(bool p_enable){ +void RigidBody2D::set_use_custom_integrator(bool p_enable) { - if (custom_integrator==p_enable) + if (custom_integrator == p_enable) return; - custom_integrator=p_enable; - Physics2DServer::get_singleton()->body_set_omit_force_integration(get_rid(),p_enable); - - + custom_integrator = p_enable; + Physics2DServer::get_singleton()->body_set_omit_force_integration(get_rid(), p_enable); } -bool RigidBody2D::is_using_custom_integrator(){ +bool RigidBody2D::is_using_custom_integrator() { return custom_integrator; } void RigidBody2D::set_sleeping(bool p_sleeping) { - sleeping=p_sleeping; - Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_SLEEPING,sleeping); - + sleeping = p_sleeping; + Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_SLEEPING, sleeping); } void RigidBody2D::set_can_sleep(bool p_active) { - can_sleep=p_active; - Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_CAN_SLEEP,p_active); + can_sleep = p_active; + Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_CAN_SLEEP, p_active); } bool RigidBody2D::is_able_to_sleep() const { @@ -774,21 +726,21 @@ bool RigidBody2D::is_sleeping() const { void RigidBody2D::set_max_contacts_reported(int p_amount) { - max_contacts_reported=p_amount; - Physics2DServer::get_singleton()->body_set_max_contacts_reported(get_rid(),p_amount); + max_contacts_reported = p_amount; + Physics2DServer::get_singleton()->body_set_max_contacts_reported(get_rid(), p_amount); } -int RigidBody2D::get_max_contacts_reported() const{ +int RigidBody2D::get_max_contacts_reported() const { return max_contacts_reported; } -void RigidBody2D::apply_impulse(const Vector2& p_offset, const Vector2& p_impulse) { +void RigidBody2D::apply_impulse(const Vector2 &p_offset, const Vector2 &p_impulse) { - Physics2DServer::get_singleton()->body_apply_impulse(get_rid(),p_offset,p_impulse); + Physics2DServer::get_singleton()->body_apply_impulse(get_rid(), p_offset, p_impulse); } -void RigidBody2D::set_applied_force(const Vector2& p_force) { +void RigidBody2D::set_applied_force(const Vector2 &p_force) { Physics2DServer::get_singleton()->body_set_applied_force(get_rid(), p_force); }; @@ -808,16 +760,15 @@ float RigidBody2D::get_applied_torque() const { return Physics2DServer::get_singleton()->body_get_applied_torque(get_rid()); }; -void RigidBody2D::add_force(const Vector2& p_offset, const Vector2& p_force) { +void RigidBody2D::add_force(const Vector2 &p_offset, const Vector2 &p_force) { - Physics2DServer::get_singleton()->body_add_force(get_rid(),p_offset,p_force); + Physics2DServer::get_singleton()->body_add_force(get_rid(), p_offset, p_force); } void RigidBody2D::set_continuous_collision_detection_mode(CCDMode p_mode) { - ccd_mode=p_mode; - Physics2DServer::get_singleton()->body_set_continuous_collision_detection_mode(get_rid(),Physics2DServer::CCDMode(p_mode)); - + ccd_mode = p_mode; + Physics2DServer::get_singleton()->body_set_continuous_collision_detection_mode(get_rid(), Physics2DServer::CCDMode(p_mode)); } RigidBody2D::CCDMode RigidBody2D::get_continuous_collision_detection_mode() const { @@ -825,22 +776,20 @@ RigidBody2D::CCDMode RigidBody2D::get_continuous_collision_detection_mode() cons return ccd_mode; } - Array RigidBody2D::get_colliding_bodies() const { - ERR_FAIL_COND_V(!contact_monitor,Array()); + ERR_FAIL_COND_V(!contact_monitor, Array()); Array ret; ret.resize(contact_monitor->body_map.size()); - int idx=0; - for (const Map::Element *E=contact_monitor->body_map.front();E;E=E->next()) { + int idx = 0; + for (const Map::Element *E = contact_monitor->body_map.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); if (!obj) { - ret.resize( ret.size() -1 ); //ops + ret.resize(ret.size() - 1); //ops } else { - ret[idx++]=obj; + ret[idx++] = obj; } - } return ret; @@ -848,7 +797,7 @@ Array RigidBody2D::get_colliding_bodies() const { void RigidBody2D::set_contact_monitor(bool p_enabled) { - if (p_enabled==is_contact_monitor_enabled()) + if (p_enabled == is_contact_monitor_enabled()) return; if (!p_enabled) { @@ -858,180 +807,173 @@ void RigidBody2D::set_contact_monitor(bool p_enabled) { } ERR_FAIL_COND(contact_monitor->locked); - for(Map::Element *E=contact_monitor->body_map.front();E;E=E->next()) { + for (Map::Element *E = contact_monitor->body_map.front(); E; E = E->next()) { //clean up mess } - memdelete( contact_monitor ); - contact_monitor=NULL; + memdelete(contact_monitor); + contact_monitor = NULL; } else { - contact_monitor = memnew( ContactMonitor ); - contact_monitor->locked=false; + contact_monitor = memnew(ContactMonitor); + contact_monitor->locked = false; } - } bool RigidBody2D::is_contact_monitor_enabled() const { - return contact_monitor!=NULL; + return contact_monitor != NULL; } - - void RigidBody2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_mode","mode"),&RigidBody2D::set_mode); - ClassDB::bind_method(D_METHOD("get_mode"),&RigidBody2D::get_mode); - - ClassDB::bind_method(D_METHOD("set_mass","mass"),&RigidBody2D::set_mass); - ClassDB::bind_method(D_METHOD("get_mass"),&RigidBody2D::get_mass); + ClassDB::bind_method(D_METHOD("set_mode", "mode"), &RigidBody2D::set_mode); + ClassDB::bind_method(D_METHOD("get_mode"), &RigidBody2D::get_mode); - ClassDB::bind_method(D_METHOD("get_inertia"),&RigidBody2D::get_inertia); - ClassDB::bind_method(D_METHOD("set_inertia","inertia"),&RigidBody2D::set_inertia); + ClassDB::bind_method(D_METHOD("set_mass", "mass"), &RigidBody2D::set_mass); + ClassDB::bind_method(D_METHOD("get_mass"), &RigidBody2D::get_mass); - ClassDB::bind_method(D_METHOD("set_weight","weight"),&RigidBody2D::set_weight); - ClassDB::bind_method(D_METHOD("get_weight"),&RigidBody2D::get_weight); + ClassDB::bind_method(D_METHOD("get_inertia"), &RigidBody2D::get_inertia); + ClassDB::bind_method(D_METHOD("set_inertia", "inertia"), &RigidBody2D::set_inertia); - ClassDB::bind_method(D_METHOD("set_friction","friction"),&RigidBody2D::set_friction); - ClassDB::bind_method(D_METHOD("get_friction"),&RigidBody2D::get_friction); + ClassDB::bind_method(D_METHOD("set_weight", "weight"), &RigidBody2D::set_weight); + ClassDB::bind_method(D_METHOD("get_weight"), &RigidBody2D::get_weight); - ClassDB::bind_method(D_METHOD("set_bounce","bounce"),&RigidBody2D::set_bounce); - ClassDB::bind_method(D_METHOD("get_bounce"),&RigidBody2D::get_bounce); + ClassDB::bind_method(D_METHOD("set_friction", "friction"), &RigidBody2D::set_friction); + ClassDB::bind_method(D_METHOD("get_friction"), &RigidBody2D::get_friction); - ClassDB::bind_method(D_METHOD("set_gravity_scale","gravity_scale"),&RigidBody2D::set_gravity_scale); - ClassDB::bind_method(D_METHOD("get_gravity_scale"),&RigidBody2D::get_gravity_scale); + ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &RigidBody2D::set_bounce); + ClassDB::bind_method(D_METHOD("get_bounce"), &RigidBody2D::get_bounce); - ClassDB::bind_method(D_METHOD("set_linear_damp","linear_damp"),&RigidBody2D::set_linear_damp); - ClassDB::bind_method(D_METHOD("get_linear_damp"),&RigidBody2D::get_linear_damp); + ClassDB::bind_method(D_METHOD("set_gravity_scale", "gravity_scale"), &RigidBody2D::set_gravity_scale); + ClassDB::bind_method(D_METHOD("get_gravity_scale"), &RigidBody2D::get_gravity_scale); - ClassDB::bind_method(D_METHOD("set_angular_damp","angular_damp"),&RigidBody2D::set_angular_damp); - ClassDB::bind_method(D_METHOD("get_angular_damp"),&RigidBody2D::get_angular_damp); + ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &RigidBody2D::set_linear_damp); + ClassDB::bind_method(D_METHOD("get_linear_damp"), &RigidBody2D::get_linear_damp); - ClassDB::bind_method(D_METHOD("set_linear_velocity","linear_velocity"),&RigidBody2D::set_linear_velocity); - ClassDB::bind_method(D_METHOD("get_linear_velocity"),&RigidBody2D::get_linear_velocity); + ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &RigidBody2D::set_angular_damp); + ClassDB::bind_method(D_METHOD("get_angular_damp"), &RigidBody2D::get_angular_damp); - ClassDB::bind_method(D_METHOD("set_angular_velocity","angular_velocity"),&RigidBody2D::set_angular_velocity); - ClassDB::bind_method(D_METHOD("get_angular_velocity"),&RigidBody2D::get_angular_velocity); + ClassDB::bind_method(D_METHOD("set_linear_velocity", "linear_velocity"), &RigidBody2D::set_linear_velocity); + ClassDB::bind_method(D_METHOD("get_linear_velocity"), &RigidBody2D::get_linear_velocity); - ClassDB::bind_method(D_METHOD("set_max_contacts_reported","amount"),&RigidBody2D::set_max_contacts_reported); - ClassDB::bind_method(D_METHOD("get_max_contacts_reported"),&RigidBody2D::get_max_contacts_reported); + ClassDB::bind_method(D_METHOD("set_angular_velocity", "angular_velocity"), &RigidBody2D::set_angular_velocity); + ClassDB::bind_method(D_METHOD("get_angular_velocity"), &RigidBody2D::get_angular_velocity); - ClassDB::bind_method(D_METHOD("set_use_custom_integrator","enable"),&RigidBody2D::set_use_custom_integrator); - ClassDB::bind_method(D_METHOD("is_using_custom_integrator"),&RigidBody2D::is_using_custom_integrator); + ClassDB::bind_method(D_METHOD("set_max_contacts_reported", "amount"), &RigidBody2D::set_max_contacts_reported); + ClassDB::bind_method(D_METHOD("get_max_contacts_reported"), &RigidBody2D::get_max_contacts_reported); - ClassDB::bind_method(D_METHOD("set_contact_monitor","enabled"),&RigidBody2D::set_contact_monitor); - ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"),&RigidBody2D::is_contact_monitor_enabled); + ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &RigidBody2D::set_use_custom_integrator); + ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &RigidBody2D::is_using_custom_integrator); - ClassDB::bind_method(D_METHOD("set_continuous_collision_detection_mode","mode"),&RigidBody2D::set_continuous_collision_detection_mode); - ClassDB::bind_method(D_METHOD("get_continuous_collision_detection_mode"),&RigidBody2D::get_continuous_collision_detection_mode); + ClassDB::bind_method(D_METHOD("set_contact_monitor", "enabled"), &RigidBody2D::set_contact_monitor); + ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"), &RigidBody2D::is_contact_monitor_enabled); - ClassDB::bind_method(D_METHOD("set_axis_velocity","axis_velocity"),&RigidBody2D::set_axis_velocity); - ClassDB::bind_method(D_METHOD("apply_impulse","offset","impulse"),&RigidBody2D::apply_impulse); + ClassDB::bind_method(D_METHOD("set_continuous_collision_detection_mode", "mode"), &RigidBody2D::set_continuous_collision_detection_mode); + ClassDB::bind_method(D_METHOD("get_continuous_collision_detection_mode"), &RigidBody2D::get_continuous_collision_detection_mode); - ClassDB::bind_method(D_METHOD("set_applied_force","force"),&RigidBody2D::set_applied_force); - ClassDB::bind_method(D_METHOD("get_applied_force"),&RigidBody2D::get_applied_force); + ClassDB::bind_method(D_METHOD("set_axis_velocity", "axis_velocity"), &RigidBody2D::set_axis_velocity); + ClassDB::bind_method(D_METHOD("apply_impulse", "offset", "impulse"), &RigidBody2D::apply_impulse); - ClassDB::bind_method(D_METHOD("set_applied_torque","torque"),&RigidBody2D::set_applied_torque); - ClassDB::bind_method(D_METHOD("get_applied_torque"),&RigidBody2D::get_applied_torque); + ClassDB::bind_method(D_METHOD("set_applied_force", "force"), &RigidBody2D::set_applied_force); + ClassDB::bind_method(D_METHOD("get_applied_force"), &RigidBody2D::get_applied_force); - ClassDB::bind_method(D_METHOD("add_force","offset","force"),&RigidBody2D::add_force); + ClassDB::bind_method(D_METHOD("set_applied_torque", "torque"), &RigidBody2D::set_applied_torque); + ClassDB::bind_method(D_METHOD("get_applied_torque"), &RigidBody2D::get_applied_torque); - ClassDB::bind_method(D_METHOD("set_sleeping","sleeping"),&RigidBody2D::set_sleeping); - ClassDB::bind_method(D_METHOD("is_sleeping"),&RigidBody2D::is_sleeping); + ClassDB::bind_method(D_METHOD("add_force", "offset", "force"), &RigidBody2D::add_force); - ClassDB::bind_method(D_METHOD("set_can_sleep","able_to_sleep"),&RigidBody2D::set_can_sleep); - ClassDB::bind_method(D_METHOD("is_able_to_sleep"),&RigidBody2D::is_able_to_sleep); + ClassDB::bind_method(D_METHOD("set_sleeping", "sleeping"), &RigidBody2D::set_sleeping); + ClassDB::bind_method(D_METHOD("is_sleeping"), &RigidBody2D::is_sleeping); - ClassDB::bind_method(D_METHOD("test_motion","motion","margin","result:Physics2DTestMotionResult"),&RigidBody2D::_test_motion,DEFVAL(0.08),DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("set_can_sleep", "able_to_sleep"), &RigidBody2D::set_can_sleep); + ClassDB::bind_method(D_METHOD("is_able_to_sleep"), &RigidBody2D::is_able_to_sleep); - ClassDB::bind_method(D_METHOD("_direct_state_changed"),&RigidBody2D::_direct_state_changed); - ClassDB::bind_method(D_METHOD("_body_enter_tree"),&RigidBody2D::_body_enter_tree); - ClassDB::bind_method(D_METHOD("_body_exit_tree"),&RigidBody2D::_body_exit_tree); + ClassDB::bind_method(D_METHOD("test_motion", "motion", "margin", "result:Physics2DTestMotionResult"), &RigidBody2D::_test_motion, DEFVAL(0.08), DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("get_colliding_bodies"),&RigidBody2D::get_colliding_bodies); + ClassDB::bind_method(D_METHOD("_direct_state_changed"), &RigidBody2D::_direct_state_changed); + ClassDB::bind_method(D_METHOD("_body_enter_tree"), &RigidBody2D::_body_enter_tree); + ClassDB::bind_method(D_METHOD("_body_exit_tree"), &RigidBody2D::_body_exit_tree); - BIND_VMETHOD(MethodInfo("_integrate_forces",PropertyInfo(Variant::OBJECT,"state:Physics2DDirectBodyState"))); + ClassDB::bind_method(D_METHOD("get_colliding_bodies"), &RigidBody2D::get_colliding_bodies); - ADD_PROPERTY( PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Rigid,Static,Character,Kinematic"),"set_mode","get_mode"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"mass",PROPERTY_HINT_EXP_RANGE,"0.01,65535,0.01"),"set_mass","get_mass"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"weight",PROPERTY_HINT_EXP_RANGE,"0.01,65535,0.01",PROPERTY_USAGE_EDITOR),"set_weight","get_weight"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_friction","get_friction"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_bounce","get_bounce"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"gravity_scale",PROPERTY_HINT_RANGE,"-128,128,0.01"),"set_gravity_scale","get_gravity_scale"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"custom_integrator"),"set_use_custom_integrator","is_using_custom_integrator"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"continuous_cd",PROPERTY_HINT_ENUM,"Disabled,Cast Ray,Cast Shape"),"set_continuous_collision_detection_mode","get_continuous_collision_detection_mode"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"contacts_reported"),"set_max_contacts_reported","get_max_contacts_reported"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"contact_monitor"),"set_contact_monitor","is_contact_monitor_enabled"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"sleeping"),"set_sleeping","is_sleeping"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"can_sleep"),"set_can_sleep","is_able_to_sleep"); - ADD_GROUP("Linear","linear_"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"linear_velocity"),"set_linear_velocity","get_linear_velocity"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"linear_damp",PROPERTY_HINT_RANGE,"-1,128,0.01"),"set_linear_damp","get_linear_damp"); - ADD_GROUP("Angular","angular_"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_velocity"),"set_angular_velocity","get_angular_velocity"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_damp",PROPERTY_HINT_RANGE,"-1,128,0.01"),"set_angular_damp","get_angular_damp"); + BIND_VMETHOD(MethodInfo("_integrate_forces", PropertyInfo(Variant::OBJECT, "state:Physics2DDirectBodyState"))); - ADD_SIGNAL( MethodInfo("body_shape_entered",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"local_shape"))); - ADD_SIGNAL( MethodInfo("body_shape_exited",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"local_shape"))); - ADD_SIGNAL( MethodInfo("body_entered",PropertyInfo(Variant::OBJECT,"body"))); - ADD_SIGNAL( MethodInfo("body_exited",PropertyInfo(Variant::OBJECT,"body"))); - ADD_SIGNAL( MethodInfo("sleeping_state_changed")); + ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Rigid,Static,Character,Kinematic"), "set_mode", "get_mode"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "mass", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01"), "set_mass", "get_mass"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "weight", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01", PROPERTY_USAGE_EDITOR), "set_weight", "get_weight"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "continuous_cd", PROPERTY_HINT_ENUM, "Disabled,Cast Ray,Cast Shape"), "set_continuous_collision_detection_mode", "get_continuous_collision_detection_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "contacts_reported"), "set_max_contacts_reported", "get_max_contacts_reported"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "contact_monitor"), "set_contact_monitor", "is_contact_monitor_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sleeping"), "set_sleeping", "is_sleeping"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "can_sleep"), "set_can_sleep", "is_able_to_sleep"); + ADD_GROUP("Linear", "linear_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "linear_velocity"), "set_linear_velocity", "get_linear_velocity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "linear_damp", PROPERTY_HINT_RANGE, "-1,128,0.01"), "set_linear_damp", "get_linear_damp"); + ADD_GROUP("Angular", "angular_"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_velocity"), "set_angular_velocity", "get_angular_velocity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_damp", PROPERTY_HINT_RANGE, "-1,128,0.01"), "set_angular_damp", "get_angular_damp"); - BIND_CONSTANT( MODE_STATIC ); - BIND_CONSTANT( MODE_KINEMATIC ); - BIND_CONSTANT( MODE_RIGID ); - BIND_CONSTANT( MODE_CHARACTER ); + ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape"))); + ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape"))); + ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body"))); + ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body"))); + ADD_SIGNAL(MethodInfo("sleeping_state_changed")); - BIND_CONSTANT( CCD_MODE_DISABLED ); - BIND_CONSTANT( CCD_MODE_CAST_RAY ); - BIND_CONSTANT( CCD_MODE_CAST_SHAPE ); + BIND_CONSTANT(MODE_STATIC); + BIND_CONSTANT(MODE_KINEMATIC); + BIND_CONSTANT(MODE_RIGID); + BIND_CONSTANT(MODE_CHARACTER); + BIND_CONSTANT(CCD_MODE_DISABLED); + BIND_CONSTANT(CCD_MODE_CAST_RAY); + BIND_CONSTANT(CCD_MODE_CAST_SHAPE); } -RigidBody2D::RigidBody2D() : PhysicsBody2D(Physics2DServer::BODY_MODE_RIGID) { +RigidBody2D::RigidBody2D() + : PhysicsBody2D(Physics2DServer::BODY_MODE_RIGID) { - mode=MODE_RIGID; + mode = MODE_RIGID; - bounce=0; - mass=1; - friction=1; + bounce = 0; + mass = 1; + friction = 1; - gravity_scale=1; - linear_damp=-1; - angular_damp=-1; + gravity_scale = 1; + linear_damp = -1; + angular_damp = -1; - max_contacts_reported=0; - state=NULL; + max_contacts_reported = 0; + state = NULL; - angular_velocity=0; - sleeping=false; - ccd_mode=CCD_MODE_DISABLED; + angular_velocity = 0; + sleeping = false; + ccd_mode = CCD_MODE_DISABLED; - custom_integrator=false; - contact_monitor=NULL; - can_sleep=true; + custom_integrator = false; + contact_monitor = NULL; + can_sleep = true; - Physics2DServer::get_singleton()->body_set_force_integration_callback(get_rid(),this,"_direct_state_changed"); + Physics2DServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed"); } RigidBody2D::~RigidBody2D() { if (contact_monitor) - memdelete( contact_monitor ); - - - + memdelete(contact_monitor); } ////////////////////////// - Variant KinematicBody2D::_get_collider() const { - ObjectID oid=get_collider(); - if (oid==0) + ObjectID oid = get_collider(); + if (oid == 0) return Variant(); Object *obj = ObjectDB::get_instance(oid); if (!obj) @@ -1048,10 +990,9 @@ Variant KinematicBody2D::_get_collider() const { void KinematicBody2D::revert_motion() { Transform2D gt = get_global_transform(); - gt.elements[2]-=travel; - travel=Vector2(); + gt.elements[2] -= travel; + travel = Vector2(); set_global_transform(gt); - } Vector2 KinematicBody2D::get_travel() const { @@ -1059,26 +1000,24 @@ Vector2 KinematicBody2D::get_travel() const { return travel; } -Vector2 KinematicBody2D::move(const Vector2& p_motion) { +Vector2 KinematicBody2D::move(const Vector2 &p_motion) { #if 1 Transform2D gt = get_global_transform(); Physics2DServer::MotionResult result; - colliding = Physics2DServer::get_singleton()->body_test_motion(get_rid(),gt,p_motion,margin,&result); - - collider_metadata=result.collider_metadata; - collider_shape=result.collider_shape; - collider_vel=result.collider_velocity; - collision=result.collision_point; - normal=result.collision_normal; - collider=result.collider_id; + colliding = Physics2DServer::get_singleton()->body_test_motion(get_rid(), gt, p_motion, margin, &result); + collider_metadata = result.collider_metadata; + collider_shape = result.collider_shape; + collider_vel = result.collider_velocity; + collision = result.collision_point; + normal = result.collision_normal; + collider = result.collider_id; - gt.elements[2]+=result.motion; + gt.elements[2] += result.motion; set_global_transform(gt); - travel=result.motion; - + travel = result.motion; return result.remainder; @@ -1090,43 +1029,41 @@ Vector2 KinematicBody2D::move(const Vector2& p_motion) { //this took about a week to get right.. //but is it right? who knows at this point.. - colliding=false; - ERR_FAIL_COND_V(!is_inside_tree(),Vector2()); + colliding = false; + ERR_FAIL_COND_V(!is_inside_tree(), Vector2()); Physics2DDirectSpaceState *dss = Physics2DServer::get_singleton()->space_get_direct_state(get_world_2d()->get_space()); - ERR_FAIL_COND_V(!dss,Vector2()); - const int max_shapes=32; - Vector2 sr[max_shapes*2]; + ERR_FAIL_COND_V(!dss, Vector2()); + const int max_shapes = 32; + Vector2 sr[max_shapes * 2]; int res_shapes; Set exclude; exclude.insert(get_rid()); - //recover first - int recover_attempts=4; + int recover_attempts = 4; - bool collided=false; - uint32_t mask=0; + bool collided = false; + uint32_t mask = 0; if (true) - mask|=Physics2DDirectSpaceState::TYPE_MASK_STATIC_BODY; + mask |= Physics2DDirectSpaceState::TYPE_MASK_STATIC_BODY; if (true) - mask|=Physics2DDirectSpaceState::TYPE_MASK_KINEMATIC_BODY; + mask |= Physics2DDirectSpaceState::TYPE_MASK_KINEMATIC_BODY; if (true) - mask|=Physics2DDirectSpaceState::TYPE_MASK_RIGID_BODY; + mask |= Physics2DDirectSpaceState::TYPE_MASK_RIGID_BODY; if (true) - mask|=Physics2DDirectSpaceState::TYPE_MASK_CHARACTER_BODY; + mask |= Physics2DDirectSpaceState::TYPE_MASK_CHARACTER_BODY; //print_line("margin: "+rtos(margin)); do { //motion recover - for(int i=0;icollide_shape(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i),Vector2(),margin,sr,max_shapes,res_shapes,exclude,get_layer_mask(),mask)) - collided=true; - + if (dss->collide_shape(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), Vector2(), margin, sr, max_shapes, res_shapes, exclude, get_layer_mask(), mask)) + collided = true; } if (!collided) @@ -1134,10 +1071,10 @@ Vector2 KinematicBody2D::move(const Vector2& p_motion) { Vector2 recover_motion; - for(int i=0;icast_motion(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), p_motion, 0,lsafe,lunsafe,exclude,get_layer_mask(),mask); + float lsafe, lunsafe; + bool valid = dss->cast_motion(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), p_motion, 0, lsafe, lunsafe, exclude, get_layer_mask(), mask); //print_line("shape: "+itos(i)+" travel:"+rtos(ltravel)); if (!valid) { - safe=0; - unsafe=0; - best_shape=i; //sadly it's the best + safe = 0; + unsafe = 0; + best_shape = i; //sadly it's the best break; } - if (lsafe==1.0) { + if (lsafe == 1.0) { continue; } if (lsafe < safe) { - safe=lsafe; - unsafe=lunsafe; - best_shape=i; + safe = lsafe; + unsafe = lunsafe; + best_shape = i; } } - //print_line("best shape: "+itos(best_shape)+" motion "+p_motion); - if (safe>=1) { + if (safe >= 1) { //not collided - colliding=false; - + colliding = false; } else { //it collided, let's get the rest info in unsafe advance Transform2D ugt = get_global_transform(); - ugt.elements[2]+=p_motion*unsafe; + ugt.elements[2] += p_motion * unsafe; Physics2DDirectSpaceState::ShapeRestInfo rest_info; - bool c2 = dss->rest_info(get_shape(best_shape)->get_rid(), ugt*get_shape_transform(best_shape), Vector2(), margin,&rest_info,exclude,get_layer_mask(),mask); + bool c2 = dss->rest_info(get_shape(best_shape)->get_rid(), ugt * get_shape_transform(best_shape), Vector2(), margin, &rest_info, exclude, get_layer_mask(), mask); if (!c2) { //should not happen, but floating point precision is so weird.. - colliding=false; + colliding = false; } else { - //print_line("Travel: "+rtos(travel)); - colliding=true; - collision=rest_info.point; - normal=rest_info.normal; - collider=rest_info.collider_id; - collider_vel=rest_info.linear_velocity; - collider_shape=rest_info.shape; - collider_metadata=rest_info.metadata; + colliding = true; + collision = rest_info.point; + normal = rest_info.normal; + collider = rest_info.collider_id; + collider_vel = rest_info.linear_velocity; + collider_shape = rest_info.shape; + collider_metadata = rest_info.metadata; } - } - Vector2 motion=p_motion*safe; + Vector2 motion = p_motion * safe; Transform2D gt = get_global_transform(); - gt.elements[2]+=motion; + gt.elements[2] += motion; set_global_transform(gt); - return p_motion-motion; + return p_motion - motion; #endif } +Vector2 KinematicBody2D::move_and_slide(const Vector2 &p_linear_velocity, const Vector2 &p_floor_direction, float p_slope_stop_min_velocity, int p_max_bounces) { - -Vector2 KinematicBody2D::move_and_slide(const Vector2& p_linear_velocity,const Vector2& p_floor_direction,float p_slope_stop_min_velocity,int p_max_bounces) { - - Vector2 motion = (move_and_slide_floor_velocity+p_linear_velocity)*get_fixed_process_delta_time(); + Vector2 motion = (move_and_slide_floor_velocity + p_linear_velocity) * get_fixed_process_delta_time(); Vector2 lv = p_linear_velocity; - move_and_slide_on_floor=false; - move_and_slide_on_ceiling=false; - move_and_slide_on_wall=false; + move_and_slide_on_floor = false; + move_and_slide_on_ceiling = false; + move_and_slide_on_wall = false; move_and_slide_colliders.clear(); - move_and_slide_floor_velocity=Vector2(); + move_and_slide_floor_velocity = Vector2(); - while(p_max_bounces) { + while (p_max_bounces) { - motion=move(motion); + motion = move(motion); if (is_colliding()) { - - if (p_floor_direction==Vector2()) { + if (p_floor_direction == Vector2()) { //all is a wall - move_and_slide_on_wall=true; + move_and_slide_on_wall = true; } else { - if ( get_collision_normal().dot(p_floor_direction) > Math::cos(Math::deg2rad((float)45))) { //floor - + if (get_collision_normal().dot(p_floor_direction) > Math::cos(Math::deg2rad((float)45))) { //floor - move_and_slide_on_floor=true; - move_and_slide_floor_velocity=get_collider_velocity(); + move_and_slide_on_floor = true; + move_and_slide_floor_velocity = get_collider_velocity(); - if (get_travel().length()<1 && ABS((lv.x-move_and_slide_floor_velocity.x))body_test_motion(get_rid(),p_from,p_motion,margin); +bool KinematicBody2D::test_move(const Transform2D &p_from, const Vector2 &p_motion) { + ERR_FAIL_COND_V(!is_inside_tree(), false); + return Physics2DServer::get_singleton()->body_test_motion(get_rid(), p_from, p_motion, margin); } Vector2 KinematicBody2D::get_collision_pos() const { - ERR_FAIL_COND_V(!colliding,Vector2()); + ERR_FAIL_COND_V(!colliding, Vector2()); return collision; - } Vector2 KinematicBody2D::get_collision_normal() const { - ERR_FAIL_COND_V(!colliding,Vector2()); + ERR_FAIL_COND_V(!colliding, Vector2()); return normal; - } Vector2 KinematicBody2D::get_collider_velocity() const { @@ -1351,88 +1272,79 @@ Vector2 KinematicBody2D::get_collider_velocity() const { ObjectID KinematicBody2D::get_collider() const { - ERR_FAIL_COND_V(!colliding,0); + ERR_FAIL_COND_V(!colliding, 0); return collider; } - int KinematicBody2D::get_collider_shape() const { - ERR_FAIL_COND_V(!colliding,0); + ERR_FAIL_COND_V(!colliding, 0); return collider_shape; } Variant KinematicBody2D::get_collider_metadata() const { - ERR_FAIL_COND_V(!colliding,0); + ERR_FAIL_COND_V(!colliding, 0); return collider_metadata; - } - -bool KinematicBody2D::is_colliding() const{ +bool KinematicBody2D::is_colliding() const { return colliding; } void KinematicBody2D::set_collision_margin(float p_margin) { - margin=p_margin; + margin = p_margin; } -float KinematicBody2D::get_collision_margin() const{ +float KinematicBody2D::get_collision_margin() const { return margin; } void KinematicBody2D::_bind_methods() { + ClassDB::bind_method(D_METHOD("move", "rel_vec"), &KinematicBody2D::move); + ClassDB::bind_method(D_METHOD("move_to", "position"), &KinematicBody2D::move_to); + ClassDB::bind_method(D_METHOD("move_and_slide", "linear_velocity", "floor_normal", "slope_stop_min_velocity", "max_bounces"), &KinematicBody2D::move_and_slide, DEFVAL(Vector2(0, 0)), DEFVAL(5), DEFVAL(4)); - ClassDB::bind_method(D_METHOD("move","rel_vec"),&KinematicBody2D::move); - ClassDB::bind_method(D_METHOD("move_to","position"),&KinematicBody2D::move_to); - ClassDB::bind_method(D_METHOD("move_and_slide","linear_velocity","floor_normal","slope_stop_min_velocity","max_bounces"),&KinematicBody2D::move_and_slide,DEFVAL(Vector2(0,0)),DEFVAL(5),DEFVAL(4)); - - ClassDB::bind_method(D_METHOD("test_move","from","rel_vec"),&KinematicBody2D::test_move); - ClassDB::bind_method(D_METHOD("get_travel"),&KinematicBody2D::get_travel); - ClassDB::bind_method(D_METHOD("revert_motion"),&KinematicBody2D::revert_motion); - - ClassDB::bind_method(D_METHOD("is_colliding"),&KinematicBody2D::is_colliding); + ClassDB::bind_method(D_METHOD("test_move", "from", "rel_vec"), &KinematicBody2D::test_move); + ClassDB::bind_method(D_METHOD("get_travel"), &KinematicBody2D::get_travel); + ClassDB::bind_method(D_METHOD("revert_motion"), &KinematicBody2D::revert_motion); - ClassDB::bind_method(D_METHOD("get_collision_pos"),&KinematicBody2D::get_collision_pos); - ClassDB::bind_method(D_METHOD("get_collision_normal"),&KinematicBody2D::get_collision_normal); - ClassDB::bind_method(D_METHOD("get_collider_velocity"),&KinematicBody2D::get_collider_velocity); - ClassDB::bind_method(D_METHOD("get_collider:Variant"),&KinematicBody2D::_get_collider); - ClassDB::bind_method(D_METHOD("get_collider_shape"),&KinematicBody2D::get_collider_shape); - ClassDB::bind_method(D_METHOD("get_collider_metadata:Variant"),&KinematicBody2D::get_collider_metadata); - ClassDB::bind_method(D_METHOD("get_move_and_slide_colliders"),&KinematicBody2D::get_move_and_slide_colliders); - ClassDB::bind_method(D_METHOD("is_move_and_slide_on_floor"),&KinematicBody2D::is_move_and_slide_on_floor); - ClassDB::bind_method(D_METHOD("is_move_and_slide_on_ceiling"),&KinematicBody2D::is_move_and_slide_on_ceiling); - ClassDB::bind_method(D_METHOD("is_move_and_slide_on_wall"),&KinematicBody2D::is_move_and_slide_on_wall); + ClassDB::bind_method(D_METHOD("is_colliding"), &KinematicBody2D::is_colliding); - ClassDB::bind_method(D_METHOD("set_collision_margin","pixels"),&KinematicBody2D::set_collision_margin); - ClassDB::bind_method(D_METHOD("get_collision_margin","pixels"),&KinematicBody2D::get_collision_margin); - - ADD_PROPERTY( PropertyInfo(Variant::REAL,"collision/margin",PROPERTY_HINT_RANGE,"0.001,256,0.001"),"set_collision_margin","get_collision_margin"); + ClassDB::bind_method(D_METHOD("get_collision_pos"), &KinematicBody2D::get_collision_pos); + ClassDB::bind_method(D_METHOD("get_collision_normal"), &KinematicBody2D::get_collision_normal); + ClassDB::bind_method(D_METHOD("get_collider_velocity"), &KinematicBody2D::get_collider_velocity); + ClassDB::bind_method(D_METHOD("get_collider:Variant"), &KinematicBody2D::_get_collider); + ClassDB::bind_method(D_METHOD("get_collider_shape"), &KinematicBody2D::get_collider_shape); + ClassDB::bind_method(D_METHOD("get_collider_metadata:Variant"), &KinematicBody2D::get_collider_metadata); + ClassDB::bind_method(D_METHOD("get_move_and_slide_colliders"), &KinematicBody2D::get_move_and_slide_colliders); + ClassDB::bind_method(D_METHOD("is_move_and_slide_on_floor"), &KinematicBody2D::is_move_and_slide_on_floor); + ClassDB::bind_method(D_METHOD("is_move_and_slide_on_ceiling"), &KinematicBody2D::is_move_and_slide_on_ceiling); + ClassDB::bind_method(D_METHOD("is_move_and_slide_on_wall"), &KinematicBody2D::is_move_and_slide_on_wall); + ClassDB::bind_method(D_METHOD("set_collision_margin", "pixels"), &KinematicBody2D::set_collision_margin); + ClassDB::bind_method(D_METHOD("get_collision_margin", "pixels"), &KinematicBody2D::get_collision_margin); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "collision/margin", PROPERTY_HINT_RANGE, "0.001,256,0.001"), "set_collision_margin", "get_collision_margin"); } -KinematicBody2D::KinematicBody2D() : PhysicsBody2D(Physics2DServer::BODY_MODE_KINEMATIC){ - - colliding=false; - collider=0; +KinematicBody2D::KinematicBody2D() + : PhysicsBody2D(Physics2DServer::BODY_MODE_KINEMATIC) { - collider_shape=0; + colliding = false; + collider = 0; - margin=0.08; + collider_shape = 0; - move_and_slide_on_floor=false; - move_and_slide_on_ceiling=false; - move_and_slide_on_wall=false; + margin = 0.08; + move_and_slide_on_floor = false; + move_and_slide_on_ceiling = false; + move_and_slide_on_wall = false; } -KinematicBody2D::~KinematicBody2D() { - - +KinematicBody2D::~KinematicBody2D() { } - diff --git a/scene/2d/physics_body_2d.h b/scene/2d/physics_body_2d.h index 5b7db35fe..e51b51230 100644 --- a/scene/2d/physics_body_2d.h +++ b/scene/2d/physics_body_2d.h @@ -33,57 +33,52 @@ #include "servers/physics_2d_server.h" #include "vset.h" - class PhysicsBody2D : public CollisionObject2D { - GDCLASS(PhysicsBody2D,CollisionObject2D); + GDCLASS(PhysicsBody2D, CollisionObject2D); uint32_t mask; uint32_t collision_mask; Vector2 one_way_collision_direction; float one_way_collision_max_depth; - void _set_layers(uint32_t p_mask); uint32_t _get_layers() const; protected: - void _notification(int p_what); PhysicsBody2D(Physics2DServer::BodyMode p_mode); static void _bind_methods(); -public: +public: void set_collision_layer(uint32_t p_mask); uint32_t get_collision_layer() const; void set_collision_mask(uint32_t p_mask); uint32_t get_collision_mask() const; - void set_collision_mask_bit(int p_bit, bool p_value); bool get_collision_mask_bit(int p_bit) const; void set_collision_layer_bit(int p_bit, bool p_value); bool get_collision_layer_bit(int p_bit) const; - void add_collision_exception_with(Node* p_node); //must be physicsbody - void remove_collision_exception_with(Node* p_node); + void add_collision_exception_with(Node *p_node); //must be physicsbody + void remove_collision_exception_with(Node *p_node); - void set_one_way_collision_direction(const Vector2& p_dir); + void set_one_way_collision_direction(const Vector2 &p_dir); Vector2 get_one_way_collision_direction() const; void set_one_way_collision_max_depth(float p_dir); float get_one_way_collision_max_depth() const; PhysicsBody2D(); - }; class StaticBody2D : public PhysicsBody2D { - GDCLASS(StaticBody2D,PhysicsBody2D); + GDCLASS(StaticBody2D, PhysicsBody2D); Vector2 constant_linear_velocity; real_t constant_angular_velocity; @@ -91,21 +86,17 @@ class StaticBody2D : public PhysicsBody2D { real_t bounce; real_t friction; - protected: - static void _bind_methods(); public: - void set_friction(real_t p_friction); real_t get_friction() const; void set_bounce(real_t p_bounce); real_t get_bounce() const; - - void set_constant_linear_velocity(const Vector2& p_vel); + void set_constant_linear_velocity(const Vector2 &p_vel); void set_constant_angular_velocity(real_t p_vel); Vector2 get_constant_linear_velocity() const; @@ -113,14 +104,13 @@ public: StaticBody2D(); ~StaticBody2D(); - }; class RigidBody2D : public PhysicsBody2D { - GDCLASS(RigidBody2D,PhysicsBody2D); -public: + GDCLASS(RigidBody2D, PhysicsBody2D); +public: enum Mode { MODE_RIGID, MODE_STATIC, @@ -135,7 +125,6 @@ public: }; private: - bool can_sleep; Physics2DDirectBodyState *state; Mode mode; @@ -151,35 +140,34 @@ private: real_t angular_velocity; bool sleeping; - int max_contacts_reported; bool custom_integrator; CCDMode ccd_mode; - struct ShapePair { int body_shape; int local_shape; bool tagged; - bool operator<(const ShapePair& p_sp) const { - if (body_shape==p_sp.body_shape) + bool operator<(const ShapePair &p_sp) const { + if (body_shape == p_sp.body_shape) return local_shape < p_sp.local_shape; else return body_shape < p_sp.body_shape; } ShapePair() {} - ShapePair(int p_bs, int p_ls) { body_shape=p_bs; local_shape=p_ls; } + ShapePair(int p_bs, int p_ls) { + body_shape = p_bs; + local_shape = p_ls; + } }; struct RigidBody2D_RemoveAction { - ObjectID body_id; ShapePair pair; - }; struct BodyState { @@ -191,26 +179,22 @@ private: struct ContactMonitor { bool locked; - Map body_map; - + Map body_map; }; - ContactMonitor *contact_monitor; void _body_enter_tree(ObjectID p_id); void _body_exit_tree(ObjectID p_id); - - void _body_inout(int p_status, ObjectID p_instance, int p_body_shape,int p_local_shape); + void _body_inout(int p_status, ObjectID p_instance, int p_body_shape, int p_local_shape); void _direct_state_changed(Object *p_state); - bool _test_motion(const Vector2& p_motion,float p_margin=0.08,const Ref& p_result=Ref()); + bool _test_motion(const Vector2 &p_motion, float p_margin = 0.08, const Ref &p_result = Ref()); protected: - static void _bind_methods(); -public: +public: void set_mode(Mode p_mode); Mode get_mode() const; @@ -238,10 +222,10 @@ public: void set_angular_damp(real_t p_angular_damp); real_t get_angular_damp() const; - void set_linear_velocity(const Vector2& p_velocity); + void set_linear_velocity(const Vector2 &p_velocity); Vector2 get_linear_velocity() const; - void set_axis_velocity(const Vector2& p_axis); + void set_axis_velocity(const Vector2 &p_axis); void set_angular_velocity(real_t p_velocity); real_t get_angular_velocity() const; @@ -264,33 +248,28 @@ public: void set_continuous_collision_detection_mode(CCDMode p_mode); CCDMode get_continuous_collision_detection_mode() const; - void apply_impulse(const Vector2& p_offset, const Vector2& p_impulse); + void apply_impulse(const Vector2 &p_offset, const Vector2 &p_impulse); - void set_applied_force(const Vector2& p_force); + void set_applied_force(const Vector2 &p_force); Vector2 get_applied_force() const; void set_applied_torque(const float p_torque); float get_applied_torque() const; - void add_force(const Vector2& p_offset, const Vector2& p_force); - - + void add_force(const Vector2 &p_offset, const Vector2 &p_force); Array get_colliding_bodies() const; //function for script RigidBody2D(); ~RigidBody2D(); - }; VARIANT_ENUM_CAST(RigidBody2D::Mode); VARIANT_ENUM_CAST(RigidBody2D::CCDMode); - - class KinematicBody2D : public PhysicsBody2D { - GDCLASS(KinematicBody2D,PhysicsBody2D); + GDCLASS(KinematicBody2D, PhysicsBody2D); float margin; bool colliding; @@ -311,15 +290,15 @@ class KinematicBody2D : public PhysicsBody2D { Variant _get_collider() const; _FORCE_INLINE_ bool _ignores_mode(Physics2DServer::BodyMode) const; -protected: +protected: static void _bind_methods(); -public: - Vector2 move(const Vector2& p_motion); - Vector2 move_to(const Vector2& p_position); +public: + Vector2 move(const Vector2 &p_motion); + Vector2 move_to(const Vector2 &p_position); - bool test_move(const Transform2D &p_from, const Vector2& p_motion); + bool test_move(const Transform2D &p_from, const Vector2 &p_motion); bool is_colliding() const; Vector2 get_travel() const; @@ -335,17 +314,14 @@ public: void set_collision_margin(float p_margin); float get_collision_margin() const; - Vector2 move_and_slide(const Vector2& p_linear_velocity, const Vector2& p_floor_direction=Vector2(0,0), float p_slope_stop_min_velocity=5, int p_max_bounces=4); + Vector2 move_and_slide(const Vector2 &p_linear_velocity, const Vector2 &p_floor_direction = Vector2(0, 0), float p_slope_stop_min_velocity = 5, int p_max_bounces = 4); bool is_move_and_slide_on_floor() const; bool is_move_and_slide_on_wall() const; bool is_move_and_slide_on_ceiling() const; Array get_move_and_slide_colliders() const; - KinematicBody2D(); ~KinematicBody2D(); - }; - #endif // PHYSICS_BODY_2D_H diff --git a/scene/2d/polygon_2d.cpp b/scene/2d/polygon_2d.cpp index ec6729844..1d54fd153 100644 --- a/scene/2d/polygon_2d.cpp +++ b/scene/2d/polygon_2d.cpp @@ -30,29 +30,25 @@ Rect2 Polygon2D::get_item_rect() const { - - if (rect_cache_dirty){ - int l =polygon.size(); + if (rect_cache_dirty) { + int l = polygon.size(); PoolVector::Read r = polygon.read(); - item_rect=Rect2(); - for(int i=0;i points; @@ -84,162 +79,155 @@ void Polygon2D::_notification(int p_what) { int len = points.size(); { - PoolVector::Read polyr =polygon.read(); - for(int i=0;i::Read polyr = polygon.read(); + for (int i = 0; i < len; i++) { + points[i] = polyr[i] + offset; } } if (invert) { Rect2 bounds; - int highest_idx=-1; - float highest_y=-1e20; - float sum=0; + int highest_idx = -1; + float highest_y = -1e20; + float sum = 0; - for(int i=0;ihighest_y) { - highest_idx=i; - highest_y=points[i].y; + if (points[i].y > highest_y) { + highest_idx = i; + highest_y = points[i].y; } - int ni=(i+1)%len; - sum+=(points[ni].x-points[i].x)*(points[ni].y+points[i].y); + int ni = (i + 1) % len; + sum += (points[ni].x - points[i].x) * (points[ni].y + points[i].y); } - bounds=bounds.grow(invert_border); + bounds = bounds.grow(invert_border); - Vector2 ep[7]={ - Vector2(points[highest_idx].x,points[highest_idx].y+invert_border), - Vector2(bounds.pos+bounds.size), - Vector2(bounds.pos+Vector2(bounds.size.x,0)), + Vector2 ep[7] = { + Vector2(points[highest_idx].x, points[highest_idx].y + invert_border), + Vector2(bounds.pos + bounds.size), + Vector2(bounds.pos + Vector2(bounds.size.x, 0)), Vector2(bounds.pos), - Vector2(bounds.pos+Vector2(0,bounds.size.y)), - Vector2(points[highest_idx].x-CMP_EPSILON,points[highest_idx].y+invert_border), - Vector2(points[highest_idx].x-CMP_EPSILON,points[highest_idx].y), + Vector2(bounds.pos + Vector2(0, bounds.size.y)), + Vector2(points[highest_idx].x - CMP_EPSILON, points[highest_idx].y + invert_border), + Vector2(points[highest_idx].x - CMP_EPSILON, points[highest_idx].y), }; - - if (sum>0) { - SWAP(ep[1],ep[4]); - SWAP(ep[2],ep[3]); - SWAP(ep[5],ep[0]); - SWAP(ep[6],points[highest_idx]); + if (sum > 0) { + SWAP(ep[1], ep[4]); + SWAP(ep[2], ep[3]); + SWAP(ep[5], ep[0]); + SWAP(ep[6], points[highest_idx]); } - points.resize(points.size()+7); - for(int i=points.size()-1;i>=highest_idx+7;i--) { + points.resize(points.size() + 7); + for (int i = points.size() - 1; i >= highest_idx + 7; i--) { - points[i]=points[i-7]; + points[i] = points[i - 7]; } - for(int i=0;i<7;i++) { + for (int i = 0; i < 7; i++) { - points[highest_idx+i+1]=ep[i]; + points[highest_idx + i + 1] = ep[i]; } - - len=points.size(); - + len = points.size(); } if (texture.is_valid()) { - Transform2D texmat(tex_rot,tex_ofs); + Transform2D texmat(tex_rot, tex_ofs); texmat.scale(tex_scale); - Size2 tex_size=Vector2(1,1); + Size2 tex_size = Vector2(1, 1); - tex_size=texture->get_size(); + tex_size = texture->get_size(); uvs.resize(points.size()); - if (points.size()==uv.size()) { + if (points.size() == uv.size()) { PoolVector::Read uvr = uv.read(); - for(int i=0;i colors; - int color_len=vertex_colors.size(); + int color_len = vertex_colors.size(); colors.resize(len); { - PoolVector::Read color_r=vertex_colors.read(); - for(int i=0;i::Read color_r = vertex_colors.read(); + for (int i = 0; i < color_len && i < len; i++) { + colors[i] = color_r[i]; } - for(int i=color_len;i indices = Geometry::triangulate_polygon(points); - VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(),indices,points,colors,uvs,texture.is_valid()?texture->get_rid():RID()); + VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(), indices, points, colors, uvs, texture.is_valid() ? texture->get_rid() : RID()); } break; } } - -void Polygon2D::set_polygon(const PoolVector& p_polygon) { - polygon=p_polygon; - rect_cache_dirty=true; +void Polygon2D::set_polygon(const PoolVector &p_polygon) { + polygon = p_polygon; + rect_cache_dirty = true; update(); } -PoolVector Polygon2D::get_polygon() const{ +PoolVector Polygon2D::get_polygon() const { return polygon; } +void Polygon2D::set_uv(const PoolVector &p_uv) { -void Polygon2D::set_uv(const PoolVector& p_uv) { - - uv=p_uv; + uv = p_uv; update(); } -PoolVector Polygon2D::get_uv() const{ +PoolVector Polygon2D::get_uv() const { return uv; } -void Polygon2D::set_color(const Color& p_color){ +void Polygon2D::set_color(const Color &p_color) { - color=p_color; + color = p_color; update(); } -Color Polygon2D::get_color() const{ +Color Polygon2D::get_color() const { return color; } -void Polygon2D::set_vertex_colors(const PoolVector& p_colors){ +void Polygon2D::set_vertex_colors(const PoolVector &p_colors) { - vertex_colors=p_colors; + vertex_colors = p_colors; update(); } -PoolVector Polygon2D::get_vertex_colors() const{ +PoolVector Polygon2D::get_vertex_colors() const { return vertex_colors; } -void Polygon2D::set_texture(const Ref& p_texture){ +void Polygon2D::set_texture(const Ref &p_texture) { - texture=p_texture; + texture = p_texture; /*if (texture.is_valid()) { uint32_t flags=texture->get_flags(); @@ -251,77 +239,74 @@ void Polygon2D::set_texture(const Ref& p_texture){ }*/ update(); } -Ref Polygon2D::get_texture() const{ +Ref Polygon2D::get_texture() const { return texture; } +void Polygon2D::set_texture_offset(const Vector2 &p_offset) { -void Polygon2D::set_texture_offset(const Vector2& p_offset){ - - tex_ofs=p_offset; + tex_ofs = p_offset; update(); } -Vector2 Polygon2D::get_texture_offset() const{ +Vector2 Polygon2D::get_texture_offset() const { return tex_ofs; } -void Polygon2D::set_texture_rotation(float p_rot){ +void Polygon2D::set_texture_rotation(float p_rot) { - tex_rot=p_rot; + tex_rot = p_rot; update(); } -float Polygon2D::get_texture_rotation() const{ +float Polygon2D::get_texture_rotation() const { return tex_rot; } - -void Polygon2D::_set_texture_rotationd(float p_rot){ +void Polygon2D::_set_texture_rotationd(float p_rot) { set_texture_rotation(Math::deg2rad(p_rot)); } -float Polygon2D::_get_texture_rotationd() const{ +float Polygon2D::_get_texture_rotationd() const { return Math::rad2deg(get_texture_rotation()); } +void Polygon2D::set_texture_scale(const Size2 &p_scale) { -void Polygon2D::set_texture_scale(const Size2& p_scale){ - - tex_scale=p_scale; + tex_scale = p_scale; update(); } -Size2 Polygon2D::get_texture_scale() const{ +Size2 Polygon2D::get_texture_scale() const { return tex_scale; } -void Polygon2D::set_invert(bool p_invert){ +void Polygon2D::set_invert(bool p_invert) { - invert=p_invert; + invert = p_invert; update(); } -bool Polygon2D::get_invert() const{ +bool Polygon2D::get_invert() const { return invert; } -void Polygon2D::set_invert_border(float p_invert_border){ +void Polygon2D::set_invert_border(float p_invert_border) { - invert_border=p_invert_border; + invert_border = p_invert_border; update(); } -float Polygon2D::get_invert_border() const{ +float Polygon2D::get_invert_border() const { return invert_border; } -void Polygon2D::set_offset(const Vector2& p_offset) { +void Polygon2D::set_offset(const Vector2 &p_offset) { - offset=p_offset; - rect_cache_dirty=true; + offset = p_offset; + rect_cache_dirty = true; update(); } @@ -330,73 +315,68 @@ Vector2 Polygon2D::get_offset() const { return offset; } - void Polygon2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_polygon","polygon"),&Polygon2D::set_polygon); - ClassDB::bind_method(D_METHOD("get_polygon"),&Polygon2D::get_polygon); - - ClassDB::bind_method(D_METHOD("set_uv","uv"),&Polygon2D::set_uv); - ClassDB::bind_method(D_METHOD("get_uv"),&Polygon2D::get_uv); - - ClassDB::bind_method(D_METHOD("set_color","color"),&Polygon2D::set_color); - ClassDB::bind_method(D_METHOD("get_color"),&Polygon2D::get_color); - - ClassDB::bind_method(D_METHOD("set_vertex_colors","vertex_colors"),&Polygon2D::set_vertex_colors); - ClassDB::bind_method(D_METHOD("get_vertex_colors"),&Polygon2D::get_vertex_colors); - - ClassDB::bind_method(D_METHOD("set_texture","texture"),&Polygon2D::set_texture); - ClassDB::bind_method(D_METHOD("get_texture"),&Polygon2D::get_texture); + ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &Polygon2D::set_polygon); + ClassDB::bind_method(D_METHOD("get_polygon"), &Polygon2D::get_polygon); - ClassDB::bind_method(D_METHOD("set_texture_offset","texture_offset"),&Polygon2D::set_texture_offset); - ClassDB::bind_method(D_METHOD("get_texture_offset"),&Polygon2D::get_texture_offset); + ClassDB::bind_method(D_METHOD("set_uv", "uv"), &Polygon2D::set_uv); + ClassDB::bind_method(D_METHOD("get_uv"), &Polygon2D::get_uv); - ClassDB::bind_method(D_METHOD("set_texture_rotation","texture_rotation"),&Polygon2D::set_texture_rotation); - ClassDB::bind_method(D_METHOD("get_texture_rotation"),&Polygon2D::get_texture_rotation); + ClassDB::bind_method(D_METHOD("set_color", "color"), &Polygon2D::set_color); + ClassDB::bind_method(D_METHOD("get_color"), &Polygon2D::get_color); - ClassDB::bind_method(D_METHOD("_set_texture_rotationd","texture_rotation"),&Polygon2D::_set_texture_rotationd); - ClassDB::bind_method(D_METHOD("_get_texture_rotationd"),&Polygon2D::_get_texture_rotationd); + ClassDB::bind_method(D_METHOD("set_vertex_colors", "vertex_colors"), &Polygon2D::set_vertex_colors); + ClassDB::bind_method(D_METHOD("get_vertex_colors"), &Polygon2D::get_vertex_colors); - ClassDB::bind_method(D_METHOD("set_texture_scale","texture_scale"),&Polygon2D::set_texture_scale); - ClassDB::bind_method(D_METHOD("get_texture_scale"),&Polygon2D::get_texture_scale); + ClassDB::bind_method(D_METHOD("set_texture", "texture"), &Polygon2D::set_texture); + ClassDB::bind_method(D_METHOD("get_texture"), &Polygon2D::get_texture); + ClassDB::bind_method(D_METHOD("set_texture_offset", "texture_offset"), &Polygon2D::set_texture_offset); + ClassDB::bind_method(D_METHOD("get_texture_offset"), &Polygon2D::get_texture_offset); - ClassDB::bind_method(D_METHOD("set_invert","invert"),&Polygon2D::set_invert); - ClassDB::bind_method(D_METHOD("get_invert"),&Polygon2D::get_invert); + ClassDB::bind_method(D_METHOD("set_texture_rotation", "texture_rotation"), &Polygon2D::set_texture_rotation); + ClassDB::bind_method(D_METHOD("get_texture_rotation"), &Polygon2D::get_texture_rotation); - ClassDB::bind_method(D_METHOD("set_invert_border","invert_border"),&Polygon2D::set_invert_border); - ClassDB::bind_method(D_METHOD("get_invert_border"),&Polygon2D::get_invert_border); + ClassDB::bind_method(D_METHOD("_set_texture_rotationd", "texture_rotation"), &Polygon2D::_set_texture_rotationd); + ClassDB::bind_method(D_METHOD("_get_texture_rotationd"), &Polygon2D::_get_texture_rotationd); - ClassDB::bind_method(D_METHOD("set_offset","offset"),&Polygon2D::set_offset); - ClassDB::bind_method(D_METHOD("get_offset"),&Polygon2D::get_offset); + ClassDB::bind_method(D_METHOD("set_texture_scale", "texture_scale"), &Polygon2D::set_texture_scale); + ClassDB::bind_method(D_METHOD("get_texture_scale"), &Polygon2D::get_texture_scale); + ClassDB::bind_method(D_METHOD("set_invert", "invert"), &Polygon2D::set_invert); + ClassDB::bind_method(D_METHOD("get_invert"), &Polygon2D::get_invert); + ClassDB::bind_method(D_METHOD("set_invert_border", "invert_border"), &Polygon2D::set_invert_border); + ClassDB::bind_method(D_METHOD("get_invert_border"), &Polygon2D::get_invert_border); - ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"polygon"),"set_polygon","get_polygon"); - ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"uv"),"set_uv","get_uv"); - ADD_PROPERTY( PropertyInfo(Variant::COLOR,"color"),"set_color","get_color"); - ADD_PROPERTY( PropertyInfo(Variant::POOL_COLOR_ARRAY,"vertex_colors"),"set_vertex_colors","get_vertex_colors"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"offset"),"set_offset","get_offset"); - ADD_GROUP("Texture",""); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture"); - ADD_GROUP("Texture","texture_"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"texture_offset"),"set_texture_offset","get_texture_offset"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"texture_scale"),"set_texture_scale","get_texture_scale"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"texture_rotation",PROPERTY_HINT_RANGE,"-1440,1440,0.1"),"_set_texture_rotationd","_get_texture_rotationd"); + ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Polygon2D::set_offset); + ClassDB::bind_method(D_METHOD("get_offset"), &Polygon2D::get_offset); - ADD_GROUP("Invert","invert_"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"invert_enable"),"set_invert","get_invert"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"invert_border",PROPERTY_HINT_RANGE,"0.1,16384,0.1"),"set_invert_border","get_invert_border"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "uv"), "set_uv", "get_uv"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_COLOR_ARRAY, "vertex_colors"), "set_vertex_colors", "get_vertex_colors"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset"); + ADD_GROUP("Texture", ""); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); + ADD_GROUP("Texture", "texture_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "texture_offset"), "set_texture_offset", "get_texture_offset"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "texture_scale"), "set_texture_scale", "get_texture_scale"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "texture_rotation", PROPERTY_HINT_RANGE, "-1440,1440,0.1"), "_set_texture_rotationd", "_get_texture_rotationd"); + ADD_GROUP("Invert", "invert_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "invert_enable"), "set_invert", "get_invert"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "invert_border", PROPERTY_HINT_RANGE, "0.1,16384,0.1"), "set_invert_border", "get_invert_border"); } Polygon2D::Polygon2D() { - invert=0; - invert_border=100; - tex_rot=0; - tex_tile=true; - tex_scale=Vector2(1,1); - color=Color(1,1,1); - rect_cache_dirty=true; + invert = 0; + invert_border = 100; + tex_rot = 0; + tex_tile = true; + tex_scale = Vector2(1, 1); + color = Color(1, 1, 1); + rect_cache_dirty = true; } diff --git a/scene/2d/polygon_2d.h b/scene/2d/polygon_2d.h index 8434dae40..50968f3de 100644 --- a/scene/2d/polygon_2d.h +++ b/scene/2d/polygon_2d.h @@ -33,7 +33,7 @@ class Polygon2D : public Node2D { - GDCLASS(Polygon2D,Node2D); + GDCLASS(Polygon2D, Node2D); PoolVector polygon; PoolVector uv; @@ -55,33 +55,32 @@ class Polygon2D : public Node2D { float _get_texture_rotationd() const; protected: - void _notification(int p_what); static void _bind_methods(); -public: - void set_polygon(const PoolVector& p_polygon); +public: + void set_polygon(const PoolVector &p_polygon); PoolVector get_polygon() const; - void set_uv(const PoolVector& p_uv); + void set_uv(const PoolVector &p_uv); PoolVector get_uv() const; - void set_color(const Color& p_color); + void set_color(const Color &p_color); Color get_color() const; - void set_vertex_colors(const PoolVector& p_colors); + void set_vertex_colors(const PoolVector &p_colors); PoolVector get_vertex_colors() const; - void set_texture(const Ref& p_texture); + void set_texture(const Ref &p_texture); Ref get_texture() const; - void set_texture_offset(const Vector2& p_offset); + void set_texture_offset(const Vector2 &p_offset); Vector2 get_texture_offset() const; void set_texture_rotation(float p_rot); float get_texture_rotation() const; - void set_texture_scale(const Size2& p_scale); + void set_texture_scale(const Size2 &p_scale); Size2 get_texture_scale() const; void set_invert(bool p_rot); @@ -90,12 +89,12 @@ public: void set_invert_border(float p_border); float get_invert_border() const; - void set_offset(const Vector2& p_offset); + void set_offset(const Vector2 &p_offset); Vector2 get_offset() const; //editor stuff - virtual void edit_set_pivot(const Point2& p_pivot); + virtual void edit_set_pivot(const Point2 &p_pivot); virtual Point2 edit_get_pivot() const; virtual bool edit_has_pivot() const; diff --git a/scene/2d/position_2d.cpp b/scene/2d/position_2d.cpp index a25be18cb..39fc6352e 100644 --- a/scene/2d/position_2d.cpp +++ b/scene/2d/position_2d.cpp @@ -31,19 +31,18 @@ void Position2D::_draw_cross() { - draw_line(Point2(-10,0),Point2(+10,0),Color(1,0.5,0.5)); - draw_line(Point2(0,-10),Point2(0,+10),Color(0.5,1,0.5)); - + draw_line(Point2(-10, 0), Point2(+10, 0), Color(1, 0.5, 0.5)); + draw_line(Point2(0, -10), Point2(0, +10), Color(0.5, 1, 0.5)); } Rect2 Position2D::get_item_rect() const { - return Rect2(Point2(-10,-10),Size2(20,20)); + return Rect2(Point2(-10, -10), Size2(20, 20)); } void Position2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { @@ -57,9 +56,7 @@ void Position2D::_notification(int p_what) { } break; } - } -Position2D::Position2D() -{ +Position2D::Position2D() { } diff --git a/scene/2d/position_2d.h b/scene/2d/position_2d.h index fb68c265b..a9ead3d87 100644 --- a/scene/2d/position_2d.h +++ b/scene/2d/position_2d.h @@ -29,19 +29,18 @@ #ifndef POSITION_2D_H #define POSITION_2D_H - #include "scene/2d/node_2d.h" class Position2D : public Node2D { - GDCLASS(Position2D,Node2D) + GDCLASS(Position2D, Node2D) void _draw_cross(); -protected: +protected: void _notification(int p_what); -public: +public: virtual Rect2 get_item_rect() const; Position2D(); }; diff --git a/scene/2d/ray_cast_2d.cpp b/scene/2d/ray_cast_2d.cpp index 72247811d..83a0717ac 100644 --- a/scene/2d/ray_cast_2d.cpp +++ b/scene/2d/ray_cast_2d.cpp @@ -27,26 +27,25 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "ray_cast_2d.h" -#include "servers/physics_2d_server.h" #include "collision_object_2d.h" #include "physics_body_2d.h" +#include "servers/physics_2d_server.h" -void RayCast2D::set_cast_to(const Vector2& p_point) { +void RayCast2D::set_cast_to(const Vector2 &p_point) { - cast_to=p_point; + cast_to = p_point; if (is_inside_tree() && (get_tree()->is_editor_hint() || get_tree()->is_debugging_collisions_hint())) update(); - } -Vector2 RayCast2D::get_cast_to() const{ +Vector2 RayCast2D::get_cast_to() const { return cast_to; } void RayCast2D::set_layer_mask(uint32_t p_mask) { - layer_mask=p_mask; + layer_mask = p_mask; } uint32_t RayCast2D::get_layer_mask() const { @@ -56,7 +55,7 @@ uint32_t RayCast2D::get_layer_mask() const { void RayCast2D::set_type_mask(uint32_t p_mask) { - type_mask=p_mask; + type_mask = p_mask; } uint32_t RayCast2D::get_type_mask() const { @@ -64,13 +63,13 @@ uint32_t RayCast2D::get_type_mask() const { return type_mask; } -bool RayCast2D::is_colliding() const{ +bool RayCast2D::is_colliding() const { return collided; } -Object *RayCast2D::get_collider() const{ +Object *RayCast2D::get_collider() const { - if (against==0) + if (against == 0) return NULL; return ObjectDB::get_instance(against); @@ -80,61 +79,55 @@ int RayCast2D::get_collider_shape() const { return against_shape; } -Vector2 RayCast2D::get_collision_point() const{ +Vector2 RayCast2D::get_collision_point() const { return collision_point; } -Vector2 RayCast2D::get_collision_normal() const{ +Vector2 RayCast2D::get_collision_normal() const { return collision_normal; } - void RayCast2D::set_enabled(bool p_enabled) { - enabled=p_enabled; + enabled = p_enabled; if (is_inside_tree() && !get_tree()->is_editor_hint()) set_fixed_process(p_enabled); if (!p_enabled) - collided=false; - + collided = false; } - bool RayCast2D::is_enabled() const { - return enabled; } void RayCast2D::set_exclude_parent_body(bool p_exclude_parent_body) { - if (exclude_parent_body==p_exclude_parent_body) + if (exclude_parent_body == p_exclude_parent_body) return; - exclude_parent_body=p_exclude_parent_body; + exclude_parent_body = p_exclude_parent_body; if (!is_inside_tree()) return; - - if (get_parent()->cast_to()) { if (exclude_parent_body) - exclude.insert( get_parent()->cast_to()->get_rid() ); + exclude.insert(get_parent()->cast_to()->get_rid()); else - exclude.erase( get_parent()->cast_to()->get_rid() ); + exclude.erase(get_parent()->cast_to()->get_rid()); } } -bool RayCast2D::get_exclude_parent_body() const{ +bool RayCast2D::get_exclude_parent_body() const { return exclude_parent_body; } void RayCast2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { @@ -145,9 +138,9 @@ void RayCast2D::_notification(int p_what) { if (get_parent()->cast_to()) { if (exclude_parent_body) - exclude.insert( get_parent()->cast_to()->get_rid() ); + exclude.insert(get_parent()->cast_to()->get_rid()); else - exclude.erase( get_parent()->cast_to()->get_rid() ); + exclude.erase(get_parent()->cast_to()->get_rid()); } } break; case NOTIFICATION_EXIT_TREE: { @@ -159,29 +152,28 @@ void RayCast2D::_notification(int p_what) { case NOTIFICATION_DRAW: { - if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) + if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) break; Transform2D xf; xf.rotate(cast_to.angle()); - xf.translate(Vector2(0,cast_to.length())); + xf.translate(Vector2(0, cast_to.length())); //Vector2 tip = Vector2(0,s->get_length()); - Color dcol=get_tree()->get_debug_collisions_color();//0.9,0.2,0.2,0.4); - draw_line(Vector2(),cast_to,dcol,3); + Color dcol = get_tree()->get_debug_collisions_color(); //0.9,0.2,0.2,0.4); + draw_line(Vector2(), cast_to, dcol, 3); Vector pts; - float tsize=4; - pts.push_back(xf.xform(Vector2(0,tsize))); - pts.push_back(xf.xform(Vector2(0.707*tsize,0))); - pts.push_back(xf.xform(Vector2(-0.707*tsize,0))); + float tsize = 4; + pts.push_back(xf.xform(Vector2(0, tsize))); + pts.push_back(xf.xform(Vector2(0.707 * tsize, 0))); + pts.push_back(xf.xform(Vector2(-0.707 * tsize, 0))); Vector cols; - for(int i=0;i<3;i++) + for (int i = 0; i < 3; i++) cols.push_back(dcol); - draw_primitive(pts,cols,Vector()); //small arrow + draw_primitive(pts, cols, Vector()); //small arrow } break; - case NOTIFICATION_FIXED_PROCESS: { if (!enabled) @@ -189,35 +181,34 @@ void RayCast2D::_notification(int p_what) { _update_raycast_state(); - } break; } } void RayCast2D::_update_raycast_state() { Ref w2d = get_world_2d(); - ERR_FAIL_COND( w2d.is_null() ); + ERR_FAIL_COND(w2d.is_null()); Physics2DDirectSpaceState *dss = Physics2DServer::get_singleton()->space_get_direct_state(w2d->get_space()); - ERR_FAIL_COND( !dss ); + ERR_FAIL_COND(!dss); Transform2D gt = get_global_transform(); Vector2 to = cast_to; - if (to==Vector2()) - to=Vector2(0,0.01); + if (to == Vector2()) + to = Vector2(0, 0.01); Physics2DDirectSpaceState::RayResult rr; - if (dss->intersect_ray(gt.get_origin(),gt.xform(to),rr,exclude,layer_mask,type_mask)) { + if (dss->intersect_ray(gt.get_origin(), gt.xform(to), rr, exclude, layer_mask, type_mask)) { - collided=true; - against=rr.collider_id; - collision_point=rr.position; - collision_normal=rr.normal; - against_shape=rr.shape; + collided = true; + against = rr.collider_id; + collision_point = rr.position; + collision_normal = rr.normal; + against_shape = rr.shape; } else { - collided=false; + collided = false; } } @@ -225,90 +216,87 @@ void RayCast2D::force_raycast_update() { _update_raycast_state(); } -void RayCast2D::add_exception_rid(const RID& p_rid) { +void RayCast2D::add_exception_rid(const RID &p_rid) { exclude.insert(p_rid); } -void RayCast2D::add_exception(const Object* p_object){ +void RayCast2D::add_exception(const Object *p_object) { ERR_FAIL_NULL(p_object); - CollisionObject2D *co=((Object*)p_object)->cast_to(); + CollisionObject2D *co = ((Object *)p_object)->cast_to(); if (!co) return; add_exception_rid(co->get_rid()); } -void RayCast2D::remove_exception_rid(const RID& p_rid) { +void RayCast2D::remove_exception_rid(const RID &p_rid) { exclude.erase(p_rid); } -void RayCast2D::remove_exception(const Object* p_object){ +void RayCast2D::remove_exception(const Object *p_object) { ERR_FAIL_NULL(p_object); - CollisionObject2D *co=((Object*)p_object)->cast_to(); + CollisionObject2D *co = ((Object *)p_object)->cast_to(); if (!co) return; remove_exception_rid(co->get_rid()); } - -void RayCast2D::clear_exceptions(){ +void RayCast2D::clear_exceptions() { exclude.clear(); } - void RayCast2D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &RayCast2D::set_enabled); + ClassDB::bind_method(D_METHOD("is_enabled"), &RayCast2D::is_enabled); - ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&RayCast2D::set_enabled); - ClassDB::bind_method(D_METHOD("is_enabled"),&RayCast2D::is_enabled); - - ClassDB::bind_method(D_METHOD("set_cast_to","local_point"),&RayCast2D::set_cast_to); - ClassDB::bind_method(D_METHOD("get_cast_to"),&RayCast2D::get_cast_to); + ClassDB::bind_method(D_METHOD("set_cast_to", "local_point"), &RayCast2D::set_cast_to); + ClassDB::bind_method(D_METHOD("get_cast_to"), &RayCast2D::get_cast_to); - ClassDB::bind_method(D_METHOD("is_colliding"),&RayCast2D::is_colliding); - ClassDB::bind_method(D_METHOD("force_raycast_update"),&RayCast2D::force_raycast_update); + ClassDB::bind_method(D_METHOD("is_colliding"), &RayCast2D::is_colliding); + ClassDB::bind_method(D_METHOD("force_raycast_update"), &RayCast2D::force_raycast_update); - ClassDB::bind_method(D_METHOD("get_collider"),&RayCast2D::get_collider); - ClassDB::bind_method(D_METHOD("get_collider_shape"),&RayCast2D::get_collider_shape); - ClassDB::bind_method(D_METHOD("get_collision_point"),&RayCast2D::get_collision_point); - ClassDB::bind_method(D_METHOD("get_collision_normal"),&RayCast2D::get_collision_normal); + ClassDB::bind_method(D_METHOD("get_collider"), &RayCast2D::get_collider); + ClassDB::bind_method(D_METHOD("get_collider_shape"), &RayCast2D::get_collider_shape); + ClassDB::bind_method(D_METHOD("get_collision_point"), &RayCast2D::get_collision_point); + ClassDB::bind_method(D_METHOD("get_collision_normal"), &RayCast2D::get_collision_normal); - ClassDB::bind_method(D_METHOD("add_exception_rid","rid"),&RayCast2D::add_exception_rid); - ClassDB::bind_method(D_METHOD("add_exception","node"),&RayCast2D::add_exception); + ClassDB::bind_method(D_METHOD("add_exception_rid", "rid"), &RayCast2D::add_exception_rid); + ClassDB::bind_method(D_METHOD("add_exception", "node"), &RayCast2D::add_exception); - ClassDB::bind_method(D_METHOD("remove_exception_rid","rid"),&RayCast2D::remove_exception_rid); - ClassDB::bind_method(D_METHOD("remove_exception","node"),&RayCast2D::remove_exception); + ClassDB::bind_method(D_METHOD("remove_exception_rid", "rid"), &RayCast2D::remove_exception_rid); + ClassDB::bind_method(D_METHOD("remove_exception", "node"), &RayCast2D::remove_exception); - ClassDB::bind_method(D_METHOD("clear_exceptions"),&RayCast2D::clear_exceptions); + ClassDB::bind_method(D_METHOD("clear_exceptions"), &RayCast2D::clear_exceptions); - ClassDB::bind_method(D_METHOD("set_layer_mask","mask"),&RayCast2D::set_layer_mask); - ClassDB::bind_method(D_METHOD("get_layer_mask"),&RayCast2D::get_layer_mask); + ClassDB::bind_method(D_METHOD("set_layer_mask", "mask"), &RayCast2D::set_layer_mask); + ClassDB::bind_method(D_METHOD("get_layer_mask"), &RayCast2D::get_layer_mask); - ClassDB::bind_method(D_METHOD("set_type_mask","mask"),&RayCast2D::set_type_mask); - ClassDB::bind_method(D_METHOD("get_type_mask"),&RayCast2D::get_type_mask); + ClassDB::bind_method(D_METHOD("set_type_mask", "mask"), &RayCast2D::set_type_mask); + ClassDB::bind_method(D_METHOD("get_type_mask"), &RayCast2D::get_type_mask); - ClassDB::bind_method(D_METHOD("set_exclude_parent_body","mask"),&RayCast2D::set_exclude_parent_body); - ClassDB::bind_method(D_METHOD("get_exclude_parent_body"),&RayCast2D::get_exclude_parent_body); + ClassDB::bind_method(D_METHOD("set_exclude_parent_body", "mask"), &RayCast2D::set_exclude_parent_body); + ClassDB::bind_method(D_METHOD("get_exclude_parent_body"), &RayCast2D::get_exclude_parent_body); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"exclude_parent"),"set_exclude_parent_body","get_exclude_parent_body"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"cast_to"),"set_cast_to","get_cast_to"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"layer_mask",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_layer_mask","get_layer_mask"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"type_mask",PROPERTY_HINT_FLAGS,"Static,Kinematic,Rigid,Character,Area"),"set_type_mask","get_type_mask"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "exclude_parent"), "set_exclude_parent_body", "get_exclude_parent_body"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "cast_to"), "set_cast_to", "get_cast_to"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "layer_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_layer_mask", "get_layer_mask"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "type_mask", PROPERTY_HINT_FLAGS, "Static,Kinematic,Rigid,Character,Area"), "set_type_mask", "get_type_mask"); } RayCast2D::RayCast2D() { - enabled=false; - against=0; - collided=false; - against_shape=0; - layer_mask=1; - type_mask=Physics2DDirectSpaceState::TYPE_MASK_COLLISION; - cast_to=Vector2(0,50); - exclude_parent_body=true; + enabled = false; + against = 0; + collided = false; + against_shape = 0; + layer_mask = 1; + type_mask = Physics2DDirectSpaceState::TYPE_MASK_COLLISION; + cast_to = Vector2(0, 50); + exclude_parent_body = true; } diff --git a/scene/2d/ray_cast_2d.h b/scene/2d/ray_cast_2d.h index 3e7a39ffd..6a59ef963 100644 --- a/scene/2d/ray_cast_2d.h +++ b/scene/2d/ray_cast_2d.h @@ -33,8 +33,7 @@ class RayCast2D : public Node2D { - GDCLASS(RayCast2D,Node2D); - + GDCLASS(RayCast2D, Node2D); bool enabled; bool collided; @@ -47,19 +46,18 @@ class RayCast2D : public Node2D { uint32_t type_mask; bool exclude_parent_body; - Vector2 cast_to; -protected: +protected: void _notification(int p_what); void _update_raycast_state(); static void _bind_methods(); -public: +public: void set_enabled(bool p_enabled); bool is_enabled() const; - void set_cast_to(const Vector2& p_point); + void set_cast_to(const Vector2 &p_point); Vector2 get_cast_to() const; void set_layer_mask(uint32_t p_mask); @@ -79,10 +77,10 @@ public: Vector2 get_collision_point() const; Vector2 get_collision_normal() const; - void add_exception_rid(const RID& p_rid); - void add_exception(const Object* p_object); - void remove_exception_rid(const RID& p_rid); - void remove_exception(const Object* p_object); + void add_exception_rid(const RID &p_rid); + void add_exception(const Object *p_object); + void remove_exception_rid(const RID &p_rid); + void remove_exception(const Object *p_object); void clear_exceptions(); RayCast2D(); diff --git a/scene/2d/remote_transform_2d.cpp b/scene/2d/remote_transform_2d.cpp index e1f360c0c..210f64ae2 100644 --- a/scene/2d/remote_transform_2d.cpp +++ b/scene/2d/remote_transform_2d.cpp @@ -31,20 +31,19 @@ void RemoteTransform2D::_update_cache() { - cache=0; + cache = 0; if (has_node(remote_node)) { Node *node = get_node(remote_node); - if (!node || this==node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) { + if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) { return; } - cache=node->get_instance_ID(); + cache = node->get_instance_ID(); } } void RemoteTransform2D::_update_remote() { - if (!is_inside_tree()) return; @@ -62,14 +61,13 @@ void RemoteTransform2D::_update_remote() { if (!n->is_inside_tree()) return; - //todo make faster + //todo make faster n->set_global_transform(get_global_transform()); - } void RemoteTransform2D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_READY: { @@ -83,30 +81,26 @@ void RemoteTransform2D::_notification(int p_what) { if (cache) { _update_remote(); - } } break; - } } +void RemoteTransform2D::set_remote_node(const NodePath &p_remote_node) { -void RemoteTransform2D::set_remote_node(const NodePath& p_remote_node) { - - remote_node=p_remote_node; + remote_node = p_remote_node; if (is_inside_tree()) _update_cache(); update_configuration_warning(); } -NodePath RemoteTransform2D::get_remote_node() const{ +NodePath RemoteTransform2D::get_remote_node() const { return remote_node; } - String RemoteTransform2D::get_configuration_warning() const { if (!has_node(remote_node) || !get_node(remote_node) || !get_node(remote_node)->cast_to()) { @@ -118,16 +112,14 @@ String RemoteTransform2D::get_configuration_warning() const { void RemoteTransform2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_remote_node","path"),&RemoteTransform2D::set_remote_node); - ClassDB::bind_method(D_METHOD("get_remote_node"),&RemoteTransform2D::get_remote_node); + ClassDB::bind_method(D_METHOD("set_remote_node", "path"), &RemoteTransform2D::set_remote_node); + ClassDB::bind_method(D_METHOD("get_remote_node"), &RemoteTransform2D::get_remote_node); - ADD_PROPERTY( PropertyInfo(Variant::NODE_PATH,"remote_path"),"set_remote_node","get_remote_node"); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "remote_path"), "set_remote_node", "get_remote_node"); } RemoteTransform2D::RemoteTransform2D() { - cache=0; + cache = 0; set_notify_transform(true); } - - diff --git a/scene/2d/remote_transform_2d.h b/scene/2d/remote_transform_2d.h index 52c28ffd4..aa1b21431 100644 --- a/scene/2d/remote_transform_2d.h +++ b/scene/2d/remote_transform_2d.h @@ -30,7 +30,7 @@ class RemoteTransform2D : public Node2D { - GDCLASS(RemoteTransform2D,Node2D); + GDCLASS(RemoteTransform2D, Node2D); NodePath remote_node; @@ -40,12 +40,11 @@ class RemoteTransform2D : public Node2D { void _update_cache(); //void _node_exited_scene(); protected: - static void _bind_methods(); void _notification(int p_what); -public: - void set_remote_node(const NodePath& p_remote_node); +public: + void set_remote_node(const NodePath &p_remote_node); NodePath get_remote_node() const; virtual String get_configuration_warning() const; diff --git a/scene/2d/screen_button.cpp b/scene/2d/screen_button.cpp index 4b607e926..9b9fa6cfa 100644 --- a/scene/2d/screen_button.cpp +++ b/scene/2d/screen_button.cpp @@ -27,45 +27,45 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "screen_button.h" -#include "os/os.h" #include "input_map.h" #include "os/input.h" +#include "os/os.h" -void TouchScreenButton::set_texture(const Ref& p_texture) { +void TouchScreenButton::set_texture(const Ref &p_texture) { - texture=p_texture; + texture = p_texture; update(); } -Ref TouchScreenButton::get_texture() const{ +Ref TouchScreenButton::get_texture() const { return texture; } -void TouchScreenButton::set_texture_pressed(const Ref& p_texture_pressed) { +void TouchScreenButton::set_texture_pressed(const Ref &p_texture_pressed) { - texture_pressed=p_texture_pressed; + texture_pressed = p_texture_pressed; update(); } -Ref TouchScreenButton::get_texture_pressed() const{ +Ref TouchScreenButton::get_texture_pressed() const { return texture_pressed; } -void TouchScreenButton::set_bitmask(const Ref& p_bitmask){ +void TouchScreenButton::set_bitmask(const Ref &p_bitmask) { - bitmask=p_bitmask; + bitmask = p_bitmask; } -Ref TouchScreenButton::get_bitmask() const{ +Ref TouchScreenButton::get_bitmask() const { return bitmask; } -void TouchScreenButton::set_shape(const Ref& p_shape){ +void TouchScreenButton::set_shape(const Ref &p_shape) { - shape=p_shape; + shape = p_shape; if (!is_inside_tree()) return; @@ -74,14 +74,14 @@ void TouchScreenButton::set_shape(const Ref& p_shape){ update(); } -Ref TouchScreenButton::get_shape() const{ +Ref TouchScreenButton::get_shape() const { return shape; } void TouchScreenButton::set_shape_centered(bool p_shape_centered) { - shape_centered=p_shape_centered; + shape_centered = p_shape_centered; if (!is_inside_tree()) return; @@ -97,50 +97,50 @@ bool TouchScreenButton::is_shape_centered() const { void TouchScreenButton::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_DRAW: { if (!is_inside_tree()) return; - if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility==VISIBILITY_TOUCHSCREEN_ONLY) + if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility == VISIBILITY_TOUCHSCREEN_ONLY) return; - if (finger_pressed!=-1) { + if (finger_pressed != -1) { if (texture_pressed.is_valid()) - draw_texture(texture_pressed,Point2()); + draw_texture(texture_pressed, Point2()); else if (texture.is_valid()) - draw_texture(texture,Point2()); + draw_texture(texture, Point2()); } else { if (texture.is_valid()) - draw_texture(texture,Point2()); + draw_texture(texture, Point2()); } if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) return; if (shape.is_valid()) { - Color draw_col=get_tree()->get_debug_collisions_color(); - Vector2 pos=shape_centered ? get_item_rect().size*0.5f : Vector2(); + Color draw_col = get_tree()->get_debug_collisions_color(); + Vector2 pos = shape_centered ? get_item_rect().size * 0.5f : Vector2(); draw_set_transform_matrix(get_canvas_transform().translated(pos)); - shape->draw(get_canvas_item(),draw_col); + shape->draw(get_canvas_item(), draw_col); } } break; case NOTIFICATION_ENTER_TREE: { - if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility==VISIBILITY_TOUCHSCREEN_ONLY) + if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility == VISIBILITY_TOUCHSCREEN_ONLY) return; update(); if (!get_tree()->is_editor_hint()) set_process_input(true); - if (action.operator String()!="" && InputMap::get_singleton()->has_action(action)) { - action_id=InputMap::get_singleton()->get_action_id(action); + if (action.operator String() != "" && InputMap::get_singleton()->has_action(action)) { + action_id = InputMap::get_singleton()->get_action_id(action); } else { - action_id=-1; + action_id = -1; } } break; case NOTIFICATION_EXIT_TREE: { @@ -149,26 +149,24 @@ void TouchScreenButton::_notification(int p_what) { } break; case NOTIFICATION_PAUSED: { // So the button can be pressed again even though the release gets unhandled because of coming during pause - allow_repress=true; + allow_repress = true; } } } +bool TouchScreenButton::is_pressed() const { -bool TouchScreenButton::is_pressed() const{ - - return finger_pressed!=-1; + return finger_pressed != -1; } -void TouchScreenButton::set_action(const String& p_action) { +void TouchScreenButton::set_action(const String &p_action) { - action=p_action; - if (action.operator String()!="" && InputMap::get_singleton()->has_action(action)) { - action_id=InputMap::get_singleton()->get_action_id(action); + action = p_action; + if (action.operator String() != "" && InputMap::get_singleton()->has_action(action)) { + action_id = InputMap::get_singleton()->get_action_id(action); } else { - action_id=-1; + action_id = -1; } - } String TouchScreenButton::get_action() const { @@ -176,7 +174,7 @@ String TouchScreenButton::get_action() const { return action; } -void TouchScreenButton::_input(const InputEvent& p_event) { +void TouchScreenButton::_input(const InputEvent &p_event) { if (!get_tree()) return; @@ -186,94 +184,88 @@ void TouchScreenButton::_input(const InputEvent& p_event) { if (passby_press) { - if (p_event.type==InputEvent::SCREEN_TOUCH && !p_event.screen_touch.pressed && finger_pressed==p_event.screen_touch.index) { + if (p_event.type == InputEvent::SCREEN_TOUCH && !p_event.screen_touch.pressed && finger_pressed == p_event.screen_touch.index) { _release(); } - if ((p_event.type==InputEvent::SCREEN_TOUCH && p_event.screen_touch.pressed)|| p_event.type==InputEvent::SCREEN_DRAG) { + if ((p_event.type == InputEvent::SCREEN_TOUCH && p_event.screen_touch.pressed) || p_event.type == InputEvent::SCREEN_DRAG) { - if (finger_pressed==-1 || p_event.screen_touch.index==finger_pressed) { + if (finger_pressed == -1 || p_event.screen_touch.index == finger_pressed) { - Point2 coord = (get_global_transform_with_canvas()).affine_inverse().xform(Point2(p_event.screen_touch.x,p_event.screen_touch.y)); + Point2 coord = (get_global_transform_with_canvas()).affine_inverse().xform(Point2(p_event.screen_touch.x, p_event.screen_touch.y)); - bool touched=false; + bool touched = false; if (bitmask.is_valid()) { - if (Rect2(Point2(),bitmask->get_size()).has_point(coord)) { + if (Rect2(Point2(), bitmask->get_size()).has_point(coord)) { if (bitmask->get_bit(coord)) - touched=true; + touched = true; } } else { if (texture.is_valid()) - touched=Rect2(Point2(),texture->get_size()).has_point(coord); + touched = Rect2(Point2(), texture->get_size()).has_point(coord); } - - if (touched) { - if (finger_pressed==-1) { + if (finger_pressed == -1) { _press(p_event.screen_touch.index); } } else { - if (finger_pressed!=-1) { + if (finger_pressed != -1) { _release(); } } - } - - } } else { - if (p_event.type==InputEvent::SCREEN_TOUCH) { + if (p_event.type == InputEvent::SCREEN_TOUCH) { if (p_event.screen_touch.pressed) { if (!is_visible_in_tree()) return; - const bool can_press=finger_pressed==-1 || allow_repress; + const bool can_press = finger_pressed == -1 || allow_repress; if (!can_press) return; //already fingering - Point2 coord = (get_global_transform_with_canvas()).affine_inverse().xform(Point2(p_event.screen_touch.x,p_event.screen_touch.y)); + Point2 coord = (get_global_transform_with_canvas()).affine_inverse().xform(Point2(p_event.screen_touch.x, p_event.screen_touch.y)); Rect2 item_rect = get_item_rect(); - bool touched=false; - bool check_rect=true; + bool touched = false; + bool check_rect = true; if (shape.is_valid()) { - check_rect=false; - Transform2D xform=shape_centered ? Transform2D().translated(get_item_rect().size*0.5f) : Transform2D(); - touched=shape->collide(xform, unit_rect, Transform2D(0, coord + Vector2(0.5,0.5))); + check_rect = false; + Transform2D xform = shape_centered ? Transform2D().translated(get_item_rect().size * 0.5f) : Transform2D(); + touched = shape->collide(xform, unit_rect, Transform2D(0, coord + Vector2(0.5, 0.5))); } if (bitmask.is_valid()) { - check_rect=false; - if (!touched && Rect2(Point2(),bitmask->get_size()).has_point(coord)) { + check_rect = false; + if (!touched && Rect2(Point2(), bitmask->get_size()).has_point(coord)) { if (bitmask->get_bit(coord)) - touched=true; + touched = true; } } if (!touched && check_rect) { if (!texture.is_null()) - touched=item_rect.has_point(coord); + touched = item_rect.has_point(coord); } - if (touched) { _press(p_event.screen_touch.index); } } else { - if (p_event.screen_touch.index==finger_pressed) { + if (p_event.screen_touch.index == finger_pressed) { _release(); } } @@ -283,17 +275,17 @@ void TouchScreenButton::_input(const InputEvent& p_event) { void TouchScreenButton::_press(int p_finger_pressed) { - finger_pressed=p_finger_pressed; - allow_repress=false; + finger_pressed = p_finger_pressed; + allow_repress = false; - if (action_id!=-1) { + if (action_id != -1) { Input::get_singleton()->action_press(action); InputEvent ie; - ie.type=InputEvent::ACTION; - ie.ID=0; - ie.action.action=action_id; - ie.action.pressed=true; + ie.type = InputEvent::ACTION; + ie.ID = 0; + ie.action.action = action_id; + ie.action.pressed = true; get_tree()->input_event(ie); } @@ -303,17 +295,17 @@ void TouchScreenButton::_press(int p_finger_pressed) { void TouchScreenButton::_release(bool p_exiting_tree) { - finger_pressed=-1; + finger_pressed = -1; - if (action_id!=-1) { + if (action_id != -1) { Input::get_singleton()->action_release(action); if (!p_exiting_tree) { InputEvent ie; - ie.type=InputEvent::ACTION; - ie.ID=0; - ie.action.action=action_id; - ie.action.pressed=false; + ie.type = InputEvent::ACTION; + ie.ID = 0; + ie.action.action = action_id; + ie.action.pressed = false; get_tree()->input_event(ie); } } @@ -327,18 +319,17 @@ void TouchScreenButton::_release(bool p_exiting_tree) { Rect2 TouchScreenButton::get_item_rect() const { if (texture.is_null()) - return Rect2(0,0,1,1); + return Rect2(0, 0, 1, 1); /* if (texture.is_null()) return CanvasItem::get_item_rect(); */ - return Rect2(Size2(),texture->get_size()); + return Rect2(Size2(), texture->get_size()); } - void TouchScreenButton::set_visibility_mode(VisibilityMode p_mode) { - visibility=p_mode; + visibility = p_mode; update(); } @@ -349,70 +340,65 @@ TouchScreenButton::VisibilityMode TouchScreenButton::get_visibility_mode() const void TouchScreenButton::set_passby_press(bool p_enable) { - passby_press=p_enable; + passby_press = p_enable; } -bool TouchScreenButton::is_passby_press_enabled() const{ +bool TouchScreenButton::is_passby_press_enabled() const { return passby_press; } - - void TouchScreenButton::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_texture","texture"),&TouchScreenButton::set_texture); - ClassDB::bind_method(D_METHOD("get_texture"),&TouchScreenButton::get_texture); - - ClassDB::bind_method(D_METHOD("set_texture_pressed","texture_pressed"),&TouchScreenButton::set_texture_pressed); - ClassDB::bind_method(D_METHOD("get_texture_pressed"),&TouchScreenButton::get_texture_pressed); - - ClassDB::bind_method(D_METHOD("set_bitmask","bitmask"),&TouchScreenButton::set_bitmask); - ClassDB::bind_method(D_METHOD("get_bitmask"),&TouchScreenButton::get_bitmask); - - ClassDB::bind_method(D_METHOD("set_shape","shape"),&TouchScreenButton::set_shape); - ClassDB::bind_method(D_METHOD("get_shape"),&TouchScreenButton::get_shape); + ClassDB::bind_method(D_METHOD("set_texture", "texture"), &TouchScreenButton::set_texture); + ClassDB::bind_method(D_METHOD("get_texture"), &TouchScreenButton::get_texture); - ClassDB::bind_method(D_METHOD("set_shape_centered","bool"),&TouchScreenButton::set_shape_centered); - ClassDB::bind_method(D_METHOD("is_shape_centered"),&TouchScreenButton::is_shape_centered); + ClassDB::bind_method(D_METHOD("set_texture_pressed", "texture_pressed"), &TouchScreenButton::set_texture_pressed); + ClassDB::bind_method(D_METHOD("get_texture_pressed"), &TouchScreenButton::get_texture_pressed); - ClassDB::bind_method(D_METHOD("set_action","action"),&TouchScreenButton::set_action); - ClassDB::bind_method(D_METHOD("get_action"),&TouchScreenButton::get_action); + ClassDB::bind_method(D_METHOD("set_bitmask", "bitmask"), &TouchScreenButton::set_bitmask); + ClassDB::bind_method(D_METHOD("get_bitmask"), &TouchScreenButton::get_bitmask); - ClassDB::bind_method(D_METHOD("set_visibility_mode","mode"),&TouchScreenButton::set_visibility_mode); - ClassDB::bind_method(D_METHOD("get_visibility_mode"),&TouchScreenButton::get_visibility_mode); + ClassDB::bind_method(D_METHOD("set_shape", "shape"), &TouchScreenButton::set_shape); + ClassDB::bind_method(D_METHOD("get_shape"), &TouchScreenButton::get_shape); - ClassDB::bind_method(D_METHOD("set_passby_press","enabled"),&TouchScreenButton::set_passby_press); - ClassDB::bind_method(D_METHOD("is_passby_press_enabled"),&TouchScreenButton::is_passby_press_enabled); + ClassDB::bind_method(D_METHOD("set_shape_centered", "bool"), &TouchScreenButton::set_shape_centered); + ClassDB::bind_method(D_METHOD("is_shape_centered"), &TouchScreenButton::is_shape_centered); - ClassDB::bind_method(D_METHOD("is_pressed"),&TouchScreenButton::is_pressed); + ClassDB::bind_method(D_METHOD("set_action", "action"), &TouchScreenButton::set_action); + ClassDB::bind_method(D_METHOD("get_action"), &TouchScreenButton::get_action); - ClassDB::bind_method(D_METHOD("_input"),&TouchScreenButton::_input); + ClassDB::bind_method(D_METHOD("set_visibility_mode", "mode"), &TouchScreenButton::set_visibility_mode); + ClassDB::bind_method(D_METHOD("get_visibility_mode"), &TouchScreenButton::get_visibility_mode); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"normal",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture"); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"pressed",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture_pressed","get_texture_pressed"); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"bitmask",PROPERTY_HINT_RESOURCE_TYPE,"BitMap"),"set_bitmask","get_bitmask"); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape2D"),"set_shape","get_shape"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"shape_centered"),"set_shape_centered","is_shape_centered"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"passby_press"),"set_passby_press","is_passby_press_enabled"); - ADD_PROPERTY( PropertyInfo(Variant::STRING,"action"),"set_action","get_action"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"visibility_mode",PROPERTY_HINT_ENUM,"Always,TouchScreen Only"),"set_visibility_mode","get_visibility_mode"); + ClassDB::bind_method(D_METHOD("set_passby_press", "enabled"), &TouchScreenButton::set_passby_press); + ClassDB::bind_method(D_METHOD("is_passby_press_enabled"), &TouchScreenButton::is_passby_press_enabled); - ADD_SIGNAL( MethodInfo("pressed" ) ); - ADD_SIGNAL( MethodInfo("released" ) ); + ClassDB::bind_method(D_METHOD("is_pressed"), &TouchScreenButton::is_pressed); + ClassDB::bind_method(D_METHOD("_input"), &TouchScreenButton::_input); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "pressed", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture_pressed", "get_texture_pressed"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "bitmask", PROPERTY_HINT_RESOURCE_TYPE, "BitMap"), "set_bitmask", "get_bitmask"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D"), "set_shape", "get_shape"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shape_centered"), "set_shape_centered", "is_shape_centered"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "passby_press"), "set_passby_press", "is_passby_press_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "action"), "set_action", "get_action"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_mode", PROPERTY_HINT_ENUM, "Always,TouchScreen Only"), "set_visibility_mode", "get_visibility_mode"); + ADD_SIGNAL(MethodInfo("pressed")); + ADD_SIGNAL(MethodInfo("released")); } TouchScreenButton::TouchScreenButton() { - finger_pressed=-1; - allow_repress=false; - action_id=-1; - passby_press=false; - visibility=VISIBILITY_ALWAYS; - shape_centered=true; - unit_rect=Ref(memnew(RectangleShape2D)); - unit_rect->set_extents(Vector2(0.5,0.5)); + finger_pressed = -1; + allow_repress = false; + action_id = -1; + passby_press = false; + visibility = VISIBILITY_ALWAYS; + shape_centered = true; + unit_rect = Ref(memnew(RectangleShape2D)); + unit_rect->set_extents(Vector2(0.5, 0.5)); } diff --git a/scene/2d/screen_button.h b/scene/2d/screen_button.h index 8ce378c66..d648920b2 100644 --- a/scene/2d/screen_button.h +++ b/scene/2d/screen_button.h @@ -30,15 +30,15 @@ #define SCREEN_BUTTON_H #include "scene/2d/node_2d.h" -#include "scene/resources/texture.h" #include "scene/resources/bit_mask.h" #include "scene/resources/rectangle_shape_2d.h" +#include "scene/resources/texture.h" class TouchScreenButton : public Node2D { - GDCLASS(TouchScreenButton,Node2D); -public: + GDCLASS(TouchScreenButton, Node2D); +public: enum VisibilityMode { VISIBILITY_ALWAYS, VISIBILITY_TOUCHSCREEN_ONLY @@ -61,34 +61,32 @@ private: VisibilityMode visibility; - void _input(const InputEvent& p_Event); + void _input(const InputEvent &p_Event); void _press(int p_finger_pressed); - void _release(bool p_exiting_tree=false); + void _release(bool p_exiting_tree = false); protected: - void _notification(int p_what); static void _bind_methods(); -public: - - void set_texture(const Ref& p_texture); +public: + void set_texture(const Ref &p_texture); Ref get_texture() const; - void set_texture_pressed(const Ref& p_texture_pressed); + void set_texture_pressed(const Ref &p_texture_pressed); Ref get_texture_pressed() const; - void set_bitmask(const Ref& p_bitmask); + void set_bitmask(const Ref &p_bitmask); Ref get_bitmask() const; - void set_shape(const Ref& p_shape); + void set_shape(const Ref &p_shape); Ref get_shape() const; void set_shape_centered(bool p_shape_centered); bool is_shape_centered() const; - void set_action(const String& p_action); + void set_action(const String &p_action); String get_action() const; void set_passby_press(bool p_enable); @@ -101,7 +99,6 @@ public: Rect2 get_item_rect() const; - TouchScreenButton(); }; diff --git a/scene/2d/sprite.cpp b/scene/2d/sprite.cpp index 26c2756ac..41ea6a39e 100644 --- a/scene/2d/sprite.cpp +++ b/scene/2d/sprite.cpp @@ -28,14 +28,13 @@ /*************************************************************************/ #include "sprite.h" #include "core/core_string_names.h" -#include "scene/scene_string_names.h" -#include "scene/main/viewport.h" #include "os/os.h" +#include "scene/main/viewport.h" +#include "scene/scene_string_names.h" -void Sprite::edit_set_pivot(const Point2& p_pivot) { +void Sprite::edit_set_pivot(const Point2 &p_pivot) { set_offset(p_pivot); - } Point2 Sprite::edit_get_pivot() const { @@ -49,16 +48,13 @@ bool Sprite::edit_has_pivot() const { void Sprite::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_DRAW: { if (texture.is_null()) return; - - - RID ci = get_canvas_item(); /* @@ -71,52 +67,51 @@ void Sprite::_notification(int p_what) { if (region) { - s=region_rect.size; - src_rect=region_rect; + s = region_rect.size; + src_rect = region_rect; } else { s = Size2(texture->get_size()); - s=s/Size2(hframes,vframes); - - src_rect.size=s; - src_rect.pos.x+=float(frame%hframes)*s.x; - src_rect.pos.y+=float(frame/hframes)*s.y; + s = s / Size2(hframes, vframes); + src_rect.size = s; + src_rect.pos.x += float(frame % hframes) * s.x; + src_rect.pos.y += float(frame / hframes) * s.y; } - Point2 ofs=offset; + Point2 ofs = offset; if (centered) - ofs-=s/2; + ofs -= s / 2; if (Engine::get_singleton()->get_use_pixel_snap()) { - ofs=ofs.floor(); + ofs = ofs.floor(); } - Rect2 dst_rect(ofs,s); + Rect2 dst_rect(ofs, s); if (hflip) - dst_rect.size.x=-dst_rect.size.x; + dst_rect.size.x = -dst_rect.size.x; if (vflip) - dst_rect.size.y=-dst_rect.size.y; + dst_rect.size.y = -dst_rect.size.y; - texture->draw_rect_region(ci,dst_rect,src_rect); + texture->draw_rect_region(ci, dst_rect, src_rect); } break; } } -void Sprite::set_texture(const Ref& p_texture) { +void Sprite::set_texture(const Ref &p_texture) { - if (p_texture==texture) + if (p_texture == texture) return; #ifdef DEBUG_ENABLED if (texture.is_valid()) { - texture->disconnect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->update); + texture->disconnect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->update); } #endif - texture=p_texture; + texture = p_texture; #ifdef DEBUG_ENABLED if (texture.is_valid()) { texture->set_flags(texture->get_flags()); //remove repeat from texture, it looks bad in sprites - texture->connect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->update); + texture->connect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->update); } #endif update(); @@ -131,7 +126,7 @@ Ref Sprite::get_texture() const { void Sprite::set_centered(bool p_center) { - centered=p_center; + centered = p_center; update(); item_rect_changed(); } @@ -141,9 +136,9 @@ bool Sprite::is_centered() const { return centered; } -void Sprite::set_offset(const Point2& p_offset) { +void Sprite::set_offset(const Point2 &p_offset) { - offset=p_offset; + offset = p_offset; update(); item_rect_changed(); _change_notify("offset"); @@ -155,7 +150,7 @@ Point2 Sprite::get_offset() const { void Sprite::set_flip_h(bool p_flip) { - hflip=p_flip; + hflip = p_flip; update(); } bool Sprite::is_flipped_h() const { @@ -165,7 +160,7 @@ bool Sprite::is_flipped_h() const { void Sprite::set_flip_v(bool p_flip) { - vflip=p_flip; + vflip = p_flip; update(); } bool Sprite::is_flipped_v() const { @@ -175,24 +170,24 @@ bool Sprite::is_flipped_v() const { void Sprite::set_region(bool p_region) { - if (p_region==region) + if (p_region == region) return; - region=p_region; + region = p_region; update(); } -bool Sprite::is_region() const{ +bool Sprite::is_region() const { return region; } -void Sprite::set_region_rect(const Rect2& p_region_rect) { +void Sprite::set_region_rect(const Rect2 &p_region_rect) { - if (region_rect==p_region_rect) + if (region_rect == p_region_rect) return; - region_rect=p_region_rect; + region_rect = p_region_rect; if (region) item_rect_changed(); @@ -207,12 +202,12 @@ Rect2 Sprite::get_region_rect() const { void Sprite::set_frame(int p_frame) { - ERR_FAIL_INDEX(p_frame,vframes*hframes); + ERR_FAIL_INDEX(p_frame, vframes * hframes); if (frame != p_frame) item_rect_changed(); - frame=p_frame; + frame = p_frame; _change_notify("frame"); emit_signal(SceneStringNames::get_singleton()->frame_changed); @@ -225,8 +220,8 @@ int Sprite::get_frame() const { void Sprite::set_vframes(int p_amount) { - ERR_FAIL_COND(p_amount<1); - vframes=p_amount; + ERR_FAIL_COND(p_amount < 1); + vframes = p_amount; update(); item_rect_changed(); _change_notify("frame"); @@ -238,8 +233,8 @@ int Sprite::get_vframes() const { void Sprite::set_hframes(int p_amount) { - ERR_FAIL_COND(p_amount<1); - hframes=p_amount; + ERR_FAIL_COND(p_amount < 1); + hframes = p_amount; update(); item_rect_changed(); _change_notify("frame"); @@ -249,12 +244,10 @@ int Sprite::get_hframes() const { return hframes; } - - Rect2 Sprite::get_item_rect() const { if (texture.is_null()) - return Rect2(0,0,1,1); + return Rect2(0, 0, 1, 1); /* if (texture.is_null()) return CanvasItem::get_item_rect(); @@ -264,99 +257,92 @@ Rect2 Sprite::get_item_rect() const { if (region) { - s=region_rect.size; + s = region_rect.size; } else { s = texture->get_size(); - s=s/Point2(hframes,vframes); + s = s / Point2(hframes, vframes); } - Point2 ofs=offset; + Point2 ofs = offset; if (centered) - ofs-=s/2; + ofs -= s / 2; - if (s==Size2(0,0)) - s=Size2(1,1); + if (s == Size2(0, 0)) + s = Size2(1, 1); - return Rect2(ofs,s); + return Rect2(ofs, s); } +void Sprite::_validate_property(PropertyInfo &property) const { + if (property.name == "frame") { -void Sprite::_validate_property(PropertyInfo& property) const { - - if (property.name=="frame") { - - property.hint=PROPERTY_HINT_SPRITE_FRAME; + property.hint = PROPERTY_HINT_SPRITE_FRAME; - property.hint_string="0,"+itos(vframes*hframes-1)+",1"; + property.hint_string = "0," + itos(vframes * hframes - 1) + ",1"; } } void Sprite::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_texture","texture:Texture"),&Sprite::set_texture); - ClassDB::bind_method(D_METHOD("get_texture:Texture"),&Sprite::get_texture); + ClassDB::bind_method(D_METHOD("set_texture", "texture:Texture"), &Sprite::set_texture); + ClassDB::bind_method(D_METHOD("get_texture:Texture"), &Sprite::get_texture); - ClassDB::bind_method(D_METHOD("set_centered","centered"),&Sprite::set_centered); - ClassDB::bind_method(D_METHOD("is_centered"),&Sprite::is_centered); + ClassDB::bind_method(D_METHOD("set_centered", "centered"), &Sprite::set_centered); + ClassDB::bind_method(D_METHOD("is_centered"), &Sprite::is_centered); - ClassDB::bind_method(D_METHOD("set_offset","offset"),&Sprite::set_offset); - ClassDB::bind_method(D_METHOD("get_offset"),&Sprite::get_offset); + ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Sprite::set_offset); + ClassDB::bind_method(D_METHOD("get_offset"), &Sprite::get_offset); - ClassDB::bind_method(D_METHOD("set_flip_h","flip_h"),&Sprite::set_flip_h); - ClassDB::bind_method(D_METHOD("is_flipped_h"),&Sprite::is_flipped_h); + ClassDB::bind_method(D_METHOD("set_flip_h", "flip_h"), &Sprite::set_flip_h); + ClassDB::bind_method(D_METHOD("is_flipped_h"), &Sprite::is_flipped_h); - ClassDB::bind_method(D_METHOD("set_flip_v","flip_v"),&Sprite::set_flip_v); - ClassDB::bind_method(D_METHOD("is_flipped_v"),&Sprite::is_flipped_v); + ClassDB::bind_method(D_METHOD("set_flip_v", "flip_v"), &Sprite::set_flip_v); + ClassDB::bind_method(D_METHOD("is_flipped_v"), &Sprite::is_flipped_v); - ClassDB::bind_method(D_METHOD("set_region","enabled"),&Sprite::set_region); - ClassDB::bind_method(D_METHOD("is_region"),&Sprite::is_region); + ClassDB::bind_method(D_METHOD("set_region", "enabled"), &Sprite::set_region); + ClassDB::bind_method(D_METHOD("is_region"), &Sprite::is_region); - ClassDB::bind_method(D_METHOD("set_region_rect","rect"),&Sprite::set_region_rect); - ClassDB::bind_method(D_METHOD("get_region_rect"),&Sprite::get_region_rect); + ClassDB::bind_method(D_METHOD("set_region_rect", "rect"), &Sprite::set_region_rect); + ClassDB::bind_method(D_METHOD("get_region_rect"), &Sprite::get_region_rect); - ClassDB::bind_method(D_METHOD("set_frame","frame"),&Sprite::set_frame); - ClassDB::bind_method(D_METHOD("get_frame"),&Sprite::get_frame); + ClassDB::bind_method(D_METHOD("set_frame", "frame"), &Sprite::set_frame); + ClassDB::bind_method(D_METHOD("get_frame"), &Sprite::get_frame); - ClassDB::bind_method(D_METHOD("set_vframes","vframes"),&Sprite::set_vframes); - ClassDB::bind_method(D_METHOD("get_vframes"),&Sprite::get_vframes); + ClassDB::bind_method(D_METHOD("set_vframes", "vframes"), &Sprite::set_vframes); + ClassDB::bind_method(D_METHOD("get_vframes"), &Sprite::get_vframes); - ClassDB::bind_method(D_METHOD("set_hframes","hframes"),&Sprite::set_hframes); - ClassDB::bind_method(D_METHOD("get_hframes"),&Sprite::get_hframes); + ClassDB::bind_method(D_METHOD("set_hframes", "hframes"), &Sprite::set_hframes); + ClassDB::bind_method(D_METHOD("get_hframes"), &Sprite::get_hframes); ADD_SIGNAL(MethodInfo("frame_changed")); ADD_SIGNAL(MethodInfo("texture_changed")); - ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_texture","get_texture"); - ADD_PROPERTYNO( PropertyInfo( Variant::BOOL, "centered"), "set_centered","is_centered"); - ADD_PROPERTYNZ( PropertyInfo( Variant::VECTOR2, "offset"), "set_offset","get_offset"); - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "flip_h"), "set_flip_h","is_flipped_h"); - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "flip_v"), "set_flip_v","is_flipped_v"); - ADD_PROPERTYNO( PropertyInfo( Variant::INT, "vframes",PROPERTY_HINT_RANGE,"1,16384,1"), "set_vframes","get_vframes"); - ADD_PROPERTYNO( PropertyInfo( Variant::INT, "hframes",PROPERTY_HINT_RANGE,"1,16384,1"), "set_hframes","get_hframes"); - ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "frame",PROPERTY_HINT_SPRITE_FRAME), "set_frame","get_frame"); - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "region"), "set_region","is_region"); - ADD_PROPERTYNZ( PropertyInfo( Variant::RECT2, "region_rect"), "set_region_rect","get_region_rect"); - + ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); + ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered"); + ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v"); + ADD_PROPERTYNO(PropertyInfo(Variant::INT, "vframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_vframes", "get_vframes"); + ADD_PROPERTYNO(PropertyInfo(Variant::INT, "hframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_hframes", "get_hframes"); + ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "frame", PROPERTY_HINT_SPRITE_FRAME), "set_frame", "get_frame"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "region"), "set_region", "is_region"); + ADD_PROPERTYNZ(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect"); } Sprite::Sprite() { - centered=true; - hflip=false; - vflip=false; - region=false; - - frame=0; + centered = true; + hflip = false; + vflip = false; + region = false; - vframes=1; - hframes=1; + frame = 0; + vframes = 1; + hframes = 1; } - - - //////////////////////////// VPSPRITE /// /// diff --git a/scene/2d/sprite.h b/scene/2d/sprite.h index ab4487ef7..c4bc80064 100644 --- a/scene/2d/sprite.h +++ b/scene/2d/sprite.h @@ -32,10 +32,9 @@ #include "scene/2d/node_2d.h" #include "scene/resources/texture.h" - class Sprite : public Node2D { - GDCLASS( Sprite, Node2D ); + GDCLASS(Sprite, Node2D); Ref texture; @@ -52,29 +51,25 @@ class Sprite : public Node2D { int vframes; int hframes; - - protected: - void _notification(int p_what); static void _bind_methods(); - virtual void _validate_property(PropertyInfo& property) const; + virtual void _validate_property(PropertyInfo &property) const; public: - - virtual void edit_set_pivot(const Point2& p_pivot); + virtual void edit_set_pivot(const Point2 &p_pivot); virtual Point2 edit_get_pivot() const; virtual bool edit_has_pivot() const; - void set_texture(const Ref& p_texture); + void set_texture(const Ref &p_texture); Ref get_texture() const; void set_centered(bool p_center); bool is_centered() const; - void set_offset(const Point2& p_offset); + void set_offset(const Point2 &p_offset); Point2 get_offset() const; void set_flip_h(bool p_flip); @@ -86,7 +81,7 @@ public: void set_region(bool p_region); bool is_region() const; - void set_region_rect(const Rect2& p_region_rect); + void set_region_rect(const Rect2 &p_region_rect); Rect2 get_region_rect() const; void set_frame(int p_frame); diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp index f89a72e1b..02b41fbd0 100644 --- a/scene/2d/tile_map.cpp +++ b/scene/2d/tile_map.cpp @@ -28,11 +28,9 @@ /*************************************************************************/ #include "tile_map.h" #include "io/marshalls.h" -#include "servers/physics_2d_server.h" #include "method_bind_ext.inc" #include "os/os.h" - - +#include "servers/physics_2d_server.h" int TileMap::_get_quadrant_size() const { @@ -44,51 +42,49 @@ int TileMap::_get_quadrant_size() const { void TileMap::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - Node2D *c=this; - while(c) { + Node2D *c = this; + while (c) { - navigation=c->cast_to(); + navigation = c->cast_to(); if (navigation) { break; } - c=c->get_parent()->cast_to(); + c = c->get_parent()->cast_to(); } - pending_update=true; + pending_update = true; _update_dirty_quadrants(); RID space = get_world_2d()->get_space(); _update_quadrant_transform(); _update_quadrant_space(space); - } break; case NOTIFICATION_EXIT_TREE: { _update_quadrant_space(RID()); - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - Quadrant &q=E->get(); + Quadrant &q = E->get(); if (navigation) { - for(Map::Element *E=q.navpoly_ids.front();E;E=E->next()) { + for (Map::Element *E = q.navpoly_ids.front(); E; E = E->next()) { navigation->navpoly_remove(E->get().id); } q.navpoly_ids.clear(); } - for(Map::Element *E=q.occluder_instances.front();E;E=E->next()) { + for (Map::Element *E = q.occluder_instances.front(); E; E = E->next()) { VS::get_singleton()->free(E->get().id); } q.occluder_instances.clear(); } - navigation=NULL; - + navigation = NULL; } break; case NOTIFICATION_TRANSFORM_CHANGED: { @@ -100,12 +96,12 @@ void TileMap::_notification(int p_what) { } } -void TileMap::_update_quadrant_space(const RID& p_space) { +void TileMap::_update_quadrant_space(const RID &p_space) { - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - Quadrant &q=E->get(); - Physics2DServer::get_singleton()->body_set_space(q.body,p_space); + Quadrant &q = E->get(); + Physics2DServer::get_singleton()->body_set_space(q.body, p_space); } } @@ -120,43 +116,42 @@ void TileMap::_update_quadrant_transform() { if (navigation) nav_rel = get_relative_transform_to_parent(navigation); - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - Quadrant &q=E->get(); + Quadrant &q = E->get(); Transform2D xform; - xform.set_origin( q.pos ); + xform.set_origin(q.pos); xform = global_transform * xform; - Physics2DServer::get_singleton()->body_set_state(q.body,Physics2DServer::BODY_STATE_TRANSFORM,xform); + Physics2DServer::get_singleton()->body_set_state(q.body, Physics2DServer::BODY_STATE_TRANSFORM, xform); if (navigation) { - for(Map::Element *E=q.navpoly_ids.front();E;E=E->next()) { + for (Map::Element *E = q.navpoly_ids.front(); E; E = E->next()) { - navigation->navpoly_set_transform(E->get().id,nav_rel * E->get().xform); + navigation->navpoly_set_transform(E->get().id, nav_rel * E->get().xform); } } - for(Map::Element *E=q.occluder_instances.front();E;E=E->next()) { - VS::get_singleton()->canvas_light_occluder_set_transform(E->get().id,global_transform * E->get().xform); + for (Map::Element *E = q.occluder_instances.front(); E; E = E->next()) { + VS::get_singleton()->canvas_light_occluder_set_transform(E->get().id, global_transform * E->get().xform); } } } -void TileMap::set_tileset(const Ref& p_tileset) { +void TileMap::set_tileset(const Ref &p_tileset) { if (tile_set.is_valid()) - tile_set->disconnect("changed",this,"_recreate_quadrants"); + tile_set->disconnect("changed", this, "_recreate_quadrants"); _clear_quadrants(); - tile_set=p_tileset; + tile_set = p_tileset; if (tile_set.is_valid()) - tile_set->connect("changed",this,"_recreate_quadrants"); + tile_set->connect("changed", this, "_recreate_quadrants"); else clear(); _recreate_quadrants(); emit_signal("settings_changed"); - } Ref TileMap::get_tileset() const { @@ -166,14 +161,12 @@ Ref TileMap::get_tileset() const { void TileMap::set_cell_size(Size2 p_size) { - ERR_FAIL_COND(p_size.x<1 || p_size.y<1); + ERR_FAIL_COND(p_size.x < 1 || p_size.y < 1); _clear_quadrants(); - cell_size=p_size; + cell_size = p_size; _recreate_quadrants(); emit_signal("settings_changed"); - - } Size2 TileMap::get_cell_size() const { @@ -181,13 +174,12 @@ Size2 TileMap::get_cell_size() const { } void TileMap::set_quadrant_size(int p_size) { - ERR_FAIL_COND(p_size<1); + ERR_FAIL_COND(p_size < 1); _clear_quadrants(); - quadrant_size=p_size; + quadrant_size = p_size; _recreate_quadrants(); emit_signal("settings_changed"); - } int TileMap::get_quadrant_size() const { @@ -196,11 +188,9 @@ int TileMap::get_quadrant_size() const { void TileMap::set_center_x(bool p_enable) { - center_x=p_enable; + center_x = p_enable; _recreate_quadrants(); emit_signal("settings_changed"); - - } bool TileMap::get_center_x() const { @@ -208,24 +198,22 @@ bool TileMap::get_center_x() const { } void TileMap::set_center_y(bool p_enable) { - center_y=p_enable; + center_y = p_enable; _recreate_quadrants(); emit_signal("settings_changed"); - } bool TileMap::get_center_y() const { return center_y; } -void TileMap::_fix_cell_transform(Transform2D& xform,const Cell& p_cell, const Vector2& p_offset, const Size2 &p_sc) { +void TileMap::_fix_cell_transform(Transform2D &xform, const Cell &p_cell, const Vector2 &p_offset, const Size2 &p_sc) { - Size2 s=p_sc; + Size2 s = p_sc; Vector2 offset = p_offset; - - if (tile_origin==TILE_ORIGIN_BOTTOM_LEFT) - offset.y+=cell_size.y; + if (tile_origin == TILE_ORIGIN_BOTTOM_LEFT) + offset.y += cell_size.y; if (s.y > s.x) { if ((p_cell.flip_h && (p_cell.flip_v || p_cell.transpose)) || (p_cell.flip_v && !p_cell.transpose)) @@ -242,26 +230,25 @@ void TileMap::_fix_cell_transform(Transform2D& xform,const Cell& p_cell, const V SWAP(s.x, s.y); } if (p_cell.flip_h) { - xform.elements[0].x=-xform.elements[0].x; - xform.elements[1].x=-xform.elements[1].x; - if (tile_origin==TILE_ORIGIN_TOP_LEFT || tile_origin==TILE_ORIGIN_BOTTOM_LEFT) - offset.x=s.x-offset.x; + xform.elements[0].x = -xform.elements[0].x; + xform.elements[1].x = -xform.elements[1].x; + if (tile_origin == TILE_ORIGIN_TOP_LEFT || tile_origin == TILE_ORIGIN_BOTTOM_LEFT) + offset.x = s.x - offset.x; } if (p_cell.flip_v) { - xform.elements[0].y=-xform.elements[0].y; - xform.elements[1].y=-xform.elements[1].y; - if (tile_origin==TILE_ORIGIN_TOP_LEFT) - offset.y=s.y-offset.y; - else if (tile_origin==TILE_ORIGIN_BOTTOM_LEFT) { - if(p_cell.transpose) - offset.y+=s.y; + xform.elements[0].y = -xform.elements[0].y; + xform.elements[1].y = -xform.elements[1].y; + if (tile_origin == TILE_ORIGIN_TOP_LEFT) + offset.y = s.y - offset.y; + else if (tile_origin == TILE_ORIGIN_BOTTOM_LEFT) { + if (p_cell.transpose) + offset.y += s.y; else - offset.y-=s.y; + offset.y -= s.y; } } - xform.elements[2].x+=offset.x; - xform.elements[2].y+=offset.y; - + xform.elements[2].x += offset.x; + xform.elements[2].y += offset.y; } void TileMap::_update_dirty_quadrants() { @@ -276,26 +263,26 @@ void TileMap::_update_dirty_quadrants() { VisualServer *vs = VisualServer::get_singleton(); Physics2DServer *ps = Physics2DServer::get_singleton(); Vector2 tofs = get_cell_draw_offset(); - Vector2 tcenter = cell_size/2; + Vector2 tcenter = cell_size / 2; Transform2D nav_rel; if (navigation) nav_rel = get_relative_transform_to_parent(navigation); Vector2 qofs; - SceneTree *st=SceneTree::get_singleton(); + SceneTree *st = SceneTree::get_singleton(); Color debug_collision_color; bool debug_shapes = st && st->is_debugging_collisions_hint(); if (debug_shapes) { - debug_collision_color=st->get_debug_collisions_color(); + debug_collision_color = st->get_debug_collisions_color(); } while (dirty_quadrant_list.first()) { Quadrant &q = *dirty_quadrant_list.first()->self(); - for (List::Element *E=q.canvas_items.front();E;E=E->next()) { + for (List::Element *E = q.canvas_items.front(); E; E = E->next()) { vs->free(E->get()); } @@ -303,17 +290,17 @@ void TileMap::_update_dirty_quadrants() { q.canvas_items.clear(); ps->body_clear_shapes(q.body); - int shape_idx=0; + int shape_idx = 0; if (navigation) { - for(Map::Element *E=q.navpoly_ids.front();E;E=E->next()) { + for (Map::Element *E = q.navpoly_ids.front(); E; E = E->next()) { navigation->navpoly_remove(E->get().id); } q.navpoly_ids.clear(); } - for(Map::Element *E=q.occluder_instances.front();E;E=E->next()) { + for (Map::Element *E = q.occluder_instances.front(); E; E = E->next()) { VS::get_singleton()->free(E->get().id); } q.occluder_instances.clear(); @@ -321,10 +308,10 @@ void TileMap::_update_dirty_quadrants() { RID prev_canvas_item; RID prev_debug_canvas_item; - for(int i=0;i::Element *E=tile_map.find( q.cells[i] ); - Cell &c=E->get(); + Map::Element *E = tile_map.find(q.cells[i]); + Cell &c = E->get(); //moment of truth if (!tile_set->has_tile(c.id)) continue; @@ -342,57 +329,55 @@ void TileMap::_update_dirty_quadrants() { RID canvas_item; RID debug_canvas_item; - if (prev_canvas_item==RID() || prev_material!=mat) { + if (prev_canvas_item == RID() || prev_material != mat) { - canvas_item=vs->canvas_item_create(); + canvas_item = vs->canvas_item_create(); if (mat.is_valid()) - vs->canvas_item_set_material(canvas_item,mat->get_rid()); - vs->canvas_item_set_parent( canvas_item, get_canvas_item() ); + vs->canvas_item_set_material(canvas_item, mat->get_rid()); + vs->canvas_item_set_parent(canvas_item, get_canvas_item()); Transform2D xform; - xform.set_origin( q.pos ); - vs->canvas_item_set_transform( canvas_item, xform ); - vs->canvas_item_set_light_mask(canvas_item,get_light_mask()); + xform.set_origin(q.pos); + vs->canvas_item_set_transform(canvas_item, xform); + vs->canvas_item_set_light_mask(canvas_item, get_light_mask()); q.canvas_items.push_back(canvas_item); if (debug_shapes) { - debug_canvas_item=vs->canvas_item_create(); - vs->canvas_item_set_parent( debug_canvas_item, canvas_item ); - vs->canvas_item_set_z_as_relative_to_parent(debug_canvas_item,false); - vs->canvas_item_set_z(debug_canvas_item,VS::CANVAS_ITEM_Z_MAX-1); + debug_canvas_item = vs->canvas_item_create(); + vs->canvas_item_set_parent(debug_canvas_item, canvas_item); + vs->canvas_item_set_z_as_relative_to_parent(debug_canvas_item, false); + vs->canvas_item_set_z(debug_canvas_item, VS::CANVAS_ITEM_Z_MAX - 1); q.canvas_items.push_back(debug_canvas_item); - prev_debug_canvas_item=debug_canvas_item; + prev_debug_canvas_item = debug_canvas_item; } - prev_canvas_item=canvas_item; - prev_material=mat; + prev_canvas_item = canvas_item; + prev_material = mat; } else { - canvas_item=prev_canvas_item; + canvas_item = prev_canvas_item; if (debug_shapes) { - debug_canvas_item=prev_debug_canvas_item; + debug_canvas_item = prev_debug_canvas_item; } } - - Rect2 r = tile_set->tile_get_region(c.id); Size2 s = tex->get_size(); - if (r==Rect2()) + if (r == Rect2()) s = tex->get_size(); else { s = r.size; - r.pos.x+=fp_adjust; - r.pos.y+=fp_adjust; - r.size.x-=fp_adjust*2.0; - r.size.y-=fp_adjust*2.0; + r.pos.x += fp_adjust; + r.pos.y += fp_adjust; + r.size.x -= fp_adjust * 2.0; + r.size.y -= fp_adjust * 2.0; } Rect2 rect; - rect.pos=offset.floor(); - rect.size=s; + rect.pos = offset.floor(); + rect.size = s; if (rect.size.y > rect.size.x) { if ((c.flip_h && (c.flip_v || c.transpose)) || (c.flip_v && !c.transpose)) @@ -402,75 +387,72 @@ void TileMap::_update_dirty_quadrants() { tile_ofs.x += rect.size.x - rect.size.y; } - /* rect.size.x+=fp_adjust; + /* rect.size.x+=fp_adjust; rect.size.y+=fp_adjust;*/ if (c.transpose) SWAP(tile_ofs.x, tile_ofs.y); if (c.flip_h) { - rect.size.x=-rect.size.x; - tile_ofs.x=-tile_ofs.x; + rect.size.x = -rect.size.x; + tile_ofs.x = -tile_ofs.x; } if (c.flip_v) { - rect.size.y=-rect.size.y; - tile_ofs.y=-tile_ofs.y; + rect.size.y = -rect.size.y; + tile_ofs.y = -tile_ofs.y; } Vector2 center_ofs; - if (tile_origin==TILE_ORIGIN_TOP_LEFT) { - rect.pos+=tile_ofs; - - } else if (tile_origin==TILE_ORIGIN_BOTTOM_LEFT) { - - rect.pos+=tile_ofs; - - if(c.transpose) - { - if(c.flip_h) - rect.pos.x-=cell_size.x; + if (tile_origin == TILE_ORIGIN_TOP_LEFT) { + rect.pos += tile_ofs; + + } else if (tile_origin == TILE_ORIGIN_BOTTOM_LEFT) { + + rect.pos += tile_ofs; + + if (c.transpose) { + if (c.flip_h) + rect.pos.x -= cell_size.x; else - rect.pos.x+=cell_size.x; + rect.pos.x += cell_size.x; } else { - if(c.flip_v) - rect.pos.y-=cell_size.y; + if (c.flip_v) + rect.pos.y -= cell_size.y; else - rect.pos.y+=cell_size.y; + rect.pos.y += cell_size.y; } - - } else if (tile_origin==TILE_ORIGIN_CENTER) { - rect.pos+=tcenter; - Vector2 center = (s/2) - tile_ofs; - center_ofs=tcenter-(s/2); + } else if (tile_origin == TILE_ORIGIN_CENTER) { + rect.pos += tcenter; + + Vector2 center = (s / 2) - tile_ofs; + center_ofs = tcenter - (s / 2); if (c.flip_h) - rect.pos.x-=s.x-center.x; + rect.pos.x -= s.x - center.x; else - rect.pos.x-=center.x; + rect.pos.x -= center.x; if (c.flip_v) - rect.pos.y-=s.y-center.y; + rect.pos.y -= s.y - center.y; else - rect.pos.y-=center.y; + rect.pos.y -= center.y; } - Color modulate = tile_set->tile_get_modulate(c.id); Color self_modulate = get_self_modulate(); - modulate = Color(modulate.r*self_modulate.r, modulate.g*self_modulate.g, - modulate.b*self_modulate.b, modulate.a*self_modulate.a); - if (r==Rect2()) { - tex->draw_rect(canvas_item,rect,false,modulate,c.transpose); + modulate = Color(modulate.r * self_modulate.r, modulate.g * self_modulate.g, + modulate.b * self_modulate.b, modulate.a * self_modulate.a); + if (r == Rect2()) { + tex->draw_rect(canvas_item, rect, false, modulate, c.transpose); } else { - tex->draw_rect_region(canvas_item,rect,r,modulate,c.transpose); + tex->draw_rect_region(canvas_item, rect, r, modulate, c.transpose); } - Vector< Ref > shapes = tile_set->tile_get_shapes(c.id); - + Vector > shapes = tile_set->tile_get_shapes(c.id); - for(int i=0;i shape = shapes[i]; if (shape.is_valid()) { @@ -479,21 +461,19 @@ void TileMap::_update_dirty_quadrants() { Transform2D xform; xform.set_origin(offset.floor()); - _fix_cell_transform(xform,c,shape_ofs+center_ofs,s); + _fix_cell_transform(xform, c, shape_ofs + center_ofs, s); if (debug_canvas_item.is_valid()) { - vs->canvas_item_add_set_transform(debug_canvas_item,xform); - shape->draw(debug_canvas_item,debug_collision_color); - + vs->canvas_item_add_set_transform(debug_canvas_item, xform); + shape->draw(debug_canvas_item, debug_collision_color); } - ps->body_add_shape(q.body,shape->get_rid(),xform); - ps->body_set_shape_metadata(q.body,shape_idx++,Vector2(E->key().x,E->key().y)); - + ps->body_add_shape(q.body, shape->get_rid(), xform); + ps->body_set_shape_metadata(q.body, shape_idx++, Vector2(E->key().x, E->key().y)); } } if (debug_canvas_item.is_valid()) { - vs->canvas_item_add_set_transform(debug_canvas_item,Transform2D()); + vs->canvas_item_add_set_transform(debug_canvas_item, Transform2D()); } if (navigation) { @@ -501,145 +481,134 @@ void TileMap::_update_dirty_quadrants() { if (navpoly.is_valid()) { Vector2 npoly_ofs = tile_set->tile_get_navigation_polygon_offset(c.id); Transform2D xform; - xform.set_origin(offset.floor()+q.pos); - _fix_cell_transform(xform,c,npoly_ofs+center_ofs,s); + xform.set_origin(offset.floor() + q.pos); + _fix_cell_transform(xform, c, npoly_ofs + center_ofs, s); - - int pid = navigation->navpoly_create(navpoly,nav_rel * xform); + int pid = navigation->navpoly_create(navpoly, nav_rel * xform); Quadrant::NavPoly np; - np.id=pid; - np.xform=xform; - q.navpoly_ids[E->key()]=np; + np.id = pid; + np.xform = xform; + q.navpoly_ids[E->key()] = np; } } - - Ref occluder=tile_set->tile_get_light_occluder(c.id); + Ref occluder = tile_set->tile_get_light_occluder(c.id); if (occluder.is_valid()) { Vector2 occluder_ofs = tile_set->tile_get_occluder_offset(c.id); Transform2D xform; - xform.set_origin(offset.floor()+q.pos); - _fix_cell_transform(xform,c,occluder_ofs+center_ofs,s); + xform.set_origin(offset.floor() + q.pos); + _fix_cell_transform(xform, c, occluder_ofs + center_ofs, s); RID orid = VS::get_singleton()->canvas_light_occluder_create(); - VS::get_singleton()->canvas_light_occluder_set_transform(orid,get_global_transform() * xform); - VS::get_singleton()->canvas_light_occluder_set_polygon(orid,occluder->get_rid()); - VS::get_singleton()->canvas_light_occluder_attach_to_canvas(orid,get_canvas()); - VS::get_singleton()->canvas_light_occluder_set_light_mask(orid,occluder_light_mask); + VS::get_singleton()->canvas_light_occluder_set_transform(orid, get_global_transform() * xform); + VS::get_singleton()->canvas_light_occluder_set_polygon(orid, occluder->get_rid()); + VS::get_singleton()->canvas_light_occluder_attach_to_canvas(orid, get_canvas()); + VS::get_singleton()->canvas_light_occluder_set_light_mask(orid, occluder_light_mask); Quadrant::Occluder oc; - oc.xform=xform; - oc.id=orid; - q.occluder_instances[E->key()]=oc; + oc.xform = xform; + oc.id = orid; + q.occluder_instances[E->key()] = oc; } } - dirty_quadrant_list.remove( dirty_quadrant_list.first() ); - quadrant_order_dirty=true; + dirty_quadrant_list.remove(dirty_quadrant_list.first()); + quadrant_order_dirty = true; } - - - pending_update=false; + pending_update = false; if (quadrant_order_dirty) { - int index=-0x80000000; //always must be drawn below children - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + int index = -0x80000000; //always must be drawn below children + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - Quadrant &q=E->get(); - for (List::Element *E=q.canvas_items.front();E;E=E->next()) { + Quadrant &q = E->get(); + for (List::Element *E = q.canvas_items.front(); E; E = E->next()) { - VS::get_singleton()->canvas_item_set_draw_index(E->get(),index++); + VS::get_singleton()->canvas_item_set_draw_index(E->get(), index++); } } - quadrant_order_dirty=false; + quadrant_order_dirty = false; } _recompute_rect_cache(); - } void TileMap::_recompute_rect_cache() { - #ifdef DEBUG_ENABLED if (!rect_cache_dirty) return; Rect2 r_total; - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { - + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { Rect2 r; - r.pos=_map_to_world(E->key().x*_get_quadrant_size(), E->key().y*_get_quadrant_size()); - r.expand_to( _map_to_world(E->key().x*_get_quadrant_size()+_get_quadrant_size(), E->key().y*_get_quadrant_size()) ); - r.expand_to( _map_to_world(E->key().x*_get_quadrant_size()+_get_quadrant_size(), E->key().y*_get_quadrant_size()+_get_quadrant_size()) ); - r.expand_to( _map_to_world(E->key().x*_get_quadrant_size(), E->key().y*_get_quadrant_size()+_get_quadrant_size()) ); - if (E==quadrant_map.front()) - r_total=r; + r.pos = _map_to_world(E->key().x * _get_quadrant_size(), E->key().y * _get_quadrant_size()); + r.expand_to(_map_to_world(E->key().x * _get_quadrant_size() + _get_quadrant_size(), E->key().y * _get_quadrant_size())); + r.expand_to(_map_to_world(E->key().x * _get_quadrant_size() + _get_quadrant_size(), E->key().y * _get_quadrant_size() + _get_quadrant_size())); + r.expand_to(_map_to_world(E->key().x * _get_quadrant_size(), E->key().y * _get_quadrant_size() + _get_quadrant_size())); + if (E == quadrant_map.front()) + r_total = r; else - r_total=r_total.merge(r); - + r_total = r_total.merge(r); } - if (r_total==Rect2()) { - rect_cache=Rect2(-10,-10,20,20); + if (r_total == Rect2()) { + rect_cache = Rect2(-10, -10, 20, 20); } else { - rect_cache=r_total.grow(MAX(cell_size.x,cell_size.y)*_get_quadrant_size()); + rect_cache = r_total.grow(MAX(cell_size.x, cell_size.y) * _get_quadrant_size()); } item_rect_changed(); - rect_cache_dirty=false; + rect_cache_dirty = false; #endif - - } -Map::Element *TileMap::_create_quadrant(const PosKey& p_qk) { +Map::Element *TileMap::_create_quadrant(const PosKey &p_qk) { Transform2D xform; //xform.set_origin(Point2(p_qk.x,p_qk.y)*cell_size*quadrant_size); Quadrant q; - q.pos = _map_to_world(p_qk.x*_get_quadrant_size(),p_qk.y*_get_quadrant_size()); - q.pos+=get_cell_draw_offset(); - if (tile_origin==TILE_ORIGIN_CENTER) - q.pos+=cell_size/2; - else if (tile_origin==TILE_ORIGIN_BOTTOM_LEFT) - q.pos.y+=cell_size.y; - - - xform.set_origin( q.pos ); + q.pos = _map_to_world(p_qk.x * _get_quadrant_size(), p_qk.y * _get_quadrant_size()); + q.pos += get_cell_draw_offset(); + if (tile_origin == TILE_ORIGIN_CENTER) + q.pos += cell_size / 2; + else if (tile_origin == TILE_ORIGIN_BOTTOM_LEFT) + q.pos.y += cell_size.y; + + xform.set_origin(q.pos); //q.canvas_item = VisualServer::get_singleton()->canvas_item_create(); - q.body=Physics2DServer::get_singleton()->body_create(use_kinematic?Physics2DServer::BODY_MODE_KINEMATIC:Physics2DServer::BODY_MODE_STATIC); - Physics2DServer::get_singleton()->body_attach_object_instance_ID(q.body,get_instance_ID()); - Physics2DServer::get_singleton()->body_set_layer_mask(q.body,collision_layer); - Physics2DServer::get_singleton()->body_set_collision_mask(q.body,collision_mask); - Physics2DServer::get_singleton()->body_set_param(q.body,Physics2DServer::BODY_PARAM_FRICTION,friction); - Physics2DServer::get_singleton()->body_set_param(q.body,Physics2DServer::BODY_PARAM_BOUNCE,bounce); + q.body = Physics2DServer::get_singleton()->body_create(use_kinematic ? Physics2DServer::BODY_MODE_KINEMATIC : Physics2DServer::BODY_MODE_STATIC); + Physics2DServer::get_singleton()->body_attach_object_instance_ID(q.body, get_instance_ID()); + Physics2DServer::get_singleton()->body_set_layer_mask(q.body, collision_layer); + Physics2DServer::get_singleton()->body_set_collision_mask(q.body, collision_mask); + Physics2DServer::get_singleton()->body_set_param(q.body, Physics2DServer::BODY_PARAM_FRICTION, friction); + Physics2DServer::get_singleton()->body_set_param(q.body, Physics2DServer::BODY_PARAM_BOUNCE, bounce); if (is_inside_tree()) { xform = get_global_transform() * xform; RID space = get_world_2d()->get_space(); - Physics2DServer::get_singleton()->body_set_space(q.body,space); + Physics2DServer::get_singleton()->body_set_space(q.body, space); } - Physics2DServer::get_singleton()->body_set_state(q.body,Physics2DServer::BODY_STATE_TRANSFORM,xform); + Physics2DServer::get_singleton()->body_set_state(q.body, Physics2DServer::BODY_STATE_TRANSFORM, xform); - rect_cache_dirty=true; - quadrant_order_dirty=true; - return quadrant_map.insert(p_qk,q); + rect_cache_dirty = true; + quadrant_order_dirty = true; + return quadrant_map.insert(p_qk, q); } -void TileMap::_erase_quadrant(Map::Element *Q) { +void TileMap::_erase_quadrant(Map::Element *Q) { - Quadrant &q=Q->get(); + Quadrant &q = Q->get(); Physics2DServer::get_singleton()->free(q.body); - for (List::Element *E=q.canvas_items.front();E;E=E->next()) { + for (List::Element *E = q.canvas_items.front(); E; E = E->next()) { VisualServer::get_singleton()->free(E->get()); } @@ -648,58 +617,58 @@ void TileMap::_erase_quadrant(Map::Element *Q) { dirty_quadrant_list.remove(&q.dirty_list); if (navigation) { - for(Map::Element *E=q.navpoly_ids.front();E;E=E->next()) { + for (Map::Element *E = q.navpoly_ids.front(); E; E = E->next()) { navigation->navpoly_remove(E->get().id); } q.navpoly_ids.clear(); } - for(Map::Element *E=q.occluder_instances.front();E;E=E->next()) { + for (Map::Element *E = q.occluder_instances.front(); E; E = E->next()) { VS::get_singleton()->free(E->get().id); } q.occluder_instances.clear(); quadrant_map.erase(Q); - rect_cache_dirty=true; + rect_cache_dirty = true; } -void TileMap::_make_quadrant_dirty(Map::Element *Q) { +void TileMap::_make_quadrant_dirty(Map::Element *Q) { - Quadrant &q=Q->get(); + Quadrant &q = Q->get(); if (!q.dirty_list.in_list()) dirty_quadrant_list.add(&q.dirty_list); if (pending_update) return; - pending_update=true; + pending_update = true; if (!is_inside_tree()) return; call_deferred("_update_dirty_quadrants"); } -void TileMap::set_cellv(const Vector2& p_pos,int p_tile,bool p_flip_x,bool p_flip_y,bool p_transpose) { +void TileMap::set_cellv(const Vector2 &p_pos, int p_tile, bool p_flip_x, bool p_flip_y, bool p_transpose) { - set_cell(p_pos.x,p_pos.y,p_tile,p_flip_x,p_flip_y,p_transpose); + set_cell(p_pos.x, p_pos.y, p_tile, p_flip_x, p_flip_y, p_transpose); } -void TileMap::set_cell(int p_x,int p_y,int p_tile,bool p_flip_x,bool p_flip_y,bool p_transpose) { +void TileMap::set_cell(int p_x, int p_y, int p_tile, bool p_flip_x, bool p_flip_y, bool p_transpose) { - PosKey pk(p_x,p_y); + PosKey pk(p_x, p_y); - Map::Element *E=tile_map.find(pk); - if (!E && p_tile==INVALID_CELL) + Map::Element *E = tile_map.find(pk); + if (!E && p_tile == INVALID_CELL) return; //nothing to do - PosKey qk(p_x/_get_quadrant_size(),p_y/_get_quadrant_size()); - if (p_tile==INVALID_CELL) { + PosKey qk(p_x / _get_quadrant_size(), p_y / _get_quadrant_size()); + if (p_tile == INVALID_CELL) { //erase existing tile_map.erase(pk); - Map::Element *Q = quadrant_map.find(qk); + Map::Element *Q = quadrant_map.find(qk); ERR_FAIL_COND(!Q); - Quadrant &q=Q->get(); + Quadrant &q = Q->get(); q.cells.erase(pk); - if (q.cells.size()==0) + if (q.cells.size() == 0) _erase_quadrant(Q); else _make_quadrant_dirty(Q); @@ -707,79 +676,75 @@ void TileMap::set_cell(int p_x,int p_y,int p_tile,bool p_flip_x,bool p_flip_y,bo return; } - Map::Element *Q = quadrant_map.find(qk); + Map::Element *Q = quadrant_map.find(qk); if (!E) { - E=tile_map.insert(pk,Cell()); + E = tile_map.insert(pk, Cell()); if (!Q) { - Q=_create_quadrant(qk); + Q = _create_quadrant(qk); } - Quadrant &q=Q->get(); + Quadrant &q = Q->get(); q.cells.insert(pk); } else { ERR_FAIL_COND(!Q); // quadrant should exist... - if (E->get().id==p_tile && E->get().flip_h==p_flip_x && E->get().flip_v==p_flip_y && E->get().transpose==p_transpose) + if (E->get().id == p_tile && E->get().flip_h == p_flip_x && E->get().flip_v == p_flip_y && E->get().transpose == p_transpose) return; //nothing changed - } - Cell &c = E->get(); - c.id=p_tile; - c.flip_h=p_flip_x; - c.flip_v=p_flip_y; - c.transpose=p_transpose; + c.id = p_tile; + c.flip_h = p_flip_x; + c.flip_v = p_flip_y; + c.transpose = p_transpose; _make_quadrant_dirty(Q); - used_size_cache_dirty=true; - + used_size_cache_dirty = true; } -int TileMap::get_cellv(const Vector2& p_pos) const { - return get_cell(p_pos.x,p_pos.y); +int TileMap::get_cellv(const Vector2 &p_pos) const { + return get_cell(p_pos.x, p_pos.y); } -int TileMap::get_cell(int p_x,int p_y) const { +int TileMap::get_cell(int p_x, int p_y) const { - PosKey pk(p_x,p_y); + PosKey pk(p_x, p_y); - const Map::Element *E=tile_map.find(pk); + const Map::Element *E = tile_map.find(pk); if (!E) return INVALID_CELL; return E->get().id; - } -bool TileMap::is_cell_x_flipped(int p_x,int p_y) const { +bool TileMap::is_cell_x_flipped(int p_x, int p_y) const { - PosKey pk(p_x,p_y); + PosKey pk(p_x, p_y); - const Map::Element *E=tile_map.find(pk); + const Map::Element *E = tile_map.find(pk); if (!E) return false; return E->get().flip_h; } -bool TileMap::is_cell_y_flipped(int p_x,int p_y) const { +bool TileMap::is_cell_y_flipped(int p_x, int p_y) const { - PosKey pk(p_x,p_y); + PosKey pk(p_x, p_y); - const Map::Element *E=tile_map.find(pk); + const Map::Element *E = tile_map.find(pk); if (!E) return false; return E->get().flip_v; } -bool TileMap::is_cell_transposed(int p_x,int p_y) const { +bool TileMap::is_cell_transposed(int p_x, int p_y) const { - PosKey pk(p_x,p_y); + PosKey pk(p_x, p_y); - const Map::Element *E=tile_map.find(pk); + const Map::Element *E = tile_map.find(pk); if (!E) return false; @@ -787,34 +752,29 @@ bool TileMap::is_cell_transposed(int p_x,int p_y) const { return E->get().transpose; } - void TileMap::_recreate_quadrants() { _clear_quadrants(); - for (Map::Element *E=tile_map.front();E;E=E->next()) { + for (Map::Element *E = tile_map.front(); E; E = E->next()) { - PosKey qk(E->key().x/_get_quadrant_size(),E->key().y/_get_quadrant_size()); + PosKey qk(E->key().x / _get_quadrant_size(), E->key().y / _get_quadrant_size()); - Map::Element *Q=quadrant_map.find(qk); + Map::Element *Q = quadrant_map.find(qk); if (!Q) { - Q=_create_quadrant(qk); + Q = _create_quadrant(qk); dirty_quadrant_list.add(&Q->get().dirty_list); } Q->get().cells.insert(E->key()); _make_quadrant_dirty(Q); } - - - } - void TileMap::_clear_quadrants() { while (quadrant_map.size()) { - _erase_quadrant( quadrant_map.front() ); + _erase_quadrant(quadrant_map.front()); } } @@ -822,107 +782,101 @@ void TileMap::clear() { _clear_quadrants(); tile_map.clear(); - used_size_cache_dirty=true; + used_size_cache_dirty = true; } -void TileMap::_set_tile_data(const PoolVector& p_data) { +void TileMap::_set_tile_data(const PoolVector &p_data) { - int c=p_data.size(); + int c = p_data.size(); PoolVector::Read r = p_data.read(); + for (int i = 0; i < c; i += 2) { - for(int i=0;i4000 || y>4000) continue; */ - set_cell(x,y,v,flip_h,flip_v,transpose); - + set_cell(x, y, v, flip_h, flip_v, transpose); } - } PoolVector TileMap::_get_tile_data() const { PoolVector data; - data.resize(tile_map.size()*2); + data.resize(tile_map.size() * 2); PoolVector::Write w = data.write(); - int idx=0; - for(const Map::Element *E=tile_map.front();E;E=E->next()) { + int idx = 0; + for (const Map::Element *E = tile_map.front(); E; E = E->next()) { - uint8_t *ptr = (uint8_t*)&w[idx]; - encode_uint16(E->key().x,&ptr[0]); - encode_uint16(E->key().y,&ptr[2]); + uint8_t *ptr = (uint8_t *)&w[idx]; + encode_uint16(E->key().x, &ptr[0]); + encode_uint16(E->key().y, &ptr[2]); uint32_t val = E->get().id; if (E->get().flip_h) - val|=(1<<29); + val |= (1 << 29); if (E->get().flip_v) - val|=(1<<30); + val |= (1 << 30); if (E->get().transpose) - val|=(1<<31); + val |= (1 << 31); - encode_uint32(val,&ptr[4]); - idx+=2; + encode_uint32(val, &ptr[4]); + idx += 2; } - w = PoolVector::Write(); return data; - } Rect2 TileMap::get_item_rect() const { - const_cast(this)->_update_dirty_quadrants(); + const_cast(this)->_update_dirty_quadrants(); return rect_cache; } void TileMap::set_collision_layer(uint32_t p_layer) { - collision_layer=p_layer; - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + collision_layer = p_layer; + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - Quadrant &q=E->get(); - Physics2DServer::get_singleton()->body_set_layer_mask(q.body,collision_layer); + Quadrant &q = E->get(); + Physics2DServer::get_singleton()->body_set_layer_mask(q.body, collision_layer); } } void TileMap::set_collision_mask(uint32_t p_mask) { - collision_mask=p_mask; - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + collision_mask = p_mask; + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - Quadrant &q=E->get(); - Physics2DServer::get_singleton()->body_set_collision_mask(q.body,collision_mask); + Quadrant &q = E->get(); + Physics2DServer::get_singleton()->body_set_collision_mask(q.body, collision_mask); } } -bool TileMap::get_collision_use_kinematic() const{ +bool TileMap::get_collision_use_kinematic() const { return use_kinematic; } @@ -930,42 +884,39 @@ bool TileMap::get_collision_use_kinematic() const{ void TileMap::set_collision_use_kinematic(bool p_use_kinematic) { _clear_quadrants(); - use_kinematic=p_use_kinematic; + use_kinematic = p_use_kinematic; _recreate_quadrants(); } void TileMap::set_collision_friction(float p_friction) { - friction=p_friction; - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + friction = p_friction; + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - Quadrant &q=E->get(); - Physics2DServer::get_singleton()->body_set_param(q.body,Physics2DServer::BODY_PARAM_FRICTION,p_friction); + Quadrant &q = E->get(); + Physics2DServer::get_singleton()->body_set_param(q.body, Physics2DServer::BODY_PARAM_FRICTION, p_friction); } - } -float TileMap::get_collision_friction() const{ +float TileMap::get_collision_friction() const { return friction; } -void TileMap::set_collision_bounce(float p_bounce){ +void TileMap::set_collision_bounce(float p_bounce) { - bounce=p_bounce; - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + bounce = p_bounce; + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - Quadrant &q=E->get(); - Physics2DServer::get_singleton()->body_set_param(q.body,Physics2DServer::BODY_PARAM_BOUNCE,p_bounce); + Quadrant &q = E->get(); + Physics2DServer::get_singleton()->body_set_param(q.body, Physics2DServer::BODY_PARAM_BOUNCE, p_bounce); } - } -float TileMap::get_collision_bounce() const{ +float TileMap::get_collision_bounce() const { return bounce; } - uint32_t TileMap::get_collision_layer() const { return collision_layer; @@ -979,7 +930,7 @@ uint32_t TileMap::get_collision_mask() const { void TileMap::set_mode(Mode p_mode) { _clear_quadrants(); - mode=p_mode; + mode = p_mode; _recreate_quadrants(); emit_signal("settings_changed"); } @@ -991,7 +942,7 @@ TileMap::Mode TileMap::get_mode() const { void TileMap::set_half_offset(HalfOffset p_half_offset) { _clear_quadrants(); - half_offset=p_half_offset; + half_offset = p_half_offset; _recreate_quadrants(); emit_signal("settings_changed"); } @@ -999,20 +950,19 @@ void TileMap::set_half_offset(HalfOffset p_half_offset) { void TileMap::set_tile_origin(TileOrigin p_tile_origin) { _clear_quadrants(); - tile_origin=p_tile_origin; + tile_origin = p_tile_origin; _recreate_quadrants(); emit_signal("settings_changed"); } -TileMap::TileOrigin TileMap::get_tile_origin() const{ +TileMap::TileOrigin TileMap::get_tile_origin() const { return tile_origin; } - Vector2 TileMap::get_cell_draw_offset() const { - switch(mode) { + switch (mode) { case MODE_SQUARE: { @@ -1020,22 +970,21 @@ Vector2 TileMap::get_cell_draw_offset() const { } break; case MODE_ISOMETRIC: { - return Vector2(-cell_size.x*0.5,0); + return Vector2(-cell_size.x * 0.5, 0); } break; case MODE_CUSTOM: { Vector2 min; - min.x = MIN(custom_transform[0].x,min.x); - min.y = MIN(custom_transform[0].y,min.y); - min.x = MIN(custom_transform[1].x,min.x); - min.y = MIN(custom_transform[1].y,min.y); + min.x = MIN(custom_transform[0].x, min.x); + min.y = MIN(custom_transform[0].y, min.y); + min.x = MIN(custom_transform[1].x, min.x); + min.y = MIN(custom_transform[1].y, min.y); return min; } break; } return Vector2(); - } TileMap::HalfOffset TileMap::get_half_offset() const { @@ -1044,13 +993,13 @@ TileMap::HalfOffset TileMap::get_half_offset() const { Transform2D TileMap::get_cell_transform() const { - switch(mode) { + switch (mode) { case MODE_SQUARE: { Transform2D m; - m[0]*=cell_size.x; - m[1]*=cell_size.y; + m[0] *= cell_size.x; + m[1] *= cell_size.y; return m; } break; case MODE_ISOMETRIC: { @@ -1058,8 +1007,8 @@ Transform2D TileMap::get_cell_transform() const { //isometric only makes sense when y is positive in both x and y vectors, otherwise //the drawing of tiles will overlap Transform2D m; - m[0]=Vector2(cell_size.x*0.5,cell_size.y*0.5); - m[1]=Vector2(-cell_size.x*0.5,cell_size.y*0.5); + m[0] = Vector2(cell_size.x * 0.5, cell_size.y * 0.5); + m[1] = Vector2(-cell_size.x * 0.5, cell_size.y * 0.5); return m; } break; @@ -1072,35 +1021,34 @@ Transform2D TileMap::get_cell_transform() const { return Transform2D(); } -void TileMap::set_custom_transform(const Transform2D& p_xform) { +void TileMap::set_custom_transform(const Transform2D &p_xform) { _clear_quadrants(); - custom_transform=p_xform; + custom_transform = p_xform; _recreate_quadrants(); emit_signal("settings_changed"); - } -Transform2D TileMap::get_custom_transform() const{ +Transform2D TileMap::get_custom_transform() const { return custom_transform; } -Vector2 TileMap::_map_to_world(int x,int y,bool p_ignore_ofs) const { +Vector2 TileMap::_map_to_world(int x, int y, bool p_ignore_ofs) const { - Vector2 ret = get_cell_transform().xform(Vector2(x,y)); + Vector2 ret = get_cell_transform().xform(Vector2(x, y)); if (!p_ignore_ofs) { - switch(half_offset) { + switch (half_offset) { case HALF_OFFSET_X: { - if (ABS(y)&1) { + if (ABS(y) & 1) { - ret+=get_cell_transform()[0]*0.5; + ret += get_cell_transform()[0] * 0.5; } } break; case HALF_OFFSET_Y: { - if (ABS(x)&1) { - ret+=get_cell_transform()[1]*0.5; + if (ABS(x) & 1) { + ret += get_cell_transform()[1] * 0.5; } } break; default: {} @@ -1108,25 +1056,24 @@ Vector2 TileMap::_map_to_world(int x,int y,bool p_ignore_ofs) const { } return ret; } -Vector2 TileMap::map_to_world(const Vector2& p_pos,bool p_ignore_ofs) const { +Vector2 TileMap::map_to_world(const Vector2 &p_pos, bool p_ignore_ofs) const { - return _map_to_world(p_pos.x,p_pos.y,p_ignore_ofs); + return _map_to_world(p_pos.x, p_pos.y, p_ignore_ofs); } -Vector2 TileMap::world_to_map(const Vector2& p_pos) const{ +Vector2 TileMap::world_to_map(const Vector2 &p_pos) const { Vector2 ret = get_cell_transform().affine_inverse().xform(p_pos); - - switch(half_offset) { + switch (half_offset) { case HALF_OFFSET_X: { - if ( ret.y > 0 ? int(ret.y)&1 : (int(ret.y)-1)&1 ) { - ret.x-=0.5; + if (ret.y > 0 ? int(ret.y) & 1 : (int(ret.y) - 1) & 1) { + ret.x -= 0.5; } } break; case HALF_OFFSET_Y: { - if ( ret.x > 0 ? int(ret.x)&1 : (int(ret.x)-1)&1) { - ret.y-=0.5; + if (ret.x > 0 ? int(ret.x) & 1 : (int(ret.x) - 1) & 1) { + ret.y -= 0.5; } } break; default: {} @@ -1138,11 +1085,10 @@ Vector2 TileMap::world_to_map(const Vector2& p_pos) const{ void TileMap::set_y_sort_mode(bool p_enable) { _clear_quadrants(); - y_sort_mode=p_enable; - VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(),y_sort_mode); + y_sort_mode = p_enable; + VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(), y_sort_mode); _recreate_quadrants(); emit_signal("settings_changed"); - } bool TileMap::is_y_sort_mode_enabled() const { @@ -1154,11 +1100,11 @@ Array TileMap::get_used_cells() const { Array a; a.resize(tile_map.size()); - int i=0; - for (Map::Element *E=tile_map.front();E;E=E->next()) { + int i = 0; + for (Map::Element *E = tile_map.front(); E; E = E->next()) { - Vector2 p (E->key().x,E->key().y); - a[i++]=p; + Vector2 p(E->key().x, E->key().y); + a[i++] = p; } return a; @@ -1167,14 +1113,14 @@ Array TileMap::get_used_cells() const { Rect2 TileMap::get_used_rect() { // Not const because of cache if (used_size_cache_dirty) { - if(tile_map.size() > 0) { + if (tile_map.size() > 0) { used_size_cache = Rect2(tile_map.front()->key().x, tile_map.front()->key().y, 0, 0); - for (Map::Element *E=tile_map.front();E;E=E->next()) { + for (Map::Element *E = tile_map.front(); E; E = E->next()) { used_size_cache.expand_to(Vector2(E->key().x, E->key().y)); } - used_size_cache.size += Vector2(1,1); + used_size_cache.size += Vector2(1, 1); } else { used_size_cache = Rect2(); } @@ -1185,19 +1131,18 @@ Rect2 TileMap::get_used_rect() { // Not const because of cache return used_size_cache; } - void TileMap::set_occluder_light_mask(int p_mask) { - occluder_light_mask=p_mask; - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + occluder_light_mask = p_mask; + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - for (Map::Element *F=E->get().occluder_instances.front();F;F=F->next()) { - VisualServer::get_singleton()->canvas_light_occluder_set_light_mask(F->get().id,occluder_light_mask); + for (Map::Element *F = E->get().occluder_instances.front(); F; F = F->next()) { + VisualServer::get_singleton()->canvas_light_occluder_set_light_mask(F->get().id, occluder_light_mask); } } } -int TileMap::get_occluder_light_mask() const{ +int TileMap::get_occluder_light_mask() const { return occluder_light_mask; } @@ -1205,154 +1150,150 @@ int TileMap::get_occluder_light_mask() const{ void TileMap::set_light_mask(int p_light_mask) { CanvasItem::set_light_mask(p_light_mask); - for (Map::Element *E=quadrant_map.front();E;E=E->next()) { + for (Map::Element *E = quadrant_map.front(); E; E = E->next()) { - for (List::Element *F=E->get().canvas_items.front();F;F=F->next()) { - VisualServer::get_singleton()->canvas_item_set_light_mask(F->get(),get_light_mask()); + for (List::Element *F = E->get().canvas_items.front(); F; F = F->next()) { + VisualServer::get_singleton()->canvas_item_set_light_mask(F->get(), get_light_mask()); } } } void TileMap::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_tileset", "tileset:TileSet"), &TileMap::set_tileset); + ClassDB::bind_method(D_METHOD("get_tileset:TileSet"), &TileMap::get_tileset); - ClassDB::bind_method(D_METHOD("set_tileset","tileset:TileSet"),&TileMap::set_tileset); - ClassDB::bind_method(D_METHOD("get_tileset:TileSet"),&TileMap::get_tileset); - - ClassDB::bind_method(D_METHOD("set_mode","mode"),&TileMap::set_mode); - ClassDB::bind_method(D_METHOD("get_mode"),&TileMap::get_mode); + ClassDB::bind_method(D_METHOD("set_mode", "mode"), &TileMap::set_mode); + ClassDB::bind_method(D_METHOD("get_mode"), &TileMap::get_mode); - ClassDB::bind_method(D_METHOD("set_half_offset","half_offset"),&TileMap::set_half_offset); - ClassDB::bind_method(D_METHOD("get_half_offset"),&TileMap::get_half_offset); + ClassDB::bind_method(D_METHOD("set_half_offset", "half_offset"), &TileMap::set_half_offset); + ClassDB::bind_method(D_METHOD("get_half_offset"), &TileMap::get_half_offset); - ClassDB::bind_method(D_METHOD("set_custom_transform","custom_transform"),&TileMap::set_custom_transform); - ClassDB::bind_method(D_METHOD("get_custom_transform"),&TileMap::get_custom_transform); + ClassDB::bind_method(D_METHOD("set_custom_transform", "custom_transform"), &TileMap::set_custom_transform); + ClassDB::bind_method(D_METHOD("get_custom_transform"), &TileMap::get_custom_transform); - ClassDB::bind_method(D_METHOD("set_cell_size","size"),&TileMap::set_cell_size); - ClassDB::bind_method(D_METHOD("get_cell_size"),&TileMap::get_cell_size); + ClassDB::bind_method(D_METHOD("set_cell_size", "size"), &TileMap::set_cell_size); + ClassDB::bind_method(D_METHOD("get_cell_size"), &TileMap::get_cell_size); - ClassDB::bind_method(D_METHOD("_set_old_cell_size","size"),&TileMap::_set_old_cell_size); - ClassDB::bind_method(D_METHOD("_get_old_cell_size"),&TileMap::_get_old_cell_size); + ClassDB::bind_method(D_METHOD("_set_old_cell_size", "size"), &TileMap::_set_old_cell_size); + ClassDB::bind_method(D_METHOD("_get_old_cell_size"), &TileMap::_get_old_cell_size); - ClassDB::bind_method(D_METHOD("set_quadrant_size","size"),&TileMap::set_quadrant_size); - ClassDB::bind_method(D_METHOD("get_quadrant_size"),&TileMap::get_quadrant_size); + ClassDB::bind_method(D_METHOD("set_quadrant_size", "size"), &TileMap::set_quadrant_size); + ClassDB::bind_method(D_METHOD("get_quadrant_size"), &TileMap::get_quadrant_size); - ClassDB::bind_method(D_METHOD("set_tile_origin","origin"),&TileMap::set_tile_origin); - ClassDB::bind_method(D_METHOD("get_tile_origin"),&TileMap::get_tile_origin); + ClassDB::bind_method(D_METHOD("set_tile_origin", "origin"), &TileMap::set_tile_origin); + ClassDB::bind_method(D_METHOD("get_tile_origin"), &TileMap::get_tile_origin); - ClassDB::bind_method(D_METHOD("set_center_x","enable"),&TileMap::set_center_x); - ClassDB::bind_method(D_METHOD("get_center_x"),&TileMap::get_center_x); + ClassDB::bind_method(D_METHOD("set_center_x", "enable"), &TileMap::set_center_x); + ClassDB::bind_method(D_METHOD("get_center_x"), &TileMap::get_center_x); - ClassDB::bind_method(D_METHOD("set_center_y","enable"),&TileMap::set_center_y); - ClassDB::bind_method(D_METHOD("get_center_y"),&TileMap::get_center_y); + ClassDB::bind_method(D_METHOD("set_center_y", "enable"), &TileMap::set_center_y); + ClassDB::bind_method(D_METHOD("get_center_y"), &TileMap::get_center_y); - ClassDB::bind_method(D_METHOD("set_y_sort_mode","enable"),&TileMap::set_y_sort_mode); - ClassDB::bind_method(D_METHOD("is_y_sort_mode_enabled"),&TileMap::is_y_sort_mode_enabled); + ClassDB::bind_method(D_METHOD("set_y_sort_mode", "enable"), &TileMap::set_y_sort_mode); + ClassDB::bind_method(D_METHOD("is_y_sort_mode_enabled"), &TileMap::is_y_sort_mode_enabled); - ClassDB::bind_method(D_METHOD("set_collision_use_kinematic","use_kinematic"),&TileMap::set_collision_use_kinematic); - ClassDB::bind_method(D_METHOD("get_collision_use_kinematic"),&TileMap::get_collision_use_kinematic); + ClassDB::bind_method(D_METHOD("set_collision_use_kinematic", "use_kinematic"), &TileMap::set_collision_use_kinematic); + ClassDB::bind_method(D_METHOD("get_collision_use_kinematic"), &TileMap::get_collision_use_kinematic); - ClassDB::bind_method(D_METHOD("set_collision_layer","mask"),&TileMap::set_collision_layer); - ClassDB::bind_method(D_METHOD("get_collision_layer"),&TileMap::get_collision_layer); + ClassDB::bind_method(D_METHOD("set_collision_layer", "mask"), &TileMap::set_collision_layer); + ClassDB::bind_method(D_METHOD("get_collision_layer"), &TileMap::get_collision_layer); - ClassDB::bind_method(D_METHOD("set_collision_mask","mask"),&TileMap::set_collision_mask); - ClassDB::bind_method(D_METHOD("get_collision_mask"),&TileMap::get_collision_mask); + ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &TileMap::set_collision_mask); + ClassDB::bind_method(D_METHOD("get_collision_mask"), &TileMap::get_collision_mask); - ClassDB::bind_method(D_METHOD("set_collision_friction","value"),&TileMap::set_collision_friction); - ClassDB::bind_method(D_METHOD("get_collision_friction"),&TileMap::get_collision_friction); + ClassDB::bind_method(D_METHOD("set_collision_friction", "value"), &TileMap::set_collision_friction); + ClassDB::bind_method(D_METHOD("get_collision_friction"), &TileMap::get_collision_friction); - ClassDB::bind_method(D_METHOD("set_collision_bounce","value"),&TileMap::set_collision_bounce); - ClassDB::bind_method(D_METHOD("get_collision_bounce"),&TileMap::get_collision_bounce); + ClassDB::bind_method(D_METHOD("set_collision_bounce", "value"), &TileMap::set_collision_bounce); + ClassDB::bind_method(D_METHOD("get_collision_bounce"), &TileMap::get_collision_bounce); - ClassDB::bind_method(D_METHOD("set_occluder_light_mask","mask"),&TileMap::set_occluder_light_mask); - ClassDB::bind_method(D_METHOD("get_occluder_light_mask"),&TileMap::get_occluder_light_mask); + ClassDB::bind_method(D_METHOD("set_occluder_light_mask", "mask"), &TileMap::set_occluder_light_mask); + ClassDB::bind_method(D_METHOD("get_occluder_light_mask"), &TileMap::get_occluder_light_mask); - ClassDB::bind_method(D_METHOD("set_cell","x","y","tile","flip_x","flip_y","transpose"),&TileMap::set_cell,DEFVAL(false),DEFVAL(false),DEFVAL(false)); - ClassDB::bind_method(D_METHOD("set_cellv","pos","tile","flip_x","flip_y","transpose"),&TileMap::set_cellv,DEFVAL(false),DEFVAL(false),DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_cell","x","y"),&TileMap::get_cell); - ClassDB::bind_method(D_METHOD("get_cellv","pos"),&TileMap::get_cellv); - ClassDB::bind_method(D_METHOD("is_cell_x_flipped","x","y"),&TileMap::is_cell_x_flipped); - ClassDB::bind_method(D_METHOD("is_cell_y_flipped","x","y"),&TileMap::is_cell_y_flipped); - ClassDB::bind_method(D_METHOD("is_cell_transposed","x","y"),&TileMap::is_cell_transposed); + ClassDB::bind_method(D_METHOD("set_cell", "x", "y", "tile", "flip_x", "flip_y", "transpose"), &TileMap::set_cell, DEFVAL(false), DEFVAL(false), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("set_cellv", "pos", "tile", "flip_x", "flip_y", "transpose"), &TileMap::set_cellv, DEFVAL(false), DEFVAL(false), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_cell", "x", "y"), &TileMap::get_cell); + ClassDB::bind_method(D_METHOD("get_cellv", "pos"), &TileMap::get_cellv); + ClassDB::bind_method(D_METHOD("is_cell_x_flipped", "x", "y"), &TileMap::is_cell_x_flipped); + ClassDB::bind_method(D_METHOD("is_cell_y_flipped", "x", "y"), &TileMap::is_cell_y_flipped); + ClassDB::bind_method(D_METHOD("is_cell_transposed", "x", "y"), &TileMap::is_cell_transposed); - ClassDB::bind_method(D_METHOD("clear"),&TileMap::clear); + ClassDB::bind_method(D_METHOD("clear"), &TileMap::clear); - ClassDB::bind_method(D_METHOD("get_used_cells"),&TileMap::get_used_cells); - ClassDB::bind_method(D_METHOD("get_used_rect"),&TileMap::get_used_rect); + ClassDB::bind_method(D_METHOD("get_used_cells"), &TileMap::get_used_cells); + ClassDB::bind_method(D_METHOD("get_used_rect"), &TileMap::get_used_rect); - ClassDB::bind_method(D_METHOD("map_to_world","mappos","ignore_half_ofs"),&TileMap::map_to_world,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("world_to_map","worldpos"),&TileMap::world_to_map); + ClassDB::bind_method(D_METHOD("map_to_world", "mappos", "ignore_half_ofs"), &TileMap::map_to_world, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("world_to_map", "worldpos"), &TileMap::world_to_map); - ClassDB::bind_method(D_METHOD("_clear_quadrants"),&TileMap::_clear_quadrants); - ClassDB::bind_method(D_METHOD("_recreate_quadrants"),&TileMap::_recreate_quadrants); - ClassDB::bind_method(D_METHOD("_update_dirty_quadrants"),&TileMap::_update_dirty_quadrants); + ClassDB::bind_method(D_METHOD("_clear_quadrants"), &TileMap::_clear_quadrants); + ClassDB::bind_method(D_METHOD("_recreate_quadrants"), &TileMap::_recreate_quadrants); + ClassDB::bind_method(D_METHOD("_update_dirty_quadrants"), &TileMap::_update_dirty_quadrants); - ClassDB::bind_method(D_METHOD("_set_tile_data"),&TileMap::_set_tile_data); - ClassDB::bind_method(D_METHOD("_get_tile_data"),&TileMap::_get_tile_data); + ClassDB::bind_method(D_METHOD("_set_tile_data"), &TileMap::_set_tile_data); + ClassDB::bind_method(D_METHOD("_get_tile_data"), &TileMap::_get_tile_data); - ADD_PROPERTY( PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Square,Isometric,Custom"),"set_mode","get_mode"); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"tile_set",PROPERTY_HINT_RESOURCE_TYPE,"TileSet"),"set_tileset","get_tileset"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Square,Isometric,Custom"), "set_mode", "get_mode"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tile_set", PROPERTY_HINT_RESOURCE_TYPE, "TileSet"), "set_tileset", "get_tileset"); - ADD_GROUP("Cell","cell_"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"cell_size",PROPERTY_HINT_RANGE,"1,8192,1"),"set_cell_size","get_cell_size"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"cell_quadrant_size",PROPERTY_HINT_RANGE,"1,128,1"),"set_quadrant_size","get_quadrant_size"); - ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM2D,"cell_custom_transform"),"set_custom_transform","get_custom_transform"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"cell_half_offset",PROPERTY_HINT_ENUM,"Offset X,Offset Y,Disabled"),"set_half_offset","get_half_offset"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"cell_tile_origin",PROPERTY_HINT_ENUM,"Top Left,Center,Bottom Left"),"set_tile_origin","get_tile_origin"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"cell_y_sort"),"set_y_sort_mode","is_y_sort_mode_enabled"); + ADD_GROUP("Cell", "cell_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "cell_size", PROPERTY_HINT_RANGE, "1,8192,1"), "set_cell_size", "get_cell_size"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_quadrant_size", PROPERTY_HINT_RANGE, "1,128,1"), "set_quadrant_size", "get_quadrant_size"); + ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "cell_custom_transform"), "set_custom_transform", "get_custom_transform"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_half_offset", PROPERTY_HINT_ENUM, "Offset X,Offset Y,Disabled"), "set_half_offset", "get_half_offset"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_tile_origin", PROPERTY_HINT_ENUM, "Top Left,Center,Bottom Left"), "set_tile_origin", "get_tile_origin"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cell_y_sort"), "set_y_sort_mode", "is_y_sort_mode_enabled"); - ADD_GROUP("Collision","collision_"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collision_use_kinematic",PROPERTY_HINT_NONE,""),"set_collision_use_kinematic","get_collision_use_kinematic"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"collision_friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_collision_friction","get_collision_friction"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"collision_bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_collision_bounce","get_collision_bounce"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"collision_layers",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_collision_layer","get_collision_layer"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"collision_mask",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_collision_mask","get_collision_mask"); + ADD_GROUP("Collision", "collision_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision_use_kinematic", PROPERTY_HINT_NONE, ""), "set_collision_use_kinematic", "get_collision_use_kinematic"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "collision_friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_collision_friction", "get_collision_friction"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "collision_bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_collision_bounce", "get_collision_bounce"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_layer", "get_collision_layer"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_mask", "get_collision_mask"); - ADD_GROUP("Occluder","occluder_"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"occluder_light_mask",PROPERTY_HINT_LAYERS_2D_RENDER),"set_occluder_light_mask","get_occluder_light_mask"); - ADD_GROUP("",""); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"tile_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_tile_data","_get_tile_data"); + ADD_GROUP("Occluder", "occluder_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "occluder_light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_occluder_light_mask", "get_occluder_light_mask"); + ADD_GROUP("", ""); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tile_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_tile_data", "_get_tile_data"); ADD_SIGNAL(MethodInfo("settings_changed")); - BIND_CONSTANT( INVALID_CELL ); - BIND_CONSTANT( MODE_SQUARE ); - BIND_CONSTANT( MODE_ISOMETRIC ); - BIND_CONSTANT( MODE_CUSTOM ); - BIND_CONSTANT( HALF_OFFSET_X ); - BIND_CONSTANT( HALF_OFFSET_Y ); - BIND_CONSTANT( HALF_OFFSET_DISABLED ); - BIND_CONSTANT( TILE_ORIGIN_TOP_LEFT ); - BIND_CONSTANT( TILE_ORIGIN_CENTER ); - BIND_CONSTANT( TILE_ORIGIN_BOTTOM_LEFT ); - + BIND_CONSTANT(INVALID_CELL); + BIND_CONSTANT(MODE_SQUARE); + BIND_CONSTANT(MODE_ISOMETRIC); + BIND_CONSTANT(MODE_CUSTOM); + BIND_CONSTANT(HALF_OFFSET_X); + BIND_CONSTANT(HALF_OFFSET_Y); + BIND_CONSTANT(HALF_OFFSET_DISABLED); + BIND_CONSTANT(TILE_ORIGIN_TOP_LEFT); + BIND_CONSTANT(TILE_ORIGIN_CENTER); + BIND_CONSTANT(TILE_ORIGIN_BOTTOM_LEFT); } TileMap::TileMap() { - - - rect_cache_dirty=true; - used_size_cache_dirty=true; - pending_update=false; - quadrant_order_dirty=false; - quadrant_size=16; - cell_size=Size2(64,64); - center_x=false; - center_y=false; - collision_layer=1; - collision_mask=1; - friction=1; - bounce=0; - mode=MODE_SQUARE; - half_offset=HALF_OFFSET_DISABLED; - use_kinematic=false; - navigation=NULL; - y_sort_mode=false; - occluder_light_mask=1; - - fp_adjust=0.00001; - tile_origin=TILE_ORIGIN_TOP_LEFT; + rect_cache_dirty = true; + used_size_cache_dirty = true; + pending_update = false; + quadrant_order_dirty = false; + quadrant_size = 16; + cell_size = Size2(64, 64); + center_x = false; + center_y = false; + collision_layer = 1; + collision_mask = 1; + friction = 1; + bounce = 0; + mode = MODE_SQUARE; + half_offset = HALF_OFFSET_DISABLED; + use_kinematic = false; + navigation = NULL; + y_sort_mode = false; + occluder_light_mask = 1; + + fp_adjust = 0.00001; + tile_origin = TILE_ORIGIN_TOP_LEFT; set_notify_transform(true); } diff --git a/scene/2d/tile_map.h b/scene/2d/tile_map.h index c581aa805..f52adcd51 100644 --- a/scene/2d/tile_map.h +++ b/scene/2d/tile_map.h @@ -29,17 +29,17 @@ #ifndef TILE_MAP_H #define TILE_MAP_H -#include "scene/2d/node_2d.h" #include "scene/2d/navigation2d.h" +#include "scene/2d/node_2d.h" #include "scene/resources/tile_set.h" #include "self_list.h" #include "vset.h" class TileMap : public Node2D { - GDCLASS( TileMap, Node2D ); -public: + GDCLASS(TileMap, Node2D); +public: enum Mode { MODE_SQUARE, MODE_ISOMETRIC, @@ -58,20 +58,17 @@ public: TILE_ORIGIN_BOTTOM_LEFT }; - private: - Ref tile_set; Size2i cell_size; int quadrant_size; - bool center_x,center_y; + bool center_x, center_y; Mode mode; Transform2D custom_transform; HalfOffset half_offset; bool use_kinematic; Navigation2D *navigation; - union PosKey { struct { @@ -81,29 +78,32 @@ private: uint32_t key; //using a more precise comparison so the regions can be sorted later - bool operator<(const PosKey& p_k) const { return (y==p_k.y) ? x < p_k.x : y < p_k.y; } - - PosKey(int16_t p_x, int16_t p_y) { x=p_x; y=p_y; } - PosKey() { x=0; y=0; } - + bool operator<(const PosKey &p_k) const { return (y == p_k.y) ? x < p_k.x : y < p_k.y; } + + PosKey(int16_t p_x, int16_t p_y) { + x = p_x; + y = p_y; + } + PosKey() { + x = 0; + y = 0; + } }; - union Cell { struct { - int32_t id:24; - bool flip_h:1; - bool flip_v:1; - bool transpose:1; + int32_t id : 24; + bool flip_h : 1; + bool flip_v : 1; + bool transpose : 1; }; uint32_t _u32t; - Cell() { _u32t=0; } + Cell() { _u32t = 0; } }; - - Map tile_map; + Map tile_map; struct Quadrant { Vector2 pos; @@ -122,18 +122,33 @@ private: Transform2D xform; }; - - Map navpoly_ids; - Map occluder_instances; + Map navpoly_ids; + Map occluder_instances; VSet cells; - void operator=(const Quadrant& q) { pos=q.pos; canvas_items=q.canvas_items; body=q.body; cells=q.cells; navpoly_ids=q.navpoly_ids; occluder_instances=q.occluder_instances; } - Quadrant(const Quadrant& q) : dirty_list(this) { pos=q.pos; canvas_items=q.canvas_items; body=q.body; cells=q.cells; occluder_instances=q.occluder_instances; navpoly_ids=q.navpoly_ids;} - Quadrant() : dirty_list(this) {} + void operator=(const Quadrant &q) { + pos = q.pos; + canvas_items = q.canvas_items; + body = q.body; + cells = q.cells; + navpoly_ids = q.navpoly_ids; + occluder_instances = q.occluder_instances; + } + Quadrant(const Quadrant &q) + : dirty_list(this) { + pos = q.pos; + canvas_items = q.canvas_items; + body = q.body; + cells = q.cells; + occluder_instances = q.occluder_instances; + navpoly_ids = q.navpoly_ids; + } + Quadrant() + : dirty_list(this) {} }; - Map quadrant_map; + Map quadrant_map; SelfList::List dirty_quadrant_list; @@ -155,43 +170,38 @@ private: int occluder_light_mask; - void _fix_cell_transform(Transform2D& xform, const Cell& p_cell, const Vector2 &p_offset, const Size2 &p_sc); + void _fix_cell_transform(Transform2D &xform, const Cell &p_cell, const Vector2 &p_offset, const Size2 &p_sc); - Map::Element *_create_quadrant(const PosKey& p_qk); - void _erase_quadrant(Map::Element *Q); - void _make_quadrant_dirty(Map::Element *Q); + Map::Element *_create_quadrant(const PosKey &p_qk); + void _erase_quadrant(Map::Element *Q); + void _make_quadrant_dirty(Map::Element *Q); void _recreate_quadrants(); void _clear_quadrants(); void _update_dirty_quadrants(); - void _update_quadrant_space(const RID& p_space); + void _update_quadrant_space(const RID &p_space); void _update_quadrant_transform(); void _recompute_rect_cache(); _FORCE_INLINE_ int _get_quadrant_size() const; - - void _set_tile_data(const PoolVector& p_data); + void _set_tile_data(const PoolVector &p_data); PoolVector _get_tile_data() const; - void _set_old_cell_size(int p_size) { set_cell_size(Size2(p_size,p_size)); } + void _set_old_cell_size(int p_size) { set_cell_size(Size2(p_size, p_size)); } int _get_old_cell_size() const { return cell_size.x; } - _FORCE_INLINE_ Vector2 _map_to_world(int p_x,int p_y,bool p_ignore_ofs=false) const; + _FORCE_INLINE_ Vector2 _map_to_world(int p_x, int p_y, bool p_ignore_ofs = false) const; protected: - - void _notification(int p_what); static void _bind_methods(); public: - enum { - INVALID_CELL=-1 + INVALID_CELL = -1 }; - - void set_tileset(const Ref& p_tileset); + void set_tileset(const Ref &p_tileset); Ref get_tileset() const; void set_cell_size(Size2 p_size); @@ -205,14 +215,14 @@ public: void set_center_y(bool p_enable); bool get_center_y() const; - void set_cell(int p_x,int p_y,int p_tile,bool p_flip_x=false,bool p_flip_y=false,bool p_transpose=false); - int get_cell(int p_x,int p_y) const; - bool is_cell_x_flipped(int p_x,int p_y) const; - bool is_cell_y_flipped(int p_x,int p_y) const; - bool is_cell_transposed(int p_x,int p_y) const; + void set_cell(int p_x, int p_y, int p_tile, bool p_flip_x = false, bool p_flip_y = false, bool p_transpose = false); + int get_cell(int p_x, int p_y) const; + bool is_cell_x_flipped(int p_x, int p_y) const; + bool is_cell_y_flipped(int p_x, int p_y) const; + bool is_cell_transposed(int p_x, int p_y) const; - void set_cellv(const Vector2& p_pos,int p_tile,bool p_flip_x=false,bool p_flip_y=false,bool p_transpose=false); - int get_cellv(const Vector2& p_pos) const; + void set_cellv(const Vector2 &p_pos, int p_tile, bool p_flip_x = false, bool p_flip_y = false, bool p_transpose = false); + int get_cellv(const Vector2 &p_pos) const; Rect2 get_item_rect() const; @@ -240,14 +250,14 @@ public: void set_tile_origin(TileOrigin p_tile_origin); TileOrigin get_tile_origin() const; - void set_custom_transform(const Transform2D& p_xform); + void set_custom_transform(const Transform2D &p_xform); Transform2D get_custom_transform() const; Transform2D get_cell_transform() const; Vector2 get_cell_draw_offset() const; - Vector2 map_to_world(const Vector2& p_pos, bool p_ignore_ofs=false) const; - Vector2 world_to_map(const Vector2& p_pos) const; + Vector2 map_to_world(const Vector2 &p_pos, bool p_ignore_ofs = false) const; + Vector2 world_to_map(const Vector2 &p_pos) const; void set_y_sort_mode(bool p_enable); bool is_y_sort_mode_enabled() const; diff --git a/scene/2d/visibility_notifier_2d.cpp b/scene/2d/visibility_notifier_2d.cpp index 64ab333e4..f20a995d5 100644 --- a/scene/2d/visibility_notifier_2d.cpp +++ b/scene/2d/visibility_notifier_2d.cpp @@ -28,14 +28,14 @@ /*************************************************************************/ #include "visibility_notifier_2d.h" -#include "scene/scene_string_names.h" -#include "scene/2d/physics_body_2d.h" +#include "particles_2d.h" #include "scene/2d/animated_sprite.h" +#include "scene/2d/physics_body_2d.h" #include "scene/animation/animation_player.h" #include "scene/scene_string_names.h" -#include "particles_2d.h" +#include "scene/scene_string_names.h" -void VisibilityNotifier2D::_enter_viewport(Viewport* p_viewport) { +void VisibilityNotifier2D::_enter_viewport(Viewport *p_viewport) { ERR_FAIL_COND(viewports.has(p_viewport)); viewports.insert(p_viewport); @@ -43,16 +43,15 @@ void VisibilityNotifier2D::_enter_viewport(Viewport* p_viewport) { if (is_inside_tree() && get_tree()->is_editor_hint()) return; - if (viewports.size()==1) { + if (viewports.size() == 1) { emit_signal(SceneStringNames::get_singleton()->screen_entered); _screen_enter(); } - emit_signal(SceneStringNames::get_singleton()->viewport_entered,p_viewport); - + emit_signal(SceneStringNames::get_singleton()->viewport_entered, p_viewport); } -void VisibilityNotifier2D::_exit_viewport(Viewport* p_viewport){ +void VisibilityNotifier2D::_exit_viewport(Viewport *p_viewport) { ERR_FAIL_COND(!viewports.has(p_viewport)); viewports.erase(p_viewport); @@ -60,20 +59,19 @@ void VisibilityNotifier2D::_exit_viewport(Viewport* p_viewport){ if (is_inside_tree() && get_tree()->is_editor_hint()) return; - emit_signal(SceneStringNames::get_singleton()->viewport_exited,p_viewport); - if (viewports.size()==0) { + emit_signal(SceneStringNames::get_singleton()->viewport_exited, p_viewport); + if (viewports.size() == 0) { emit_signal(SceneStringNames::get_singleton()->screen_exited); _screen_exit(); } } +void VisibilityNotifier2D::set_rect(const Rect2 &p_rect) { -void VisibilityNotifier2D::set_rect(const Rect2& p_rect){ - - rect=p_rect; + rect = p_rect; if (is_inside_tree()) { - get_world_2d()->_update_notifier(this,get_global_transform().xform(rect)); + get_world_2d()->_update_notifier(this, get_global_transform().xform(rect)); if (get_tree()->is_editor_hint()) { update(); item_rect_changed(); @@ -88,31 +86,29 @@ Rect2 VisibilityNotifier2D::get_item_rect() const { return rect; } -Rect2 VisibilityNotifier2D::get_rect() const{ +Rect2 VisibilityNotifier2D::get_rect() const { return rect; } - void VisibilityNotifier2D::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { //get_world_2d()-> - get_world_2d()->_register_notifier(this,get_global_transform().xform(rect)); + get_world_2d()->_register_notifier(this, get_global_transform().xform(rect)); } break; case NOTIFICATION_TRANSFORM_CHANGED: { //get_world_2d()-> - get_world_2d()->_update_notifier(this,get_global_transform().xform(rect)); + get_world_2d()->_update_notifier(this, get_global_transform().xform(rect)); } break; case NOTIFICATION_DRAW: { if (get_tree()->is_editor_hint()) { - draw_rect(rect,Color(1,0.5,1,0.2)); + draw_rect(rect, Color(1, 0.5, 1, 0.2)); } } break; case NOTIFICATION_EXIT_TREE: { @@ -124,43 +120,36 @@ void VisibilityNotifier2D::_notification(int p_what) { bool VisibilityNotifier2D::is_on_screen() const { - return viewports.size()>0; + return viewports.size() > 0; } -void VisibilityNotifier2D::_bind_methods(){ +void VisibilityNotifier2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_rect","rect"),&VisibilityNotifier2D::set_rect); - ClassDB::bind_method(D_METHOD("get_rect"),&VisibilityNotifier2D::get_rect); - ClassDB::bind_method(D_METHOD("is_on_screen"),&VisibilityNotifier2D::is_on_screen); + ClassDB::bind_method(D_METHOD("set_rect", "rect"), &VisibilityNotifier2D::set_rect); + ClassDB::bind_method(D_METHOD("get_rect"), &VisibilityNotifier2D::get_rect); + ClassDB::bind_method(D_METHOD("is_on_screen"), &VisibilityNotifier2D::is_on_screen); - ADD_PROPERTY( PropertyInfo(Variant::RECT2,"rect"),"set_rect","get_rect"); + ADD_PROPERTY(PropertyInfo(Variant::RECT2, "rect"), "set_rect", "get_rect"); - ADD_SIGNAL( MethodInfo("viewport_entered",PropertyInfo(Variant::OBJECT,"viewport",PROPERTY_HINT_RESOURCE_TYPE,"Viewport")) ); - ADD_SIGNAL( MethodInfo("viewport_exited",PropertyInfo(Variant::OBJECT,"viewport",PROPERTY_HINT_RESOURCE_TYPE,"Viewport")) ); - ADD_SIGNAL( MethodInfo("screen_entered")); - ADD_SIGNAL( MethodInfo("screen_exited")); + ADD_SIGNAL(MethodInfo("viewport_entered", PropertyInfo(Variant::OBJECT, "viewport", PROPERTY_HINT_RESOURCE_TYPE, "Viewport"))); + ADD_SIGNAL(MethodInfo("viewport_exited", PropertyInfo(Variant::OBJECT, "viewport", PROPERTY_HINT_RESOURCE_TYPE, "Viewport"))); + ADD_SIGNAL(MethodInfo("screen_entered")); + ADD_SIGNAL(MethodInfo("screen_exited")); } - VisibilityNotifier2D::VisibilityNotifier2D() { - rect=Rect2(-10,-10,20,20); + rect = Rect2(-10, -10, 20, 20); set_notify_transform(true); } - - - - ////////////////////////////////////// - void VisibilityEnabler2D::_screen_enter() { + for (Map::Element *E = nodes.front(); E; E = E->next()) { - for(Map::Element *E=nodes.front();E;E=E->next()) { - - _change_node_state(E->key(),true); + _change_node_state(E->key(), true); } if (enabler[ENABLER_PARENT_FIXED_PROCESS] && get_parent()) @@ -168,14 +157,14 @@ void VisibilityEnabler2D::_screen_enter() { if (enabler[ENABLER_PARENT_PROCESS] && get_parent()) get_parent()->set_process(true); - visible=true; + visible = true; } -void VisibilityEnabler2D::_screen_exit(){ +void VisibilityEnabler2D::_screen_exit() { - for(Map::Element *E=nodes.front();E;E=E->next()) { + for (Map::Element *E = nodes.front(); E; E = E->next()) { - _change_node_state(E->key(),false); + _change_node_state(E->key(), false); } if (enabler[ENABLER_PARENT_FIXED_PROCESS] && get_parent()) @@ -183,23 +172,21 @@ void VisibilityEnabler2D::_screen_exit(){ if (enabler[ENABLER_PARENT_PROCESS] && get_parent()) get_parent()->set_process(false); - visible=false; + visible = false; } -void VisibilityEnabler2D::_find_nodes(Node* p_node) { +void VisibilityEnabler2D::_find_nodes(Node *p_node) { - - bool add=false; + bool add = false; Variant meta; if (enabler[ENABLER_FREEZE_BODIES]) { RigidBody2D *rb2d = p_node->cast_to(); - if (rb2d && ((rb2d->get_mode()==RigidBody2D::MODE_CHARACTER || (rb2d->get_mode()==RigidBody2D::MODE_RIGID && !rb2d->is_able_to_sleep())))) { - + if (rb2d && ((rb2d->get_mode() == RigidBody2D::MODE_CHARACTER || (rb2d->get_mode() == RigidBody2D::MODE_RIGID && !rb2d->is_able_to_sleep())))) { - add=true; - meta=rb2d->get_mode(); + add = true; + meta = rb2d->get_mode(); } } @@ -207,59 +194,53 @@ void VisibilityEnabler2D::_find_nodes(Node* p_node) { AnimationPlayer *ap = p_node->cast_to(); if (ap) { - add=true; + add = true; } - } if (enabler[ENABLER_PAUSE_ANIMATED_SPRITES]) { AnimatedSprite *as = p_node->cast_to(); if (as) { - add=true; + add = true; } - } - if (enabler[ENABLER_PAUSE_PARTICLES]) { Particles2D *ps = p_node->cast_to(); if (ps) { - add=true; + add = true; } - } if (add) { - p_node->connect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed",varray(p_node),CONNECT_ONESHOT); - nodes[p_node]=meta; - _change_node_state(p_node,false); + p_node->connect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed", varray(p_node), CONNECT_ONESHOT); + nodes[p_node] = meta; + _change_node_state(p_node, false); } - for(int i=0;iget_child_count();i++) { + for (int i = 0; i < p_node->get_child_count(); i++) { Node *c = p_node->get_child(i); - if (c->get_filename()!=String()) + if (c->get_filename() != String()) continue; //skip, instance _find_nodes(c); } - } -void VisibilityEnabler2D::_notification(int p_what){ +void VisibilityEnabler2D::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_TREE) { + if (p_what == NOTIFICATION_ENTER_TREE) { if (get_tree()->is_editor_hint()) return; - Node *from = this; //find where current scene starts - while(from->get_parent() && from->get_filename()==String()) - from=from->get_parent(); + while (from->get_parent() && from->get_filename() == String()) + from = from->get_parent(); _find_nodes(from); @@ -267,29 +248,25 @@ void VisibilityEnabler2D::_notification(int p_what){ get_parent()->set_fixed_process(false); if (enabler[ENABLER_PARENT_PROCESS] && get_parent()) get_parent()->set_process(false); - - } - if (p_what==NOTIFICATION_EXIT_TREE) { + if (p_what == NOTIFICATION_EXIT_TREE) { if (get_tree()->is_editor_hint()) return; - - for (Map::Element *E=nodes.front();E;E=E->next()) { + for (Map::Element *E = nodes.front(); E; E = E->next()) { if (!visible) - _change_node_state(E->key(),true); - E->key()->disconnect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed"); + _change_node_state(E->key(), true); + E->key()->disconnect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed"); } nodes.clear(); - } } -void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) { +void VisibilityEnabler2D::_change_node_state(Node *p_node, bool p_enabled) { ERR_FAIL_COND(!nodes.has(p_node)); @@ -302,7 +279,7 @@ void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) { } { - AnimationPlayer *ap=p_node->cast_to(); + AnimationPlayer *ap = p_node->cast_to(); if (ap) { @@ -310,7 +287,7 @@ void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) { } } { - AnimatedSprite *as=p_node->cast_to(); + AnimatedSprite *as = p_node->cast_to(); if (as) { @@ -322,81 +299,72 @@ void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) { } { - Particles2D *ps=p_node->cast_to(); + Particles2D *ps = p_node->cast_to(); if (ps) { ps->set_emitting(p_enabled); } } - } - -void VisibilityEnabler2D::_node_removed(Node* p_node) { +void VisibilityEnabler2D::_node_removed(Node *p_node) { if (!visible) - _change_node_state(p_node,true); + _change_node_state(p_node, true); //changed to one shot, not needed //p_node->disconnect(SceneStringNames::get_singleton()->exit_scene,this,"_node_removed"); nodes.erase(p_node); - } String VisibilityEnabler2D::get_configuration_warning() const { #ifdef TOOLS_ENABLED - if (is_inside_tree() && get_parent() && (get_parent()->get_filename()==String() && get_parent()!=get_tree()->get_edited_scene_root())) { + if (is_inside_tree() && get_parent() && (get_parent()->get_filename() == String() && get_parent() != get_tree()->get_edited_scene_root())) { return TTR("VisibilityEnable2D works best when used with the edited scene root directly as parent."); } #endif return String(); } - -void VisibilityEnabler2D::_bind_methods(){ - - ClassDB::bind_method(D_METHOD("set_enabler","enabler","enabled"),&VisibilityEnabler2D::set_enabler); - ClassDB::bind_method(D_METHOD("is_enabler_enabled","enabler"),&VisibilityEnabler2D::is_enabler_enabled); - ClassDB::bind_method(D_METHOD("_node_removed"),&VisibilityEnabler2D::_node_removed); - - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"pause_animations"),"set_enabler","is_enabler_enabled", ENABLER_PAUSE_ANIMATIONS ); - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"freeze_bodies"),"set_enabler","is_enabler_enabled", ENABLER_FREEZE_BODIES); - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"pause_particles"),"set_enabler","is_enabler_enabled", ENABLER_PAUSE_PARTICLES); - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"pause_animated_sprites"),"set_enabler","is_enabler_enabled", ENABLER_PAUSE_ANIMATED_SPRITES); - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"process_parent"),"set_enabler","is_enabler_enabled", ENABLER_PARENT_PROCESS); - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"fixed_process_parent"),"set_enabler","is_enabler_enabled", ENABLER_PARENT_FIXED_PROCESS); - - BIND_CONSTANT( ENABLER_FREEZE_BODIES ); - BIND_CONSTANT( ENABLER_PAUSE_ANIMATIONS ); - BIND_CONSTANT( ENABLER_PAUSE_PARTICLES ); - BIND_CONSTANT( ENABLER_PAUSE_ANIMATED_SPRITES ); - BIND_CONSTANT( ENABLER_PARENT_PROCESS ); - BIND_CONSTANT( ENABLER_PARENT_FIXED_PROCESS ); - BIND_CONSTANT( ENABLER_MAX); +void VisibilityEnabler2D::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_enabler", "enabler", "enabled"), &VisibilityEnabler2D::set_enabler); + ClassDB::bind_method(D_METHOD("is_enabler_enabled", "enabler"), &VisibilityEnabler2D::is_enabler_enabled); + ClassDB::bind_method(D_METHOD("_node_removed"), &VisibilityEnabler2D::_node_removed); + + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "pause_animations"), "set_enabler", "is_enabler_enabled", ENABLER_PAUSE_ANIMATIONS); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "freeze_bodies"), "set_enabler", "is_enabler_enabled", ENABLER_FREEZE_BODIES); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "pause_particles"), "set_enabler", "is_enabler_enabled", ENABLER_PAUSE_PARTICLES); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "pause_animated_sprites"), "set_enabler", "is_enabler_enabled", ENABLER_PAUSE_ANIMATED_SPRITES); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "process_parent"), "set_enabler", "is_enabler_enabled", ENABLER_PARENT_PROCESS); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "fixed_process_parent"), "set_enabler", "is_enabler_enabled", ENABLER_PARENT_FIXED_PROCESS); + + BIND_CONSTANT(ENABLER_FREEZE_BODIES); + BIND_CONSTANT(ENABLER_PAUSE_ANIMATIONS); + BIND_CONSTANT(ENABLER_PAUSE_PARTICLES); + BIND_CONSTANT(ENABLER_PAUSE_ANIMATED_SPRITES); + BIND_CONSTANT(ENABLER_PARENT_PROCESS); + BIND_CONSTANT(ENABLER_PARENT_FIXED_PROCESS); + BIND_CONSTANT(ENABLER_MAX); } -void VisibilityEnabler2D::set_enabler(Enabler p_enabler,bool p_enable){ - - ERR_FAIL_INDEX(p_enabler,ENABLER_MAX); - enabler[p_enabler]=p_enable; +void VisibilityEnabler2D::set_enabler(Enabler p_enabler, bool p_enable) { + ERR_FAIL_INDEX(p_enabler, ENABLER_MAX); + enabler[p_enabler] = p_enable; } -bool VisibilityEnabler2D::is_enabler_enabled(Enabler p_enabler) const{ +bool VisibilityEnabler2D::is_enabler_enabled(Enabler p_enabler) const { - ERR_FAIL_INDEX_V(p_enabler,ENABLER_MAX,false); + ERR_FAIL_INDEX_V(p_enabler, ENABLER_MAX, false); return enabler[p_enabler]; - } VisibilityEnabler2D::VisibilityEnabler2D() { - for(int i=0;i viewports; + Set viewports; Rect2 rect; protected: -friend class SpatialIndexer2D; - - void _enter_viewport(Viewport* p_viewport); - void _exit_viewport(Viewport* p_viewport); + friend class SpatialIndexer2D; + void _enter_viewport(Viewport *p_viewport); + void _exit_viewport(Viewport *p_viewport); virtual void _screen_enter() {} virtual void _screen_exit() {} void _notification(int p_what); static void _bind_methods(); -public: - void set_rect(const Rect2& p_rect); +public: + void set_rect(const Rect2 &p_rect); Rect2 get_rect() const; bool is_on_screen() const; @@ -64,12 +63,11 @@ public: VisibilityNotifier2D(); }; - class VisibilityEnabler2D : public VisibilityNotifier2D { - GDCLASS(VisibilityEnabler2D,VisibilityNotifier2D); -public: + GDCLASS(VisibilityEnabler2D, VisibilityNotifier2D); +public: enum Enabler { ENABLER_PAUSE_ANIMATIONS, ENABLER_FREEZE_BODIES, @@ -81,35 +79,31 @@ public: }; protected: - virtual void _screen_enter(); virtual void _screen_exit(); bool visible; - void _find_nodes(Node* p_node); + void _find_nodes(Node *p_node); - Map nodes; - void _node_removed(Node* p_node); + Map nodes; + void _node_removed(Node *p_node); bool enabler[ENABLER_MAX]; - void _change_node_state(Node* p_node,bool p_enabled); + void _change_node_state(Node *p_node, bool p_enabled); void _notification(int p_what); static void _bind_methods(); public: - - void set_enabler(Enabler p_enabler,bool p_enable); + void set_enabler(Enabler p_enabler, bool p_enable); bool is_enabler_enabled(Enabler p_enabler) const; String get_configuration_warning() const; VisibilityEnabler2D(); - }; VARIANT_ENUM_CAST(VisibilityEnabler2D::Enabler); - #endif // VISIBILITY_NOTIFIER_2D_H diff --git a/scene/2d/y_sort.cpp b/scene/2d/y_sort.cpp index cb9a494e8..760139287 100644 --- a/scene/2d/y_sort.cpp +++ b/scene/2d/y_sort.cpp @@ -28,12 +28,10 @@ /*************************************************************************/ #include "y_sort.h" - - void YSort::set_sort_enabled(bool p_enabled) { - sort_enabled=p_enabled; - VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(),sort_enabled); + sort_enabled = p_enabled; + VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(), sort_enabled); } bool YSort::is_sort_enabled() const { @@ -43,16 +41,15 @@ bool YSort::is_sort_enabled() const { void YSort::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_sort_enabled","enabled"),&YSort::set_sort_enabled); - ClassDB::bind_method(D_METHOD("is_sort_enabled"),&YSort::is_sort_enabled); + ClassDB::bind_method(D_METHOD("set_sort_enabled", "enabled"), &YSort::set_sort_enabled); + ClassDB::bind_method(D_METHOD("is_sort_enabled"), &YSort::is_sort_enabled); - ADD_GROUP("Sort","sort_"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"sort_enabled"),"set_sort_enabled","is_sort_enabled"); + ADD_GROUP("Sort", "sort_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sort_enabled"), "set_sort_enabled", "is_sort_enabled"); } - YSort::YSort() { - sort_enabled=true; - VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(),true); + sort_enabled = true; + VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(), true); } diff --git a/scene/2d/y_sort.h b/scene/2d/y_sort.h index ebfe695da..c91978849 100644 --- a/scene/2d/y_sort.h +++ b/scene/2d/y_sort.h @@ -32,11 +32,11 @@ #include "scene/2d/node_2d.h" class YSort : public Node2D { - GDCLASS(YSort,Node2D); + GDCLASS(YSort, Node2D); bool sort_enabled; static void _bind_methods(); -public: +public: void set_sort_enabled(bool p_enabled); bool is_sort_enabled() const; YSort(); diff --git a/scene/3d/area.cpp b/scene/3d/area.cpp index 92ac091fc..c42ca2f3f 100644 --- a/scene/3d/area.cpp +++ b/scene/3d/area.cpp @@ -31,164 +31,152 @@ #include "servers/physics_server.h" void Area::set_space_override_mode(SpaceOverride p_mode) { - space_override=p_mode; - PhysicsServer::get_singleton()->area_set_space_override_mode(get_rid(),PhysicsServer::AreaSpaceOverrideMode(p_mode)); - - + space_override = p_mode; + PhysicsServer::get_singleton()->area_set_space_override_mode(get_rid(), PhysicsServer::AreaSpaceOverrideMode(p_mode)); } -Area::SpaceOverride Area::get_space_override_mode() const{ +Area::SpaceOverride Area::get_space_override_mode() const { return space_override; } -void Area::set_gravity_is_point(bool p_enabled){ - - gravity_is_point=p_enabled; - PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT,p_enabled); +void Area::set_gravity_is_point(bool p_enabled) { + gravity_is_point = p_enabled; + PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT, p_enabled); } -bool Area::is_gravity_a_point() const{ +bool Area::is_gravity_a_point() const { return gravity_is_point; } -void Area::set_gravity_distance_scale(real_t p_scale){ - - gravity_distance_scale=p_scale; - PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE,p_scale); +void Area::set_gravity_distance_scale(real_t p_scale) { + gravity_distance_scale = p_scale; + PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE, p_scale); } -real_t Area::get_gravity_distance_scale() const{ +real_t Area::get_gravity_distance_scale() const { return gravity_distance_scale; } -void Area::set_gravity_vector(const Vector3& p_vec){ - - gravity_vec=p_vec; - PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_GRAVITY_VECTOR,p_vec); +void Area::set_gravity_vector(const Vector3 &p_vec) { + gravity_vec = p_vec; + PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_GRAVITY_VECTOR, p_vec); } -Vector3 Area::get_gravity_vector() const{ +Vector3 Area::get_gravity_vector() const { return gravity_vec; } -void Area::set_gravity(real_t p_gravity){ +void Area::set_gravity(real_t p_gravity) { - gravity=p_gravity; - PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_GRAVITY,p_gravity); + gravity = p_gravity; + PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_GRAVITY, p_gravity); } -real_t Area::get_gravity() const{ +real_t Area::get_gravity() const { return gravity; } -void Area::set_linear_damp(real_t p_linear_damp){ +void Area::set_linear_damp(real_t p_linear_damp) { - linear_damp=p_linear_damp; - PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_LINEAR_DAMP,p_linear_damp); + linear_damp = p_linear_damp; + PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_LINEAR_DAMP, p_linear_damp); } -real_t Area::get_linear_damp() const{ +real_t Area::get_linear_damp() const { return linear_damp; } -void Area::set_angular_damp(real_t p_angular_damp){ +void Area::set_angular_damp(real_t p_angular_damp) { - angular_damp=p_angular_damp; - PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_ANGULAR_DAMP,p_angular_damp); + angular_damp = p_angular_damp; + PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_ANGULAR_DAMP, p_angular_damp); } -real_t Area::get_angular_damp() const{ +real_t Area::get_angular_damp() const { return angular_damp; } -void Area::set_priority(real_t p_priority){ +void Area::set_priority(real_t p_priority) { - priority=p_priority; - PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_PRIORITY,p_priority); + priority = p_priority; + PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_PRIORITY, p_priority); } -real_t Area::get_priority() const{ +real_t Area::get_priority() const { return priority; } - void Area::_body_enter_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=body_map.find(p_id); + Map::Element *E = body_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(E->get().in_tree); - E->get().in_tree=true; - emit_signal(SceneStringNames::get_singleton()->body_entered,node); - for(int i=0;iget().shapes.size();i++) { + E->get().in_tree = true; + emit_signal(SceneStringNames::get_singleton()->body_entered, node); + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_entered,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_entered, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape); } - } void Area::_body_exit_tree(ObjectID p_id) { - Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=body_map.find(p_id); + Map::Element *E = body_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(!E->get().in_tree); - E->get().in_tree=false; - emit_signal(SceneStringNames::get_singleton()->body_exited,node); - for(int i=0;iget().shapes.size();i++) { + E->get().in_tree = false; + emit_signal(SceneStringNames::get_singleton()->body_exited, node); + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape); } - } -void Area::_body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape) { - +void Area::_body_inout(int p_status, const RID &p_body, int p_instance, int p_body_shape, int p_area_shape) { - bool body_in = p_status==PhysicsServer::AREA_BODY_ADDED; - ObjectID objid=p_instance; + bool body_in = p_status == PhysicsServer::AREA_BODY_ADDED; + ObjectID objid = p_instance; Object *obj = ObjectDB::get_instance(objid); Node *node = obj ? obj->cast_to() : NULL; - Map::Element *E=body_map.find(objid); + Map::Element *E = body_map.find(objid); ERR_FAIL_COND(!body_in && !E); - locked=true; + locked = true; if (body_in) { if (!E) { - E = body_map.insert(objid,BodyState()); - E->get().rc=0; - E->get().in_tree=node && node->is_inside_tree(); + E = body_map.insert(objid, BodyState()); + E->get().rc = 0; + E->get().in_tree = node && node->is_inside_tree(); if (node) { - node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree,make_binds(objid)); - node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree,make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree, make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree, make_binds(objid)); if (E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->body_entered,node); + emit_signal(SceneStringNames::get_singleton()->body_entered, node); } } - } E->get().rc++; if (node) - E->get().shapes.insert(ShapePair(p_body_shape,p_area_shape)); - + E->get().shapes.insert(ShapePair(p_body_shape, p_area_shape)); if (E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->body_shape_entered,objid,node,p_body_shape,p_area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_entered, objid, node, p_body_shape, p_area_shape); } } else { @@ -196,38 +184,32 @@ void Area::_body_inout(int p_status,const RID& p_body, int p_instance, int p_bod E->get().rc--; if (node) - E->get().shapes.erase(ShapePair(p_body_shape,p_area_shape)); + E->get().shapes.erase(ShapePair(p_body_shape, p_area_shape)); - bool eraseit=false; + bool eraseit = false; - if (E->get().rc==0) { + if (E->get().rc == 0) { if (node) { - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree); if (E->get().in_tree) - emit_signal(SceneStringNames::get_singleton()->body_exited,obj); - + emit_signal(SceneStringNames::get_singleton()->body_exited, obj); } - eraseit=true; - + eraseit = true; } if (node && E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,objid,obj,p_body_shape,p_area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, objid, obj, p_body_shape, p_area_shape); } if (eraseit) body_map.erase(E); - } - locked=false; - - + locked = false; } - void Area::_clear_monitoring() { if (locked) { @@ -236,11 +218,11 @@ void Area::_clear_monitoring() { ERR_FAIL_COND(locked); { - Map bmcopy = body_map; + Map bmcopy = body_map; body_map.clear(); //disconnect all monitored stuff - for (Map::Element *E=bmcopy.front();E;E=E->next()) { + for (Map::Element *E = bmcopy.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); Node *node = obj ? obj->cast_to() : NULL; @@ -248,26 +230,25 @@ void Area::_clear_monitoring() { if (!E->get().in_tree) continue; - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,E->key(),node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, E->key(), node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape); } - emit_signal(SceneStringNames::get_singleton()->body_exited,obj); + emit_signal(SceneStringNames::get_singleton()->body_exited, obj); - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree); } - } { - Map bmcopy = area_map; + Map bmcopy = area_map; area_map.clear(); //disconnect all monitored stuff - for (Map::Element *E=bmcopy.front();E;E=E->next()) { + for (Map::Element *E = bmcopy.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); Node *node = obj ? obj->cast_to() : NULL; @@ -275,22 +256,21 @@ void Area::_clear_monitoring() { if (!E->get().in_tree) continue; - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->area_shape_exited,E->key(),node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_exited, E->key(), node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape); } - emit_signal(SceneStringNames::get_singleton()->area_exited,obj); + emit_signal(SceneStringNames::get_singleton()->area_exited, obj); - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree); } } - } void Area::_notification(int p_what) { - if (p_what==NOTIFICATION_EXIT_TREE) { + if (p_what == NOTIFICATION_EXIT_TREE) { _clear_monitoring(); } } @@ -302,41 +282,38 @@ void Area::set_monitoring(bool p_enable) { } ERR_FAIL_COND(locked); - if (p_enable==monitoring) + if (p_enable == monitoring) return; - monitoring=p_enable; + monitoring = p_enable; if (monitoring) { - PhysicsServer::get_singleton()->area_set_monitor_callback(get_rid(),this,SceneStringNames::get_singleton()->_body_inout); - PhysicsServer::get_singleton()->area_set_area_monitor_callback(get_rid(),this,SceneStringNames::get_singleton()->_area_inout); + PhysicsServer::get_singleton()->area_set_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_body_inout); + PhysicsServer::get_singleton()->area_set_area_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_area_inout); } else { - PhysicsServer::get_singleton()->area_set_monitor_callback(get_rid(),NULL,StringName()); - PhysicsServer::get_singleton()->area_set_area_monitor_callback(get_rid(),NULL,StringName()); + PhysicsServer::get_singleton()->area_set_monitor_callback(get_rid(), NULL, StringName()); + PhysicsServer::get_singleton()->area_set_area_monitor_callback(get_rid(), NULL, StringName()); _clear_monitoring(); - } } - void Area::_area_enter_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=area_map.find(p_id); + Map::Element *E = area_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(E->get().in_tree); - E->get().in_tree=true; - emit_signal(SceneStringNames::get_singleton()->area_entered,node); - for(int i=0;iget().shapes.size();i++) { + E->get().in_tree = true; + emit_signal(SceneStringNames::get_singleton()->area_entered, node); + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->area_shape_entered,p_id,node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_entered, p_id, node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape); } - } void Area::_area_exit_tree(ObjectID p_id) { @@ -344,56 +321,51 @@ void Area::_area_exit_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=area_map.find(p_id); + Map::Element *E = area_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(!E->get().in_tree); - E->get().in_tree=false; - emit_signal(SceneStringNames::get_singleton()->area_exited,node); - for(int i=0;iget().shapes.size();i++) { + E->get().in_tree = false; + emit_signal(SceneStringNames::get_singleton()->area_exited, node); + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->area_shape_exited,p_id,node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_exited, p_id, node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape); } - } -void Area::_area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape) { - +void Area::_area_inout(int p_status, const RID &p_area, int p_instance, int p_area_shape, int p_self_shape) { - bool area_in = p_status==PhysicsServer::AREA_BODY_ADDED; - ObjectID objid=p_instance; + bool area_in = p_status == PhysicsServer::AREA_BODY_ADDED; + ObjectID objid = p_instance; Object *obj = ObjectDB::get_instance(objid); Node *node = obj ? obj->cast_to() : NULL; - Map::Element *E=area_map.find(objid); + Map::Element *E = area_map.find(objid); ERR_FAIL_COND(!area_in && !E); - locked=true; + locked = true; if (area_in) { if (!E) { - E = area_map.insert(objid,AreaState()); - E->get().rc=0; - E->get().in_tree=node && node->is_inside_tree(); + E = area_map.insert(objid, AreaState()); + E->get().rc = 0; + E->get().in_tree = node && node->is_inside_tree(); if (node) { - node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree,make_binds(objid)); - node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree,make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree, make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree, make_binds(objid)); if (E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->area_entered,node); - + emit_signal(SceneStringNames::get_singleton()->area_entered, node); } } - } E->get().rc++; if (node) - E->get().shapes.insert(AreaShapePair(p_area_shape,p_self_shape)); - + E->get().shapes.insert(AreaShapePair(p_area_shape, p_self_shape)); if (!node || E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->area_shape_entered,objid,node,p_area_shape,p_self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_entered, objid, node, p_area_shape, p_self_shape); } } else { @@ -401,36 +373,31 @@ void Area::_area_inout(int p_status,const RID& p_area, int p_instance, int p_are E->get().rc--; if (node) - E->get().shapes.erase(AreaShapePair(p_area_shape,p_self_shape)); + E->get().shapes.erase(AreaShapePair(p_area_shape, p_self_shape)); - bool eraseit=false; + bool eraseit = false; - if (E->get().rc==0) { + if (E->get().rc == 0) { if (node) { - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree); if (E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->area_exited,obj); + emit_signal(SceneStringNames::get_singleton()->area_exited, obj); } - } - eraseit=true; - + eraseit = true; } if (!node || E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->area_shape_exited,objid,obj,p_area_shape,p_self_shape); + emit_signal(SceneStringNames::get_singleton()->area_shape_exited, objid, obj, p_area_shape, p_self_shape); } if (eraseit) area_map.erase(E); - } - locked=false; - - + locked = false; } bool Area::is_monitoring() const { @@ -438,21 +405,19 @@ bool Area::is_monitoring() const { return monitoring; } - Array Area::get_overlapping_bodies() const { - ERR_FAIL_COND_V(!monitoring,Array()); + ERR_FAIL_COND_V(!monitoring, Array()); Array ret; ret.resize(body_map.size()); - int idx=0; - for (const Map::Element *E=body_map.front();E;E=E->next()) { + int idx = 0; + for (const Map::Element *E = body_map.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); if (!obj) { - ret.resize( ret.size() -1 ); //ops + ret.resize(ret.size() - 1); //ops } else { - ret[idx++]=obj; + ret[idx++] = obj; } - } return ret; @@ -465,12 +430,12 @@ void Area::set_monitorable(bool p_enable) { } ERR_FAIL_COND(locked); - if (p_enable==monitorable) + if (p_enable == monitorable) return; - monitorable=p_enable; + monitorable = p_enable; - PhysicsServer::get_singleton()->area_set_monitorable(get_rid(),monitorable); + PhysicsServer::get_singleton()->area_set_monitorable(get_rid(), monitorable); } bool Area::is_monitorable() const { @@ -478,51 +443,45 @@ bool Area::is_monitorable() const { return monitorable; } - Array Area::get_overlapping_areas() const { - ERR_FAIL_COND_V(!monitoring,Array()); + ERR_FAIL_COND_V(!monitoring, Array()); Array ret; ret.resize(area_map.size()); - int idx=0; - for (const Map::Element *E=area_map.front();E;E=E->next()) { + int idx = 0; + for (const Map::Element *E = area_map.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); if (!obj) { - ret.resize( ret.size() -1 ); //ops + ret.resize(ret.size() - 1); //ops } else { - ret[idx++]=obj; + ret[idx++] = obj; } - } return ret; } -bool Area::overlaps_area(Node* p_area) const { +bool Area::overlaps_area(Node *p_area) const { - ERR_FAIL_NULL_V(p_area,false); - const Map::Element *E=area_map.find(p_area->get_instance_ID()); + ERR_FAIL_NULL_V(p_area, false); + const Map::Element *E = area_map.find(p_area->get_instance_ID()); if (!E) return false; return E->get().in_tree; - - - } -bool Area::overlaps_body(Node* p_body) const{ +bool Area::overlaps_body(Node *p_body) const { - ERR_FAIL_NULL_V(p_body,false); - const Map::Element *E=body_map.find(p_body->get_instance_ID()); + ERR_FAIL_NULL_V(p_body, false); + const Map::Element *E = body_map.find(p_body->get_instance_ID()); if (!E) return false; return E->get().in_tree; - } void Area::set_collision_mask(uint32_t p_mask) { - collision_mask=p_mask; - PhysicsServer::get_singleton()->area_set_collision_mask(get_rid(),p_mask); + collision_mask = p_mask; + PhysicsServer::get_singleton()->area_set_collision_mask(get_rid(), p_mask); } uint32_t Area::get_collision_mask() const { @@ -531,8 +490,8 @@ uint32_t Area::get_collision_mask() const { } void Area::set_layer_mask(uint32_t p_mask) { - layer_mask=p_mask; - PhysicsServer::get_singleton()->area_set_layer_mask(get_rid(),p_mask); + layer_mask = p_mask; + PhysicsServer::get_singleton()->area_set_layer_mask(get_rid(), p_mask); } uint32_t Area::get_layer_mask() const { @@ -544,144 +503,135 @@ void Area::set_collision_mask_bit(int p_bit, bool p_value) { uint32_t mask = get_collision_mask(); if (p_value) - mask|=1<area_create(),true) { +Area::Area() + : CollisionObject(PhysicsServer::get_singleton()->area_create(), true) { - space_override=SPACE_OVERRIDE_DISABLED; + space_override = SPACE_OVERRIDE_DISABLED; set_gravity(9.8); - locked=false; - set_gravity_vector(Vector3(0,-1,0)); - gravity_is_point=false; - gravity_distance_scale=0; - linear_damp=0.1; - angular_damp=1; - priority=0; - monitoring=false; - collision_mask=1; - layer_mask=1; + locked = false; + set_gravity_vector(Vector3(0, -1, 0)); + gravity_is_point = false; + gravity_distance_scale = 0; + linear_damp = 0.1; + angular_damp = 1; + priority = 0; + monitoring = false; + collision_mask = 1; + layer_mask = 1; set_ray_pickable(false); set_monitoring(true); set_monitorable(true); - } Area::~Area() { - - } diff --git a/scene/3d/area.h b/scene/3d/area.h index 795684650..a50f101ec 100644 --- a/scene/3d/area.h +++ b/scene/3d/area.h @@ -34,9 +34,9 @@ class Area : public CollisionObject { - GDCLASS( Area, CollisionObject ); -public: + GDCLASS(Area, CollisionObject); +public: enum SpaceOverride { SPACE_OVERRIDE_DISABLED, SPACE_OVERRIDE_COMBINE, @@ -44,9 +44,8 @@ public: SPACE_OVERRIDE_REPLACE, SPACE_OVERRIDE_REPLACE_COMBINE }; -private: - +private: SpaceOverride space_override; Vector3 gravity_vec; real_t gravity; @@ -61,8 +60,7 @@ private: bool monitorable; bool locked; - - void _body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape); + void _body_inout(int p_status, const RID &p_body, int p_instance, int p_body_shape, int p_area_shape); void _body_enter_tree(ObjectID p_id); void _body_exit_tree(ObjectID p_id); @@ -71,15 +69,18 @@ private: int body_shape; int area_shape; - bool operator<(const ShapePair& p_sp) const { - if (body_shape==p_sp.body_shape) + bool operator<(const ShapePair &p_sp) const { + if (body_shape == p_sp.body_shape) return area_shape < p_sp.area_shape; else return body_shape < p_sp.body_shape; } ShapePair() {} - ShapePair(int p_bs, int p_as) { body_shape=p_bs; area_shape=p_as; } + ShapePair(int p_bs, int p_as) { + body_shape = p_bs; + area_shape = p_as; + } }; struct BodyState { @@ -89,10 +90,9 @@ private: VSet shapes; }; - Map body_map; + Map body_map; - - void _area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape); + void _area_inout(int p_status, const RID &p_area, int p_instance, int p_area_shape, int p_self_shape); void _area_enter_tree(ObjectID p_id); void _area_exit_tree(ObjectID p_id); @@ -101,15 +101,18 @@ private: int area_shape; int self_shape; - bool operator<(const AreaShapePair& p_sp) const { - if (area_shape==p_sp.area_shape) + bool operator<(const AreaShapePair &p_sp) const { + if (area_shape == p_sp.area_shape) return self_shape < p_sp.self_shape; else return area_shape < p_sp.area_shape; } AreaShapePair() {} - AreaShapePair(int p_bs, int p_as) { area_shape=p_bs; self_shape=p_as; } + AreaShapePair(int p_bs, int p_as) { + area_shape = p_bs; + self_shape = p_as; + } }; struct AreaState { @@ -119,16 +122,14 @@ private: VSet shapes; }; - Map area_map; + Map area_map; void _clear_monitoring(); - protected: - void _notification(int p_what); static void _bind_methods(); -public: +public: void set_space_override_mode(SpaceOverride p_mode); SpaceOverride get_space_override_mode() const; @@ -138,7 +139,7 @@ public: void set_gravity_distance_scale(real_t p_scale); real_t get_gravity_distance_scale() const; - void set_gravity_vector(const Vector3& p_vec); + void set_gravity_vector(const Vector3 &p_vec); Vector3 get_gravity_vector() const; void set_gravity(real_t p_gravity); @@ -174,9 +175,8 @@ public: Array get_overlapping_bodies() const; Array get_overlapping_areas() const; //function for script - bool overlaps_area(Node* p_area) const; - bool overlaps_body(Node* p_body) const; - + bool overlaps_area(Node *p_area) const; + bool overlaps_body(Node *p_body) const; Area(); ~Area(); diff --git a/scene/3d/baked_light_instance.cpp b/scene/3d/baked_light_instance.cpp index e20d8faaf..ac424475e 100644 --- a/scene/3d/baked_light_instance.cpp +++ b/scene/3d/baked_light_instance.cpp @@ -27,200 +27,226 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "baked_light_instance.h" -#include "scene/scene_string_names.h" -#include "mesh_instance.h" #include "light.h" #include "math.h" +#include "mesh_instance.h" +#include "scene/scene_string_names.h" -#define FINDMINMAX(x0,x1,x2,min,max) \ - min = max = x0; \ - if(x1max) max=x1;\ - if(x2max) max=x2; - -static bool planeBoxOverlap(Vector3 normal,float d, Vector3 maxbox) -{ - int q; - Vector3 vmin,vmax; - for(q=0;q<=2;q++) - { - if(normal[q]>0.0f) - { - vmin[q]=-maxbox[q]; - vmax[q]=maxbox[q]; - } - else - { - vmin[q]=maxbox[q]; - vmax[q]=-maxbox[q]; - } - } - if(normal.dot(vmin)+d>0.0f) return false; - if(normal.dot(vmax)+d>=0.0f) return true; - - return false; -} +#define FINDMINMAX(x0, x1, x2, min, max) \ + min = max = x0; \ + if (x1 < min) min = x1; \ + if (x1 > max) max = x1; \ + if (x2 < min) min = x2; \ + if (x2 > max) max = x2; + +static bool planeBoxOverlap(Vector3 normal, float d, Vector3 maxbox) { + int q; + Vector3 vmin, vmax; + for (q = 0; q <= 2; q++) { + if (normal[q] > 0.0f) { + vmin[q] = -maxbox[q]; + vmax[q] = maxbox[q]; + } else { + vmin[q] = maxbox[q]; + vmax[q] = -maxbox[q]; + } + } + if (normal.dot(vmin) + d > 0.0f) return false; + if (normal.dot(vmax) + d >= 0.0f) return true; + return false; +} /*======================== X-tests ========================*/ -#define AXISTEST_X01(a, b, fa, fb) \ - p0 = a*v0.y - b*v0.z; \ - p2 = a*v2.y - b*v2.z; \ - if(p0rad || max<-rad) return false; - -#define AXISTEST_X2(a, b, fa, fb) \ - p0 = a*v0.y - b*v0.z; \ - p1 = a*v1.y - b*v1.z; \ - if(p0rad || max<-rad) return false; +#define AXISTEST_X01(a, b, fa, fb) \ + p0 = a * v0.y - b * v0.z; \ + p2 = a * v2.y - b * v2.z; \ + if (p0 < p2) { \ + min = p0; \ + max = p2; \ + } else { \ + min = p2; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \ + if (min > rad || max < -rad) return false; + +#define AXISTEST_X2(a, b, fa, fb) \ + p0 = a * v0.y - b * v0.z; \ + p1 = a * v1.y - b * v1.z; \ + if (p0 < p1) { \ + min = p0; \ + max = p1; \ + } else { \ + min = p1; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \ + if (min > rad || max < -rad) return false; /*======================== Y-tests ========================*/ -#define AXISTEST_Y02(a, b, fa, fb) \ - p0 = -a*v0.x + b*v0.z; \ - p2 = -a*v2.x + b*v2.z; \ - if(p0rad || max<-rad) return false; - -#define AXISTEST_Y1(a, b, fa, fb) \ - p0 = -a*v0.x + b*v0.z; \ - p1 = -a*v1.x + b*v1.z; \ - if(p0rad || max<-rad) return false; +#define AXISTEST_Y02(a, b, fa, fb) \ + p0 = -a * v0.x + b * v0.z; \ + p2 = -a * v2.x + b * v2.z; \ + if (p0 < p2) { \ + min = p0; \ + max = p2; \ + } else { \ + min = p2; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \ + if (min > rad || max < -rad) return false; + +#define AXISTEST_Y1(a, b, fa, fb) \ + p0 = -a * v0.x + b * v0.z; \ + p1 = -a * v1.x + b * v1.z; \ + if (p0 < p1) { \ + min = p0; \ + max = p1; \ + } else { \ + min = p1; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \ + if (min > rad || max < -rad) return false; /*======================== Z-tests ========================*/ -#define AXISTEST_Z12(a, b, fa, fb) \ - p1 = a*v1.x - b*v1.y; \ - p2 = a*v2.x - b*v2.y; \ - if(p2rad || max<-rad) return false; - -#define AXISTEST_Z0(a, b, fa, fb) \ - p0 = a*v0.x - b*v0.y; \ - p1 = a*v1.x - b*v1.y; \ - if(p0rad || max<-rad) return false; - -static bool fast_tri_box_overlap(const Vector3& boxcenter,const Vector3 boxhalfsize,const Vector3 *triverts) { - - /* use separating axis theorem to test overlap between triangle and box */ - /* need to test for overlap in these directions: */ - /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */ - /* we do not even need to test these) */ - /* 2) normal of the triangle */ - /* 3) crossproduct(edge from tri, {x,y,z}-directin) */ - /* this gives 3x3=9 more tests */ - Vector3 v0,v1,v2; - float min,max,d,p0,p1,p2,rad,fex,fey,fez; - Vector3 normal,e0,e1,e2; - - /* This is the fastest branch on Sun */ - /* move everything so that the boxcenter is in (0,0,0) */ - - v0=triverts[0]-boxcenter; - v1=triverts[1]-boxcenter; - v2=triverts[2]-boxcenter; - - /* compute triangle edges */ - e0=v1-v0; /* tri edge 0 */ - e1=v2-v1; /* tri edge 1 */ - e2=v0-v2; /* tri edge 2 */ - - /* Bullet 3: */ - /* test the 9 tests first (this was faster) */ - fex = Math::abs(e0.x); - fey = Math::abs(e0.y); - fez = Math::abs(e0.z); - AXISTEST_X01(e0.z, e0.y, fez, fey); - AXISTEST_Y02(e0.z, e0.x, fez, fex); - AXISTEST_Z12(e0.y, e0.x, fey, fex); - - fex = Math::abs(e1.x); - fey = Math::abs(e1.y); - fez = Math::abs(e1.z); - AXISTEST_X01(e1.z, e1.y, fez, fey); - AXISTEST_Y02(e1.z, e1.x, fez, fex); - AXISTEST_Z0(e1.y, e1.x, fey, fex); - - fex = Math::abs(e2.x); - fey = Math::abs(e2.y); - fez = Math::abs(e2.z); - AXISTEST_X2(e2.z, e2.y, fez, fey); - AXISTEST_Y1(e2.z, e2.x, fez, fex); - AXISTEST_Z12(e2.y, e2.x, fey, fex); - - /* Bullet 1: */ - /* first test overlap in the {x,y,z}-directions */ - /* find min, max of the triangle each direction, and test for overlap in */ - /* that direction -- this is equivalent to testing a minimal AABB around */ - /* the triangle against the AABB */ - - /* test in X-direction */ - FINDMINMAX(v0.x,v1.x,v2.x,min,max); - if(min>boxhalfsize.x || max<-boxhalfsize.x) return false; - - /* test in Y-direction */ - FINDMINMAX(v0.y,v1.y,v2.y,min,max); - if(min>boxhalfsize.y || max<-boxhalfsize.y) return false; - - /* test in Z-direction */ - FINDMINMAX(v0.z,v1.z,v2.z,min,max); - if(min>boxhalfsize.z || max<-boxhalfsize.z) return false; - - /* Bullet 2: */ - /* test if the box intersects the plane of the triangle */ - /* compute plane equation of triangle: normal*x+d=0 */ - normal=e0.cross(e1); - d=-normal.dot(v0); /* plane eq: normal.x+d=0 */ - if(!planeBoxOverlap(normal,d,boxhalfsize)) return false; - - return true; /* box and triangle overlaps */ +#define AXISTEST_Z12(a, b, fa, fb) \ + p1 = a * v1.x - b * v1.y; \ + p2 = a * v2.x - b * v2.y; \ + if (p2 < p1) { \ + min = p2; \ + max = p1; \ + } else { \ + min = p1; \ + max = p2; \ + } \ + rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \ + if (min > rad || max < -rad) return false; + +#define AXISTEST_Z0(a, b, fa, fb) \ + p0 = a * v0.x - b * v0.y; \ + p1 = a * v1.x - b * v1.y; \ + if (p0 < p1) { \ + min = p0; \ + max = p1; \ + } else { \ + min = p1; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \ + if (min > rad || max < -rad) return false; + +static bool fast_tri_box_overlap(const Vector3 &boxcenter, const Vector3 boxhalfsize, const Vector3 *triverts) { + + /* use separating axis theorem to test overlap between triangle and box */ + /* need to test for overlap in these directions: */ + /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */ + /* we do not even need to test these) */ + /* 2) normal of the triangle */ + /* 3) crossproduct(edge from tri, {x,y,z}-directin) */ + /* this gives 3x3=9 more tests */ + Vector3 v0, v1, v2; + float min, max, d, p0, p1, p2, rad, fex, fey, fez; + Vector3 normal, e0, e1, e2; + + /* This is the fastest branch on Sun */ + /* move everything so that the boxcenter is in (0,0,0) */ + + v0 = triverts[0] - boxcenter; + v1 = triverts[1] - boxcenter; + v2 = triverts[2] - boxcenter; + + /* compute triangle edges */ + e0 = v1 - v0; /* tri edge 0 */ + e1 = v2 - v1; /* tri edge 1 */ + e2 = v0 - v2; /* tri edge 2 */ + + /* Bullet 3: */ + /* test the 9 tests first (this was faster) */ + fex = Math::abs(e0.x); + fey = Math::abs(e0.y); + fez = Math::abs(e0.z); + AXISTEST_X01(e0.z, e0.y, fez, fey); + AXISTEST_Y02(e0.z, e0.x, fez, fex); + AXISTEST_Z12(e0.y, e0.x, fey, fex); + + fex = Math::abs(e1.x); + fey = Math::abs(e1.y); + fez = Math::abs(e1.z); + AXISTEST_X01(e1.z, e1.y, fez, fey); + AXISTEST_Y02(e1.z, e1.x, fez, fex); + AXISTEST_Z0(e1.y, e1.x, fey, fex); + + fex = Math::abs(e2.x); + fey = Math::abs(e2.y); + fez = Math::abs(e2.z); + AXISTEST_X2(e2.z, e2.y, fez, fey); + AXISTEST_Y1(e2.z, e2.x, fez, fex); + AXISTEST_Z12(e2.y, e2.x, fey, fex); + + /* Bullet 1: */ + /* first test overlap in the {x,y,z}-directions */ + /* find min, max of the triangle each direction, and test for overlap in */ + /* that direction -- this is equivalent to testing a minimal AABB around */ + /* the triangle against the AABB */ + + /* test in X-direction */ + FINDMINMAX(v0.x, v1.x, v2.x, min, max); + if (min > boxhalfsize.x || max < -boxhalfsize.x) return false; + + /* test in Y-direction */ + FINDMINMAX(v0.y, v1.y, v2.y, min, max); + if (min > boxhalfsize.y || max < -boxhalfsize.y) return false; + + /* test in Z-direction */ + FINDMINMAX(v0.z, v1.z, v2.z, min, max); + if (min > boxhalfsize.z || max < -boxhalfsize.z) return false; + + /* Bullet 2: */ + /* test if the box intersects the plane of the triangle */ + /* compute plane equation of triangle: normal*x+d=0 */ + normal = e0.cross(e1); + d = -normal.dot(v0); /* plane eq: normal.x+d=0 */ + if (!planeBoxOverlap(normal, d, boxhalfsize)) return false; + + return true; /* box and triangle overlaps */ } - -Vector BakedLight::_get_bake_texture(Image &p_image,const Color& p_color) { +Vector BakedLight::_get_bake_texture(Image &p_image, const Color &p_color) { Vector ret; if (p_image.empty()) { - ret.resize(bake_texture_size*bake_texture_size); - for(int i=0;i::Read r = p_image.get_data().read(); - ret.resize(bake_texture_size*bake_texture_size); + ret.resize(bake_texture_size * bake_texture_size); - for(int i=0;i p_material) { //this way of obtaining materials is inaccurate and also does not support some compressed formats very well @@ -236,7 +262,6 @@ BakedLight::MaterialCache BakedLight::_get_material_cache(Ref p_materi if (mat.is_valid()) { - Ref albedo_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_ALBEDO); Image img_albedo; @@ -245,14 +270,14 @@ BakedLight::MaterialCache BakedLight::_get_material_cache(Ref p_materi img_albedo = albedo_tex->get_data(); } - mc.albedo=_get_bake_texture(img_albedo,mat->get_albedo()); + mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo()); Ref emission_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_EMISSION); Color emission_col = mat->get_emission(); - emission_col.r*=mat->get_emission_energy(); - emission_col.g*=mat->get_emission_energy(); - emission_col.b*=mat->get_emission_energy(); + emission_col.r *= mat->get_emission_energy(); + emission_col.g *= mat->get_emission_energy(); + emission_col.b *= mat->get_emission_energy(); Image img_emission; @@ -261,503 +286,465 @@ BakedLight::MaterialCache BakedLight::_get_material_cache(Ref p_materi img_emission = emission_tex->get_data(); } - mc.emission=_get_bake_texture(img_emission,emission_col); + mc.emission = _get_bake_texture(img_emission, emission_col); } else { Image empty; - mc.albedo=_get_bake_texture(empty,Color(0.7,0.7,0.7)); - mc.emission=_get_bake_texture(empty,Color(0,0,0)); - - + mc.albedo = _get_bake_texture(empty, Color(0.7, 0.7, 0.7)); + mc.emission = _get_bake_texture(empty, Color(0, 0, 0)); } - material_cache[p_material]=mc; + material_cache[p_material] = mc; return mc; - - } +static _FORCE_INLINE_ Vector2 get_uv(const Vector3 &p_pos, const Vector3 *p_vtx, const Vector2 *p_uv) { - -static _FORCE_INLINE_ Vector2 get_uv(const Vector3& p_pos, const Vector3 *p_vtx, const Vector2* p_uv) { - - if (p_pos.distance_squared_to(p_vtx[0])closest_dot) { - closest_axis=i; - closest_dot=dot; + axis[i] = 1.0; + float dot = ABS(normal.dot(axis)); + if (i == 0 || dot > closest_dot) { + closest_axis = i; + closest_dot = dot; } } Vector3 axis; - axis[closest_axis]=1.0; + axis[closest_axis] = 1.0; Vector3 t1; - t1[(closest_axis+1)%3]=1.0; + t1[(closest_axis + 1) % 3] = 1.0; Vector3 t2; - t2[(closest_axis+2)%3]=1.0; + t2[(closest_axis + 2) % 3] = 1.0; - t1*=p_aabb.size[(closest_axis+1)%3]/float(color_scan_cell_width); - t2*=p_aabb.size[(closest_axis+2)%3]/float(color_scan_cell_width); + t1 *= p_aabb.size[(closest_axis + 1) % 3] / float(color_scan_cell_width); + t2 *= p_aabb.size[(closest_axis + 2) % 3] / float(color_scan_cell_width); Color albedo_accum; Color emission_accum; - float alpha=0.0; + float alpha = 0.0; //map to a grid average in the best axis for this face - for(int i=0;iCMP_EPSILON) { - bake_cells_write[p_idx].used_sides|=(1< CMP_EPSILON) { + bake_cells_write[p_idx].used_sides |= (1 << i); } } - } else { //go down - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - Rect3 aabb=p_aabb; - aabb.size*=0.5; + Rect3 aabb = p_aabb; + aabb.size *= 0.5; - if (i&1) - aabb.pos.x+=aabb.size.x; - if (i&2) - aabb.pos.y+=aabb.size.y; - if (i&4) - aabb.pos.z+=aabb.size.z; + if (i & 1) + aabb.pos.x += aabb.size.x; + if (i & 2) + aabb.pos.y += aabb.size.y; + if (i & 4) + aabb.pos.z += aabb.size.z; { - Rect3 test_aabb=aabb; + Rect3 test_aabb = aabb; //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time - Vector3 qsize = test_aabb.size*0.5; //quarter size, for fast aabb test + Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test - if (!fast_tri_box_overlap(test_aabb.pos+qsize,qsize,p_vtx)) { - //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) { + if (!fast_tri_box_overlap(test_aabb.pos + qsize, qsize, p_vtx)) { + //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) { //does not fit in child, go on continue; } - } - if (bake_cells_write[p_idx].childs[i]==CHILD_EMPTY) { + if (bake_cells_write[p_idx].childs[i] == CHILD_EMPTY) { //sub cell must be created - if (bake_cells_used==(1<::Write(); - bake_cells.resize(1<::Write(); + bake_cells.resize(1 << bake_cells_alloc); + bake_cells_write = bake_cells.write(); } - bake_cells_write[p_idx].childs[i]=bake_cells_used; - bake_cells_level_used[p_level+1]++; + bake_cells_write[p_idx].childs[i] = bake_cells_used; + bake_cells_level_used[p_level + 1]++; bake_cells_used++; - - } - - _plot_face(bake_cells_write[p_idx].childs[i],p_level+1,p_vtx,p_uv,p_material,aabb); + _plot_face(bake_cells_write[p_idx].childs[i], p_level + 1, p_vtx, p_uv, p_material, aabb); } } } +void BakedLight::_fixup_plot(int p_idx, int p_level, int p_x, int p_y, int p_z) { - -void BakedLight::_fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z) { - - - - if (p_level==cell_subdiv-1) { - + if (p_level == cell_subdiv - 1) { float alpha = bake_cells_write[p_idx].alpha; - bake_cells_write[p_idx].albedo[0]/=alpha; - bake_cells_write[p_idx].albedo[1]/=alpha; - bake_cells_write[p_idx].albedo[2]/=alpha; + bake_cells_write[p_idx].albedo[0] /= alpha; + bake_cells_write[p_idx].albedo[1] /= alpha; + bake_cells_write[p_idx].albedo[2] /= alpha; //transfer emission to light - bake_cells_write[p_idx].light[0]/=alpha; - bake_cells_write[p_idx].light[1]/=alpha; - bake_cells_write[p_idx].light[2]/=alpha; + bake_cells_write[p_idx].light[0] /= alpha; + bake_cells_write[p_idx].light[1] /= alpha; + bake_cells_write[p_idx].light[2] /= alpha; - bake_cells_write[p_idx].alpha=1.0; + bake_cells_write[p_idx].alpha = 1.0; //remove neighbours from used sides - for(int n=0;n<6;n++) { + for (int n = 0; n < 6; n++) { - int ofs[3]={0,0,0}; + int ofs[3] = { 0, 0, 0 }; - ofs[n/2]=(n&1)?1:-1; + ofs[n / 2] = (n & 1) ? 1 : -1; //convert to x,y,z on this level - int x=p_x; - int y=p_y; - int z=p_z; - - x+=ofs[0]; - y+=ofs[1]; - z+=ofs[2]; + int x = p_x; + int y = p_y; + int z = p_z; - int ofs_x=0; - int ofs_y=0; - int ofs_z=0; - int size = 1<=size || y<0 || y>=size || z<0 || z>=size) { + if (x < 0 || x >= size || y < 0 || y >= size || z < 0 || z >= size) { //neighbour is out, can't use it - bake_cells_write[p_idx].used_sides&=~(1<= ofs_x + half) { - child|=1; - ofs_x+=half; + child |= 1; + ofs_x += half; } if (y >= ofs_y + half) { - child|=2; - ofs_y+=half; + child |= 2; + ofs_y += half; } if (z >= ofs_z + half) { - child|=4; - ofs_z+=half; + child |= 4; + ofs_z += half; } neighbour = bc->childs[child]; - if (neighbour==CHILD_EMPTY) { + if (neighbour == CHILD_EMPTY) { break; } - half>>=1; + half >>= 1; } - if (neighbour!=CHILD_EMPTY) { - bake_cells_write[p_idx].used_sides&=~(1<> (p_level+1); - for(int i=0;i<8;i++) { + float alpha_average = 0; + int half = cells_per_axis >> (p_level + 1); + for (int i = 0; i < 8; i++) { uint32_t child = bake_cells_write[p_idx].childs[i]; - if (child==CHILD_EMPTY) + if (child == CHILD_EMPTY) continue; + int nx = p_x; + int ny = p_y; + int nz = p_z; - int nx=p_x; - int ny=p_y; - int nz=p_z; + if (i & 1) + nx += half; + if (i & 2) + ny += half; + if (i & 4) + nz += half; - if (i&1) - nx+=half; - if (i&2) - ny+=half; - if (i&4) - nz+=half; - - _fixup_plot(child,p_level+1,nx,ny,nz); - alpha_average+=bake_cells_write[child].alpha; + _fixup_plot(child, p_level + 1, nx, ny, nz); + alpha_average += bake_cells_write[child].alpha; } - bake_cells_write[p_idx].alpha=alpha_average/8.0; - bake_cells_write[p_idx].light[0]=0; - bake_cells_write[p_idx].light[1]=0; - bake_cells_write[p_idx].light[2]=0; - bake_cells_write[p_idx].albedo[0]=0; - bake_cells_write[p_idx].albedo[1]=0; - bake_cells_write[p_idx].albedo[2]=0; - + bake_cells_write[p_idx].alpha = alpha_average / 8.0; + bake_cells_write[p_idx].light[0] = 0; + bake_cells_write[p_idx].light[1] = 0; + bake_cells_write[p_idx].light[2] = 0; + bake_cells_write[p_idx].albedo[0] = 0; + bake_cells_write[p_idx].albedo[1] = 0; + bake_cells_write[p_idx].albedo[2] = 0; } //clean up light - bake_cells_write[p_idx].light_pass=0; + bake_cells_write[p_idx].light_pass = 0; //find neighbours - - - } +void BakedLight::_bake_add_mesh(const Transform &p_xform, Ref &p_mesh) { -void BakedLight::_bake_add_mesh(const Transform& p_xform,Ref& p_mesh) { - + for (int i = 0; i < p_mesh->get_surface_count(); i++) { - for(int i=0;iget_surface_count();i++) { - - if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES) + if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) continue; //only triangles MaterialCache material = _get_material_cache(p_mesh->surface_get_material(i)); Array a = p_mesh->surface_get_arrays(i); - PoolVector vertices = a[Mesh::ARRAY_VERTEX]; - PoolVector::Read vr=vertices.read(); + PoolVector::Read vr = vertices.read(); PoolVector uv = a[Mesh::ARRAY_TEX_UV]; PoolVector::Read uvr; PoolVector index = a[Mesh::ARRAY_INDEX]; - bool read_uv=false; + bool read_uv = false; if (uv.size()) { - uvr=uv.read(); - read_uv=true; + uvr = uv.read(); + read_uv = true; } if (index.size()) { - int facecount = index.size()/3; - PoolVector::Read ir=index.read(); + int facecount = index.size() / 3; + PoolVector::Read ir = index.read(); - for(int j=0;j &p_mesh, bool &first) { + for (int i = 0; i < p_mesh->get_surface_count(); i++) { -void BakedLight::_bake_add_to_aabb(const Transform& p_xform,Ref& p_mesh,bool &first) { - - for(int i=0;iget_surface_count();i++) { - - if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES) + if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) continue; //only triangles Array a = p_mesh->surface_get_arrays(i); PoolVector vertices = a[Mesh::ARRAY_VERTEX]; int vc = vertices.size(); - PoolVector::Read vr=vertices.read(); + PoolVector::Read vr = vertices.read(); if (first) { - bounds.pos=p_xform.xform(vr[0]); - first=false; + bounds.pos = p_xform.xform(vr[0]); + first = false; } - - for(int j=0;j& p_mesh,bo void BakedLight::bake() { + bake_cells_alloc = 16; + bake_cells.resize(1 << bake_cells_alloc); + bake_cells_used = 1; + cells_per_axis = (1 << (cell_subdiv - 1)); + zero_alphas = 0; - bake_cells_alloc=16; - bake_cells.resize(1<::Element *E=geometries.front();E;E=E->next()) { + int count = 0; + for (Set::Element *E = geometries.front(); E; E = E->next()) { - print_line("aabb geom "+itos(count)+"/"+itos(geometries.size())); + print_line("aabb geom " + itos(count) + "/" + itos(geometries.size())); GeometryInstance *geom = E->get(); @@ -793,22 +779,22 @@ void BakedLight::bake() { Ref mesh = mesh_instance->get_mesh(); if (mesh.is_valid()) { - _bake_add_to_aabb(geom->get_relative_transform(this),mesh,aabb_first); + _bake_add_to_aabb(geom->get_relative_transform(this), mesh, aabb_first); } } count++; } - print_line("AABB: "+bounds); + print_line("AABB: " + bounds); ERR_FAIL_COND(aabb_first); bake_cells_write = bake_cells.write(); - count=0; + count = 0; - for (Set::Element *E=geometries.front();E;E=E->next()) { + for (Set::Element *E = geometries.front(); E; E = E->next()) { GeometryInstance *geom = E->get(); - print_line("plot geom "+itos(count)+"/"+itos(geometries.size())); + print_line("plot geom " + itos(count) + "/" + itos(geometries.size())); if (geom->cast_to()) { @@ -816,127 +802,107 @@ void BakedLight::bake() { Ref mesh = mesh_instance->get_mesh(); if (mesh.is_valid()) { - _bake_add_mesh(geom->get_relative_transform(this),mesh); + _bake_add_mesh(geom->get_relative_transform(this), mesh); } } count++; } + _fixup_plot(0, 0, 0, 0, 0); - _fixup_plot(0, 0,0,0,0); - - - bake_cells_write=PoolVector::Write(); + bake_cells_write = PoolVector::Write(); bake_cells.resize(bake_cells_used); - - - print_line("total bake cells used: "+itos(bake_cells_used)); - for(int i=0;i=0 && light_pass!=bake_cells_write[idx].light_pass) { + if (idx >= 0 && light_pass != bake_cells_write[idx].light_pass) { //hit something, add or remove light to it - Color albedo = Color(bake_cells_write[idx].albedo[0],bake_cells_write[idx].albedo[1],bake_cells_write[idx].albedo[2]); - bake_cells_write[idx].light[0]+=albedo.r*p_color.r*p_sign; - bake_cells_write[idx].light[1]+=albedo.g*p_color.g*p_sign; - bake_cells_write[idx].light[2]+=albedo.b*p_color.b*p_sign; - bake_cells_write[idx].light_pass=light_pass; - + Color albedo = Color(bake_cells_write[idx].albedo[0], bake_cells_write[idx].albedo[1], bake_cells_write[idx].albedo[2]); + bake_cells_write[idx].light[0] += albedo.r * p_color.r * p_sign; + bake_cells_write[idx].light[1] += albedo.g * p_color.g * p_sign; + bake_cells_write[idx].light[2] += albedo.b * p_color.b * p_sign; + bake_cells_write[idx].light_pass = light_pass; } - } else { - int half = cells_per_axis >> (p_level+1); + int half = cells_per_axis >> (p_level + 1); //go down - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { uint32_t child = bake_cells_write[p_idx].childs[i]; - if (child==CHILD_EMPTY) + if (child == CHILD_EMPTY) continue; - int nx=p_x; - int ny=p_y; - int nz=p_z; - - if (i&1) - nx+=half; - if (i&2) - ny+=half; - if (i&4) - nz+=half; + int nx = p_x; + int ny = p_y; + int nz = p_z; + if (i & 1) + nx += half; + if (i & 2) + ny += half; + if (i & 4) + nz += half; - _bake_directional(child,p_level+1,nx,ny,nz,p_dir,p_color,p_sign); + _bake_directional(child, p_level + 1, nx, ny, nz, p_dir, p_color, p_sign); } } } - - - -void BakedLight::_bake_light(Light* p_light) { +void BakedLight::_bake_light(Light *p_light) { if (p_light->cast_to()) { - DirectionalLight * dl = p_light->cast_to(); + DirectionalLight *dl = p_light->cast_to(); Transform rel_xf = dl->get_relative_transform(this); @@ -944,91 +910,79 @@ void BakedLight::_bake_light(Light* p_light) { Color color = dl->get_color(); float nrg = dl->get_param(Light::PARAM_ENERGY); - color.r*=nrg; - color.g*=nrg; - color.b*=nrg; + color.r *= nrg; + color.g *= nrg; + color.b *= nrg; light_pass++; - _bake_directional(0,0,0,0,0,light_dir,color,1); - + _bake_directional(0, 0, 0, 0, 0, light_dir, color, 1); } } - -void BakedLight::_upscale_light(int p_idx,int p_level) { - +void BakedLight::_upscale_light(int p_idx, int p_level) { //go down - float light_accum[3]={0,0,0}; - float alpha_accum=0; + float light_accum[3] = { 0, 0, 0 }; + float alpha_accum = 0; - bool check_children = p_level < (cell_subdiv -2); + bool check_children = p_level < (cell_subdiv - 2); - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { uint32_t child = bake_cells_write[p_idx].childs[i]; - if (child==CHILD_EMPTY) + if (child == CHILD_EMPTY) continue; if (check_children) { - _upscale_light(child,p_level+1); + _upscale_light(child, p_level + 1); } - light_accum[0]+=bake_cells_write[child].light[0]; - light_accum[1]+=bake_cells_write[child].light[1]; - light_accum[2]+=bake_cells_write[child].light[2]; - alpha_accum+=bake_cells_write[child].alpha; - + light_accum[0] += bake_cells_write[child].light[0]; + light_accum[1] += bake_cells_write[child].light[1]; + light_accum[2] += bake_cells_write[child].light[2]; + alpha_accum += bake_cells_write[child].alpha; } - bake_cells_write[p_idx].light[0]=light_accum[0]/8.0; - bake_cells_write[p_idx].light[1]=light_accum[1]/8.0; - bake_cells_write[p_idx].light[2]=light_accum[2]/8.0; - bake_cells_write[p_idx].alpha=alpha_accum/8.0; - + bake_cells_write[p_idx].light[0] = light_accum[0] / 8.0; + bake_cells_write[p_idx].light[1] = light_accum[1] / 8.0; + bake_cells_write[p_idx].light[2] = light_accum[2] / 8.0; + bake_cells_write[p_idx].alpha = alpha_accum / 8.0; } - void BakedLight::bake_lights() { - ERR_FAIL_COND(bake_cells.size()==0); + ERR_FAIL_COND(bake_cells.size() == 0); bake_cells_write = bake_cells.write(); - for(Set::Element *E=lights.front();E;E=E->next()) { + for (Set::Element *E = lights.front(); E; E = E->next()) { _bake_light(E->get()); } + _upscale_light(0, 0); - _upscale_light(0,0); - - bake_cells_write=PoolVector::Write(); - + bake_cells_write = PoolVector::Write(); } +Color BakedLight::_cone_trace(const Vector3 &p_from, const Vector3 &p_dir, float p_half_angle) { + Color color(0, 0, 0, 0); + float tha = Math::tan(p_half_angle); //tan half angle + Vector3 from = (p_from - bounds.pos) / bounds.size; //convert to 0..1 + from /= cells_per_axis; //convert to voxels of size 1 + Vector3 dir = (p_dir / bounds.size).normalized(); -Color BakedLight::_cone_trace(const Vector3& p_from, const Vector3& p_dir, float p_half_angle) { - - - Color color(0,0,0,0); - float tha = Math::tan(p_half_angle);//tan half angle - Vector3 from =(p_from-bounds.pos)/bounds.size; //convert to 0..1 - from/=cells_per_axis; //convert to voxels of size 1 - Vector3 dir = (p_dir/bounds.size).normalized(); - - float max_dist = Vector3(cells_per_axis,cells_per_axis,cells_per_axis).length(); + float max_dist = Vector3(cells_per_axis, cells_per_axis, cells_per_axis).length(); float dist = 1.0; // self occlusion in flat surfaces - float alpha=0; + float alpha = 0; - - while(dist < max_dist && alpha < 0.95) { + while (dist < max_dist && alpha < 0.95) { #if 0 // smallest sample diameter possible is the voxel size @@ -1149,56 +1103,55 @@ Color BakedLight::_cone_trace(const Vector3& p_from, const Vector3& p_dir, float float diameter = 1.0; Vector3 sample_pos = from + dist * dir; - Color m(0,0,0,0); + Color m(0, 0, 0, 0); { int x = Math::floor(sample_pos.x); int y = Math::floor(sample_pos.y); int z = Math::floor(sample_pos.z); - int ofs_x=0; - int ofs_y=0; - int ofs_z=0; + int ofs_x = 0; + int ofs_y = 0; + int ofs_z = 0; int size = cells_per_axis; - int half=size/2; + int half = size / 2; - bool outside=x<0 || x>=size || y<0 || y>=size || z<0 || z>=size; + bool outside = x < 0 || x >= size || y < 0 || y >= size || z < 0 || z >= size; if (!outside) { + uint32_t cell = 0; - uint32_t cell=0; - - for(int i=0;i= ofs_x + half) { - child|=1; - ofs_x+=half; + child |= 1; + ofs_x += half; } if (y >= ofs_y + half) { - child|=2; - ofs_y+=half; + child |= 2; + ofs_y += half; } if (z >= ofs_z + half) { - child|=4; - ofs_z+=half; + child |= 4; + ofs_z += half; } cell = bc->childs[child]; - if (cell==CHILD_EMPTY) + if (cell == CHILD_EMPTY) break; - half>>=1; + half >>= 1; } - if (cell!=CHILD_EMPTY) { + if (cell != CHILD_EMPTY) { - m.r=bake_cells_write[cell].light[0]; - m.g=bake_cells_write[cell].light[1]; - m.b=bake_cells_write[cell].light[2]; - m.a=bake_cells_write[cell].alpha; + m.r = bake_cells_write[cell].light[0]; + m.g = bake_cells_write[cell].light[1]; + m.b = bake_cells_write[cell].light[2]; + m.a = bake_cells_write[cell].alpha; } } } @@ -1219,72 +1172,64 @@ Color BakedLight::_cone_trace(const Vector3& p_from, const Vector3& p_dir, float return color; } +void BakedLight::_bake_radiance(int p_idx, int p_level, int p_x, int p_y, int p_z) { - -void BakedLight::_bake_radiance(int p_idx, int p_level, int p_x,int p_y,int p_z) { - - - - - if (p_level==cell_subdiv-1) { + if (p_level == cell_subdiv - 1) { const int NUM_CONES = 6; Vector3 cone_directions[6] = { - Vector3(1, 0, 0), - Vector3(0.5, 0.866025, 0), - Vector3( 0.5, 0.267617, 0.823639), - Vector3( 0.5, -0.700629, 0.509037), - Vector3( 0.5, -0.700629, -0.509037), - Vector3( 0.5, 0.267617, -0.823639) - }; - float coneWeights[6] = {0.25, 0.15, 0.15, 0.15, 0.15, 0.15}; - - Vector3 pos = (Vector3(p_x,p_y,p_z)/float(cells_per_axis))*bounds.size+bounds.pos; - Vector3 voxel_size = bounds.size/float(cells_per_axis); - pos+=voxel_size*0.5; + Vector3(1, 0, 0), + Vector3(0.5, 0.866025, 0), + Vector3(0.5, 0.267617, 0.823639), + Vector3(0.5, -0.700629, 0.509037), + Vector3(0.5, -0.700629, -0.509037), + Vector3(0.5, 0.267617, -0.823639) + }; + float coneWeights[6] = { 0.25, 0.15, 0.15, 0.15, 0.15, 0.15 }; + + Vector3 pos = (Vector3(p_x, p_y, p_z) / float(cells_per_axis)) * bounds.size + bounds.pos; + Vector3 voxel_size = bounds.size / float(cells_per_axis); + pos += voxel_size * 0.5; Color accum; - bake_cells_write[p_idx].light[0]=0; - bake_cells_write[p_idx].light[1]=0; - bake_cells_write[p_idx].light[2]=0; + bake_cells_write[p_idx].light[0] = 0; + bake_cells_write[p_idx].light[1] = 0; + bake_cells_write[p_idx].light[2] = 0; - int freepix=0; - for(int i=0;i<6;i++) { + int freepix = 0; + for (int i = 0; i < 6; i++) { - if (!(bake_cells_write[p_idx].used_sides&(1<> (p_level+1); + int half = cells_per_axis >> (p_level + 1); //go down - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { uint32_t child = bake_cells_write[p_idx].childs[i]; - if (child==CHILD_EMPTY) + if (child == CHILD_EMPTY) continue; - int nx=p_x; - int ny=p_y; - int nz=p_z; - - if (i&1) - nx+=half; - if (i&2) - ny+=half; - if (i&4) - nz+=half; + int nx = p_x; + int ny = p_y; + int nz = p_z; + if (i & 1) + nx += half; + if (i & 2) + ny += half; + if (i & 4) + nz += half; - _bake_radiance(child,p_level+1,nx,ny,nz); + _bake_radiance(child, p_level + 1, nx, ny, nz); } } } void BakedLight::bake_radiance() { - ERR_FAIL_COND(bake_cells.size()==0); + ERR_FAIL_COND(bake_cells.size() == 0); bake_cells_write = bake_cells.write(); - _bake_radiance(0,0,0,0,0); - - bake_cells_write=PoolVector::Write(); + _bake_radiance(0, 0, 0, 0, 0); + bake_cells_write = PoolVector::Write(); } -int BakedLight::_find_cell(int x,int y, int z) { - +int BakedLight::_find_cell(int x, int y, int z) { - uint32_t cell=0; + uint32_t cell = 0; - int ofs_x=0; - int ofs_y=0; - int ofs_z=0; + int ofs_x = 0; + int ofs_y = 0; + int ofs_z = 0; int size = cells_per_axis; - int half=size/2; + int half = size / 2; - if (x<0 || x>=size) + if (x < 0 || x >= size) return -1; - if (y<0 || y>=size) + if (y < 0 || y >= size) return -1; - if (z<0 || z>=size) + if (z < 0 || z >= size) return -1; - for(int i=0;i= ofs_x + half) { - child|=1; - ofs_x+=half; + child |= 1; + ofs_x += half; } if (y >= ofs_y + half) { - child|=2; - ofs_y+=half; + child |= 2; + ofs_y += half; } if (z >= ofs_z + half) { - child|=4; - ofs_z+=half; + child |= 4; + ofs_z += half; } cell = bc->childs[child]; - if (cell==CHILD_EMPTY) + if (cell == CHILD_EMPTY) return -1; - half>>=1; + half >>= 1; } return cell; - } - -int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) { +int BakedLight::_plot_ray(const Vector3 &p_from, const Vector3 &p_to) { Vector3 from = (p_from - bounds.pos) / bounds.size; Vector3 to = (p_to - bounds.pos) / bounds.size; - int x1 = Math::floor(from.x*cells_per_axis); - int y1 = Math::floor(from.y*cells_per_axis); - int z1 = Math::floor(from.z*cells_per_axis); - - int x2 = Math::floor(to.x*cells_per_axis); - int y2 = Math::floor(to.y*cells_per_axis); - int z2 = Math::floor(to.z*cells_per_axis); + int x1 = Math::floor(from.x * cells_per_axis); + int y1 = Math::floor(from.y * cells_per_axis); + int z1 = Math::floor(from.z * cells_per_axis); + int x2 = Math::floor(to.x * cells_per_axis); + int y2 = Math::floor(to.y * cells_per_axis); + int z2 = Math::floor(to.z * cells_per_axis); int i, dx, dy, dz, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2; int point[3]; @@ -1459,8 +1397,8 @@ int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) { err_1 = dy2 - l; err_2 = dz2 - l; for (i = 0; i < l; i++) { - int cell = _find_cell(point[0],point[1],point[2]); - if (cell>=0) + int cell = _find_cell(point[0], point[1], point[2]); + if (cell >= 0) return cell; if (err_1 > 0) { @@ -1479,8 +1417,8 @@ int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) { err_1 = dx2 - m; err_2 = dz2 - m; for (i = 0; i < m; i++) { - int cell = _find_cell(point[0],point[1],point[2]); - if (cell>=0) + int cell = _find_cell(point[0], point[1], point[2]); + if (cell >= 0) return cell; if (err_1 > 0) { point[0] += x_inc; @@ -1498,8 +1436,8 @@ int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) { err_1 = dy2 - n; err_2 = dx2 - n; for (i = 0; i < n; i++) { - int cell = _find_cell(point[0],point[1],point[2]); - if (cell>=0) + int cell = _find_cell(point[0], point[1], point[2]); + if (cell >= 0) return cell; if (err_1 > 0) { @@ -1515,14 +1453,12 @@ int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) { point[2] += z_inc; } } - return _find_cell(point[0],point[1],point[2]); - + return _find_cell(point[0], point[1], point[2]); } - void BakedLight::set_cell_subdiv(int p_subdiv) { - cell_subdiv=p_subdiv; + cell_subdiv = p_subdiv; //VS::get_singleton()->baked_light_set_subdivision(baked_light,p_subdiv); } @@ -1532,77 +1468,67 @@ int BakedLight::get_cell_subdiv() const { return cell_subdiv; } - - Rect3 BakedLight::get_aabb() const { - return Rect3(Vector3(0,0,0),Vector3(1,1,1)); + return Rect3(Vector3(0, 0, 0), Vector3(1, 1, 1)); } PoolVector BakedLight::get_faces(uint32_t p_usage_flags) const { return PoolVector(); } - String BakedLight::get_configuration_warning() const { return String(); } +void BakedLight::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb, DebugMode p_mode, Ref &p_multimesh, int &idx) { -void BakedLight::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,DebugMode p_mode,Ref &p_multimesh,int &idx) { + if (p_level == cell_subdiv - 1) { - - if (p_level==cell_subdiv-1) { - - Vector3 center = p_aabb.pos+p_aabb.size*0.5; + Vector3 center = p_aabb.pos + p_aabb.size * 0.5; Transform xform; - xform.origin=center; - xform.basis.scale(p_aabb.size*0.5); - p_multimesh->set_instance_transform(idx,xform); + xform.origin = center; + xform.basis.scale(p_aabb.size * 0.5); + p_multimesh->set_instance_transform(idx, xform); Color col; - switch(p_mode) { + switch (p_mode) { case DEBUG_ALBEDO: { - col=Color(bake_cells_write[p_idx].albedo[0],bake_cells_write[p_idx].albedo[1],bake_cells_write[p_idx].albedo[2]); + col = Color(bake_cells_write[p_idx].albedo[0], bake_cells_write[p_idx].albedo[1], bake_cells_write[p_idx].albedo[2]); } break; case DEBUG_LIGHT: { - col=Color(bake_cells_write[p_idx].light[0],bake_cells_write[p_idx].light[1],bake_cells_write[p_idx].light[2]); - Color colr=Color(bake_cells_write[p_idx].radiance[0],bake_cells_write[p_idx].radiance[1],bake_cells_write[p_idx].radiance[2]); - col.r+=colr.r; - col.g+=colr.g; - col.b+=colr.b; + col = Color(bake_cells_write[p_idx].light[0], bake_cells_write[p_idx].light[1], bake_cells_write[p_idx].light[2]); + Color colr = Color(bake_cells_write[p_idx].radiance[0], bake_cells_write[p_idx].radiance[1], bake_cells_write[p_idx].radiance[2]); + col.r += colr.r; + col.g += colr.g; + col.b += colr.b; } break; - } - p_multimesh->set_instance_color(idx,col); - + p_multimesh->set_instance_color(idx, col); idx++; } else { - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - if (bake_cells_write[p_idx].childs[i]==CHILD_EMPTY) + if (bake_cells_write[p_idx].childs[i] == CHILD_EMPTY) continue; - Rect3 aabb=p_aabb; - aabb.size*=0.5; + Rect3 aabb = p_aabb; + aabb.size *= 0.5; - if (i&1) - aabb.pos.x+=aabb.size.x; - if (i&2) - aabb.pos.y+=aabb.size.y; - if (i&4) - aabb.pos.z+=aabb.size.z; + if (i & 1) + aabb.pos.x += aabb.size.x; + if (i & 2) + aabb.pos.y += aabb.size.y; + if (i & 4) + aabb.pos.z += aabb.size.z; - _debug_mesh(bake_cells_write[p_idx].childs[i],p_level+1,aabb,p_mode,p_multimesh,idx); + _debug_mesh(bake_cells_write[p_idx].childs[i], p_level + 1, aabb, p_mode, p_multimesh, idx); } - } - } - void BakedLight::create_debug_mesh(DebugMode p_mode) { Ref mm; @@ -1610,13 +1536,11 @@ void BakedLight::create_debug_mesh(DebugMode p_mode) { mm->set_transform_format(MultiMesh::TRANSFORM_3D); mm->set_color_format(MultiMesh::COLOR_8BIT); - mm->set_instance_count(bake_cells_level_used[cell_subdiv-1]); + mm->set_instance_count(bake_cells_level_used[cell_subdiv - 1]); Ref mesh; mesh.instance(); - - { Array arr; arr.resize(Mesh::ARRAY_MAX); @@ -1624,83 +1548,76 @@ void BakedLight::create_debug_mesh(DebugMode p_mode) { PoolVector vertices; PoolVector colors; - int vtx_idx=0; - #define ADD_VTX(m_idx);\ - vertices.push_back( face_points[m_idx] );\ - colors.push_back( Color(1,1,1,1) );\ - vtx_idx++;\ - - for (int i=0;i<6;i++) { + int vtx_idx = 0; +#define ADD_VTX(m_idx) \ + ; \ + vertices.push_back(face_points[m_idx]); \ + colors.push_back(Color(1, 1, 1, 1)); \ + vtx_idx++; + for (int i = 0; i < 6; i++) { Vector3 face_points[4]; - for (int j=0;j<4;j++) { + for (int j = 0; j < 4; j++) { float v[3]; - v[0]=1.0; - v[1]=1-2*((j>>1)&1); - v[2]=v[1]*(1-2*(j&1)); + v[0] = 1.0; + v[1] = 1 - 2 * ((j >> 1) & 1); + v[2] = v[1] * (1 - 2 * (j & 1)); - for (int k=0;k<3;k++) { + for (int k = 0; k < 3; k++) { - if (i<3) - face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1); + if (i < 3) + face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1); else - face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1); + face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1); } } - //tri 1 + //tri 1 ADD_VTX(0); ADD_VTX(1); ADD_VTX(2); - //tri 2 + //tri 2 ADD_VTX(2); ADD_VTX(3); ADD_VTX(0); - } - - arr[Mesh::ARRAY_VERTEX]=vertices; - arr[Mesh::ARRAY_COLOR]=colors; - mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,arr); + arr[Mesh::ARRAY_VERTEX] = vertices; + arr[Mesh::ARRAY_COLOR] = colors; + mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr); } { Ref fsm; fsm.instance(); - fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true); - fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true); - fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true); - fsm->set_albedo(Color(1,1,1,1)); + fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); + fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); + fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true); + fsm->set_albedo(Color(1, 1, 1, 1)); - mesh->surface_set_material(0,fsm); + mesh->surface_set_material(0, fsm); } mm->set_mesh(mesh); - bake_cells_write = bake_cells.write(); + int idx = 0; + _debug_mesh(0, 0, bounds, p_mode, mm, idx); + print_line("written: " + itos(idx) + " total: " + itos(bake_cells_level_used[cell_subdiv - 1])); - int idx=0; - _debug_mesh(0,0,bounds,p_mode,mm,idx); - - print_line("written: "+itos(idx)+" total: "+itos(bake_cells_level_used[cell_subdiv-1])); - - - MultiMeshInstance *mmi = memnew( MultiMeshInstance ); + MultiMeshInstance *mmi = memnew(MultiMeshInstance); mmi->set_multimesh(mm); add_child(mmi); #ifdef TOOLS_ENABLED - if (get_tree()->get_edited_scene_root()==this){ + if (get_tree()->get_edited_scene_root() == this) { mmi->set_owner(this); } else { mmi->set_owner(get_owner()); - } #else mmi->set_owner(get_owner()); @@ -1715,45 +1632,41 @@ void BakedLight::_debug_mesh_light() { create_debug_mesh(DEBUG_LIGHT); } - void BakedLight::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_cell_subdiv","steps"),&BakedLight::set_cell_subdiv); - ClassDB::bind_method(D_METHOD("get_cell_subdiv"),&BakedLight::get_cell_subdiv); - - ClassDB::bind_method(D_METHOD("bake"),&BakedLight::bake); - ClassDB::set_method_flags(get_class_static(),_scs_create("bake"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); + ClassDB::bind_method(D_METHOD("set_cell_subdiv", "steps"), &BakedLight::set_cell_subdiv); + ClassDB::bind_method(D_METHOD("get_cell_subdiv"), &BakedLight::get_cell_subdiv); - ClassDB::bind_method(D_METHOD("bake_lights"),&BakedLight::bake_lights); - ClassDB::set_method_flags(get_class_static(),_scs_create("bake_lights"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); + ClassDB::bind_method(D_METHOD("bake"), &BakedLight::bake); + ClassDB::set_method_flags(get_class_static(), _scs_create("bake"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); - ClassDB::bind_method(D_METHOD("bake_radiance"),&BakedLight::bake_radiance); - ClassDB::set_method_flags(get_class_static(),_scs_create("bake_radiance"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); + ClassDB::bind_method(D_METHOD("bake_lights"), &BakedLight::bake_lights); + ClassDB::set_method_flags(get_class_static(), _scs_create("bake_lights"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); - ClassDB::bind_method(D_METHOD("debug_mesh_albedo"),&BakedLight::_debug_mesh_albedo); - ClassDB::set_method_flags(get_class_static(),_scs_create("debug_mesh_albedo"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); + ClassDB::bind_method(D_METHOD("bake_radiance"), &BakedLight::bake_radiance); + ClassDB::set_method_flags(get_class_static(), _scs_create("bake_radiance"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); + ClassDB::bind_method(D_METHOD("debug_mesh_albedo"), &BakedLight::_debug_mesh_albedo); + ClassDB::set_method_flags(get_class_static(), _scs_create("debug_mesh_albedo"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); - ClassDB::bind_method(D_METHOD("debug_mesh_light"),&BakedLight::_debug_mesh_light); - ClassDB::set_method_flags(get_class_static(),_scs_create("debug_mesh_light"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); - - ADD_PROPERTY(PropertyInfo(Variant::INT,"cell_subdiv"),"set_cell_subdiv","get_cell_subdiv"); - ADD_SIGNAL( MethodInfo("baked_light_changed")); + ClassDB::bind_method(D_METHOD("debug_mesh_light"), &BakedLight::_debug_mesh_light); + ClassDB::set_method_flags(get_class_static(), _scs_create("debug_mesh_light"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); + ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_subdiv"), "set_cell_subdiv", "get_cell_subdiv"); + ADD_SIGNAL(MethodInfo("baked_light_changed")); } BakedLight::BakedLight() { //baked_light=VisualServer::get_singleton()->baked_light_create(); - VS::get_singleton()->instance_set_base(get_instance(),baked_light); + VS::get_singleton()->instance_set_base(get_instance(), baked_light); - cell_subdiv=8; - bake_texture_size=128; - color_scan_cell_width=8; - light_pass=0; + cell_subdiv = 8; + bake_texture_size = 128; + color_scan_cell_width = 8; + light_pass = 0; } - BakedLight::~BakedLight() { VS::get_singleton()->free(baked_light); diff --git a/scene/3d/baked_light_instance.h b/scene/3d/baked_light_instance.h index 2fda26ece..2180f8b17 100644 --- a/scene/3d/baked_light_instance.h +++ b/scene/3d/baked_light_instance.h @@ -29,16 +29,15 @@ #ifndef BAKED_LIGHT_INSTANCE_H #define BAKED_LIGHT_INSTANCE_H +#include "scene/3d/multimesh_instance.h" #include "scene/3d/visual_instance.h" #include "scene/resources/baked_light.h" -#include "scene/3d/multimesh_instance.h" - class BakedLightBaker; class Light; class BakedLight : public VisualInstance { - GDCLASS(BakedLight,VisualInstance); + GDCLASS(BakedLight, VisualInstance); public: enum DebugMode { @@ -53,10 +52,9 @@ private: int cells_per_axis; enum { - CHILD_EMPTY=0xFFFFFFFF, + CHILD_EMPTY = 0xFFFFFFFF, }; - /* BAKE DATA */ struct BakeCell { @@ -70,22 +68,21 @@ private: uint32_t light_pass; //used for baking light BakeCell() { - for(int i=0;i<8;i++) { - childs[i]=0xFFFFFFFF; + for (int i = 0; i < 8; i++) { + childs[i] = 0xFFFFFFFF; } - for(int i=0;i<3;i++) { - light[i]=0; - albedo[i]=0; - radiance[i]=0; + for (int i = 0; i < 3; i++) { + light[i] = 0; + albedo[i] = 0; + radiance[i] = 0; } - alpha=0; - light_pass=0; - used_sides=0; + alpha = 0; + light_pass = 0; + used_sides = 0; } }; - int bake_texture_size; int color_scan_cell_width; @@ -95,12 +92,9 @@ private: Vector emission; }; - Vector _get_bake_texture(Image &p_image, const Color &p_color); - - - Map,MaterialCache> material_cache; + Map, MaterialCache> material_cache; MaterialCache _get_material_cache(Ref p_material); int bake_cells_alloc; @@ -110,42 +104,38 @@ private: PoolVector bake_cells; PoolVector::Write bake_cells_write; - - - void _plot_face(int p_idx,int p_level,const Vector3 *p_vtx,const Vector2* p_uv, const MaterialCache& p_material,const Rect3& p_aabb); + void _plot_face(int p_idx, int p_level, const Vector3 *p_vtx, const Vector2 *p_uv, const MaterialCache &p_material, const Rect3 &p_aabb); void _fixup_plot(int p_idx, int p_level, int p_x, int p_y, int p_z); - void _bake_add_mesh(const Transform& p_xform,Ref& p_mesh); - void _bake_add_to_aabb(const Transform& p_xform,Ref& p_mesh,bool &first); + void _bake_add_mesh(const Transform &p_xform, Ref &p_mesh); + void _bake_add_to_aabb(const Transform &p_xform, Ref &p_mesh, bool &first); - void _debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,DebugMode p_mode,Ref &p_multimesh,int &idx); + void _debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb, DebugMode p_mode, Ref &p_multimesh, int &idx); void _debug_mesh_albedo(); void _debug_mesh_light(); - - _FORCE_INLINE_ int _find_cell(int x,int y, int z); - int _plot_ray(const Vector3& p_from, const Vector3& p_to); + _FORCE_INLINE_ int _find_cell(int x, int y, int z); + int _plot_ray(const Vector3 &p_from, const Vector3 &p_to); uint32_t light_pass; + void _bake_directional(int p_idx, int p_level, int p_x, int p_y, int p_z, const Vector3 &p_dir, const Color &p_color, int p_sign); + void _upscale_light(int p_idx, int p_level); + void _bake_light(Light *p_light); - void _bake_directional(int p_idx, int p_level, int p_x,int p_y,int p_z,const Vector3& p_dir,const Color& p_color,int p_sign); - void _upscale_light(int p_idx,int p_level); - void _bake_light(Light* p_light); + Color _cone_trace(const Vector3 &p_from, const Vector3 &p_dir, float p_half_angle); + void _bake_radiance(int p_idx, int p_level, int p_x, int p_y, int p_z); - Color _cone_trace(const Vector3& p_from, const Vector3& p_dir, float p_half_angle); - void _bake_radiance(int p_idx, int p_level, int p_x,int p_y,int p_z); + friend class GeometryInstance; -friend class GeometryInstance; + Set geometries; + friend class Light; - Set geometries; -friend class Light; + Set lights; - Set lights; protected: - static void _bind_methods(); -public: +public: void set_cell_subdiv(int p_subdiv); int get_cell_subdiv() const; @@ -153,7 +143,6 @@ public: void bake_lights(); void bake_radiance(); - void create_debug_mesh(DebugMode p_mode); virtual Rect3 get_aabb() const; @@ -165,7 +154,6 @@ public: ~BakedLight(); }; - #if 0 class BakedLightSampler : public VisualInstance { GDCLASS(BakedLightSampler,VisualInstance); diff --git a/scene/3d/body_shape.cpp b/scene/3d/body_shape.cpp index af3fe3c0a..840380657 100644 --- a/scene/3d/body_shape.cpp +++ b/scene/3d/body_shape.cpp @@ -27,14 +27,14 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "body_shape.h" -#include "servers/visual_server.h" -#include "scene/resources/sphere_shape.h" -#include "scene/resources/ray_shape.h" #include "scene/resources/box_shape.h" #include "scene/resources/capsule_shape.h" -#include "scene/resources/convex_polygon_shape.h" #include "scene/resources/concave_polygon_shape.h" +#include "scene/resources/convex_polygon_shape.h" #include "scene/resources/plane_shape.h" +#include "scene/resources/ray_shape.h" +#include "scene/resources/sphere_shape.h" +#include "servers/visual_server.h" //TODO: Implement CylinderShape and HeightMapShape? #include "mesh_instance.h" #include "physics_body.h" @@ -48,7 +48,6 @@ void CollisionShape::_update_body() { return; if (get_parent() && get_parent()->cast_to()) get_parent()->cast_to()->_update_shapes_from_children(); - } void CollisionShape::make_convex_from_brothers() { @@ -57,12 +56,12 @@ void CollisionShape::make_convex_from_brothers() { if (!p) return; - for(int i=0;iget_child_count();i++) { + for (int i = 0; i < p->get_child_count(); i++) { Node *n = p->get_child(i); if (n->cast_to()) { - MeshInstance *mi=n->cast_to(); + MeshInstance *mi = n->cast_to(); Ref m = mi->get_mesh(); if (m.is_valid()) { @@ -71,7 +70,6 @@ void CollisionShape::make_convex_from_brothers() { } } } - } /* @@ -302,32 +300,32 @@ void CollisionShape::_update_indicator() { } */ -void CollisionShape::_add_to_collision_object(Object* p_cshape) { +void CollisionShape::_add_to_collision_object(Object *p_cshape) { if (unparenting) return; - CollisionObject *co=p_cshape->cast_to(); + CollisionObject *co = p_cshape->cast_to(); ERR_FAIL_COND(!co); if (shape.is_valid()) { - update_shape_index=co->get_shape_count(); - co->add_shape(shape,get_transform()); + update_shape_index = co->get_shape_count(); + co->add_shape(shape, get_transform()); if (trigger) - co->set_shape_as_trigger( co->get_shape_count() -1, true ); + co->set_shape_as_trigger(co->get_shape_count() - 1, true); } else { - update_shape_index=-1; + update_shape_index = -1; } } void CollisionShape::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - unparenting=false; - can_update_body=get_tree()->is_editor_hint(); + unparenting = false; + can_update_body = get_tree()->is_editor_hint(); set_notify_local_transform(!can_update_body); if (get_tree()->is_debugging_collisions_hint()) { @@ -343,19 +341,19 @@ void CollisionShape::_notification(int p_what) { } } break; case NOTIFICATION_EXIT_TREE: { - /* if (indicator_instance.is_valid()) { + /* if (indicator_instance.is_valid()) { VisualServer::get_singleton()->free(indicator_instance); indicator_instance=RID(); }*/ - can_update_body=false; + can_update_body = false; set_notify_local_transform(false); if (debug_shape) { debug_shape->queue_delete(); - debug_shape=NULL; + debug_shape = NULL; } } break; case NOTIFICATION_UNPARENTED: { - unparenting=true; + unparenting = true; if (can_update_body && updating_body) _update_body(); } break; @@ -365,34 +363,29 @@ void CollisionShape::_notification(int p_what) { } break; case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: { - if (!can_update_body && update_shape_index>=0) { + if (!can_update_body && update_shape_index >= 0) { CollisionObject *co = get_parent()->cast_to(); if (co) { - co->set_shape_transform(update_shape_index,get_transform()); + co->set_shape_transform(update_shape_index, get_transform()); } } } break; - } } - void CollisionShape::resource_changed(RES res) { update_gizmo(); - - } void CollisionShape::_set_update_shape_index(int p_index) { - - update_shape_index=p_index; + update_shape_index = p_index; } -int CollisionShape::_get_update_shape_index() const{ +int CollisionShape::_get_update_shape_index() const { return update_shape_index; } @@ -410,45 +403,42 @@ String CollisionShape::get_configuration_warning() const { return String(); } - void CollisionShape::_bind_methods() { //not sure if this should do anything - ClassDB::bind_method(D_METHOD("resource_changed","resource"),&CollisionShape::resource_changed); - ClassDB::bind_method(D_METHOD("set_shape","shape"),&CollisionShape::set_shape); - ClassDB::bind_method(D_METHOD("get_shape"),&CollisionShape::get_shape); - ClassDB::bind_method(D_METHOD("_add_to_collision_object"),&CollisionShape::_add_to_collision_object); - ClassDB::bind_method(D_METHOD("set_trigger","enable"),&CollisionShape::set_trigger); - ClassDB::bind_method(D_METHOD("is_trigger"),&CollisionShape::is_trigger); - ClassDB::bind_method(D_METHOD("make_convex_from_brothers"),&CollisionShape::make_convex_from_brothers); - ClassDB::set_method_flags("CollisionShape","make_convex_from_brothers",METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); - ClassDB::bind_method(D_METHOD("_set_update_shape_index","index"),&CollisionShape::_set_update_shape_index); - ClassDB::bind_method(D_METHOD("_get_update_shape_index"),&CollisionShape::_get_update_shape_index); + ClassDB::bind_method(D_METHOD("resource_changed", "resource"), &CollisionShape::resource_changed); + ClassDB::bind_method(D_METHOD("set_shape", "shape"), &CollisionShape::set_shape); + ClassDB::bind_method(D_METHOD("get_shape"), &CollisionShape::get_shape); + ClassDB::bind_method(D_METHOD("_add_to_collision_object"), &CollisionShape::_add_to_collision_object); + ClassDB::bind_method(D_METHOD("set_trigger", "enable"), &CollisionShape::set_trigger); + ClassDB::bind_method(D_METHOD("is_trigger"), &CollisionShape::is_trigger); + ClassDB::bind_method(D_METHOD("make_convex_from_brothers"), &CollisionShape::make_convex_from_brothers); + ClassDB::set_method_flags("CollisionShape", "make_convex_from_brothers", METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); + ClassDB::bind_method(D_METHOD("_set_update_shape_index", "index"), &CollisionShape::_set_update_shape_index); + ClassDB::bind_method(D_METHOD("_get_update_shape_index"), &CollisionShape::_get_update_shape_index); - ClassDB::bind_method(D_METHOD("get_collision_object_shape_index"),&CollisionShape::get_collision_object_shape_index); + ClassDB::bind_method(D_METHOD("get_collision_object_shape_index"), &CollisionShape::get_collision_object_shape_index); - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape"), "set_shape", "get_shape"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"trigger"),"set_trigger","is_trigger"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "_update_shape_index", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR), "_set_update_shape_index", "_get_update_shape_index"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape"), "set_shape", "get_shape"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "trigger"), "set_trigger", "is_trigger"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "_update_shape_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_update_shape_index", "_get_update_shape_index"); } - void CollisionShape::set_shape(const Ref &p_shape) { if (!shape.is_null()) shape->unregister_owner(this); - shape=p_shape; + shape = p_shape; if (!shape.is_null()) shape->register_owner(this); update_gizmo(); if (updating_body) { _update_body(); - } else if (can_update_body && update_shape_index>=0 && is_inside_tree()){ + } else if (can_update_body && update_shape_index >= 0 && is_inside_tree()) { CollisionObject *co = get_parent()->cast_to(); if (co) { - co->set_shape(update_shape_index,p_shape); + co->set_shape(update_shape_index, p_shape); } - } } @@ -457,9 +447,8 @@ Ref CollisionShape::get_shape() const { return shape; } - void CollisionShape::set_updating_body(bool p_update) { - updating_body=p_update; + updating_body = p_update; } bool CollisionShape::is_updating_body() const { @@ -469,31 +458,31 @@ bool CollisionShape::is_updating_body() const { void CollisionShape::set_trigger(bool p_trigger) { - trigger=p_trigger; - if (updating_body) { - _update_body(); - } else if (can_update_body && update_shape_index>=0 && is_inside_tree()){ - CollisionObject *co = get_parent()->cast_to(); - if (co) { - co->set_shape_as_trigger(update_shape_index,p_trigger); - } - } + trigger = p_trigger; + if (updating_body) { + _update_body(); + } else if (can_update_body && update_shape_index >= 0 && is_inside_tree()) { + CollisionObject *co = get_parent()->cast_to(); + if (co) { + co->set_shape_as_trigger(update_shape_index, p_trigger); + } + } } -bool CollisionShape::is_trigger() const{ +bool CollisionShape::is_trigger() const { - return trigger; + return trigger; } CollisionShape::CollisionShape() { //indicator = VisualServer::get_singleton()->mesh_create(); - updating_body=true; - unparenting=false; - update_shape_index=-1; - trigger=false; - can_update_body=false; - debug_shape=NULL; + updating_body = true; + unparenting = false; + update_shape_index = -1; + trigger = false; + can_update_body = false; + debug_shape = NULL; } CollisionShape::~CollisionShape() { @@ -504,10 +493,9 @@ CollisionShape::~CollisionShape() { void CollisionShape::_create_debug_shape() { - if (debug_shape) { debug_shape->queue_delete(); - debug_shape=NULL; + debug_shape = NULL; } Ref s = get_shape(); @@ -515,37 +503,35 @@ void CollisionShape::_create_debug_shape() { if (s.is_null()) return; - Ref mesh = s->get_debug_mesh(); - MeshInstance *mi = memnew( MeshInstance ); + MeshInstance *mi = memnew(MeshInstance); mi->set_mesh(mesh); add_child(mi); - debug_shape=mi; - + debug_shape = mi; } #if 0 #include "body_volume.h" -#include "scene/3d/physics_body.h" #include "geometry.h" +#include "scene/3d/physics_body.h" -#define ADD_TRIANGLE( m_a, m_b, m_c, m_color)\ -{\ - Vector points;\ - points.resize(3);\ - points[0]=m_a;\ - points[1]=m_b;\ - points[2]=m_c;\ - Vector colors;\ - colors.resize(3);\ - colors[0]=m_color;\ - colors[1]=m_color;\ - colors[2]=m_color;\ - vs->poly_add_primitive(p_indicator,points,Vector(),colors,Vector());\ -} +#define ADD_TRIANGLE(m_a, m_b, m_c, m_color) \ + { \ + Vector points; \ + points.resize(3); \ + points[0] = m_a; \ + points[1] = m_b; \ + points[2] = m_c; \ + Vector colors; \ + colors.resize(3); \ + colors[0] = m_color; \ + colors[1] = m_color; \ + colors[2] = m_color; \ + vs->poly_add_primitive(p_indicator, points, Vector(), colors, Vector()); \ + } void CollisionShape::_notification(int p_what) { diff --git a/scene/3d/body_shape.h b/scene/3d/body_shape.h index a7c367825..137a6cd9f 100644 --- a/scene/3d/body_shape.h +++ b/scene/3d/body_shape.h @@ -34,7 +34,7 @@ class CollisionShape : public Spatial { - GDCLASS( CollisionShape, Spatial ); + GDCLASS(CollisionShape, Spatial); OBJ_CATEGORY("3D Physics Nodes"); Ref shape; @@ -50,7 +50,7 @@ class CollisionShape : public Spatial { RID indicator_instance; */ - Node* debug_shape; + Node *debug_shape; void resource_changed(RES res); @@ -63,7 +63,7 @@ class CollisionShape : public Spatial { int update_shape_index; void _update_body(); - void _add_to_collision_object(Object* p_cshape); + void _add_to_collision_object(Object *p_cshape); void _set_update_shape_index(int p_index); int _get_update_shape_index() const; @@ -71,12 +71,10 @@ class CollisionShape : public Spatial { void _create_debug_shape(); protected: - void _notification(int p_what); static void _bind_methods(); public: - void make_convex_from_brothers(); void set_shape(const Ref &p_shape); @@ -90,7 +88,6 @@ public: int get_collision_object_shape_index() const { return _get_update_shape_index(); } - String get_configuration_warning() const; CollisionShape(); @@ -98,4 +95,3 @@ public: }; #endif // BODY_VOLUME_H - diff --git a/scene/3d/bone_attachment.cpp b/scene/3d/bone_attachment.cpp index 1a2680e3b..d8cb2dfda 100644 --- a/scene/3d/bone_attachment.cpp +++ b/scene/3d/bone_attachment.cpp @@ -28,19 +28,19 @@ /*************************************************************************/ #include "bone_attachment.h" -bool BoneAttachment::_get(const StringName& p_name,Variant &r_ret) const { +bool BoneAttachment::_get(const StringName &p_name, Variant &r_ret) const { - if (String(p_name)=="bone_name") { + if (String(p_name) == "bone_name") { - r_ret=get_bone_name(); + r_ret = get_bone_name(); return true; } return false; } -bool BoneAttachment::_set(const StringName& p_name, const Variant& p_value){ +bool BoneAttachment::_set(const StringName &p_name, const Variant &p_value) { - if (String(p_name)=="bone_name") { + if (String(p_name) == "bone_name") { set_bone_name(p_value); return true; @@ -48,40 +48,37 @@ bool BoneAttachment::_set(const StringName& p_name, const Variant& p_value){ return false; } -void BoneAttachment::_get_property_list( List* p_list ) const{ +void BoneAttachment::_get_property_list(List *p_list) const { - Skeleton *parent=NULL; - if(get_parent()) - parent=get_parent()->cast_to(); + Skeleton *parent = NULL; + if (get_parent()) + parent = get_parent()->cast_to(); if (parent) { String names; - for(int i=0;iget_bone_count();i++) { - if(i>0) - names+=","; - names+=parent->get_bone_name(i); + for (int i = 0; i < parent->get_bone_count(); i++) { + if (i > 0) + names += ","; + names += parent->get_bone_name(i); } - p_list->push_back(PropertyInfo(Variant::STRING,"bone_name",PROPERTY_HINT_ENUM,names)); + p_list->push_back(PropertyInfo(Variant::STRING, "bone_name", PROPERTY_HINT_ENUM, names)); } else { - p_list->push_back(PropertyInfo(Variant::STRING,"bone_name")); - + p_list->push_back(PropertyInfo(Variant::STRING, "bone_name")); } - } - void BoneAttachment::_check_bind() { if (get_parent() && get_parent()->cast_to()) { Skeleton *sk = get_parent()->cast_to(); int idx = sk->find_bone(bone_name); - if (idx!=-1) { - sk->bind_child_node_to_bone(idx,this); + if (idx != -1) { + sk->bind_child_node_to_bone(idx, this); set_transform(sk->get_bone_global_pose(idx)); - bound=true; + bound = true; } } } @@ -93,33 +90,33 @@ void BoneAttachment::_check_unbind() { if (get_parent() && get_parent()->cast_to()) { Skeleton *sk = get_parent()->cast_to(); int idx = sk->find_bone(bone_name); - if (idx!=-1) { - sk->unbind_child_node_from_bone(idx,this); + if (idx != -1) { + sk->unbind_child_node_from_bone(idx, this); } } - bound=false; + bound = false; } } -void BoneAttachment::set_bone_name(const String& p_name) { +void BoneAttachment::set_bone_name(const String &p_name) { if (is_inside_tree()) _check_unbind(); - bone_name=p_name; + bone_name = p_name; if (is_inside_tree()) _check_bind(); } -String BoneAttachment::get_bone_name() const{ +String BoneAttachment::get_bone_name() const { return bone_name; } void BoneAttachment::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { @@ -132,13 +129,11 @@ void BoneAttachment::_notification(int p_what) { } } -BoneAttachment::BoneAttachment() -{ - bound=false; - +BoneAttachment::BoneAttachment() { + bound = false; } -void BoneAttachment::_bind_methods(){ - ClassDB::bind_method(D_METHOD("set_bone_name","bone_name"),&BoneAttachment::set_bone_name); - ClassDB::bind_method(D_METHOD("get_bone_name"),&BoneAttachment::get_bone_name); +void BoneAttachment::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_bone_name", "bone_name"), &BoneAttachment::set_bone_name); + ClassDB::bind_method(D_METHOD("get_bone_name"), &BoneAttachment::get_bone_name); } diff --git a/scene/3d/bone_attachment.h b/scene/3d/bone_attachment.h index 9bcbb8286..194d6b4f9 100644 --- a/scene/3d/bone_attachment.h +++ b/scene/3d/bone_attachment.h @@ -33,25 +33,24 @@ class BoneAttachment : public Spatial { - GDCLASS(BoneAttachment,Spatial); + GDCLASS(BoneAttachment, Spatial); bool bound; String bone_name; void _check_bind(); void _check_unbind(); -protected: - bool _get(const StringName& p_name,Variant &r_ret) const; - bool _set(const StringName& p_name, const Variant& p_value); - void _get_property_list( List* p_list ) const; +protected: + bool _get(const StringName &p_name, Variant &r_ret) const; + bool _set(const StringName &p_name, const Variant &p_value); + void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); public: - - void set_bone_name(const String& p_name); + void set_bone_name(const String &p_name); String get_bone_name() const; BoneAttachment(); diff --git a/scene/3d/camera.cpp b/scene/3d/camera.cpp index 2e04f2d8b..540edd8a2 100644 --- a/scene/3d/camera.cpp +++ b/scene/3d/camera.cpp @@ -32,10 +32,7 @@ #include "scene/resources/material.h" #include "scene/resources/surface_tool.h" - void Camera::_update_audio_listener_state() { - - } void Camera::_request_camera_update() { @@ -45,60 +42,56 @@ void Camera::_request_camera_update() { void Camera::_update_camera_mode() { - - force_change=true; - switch(mode) { + force_change = true; + switch (mode) { case PROJECTION_PERSPECTIVE: { - - set_perspective(fov,near,far); + set_perspective(fov, near, far); } break; case PROJECTION_ORTHOGONAL: { - set_orthogonal(size,near,far); + set_orthogonal(size, near, far); } break; - } - } -bool Camera::_set(const StringName& p_name, const Variant& p_value) { +bool Camera::_set(const StringName &p_name, const Variant &p_value) { - bool changed_all=false; - if (p_name=="projection") { + bool changed_all = false; + if (p_name == "projection") { int proj = p_value; - if (proj==PROJECTION_PERSPECTIVE) - mode=PROJECTION_PERSPECTIVE; - if (proj==PROJECTION_ORTHOGONAL) - mode=PROJECTION_ORTHOGONAL; - - changed_all=true; - } else if (p_name=="fov" || p_name=="fovy" || p_name=="fovx") - fov=p_value; - else if (p_name=="size" || p_name=="sizex" || p_name=="sizey") - size=p_value; - else if (p_name=="near") - near=p_value; - else if (p_name=="far") - far=p_value; - else if (p_name=="keep_aspect") + if (proj == PROJECTION_PERSPECTIVE) + mode = PROJECTION_PERSPECTIVE; + if (proj == PROJECTION_ORTHOGONAL) + mode = PROJECTION_ORTHOGONAL; + + changed_all = true; + } else if (p_name == "fov" || p_name == "fovy" || p_name == "fovx") + fov = p_value; + else if (p_name == "size" || p_name == "sizex" || p_name == "sizey") + size = p_value; + else if (p_name == "near") + near = p_value; + else if (p_name == "far") + far = p_value; + else if (p_name == "keep_aspect") set_keep_aspect_mode(KeepAspect(int(p_value))); - else if (p_name=="vaspect") - set_keep_aspect_mode(p_value?KEEP_WIDTH:KEEP_HEIGHT); - else if (p_name=="h_offset") - h_offset=p_value; - else if (p_name=="v_offset") - v_offset=p_value; - else if (p_name=="current") { + else if (p_name == "vaspect") + set_keep_aspect_mode(p_value ? KEEP_WIDTH : KEEP_HEIGHT); + else if (p_name == "h_offset") + h_offset = p_value; + else if (p_name == "v_offset") + v_offset = p_value; + else if (p_name == "current") { if (p_value.operator bool()) { make_current(); } else { clear_current(); } - } else if (p_name=="cull_mask") { + } else if (p_name == "cull_mask") { set_cull_mask(p_value); - } else if (p_name=="environment") { + } else if (p_name == "environment") { set_environment(p_value); } else return false; @@ -107,88 +100,84 @@ bool Camera::_set(const StringName& p_name, const Variant& p_value) { if (changed_all) _change_notify(); return true; - } -bool Camera::_get(const StringName& p_name,Variant &r_ret) const { - - if (p_name=="projection") { - r_ret= mode; - } else if (p_name=="fov" || p_name=="fovy" || p_name=="fovx") - r_ret= fov; - else if (p_name=="size" || p_name=="sizex" || p_name=="sizey") - r_ret= size; - else if (p_name=="near") - r_ret= near; - else if (p_name=="far") - r_ret= far; - else if (p_name=="keep_aspect") - r_ret= int(keep_aspect); - else if (p_name=="current") { +bool Camera::_get(const StringName &p_name, Variant &r_ret) const { + + if (p_name == "projection") { + r_ret = mode; + } else if (p_name == "fov" || p_name == "fovy" || p_name == "fovx") + r_ret = fov; + else if (p_name == "size" || p_name == "sizex" || p_name == "sizey") + r_ret = size; + else if (p_name == "near") + r_ret = near; + else if (p_name == "far") + r_ret = far; + else if (p_name == "keep_aspect") + r_ret = int(keep_aspect); + else if (p_name == "current") { if (is_inside_tree() && get_tree()->is_node_being_edited(this)) { - r_ret=current; + r_ret = current; } else { - r_ret=is_current(); + r_ret = is_current(); } - } else if (p_name=="cull_mask") { - r_ret=get_cull_mask(); - } else if (p_name=="h_offset") { - r_ret=get_h_offset(); - } else if (p_name=="v_offset") { - r_ret=get_v_offset(); - } else if (p_name=="environment") { - r_ret=get_environment(); + } else if (p_name == "cull_mask") { + r_ret = get_cull_mask(); + } else if (p_name == "h_offset") { + r_ret = get_h_offset(); + } else if (p_name == "v_offset") { + r_ret = get_v_offset(); + } else if (p_name == "environment") { + r_ret = get_environment(); } else return false; return true; } -void Camera::_get_property_list( List *p_list) const { +void Camera::_get_property_list(List *p_list) const { - p_list->push_back( PropertyInfo( Variant::INT, "projection", PROPERTY_HINT_ENUM, "Perspective,Orthogonal") ); + p_list->push_back(PropertyInfo(Variant::INT, "projection", PROPERTY_HINT_ENUM, "Perspective,Orthogonal")); - switch(mode) { + switch (mode) { case PROJECTION_PERSPECTIVE: { - p_list->push_back( PropertyInfo( Variant::REAL, "fov" , PROPERTY_HINT_RANGE, "1,179,0.1",PROPERTY_USAGE_NOEDITOR) ); - if (keep_aspect==KEEP_WIDTH) - p_list->push_back( PropertyInfo( Variant::REAL, "fovx" , PROPERTY_HINT_RANGE, "1,179,0.1",PROPERTY_USAGE_EDITOR) ); + p_list->push_back(PropertyInfo(Variant::REAL, "fov", PROPERTY_HINT_RANGE, "1,179,0.1", PROPERTY_USAGE_NOEDITOR)); + if (keep_aspect == KEEP_WIDTH) + p_list->push_back(PropertyInfo(Variant::REAL, "fovx", PROPERTY_HINT_RANGE, "1,179,0.1", PROPERTY_USAGE_EDITOR)); else - p_list->push_back( PropertyInfo( Variant::REAL, "fovy" , PROPERTY_HINT_RANGE, "1,179,0.1",PROPERTY_USAGE_EDITOR) ); - + p_list->push_back(PropertyInfo(Variant::REAL, "fovy", PROPERTY_HINT_RANGE, "1,179,0.1", PROPERTY_USAGE_EDITOR)); } break; case PROJECTION_ORTHOGONAL: { - p_list->push_back( PropertyInfo( Variant::REAL, "size" , PROPERTY_HINT_RANGE, "1,16384,0.01",PROPERTY_USAGE_NOEDITOR ) ); - if (keep_aspect==KEEP_WIDTH) - p_list->push_back( PropertyInfo( Variant::REAL, "sizex" , PROPERTY_HINT_RANGE, "0.1,16384,0.01",PROPERTY_USAGE_EDITOR) ); + p_list->push_back(PropertyInfo(Variant::REAL, "size", PROPERTY_HINT_RANGE, "1,16384,0.01", PROPERTY_USAGE_NOEDITOR)); + if (keep_aspect == KEEP_WIDTH) + p_list->push_back(PropertyInfo(Variant::REAL, "sizex", PROPERTY_HINT_RANGE, "0.1,16384,0.01", PROPERTY_USAGE_EDITOR)); else - p_list->push_back( PropertyInfo( Variant::REAL, "sizey" , PROPERTY_HINT_RANGE, "0.1,16384,0.01",PROPERTY_USAGE_EDITOR) ); + p_list->push_back(PropertyInfo(Variant::REAL, "sizey", PROPERTY_HINT_RANGE, "0.1,16384,0.01", PROPERTY_USAGE_EDITOR)); } break; - } - p_list->push_back( PropertyInfo( Variant::REAL, "near" , PROPERTY_HINT_EXP_RANGE, "0.01,4096.0,0.01") ); - p_list->push_back( PropertyInfo( Variant::REAL, "far" , PROPERTY_HINT_EXP_RANGE, "0.01,4096.0,0.01") ); - p_list->push_back( PropertyInfo( Variant::INT, "keep_aspect",PROPERTY_HINT_ENUM,"Keep Width,Keep Height") ); - p_list->push_back( PropertyInfo( Variant::BOOL, "current" ) ); - p_list->push_back( PropertyInfo( Variant::INT, "cull_mask",PROPERTY_HINT_LAYERS_3D_RENDER ) ); - p_list->push_back( PropertyInfo( Variant::OBJECT, "environment",PROPERTY_HINT_RESOURCE_TYPE,"Environment" ) ); - p_list->push_back( PropertyInfo( Variant::REAL, "h_offset" ) ); - p_list->push_back( PropertyInfo( Variant::REAL, "v_offset" ) ); - + p_list->push_back(PropertyInfo(Variant::REAL, "near", PROPERTY_HINT_EXP_RANGE, "0.01,4096.0,0.01")); + p_list->push_back(PropertyInfo(Variant::REAL, "far", PROPERTY_HINT_EXP_RANGE, "0.01,4096.0,0.01")); + p_list->push_back(PropertyInfo(Variant::INT, "keep_aspect", PROPERTY_HINT_ENUM, "Keep Width,Keep Height")); + p_list->push_back(PropertyInfo(Variant::BOOL, "current")); + p_list->push_back(PropertyInfo(Variant::INT, "cull_mask", PROPERTY_HINT_LAYERS_3D_RENDER)); + p_list->push_back(PropertyInfo(Variant::OBJECT, "environment", PROPERTY_HINT_RESOURCE_TYPE, "Environment")); + p_list->push_back(PropertyInfo(Variant::REAL, "h_offset")); + p_list->push_back(PropertyInfo(Variant::REAL, "v_offset")); } void Camera::_update_camera() { Transform tr = get_camera_transform(); - tr.origin+=tr.basis.get_axis(1)*v_offset; - tr.origin+=tr.basis.get_axis(0)*h_offset; - VisualServer::get_singleton()->camera_set_transform( camera, tr ); + tr.origin += tr.basis.get_axis(1) * v_offset; + tr.origin += tr.basis.get_axis(0) * h_offset; + VisualServer::get_singleton()->camera_set_transform(camera, tr); // here goes listener stuff /* @@ -198,28 +187,23 @@ void Camera::_update_camera() { if (is_inside_tree() && is_current()) { get_viewport()->_camera_transform_changed_notify(); - } if (is_current() && get_world().is_valid()) { get_world()->_update_camera(this); } - - } void Camera::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_WORLD: { - bool first_camera = get_viewport()->_camera_add(this); if (!get_tree()->is_node_being_edited(this) && (current || first_camera)) make_current(); - } break; case NOTIFICATION_TRANSFORM_CHANGED: { @@ -230,16 +214,15 @@ void Camera::_notification(int p_what) { if (!get_tree()->is_node_being_edited(this)) { if (is_current()) { clear_current(); - current=true; //keep it true + current = true; //keep it true } else { - current=false; + current = false; } } get_viewport()->_camera_remove(this); - } break; case NOTIFICATION_BECAME_CURRENT: { if (get_world().is_valid()) { @@ -251,13 +234,9 @@ void Camera::_notification(int p_what) { get_world()->_remove_camera(this); } } break; - - } - } - Transform Camera::get_camera_transform() const { return get_global_transform().orthonormalized(); @@ -265,31 +244,31 @@ Transform Camera::get_camera_transform() const { void Camera::set_perspective(float p_fovy_degrees, float p_z_near, float p_z_far) { - if (!force_change && fov==p_fovy_degrees && p_z_near==near && p_z_far==far && mode==PROJECTION_PERSPECTIVE) + if (!force_change && fov == p_fovy_degrees && p_z_near == near && p_z_far == far && mode == PROJECTION_PERSPECTIVE) return; - fov=p_fovy_degrees; - near=p_z_near; - far=p_z_far; - mode=PROJECTION_PERSPECTIVE; + fov = p_fovy_degrees; + near = p_z_near; + far = p_z_far; + mode = PROJECTION_PERSPECTIVE; - VisualServer::get_singleton()->camera_set_perspective(camera,fov,near,far); + VisualServer::get_singleton()->camera_set_perspective(camera, fov, near, far); update_gizmo(); - force_change=false; + force_change = false; } void Camera::set_orthogonal(float p_size, float p_z_near, float p_z_far) { - if (!force_change && size==p_size && p_z_near==near && p_z_far==far && mode==PROJECTION_ORTHOGONAL) + if (!force_change && size == p_size && p_z_near == near && p_z_far == far && mode == PROJECTION_ORTHOGONAL) return; size = p_size; - near=p_z_near; - far=p_z_far; - mode=PROJECTION_ORTHOGONAL; - force_change=false; + near = p_z_near; + far = p_z_far; + mode = PROJECTION_ORTHOGONAL; + force_change = false; - VisualServer::get_singleton()->camera_set_orthogonal(camera,size,near,far); + VisualServer::get_singleton()->camera_set_orthogonal(camera, size, near, far); update_gizmo(); } @@ -300,7 +279,7 @@ RID Camera::get_camera() const { void Camera::make_current() { - current=true; + current = true; if (!is_inside_tree()) return; @@ -310,55 +289,47 @@ void Camera::make_current() { //get_scene()->call_group(SceneMainLoop::GROUP_CALL_REALTIME,camera_group,"_camera_make_current",this); } - - - void Camera::clear_current() { - current=false; + current = false; if (!is_inside_tree()) return; - if (get_viewport()->get_camera()==this) { + if (get_viewport()->get_camera() == this) { get_viewport()->_camera_set(NULL); get_viewport()->_camera_make_next_current(this); } - } bool Camera::is_current() const { if (is_inside_tree() && !get_tree()->is_node_being_edited(this)) { - return get_viewport()->get_camera()==this; + return get_viewport()->get_camera() == this; } else return current; return false; } - bool Camera::_can_gizmo_scale() const { return false; } - - -Vector3 Camera::project_ray_normal(const Point2& p_pos) const { +Vector3 Camera::project_ray_normal(const Point2 &p_pos) const { Vector3 ray = project_local_ray_normal(p_pos); return get_camera_transform().basis.xform(ray).normalized(); }; -Vector3 Camera::project_local_ray_normal(const Point2& p_pos) const { +Vector3 Camera::project_local_ray_normal(const Point2 &p_pos) const { if (!is_inside_tree()) { ERR_EXPLAIN("Camera is not inside scene."); - ERR_FAIL_COND_V(!is_inside_tree(),Vector3()); + ERR_FAIL_COND_V(!is_inside_tree(), Vector3()); } - #if 0 Size2 viewport_size = get_viewport()->get_visible_rect().size; Vector2 cpos = p_pos; @@ -370,26 +341,25 @@ Vector3 Camera::project_local_ray_normal(const Point2& p_pos) const { Vector3 ray; - if (mode==PROJECTION_ORTHOGONAL) { + if (mode == PROJECTION_ORTHOGONAL) { - ray=Vector3(0,0,-1); + ray = Vector3(0, 0, -1); } else { CameraMatrix cm; - cm.set_perspective(fov,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH); - float screen_w,screen_h; - cm.get_viewport_size(screen_w,screen_h); - ray=Vector3( ((cpos.x/viewport_size.width)*2.0-1.0)*screen_w, ((1.0-(cpos.y/viewport_size.height))*2.0-1.0)*screen_h,-near).normalized(); + cm.set_perspective(fov, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH); + float screen_w, screen_h; + cm.get_viewport_size(screen_w, screen_h); + ray = Vector3(((cpos.x / viewport_size.width) * 2.0 - 1.0) * screen_w, ((1.0 - (cpos.y / viewport_size.height)) * 2.0 - 1.0) * screen_h, -near).normalized(); } return ray; }; - -Vector3 Camera::project_ray_origin(const Point2& p_pos) const { +Vector3 Camera::project_ray_origin(const Point2 &p_pos) const { if (!is_inside_tree()) { ERR_EXPLAIN("Camera is not inside scene."); - ERR_FAIL_COND_V(!is_inside_tree(),Vector3()); + ERR_FAIL_COND_V(!is_inside_tree(), Vector3()); } #if 0 @@ -401,7 +371,7 @@ Vector3 Camera::project_ray_origin(const Point2& p_pos) const { Vector2 cpos = get_viewport()->get_camera_coords(p_pos); #endif - ERR_FAIL_COND_V( viewport_size.y == 0, Vector3() ); + ERR_FAIL_COND_V(viewport_size.y == 0, Vector3()); //float aspect = viewport_size.x / viewport_size.y; if (mode == PROJECTION_PERSPECTIVE) { @@ -410,91 +380,84 @@ Vector3 Camera::project_ray_origin(const Point2& p_pos) const { } else { Vector2 pos = cpos / viewport_size; - float vsize,hsize; - if (keep_aspect==KEEP_WIDTH) { - vsize = size/viewport_size.aspect(); + float vsize, hsize; + if (keep_aspect == KEEP_WIDTH) { + vsize = size / viewport_size.aspect(); hsize = size; } else { - hsize = size*viewport_size.aspect(); + hsize = size * viewport_size.aspect(); vsize = size; - } - - Vector3 ray; - ray.x = pos.x * (hsize) - hsize/2; - ray.y = (1.0 - pos.y) * (vsize) - vsize/2; + ray.x = pos.x * (hsize)-hsize / 2; + ray.y = (1.0 - pos.y) * (vsize)-vsize / 2; ray.z = -near; ray = get_camera_transform().xform(ray); return ray; }; }; -bool Camera::is_position_behind(const Vector3& p_pos) const { +bool Camera::is_position_behind(const Vector3 &p_pos) const { Transform t = get_global_transform(); Vector3 eyedir = -get_global_transform().basis.get_axis(2).normalized(); - return eyedir.dot(p_pos) < (eyedir.dot(t.origin)+near); + return eyedir.dot(p_pos) < (eyedir.dot(t.origin) + near); } -Point2 Camera::unproject_position(const Vector3& p_pos) const { +Point2 Camera::unproject_position(const Vector3 &p_pos) const { if (!is_inside_tree()) { ERR_EXPLAIN("Camera is not inside scene."); - ERR_FAIL_COND_V(!is_inside_tree(),Vector2()); + ERR_FAIL_COND_V(!is_inside_tree(), Vector2()); } Size2 viewport_size = get_viewport()->get_visible_rect().size; CameraMatrix cm; - - if (mode==PROJECTION_ORTHOGONAL) - cm.set_orthogonal(size,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH); + if (mode == PROJECTION_ORTHOGONAL) + cm.set_orthogonal(size, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH); else - cm.set_perspective(fov,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH); - - Plane p(get_camera_transform().xform_inv(p_pos),1.0); + cm.set_perspective(fov, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH); - p=cm.xform4(p); - p.normal/=p.d; + Plane p(get_camera_transform().xform_inv(p_pos), 1.0); + p = cm.xform4(p); + p.normal /= p.d; Point2 res; - res.x = (p.normal.x * 0.5 + 0.5) * viewport_size.x; - res.y = (-p.normal.y * 0.5 + 0.5) * viewport_size.y; + res.x = (p.normal.x * 0.5 + 0.5) * viewport_size.x; + res.y = (-p.normal.y * 0.5 + 0.5) * viewport_size.y; return res; - } -Vector3 Camera::project_position(const Point2& p_point) const { +Vector3 Camera::project_position(const Point2 &p_point) const { if (!is_inside_tree()) { ERR_EXPLAIN("Camera is not inside scene."); - ERR_FAIL_COND_V(!is_inside_tree(),Vector3()); + ERR_FAIL_COND_V(!is_inside_tree(), Vector3()); } Size2 viewport_size = get_viewport()->get_visible_rect().size; CameraMatrix cm; - if (mode==PROJECTION_ORTHOGONAL) - cm.set_orthogonal(size,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH); + if (mode == PROJECTION_ORTHOGONAL) + cm.set_orthogonal(size, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH); else - cm.set_perspective(fov,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH); + cm.set_perspective(fov, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH); Size2 vp_size; - cm.get_viewport_size(vp_size.x,vp_size.y); + cm.get_viewport_size(vp_size.x, vp_size.y); Vector2 point; - point.x = (p_point.x/viewport_size.x) * 2.0 - 1.0; - point.y = (1.0-(p_point.y/viewport_size.y)) * 2.0 - 1.0; - point*=vp_size; - - Vector3 p(point.x,point.y,-near); + point.x = (p_point.x / viewport_size.x) * 2.0 - 1.0; + point.y = (1.0 - (p_point.y / viewport_size.y)) * 2.0 - 1.0; + point *= vp_size; + Vector3 p(point.x, point.y, -near); return get_camera_transform().xform(p); } @@ -516,13 +479,13 @@ void Camera::_camera_make_current(Node *p_camera) { } */ -void Camera::set_environment(const Ref& p_environment) { +void Camera::set_environment(const Ref &p_environment) { - environment=p_environment; + environment = p_environment; if (environment.is_valid()) - VS::get_singleton()->camera_set_environment(camera,environment->get_rid()); + VS::get_singleton()->camera_set_environment(camera, environment->get_rid()); else - VS::get_singleton()->camera_set_environment(camera,RID()); + VS::get_singleton()->camera_set_environment(camera, RID()); } Ref Camera::get_environment() const { @@ -530,59 +493,55 @@ Ref Camera::get_environment() const { return environment; } - void Camera::set_keep_aspect_mode(KeepAspect p_aspect) { - keep_aspect=p_aspect; - VisualServer::get_singleton()->camera_set_use_vertical_aspect(camera,p_aspect==KEEP_WIDTH); + keep_aspect = p_aspect; + VisualServer::get_singleton()->camera_set_use_vertical_aspect(camera, p_aspect == KEEP_WIDTH); _change_notify(); } -Camera::KeepAspect Camera::get_keep_aspect_mode() const{ +Camera::KeepAspect Camera::get_keep_aspect_mode() const { return keep_aspect; } - - void Camera::_bind_methods() { - ClassDB::bind_method(D_METHOD("project_ray_normal","screen_point"), &Camera::project_ray_normal); - ClassDB::bind_method(D_METHOD("project_local_ray_normal","screen_point"), &Camera::project_local_ray_normal); - ClassDB::bind_method(D_METHOD("project_ray_origin","screen_point"), &Camera::project_ray_origin); - ClassDB::bind_method(D_METHOD("unproject_position","world_point"), &Camera::unproject_position); - ClassDB::bind_method(D_METHOD("is_position_behind","world_point"), &Camera::is_position_behind); - ClassDB::bind_method(D_METHOD("project_position","screen_point"), &Camera::project_position); - ClassDB::bind_method(D_METHOD("set_perspective","fov","z_near","z_far"),&Camera::set_perspective ); - ClassDB::bind_method(D_METHOD("set_orthogonal","size","z_near","z_far"),&Camera::set_orthogonal ); - ClassDB::bind_method(D_METHOD("make_current"),&Camera::make_current ); - ClassDB::bind_method(D_METHOD("clear_current"),&Camera::clear_current ); - ClassDB::bind_method(D_METHOD("is_current"),&Camera::is_current ); - ClassDB::bind_method(D_METHOD("get_camera_transform"),&Camera::get_camera_transform ); - ClassDB::bind_method(D_METHOD("get_fov"),&Camera::get_fov ); - ClassDB::bind_method(D_METHOD("get_size"),&Camera::get_size ); - ClassDB::bind_method(D_METHOD("get_zfar"),&Camera::get_zfar ); - ClassDB::bind_method(D_METHOD("get_znear"),&Camera::get_znear ); - ClassDB::bind_method(D_METHOD("get_projection"),&Camera::get_projection ); - ClassDB::bind_method(D_METHOD("set_h_offset","ofs"),&Camera::set_h_offset ); - ClassDB::bind_method(D_METHOD("get_h_offset"),&Camera::get_h_offset ); - ClassDB::bind_method(D_METHOD("set_v_offset","ofs"),&Camera::set_v_offset ); - ClassDB::bind_method(D_METHOD("get_v_offset"),&Camera::get_v_offset ); - ClassDB::bind_method(D_METHOD("set_cull_mask","mask"),&Camera::set_cull_mask ); - ClassDB::bind_method(D_METHOD("get_cull_mask"),&Camera::get_cull_mask ); - ClassDB::bind_method(D_METHOD("set_environment","env:Environment"),&Camera::set_environment ); - ClassDB::bind_method(D_METHOD("get_environment:Environment"),&Camera::get_environment ); - ClassDB::bind_method(D_METHOD("set_keep_aspect_mode","mode"),&Camera::set_keep_aspect_mode ); - ClassDB::bind_method(D_METHOD("get_keep_aspect_mode"),&Camera::get_keep_aspect_mode ); + ClassDB::bind_method(D_METHOD("project_ray_normal", "screen_point"), &Camera::project_ray_normal); + ClassDB::bind_method(D_METHOD("project_local_ray_normal", "screen_point"), &Camera::project_local_ray_normal); + ClassDB::bind_method(D_METHOD("project_ray_origin", "screen_point"), &Camera::project_ray_origin); + ClassDB::bind_method(D_METHOD("unproject_position", "world_point"), &Camera::unproject_position); + ClassDB::bind_method(D_METHOD("is_position_behind", "world_point"), &Camera::is_position_behind); + ClassDB::bind_method(D_METHOD("project_position", "screen_point"), &Camera::project_position); + ClassDB::bind_method(D_METHOD("set_perspective", "fov", "z_near", "z_far"), &Camera::set_perspective); + ClassDB::bind_method(D_METHOD("set_orthogonal", "size", "z_near", "z_far"), &Camera::set_orthogonal); + ClassDB::bind_method(D_METHOD("make_current"), &Camera::make_current); + ClassDB::bind_method(D_METHOD("clear_current"), &Camera::clear_current); + ClassDB::bind_method(D_METHOD("is_current"), &Camera::is_current); + ClassDB::bind_method(D_METHOD("get_camera_transform"), &Camera::get_camera_transform); + ClassDB::bind_method(D_METHOD("get_fov"), &Camera::get_fov); + ClassDB::bind_method(D_METHOD("get_size"), &Camera::get_size); + ClassDB::bind_method(D_METHOD("get_zfar"), &Camera::get_zfar); + ClassDB::bind_method(D_METHOD("get_znear"), &Camera::get_znear); + ClassDB::bind_method(D_METHOD("get_projection"), &Camera::get_projection); + ClassDB::bind_method(D_METHOD("set_h_offset", "ofs"), &Camera::set_h_offset); + ClassDB::bind_method(D_METHOD("get_h_offset"), &Camera::get_h_offset); + ClassDB::bind_method(D_METHOD("set_v_offset", "ofs"), &Camera::set_v_offset); + ClassDB::bind_method(D_METHOD("get_v_offset"), &Camera::get_v_offset); + ClassDB::bind_method(D_METHOD("set_cull_mask", "mask"), &Camera::set_cull_mask); + ClassDB::bind_method(D_METHOD("get_cull_mask"), &Camera::get_cull_mask); + ClassDB::bind_method(D_METHOD("set_environment", "env:Environment"), &Camera::set_environment); + ClassDB::bind_method(D_METHOD("get_environment:Environment"), &Camera::get_environment); + ClassDB::bind_method(D_METHOD("set_keep_aspect_mode", "mode"), &Camera::set_keep_aspect_mode); + ClassDB::bind_method(D_METHOD("get_keep_aspect_mode"), &Camera::get_keep_aspect_mode); //ClassDB::bind_method(D_METHOD("_camera_make_current"),&Camera::_camera_make_current ); - BIND_CONSTANT( PROJECTION_PERSPECTIVE ); - BIND_CONSTANT( PROJECTION_ORTHOGONAL ); - - BIND_CONSTANT( KEEP_WIDTH ); - BIND_CONSTANT( KEEP_HEIGHT ); + BIND_CONSTANT(PROJECTION_PERSPECTIVE); + BIND_CONSTANT(PROJECTION_ORTHOGONAL); + BIND_CONSTANT(KEEP_WIDTH); + BIND_CONSTANT(KEEP_HEIGHT); } float Camera::get_fov() const { @@ -605,7 +564,6 @@ float Camera::get_zfar() const { return far; } - Camera::Projection Camera::get_projection() const { return mode; @@ -613,37 +571,32 @@ Camera::Projection Camera::get_projection() const { void Camera::set_cull_mask(uint32_t p_layers) { - layers=p_layers; - VisualServer::get_singleton()->camera_set_cull_mask(camera,layers); + layers = p_layers; + VisualServer::get_singleton()->camera_set_cull_mask(camera, layers); } -uint32_t Camera::get_cull_mask() const{ +uint32_t Camera::get_cull_mask() const { return layers; } - Vector Camera::get_frustum() const { - ERR_FAIL_COND_V(!is_inside_world(),Vector()); + ERR_FAIL_COND_V(!is_inside_world(), Vector()); Size2 viewport_size = get_viewport()->get_visible_rect().size; CameraMatrix cm; - if (mode==PROJECTION_PERSPECTIVE) - cm.set_perspective(fov,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH); + if (mode == PROJECTION_PERSPECTIVE) + cm.set_perspective(fov, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH); else - cm.set_orthogonal(size,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH); + cm.set_orthogonal(size, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH); return cm.get_projection_planes(get_camera_transform()); - } - - - void Camera::set_v_offset(float p_offset) { - v_offset=p_offset; + v_offset = p_offset; _update_camera(); } @@ -653,7 +606,7 @@ float Camera::get_v_offset() const { } void Camera::set_h_offset(float p_offset) { - h_offset=p_offset; + h_offset = p_offset; _update_camera(); } @@ -662,32 +615,27 @@ float Camera::get_h_offset() const { return h_offset; } - Camera::Camera() { camera = VisualServer::get_singleton()->camera_create(); - size=1; - fov=0; - near=0; - far=0; - current=false; - force_change=false; - mode=PROJECTION_PERSPECTIVE; - set_perspective(60.0,0.1,100.0); - keep_aspect=KEEP_HEIGHT; - layers=0xfffff; - v_offset=0; - h_offset=0; - VisualServer::get_singleton()->camera_set_cull_mask(camera,layers); + size = 1; + fov = 0; + near = 0; + far = 0; + current = false; + force_change = false; + mode = PROJECTION_PERSPECTIVE; + set_perspective(60.0, 0.1, 100.0); + keep_aspect = KEEP_HEIGHT; + layers = 0xfffff; + v_offset = 0; + h_offset = 0; + VisualServer::get_singleton()->camera_set_cull_mask(camera, layers); //active=false; set_notify_transform(true); } - Camera::~Camera() { VisualServer::get_singleton()->free(camera); - } - - diff --git a/scene/3d/camera.h b/scene/3d/camera.h index 5301c06ee..3c31b6bee 100644 --- a/scene/3d/camera.h +++ b/scene/3d/camera.h @@ -29,7 +29,6 @@ #ifndef CAMERA_H #define CAMERA_H - #include "scene/3d/spatial.h" #include "scene/main/viewport.h" #include "scene/resources/environment.h" @@ -38,7 +37,8 @@ */ class Camera : public Spatial { - GDCLASS( Camera, Spatial ); + GDCLASS(Camera, Spatial); + public: enum Projection { @@ -52,7 +52,6 @@ public: }; private: - bool force_change; bool current; @@ -60,7 +59,7 @@ private: float fov; float size; - float near,far; + float near, far; float v_offset; float h_offset; KeepAspect keep_aspect; @@ -76,30 +75,27 @@ private: virtual bool _can_gizmo_scale() const; - - //void _camera_make_current(Node *p_camera); -friend class Viewport; + friend class Viewport; void _update_audio_listener_state(); -protected: +protected: void _update_camera(); virtual void _request_camera_update(); void _update_camera_mode(); - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); public: - enum { - NOTIFICATION_BECAME_CURRENT=50, - NOTIFICATION_LOST_CURRENT=51 + NOTIFICATION_BECAME_CURRENT = 50, + NOTIFICATION_LOST_CURRENT = 51 }; void set_perspective(float p_fovy_degrees, float p_z_near, float p_z_far); @@ -119,39 +115,35 @@ public: virtual Transform get_camera_transform() const; - Vector3 project_ray_normal(const Point2& p_point) const; - Vector3 project_ray_origin(const Point2& p_point) const; - Vector3 project_local_ray_normal(const Point2& p_point) const; - Point2 unproject_position(const Vector3& p_pos) const; - bool is_position_behind(const Vector3& p_pos) const; - Vector3 project_position(const Point2& p_point) const; + Vector3 project_ray_normal(const Point2 &p_point) const; + Vector3 project_ray_origin(const Point2 &p_point) const; + Vector3 project_local_ray_normal(const Point2 &p_point) const; + Point2 unproject_position(const Vector3 &p_pos) const; + bool is_position_behind(const Vector3 &p_pos) const; + Vector3 project_position(const Point2 &p_point) const; void set_cull_mask(uint32_t p_layers); uint32_t get_cull_mask() const; Vector get_frustum() const; - void set_environment(const Ref& p_environment); + void set_environment(const Ref &p_environment); Ref get_environment() const; void set_keep_aspect_mode(KeepAspect p_aspect); KeepAspect get_keep_aspect_mode() const; - void set_v_offset(float p_offset); float get_v_offset() const; void set_h_offset(float p_offset); float get_h_offset() const; - Camera(); ~Camera(); - }; - -VARIANT_ENUM_CAST( Camera::Projection ); -VARIANT_ENUM_CAST( Camera::KeepAspect ); +VARIANT_ENUM_CAST(Camera::Projection); +VARIANT_ENUM_CAST(Camera::KeepAspect); #endif diff --git a/scene/3d/character_camera.cpp b/scene/3d/character_camera.cpp index 424a7fc79..edd97eaa6 100644 --- a/scene/3d/character_camera.cpp +++ b/scene/3d/character_camera.cpp @@ -237,7 +237,6 @@ void CharacterCamera::_compute_camera() { new_pos = character_pos + rel_n * l; - #endif follow_pos=new_pos; diff --git a/scene/3d/character_camera.h b/scene/3d/character_camera.h index 5fde8c342..464fa5c23 100644 --- a/scene/3d/character_camera.h +++ b/scene/3d/character_camera.h @@ -29,7 +29,6 @@ #ifndef CHARACTER_CAMERA_H #define CHARACTER_CAMERA_H - #include "scene/3d/camera.h" #if 0 class CharacterCamera : public Camera { diff --git a/scene/3d/collision_object.cpp b/scene/3d/collision_object.cpp index 32e60f0d5..c3e19c4b8 100644 --- a/scene/3d/collision_object.cpp +++ b/scene/3d/collision_object.cpp @@ -27,15 +27,15 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "collision_object.h" -#include "servers/physics_server.h" #include "scene/scene_string_names.h" +#include "servers/physics_server.h" void CollisionObject::_update_shapes_from_children() { shapes.clear(); - for(int i=0;icall("_add_to_collision_object",this); + Node *n = get_child(i); + n->call("_add_to_collision_object", this); } _update_shapes(); @@ -43,31 +43,31 @@ void CollisionObject::_update_shapes_from_children() { void CollisionObject::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_WORLD: { if (area) - PhysicsServer::get_singleton()->area_set_transform(rid,get_global_transform()); + PhysicsServer::get_singleton()->area_set_transform(rid, get_global_transform()); else - PhysicsServer::get_singleton()->body_set_state(rid,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform()); + PhysicsServer::get_singleton()->body_set_state(rid, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform()); RID space = get_world()->get_space(); if (area) { - PhysicsServer::get_singleton()->area_set_space(rid,space); + PhysicsServer::get_singleton()->area_set_space(rid, space); } else - PhysicsServer::get_singleton()->body_set_space(rid,space); + PhysicsServer::get_singleton()->body_set_space(rid, space); _update_pickable(); - //get space + //get space }; case NOTIFICATION_TRANSFORM_CHANGED: { if (area) - PhysicsServer::get_singleton()->area_set_transform(rid,get_global_transform()); + PhysicsServer::get_singleton()->area_set_transform(rid, get_global_transform()); else - PhysicsServer::get_singleton()->body_set_state(rid,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform()); + PhysicsServer::get_singleton()->body_set_state(rid, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform()); } break; case NOTIFICATION_VISIBILITY_CHANGED: { @@ -78,9 +78,9 @@ void CollisionObject::_notification(int p_what) { case NOTIFICATION_EXIT_WORLD: { if (area) { - PhysicsServer::get_singleton()->area_set_space(rid,RID()); + PhysicsServer::get_singleton()->area_set_space(rid, RID()); } else - PhysicsServer::get_singleton()->body_set_space(rid,RID()); + PhysicsServer::get_singleton()->body_set_space(rid, RID()); } break; } @@ -96,25 +96,24 @@ void CollisionObject::_update_shapes() { else PhysicsServer::get_singleton()->body_clear_shapes(rid); - for(int i=0;iarea_add_shape(rid,shapes[i].shape->get_rid(),shapes[i].xform); + PhysicsServer::get_singleton()->area_add_shape(rid, shapes[i].shape->get_rid(), shapes[i].xform); else { - PhysicsServer::get_singleton()->body_add_shape(rid,shapes[i].shape->get_rid(),shapes[i].xform); + PhysicsServer::get_singleton()->body_add_shape(rid, shapes[i].shape->get_rid(), shapes[i].xform); if (shapes[i].trigger) - PhysicsServer::get_singleton()->body_set_shape_as_trigger(rid,i,shapes[i].trigger); + PhysicsServer::get_singleton()->body_set_shape_as_trigger(rid, i, shapes[i].trigger); } } } +bool CollisionObject::_set(const StringName &p_name, const Variant &p_value) { + String name = p_name; -bool CollisionObject::_set(const StringName& p_name, const Variant& p_value) { - String name=p_name; - - if (name=="shape_count") { + if (name == "shape_count") { shapes.resize(p_value); _update_shapes(); @@ -122,40 +121,37 @@ bool CollisionObject::_set(const StringName& p_name, const Variant& p_value) { } else if (name.begins_with("shapes/")) { - int idx=name.get_slicec('/',1).to_int(); - String what=name.get_slicec('/',2); - if (what=="shape") - set_shape(idx,RefPtr(p_value)); - else if (what=="transform") - set_shape_transform(idx,p_value); - else if (what=="trigger") - set_shape_as_trigger(idx,p_value); - + int idx = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); + if (what == "shape") + set_shape(idx, RefPtr(p_value)); + else if (what == "transform") + set_shape_transform(idx, p_value); + else if (what == "trigger") + set_shape_as_trigger(idx, p_value); } else return false; return true; - - } -bool CollisionObject::_get(const StringName& p_name,Variant &r_ret) const { +bool CollisionObject::_get(const StringName &p_name, Variant &r_ret) const { - String name=p_name; + String name = p_name; - if (name=="shape_count") { - r_ret= shapes.size(); + if (name == "shape_count") { + r_ret = shapes.size(); } else if (name.begins_with("shapes/")) { - int idx=name.get_slicec('/',1).to_int(); - String what=name.get_slicec('/',2); - if (what=="shape") - r_ret= get_shape(idx); - else if (what=="transform") - r_ret= get_shape_transform(idx); - else if (what=="trigger") - r_ret= is_shape_set_as_trigger(idx); + int idx = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); + if (what == "shape") + r_ret = get_shape(idx); + else if (what == "transform") + r_ret = get_shape_transform(idx); + else if (what == "trigger") + r_ret = is_shape_set_as_trigger(idx); } else return false; @@ -163,26 +159,24 @@ bool CollisionObject::_get(const StringName& p_name,Variant &r_ret) const { return true; } -void CollisionObject::_get_property_list( List *p_list) const { +void CollisionObject::_get_property_list(List *p_list) const { - p_list->push_back( PropertyInfo(Variant::INT,"shape_count",PROPERTY_HINT_RANGE,"0,256,1",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) ); - - for(int i=0;ipush_back( PropertyInfo(Variant::OBJECT,path+"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) ); - p_list->push_back( PropertyInfo(Variant::TRANSFORM,path+"transform",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) ); - p_list->push_back( PropertyInfo(Variant::BOOL,path+"trigger",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) ); + p_list->push_back(PropertyInfo(Variant::INT, "shape_count", PROPERTY_HINT_RANGE, "0,256,1", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE)); + for (int i = 0; i < shapes.size(); i++) { + String path = "shapes/" + itos(i) + "/"; + p_list->push_back(PropertyInfo(Variant::OBJECT, path + "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE)); + p_list->push_back(PropertyInfo(Variant::TRANSFORM, path + "transform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE)); + p_list->push_back(PropertyInfo(Variant::BOOL, path + "trigger", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE)); } } - -void CollisionObject::_input_event(Node *p_camera, const InputEvent& p_input_event, const Vector3& p_pos, const Vector3& p_normal, int p_shape) { +void CollisionObject::_input_event(Node *p_camera, const InputEvent &p_input_event, const Vector3 &p_pos, const Vector3 &p_normal, int p_shape) { if (get_script_instance()) { - get_script_instance()->call(SceneStringNames::get_singleton()->_input_event,p_camera,p_input_event,p_pos,p_normal,p_shape); + get_script_instance()->call(SceneStringNames::get_singleton()->_input_event, p_camera, p_input_event, p_pos, p_normal, p_shape); } - emit_signal(SceneStringNames::get_singleton()->input_event,p_camera,p_input_event,p_pos,p_normal,p_shape); + emit_signal(SceneStringNames::get_singleton()->input_event, p_camera, p_input_event, p_pos, p_normal, p_shape); } void CollisionObject::_mouse_enter() { @@ -193,14 +187,12 @@ void CollisionObject::_mouse_enter() { emit_signal(SceneStringNames::get_singleton()->mouse_entered); } - void CollisionObject::_mouse_exit() { if (get_script_instance()) { get_script_instance()->call(SceneStringNames::get_singleton()->_mouse_exit); } emit_signal(SceneStringNames::get_singleton()->mouse_exited); - } void CollisionObject::_update_pickable() { @@ -208,16 +200,15 @@ void CollisionObject::_update_pickable() { return; bool pickable = ray_pickable && is_inside_tree() && is_visible_in_tree(); if (area) - PhysicsServer::get_singleton()->area_set_ray_pickable(rid,pickable); + PhysicsServer::get_singleton()->area_set_ray_pickable(rid, pickable); else - PhysicsServer::get_singleton()->body_set_ray_pickable(rid,pickable); + PhysicsServer::get_singleton()->body_set_ray_pickable(rid, pickable); } void CollisionObject::set_ray_pickable(bool p_ray_pickable) { - ray_pickable=p_ray_pickable; + ray_pickable = p_ray_pickable; _update_pickable(); - } bool CollisionObject::is_ray_pickable() const { @@ -225,80 +216,74 @@ bool CollisionObject::is_ray_pickable() const { return ray_pickable; } - void CollisionObject::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_shape","shape:Shape","transform"),&CollisionObject::add_shape,DEFVAL(Transform())); - ClassDB::bind_method(D_METHOD("get_shape_count"),&CollisionObject::get_shape_count); - ClassDB::bind_method(D_METHOD("set_shape","shape_idx","shape:Shape"),&CollisionObject::set_shape); - ClassDB::bind_method(D_METHOD("set_shape_transform","shape_idx","transform"),&CollisionObject::set_shape_transform); -// ClassDB::bind_method(D_METHOD("set_shape_transform","shape_idx","transform"),&CollisionObject::set_shape_transform); - ClassDB::bind_method(D_METHOD("set_shape_as_trigger","shape_idx","enable"),&CollisionObject::set_shape_as_trigger); - ClassDB::bind_method(D_METHOD("is_shape_set_as_trigger","shape_idx"),&CollisionObject::is_shape_set_as_trigger); - ClassDB::bind_method(D_METHOD("get_shape:Shape","shape_idx"),&CollisionObject::get_shape); - ClassDB::bind_method(D_METHOD("get_shape_transform","shape_idx"),&CollisionObject::get_shape_transform); - ClassDB::bind_method(D_METHOD("remove_shape","shape_idx"),&CollisionObject::remove_shape); - ClassDB::bind_method(D_METHOD("clear_shapes"),&CollisionObject::clear_shapes); - ClassDB::bind_method(D_METHOD("set_ray_pickable","ray_pickable"),&CollisionObject::set_ray_pickable); - ClassDB::bind_method(D_METHOD("is_ray_pickable"),&CollisionObject::is_ray_pickable); - ClassDB::bind_method(D_METHOD("set_capture_input_on_drag","enable"),&CollisionObject::set_capture_input_on_drag); - ClassDB::bind_method(D_METHOD("get_capture_input_on_drag"),&CollisionObject::get_capture_input_on_drag); - ClassDB::bind_method(D_METHOD("get_rid"),&CollisionObject::get_rid); - BIND_VMETHOD( MethodInfo("_input_event",PropertyInfo(Variant::OBJECT,"camera"),PropertyInfo(Variant::INPUT_EVENT,"event"),PropertyInfo(Variant::VECTOR3,"click_pos"),PropertyInfo(Variant::VECTOR3,"click_normal"),PropertyInfo(Variant::INT,"shape_idx"))); - - ADD_SIGNAL( MethodInfo("input_event",PropertyInfo(Variant::OBJECT,"camera"),PropertyInfo(Variant::INPUT_EVENT,"event"),PropertyInfo(Variant::VECTOR3,"click_pos"),PropertyInfo(Variant::VECTOR3,"click_normal"),PropertyInfo(Variant::INT,"shape_idx"))); - ADD_SIGNAL( MethodInfo("mouse_entered")); - ADD_SIGNAL( MethodInfo("mouse_exited")); - - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"input_ray_pickable"),"set_ray_pickable","is_ray_pickable"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"input_capture_on_drag"),"set_capture_input_on_drag","get_capture_input_on_drag"); + ClassDB::bind_method(D_METHOD("add_shape", "shape:Shape", "transform"), &CollisionObject::add_shape, DEFVAL(Transform())); + ClassDB::bind_method(D_METHOD("get_shape_count"), &CollisionObject::get_shape_count); + ClassDB::bind_method(D_METHOD("set_shape", "shape_idx", "shape:Shape"), &CollisionObject::set_shape); + ClassDB::bind_method(D_METHOD("set_shape_transform", "shape_idx", "transform"), &CollisionObject::set_shape_transform); + // ClassDB::bind_method(D_METHOD("set_shape_transform","shape_idx","transform"),&CollisionObject::set_shape_transform); + ClassDB::bind_method(D_METHOD("set_shape_as_trigger", "shape_idx", "enable"), &CollisionObject::set_shape_as_trigger); + ClassDB::bind_method(D_METHOD("is_shape_set_as_trigger", "shape_idx"), &CollisionObject::is_shape_set_as_trigger); + ClassDB::bind_method(D_METHOD("get_shape:Shape", "shape_idx"), &CollisionObject::get_shape); + ClassDB::bind_method(D_METHOD("get_shape_transform", "shape_idx"), &CollisionObject::get_shape_transform); + ClassDB::bind_method(D_METHOD("remove_shape", "shape_idx"), &CollisionObject::remove_shape); + ClassDB::bind_method(D_METHOD("clear_shapes"), &CollisionObject::clear_shapes); + ClassDB::bind_method(D_METHOD("set_ray_pickable", "ray_pickable"), &CollisionObject::set_ray_pickable); + ClassDB::bind_method(D_METHOD("is_ray_pickable"), &CollisionObject::is_ray_pickable); + ClassDB::bind_method(D_METHOD("set_capture_input_on_drag", "enable"), &CollisionObject::set_capture_input_on_drag); + ClassDB::bind_method(D_METHOD("get_capture_input_on_drag"), &CollisionObject::get_capture_input_on_drag); + ClassDB::bind_method(D_METHOD("get_rid"), &CollisionObject::get_rid); + BIND_VMETHOD(MethodInfo("_input_event", PropertyInfo(Variant::OBJECT, "camera"), PropertyInfo(Variant::INPUT_EVENT, "event"), PropertyInfo(Variant::VECTOR3, "click_pos"), PropertyInfo(Variant::VECTOR3, "click_normal"), PropertyInfo(Variant::INT, "shape_idx"))); + + ADD_SIGNAL(MethodInfo("input_event", PropertyInfo(Variant::OBJECT, "camera"), PropertyInfo(Variant::INPUT_EVENT, "event"), PropertyInfo(Variant::VECTOR3, "click_pos"), PropertyInfo(Variant::VECTOR3, "click_normal"), PropertyInfo(Variant::INT, "shape_idx"))); + ADD_SIGNAL(MethodInfo("mouse_entered")); + ADD_SIGNAL(MethodInfo("mouse_exited")); + + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_ray_pickable"), "set_ray_pickable", "is_ray_pickable"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_capture_on_drag"), "set_capture_input_on_drag", "get_capture_input_on_drag"); } - -void CollisionObject::add_shape(const Ref& p_shape, const Transform& p_transform) { +void CollisionObject::add_shape(const Ref &p_shape, const Transform &p_transform) { ShapeData sdata; - sdata.shape=p_shape; - sdata.xform=p_transform; + sdata.shape = p_shape; + sdata.xform = p_transform; shapes.push_back(sdata); _update_shapes(); - } int CollisionObject::get_shape_count() const { return shapes.size(); - } -void CollisionObject::set_shape(int p_shape_idx, const Ref& p_shape) { +void CollisionObject::set_shape(int p_shape_idx, const Ref &p_shape) { - ERR_FAIL_INDEX(p_shape_idx,shapes.size()); - shapes[p_shape_idx].shape=p_shape; + ERR_FAIL_INDEX(p_shape_idx, shapes.size()); + shapes[p_shape_idx].shape = p_shape; _update_shapes(); } -void CollisionObject::set_shape_transform(int p_shape_idx, const Transform& p_transform) { +void CollisionObject::set_shape_transform(int p_shape_idx, const Transform &p_transform) { - ERR_FAIL_INDEX(p_shape_idx,shapes.size()); - shapes[p_shape_idx].xform=p_transform; + ERR_FAIL_INDEX(p_shape_idx, shapes.size()); + shapes[p_shape_idx].xform = p_transform; _update_shapes(); } Ref CollisionObject::get_shape(int p_shape_idx) const { - ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),Ref()); + ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), Ref()); return shapes[p_shape_idx].shape; - } Transform CollisionObject::get_shape_transform(int p_shape_idx) const { - ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),Transform()); + ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), Transform()); return shapes[p_shape_idx].xform; - } void CollisionObject::remove_shape(int p_shape_idx) { - ERR_FAIL_INDEX(p_shape_idx,shapes.size()); + ERR_FAIL_INDEX(p_shape_idx, shapes.size()); shapes.remove(p_shape_idx); _update_shapes(); @@ -313,41 +298,38 @@ void CollisionObject::clear_shapes() { void CollisionObject::set_shape_as_trigger(int p_shape_idx, bool p_trigger) { - ERR_FAIL_INDEX(p_shape_idx,shapes.size()); - shapes[p_shape_idx].trigger=p_trigger; - if (!area && rid.is_valid()) { - - PhysicsServer::get_singleton()->body_set_shape_as_trigger(rid,p_shape_idx,p_trigger); + ERR_FAIL_INDEX(p_shape_idx, shapes.size()); + shapes[p_shape_idx].trigger = p_trigger; + if (!area && rid.is_valid()) { - } + PhysicsServer::get_singleton()->body_set_shape_as_trigger(rid, p_shape_idx, p_trigger); + } } bool CollisionObject::is_shape_set_as_trigger(int p_shape_idx) const { - ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),false); - return shapes[p_shape_idx].trigger; + ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), false); + return shapes[p_shape_idx].trigger; } CollisionObject::CollisionObject(RID p_rid, bool p_area) { - rid=p_rid; - area=p_area; - capture_input_on_drag=false; - ray_pickable=true; + rid = p_rid; + area = p_area; + capture_input_on_drag = false; + ray_pickable = true; set_notify_transform(true); if (p_area) { - PhysicsServer::get_singleton()->area_attach_object_instance_ID(rid,get_instance_ID()); + PhysicsServer::get_singleton()->area_attach_object_instance_ID(rid, get_instance_ID()); } else { - PhysicsServer::get_singleton()->body_attach_object_instance_ID(rid,get_instance_ID()); + PhysicsServer::get_singleton()->body_attach_object_instance_ID(rid, get_instance_ID()); } //set_transform_notify(true); - } void CollisionObject::set_capture_input_on_drag(bool p_capture) { - capture_input_on_drag=p_capture; - + capture_input_on_drag = p_capture; } bool CollisionObject::get_capture_input_on_drag() const { @@ -355,12 +337,10 @@ bool CollisionObject::get_capture_input_on_drag() const { return capture_input_on_drag; } - CollisionObject::CollisionObject() { - - capture_input_on_drag=false; - ray_pickable=true; + capture_input_on_drag = false; + ray_pickable = true; set_notify_transform(true); //owner= diff --git a/scene/3d/collision_object.h b/scene/3d/collision_object.h index b89b7e336..9b124cf27 100644 --- a/scene/3d/collision_object.h +++ b/scene/3d/collision_object.h @@ -34,7 +34,7 @@ class CollisionObject : public Spatial { - GDCLASS( CollisionObject, Spatial ); + GDCLASS(CollisionObject, Spatial); bool area; RID rid; @@ -42,12 +42,11 @@ class CollisionObject : public Spatial { struct ShapeData { Transform xform; Ref shape; - bool trigger; - - ShapeData() { - trigger=false; - } + bool trigger; + ShapeData() { + trigger = false; + } }; bool capture_input_on_drag; @@ -57,30 +56,28 @@ class CollisionObject : public Spatial { void _update_pickable(); void _update_shapes(); -friend class CollisionShape; -friend class CollisionPolygon; + friend class CollisionShape; + friend class CollisionPolygon; void _update_shapes_from_children(); -protected: +protected: CollisionObject(RID p_rid, bool p_area); void _notification(int p_what); - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; static void _bind_methods(); -friend class Viewport; - virtual void _input_event(Node* p_camera,const InputEvent& p_input_event,const Vector3& p_pos, const Vector3& p_normal, int p_shape); + friend class Viewport; + virtual void _input_event(Node *p_camera, const InputEvent &p_input_event, const Vector3 &p_pos, const Vector3 &p_normal, int p_shape); virtual void _mouse_enter(); virtual void _mouse_exit(); public: - - - void add_shape(const Ref& p_shape, const Transform& p_transform=Transform()); + void add_shape(const Ref &p_shape, const Transform &p_transform = Transform()); int get_shape_count() const; - void set_shape(int p_shape_idx, const Ref& p_shape); - void set_shape_transform(int p_shape_idx, const Transform& p_transform); + void set_shape(int p_shape_idx, const Ref &p_shape); + void set_shape_transform(int p_shape_idx, const Transform &p_transform); Ref get_shape(int p_shape_idx) const; Transform get_shape_transform(int p_shape_idx) const; void remove_shape(int p_shape_idx); @@ -94,7 +91,6 @@ public: void set_capture_input_on_drag(bool p_capture); bool get_capture_input_on_drag() const; - _FORCE_INLINE_ RID get_rid() const { return rid; } CollisionObject(); diff --git a/scene/3d/collision_polygon.cpp b/scene/3d/collision_polygon.cpp index 82637c248..12dab067d 100644 --- a/scene/3d/collision_polygon.cpp +++ b/scene/3d/collision_polygon.cpp @@ -40,44 +40,43 @@ void CollisionPolygon::_add_to_collision_object(Object *p_obj) { CollisionObject *co = p_obj->cast_to(); ERR_FAIL_COND(!co); - if (polygon.size()==0) + if (polygon.size() == 0) return; - bool solids=build_mode==BUILD_SOLIDS; + bool solids = build_mode == BUILD_SOLIDS; - Vector< Vector > decomp = Geometry::decompose_polygon(polygon); - if (decomp.size()==0) + Vector > decomp = Geometry::decompose_polygon(polygon); + if (decomp.size() == 0) return; if (true || solids) { //here comes the sun, lalalala //decompose concave into multiple convex polygons and add them - shape_from=co->get_shape_count(); - for(int i=0;i convex = memnew( ConvexPolygonShape ); + shape_from = co->get_shape_count(); + for (int i = 0; i < decomp.size(); i++) { + Ref convex = memnew(ConvexPolygonShape); PoolVector cp; int cs = decomp[i].size(); - cp.resize(cs*2); + cp.resize(cs * 2); { PoolVector::Write w = cp.write(); - int idx=0; - for(int j=0;jset_points(cp); - co->add_shape(convex,get_transform()); - + co->add_shape(convex, get_transform()); } - shape_to=co->get_shape_count()-1; - if (shape_toget_shape_count() - 1; + if (shape_to < shape_from) { + shape_from = -1; + shape_to = -1; } } else { @@ -100,9 +99,7 @@ void CollisionPolygon::_add_to_collision_object(Object *p_obj) { #endif } - //co->add_shape(shape,get_transform()); - } void CollisionPolygon::_update_parent() { @@ -119,29 +116,28 @@ void CollisionPolygon::_update_parent() { co->_update_shapes_from_children(); } -void CollisionPolygon::_set_shape_range(const Vector2& p_range) { +void CollisionPolygon::_set_shape_range(const Vector2 &p_range) { - shape_from=p_range.x; - shape_to=p_range.y; + shape_from = p_range.x; + shape_to = p_range.y; } Vector2 CollisionPolygon::_get_shape_range() const { - return Vector2(shape_from,shape_to); + return Vector2(shape_from, shape_to); } void CollisionPolygon::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - can_update_body=get_tree()->is_editor_hint(); + can_update_body = get_tree()->is_editor_hint(); set_notify_local_transform(!can_update_body); //indicator_instance = VisualServer::get_singleton()->instance_create2(indicator,get_world()->get_scenario()); } break; case NOTIFICATION_EXIT_TREE: { - can_update_body=false; + can_update_body = false; set_notify_local_transform(false); } break; case NOTIFICATION_TRANSFORM_CHANGED: { @@ -154,12 +150,12 @@ void CollisionPolygon::_notification(int p_what) { } break; case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: { - if (!can_update_body && shape_from>=0 && shape_to>=0) { + if (!can_update_body && shape_from >= 0 && shape_to >= 0) { CollisionObject *co = get_parent()->cast_to(); if (co) { - for(int i=shape_from;i<=shape_to;i++) { - co->set_shape_transform(i,get_transform()); + for (int i = shape_from; i <= shape_to; i++) { + co->set_shape_transform(i, get_transform()); } } } @@ -190,31 +186,29 @@ void CollisionPolygon::_notification(int p_what) { } } -void CollisionPolygon::set_polygon(const Vector& p_polygon) { +void CollisionPolygon::set_polygon(const Vector &p_polygon) { - polygon=p_polygon; + polygon = p_polygon; if (can_update_body) { - for(int i=0;i CollisionPolygon::get_polygon() const { void CollisionPolygon::set_build_mode(BuildMode p_mode) { - ERR_FAIL_INDEX(p_mode,2); - build_mode=p_mode; + ERR_FAIL_INDEX(p_mode, 2); + build_mode = p_mode; if (!can_update_body) return; _update_parent(); } -CollisionPolygon::BuildMode CollisionPolygon::get_build_mode() const{ +CollisionPolygon::BuildMode CollisionPolygon::get_build_mode() const { return build_mode; } @@ -247,7 +241,7 @@ Rect3 CollisionPolygon::get_item_rect() const { void CollisionPolygon::set_depth(float p_depth) { - depth=p_depth; + depth = p_depth; if (!can_update_body) return; _update_parent(); @@ -267,7 +261,6 @@ String CollisionPolygon::get_configuration_warning() const { if (polygon.empty()) { return TTR("An empty CollisionPolygon has no effect on collision."); - } return String(); @@ -275,37 +268,36 @@ String CollisionPolygon::get_configuration_warning() const { void CollisionPolygon::_bind_methods() { - ClassDB::bind_method(D_METHOD("_add_to_collision_object"),&CollisionPolygon::_add_to_collision_object); + ClassDB::bind_method(D_METHOD("_add_to_collision_object"), &CollisionPolygon::_add_to_collision_object); - ClassDB::bind_method(D_METHOD("set_build_mode","build_mode"),&CollisionPolygon::set_build_mode); - ClassDB::bind_method(D_METHOD("get_build_mode"),&CollisionPolygon::get_build_mode); + ClassDB::bind_method(D_METHOD("set_build_mode", "build_mode"), &CollisionPolygon::set_build_mode); + ClassDB::bind_method(D_METHOD("get_build_mode"), &CollisionPolygon::get_build_mode); - ClassDB::bind_method(D_METHOD("set_depth","depth"),&CollisionPolygon::set_depth); - ClassDB::bind_method(D_METHOD("get_depth"),&CollisionPolygon::get_depth); + ClassDB::bind_method(D_METHOD("set_depth", "depth"), &CollisionPolygon::set_depth); + ClassDB::bind_method(D_METHOD("get_depth"), &CollisionPolygon::get_depth); - ClassDB::bind_method(D_METHOD("set_polygon","polygon"),&CollisionPolygon::set_polygon); - ClassDB::bind_method(D_METHOD("get_polygon"),&CollisionPolygon::get_polygon); + ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &CollisionPolygon::set_polygon); + ClassDB::bind_method(D_METHOD("get_polygon"), &CollisionPolygon::get_polygon); - ClassDB::bind_method(D_METHOD("_set_shape_range","shape_range"),&CollisionPolygon::_set_shape_range); - ClassDB::bind_method(D_METHOD("_get_shape_range"),&CollisionPolygon::_get_shape_range); + ClassDB::bind_method(D_METHOD("_set_shape_range", "shape_range"), &CollisionPolygon::_set_shape_range); + ClassDB::bind_method(D_METHOD("_get_shape_range"), &CollisionPolygon::_get_shape_range); - ClassDB::bind_method(D_METHOD("get_collision_object_first_shape"),&CollisionPolygon::get_collision_object_first_shape); - ClassDB::bind_method(D_METHOD("get_collision_object_last_shape"),&CollisionPolygon::get_collision_object_last_shape); + ClassDB::bind_method(D_METHOD("get_collision_object_first_shape"), &CollisionPolygon::get_collision_object_first_shape); + ClassDB::bind_method(D_METHOD("get_collision_object_last_shape"), &CollisionPolygon::get_collision_object_last_shape); - ADD_PROPERTY( PropertyInfo(Variant::INT,"build_mode",PROPERTY_HINT_ENUM,"Solids,Triangles"),"set_build_mode","get_build_mode"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"depth"),"set_depth","get_depth"); - ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"polygon"),"set_polygon","get_polygon"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"shape_range",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_shape_range","_get_shape_range"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "build_mode", PROPERTY_HINT_ENUM, "Solids,Triangles"), "set_build_mode", "get_build_mode"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "depth"), "set_depth", "get_depth"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "shape_range", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_shape_range", "_get_shape_range"); } CollisionPolygon::CollisionPolygon() { - shape_from=-1; - shape_to=-1; - can_update_body=false; - - aabb=Rect3(Vector3(-1,-1,-1),Vector3(2,2,2)); - build_mode=BUILD_SOLIDS; - depth=1.0; + shape_from = -1; + shape_to = -1; + can_update_body = false; + aabb = Rect3(Vector3(-1, -1, -1), Vector3(2, 2, 2)); + build_mode = BUILD_SOLIDS; + depth = 1.0; } diff --git a/scene/3d/collision_polygon.h b/scene/3d/collision_polygon.h index 693cf0640..fee146a87 100644 --- a/scene/3d/collision_polygon.h +++ b/scene/3d/collision_polygon.h @@ -32,27 +32,22 @@ #include "scene/3d/spatial.h" #include "scene/resources/shape.h" - - class CollisionPolygon : public Spatial { - GDCLASS(CollisionPolygon,Spatial); -public: + GDCLASS(CollisionPolygon, Spatial); +public: enum BuildMode { BUILD_SOLIDS, BUILD_TRIANGLES, }; protected: - - float depth; Rect3 aabb; BuildMode build_mode; Vector polygon; - void _add_to_collision_object(Object *p_obj); void _update_parent(); @@ -60,22 +55,21 @@ protected: int shape_from; int shape_to; - void _set_shape_range(const Vector2& p_range); + void _set_shape_range(const Vector2 &p_range); Vector2 _get_shape_range() const; protected: - void _notification(int p_what); static void _bind_methods(); -public: +public: void set_build_mode(BuildMode p_mode); BuildMode get_build_mode() const; void set_depth(float p_depth); float get_depth() const; - void set_polygon(const Vector& p_polygon); + void set_polygon(const Vector &p_polygon); Vector get_polygon() const; virtual Rect3 get_item_rect() const; @@ -88,5 +82,5 @@ public: CollisionPolygon(); }; -VARIANT_ENUM_CAST( CollisionPolygon::BuildMode ); +VARIANT_ENUM_CAST(CollisionPolygon::BuildMode); #endif // COLLISION_POLYGON_H diff --git a/scene/3d/gi_probe.cpp b/scene/3d/gi_probe.cpp index b22795e74..cb1292a9d 100644 --- a/scene/3d/gi_probe.cpp +++ b/scene/3d/gi_probe.cpp @@ -30,180 +30,158 @@ #include "mesh_instance.h" +void GIProbeData::set_bounds(const Rect3 &p_bounds) { -void GIProbeData::set_bounds(const Rect3& p_bounds) { - - VS::get_singleton()->gi_probe_set_bounds(probe,p_bounds); + VS::get_singleton()->gi_probe_set_bounds(probe, p_bounds); } -Rect3 GIProbeData::get_bounds() const{ +Rect3 GIProbeData::get_bounds() const { return VS::get_singleton()->gi_probe_get_bounds(probe); } void GIProbeData::set_cell_size(float p_size) { - VS::get_singleton()->gi_probe_set_cell_size(probe,p_size); - + VS::get_singleton()->gi_probe_set_cell_size(probe, p_size); } float GIProbeData::get_cell_size() const { return VS::get_singleton()->gi_probe_get_cell_size(probe); - } -void GIProbeData::set_to_cell_xform(const Transform& p_xform) { - - VS::get_singleton()->gi_probe_set_to_cell_xform(probe,p_xform); +void GIProbeData::set_to_cell_xform(const Transform &p_xform) { + VS::get_singleton()->gi_probe_set_to_cell_xform(probe, p_xform); } Transform GIProbeData::get_to_cell_xform() const { return VS::get_singleton()->gi_probe_get_to_cell_xform(probe); - } +void GIProbeData::set_dynamic_data(const PoolVector &p_data) { -void GIProbeData::set_dynamic_data(const PoolVector& p_data){ - - VS::get_singleton()->gi_probe_set_dynamic_data(probe,p_data); - + VS::get_singleton()->gi_probe_set_dynamic_data(probe, p_data); } -PoolVector GIProbeData::get_dynamic_data() const{ +PoolVector GIProbeData::get_dynamic_data() const { return VS::get_singleton()->gi_probe_get_dynamic_data(probe); } -void GIProbeData::set_dynamic_range(int p_range){ - - VS::get_singleton()->gi_probe_set_dynamic_range(probe,p_range); +void GIProbeData::set_dynamic_range(int p_range) { + VS::get_singleton()->gi_probe_set_dynamic_range(probe, p_range); } void GIProbeData::set_energy(float p_range) { - VS::get_singleton()->gi_probe_set_energy(probe,p_range); + VS::get_singleton()->gi_probe_set_energy(probe, p_range); } -float GIProbeData::get_energy() const{ +float GIProbeData::get_energy() const { return VS::get_singleton()->gi_probe_get_energy(probe); - } - void GIProbeData::set_bias(float p_range) { - VS::get_singleton()->gi_probe_set_bias(probe,p_range); + VS::get_singleton()->gi_probe_set_bias(probe, p_range); } -float GIProbeData::get_bias() const{ +float GIProbeData::get_bias() const { return VS::get_singleton()->gi_probe_get_bias(probe); - } - void GIProbeData::set_propagation(float p_range) { - VS::get_singleton()->gi_probe_set_propagation(probe,p_range); + VS::get_singleton()->gi_probe_set_propagation(probe, p_range); } -float GIProbeData::get_propagation() const{ +float GIProbeData::get_propagation() const { return VS::get_singleton()->gi_probe_get_propagation(probe); - } - void GIProbeData::set_interior(bool p_enable) { - VS::get_singleton()->gi_probe_set_interior(probe,p_enable); - + VS::get_singleton()->gi_probe_set_interior(probe, p_enable); } -bool GIProbeData::is_interior() const{ +bool GIProbeData::is_interior() const { return VS::get_singleton()->gi_probe_is_interior(probe); } - -bool GIProbeData::is_compressed() const{ +bool GIProbeData::is_compressed() const { return VS::get_singleton()->gi_probe_is_compressed(probe); } - void GIProbeData::set_compress(bool p_enable) { - VS::get_singleton()->gi_probe_set_compress(probe,p_enable); - + VS::get_singleton()->gi_probe_set_compress(probe, p_enable); } -int GIProbeData::get_dynamic_range() const{ - +int GIProbeData::get_dynamic_range() const { return VS::get_singleton()->gi_probe_get_dynamic_range(probe); } - RID GIProbeData::get_rid() const { return probe; } - void GIProbeData::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_bounds","bounds"),&GIProbeData::set_bounds); - ClassDB::bind_method(D_METHOD("get_bounds"),&GIProbeData::get_bounds); + ClassDB::bind_method(D_METHOD("set_bounds", "bounds"), &GIProbeData::set_bounds); + ClassDB::bind_method(D_METHOD("get_bounds"), &GIProbeData::get_bounds); - ClassDB::bind_method(D_METHOD("set_cell_size","cell_size"),&GIProbeData::set_cell_size); - ClassDB::bind_method(D_METHOD("get_cell_size"),&GIProbeData::get_cell_size); + ClassDB::bind_method(D_METHOD("set_cell_size", "cell_size"), &GIProbeData::set_cell_size); + ClassDB::bind_method(D_METHOD("get_cell_size"), &GIProbeData::get_cell_size); - ClassDB::bind_method(D_METHOD("set_to_cell_xform","to_cell_xform"),&GIProbeData::set_to_cell_xform); - ClassDB::bind_method(D_METHOD("get_to_cell_xform"),&GIProbeData::get_to_cell_xform); + ClassDB::bind_method(D_METHOD("set_to_cell_xform", "to_cell_xform"), &GIProbeData::set_to_cell_xform); + ClassDB::bind_method(D_METHOD("get_to_cell_xform"), &GIProbeData::get_to_cell_xform); - ClassDB::bind_method(D_METHOD("set_dynamic_data","dynamic_data"),&GIProbeData::set_dynamic_data); - ClassDB::bind_method(D_METHOD("get_dynamic_data"),&GIProbeData::get_dynamic_data); + ClassDB::bind_method(D_METHOD("set_dynamic_data", "dynamic_data"), &GIProbeData::set_dynamic_data); + ClassDB::bind_method(D_METHOD("get_dynamic_data"), &GIProbeData::get_dynamic_data); - ClassDB::bind_method(D_METHOD("set_dynamic_range","dynamic_range"),&GIProbeData::set_dynamic_range); - ClassDB::bind_method(D_METHOD("get_dynamic_range"),&GIProbeData::get_dynamic_range); + ClassDB::bind_method(D_METHOD("set_dynamic_range", "dynamic_range"), &GIProbeData::set_dynamic_range); + ClassDB::bind_method(D_METHOD("get_dynamic_range"), &GIProbeData::get_dynamic_range); - ClassDB::bind_method(D_METHOD("set_energy","energy"),&GIProbeData::set_energy); - ClassDB::bind_method(D_METHOD("get_energy"),&GIProbeData::get_energy); + ClassDB::bind_method(D_METHOD("set_energy", "energy"), &GIProbeData::set_energy); + ClassDB::bind_method(D_METHOD("get_energy"), &GIProbeData::get_energy); - ClassDB::bind_method(D_METHOD("set_bias","bias"),&GIProbeData::set_bias); - ClassDB::bind_method(D_METHOD("get_bias"),&GIProbeData::get_bias); + ClassDB::bind_method(D_METHOD("set_bias", "bias"), &GIProbeData::set_bias); + ClassDB::bind_method(D_METHOD("get_bias"), &GIProbeData::get_bias); - ClassDB::bind_method(D_METHOD("set_propagation","propagation"),&GIProbeData::set_propagation); - ClassDB::bind_method(D_METHOD("get_propagation"),&GIProbeData::get_propagation); + ClassDB::bind_method(D_METHOD("set_propagation", "propagation"), &GIProbeData::set_propagation); + ClassDB::bind_method(D_METHOD("get_propagation"), &GIProbeData::get_propagation); - ClassDB::bind_method(D_METHOD("set_interior","interior"),&GIProbeData::set_interior); - ClassDB::bind_method(D_METHOD("is_interior"),&GIProbeData::is_interior); + ClassDB::bind_method(D_METHOD("set_interior", "interior"), &GIProbeData::set_interior); + ClassDB::bind_method(D_METHOD("is_interior"), &GIProbeData::is_interior); - ClassDB::bind_method(D_METHOD("set_compress","compress"),&GIProbeData::set_compress); - ClassDB::bind_method(D_METHOD("is_compressed"),&GIProbeData::is_compressed); + ClassDB::bind_method(D_METHOD("set_compress", "compress"), &GIProbeData::set_compress); + ClassDB::bind_method(D_METHOD("is_compressed"), &GIProbeData::is_compressed); - ADD_PROPERTY(PropertyInfo(Variant::RECT3,"bounds",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_bounds","get_bounds"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"cell_size",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_cell_size","get_cell_size"); - ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM,"to_cell_xform",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_to_cell_xform","get_to_cell_xform"); - - ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY,"dynamic_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_dynamic_data","get_dynamic_data"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"dynamic_range",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_dynamic_range","get_dynamic_range"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"energy",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_energy","get_energy"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"bias",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_bias","get_bias"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"propagation",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_propagation","get_propagation"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"interior",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_interior","is_interior"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"compress",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_compress","is_compressed"); + ADD_PROPERTY(PropertyInfo(Variant::RECT3, "bounds", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_bounds", "get_bounds"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "cell_size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_cell_size", "get_cell_size"); + ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "to_cell_xform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_to_cell_xform", "get_to_cell_xform"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY, "dynamic_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_dynamic_data", "get_dynamic_data"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "dynamic_range", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_dynamic_range", "get_dynamic_range"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "energy", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_energy", "get_energy"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_bias", "get_bias"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "propagation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_propagation", "get_propagation"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_interior", "is_interior"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "compress", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_compress", "is_compressed"); } GIProbeData::GIProbeData() { - probe=VS::get_singleton()->gi_probe_create(); + probe = VS::get_singleton()->gi_probe_create(); } GIProbeData::~GIProbeData() { @@ -211,20 +189,18 @@ GIProbeData::~GIProbeData() { VS::get_singleton()->free(probe); } - ////////////////////// ////////////////////// - -void GIProbe::set_probe_data(const Ref& p_data) { +void GIProbe::set_probe_data(const Ref &p_data) { if (p_data.is_valid()) { - VS::get_singleton()->instance_set_base(get_instance(),p_data->get_rid()); + VS::get_singleton()->instance_set_base(get_instance(), p_data->get_rid()); } else { - VS::get_singleton()->instance_set_base(get_instance(),RID()); + VS::get_singleton()->instance_set_base(get_instance(), RID()); } - probe_data=p_data; + probe_data = p_data; } Ref GIProbe::get_probe_data() const { @@ -234,8 +210,8 @@ Ref GIProbe::get_probe_data() const { void GIProbe::set_subdiv(Subdiv p_subdiv) { - ERR_FAIL_INDEX(p_subdiv,SUBDIV_MAX); - subdiv=p_subdiv; + ERR_FAIL_INDEX(p_subdiv, SUBDIV_MAX); + subdiv = p_subdiv; update_gizmo(); } @@ -244,9 +220,9 @@ GIProbe::Subdiv GIProbe::get_subdiv() const { return subdiv; } -void GIProbe::set_extents(const Vector3& p_extents) { +void GIProbe::set_extents(const Vector3 &p_extents) { - extents=p_extents; + extents = p_extents; update_gizmo(); } @@ -257,7 +233,7 @@ Vector3 GIProbe::get_extents() const { void GIProbe::set_dynamic_range(int p_dynamic_range) { - dynamic_range=p_dynamic_range; + dynamic_range = p_dynamic_range; } int GIProbe::get_dynamic_range() const { @@ -266,7 +242,7 @@ int GIProbe::get_dynamic_range() const { void GIProbe::set_energy(float p_energy) { - energy=p_energy; + energy = p_energy; if (probe_data.is_valid()) { probe_data->set_energy(energy); } @@ -278,7 +254,7 @@ float GIProbe::get_energy() const { void GIProbe::set_bias(float p_bias) { - bias=p_bias; + bias = p_bias; if (probe_data.is_valid()) { probe_data->set_bias(bias); } @@ -290,7 +266,7 @@ float GIProbe::get_bias() const { void GIProbe::set_propagation(float p_propagation) { - propagation=p_propagation; + propagation = p_propagation; if (probe_data.is_valid()) { probe_data->set_propagation(propagation); } @@ -302,7 +278,7 @@ float GIProbe::get_propagation() const { void GIProbe::set_interior(bool p_enable) { - interior=p_enable; + interior = p_enable; if (probe_data.is_valid()) { probe_data->set_interior(p_enable); } @@ -313,10 +289,9 @@ bool GIProbe::is_interior() const { return interior; } - void GIProbe::set_compress(bool p_enable) { - compress=p_enable; + compress = p_enable; if (probe_data.is_valid()) { probe_data->set_compress(p_enable); } @@ -327,263 +302,287 @@ bool GIProbe::is_compressed() const { return compress; } - #include "math.h" -#define FINDMINMAX(x0,x1,x2,min,max) \ - min = max = x0; \ - if(x1max) max=x1;\ - if(x2max) max=x2; - -static bool planeBoxOverlap(Vector3 normal,float d, Vector3 maxbox) -{ - int q; - Vector3 vmin,vmax; - for(q=0;q<=2;q++) - { - if(normal[q]>0.0f) - { - vmin[q]=-maxbox[q]; - vmax[q]=maxbox[q]; - } - else - { - vmin[q]=maxbox[q]; - vmax[q]=-maxbox[q]; - } - } - if(normal.dot(vmin)+d>0.0f) return false; - if(normal.dot(vmax)+d>=0.0f) return true; - - return false; -} +#define FINDMINMAX(x0, x1, x2, min, max) \ + min = max = x0; \ + if (x1 < min) min = x1; \ + if (x1 > max) max = x1; \ + if (x2 < min) min = x2; \ + if (x2 > max) max = x2; + +static bool planeBoxOverlap(Vector3 normal, float d, Vector3 maxbox) { + int q; + Vector3 vmin, vmax; + for (q = 0; q <= 2; q++) { + if (normal[q] > 0.0f) { + vmin[q] = -maxbox[q]; + vmax[q] = maxbox[q]; + } else { + vmin[q] = maxbox[q]; + vmax[q] = -maxbox[q]; + } + } + if (normal.dot(vmin) + d > 0.0f) return false; + if (normal.dot(vmax) + d >= 0.0f) return true; + return false; +} /*======================== X-tests ========================*/ -#define AXISTEST_X01(a, b, fa, fb) \ - p0 = a*v0.y - b*v0.z; \ - p2 = a*v2.y - b*v2.z; \ - if(p0rad || max<-rad) return false; - -#define AXISTEST_X2(a, b, fa, fb) \ - p0 = a*v0.y - b*v0.z; \ - p1 = a*v1.y - b*v1.z; \ - if(p0rad || max<-rad) return false; +#define AXISTEST_X01(a, b, fa, fb) \ + p0 = a * v0.y - b * v0.z; \ + p2 = a * v2.y - b * v2.z; \ + if (p0 < p2) { \ + min = p0; \ + max = p2; \ + } else { \ + min = p2; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \ + if (min > rad || max < -rad) return false; + +#define AXISTEST_X2(a, b, fa, fb) \ + p0 = a * v0.y - b * v0.z; \ + p1 = a * v1.y - b * v1.z; \ + if (p0 < p1) { \ + min = p0; \ + max = p1; \ + } else { \ + min = p1; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \ + if (min > rad || max < -rad) return false; /*======================== Y-tests ========================*/ -#define AXISTEST_Y02(a, b, fa, fb) \ - p0 = -a*v0.x + b*v0.z; \ - p2 = -a*v2.x + b*v2.z; \ - if(p0rad || max<-rad) return false; - -#define AXISTEST_Y1(a, b, fa, fb) \ - p0 = -a*v0.x + b*v0.z; \ - p1 = -a*v1.x + b*v1.z; \ - if(p0rad || max<-rad) return false; +#define AXISTEST_Y02(a, b, fa, fb) \ + p0 = -a * v0.x + b * v0.z; \ + p2 = -a * v2.x + b * v2.z; \ + if (p0 < p2) { \ + min = p0; \ + max = p2; \ + } else { \ + min = p2; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \ + if (min > rad || max < -rad) return false; + +#define AXISTEST_Y1(a, b, fa, fb) \ + p0 = -a * v0.x + b * v0.z; \ + p1 = -a * v1.x + b * v1.z; \ + if (p0 < p1) { \ + min = p0; \ + max = p1; \ + } else { \ + min = p1; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \ + if (min > rad || max < -rad) return false; /*======================== Z-tests ========================*/ -#define AXISTEST_Z12(a, b, fa, fb) \ - p1 = a*v1.x - b*v1.y; \ - p2 = a*v2.x - b*v2.y; \ - if(p2rad || max<-rad) return false; - -#define AXISTEST_Z0(a, b, fa, fb) \ - p0 = a*v0.x - b*v0.y; \ - p1 = a*v1.x - b*v1.y; \ - if(p0rad || max<-rad) return false; - -static bool fast_tri_box_overlap(const Vector3& boxcenter,const Vector3 boxhalfsize,const Vector3 *triverts) { - - /* use separating axis theorem to test overlap between triangle and box */ - /* need to test for overlap in these directions: */ - /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */ - /* we do not even need to test these) */ - /* 2) normal of the triangle */ - /* 3) crossproduct(edge from tri, {x,y,z}-directin) */ - /* this gives 3x3=9 more tests */ - Vector3 v0,v1,v2; - float min,max,d,p0,p1,p2,rad,fex,fey,fez; - Vector3 normal,e0,e1,e2; - - /* This is the fastest branch on Sun */ - /* move everything so that the boxcenter is in (0,0,0) */ - - v0=triverts[0]-boxcenter; - v1=triverts[1]-boxcenter; - v2=triverts[2]-boxcenter; - - /* compute triangle edges */ - e0=v1-v0; /* tri edge 0 */ - e1=v2-v1; /* tri edge 1 */ - e2=v0-v2; /* tri edge 2 */ - - /* Bullet 3: */ - /* test the 9 tests first (this was faster) */ - fex = Math::abs(e0.x); - fey = Math::abs(e0.y); - fez = Math::abs(e0.z); - AXISTEST_X01(e0.z, e0.y, fez, fey); - AXISTEST_Y02(e0.z, e0.x, fez, fex); - AXISTEST_Z12(e0.y, e0.x, fey, fex); - - fex = Math::abs(e1.x); - fey = Math::abs(e1.y); - fez = Math::abs(e1.z); - AXISTEST_X01(e1.z, e1.y, fez, fey); - AXISTEST_Y02(e1.z, e1.x, fez, fex); - AXISTEST_Z0(e1.y, e1.x, fey, fex); - - fex = Math::abs(e2.x); - fey = Math::abs(e2.y); - fez = Math::abs(e2.z); - AXISTEST_X2(e2.z, e2.y, fez, fey); - AXISTEST_Y1(e2.z, e2.x, fez, fex); - AXISTEST_Z12(e2.y, e2.x, fey, fex); - - /* Bullet 1: */ - /* first test overlap in the {x,y,z}-directions */ - /* find min, max of the triangle each direction, and test for overlap in */ - /* that direction -- this is equivalent to testing a minimal AABB around */ - /* the triangle against the AABB */ - - /* test in X-direction */ - FINDMINMAX(v0.x,v1.x,v2.x,min,max); - if(min>boxhalfsize.x || max<-boxhalfsize.x) return false; - - /* test in Y-direction */ - FINDMINMAX(v0.y,v1.y,v2.y,min,max); - if(min>boxhalfsize.y || max<-boxhalfsize.y) return false; - - /* test in Z-direction */ - FINDMINMAX(v0.z,v1.z,v2.z,min,max); - if(min>boxhalfsize.z || max<-boxhalfsize.z) return false; - - /* Bullet 2: */ - /* test if the box intersects the plane of the triangle */ - /* compute plane equation of triangle: normal*x+d=0 */ - normal=e0.cross(e1); - d=-normal.dot(v0); /* plane eq: normal.x+d=0 */ - if(!planeBoxOverlap(normal,d,boxhalfsize)) return false; - - return true; /* box and triangle overlaps */ +#define AXISTEST_Z12(a, b, fa, fb) \ + p1 = a * v1.x - b * v1.y; \ + p2 = a * v2.x - b * v2.y; \ + if (p2 < p1) { \ + min = p2; \ + max = p1; \ + } else { \ + min = p1; \ + max = p2; \ + } \ + rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \ + if (min > rad || max < -rad) return false; + +#define AXISTEST_Z0(a, b, fa, fb) \ + p0 = a * v0.x - b * v0.y; \ + p1 = a * v1.x - b * v1.y; \ + if (p0 < p1) { \ + min = p0; \ + max = p1; \ + } else { \ + min = p1; \ + max = p0; \ + } \ + rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \ + if (min > rad || max < -rad) return false; + +static bool fast_tri_box_overlap(const Vector3 &boxcenter, const Vector3 boxhalfsize, const Vector3 *triverts) { + + /* use separating axis theorem to test overlap between triangle and box */ + /* need to test for overlap in these directions: */ + /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */ + /* we do not even need to test these) */ + /* 2) normal of the triangle */ + /* 3) crossproduct(edge from tri, {x,y,z}-directin) */ + /* this gives 3x3=9 more tests */ + Vector3 v0, v1, v2; + float min, max, d, p0, p1, p2, rad, fex, fey, fez; + Vector3 normal, e0, e1, e2; + + /* This is the fastest branch on Sun */ + /* move everything so that the boxcenter is in (0,0,0) */ + + v0 = triverts[0] - boxcenter; + v1 = triverts[1] - boxcenter; + v2 = triverts[2] - boxcenter; + + /* compute triangle edges */ + e0 = v1 - v0; /* tri edge 0 */ + e1 = v2 - v1; /* tri edge 1 */ + e2 = v0 - v2; /* tri edge 2 */ + + /* Bullet 3: */ + /* test the 9 tests first (this was faster) */ + fex = Math::abs(e0.x); + fey = Math::abs(e0.y); + fez = Math::abs(e0.z); + AXISTEST_X01(e0.z, e0.y, fez, fey); + AXISTEST_Y02(e0.z, e0.x, fez, fex); + AXISTEST_Z12(e0.y, e0.x, fey, fex); + + fex = Math::abs(e1.x); + fey = Math::abs(e1.y); + fez = Math::abs(e1.z); + AXISTEST_X01(e1.z, e1.y, fez, fey); + AXISTEST_Y02(e1.z, e1.x, fez, fex); + AXISTEST_Z0(e1.y, e1.x, fey, fex); + + fex = Math::abs(e2.x); + fey = Math::abs(e2.y); + fez = Math::abs(e2.z); + AXISTEST_X2(e2.z, e2.y, fez, fey); + AXISTEST_Y1(e2.z, e2.x, fez, fex); + AXISTEST_Z12(e2.y, e2.x, fey, fex); + + /* Bullet 1: */ + /* first test overlap in the {x,y,z}-directions */ + /* find min, max of the triangle each direction, and test for overlap in */ + /* that direction -- this is equivalent to testing a minimal AABB around */ + /* the triangle against the AABB */ + + /* test in X-direction */ + FINDMINMAX(v0.x, v1.x, v2.x, min, max); + if (min > boxhalfsize.x || max < -boxhalfsize.x) return false; + + /* test in Y-direction */ + FINDMINMAX(v0.y, v1.y, v2.y, min, max); + if (min > boxhalfsize.y || max < -boxhalfsize.y) return false; + + /* test in Z-direction */ + FINDMINMAX(v0.z, v1.z, v2.z, min, max); + if (min > boxhalfsize.z || max < -boxhalfsize.z) return false; + + /* Bullet 2: */ + /* test if the box intersects the plane of the triangle */ + /* compute plane equation of triangle: normal*x+d=0 */ + normal = e0.cross(e1); + d = -normal.dot(v0); /* plane eq: normal.x+d=0 */ + if (!planeBoxOverlap(normal, d, boxhalfsize)) return false; + + return true; /* box and triangle overlaps */ } +static _FORCE_INLINE_ Vector2 get_uv(const Vector3 &p_pos, const Vector3 *p_vtx, const Vector2 *p_uv) { - -static _FORCE_INLINE_ Vector2 get_uv(const Vector3& p_pos, const Vector3 *p_vtx, const Vector2* p_uv) { - - if (p_pos.distance_squared_to(p_vtx[0])cell_subdiv-1) { + if (p_level == p_baker->cell_subdiv - 1) { //plot the face by guessing it's albedo and emission value //find best axis to map to, for scanning values int closest_axis; float closest_dot; - Plane plane = Plane(p_vtx[0],p_vtx[1],p_vtx[2]); + Plane plane = Plane(p_vtx[0], p_vtx[1], p_vtx[2]); Vector3 normal = plane.normal; - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { Vector3 axis; - axis[i]=1.0; - float dot=ABS(normal.dot(axis)); - if (i==0 || dot>closest_dot) { - closest_axis=i; - closest_dot=dot; + axis[i] = 1.0; + float dot = ABS(normal.dot(axis)); + if (i == 0 || dot > closest_dot) { + closest_axis = i; + closest_dot = dot; } } - Vector3 axis; - axis[closest_axis]=1.0; + axis[closest_axis] = 1.0; Vector3 t1; - t1[(closest_axis+1)%3]=1.0; + t1[(closest_axis + 1) % 3] = 1.0; Vector3 t2; - t2[(closest_axis+2)%3]=1.0; + t2[(closest_axis + 2) % 3] = 1.0; - t1*=p_aabb.size[(closest_axis+1)%3]/float(color_scan_cell_width); - t2*=p_aabb.size[(closest_axis+2)%3]/float(color_scan_cell_width); + t1 *= p_aabb.size[(closest_axis + 1) % 3] / float(color_scan_cell_width); + t2 *= p_aabb.size[(closest_axis + 2) % 3] / float(color_scan_cell_width); Color albedo_accum; Color emission_accum; Vector3 normal_accum; - float alpha=0.0; + float alpha = 0.0; //map to a grid average in the best axis for this face - for(int i=0;ibake_cells[p_idx].albedo[0]+=albedo_accum.r; - p_baker->bake_cells[p_idx].albedo[1]+=albedo_accum.g; - p_baker->bake_cells[p_idx].albedo[2]+=albedo_accum.b; - p_baker->bake_cells[p_idx].emission[0]+=emission_accum.r; - p_baker->bake_cells[p_idx].emission[1]+=emission_accum.g; - p_baker->bake_cells[p_idx].emission[2]+=emission_accum.b; - p_baker->bake_cells[p_idx].normal[0]+=normal_accum.x; - p_baker->bake_cells[p_idx].normal[1]+=normal_accum.y; - p_baker->bake_cells[p_idx].normal[2]+=normal_accum.z; - p_baker->bake_cells[p_idx].alpha+=alpha; - - static const Vector3 side_normals[6]={ + p_baker->bake_cells[p_idx].albedo[0] += albedo_accum.r; + p_baker->bake_cells[p_idx].albedo[1] += albedo_accum.g; + p_baker->bake_cells[p_idx].albedo[2] += albedo_accum.b; + p_baker->bake_cells[p_idx].emission[0] += emission_accum.r; + p_baker->bake_cells[p_idx].emission[1] += emission_accum.g; + p_baker->bake_cells[p_idx].emission[2] += emission_accum.b; + p_baker->bake_cells[p_idx].normal[0] += normal_accum.x; + p_baker->bake_cells[p_idx].normal[1] += normal_accum.y; + p_baker->bake_cells[p_idx].normal[2] += normal_accum.z; + p_baker->bake_cells[p_idx].alpha += alpha; + + static const Vector3 side_normals[6] = { Vector3(-1, 0, 0), - Vector3( 1, 0, 0), - Vector3( 0,-1, 0), - Vector3( 0, 1, 0), - Vector3( 0, 0,-1), - Vector3( 0, 0, 1), + Vector3(1, 0, 0), + Vector3(0, -1, 0), + Vector3(0, 1, 0), + Vector3(0, 0, -1), + Vector3(0, 0, 1), }; /* @@ -691,104 +685,95 @@ void GIProbe::_plot_face(int p_idx, int p_level,int p_x,int p_y,int p_z, const V } }*/ - } else { //go down - int half = (1<<(p_baker->cell_subdiv-1)) >> (p_level+1); - for(int i=0;i<8;i++) { + int half = (1 << (p_baker->cell_subdiv - 1)) >> (p_level + 1); + for (int i = 0; i < 8; i++) { - Rect3 aabb=p_aabb; - aabb.size*=0.5; + Rect3 aabb = p_aabb; + aabb.size *= 0.5; - int nx=p_x; - int ny=p_y; - int nz=p_z; + int nx = p_x; + int ny = p_y; + int nz = p_z; - if (i&1) { - aabb.pos.x+=aabb.size.x; - nx+=half; + if (i & 1) { + aabb.pos.x += aabb.size.x; + nx += half; } - if (i&2) { - aabb.pos.y+=aabb.size.y; - ny+=half; + if (i & 2) { + aabb.pos.y += aabb.size.y; + ny += half; } - if (i&4) { - aabb.pos.z+=aabb.size.z; - nz+=half; + if (i & 4) { + aabb.pos.z += aabb.size.z; + nz += half; } //make sure to not plot beyond limits - if (nx<0 || nx>=p_baker->axis_cell_size[0] || ny<0 || ny>=p_baker->axis_cell_size[1] || nz<0 || nz>=p_baker->axis_cell_size[2]) + if (nx < 0 || nx >= p_baker->axis_cell_size[0] || ny < 0 || ny >= p_baker->axis_cell_size[1] || nz < 0 || nz >= p_baker->axis_cell_size[2]) continue; { - Rect3 test_aabb=aabb; + Rect3 test_aabb = aabb; //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time - Vector3 qsize = test_aabb.size*0.5; //quarter size, for fast aabb test + Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test - if (!fast_tri_box_overlap(test_aabb.pos+qsize,qsize,p_vtx)) { - //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) { + if (!fast_tri_box_overlap(test_aabb.pos + qsize, qsize, p_vtx)) { + //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) { //does not fit in child, go on continue; } - } - if (p_baker->bake_cells[p_idx].childs[i]==Baker::CHILD_EMPTY) { + if (p_baker->bake_cells[p_idx].childs[i] == Baker::CHILD_EMPTY) { //sub cell must be created uint32_t child_idx = p_baker->bake_cells.size(); - p_baker->bake_cells[p_idx].childs[i]=child_idx; - p_baker->bake_cells.resize( p_baker->bake_cells.size() + 1); - p_baker->bake_cells[child_idx].level=p_level+1; - + p_baker->bake_cells[p_idx].childs[i] = child_idx; + p_baker->bake_cells.resize(p_baker->bake_cells.size() + 1); + p_baker->bake_cells[child_idx].level = p_level + 1; } - - _plot_face(p_baker->bake_cells[p_idx].childs[i],p_level+1,nx,ny,nz,p_vtx,p_uv,p_material,aabb,p_baker); + _plot_face(p_baker->bake_cells[p_idx].childs[i], p_level + 1, nx, ny, nz, p_vtx, p_uv, p_material, aabb, p_baker); } } } +void GIProbe::_fixup_plot(int p_idx, int p_level, int p_x, int p_y, int p_z, Baker *p_baker) { - -void GIProbe::_fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z,Baker *p_baker) { - - - - if (p_level==p_baker->cell_subdiv-1) { + if (p_level == p_baker->cell_subdiv - 1) { p_baker->leaf_voxel_count++; float alpha = p_baker->bake_cells[p_idx].alpha; - p_baker->bake_cells[p_idx].albedo[0]/=alpha; - p_baker->bake_cells[p_idx].albedo[1]/=alpha; - p_baker->bake_cells[p_idx].albedo[2]/=alpha; + p_baker->bake_cells[p_idx].albedo[0] /= alpha; + p_baker->bake_cells[p_idx].albedo[1] /= alpha; + p_baker->bake_cells[p_idx].albedo[2] /= alpha; //transfer emission to light - p_baker->bake_cells[p_idx].emission[0]/=alpha; - p_baker->bake_cells[p_idx].emission[1]/=alpha; - p_baker->bake_cells[p_idx].emission[2]/=alpha; + p_baker->bake_cells[p_idx].emission[0] /= alpha; + p_baker->bake_cells[p_idx].emission[1] /= alpha; + p_baker->bake_cells[p_idx].emission[2] /= alpha; - p_baker->bake_cells[p_idx].normal[0]/=alpha; - p_baker->bake_cells[p_idx].normal[1]/=alpha; - p_baker->bake_cells[p_idx].normal[2]/=alpha; + p_baker->bake_cells[p_idx].normal[0] /= alpha; + p_baker->bake_cells[p_idx].normal[1] /= alpha; + p_baker->bake_cells[p_idx].normal[2] /= alpha; - Vector3 n(p_baker->bake_cells[p_idx].normal[0],p_baker->bake_cells[p_idx].normal[1],p_baker->bake_cells[p_idx].normal[2]); - if (n.length()<0.01) { + Vector3 n(p_baker->bake_cells[p_idx].normal[0], p_baker->bake_cells[p_idx].normal[1], p_baker->bake_cells[p_idx].normal[2]); + if (n.length() < 0.01) { //too much fight over normal, zero it - p_baker->bake_cells[p_idx].normal[0]=0; - p_baker->bake_cells[p_idx].normal[1]=0; - p_baker->bake_cells[p_idx].normal[2]=0; + p_baker->bake_cells[p_idx].normal[0] = 0; + p_baker->bake_cells[p_idx].normal[1] = 0; + p_baker->bake_cells[p_idx].normal[2] = 0; } else { n.normalize(); - p_baker->bake_cells[p_idx].normal[0]=n.x; - p_baker->bake_cells[p_idx].normal[1]=n.y; - p_baker->bake_cells[p_idx].normal[2]=n.z; + p_baker->bake_cells[p_idx].normal[0] = n.x; + p_baker->bake_cells[p_idx].normal[1] = n.y; + p_baker->bake_cells[p_idx].normal[2] = n.z; } - - p_baker->bake_cells[p_idx].alpha=1.0; + p_baker->bake_cells[p_idx].alpha = 1.0; /* //remove neighbours from used sides @@ -856,60 +841,54 @@ void GIProbe::_fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z,Baker */ } else { - //go down - float alpha_average=0; - int half = (1<<(p_baker->cell_subdiv-1)) >> (p_level+1); - for(int i=0;i<8;i++) { + float alpha_average = 0; + int half = (1 << (p_baker->cell_subdiv - 1)) >> (p_level + 1); + for (int i = 0; i < 8; i++) { uint32_t child = p_baker->bake_cells[p_idx].childs[i]; - if (child==Baker::CHILD_EMPTY) + if (child == Baker::CHILD_EMPTY) continue; + int nx = p_x; + int ny = p_y; + int nz = p_z; - int nx=p_x; - int ny=p_y; - int nz=p_z; - - if (i&1) - nx+=half; - if (i&2) - ny+=half; - if (i&4) - nz+=half; + if (i & 1) + nx += half; + if (i & 2) + ny += half; + if (i & 4) + nz += half; - _fixup_plot(child,p_level+1,nx,ny,nz,p_baker); - alpha_average+=p_baker->bake_cells[child].alpha; + _fixup_plot(child, p_level + 1, nx, ny, nz, p_baker); + alpha_average += p_baker->bake_cells[child].alpha; } - p_baker->bake_cells[p_idx].alpha=alpha_average/8.0; - p_baker->bake_cells[p_idx].emission[0]=0; - p_baker->bake_cells[p_idx].emission[1]=0; - p_baker->bake_cells[p_idx].emission[2]=0; - p_baker->bake_cells[p_idx].normal[0]=0; - p_baker->bake_cells[p_idx].normal[1]=0; - p_baker->bake_cells[p_idx].normal[2]=0; - p_baker->bake_cells[p_idx].albedo[0]=0; - p_baker->bake_cells[p_idx].albedo[1]=0; - p_baker->bake_cells[p_idx].albedo[2]=0; - + p_baker->bake_cells[p_idx].alpha = alpha_average / 8.0; + p_baker->bake_cells[p_idx].emission[0] = 0; + p_baker->bake_cells[p_idx].emission[1] = 0; + p_baker->bake_cells[p_idx].emission[2] = 0; + p_baker->bake_cells[p_idx].normal[0] = 0; + p_baker->bake_cells[p_idx].normal[1] = 0; + p_baker->bake_cells[p_idx].normal[2] = 0; + p_baker->bake_cells[p_idx].albedo[0] = 0; + p_baker->bake_cells[p_idx].albedo[1] = 0; + p_baker->bake_cells[p_idx].albedo[2] = 0; } - } - - -Vector GIProbe::_get_bake_texture(Image &p_image,const Color& p_color) { +Vector GIProbe::_get_bake_texture(Image &p_image, const Color &p_color) { Vector ret; if (p_image.empty()) { - ret.resize(bake_texture_size*bake_texture_size); - for(int i=0;i GIProbe::_get_bake_texture(Image &p_image,const Color& p_color) { p_image.decompress(); } p_image.convert(Image::FORMAT_RGBA8); - p_image.resize(bake_texture_size,bake_texture_size,Image::INTERPOLATE_CUBIC); - + p_image.resize(bake_texture_size, bake_texture_size, Image::INTERPOLATE_CUBIC); PoolVector::Read r = p_image.get_data().read(); - ret.resize(bake_texture_size*bake_texture_size); + ret.resize(bake_texture_size * bake_texture_size); - for(int i=0;i p_material,Baker *p_baker) { +GIProbe::Baker::MaterialCache GIProbe::_get_material_cache(Ref p_material, Baker *p_baker) { //this way of obtaining materials is inaccurate and also does not support some compressed formats very well Ref mat = p_material; @@ -962,17 +938,16 @@ GIProbe::Baker::MaterialCache GIProbe::_get_material_cache(Ref p_mater img_albedo = albedo_tex->get_data(); } else { - } - mc.albedo=_get_bake_texture(img_albedo,mat->get_albedo()); + mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo()); Ref emission_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_EMISSION); Color emission_col = mat->get_emission(); - emission_col.r*=mat->get_emission_energy(); - emission_col.g*=mat->get_emission_energy(); - emission_col.b*=mat->get_emission_energy(); + emission_col.r *= mat->get_emission_energy(); + emission_col.g *= mat->get_emission_energy(); + emission_col.b *= mat->get_emission_energy(); Image img_emission; @@ -981,122 +956,110 @@ GIProbe::Baker::MaterialCache GIProbe::_get_material_cache(Ref p_mater img_emission = emission_tex->get_data(); } - mc.emission=_get_bake_texture(img_emission,emission_col); + mc.emission = _get_bake_texture(img_emission, emission_col); } else { Image empty; - mc.albedo=_get_bake_texture(empty,Color(0.7,0.7,0.7)); - mc.emission=_get_bake_texture(empty,Color(0,0,0)); - - + mc.albedo = _get_bake_texture(empty, Color(0.7, 0.7, 0.7)); + mc.emission = _get_bake_texture(empty, Color(0, 0, 0)); } - p_baker->material_cache[p_material]=mc; + p_baker->material_cache[p_material] = mc; return mc; - - } -void GIProbe::_plot_mesh(const Transform& p_xform, Ref& p_mesh, Baker *p_baker, const Vector > &p_materials, const Ref &p_override_material) { +void GIProbe::_plot_mesh(const Transform &p_xform, Ref &p_mesh, Baker *p_baker, const Vector > &p_materials, const Ref &p_override_material) { + for (int i = 0; i < p_mesh->get_surface_count(); i++) { - for(int i=0;iget_surface_count();i++) { - - if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES) + if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) continue; //only triangles Ref src_material; if (p_override_material.is_valid()) { - src_material=p_override_material; - } else if (isurface_get_material(i); - + src_material = p_mesh->surface_get_material(i); } - Baker::MaterialCache material = _get_material_cache(src_material,p_baker); + Baker::MaterialCache material = _get_material_cache(src_material, p_baker); Array a = p_mesh->surface_get_arrays(i); - PoolVector vertices = a[Mesh::ARRAY_VERTEX]; - PoolVector::Read vr=vertices.read(); + PoolVector::Read vr = vertices.read(); PoolVector uv = a[Mesh::ARRAY_TEX_UV]; PoolVector::Read uvr; PoolVector index = a[Mesh::ARRAY_INDEX]; - bool read_uv=false; + bool read_uv = false; if (uv.size()) { - uvr=uv.read(); - read_uv=true; + uvr = uv.read(); + read_uv = true; } if (index.size()) { - int facecount = index.size()/3; - PoolVector::Read ir=index.read(); + int facecount = index.size() / 3; + PoolVector::Read ir = index.read(); - for(int j=0;jpo2_bounds,p_baker); + _plot_face(0, 0, 0, 0, 0, vtxs, uvs, material, p_baker->po2_bounds, p_baker); } - - } else { - int facecount = vertices.size()/3; + int facecount = vertices.size() / 3; - for(int j=0;jpo2_bounds,p_baker); + _plot_face(0, 0, 0, 0, 0, vtxs, uvs, material, p_baker->po2_bounds, p_baker); } - } } } - - -void GIProbe::_find_meshes(Node *p_at_node,Baker *p_baker){ +void GIProbe::_find_meshes(Node *p_at_node, Baker *p_baker) { MeshInstance *mi = p_at_node->cast_to(); if (mi && mi->get_flag(GeometryInstance::FLAG_USE_BAKED_LIGHT)) { @@ -1107,16 +1070,15 @@ void GIProbe::_find_meshes(Node *p_at_node,Baker *p_baker){ Transform xf = get_global_transform().affine_inverse() * mi->get_global_transform(); - if (Rect3(-extents,extents*2).intersects(xf.xform(aabb))) { + if (Rect3(-extents, extents * 2).intersects(xf.xform(aabb))) { Baker::PlotMesh pm; - pm.local_xform=xf; - pm.mesh=mesh; - for(int i=0;iget_surface_count();i++) { + pm.local_xform = xf; + pm.mesh = mesh; + for (int i = 0; i < mesh->get_surface_count(); i++) { pm.instance_materials.push_back(mi->get_surface_material(i)); } - pm.override_material=mi->get_material_override(); + pm.override_material = mi->get_material_override(); p_baker->mesh_list.push_back(pm); - } } } @@ -1125,10 +1087,10 @@ void GIProbe::_find_meshes(Node *p_at_node,Baker *p_baker){ Spatial *s = p_at_node->cast_to(); Array meshes = p_at_node->call("get_meshes"); - for(int i=0;i mesh = meshes[i+1]; + Ref mesh = meshes[i + 1]; if (!mesh.is_valid()) continue; @@ -1136,166 +1098,151 @@ void GIProbe::_find_meshes(Node *p_at_node,Baker *p_baker){ Transform xf = get_global_transform().affine_inverse() * (s->get_global_transform() * mxf); - if (Rect3(-extents,extents*2).intersects(xf.xform(aabb))) { + if (Rect3(-extents, extents * 2).intersects(xf.xform(aabb))) { Baker::PlotMesh pm; - pm.local_xform=xf; - pm.mesh=mesh; + pm.local_xform = xf; + pm.mesh = mesh; p_baker->mesh_list.push_back(pm); - } } } - for(int i=0;iget_child_count();i++) { + for (int i = 0; i < p_at_node->get_child_count(); i++) { Node *child = p_at_node->get_child(i); if (!child->get_owner()) continue; //maybe a helper - _find_meshes(child,p_baker); - + _find_meshes(child, p_baker); } } - - - -void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug){ +void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug) { Baker baker; - static const int subdiv_value[SUBDIV_MAX]={7,8,9,10}; + static const int subdiv_value[SUBDIV_MAX] = { 7, 8, 9, 10 }; - baker.cell_subdiv=subdiv_value[subdiv]; + baker.cell_subdiv = subdiv_value[subdiv]; baker.bake_cells.resize(1); //find out the actual real bounds, power of 2, which gets the highest subdivision - baker.po2_bounds=Rect3(-extents,extents*2.0); + baker.po2_bounds = Rect3(-extents, extents * 2.0); int longest_axis = baker.po2_bounds.get_longest_axis_index(); - baker.axis_cell_size[longest_axis]=(1<<(baker.cell_subdiv-1)); - baker.leaf_voxel_count=0; + baker.axis_cell_size[longest_axis] = (1 << (baker.cell_subdiv - 1)); + baker.leaf_voxel_count = 0; - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - if (i==longest_axis) + if (i == longest_axis) continue; - baker.axis_cell_size[i]=baker.axis_cell_size[longest_axis]; + baker.axis_cell_size[i] = baker.axis_cell_size[longest_axis]; float axis_size = baker.po2_bounds.size[longest_axis]; //shrink until fit subdiv - while (axis_size/2.0 >= baker.po2_bounds.size[i]) { - axis_size/=2.0; - baker.axis_cell_size[i]>>=1; + while (axis_size / 2.0 >= baker.po2_bounds.size[i]) { + axis_size /= 2.0; + baker.axis_cell_size[i] >>= 1; } - baker.po2_bounds.size[i]=baker.po2_bounds.size[longest_axis]; + baker.po2_bounds.size[i] = baker.po2_bounds.size[longest_axis]; } - - Transform to_bounds; - to_bounds.basis.scale(Vector3(baker.po2_bounds.size[longest_axis],baker.po2_bounds.size[longest_axis],baker.po2_bounds.size[longest_axis])); - to_bounds.origin=baker.po2_bounds.pos; + to_bounds.basis.scale(Vector3(baker.po2_bounds.size[longest_axis], baker.po2_bounds.size[longest_axis], baker.po2_bounds.size[longest_axis])); + to_bounds.origin = baker.po2_bounds.pos; Transform to_grid; - to_grid.basis.scale(Vector3(baker.axis_cell_size[longest_axis],baker.axis_cell_size[longest_axis],baker.axis_cell_size[longest_axis])); + to_grid.basis.scale(Vector3(baker.axis_cell_size[longest_axis], baker.axis_cell_size[longest_axis], baker.axis_cell_size[longest_axis])); baker.to_cell_space = to_grid * to_bounds.affine_inverse(); + _find_meshes(p_from_node ? p_from_node : get_parent(), &baker); - _find_meshes(p_from_node?p_from_node:get_parent(),&baker); - - + int pmc = 0; - int pmc=0; + for (List::Element *E = baker.mesh_list.front(); E; E = E->next()) { - for(List::Element *E=baker.mesh_list.front();E;E=E->next()) { + print_line("plotting mesh " + itos(pmc++) + "/" + itos(baker.mesh_list.size())); - print_line("plotting mesh "+itos(pmc++)+"/"+itos(baker.mesh_list.size())); - - _plot_mesh(E->get().local_xform,E->get().mesh,&baker,E->get().instance_materials,E->get().override_material); + _plot_mesh(E->get().local_xform, E->get().mesh, &baker, E->get().instance_materials, E->get().override_material); } - _fixup_plot(0,0,0,0,0,&baker); + _fixup_plot(0, 0, 0, 0, 0, &baker); //create the data for visual server PoolVector data; - data.resize( 16+(8+1+1+1+1)*baker.bake_cells.size() ); //4 for header, rest for rest. + data.resize(16 + (8 + 1 + 1 + 1 + 1) * baker.bake_cells.size()); //4 for header, rest for rest. { PoolVector::Write w = data.write(); - uint32_t * w32 = (uint32_t*)w.ptr(); + uint32_t *w32 = (uint32_t *)w.ptr(); - w32[0]=0;//version - w32[1]=baker.cell_subdiv; //subdiv - w32[2]=baker.axis_cell_size[0]; - w32[3]=baker.axis_cell_size[1]; - w32[4]=baker.axis_cell_size[2]; - w32[5]=baker.bake_cells.size(); - w32[6]=baker.leaf_voxel_count; + w32[0] = 0; //version + w32[1] = baker.cell_subdiv; //subdiv + w32[2] = baker.axis_cell_size[0]; + w32[3] = baker.axis_cell_size[1]; + w32[4] = baker.axis_cell_size[2]; + w32[5] = baker.bake_cells.size(); + w32[6] = baker.leaf_voxel_count; - int ofs=16; + int ofs = 16; - for(int i=0;i0) { + if (l > 0) { e.normalize(); - l=CLAMP(l/8.0,0,1.0); + l = CLAMP(l / 8.0, 0, 1.0); } - uint32_t em=uint32_t(CLAMP(e[0]*255,0,255))<<24; - em|=uint32_t(CLAMP(e[1]*255,0,255))<<16; - em|=uint32_t(CLAMP(e[2]*255,0,255))<<8; - em|=uint32_t(CLAMP(l*255,0,255)); + uint32_t em = uint32_t(CLAMP(e[0] * 255, 0, 255)) << 24; + em |= uint32_t(CLAMP(e[1] * 255, 0, 255)) << 16; + em |= uint32_t(CLAMP(e[2] * 255, 0, 255)) << 8; + em |= uint32_t(CLAMP(l * 255, 0, 255)); - w32[ofs++]=em; + w32[ofs++] = em; } //w32[ofs++]=baker.bake_cells[i].used_sides; { //normal - Vector3 n(baker.bake_cells[i].normal[0],baker.bake_cells[i].normal[1],baker.bake_cells[i].normal[2]); - n=n*Vector3(0.5,0.5,0.5)+Vector3(0.5,0.5,0.5); - uint32_t norm=0; - + Vector3 n(baker.bake_cells[i].normal[0], baker.bake_cells[i].normal[1], baker.bake_cells[i].normal[2]); + n = n * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5); + uint32_t norm = 0; - norm|=uint32_t(CLAMP( n.x*255.0, 0, 255))<<16; - norm|=uint32_t(CLAMP( n.y*255.0, 0, 255))<<8; - norm|=uint32_t(CLAMP( n.z*255.0, 0, 255))<<0; + norm |= uint32_t(CLAMP(n.x * 255.0, 0, 255)) << 16; + norm |= uint32_t(CLAMP(n.y * 255.0, 0, 255)) << 8; + norm |= uint32_t(CLAMP(n.z * 255.0, 0, 255)) << 0; - w32[ofs++]=norm; + w32[ofs++] = norm; } { - uint16_t alpha = CLAMP(uint32_t(baker.bake_cells[i].alpha*65535.0),0,65535); + uint16_t alpha = CLAMP(uint32_t(baker.bake_cells[i].alpha * 65535.0), 0, 65535); uint16_t level = baker.bake_cells[i].level; - w32[ofs++] = (uint32_t(level)<<16)|uint32_t(alpha); + w32[ofs++] = (uint32_t(level) << 16) | uint32_t(alpha); } - } - } if (p_create_visual_debug) { @@ -1304,8 +1251,8 @@ void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug){ Ref probe_data; probe_data.instance(); - probe_data->set_bounds(Rect3(-extents,extents*2.0)); - probe_data->set_cell_size(baker.po2_bounds.size[longest_axis]/baker.axis_cell_size[longest_axis]); + probe_data->set_bounds(Rect3(-extents, extents * 2.0)); + probe_data->set_cell_size(baker.po2_bounds.size[longest_axis] / baker.axis_cell_size[longest_axis]); probe_data->set_dynamic_data(data); probe_data->set_dynamic_range(dynamic_range); probe_data->set_energy(energy); @@ -1317,54 +1264,44 @@ void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug){ set_probe_data(probe_data); } - - - - - } +void GIProbe::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb, Ref &p_multimesh, int &idx, Baker *p_baker) { -void GIProbe::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,Ref &p_multimesh,int &idx,Baker *p_baker) { + if (p_level == p_baker->cell_subdiv - 1) { - - if (p_level==p_baker->cell_subdiv-1) { - - Vector3 center = p_aabb.pos+p_aabb.size*0.5; + Vector3 center = p_aabb.pos + p_aabb.size * 0.5; Transform xform; - xform.origin=center; - xform.basis.scale(p_aabb.size*0.5); - p_multimesh->set_instance_transform(idx,xform); - Color col=Color(p_baker->bake_cells[p_idx].albedo[0],p_baker->bake_cells[p_idx].albedo[1],p_baker->bake_cells[p_idx].albedo[2]); - p_multimesh->set_instance_color(idx,col); + xform.origin = center; + xform.basis.scale(p_aabb.size * 0.5); + p_multimesh->set_instance_transform(idx, xform); + Color col = Color(p_baker->bake_cells[p_idx].albedo[0], p_baker->bake_cells[p_idx].albedo[1], p_baker->bake_cells[p_idx].albedo[2]); + p_multimesh->set_instance_color(idx, col); idx++; } else { - for(int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - if (p_baker->bake_cells[p_idx].childs[i]==Baker::CHILD_EMPTY) + if (p_baker->bake_cells[p_idx].childs[i] == Baker::CHILD_EMPTY) continue; - Rect3 aabb=p_aabb; - aabb.size*=0.5; + Rect3 aabb = p_aabb; + aabb.size *= 0.5; - if (i&1) - aabb.pos.x+=aabb.size.x; - if (i&2) - aabb.pos.y+=aabb.size.y; - if (i&4) - aabb.pos.z+=aabb.size.z; + if (i & 1) + aabb.pos.x += aabb.size.x; + if (i & 2) + aabb.pos.y += aabb.size.y; + if (i & 4) + aabb.pos.z += aabb.size.z; - _debug_mesh(p_baker->bake_cells[p_idx].childs[i],p_level+1,aabb,p_multimesh,idx,p_baker); + _debug_mesh(p_baker->bake_cells[p_idx].childs[i], p_level + 1, aabb, p_multimesh, idx, p_baker); } - } - } - void GIProbe::_create_debug_mesh(Baker *p_baker) { Ref mm; @@ -1372,7 +1309,7 @@ void GIProbe::_create_debug_mesh(Baker *p_baker) { mm->set_transform_format(MultiMesh::TRANSFORM_3D); mm->set_color_format(MultiMesh::COLOR_8BIT); - print_line("leaf voxels: "+itos(p_baker->leaf_voxel_count)); + print_line("leaf voxels: " + itos(p_baker->leaf_voxel_count)); mm->set_instance_count(p_baker->leaf_voxel_count); Ref mesh; @@ -1385,76 +1322,72 @@ void GIProbe::_create_debug_mesh(Baker *p_baker) { PoolVector vertices; PoolVector colors; - int vtx_idx=0; - #define ADD_VTX(m_idx);\ - vertices.push_back( face_points[m_idx] );\ - colors.push_back( Color(1,1,1,1) );\ - vtx_idx++;\ - - for (int i=0;i<6;i++) { + int vtx_idx = 0; +#define ADD_VTX(m_idx) \ + ; \ + vertices.push_back(face_points[m_idx]); \ + colors.push_back(Color(1, 1, 1, 1)); \ + vtx_idx++; + for (int i = 0; i < 6; i++) { Vector3 face_points[4]; - for (int j=0;j<4;j++) { + for (int j = 0; j < 4; j++) { float v[3]; - v[0]=1.0; - v[1]=1-2*((j>>1)&1); - v[2]=v[1]*(1-2*(j&1)); + v[0] = 1.0; + v[1] = 1 - 2 * ((j >> 1) & 1); + v[2] = v[1] * (1 - 2 * (j & 1)); - for (int k=0;k<3;k++) { + for (int k = 0; k < 3; k++) { - if (i<3) - face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1); + if (i < 3) + face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1); else - face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1); + face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1); } } - //tri 1 + //tri 1 ADD_VTX(0); ADD_VTX(1); ADD_VTX(2); - //tri 2 + //tri 2 ADD_VTX(2); ADD_VTX(3); ADD_VTX(0); - } - - arr[Mesh::ARRAY_VERTEX]=vertices; - arr[Mesh::ARRAY_COLOR]=colors; - mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,arr); + arr[Mesh::ARRAY_VERTEX] = vertices; + arr[Mesh::ARRAY_COLOR] = colors; + mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr); } { Ref fsm; fsm.instance(); - fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true); - fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true); - fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true); - fsm->set_albedo(Color(1,1,1,1)); + fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); + fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); + fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true); + fsm->set_albedo(Color(1, 1, 1, 1)); - mesh->surface_set_material(0,fsm); + mesh->surface_set_material(0, fsm); } mm->set_mesh(mesh); + int idx = 0; + _debug_mesh(0, 0, p_baker->po2_bounds, mm, idx, p_baker); - int idx=0; - _debug_mesh(0,0,p_baker->po2_bounds,mm,idx,p_baker); - - MultiMeshInstance *mmi = memnew( MultiMeshInstance ); + MultiMeshInstance *mmi = memnew(MultiMeshInstance); mmi->set_multimesh(mm); add_child(mmi); #ifdef TOOLS_ENABLED - if (get_tree()->get_edited_scene_root()==this){ + if (get_tree()->get_edited_scene_root() == this) { mmi->set_owner(this); } else { mmi->set_owner(get_owner()); - } #else mmi->set_owner(get_owner()); @@ -1463,12 +1396,12 @@ void GIProbe::_create_debug_mesh(Baker *p_baker) { void GIProbe::_debug_bake() { - bake(NULL,true); + bake(NULL, true); } Rect3 GIProbe::get_aabb() const { - return Rect3(-extents,extents*2); + return Rect3(-extents, extents * 2); } PoolVector GIProbe::get_faces(uint32_t p_usage_flags) const { @@ -1478,74 +1411,68 @@ PoolVector GIProbe::get_faces(uint32_t p_usage_flags) const { void GIProbe::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_probe_data","data"),&GIProbe::set_probe_data); - ClassDB::bind_method(D_METHOD("get_probe_data"),&GIProbe::get_probe_data); + ClassDB::bind_method(D_METHOD("set_probe_data", "data"), &GIProbe::set_probe_data); + ClassDB::bind_method(D_METHOD("get_probe_data"), &GIProbe::get_probe_data); - ClassDB::bind_method(D_METHOD("set_subdiv","subdiv"),&GIProbe::set_subdiv); - ClassDB::bind_method(D_METHOD("get_subdiv"),&GIProbe::get_subdiv); + ClassDB::bind_method(D_METHOD("set_subdiv", "subdiv"), &GIProbe::set_subdiv); + ClassDB::bind_method(D_METHOD("get_subdiv"), &GIProbe::get_subdiv); - ClassDB::bind_method(D_METHOD("set_extents","extents"),&GIProbe::set_extents); - ClassDB::bind_method(D_METHOD("get_extents"),&GIProbe::get_extents); + ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GIProbe::set_extents); + ClassDB::bind_method(D_METHOD("get_extents"), &GIProbe::get_extents); - ClassDB::bind_method(D_METHOD("set_dynamic_range","max"),&GIProbe::set_dynamic_range); - ClassDB::bind_method(D_METHOD("get_dynamic_range"),&GIProbe::get_dynamic_range); + ClassDB::bind_method(D_METHOD("set_dynamic_range", "max"), &GIProbe::set_dynamic_range); + ClassDB::bind_method(D_METHOD("get_dynamic_range"), &GIProbe::get_dynamic_range); - ClassDB::bind_method(D_METHOD("set_energy","max"),&GIProbe::set_energy); - ClassDB::bind_method(D_METHOD("get_energy"),&GIProbe::get_energy); + ClassDB::bind_method(D_METHOD("set_energy", "max"), &GIProbe::set_energy); + ClassDB::bind_method(D_METHOD("get_energy"), &GIProbe::get_energy); - ClassDB::bind_method(D_METHOD("set_bias","max"),&GIProbe::set_bias); - ClassDB::bind_method(D_METHOD("get_bias"),&GIProbe::get_bias); + ClassDB::bind_method(D_METHOD("set_bias", "max"), &GIProbe::set_bias); + ClassDB::bind_method(D_METHOD("get_bias"), &GIProbe::get_bias); - ClassDB::bind_method(D_METHOD("set_propagation","max"),&GIProbe::set_propagation); - ClassDB::bind_method(D_METHOD("get_propagation"),&GIProbe::get_propagation); + ClassDB::bind_method(D_METHOD("set_propagation", "max"), &GIProbe::set_propagation); + ClassDB::bind_method(D_METHOD("get_propagation"), &GIProbe::get_propagation); - ClassDB::bind_method(D_METHOD("set_interior","enable"),&GIProbe::set_interior); - ClassDB::bind_method(D_METHOD("is_interior"),&GIProbe::is_interior); + ClassDB::bind_method(D_METHOD("set_interior", "enable"), &GIProbe::set_interior); + ClassDB::bind_method(D_METHOD("is_interior"), &GIProbe::is_interior); - ClassDB::bind_method(D_METHOD("set_compress","enable"),&GIProbe::set_compress); - ClassDB::bind_method(D_METHOD("is_compressed"),&GIProbe::is_compressed); + ClassDB::bind_method(D_METHOD("set_compress", "enable"), &GIProbe::set_compress); + ClassDB::bind_method(D_METHOD("is_compressed"), &GIProbe::is_compressed); - ClassDB::bind_method(D_METHOD("bake","from_node","create_visual_debug"),&GIProbe::bake,DEFVAL(Variant()),DEFVAL(false)); - ClassDB::bind_method(D_METHOD("debug_bake"),&GIProbe::_debug_bake); - ClassDB::set_method_flags(get_class_static(),_scs_create("debug_bake"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); + ClassDB::bind_method(D_METHOD("bake", "from_node", "create_visual_debug"), &GIProbe::bake, DEFVAL(Variant()), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("debug_bake"), &GIProbe::_debug_bake); + ClassDB::set_method_flags(get_class_static(), _scs_create("debug_bake"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); - ADD_PROPERTY( PropertyInfo(Variant::INT,"subdiv",PROPERTY_HINT_ENUM,"64,128,256,512"),"set_subdiv","get_subdiv"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"extents"),"set_extents","get_extents"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"dynamic_range",PROPERTY_HINT_RANGE,"1,16,1"),"set_dynamic_range","get_dynamic_range"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_energy","get_energy"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"propagation",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_propagation","get_propagation"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"bias",PROPERTY_HINT_RANGE,"0,4,0.001"),"set_bias","get_bias"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"interior"),"set_interior","is_interior"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"compress"),"set_compress","is_compressed"); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"data",PROPERTY_HINT_RESOURCE_TYPE,"GIProbeData"),"set_probe_data","get_probe_data"); - - - BIND_CONSTANT( SUBDIV_64 ); - BIND_CONSTANT( SUBDIV_128 ); - BIND_CONSTANT( SUBDIV_256 ); - BIND_CONSTANT( SUBDIV_MAX ); + ADD_PROPERTY(PropertyInfo(Variant::INT, "subdiv", PROPERTY_HINT_ENUM, "64,128,256,512"), "set_subdiv", "get_subdiv"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents"), "set_extents", "get_extents"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "dynamic_range", PROPERTY_HINT_RANGE, "1,16,1"), "set_dynamic_range", "get_dynamic_range"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_energy", "get_energy"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "propagation", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_propagation", "get_propagation"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_RANGE, "0,4,0.001"), "set_bias", "get_bias"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior"), "set_interior", "is_interior"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "compress"), "set_compress", "is_compressed"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "data", PROPERTY_HINT_RESOURCE_TYPE, "GIProbeData"), "set_probe_data", "get_probe_data"); + BIND_CONSTANT(SUBDIV_64); + BIND_CONSTANT(SUBDIV_128); + BIND_CONSTANT(SUBDIV_256); + BIND_CONSTANT(SUBDIV_MAX); } GIProbe::GIProbe() { - subdiv=SUBDIV_128; - dynamic_range=4; - energy=1.0; - bias=0.4; - propagation=1.0; - extents=Vector3(10,10,10); - color_scan_cell_width=4; - bake_texture_size=128; - interior=false; - compress=false; + subdiv = SUBDIV_128; + dynamic_range = 4; + energy = 1.0; + bias = 0.4; + propagation = 1.0; + extents = Vector3(10, 10, 10); + color_scan_cell_width = 4; + bake_texture_size = 128; + interior = false; + compress = false; gi_probe = VS::get_singleton()->gi_probe_create(); - - } GIProbe::~GIProbe() { - - } diff --git a/scene/3d/gi_probe.h b/scene/3d/gi_probe.h index a45e80806..675b41cef 100644 --- a/scene/3d/gi_probe.h +++ b/scene/3d/gi_probe.h @@ -29,32 +29,29 @@ #ifndef GIPROBE_H #define GIPROBE_H -#include "scene/3d/visual_instance.h" #include "multimesh_instance.h" +#include "scene/3d/visual_instance.h" class GIProbeData : public Resource { - GDCLASS(GIProbeData,Resource); + GDCLASS(GIProbeData, Resource); RID probe; protected: - static void _bind_methods(); -public: - - - void set_bounds(const Rect3& p_bounds); +public: + void set_bounds(const Rect3 &p_bounds); Rect3 get_bounds() const; void set_cell_size(float p_size); float get_cell_size() const; - void set_to_cell_xform(const Transform& p_xform); + void set_to_cell_xform(const Transform &p_xform); Transform get_to_cell_xform() const; - void set_dynamic_data(const PoolVector& p_data); + void set_dynamic_data(const PoolVector &p_data); PoolVector get_dynamic_data() const; void set_dynamic_range(int p_range); @@ -81,12 +78,11 @@ public: ~GIProbeData(); }; +class GIProbe : public VisualInstance { + GDCLASS(GIProbe, VisualInstance); - -class GIProbe : public VisualInstance { - GDCLASS(GIProbe,VisualInstance); public: - enum Subdiv{ + enum Subdiv { SUBDIV_64, SUBDIV_128, SUBDIV_256, @@ -94,13 +90,13 @@ public: SUBDIV_MAX }; -private: +private: //stuff used for bake struct Baker { enum { - CHILD_EMPTY=0xFFFFFFFF + CHILD_EMPTY = 0xFFFFFFFF }; struct Cell { @@ -113,18 +109,18 @@ private: int level; Cell() { - for(int i=0;i<8;i++) { - childs[i]=CHILD_EMPTY; + for (int i = 0; i < 8; i++) { + childs[i] = CHILD_EMPTY; } - for(int i=0;i<3;i++) { - emission[i]=0; - albedo[i]=0; - normal[i]=0; + for (int i = 0; i < 3; i++) { + emission[i] = 0; + albedo[i] = 0; + normal[i] = 0; } - alpha=0; - used_sides=0; - level=0; + alpha = 0; + used_sides = 0; + level = 0; } }; @@ -137,13 +133,11 @@ private: Vector emission; }; - Vector _get_bake_texture(Image &p_image, const Color &p_color); - Map,MaterialCache> material_cache; + Map, MaterialCache> material_cache; MaterialCache _get_material_cache(Ref p_material); int leaf_voxel_count; - Rect3 po2_bounds; int axis_cell_size[3]; @@ -159,7 +153,6 @@ private: List mesh_list; }; - Ref probe_data; RID gi_probe; @@ -176,30 +169,29 @@ private: int color_scan_cell_width; int bake_texture_size; - Vector _get_bake_texture(Image &p_image,const Color& p_color); - Baker::MaterialCache _get_material_cache(Ref p_material,Baker *p_baker); - void _plot_face(int p_idx, int p_level, int p_x,int p_y,int p_z,const Vector3 *p_vtx, const Vector2* p_uv, const Baker::MaterialCache& p_material, const Rect3 &p_aabb,Baker *p_baker); - void _plot_mesh(const Transform& p_xform, Ref& p_mesh, Baker *p_baker,const Vector >& p_materials,const Ref& p_override_material); - void _find_meshes(Node *p_at_node,Baker *p_baker); - void _fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z,Baker *p_baker); + Vector _get_bake_texture(Image &p_image, const Color &p_color); + Baker::MaterialCache _get_material_cache(Ref p_material, Baker *p_baker); + void _plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, const Vector3 *p_vtx, const Vector2 *p_uv, const Baker::MaterialCache &p_material, const Rect3 &p_aabb, Baker *p_baker); + void _plot_mesh(const Transform &p_xform, Ref &p_mesh, Baker *p_baker, const Vector > &p_materials, const Ref &p_override_material); + void _find_meshes(Node *p_at_node, Baker *p_baker); + void _fixup_plot(int p_idx, int p_level, int p_x, int p_y, int p_z, Baker *p_baker); - void _debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,Ref &p_multimesh,int &idx,Baker *p_baker); + void _debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb, Ref &p_multimesh, int &idx, Baker *p_baker); void _create_debug_mesh(Baker *p_baker); void _debug_bake(); protected: - static void _bind_methods(); -public: - void set_probe_data(const Ref& p_data); +public: + void set_probe_data(const Ref &p_data); Ref get_probe_data() const; void set_subdiv(Subdiv p_subdiv); Subdiv get_subdiv() const; - void set_extents(const Vector3& p_extents); + void set_extents(const Vector3 &p_extents); Vector3 get_extents() const; void set_dynamic_range(int p_dynamic_range); @@ -220,7 +212,7 @@ public: void set_compress(bool p_enable); bool is_compressed() const; - void bake(Node *p_from_node=NULL,bool p_create_visual_debug=false); + void bake(Node *p_from_node = NULL, bool p_create_visual_debug = false); virtual Rect3 get_aabb() const; virtual PoolVector get_faces(uint32_t p_usage_flags) const; diff --git a/scene/3d/immediate_geometry.cpp b/scene/3d/immediate_geometry.cpp index 6adbbe9cc..adcc16722 100644 --- a/scene/3d/immediate_geometry.cpp +++ b/scene/3d/immediate_geometry.cpp @@ -28,68 +28,60 @@ /*************************************************************************/ #include "immediate_geometry.h" +void ImmediateGeometry::begin(Mesh::PrimitiveType p_primitive, const Ref &p_texture) { -void ImmediateGeometry::begin(Mesh::PrimitiveType p_primitive,const Ref& p_texture) { - - VS::get_singleton()->immediate_begin(im,(VS::PrimitiveType)p_primitive,p_texture.is_valid()?p_texture->get_rid():RID()); + VS::get_singleton()->immediate_begin(im, (VS::PrimitiveType)p_primitive, p_texture.is_valid() ? p_texture->get_rid() : RID()); if (p_texture.is_valid()) cached_textures.push_back(p_texture); - } -void ImmediateGeometry::set_normal(const Vector3& p_normal){ +void ImmediateGeometry::set_normal(const Vector3 &p_normal) { - VS::get_singleton()->immediate_normal(im,p_normal); + VS::get_singleton()->immediate_normal(im, p_normal); } -void ImmediateGeometry::set_tangent(const Plane& p_tangent){ - - VS::get_singleton()->immediate_tangent(im,p_tangent); +void ImmediateGeometry::set_tangent(const Plane &p_tangent) { + VS::get_singleton()->immediate_tangent(im, p_tangent); } -void ImmediateGeometry::set_color(const Color& p_color){ - - VS::get_singleton()->immediate_color(im,p_color); +void ImmediateGeometry::set_color(const Color &p_color) { + VS::get_singleton()->immediate_color(im, p_color); } -void ImmediateGeometry::set_uv(const Vector2& p_uv){ - - VS::get_singleton()->immediate_uv(im,p_uv); +void ImmediateGeometry::set_uv(const Vector2 &p_uv) { + VS::get_singleton()->immediate_uv(im, p_uv); } -void ImmediateGeometry::set_uv2(const Vector2& p_uv2){ - - VS::get_singleton()->immediate_uv2(im,p_uv2); +void ImmediateGeometry::set_uv2(const Vector2 &p_uv2) { + VS::get_singleton()->immediate_uv2(im, p_uv2); } -void ImmediateGeometry::add_vertex(const Vector3& p_vertex){ +void ImmediateGeometry::add_vertex(const Vector3 &p_vertex) { - VS::get_singleton()->immediate_vertex(im,p_vertex); + VS::get_singleton()->immediate_vertex(im, p_vertex); if (empty) { - aabb.pos=p_vertex; - aabb.size=Vector3(); - empty=false; + aabb.pos = p_vertex; + aabb.size = Vector3(); + empty = false; } else { aabb.expand_to(p_vertex); } } -void ImmediateGeometry::end(){ +void ImmediateGeometry::end() { VS::get_singleton()->immediate_end(im); - } -void ImmediateGeometry::clear(){ +void ImmediateGeometry::clear() { VS::get_singleton()->immediate_clear(im); - empty=true; + empty = true; cached_textures.clear(); - } Rect3 ImmediateGeometry::get_aabb() const { @@ -101,44 +93,41 @@ PoolVector ImmediateGeometry::get_faces(uint32_t p_usage_flags) const { return PoolVector(); } - - void ImmediateGeometry::add_sphere(int p_lats, int p_lons, float p_radius, bool p_add_uv) { - for(int i = 1; i <= p_lats; i++) { - double lat0 = Math_PI * (-0.5 + (double) (i - 1) / p_lats); - double z0 = Math::sin(lat0); - double zr0 = Math::cos(lat0); + for (int i = 1; i <= p_lats; i++) { + double lat0 = Math_PI * (-0.5 + (double)(i - 1) / p_lats); + double z0 = Math::sin(lat0); + double zr0 = Math::cos(lat0); - double lat1 = Math_PI * (-0.5 + (double) i / p_lats); + double lat1 = Math_PI * (-0.5 + (double)i / p_lats); double z1 = Math::sin(lat1); double zr1 = Math::cos(lat1); - for(int j = p_lons; j >= 1; j--) { + for (int j = p_lons; j >= 1; j--) { - double lng0 = 2 * Math_PI * (double) (j - 1) / p_lons; + double lng0 = 2 * Math_PI * (double)(j - 1) / p_lons; double x0 = Math::cos(lng0); double y0 = Math::sin(lng0); - double lng1 = 2 * Math_PI * (double) (j) / p_lons; + double lng1 = 2 * Math_PI * (double)(j) / p_lons; double x1 = Math::cos(lng1); double y1 = Math::sin(lng1); - - Vector3 v[4]={ - Vector3(x1 * zr0, z0, y1 *zr0), - Vector3(x1 * zr1, z1, y1 *zr1), - Vector3(x0 * zr1, z1, y0 *zr1), - Vector3(x0 * zr0, z0, y0 *zr0) + Vector3 v[4] = { + Vector3(x1 * zr0, z0, y1 * zr0), + Vector3(x1 * zr1, z1, y1 * zr1), + Vector3(x0 * zr1, z1, y0 * zr1), + Vector3(x0 * zr0, z0, y0 * zr0) }; -#define ADD_POINT(m_idx)\ - if (p_add_uv) {\ - set_uv(Vector2(Math::atan2(v[m_idx].x,v[m_idx].z)/Math_PI * 0.5+0.5,v[m_idx].y*0.5+0.5));\ - set_tangent(Plane(Vector3(-v[m_idx].z,v[m_idx].y,v[m_idx].x),1)); \ - }\ - set_normal(v[m_idx]);\ - add_vertex(v[m_idx]*p_radius); +#define ADD_POINT(m_idx) \ + if (p_add_uv) { \ + set_uv(Vector2(Math::atan2(v[m_idx].x, v[m_idx].z) / Math_PI * 0.5 + 0.5, v[m_idx].y * 0.5 + 0.5)); \ + set_tangent(Plane(Vector3(-v[m_idx].z, v[m_idx].y, v[m_idx].x), 1)); \ + } \ + set_normal(v[m_idx]); \ + add_vertex(v[m_idx] * p_radius); ADD_POINT(0); ADD_POINT(1); @@ -149,37 +138,30 @@ void ImmediateGeometry::add_sphere(int p_lats, int p_lons, float p_radius, bool ADD_POINT(0); } } - } void ImmediateGeometry::_bind_methods() { - ClassDB::bind_method(D_METHOD("begin","primitive","texture:Texture"),&ImmediateGeometry::begin,DEFVAL(Ref())); - ClassDB::bind_method(D_METHOD("set_normal","normal"),&ImmediateGeometry::set_normal); - ClassDB::bind_method(D_METHOD("set_tangent","tangent"),&ImmediateGeometry::set_tangent); - ClassDB::bind_method(D_METHOD("set_color","color"),&ImmediateGeometry::set_color); - ClassDB::bind_method(D_METHOD("set_uv","uv"),&ImmediateGeometry::set_uv); - ClassDB::bind_method(D_METHOD("set_uv2","uv"),&ImmediateGeometry::set_uv2); - ClassDB::bind_method(D_METHOD("add_vertex","pos"),&ImmediateGeometry::add_vertex); - ClassDB::bind_method(D_METHOD("add_sphere","lats","lons","radius","add_uv"),&ImmediateGeometry::add_sphere,DEFVAL(true)); - ClassDB::bind_method(D_METHOD("end"),&ImmediateGeometry::end); - ClassDB::bind_method(D_METHOD("clear"),&ImmediateGeometry::clear); - + ClassDB::bind_method(D_METHOD("begin", "primitive", "texture:Texture"), &ImmediateGeometry::begin, DEFVAL(Ref())); + ClassDB::bind_method(D_METHOD("set_normal", "normal"), &ImmediateGeometry::set_normal); + ClassDB::bind_method(D_METHOD("set_tangent", "tangent"), &ImmediateGeometry::set_tangent); + ClassDB::bind_method(D_METHOD("set_color", "color"), &ImmediateGeometry::set_color); + ClassDB::bind_method(D_METHOD("set_uv", "uv"), &ImmediateGeometry::set_uv); + ClassDB::bind_method(D_METHOD("set_uv2", "uv"), &ImmediateGeometry::set_uv2); + ClassDB::bind_method(D_METHOD("add_vertex", "pos"), &ImmediateGeometry::add_vertex); + ClassDB::bind_method(D_METHOD("add_sphere", "lats", "lons", "radius", "add_uv"), &ImmediateGeometry::add_sphere, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("end"), &ImmediateGeometry::end); + ClassDB::bind_method(D_METHOD("clear"), &ImmediateGeometry::clear); } - - ImmediateGeometry::ImmediateGeometry() { im = VisualServer::get_singleton()->immediate_create(); set_base(im); - empty=true; - + empty = true; } - ImmediateGeometry::~ImmediateGeometry() { VisualServer::get_singleton()->free(im); - } diff --git a/scene/3d/immediate_geometry.h b/scene/3d/immediate_geometry.h index e385a34da..6e0123992 100644 --- a/scene/3d/immediate_geometry.h +++ b/scene/3d/immediate_geometry.h @@ -34,8 +34,7 @@ class ImmediateGeometry : public GeometryInstance { - GDCLASS(ImmediateGeometry,GeometryInstance); - + GDCLASS(ImmediateGeometry, GeometryInstance); RID im; //a list of texures drawn need to be kept, to avoid references @@ -43,28 +42,24 @@ class ImmediateGeometry : public GeometryInstance { List > cached_textures; bool empty; Rect3 aabb; -protected: +protected: static void _bind_methods(); -public: - - void begin(Mesh::PrimitiveType p_primitive,const Ref& p_texture=Ref()); - void set_normal(const Vector3& p_normal); - void set_tangent(const Plane& p_tangent); - void set_color(const Color& p_color); - void set_uv(const Vector2& tex_uv); - void set_uv2(const Vector2& tex_uv); +public: + void begin(Mesh::PrimitiveType p_primitive, const Ref &p_texture = Ref()); + void set_normal(const Vector3 &p_normal); + void set_tangent(const Plane &p_tangent); + void set_color(const Color &p_color); + void set_uv(const Vector2 &tex_uv); + void set_uv2(const Vector2 &tex_uv); - void add_vertex(const Vector3& p_vertex); + void add_vertex(const Vector3 &p_vertex); void end(); void clear(); - - void add_sphere(int p_lats,int p_lons,float p_radius,bool p_add_uv=true); - - + void add_sphere(int p_lats, int p_lons, float p_radius, bool p_add_uv = true); virtual Rect3 get_aabb() const; virtual PoolVector get_faces(uint32_t p_usage_flags) const; diff --git a/scene/3d/interpolated_camera.cpp b/scene/3d/interpolated_camera.cpp index 15ee971b7..9723a686c 100644 --- a/scene/3d/interpolated_camera.cpp +++ b/scene/3d/interpolated_camera.cpp @@ -28,10 +28,9 @@ /*************************************************************************/ #include "interpolated_camera.h" - void InterpolatedCamera::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { if (get_tree()->is_editor_hint() && enabled) @@ -48,32 +47,30 @@ void InterpolatedCamera::_notification(int p_what) { if (!node) break; - float delta = speed*get_process_delta_time(); + float delta = speed * get_process_delta_time(); Transform target_xform = node->get_global_transform(); Transform local_transform = get_global_transform(); - local_transform = local_transform.interpolate_with(target_xform,delta); + local_transform = local_transform.interpolate_with(target_xform, delta); set_global_transform(local_transform); if (node->cast_to()) { Camera *cam = node->cast_to(); - if (cam->get_projection()==get_projection()) { + if (cam->get_projection() == get_projection()) { - float new_near = Math::lerp(get_znear(),cam->get_znear(),delta); - float new_far = Math::lerp(get_zfar(),cam->get_zfar(),delta); + float new_near = Math::lerp(get_znear(), cam->get_znear(), delta); + float new_far = Math::lerp(get_zfar(), cam->get_zfar(), delta); - if (cam->get_projection()==PROJECTION_ORTHOGONAL) { + if (cam->get_projection() == PROJECTION_ORTHOGONAL) { - float size = Math::lerp(get_size(),cam->get_size(),delta); - set_orthogonal(size,new_near,new_far); + float size = Math::lerp(get_size(), cam->get_size(), delta); + set_orthogonal(size, new_near, new_far); } else { - float fov = Math::lerp(get_fov(),cam->get_fov(),delta); - set_perspective(fov,new_near,new_far); + float fov = Math::lerp(get_fov(), cam->get_fov(), delta); + set_perspective(fov, new_near, new_far); } } } - - } } break; @@ -89,25 +86,24 @@ void InterpolatedCamera::_set_target(const Object *p_target) { void InterpolatedCamera::set_target(const Spatial *p_target) { ERR_FAIL_NULL(p_target); - target=get_path_to(p_target); + target = get_path_to(p_target); } +void InterpolatedCamera::set_target_path(const NodePath &p_path) { -void InterpolatedCamera::set_target_path(const NodePath& p_path){ - - target=p_path; + target = p_path; } -NodePath InterpolatedCamera::get_target_path() const{ +NodePath InterpolatedCamera::get_target_path() const { return target; } void InterpolatedCamera::set_interpolation_enabled(bool p_enable) { - if (enabled==p_enable) + if (enabled == p_enable) return; - enabled=p_enable; + enabled = p_enable; if (p_enable) { if (is_inside_tree() && get_tree()->is_editor_hint()) return; @@ -123,7 +119,7 @@ bool InterpolatedCamera::is_interpolation_enabled() const { void InterpolatedCamera::set_speed(real_t p_speed) { - speed=p_speed; + speed = p_speed; } real_t InterpolatedCamera::get_speed() const { @@ -131,27 +127,25 @@ real_t InterpolatedCamera::get_speed() const { return speed; } - void InterpolatedCamera::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_target_path","target_path"),&InterpolatedCamera::set_target_path); - ClassDB::bind_method(D_METHOD("get_target_path"),&InterpolatedCamera::get_target_path); - ClassDB::bind_method(D_METHOD("set_target","target:Camera"),&InterpolatedCamera::_set_target); + ClassDB::bind_method(D_METHOD("set_target_path", "target_path"), &InterpolatedCamera::set_target_path); + ClassDB::bind_method(D_METHOD("get_target_path"), &InterpolatedCamera::get_target_path); + ClassDB::bind_method(D_METHOD("set_target", "target:Camera"), &InterpolatedCamera::_set_target); - ClassDB::bind_method(D_METHOD("set_speed","speed"),&InterpolatedCamera::set_speed); - ClassDB::bind_method(D_METHOD("get_speed"),&InterpolatedCamera::get_speed); + ClassDB::bind_method(D_METHOD("set_speed", "speed"), &InterpolatedCamera::set_speed); + ClassDB::bind_method(D_METHOD("get_speed"), &InterpolatedCamera::get_speed); - ClassDB::bind_method(D_METHOD("set_interpolation_enabled","target_path"),&InterpolatedCamera::set_interpolation_enabled); - ClassDB::bind_method(D_METHOD("is_interpolation_enabled"),&InterpolatedCamera::is_interpolation_enabled); + ClassDB::bind_method(D_METHOD("set_interpolation_enabled", "target_path"), &InterpolatedCamera::set_interpolation_enabled); + ClassDB::bind_method(D_METHOD("is_interpolation_enabled"), &InterpolatedCamera::is_interpolation_enabled); - ADD_PROPERTY( PropertyInfo(Variant::NODE_PATH,"target"), "set_target_path", "get_target_path") ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"speed"), "set_speed", "get_speed") ; - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enabled"), "set_interpolation_enabled", "is_interpolation_enabled") ; + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target"), "set_target_path", "get_target_path"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "speed"), "set_speed", "get_speed"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_interpolation_enabled", "is_interpolation_enabled"); } InterpolatedCamera::InterpolatedCamera() { - enabled=false; - speed=1; - + enabled = false; + speed = 1; } diff --git a/scene/3d/interpolated_camera.h b/scene/3d/interpolated_camera.h index c78e6935d..ebadf3994 100644 --- a/scene/3d/interpolated_camera.h +++ b/scene/3d/interpolated_camera.h @@ -33,21 +33,20 @@ class InterpolatedCamera : public Camera { - GDCLASS(InterpolatedCamera,Camera); + GDCLASS(InterpolatedCamera, Camera); bool enabled; real_t speed; NodePath target; -protected: +protected: void _notification(int p_what); static void _bind_methods(); void _set_target(const Object *p_target); public: - void set_target(const Spatial *p_target); - void set_target_path(const NodePath& p_path); + void set_target_path(const NodePath &p_path); NodePath get_target_path() const; void set_speed(real_t p_speed); @@ -56,7 +55,6 @@ public: void set_interpolation_enabled(bool p_enable); bool is_interpolation_enabled() const; - InterpolatedCamera(); }; diff --git a/scene/3d/light.cpp b/scene/3d/light.cpp index 473bca8d3..7d0123051 100644 --- a/scene/3d/light.cpp +++ b/scene/3d/light.cpp @@ -28,108 +28,99 @@ /*************************************************************************/ #include "light.h" +#include "baked_light_instance.h" #include "global_config.h" #include "scene/resources/surface_tool.h" -#include "baked_light_instance.h" - bool Light::_can_gizmo_scale() const { return false; } - void Light::set_param(Param p_param, float p_value) { - ERR_FAIL_INDEX(p_param,PARAM_MAX); - param[p_param]=p_value; + ERR_FAIL_INDEX(p_param, PARAM_MAX); + param[p_param] = p_value; - VS::get_singleton()->light_set_param(light,VS::LightParam(p_param),p_value); + VS::get_singleton()->light_set_param(light, VS::LightParam(p_param), p_value); - if (p_param==PARAM_SPOT_ANGLE || p_param==PARAM_RANGE) { + if (p_param == PARAM_SPOT_ANGLE || p_param == PARAM_RANGE) { update_gizmo(); } - - } -float Light::get_param(Param p_param) const{ +float Light::get_param(Param p_param) const { - ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); + ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return param[p_param]; - } -void Light::set_shadow(bool p_enable){ - - shadow=p_enable; - VS::get_singleton()->light_set_shadow(light,p_enable); +void Light::set_shadow(bool p_enable) { + shadow = p_enable; + VS::get_singleton()->light_set_shadow(light, p_enable); } -bool Light::has_shadow() const{ +bool Light::has_shadow() const { return shadow; } -void Light::set_negative(bool p_enable){ +void Light::set_negative(bool p_enable) { - negative=p_enable; - VS::get_singleton()->light_set_negative(light,p_enable); + negative = p_enable; + VS::get_singleton()->light_set_negative(light, p_enable); } -bool Light::is_negative() const{ +bool Light::is_negative() const { return negative; } -void Light::set_cull_mask(uint32_t p_cull_mask){ - - cull_mask=p_cull_mask; - VS::get_singleton()->light_set_cull_mask(light,p_cull_mask); +void Light::set_cull_mask(uint32_t p_cull_mask) { + cull_mask = p_cull_mask; + VS::get_singleton()->light_set_cull_mask(light, p_cull_mask); } -uint32_t Light::get_cull_mask() const{ +uint32_t Light::get_cull_mask() const { return cull_mask; } -void Light::set_color(const Color& p_color){ +void Light::set_color(const Color &p_color) { - color=p_color; - VS::get_singleton()->light_set_color(light,p_color); + color = p_color; + VS::get_singleton()->light_set_color(light, p_color); } -Color Light::get_color() const{ +Color Light::get_color() const { return color; } -void Light::set_shadow_color(const Color& p_shadow_color){ +void Light::set_shadow_color(const Color &p_shadow_color) { - shadow_color=p_shadow_color; - VS::get_singleton()->light_set_shadow_color(light,p_shadow_color); + shadow_color = p_shadow_color; + VS::get_singleton()->light_set_shadow_color(light, p_shadow_color); } -Color Light::get_shadow_color() const{ +Color Light::get_shadow_color() const { return shadow_color; } - Rect3 Light::get_aabb() const { + if (type == VisualServer::LIGHT_DIRECTIONAL) { - if (type==VisualServer::LIGHT_DIRECTIONAL) { - - return Rect3( Vector3(-1,-1,-1), Vector3(2, 2, 2 ) ); + return Rect3(Vector3(-1, -1, -1), Vector3(2, 2, 2)); - } else if (type==VisualServer::LIGHT_OMNI) { + } else if (type == VisualServer::LIGHT_OMNI) { - return Rect3( Vector3(-1,-1,-1) * param[PARAM_RANGE], Vector3(2, 2, 2 ) * param[PARAM_RANGE]); + return Rect3(Vector3(-1, -1, -1) * param[PARAM_RANGE], Vector3(2, 2, 2) * param[PARAM_RANGE]); - } else if (type==VisualServer::LIGHT_SPOT) { + } else if (type == VisualServer::LIGHT_SPOT) { - float len=param[PARAM_RANGE]; - float size=Math::tan(Math::deg2rad(param[PARAM_SPOT_ANGLE]))*len; - return Rect3( Vector3( -size,-size,-len ), Vector3( size*2, size*2, len ) ); + float len = param[PARAM_RANGE]; + float size = Math::tan(Math::deg2rad(param[PARAM_SPOT_ANGLE])) * len; + return Rect3(Vector3(-size, -size, -len), Vector3(size * 2, size * 2, len)); } return Rect3(); @@ -140,187 +131,169 @@ PoolVector Light::get_faces(uint32_t p_usage_flags) const { return PoolVector(); } - - void Light::_update_visibility() { if (!is_inside_tree()) return; - - bool editor_ok=true; + bool editor_ok = true; #ifdef TOOLS_ENABLED if (editor_only) { if (!get_tree()->is_editor_hint()) { - editor_ok=false; + editor_ok = false; } else { - editor_ok = (get_tree()->get_edited_scene_root() && (this==get_tree()->get_edited_scene_root() || get_owner()==get_tree()->get_edited_scene_root())); + editor_ok = (get_tree()->get_edited_scene_root() && (this == get_tree()->get_edited_scene_root() || get_owner() == get_tree()->get_edited_scene_root())); } } #else if (editor_only) { - editor_ok=false; + editor_ok = false; } #endif //VS::get_singleton()->instance_light_set_enabled(get_instance(),is_visible_in_tree() && editor_ok); _change_notify("geometry/visible"); - } - void Light::_notification(int p_what) { - - if (p_what==NOTIFICATION_VISIBILITY_CHANGED) { + if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { _update_visibility(); - } - if (p_what==NOTIFICATION_ENTER_TREE) { + if (p_what == NOTIFICATION_ENTER_TREE) { _update_visibility(); Node *node = this; - while(node) { + while (node) { - baked_light=node->cast_to(); + baked_light = node->cast_to(); if (baked_light) { baked_light->lights.insert(this); break; } - node=node->get_parent(); + node = node->get_parent(); } } - if (p_what==NOTIFICATION_EXIT_TREE) { + if (p_what == NOTIFICATION_EXIT_TREE) { if (baked_light) { baked_light->lights.erase(this); } } - } - void Light::set_editor_only(bool p_editor_only) { - editor_only=p_editor_only; + editor_only = p_editor_only; _update_visibility(); } -bool Light::is_editor_only() const{ +bool Light::is_editor_only() const { return editor_only; } - void Light::_bind_methods() { - - ClassDB::bind_method(D_METHOD("set_editor_only","editor_only"), &Light::set_editor_only ); - ClassDB::bind_method(D_METHOD("is_editor_only"), &Light::is_editor_only ); - - - ClassDB::bind_method(D_METHOD("set_param","param","value"), &Light::set_param ); - ClassDB::bind_method(D_METHOD("get_param","param"), &Light::get_param ); - - ClassDB::bind_method(D_METHOD("set_shadow","enabled"), &Light::set_shadow ); - ClassDB::bind_method(D_METHOD("has_shadow"), &Light::has_shadow ); - - ClassDB::bind_method(D_METHOD("set_negative","enabled"), &Light::set_negative ); - ClassDB::bind_method(D_METHOD("is_negative"), &Light::is_negative ); - - ClassDB::bind_method(D_METHOD("set_cull_mask","cull_mask"), &Light::set_cull_mask ); - ClassDB::bind_method(D_METHOD("get_cull_mask"), &Light::get_cull_mask ); - - ClassDB::bind_method(D_METHOD("set_color","color"), &Light::set_color ); - ClassDB::bind_method(D_METHOD("get_color"), &Light::get_color ); - - ClassDB::bind_method(D_METHOD("set_shadow_color","shadow_color"), &Light::set_shadow_color ); - ClassDB::bind_method(D_METHOD("get_shadow_color"), &Light::get_shadow_color ); - - ADD_GROUP("Light","light_"); - ADD_PROPERTY( PropertyInfo( Variant::COLOR, "light_color",PROPERTY_HINT_COLOR_NO_ALPHA), "set_color", "get_color"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "light_energy",PROPERTY_HINT_RANGE,"0,16,0.01"), "set_param", "get_param", PARAM_ENERGY); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "light_negative"), "set_negative", "is_negative"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "light_specular",PROPERTY_HINT_RANGE,"0,1,0.01"), "set_param", "get_param", PARAM_SPECULAR); - ADD_PROPERTY( PropertyInfo( Variant::INT, "light_cull_mask",PROPERTY_HINT_LAYERS_3D_RENDER), "set_cull_mask", "get_cull_mask"); - ADD_GROUP("Shadow","shadow_"); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "shadow_enabled"), "set_shadow", "has_shadow"); - ADD_PROPERTY( PropertyInfo( Variant::COLOR, "shadow_color",PROPERTY_HINT_COLOR_NO_ALPHA), "set_shadow_color", "get_shadow_color"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "shadow_bias",PROPERTY_HINT_RANGE,"-16,16,0.01"), "set_param", "get_param", PARAM_SHADOW_BIAS); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "shadow_contact",PROPERTY_HINT_RANGE,"0,16,0.01"), "set_param", "get_param", PARAM_CONTACT_SHADOW_SIZE); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "shadow_max_distance",PROPERTY_HINT_RANGE,"0,65536,0.1"), "set_param", "get_param", PARAM_SHADOW_MAX_DISTANCE); - ADD_GROUP("Editor",""); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "editor_only"), "set_editor_only", "is_editor_only"); - ADD_GROUP("",""); - - BIND_CONSTANT( PARAM_ENERGY ); - BIND_CONSTANT( PARAM_SPECULAR ); - BIND_CONSTANT( PARAM_RANGE ); - BIND_CONSTANT( PARAM_ATTENUATION ); - BIND_CONSTANT( PARAM_SPOT_ANGLE ); - BIND_CONSTANT( PARAM_SPOT_ATTENUATION ); - BIND_CONSTANT( PARAM_CONTACT_SHADOW_SIZE ); - BIND_CONSTANT( PARAM_SHADOW_MAX_DISTANCE ); - BIND_CONSTANT( PARAM_SHADOW_SPLIT_1_OFFSET ); - BIND_CONSTANT( PARAM_SHADOW_SPLIT_2_OFFSET ); - BIND_CONSTANT( PARAM_SHADOW_SPLIT_3_OFFSET ); - BIND_CONSTANT( PARAM_SHADOW_NORMAL_BIAS ); - BIND_CONSTANT( PARAM_SHADOW_BIAS ); - BIND_CONSTANT( PARAM_SHADOW_BIAS_SPLIT_SCALE ); - BIND_CONSTANT( PARAM_MAX ); - - + ClassDB::bind_method(D_METHOD("set_editor_only", "editor_only"), &Light::set_editor_only); + ClassDB::bind_method(D_METHOD("is_editor_only"), &Light::is_editor_only); + + ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &Light::set_param); + ClassDB::bind_method(D_METHOD("get_param", "param"), &Light::get_param); + + ClassDB::bind_method(D_METHOD("set_shadow", "enabled"), &Light::set_shadow); + ClassDB::bind_method(D_METHOD("has_shadow"), &Light::has_shadow); + + ClassDB::bind_method(D_METHOD("set_negative", "enabled"), &Light::set_negative); + ClassDB::bind_method(D_METHOD("is_negative"), &Light::is_negative); + + ClassDB::bind_method(D_METHOD("set_cull_mask", "cull_mask"), &Light::set_cull_mask); + ClassDB::bind_method(D_METHOD("get_cull_mask"), &Light::get_cull_mask); + + ClassDB::bind_method(D_METHOD("set_color", "color"), &Light::set_color); + ClassDB::bind_method(D_METHOD("get_color"), &Light::get_color); + + ClassDB::bind_method(D_METHOD("set_shadow_color", "shadow_color"), &Light::set_shadow_color); + ClassDB::bind_method(D_METHOD("get_shadow_color"), &Light::get_shadow_color); + + ADD_GROUP("Light", "light_"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "light_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_color", "get_color"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "light_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_param", "get_param", PARAM_ENERGY); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "light_negative"), "set_negative", "is_negative"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "light_specular", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param", "get_param", PARAM_SPECULAR); + ADD_PROPERTY(PropertyInfo(Variant::INT, "light_cull_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_cull_mask", "get_cull_mask"); + ADD_GROUP("Shadow", "shadow_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shadow_enabled"), "set_shadow", "has_shadow"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "shadow_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_shadow_color", "get_shadow_color"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "shadow_bias", PROPERTY_HINT_RANGE, "-16,16,0.01"), "set_param", "get_param", PARAM_SHADOW_BIAS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "shadow_contact", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_param", "get_param", PARAM_CONTACT_SHADOW_SIZE); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "shadow_max_distance", PROPERTY_HINT_RANGE, "0,65536,0.1"), "set_param", "get_param", PARAM_SHADOW_MAX_DISTANCE); + ADD_GROUP("Editor", ""); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editor_only"), "set_editor_only", "is_editor_only"); + ADD_GROUP("", ""); + + BIND_CONSTANT(PARAM_ENERGY); + BIND_CONSTANT(PARAM_SPECULAR); + BIND_CONSTANT(PARAM_RANGE); + BIND_CONSTANT(PARAM_ATTENUATION); + BIND_CONSTANT(PARAM_SPOT_ANGLE); + BIND_CONSTANT(PARAM_SPOT_ATTENUATION); + BIND_CONSTANT(PARAM_CONTACT_SHADOW_SIZE); + BIND_CONSTANT(PARAM_SHADOW_MAX_DISTANCE); + BIND_CONSTANT(PARAM_SHADOW_SPLIT_1_OFFSET); + BIND_CONSTANT(PARAM_SHADOW_SPLIT_2_OFFSET); + BIND_CONSTANT(PARAM_SHADOW_SPLIT_3_OFFSET); + BIND_CONSTANT(PARAM_SHADOW_NORMAL_BIAS); + BIND_CONSTANT(PARAM_SHADOW_BIAS); + BIND_CONSTANT(PARAM_SHADOW_BIAS_SPLIT_SCALE); + BIND_CONSTANT(PARAM_MAX); } - Light::Light(VisualServer::LightType p_type) { - type=p_type; - light=VisualServer::get_singleton()->light_create(p_type); - VS::get_singleton()->instance_set_base(get_instance(),light); + type = p_type; + light = VisualServer::get_singleton()->light_create(p_type); + VS::get_singleton()->instance_set_base(get_instance(), light); - baked_light=NULL; + baked_light = NULL; - editor_only=false; - set_color(Color(1,1,1,1)); + editor_only = false; + set_color(Color(1, 1, 1, 1)); set_shadow(false); set_negative(false); set_cull_mask(0xFFFFFFFF); - set_param(PARAM_ENERGY,1); - set_param(PARAM_SPECULAR,0.5); - set_param(PARAM_RANGE,5); - set_param(PARAM_ATTENUATION,1); - set_param(PARAM_SPOT_ANGLE,45); - set_param(PARAM_SPOT_ATTENUATION,1); - set_param(PARAM_CONTACT_SHADOW_SIZE,0); - set_param(PARAM_SHADOW_MAX_DISTANCE,0); - set_param(PARAM_SHADOW_SPLIT_1_OFFSET,0.1); - set_param(PARAM_SHADOW_SPLIT_2_OFFSET,0.2); - set_param(PARAM_SHADOW_SPLIT_3_OFFSET,0.5); - set_param(PARAM_SHADOW_NORMAL_BIAS,0.1); - set_param(PARAM_SHADOW_BIAS,0.1); - set_param(PARAM_SHADOW_BIAS_SPLIT_SCALE,0.1); - + set_param(PARAM_ENERGY, 1); + set_param(PARAM_SPECULAR, 0.5); + set_param(PARAM_RANGE, 5); + set_param(PARAM_ATTENUATION, 1); + set_param(PARAM_SPOT_ANGLE, 45); + set_param(PARAM_SPOT_ATTENUATION, 1); + set_param(PARAM_CONTACT_SHADOW_SIZE, 0); + set_param(PARAM_SHADOW_MAX_DISTANCE, 0); + set_param(PARAM_SHADOW_SPLIT_1_OFFSET, 0.1); + set_param(PARAM_SHADOW_SPLIT_2_OFFSET, 0.2); + set_param(PARAM_SHADOW_SPLIT_3_OFFSET, 0.5); + set_param(PARAM_SHADOW_NORMAL_BIAS, 0.1); + set_param(PARAM_SHADOW_BIAS, 0.1); + set_param(PARAM_SHADOW_BIAS_SPLIT_SCALE, 0.1); } - Light::Light() { - type=VisualServer::LIGHT_DIRECTIONAL; + type = VisualServer::LIGHT_DIRECTIONAL; ERR_PRINT("Light shouldn't be instanced dircetly, use the subtypes."); } - Light::~Light() { - VS::get_singleton()->instance_set_base(get_instance(),RID()); + VS::get_singleton()->instance_set_base(get_instance(), RID()); if (light.is_valid()) VisualServer::get_singleton()->free(light); @@ -329,8 +302,8 @@ Light::~Light() { void DirectionalLight::set_shadow_mode(ShadowMode p_mode) { - shadow_mode=p_mode; - VS::get_singleton()->light_directional_set_shadow_mode(light,VS::LightDirectionalShadowMode(p_mode)); + shadow_mode = p_mode; + VS::get_singleton()->light_directional_set_shadow_mode(light, VS::LightDirectionalShadowMode(p_mode)); } DirectionalLight::ShadowMode DirectionalLight::get_shadow_mode() const { @@ -340,8 +313,8 @@ DirectionalLight::ShadowMode DirectionalLight::get_shadow_mode() const { void DirectionalLight::set_blend_splits(bool p_enable) { - blend_splits=p_enable; - VS::get_singleton()->light_directional_set_blend_splits(light,p_enable); + blend_splits = p_enable; + VS::get_singleton()->light_directional_set_blend_splits(light, p_enable); } bool DirectionalLight::is_blend_splits_enabled() const { @@ -349,90 +322,83 @@ bool DirectionalLight::is_blend_splits_enabled() const { return blend_splits; } - void DirectionalLight::_bind_methods() { - ClassDB::bind_method( D_METHOD("set_shadow_mode","mode"),&DirectionalLight::set_shadow_mode); - ClassDB::bind_method( D_METHOD("get_shadow_mode"),&DirectionalLight::get_shadow_mode); + ClassDB::bind_method(D_METHOD("set_shadow_mode", "mode"), &DirectionalLight::set_shadow_mode); + ClassDB::bind_method(D_METHOD("get_shadow_mode"), &DirectionalLight::get_shadow_mode); - ClassDB::bind_method( D_METHOD("set_blend_splits","enabled"),&DirectionalLight::set_blend_splits); - ClassDB::bind_method( D_METHOD("is_blend_splits_enabled"),&DirectionalLight::is_blend_splits_enabled); + ClassDB::bind_method(D_METHOD("set_blend_splits", "enabled"), &DirectionalLight::set_blend_splits); + ClassDB::bind_method(D_METHOD("is_blend_splits_enabled"), &DirectionalLight::is_blend_splits_enabled); - ADD_GROUP("Directional Shadow","directional_shadow_"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "directional_shadow_mode",PROPERTY_HINT_ENUM,"Orthogonal,PSSM 2 Splits,PSSM 4 Splits"), "set_shadow_mode", "get_shadow_mode"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_split_1",PROPERTY_HINT_RANGE,"0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_1_OFFSET); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_split_2",PROPERTY_HINT_RANGE,"0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_2_OFFSET); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_split_3",PROPERTY_HINT_RANGE,"0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_3_OFFSET); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "directional_shadow_blend_splits"), "set_blend_splits", "is_blend_splits_enabled"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_normal_bias",PROPERTY_HINT_RANGE,"0,16,0.01"), "set_param", "get_param", PARAM_SHADOW_NORMAL_BIAS); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_bias_split_scale",PROPERTY_HINT_RANGE,"0,16,0.01"), "set_param", "get_param", PARAM_SHADOW_BIAS_SPLIT_SCALE); - - BIND_CONSTANT( SHADOW_ORTHOGONAL ); - BIND_CONSTANT( SHADOW_PARALLEL_2_SPLITS ); - BIND_CONSTANT( SHADOW_PARALLEL_4_SPLITS ); + ADD_GROUP("Directional Shadow", "directional_shadow_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "directional_shadow_mode", PROPERTY_HINT_ENUM, "Orthogonal,PSSM 2 Splits,PSSM 4 Splits"), "set_shadow_mode", "get_shadow_mode"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_split_1", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_1_OFFSET); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_split_2", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_2_OFFSET); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_split_3", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_3_OFFSET); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "directional_shadow_blend_splits"), "set_blend_splits", "is_blend_splits_enabled"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_normal_bias", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_param", "get_param", PARAM_SHADOW_NORMAL_BIAS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_bias_split_scale", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_param", "get_param", PARAM_SHADOW_BIAS_SPLIT_SCALE); + BIND_CONSTANT(SHADOW_ORTHOGONAL); + BIND_CONSTANT(SHADOW_PARALLEL_2_SPLITS); + BIND_CONSTANT(SHADOW_PARALLEL_4_SPLITS); } - -DirectionalLight::DirectionalLight() : Light( VisualServer::LIGHT_DIRECTIONAL ) { +DirectionalLight::DirectionalLight() + : Light(VisualServer::LIGHT_DIRECTIONAL) { set_shadow_mode(SHADOW_PARALLEL_4_SPLITS); - blend_splits=false; + blend_splits = false; } void OmniLight::set_shadow_mode(ShadowMode p_mode) { - shadow_mode=p_mode; - VS::get_singleton()->light_omni_set_shadow_mode(light,VS::LightOmniShadowMode(p_mode)); + shadow_mode = p_mode; + VS::get_singleton()->light_omni_set_shadow_mode(light, VS::LightOmniShadowMode(p_mode)); } -OmniLight::ShadowMode OmniLight::get_shadow_mode() const{ +OmniLight::ShadowMode OmniLight::get_shadow_mode() const { return shadow_mode; } -void OmniLight::set_shadow_detail(ShadowDetail p_detail){ +void OmniLight::set_shadow_detail(ShadowDetail p_detail) { - shadow_detail=p_detail; - VS::get_singleton()->light_omni_set_shadow_detail(light,VS::LightOmniShadowDetail(p_detail)); + shadow_detail = p_detail; + VS::get_singleton()->light_omni_set_shadow_detail(light, VS::LightOmniShadowDetail(p_detail)); } -OmniLight::ShadowDetail OmniLight::get_shadow_detail() const{ +OmniLight::ShadowDetail OmniLight::get_shadow_detail() const { return shadow_detail; } - - - void OmniLight::_bind_methods() { - ClassDB::bind_method( D_METHOD("set_shadow_mode","mode"),&OmniLight::set_shadow_mode); - ClassDB::bind_method( D_METHOD("get_shadow_mode"),&OmniLight::get_shadow_mode); - - ClassDB::bind_method( D_METHOD("set_shadow_detail","detail"),&OmniLight::set_shadow_detail); - ClassDB::bind_method( D_METHOD("get_shadow_detail"),&OmniLight::get_shadow_detail); + ClassDB::bind_method(D_METHOD("set_shadow_mode", "mode"), &OmniLight::set_shadow_mode); + ClassDB::bind_method(D_METHOD("get_shadow_mode"), &OmniLight::get_shadow_mode); - ADD_GROUP("Omni","omni_"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "omni_range",PROPERTY_HINT_RANGE,"0,65536,0.1"), "set_param", "get_param", PARAM_RANGE); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "omni_attenuation",PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_ATTENUATION); - ADD_PROPERTY( PropertyInfo( Variant::INT, "omni_shadow_mode",PROPERTY_HINT_ENUM,"Dual Paraboloid,Cube"), "set_shadow_mode", "get_shadow_mode"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "omni_shadow_detail",PROPERTY_HINT_ENUM,"Vertical,Horizontal"), "set_shadow_detail", "get_shadow_detail"); + ClassDB::bind_method(D_METHOD("set_shadow_detail", "detail"), &OmniLight::set_shadow_detail); + ClassDB::bind_method(D_METHOD("get_shadow_detail"), &OmniLight::get_shadow_detail); + ADD_GROUP("Omni", "omni_"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "omni_range", PROPERTY_HINT_RANGE, "0,65536,0.1"), "set_param", "get_param", PARAM_RANGE); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "omni_attenuation", PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_ATTENUATION); + ADD_PROPERTY(PropertyInfo(Variant::INT, "omni_shadow_mode", PROPERTY_HINT_ENUM, "Dual Paraboloid,Cube"), "set_shadow_mode", "get_shadow_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "omni_shadow_detail", PROPERTY_HINT_ENUM, "Vertical,Horizontal"), "set_shadow_detail", "get_shadow_detail"); } -OmniLight::OmniLight() : Light( VisualServer::LIGHT_OMNI ) { +OmniLight::OmniLight() + : Light(VisualServer::LIGHT_OMNI) { set_shadow_mode(SHADOW_DUAL_PARABOLOID); set_shadow_detail(SHADOW_DETAIL_HORIZONTAL); - } void SpotLight::_bind_methods() { - ADD_GROUP("Spot","spot_"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "spot_range",PROPERTY_HINT_RANGE,"0,65536,0.1"), "set_param", "get_param", PARAM_RANGE); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "spot_attenuation",PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_ATTENUATION); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "spot_angle",PROPERTY_HINT_RANGE,"0,180,0.1"), "set_param", "get_param", PARAM_SPOT_ANGLE); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "spot_angle_attenuation",PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_SPOT_ATTENUATION); - + ADD_GROUP("Spot", "spot_"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "spot_range", PROPERTY_HINT_RANGE, "0,65536,0.1"), "set_param", "get_param", PARAM_RANGE); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "spot_attenuation", PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_ATTENUATION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "spot_angle", PROPERTY_HINT_RANGE, "0,180,0.1"), "set_param", "get_param", PARAM_SPOT_ANGLE); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "spot_angle_attenuation", PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_SPOT_ATTENUATION); } diff --git a/scene/3d/light.h b/scene/3d/light.h index 4cf0156d5..fd50f0fcc 100644 --- a/scene/3d/light.h +++ b/scene/3d/light.h @@ -29,7 +29,6 @@ #ifndef LIGHT_H #define LIGHT_H - #include "scene/3d/visual_instance.h" #include "scene/resources/texture.h" #include "servers/visual_server.h" @@ -38,16 +37,14 @@ @author Juan Linietsky */ - class BakedLight; class Light : public VisualInstance { - GDCLASS( Light, VisualInstance ); + GDCLASS(Light, VisualInstance); OBJ_CATEGORY("3D Light Nodes"); public: - enum Param { PARAM_ENERGY = VS::LIGHT_PARAM_ENERGY, PARAM_SPECULAR = VS::LIGHT_PARAM_SPECULAR, @@ -55,7 +52,7 @@ public: PARAM_ATTENUATION = VS::LIGHT_PARAM_ATTENUATION, PARAM_SPOT_ANGLE = VS::LIGHT_PARAM_SPOT_ANGLE, PARAM_SPOT_ATTENUATION = VS::LIGHT_PARAM_SPOT_ATTENUATION, - PARAM_CONTACT_SHADOW_SIZE= VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE, + PARAM_CONTACT_SHADOW_SIZE = VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE, PARAM_SHADOW_MAX_DISTANCE = VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE, PARAM_SHADOW_SPLIT_1_OFFSET = VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET, PARAM_SHADOW_SPLIT_2_OFFSET = VS::LIGHT_PARAM_SHADOW_SPLIT_2_OFFSET, @@ -67,7 +64,6 @@ public: }; private: - Color color; float param[PARAM_MAX]; Color shadow_color; @@ -79,21 +75,19 @@ private: void _update_visibility(); BakedLight *baked_light; -// bind helpers + // bind helpers protected: - RID light; virtual bool _can_gizmo_scale() const; - + static void _bind_methods(); void _notification(int p_what); - Light(VisualServer::LightType p_type); -public: +public: VS::LightType get_light_type() const { return type; } void set_editor_only(bool p_editor_only); @@ -111,30 +105,26 @@ public: void set_cull_mask(uint32_t p_cull_mask); uint32_t get_cull_mask() const; - void set_color(const Color& p_color); + void set_color(const Color &p_color); Color get_color() const; - void set_shadow_color(const Color& p_shadow_color); + void set_shadow_color(const Color &p_shadow_color); Color get_shadow_color() const; - virtual Rect3 get_aabb() const; virtual PoolVector get_faces(uint32_t p_usage_flags) const; Light(); ~Light(); - }; VARIANT_ENUM_CAST(Light::Param); - class DirectionalLight : public Light { - GDCLASS( DirectionalLight, Light ); + GDCLASS(DirectionalLight, Light); public: - enum ShadowMode { SHADOW_ORTHOGONAL, SHADOW_PARALLEL_2_SPLITS, @@ -142,14 +132,13 @@ public: }; private: - bool blend_splits; ShadowMode shadow_mode; protected: static void _bind_methods(); -public: +public: void set_shadow_mode(ShadowMode p_mode); ShadowMode get_shadow_mode() const; @@ -163,7 +152,8 @@ VARIANT_ENUM_CAST(DirectionalLight::ShadowMode) class OmniLight : public Light { - GDCLASS( OmniLight, Light ); + GDCLASS(OmniLight, Light); + public: // omni light enum ShadowMode { @@ -178,14 +168,13 @@ public: }; private: - ShadowMode shadow_mode; ShadowDetail shadow_detail; + protected: static void _bind_methods(); public: - void set_shadow_mode(ShadowMode p_mode); ShadowMode get_shadow_mode() const; @@ -200,14 +189,14 @@ VARIANT_ENUM_CAST(OmniLight::ShadowDetail) class SpotLight : public Light { - GDCLASS( SpotLight, Light ); + GDCLASS(SpotLight, Light); + protected: static void _bind_methods(); -public: - - SpotLight() : Light( VisualServer::LIGHT_SPOT ) {} +public: + SpotLight() + : Light(VisualServer::LIGHT_SPOT) {} }; - #endif diff --git a/scene/3d/listener.cpp b/scene/3d/listener.cpp index 578044ad0..fc9326b57 100644 --- a/scene/3d/listener.cpp +++ b/scene/3d/listener.cpp @@ -31,8 +31,6 @@ #include "scene/resources/mesh.h" void Listener::_update_audio_listener_state() { - - } void Listener::_request_listener_update() { @@ -40,53 +38,48 @@ void Listener::_request_listener_update() { _update_listener(); } -bool Listener::_set(const StringName& p_name, const Variant& p_value) { +bool Listener::_set(const StringName &p_name, const Variant &p_value) { if (p_name == "current") { if (p_value.operator bool()) { make_current(); - } - else { + } else { clear_current(); } - } - else + } else return false; return true; } -bool Listener::_get(const StringName& p_name,Variant &r_ret) const { +bool Listener::_get(const StringName &p_name, Variant &r_ret) const { if (p_name == "current") { if (is_inside_tree() && get_tree()->is_node_being_edited(this)) { r_ret = current; - } - else { + } else { r_ret = is_current(); } - } - else + } else return false; return true; } -void Listener::_get_property_list( List *p_list) const { +void Listener::_get_property_list(List *p_list) const { - p_list->push_back( PropertyInfo( Variant::BOOL, "current" ) ); + p_list->push_back(PropertyInfo(Variant::BOOL, "current")); } void Listener::_update_listener() { if (is_inside_tree() && is_current()) { get_viewport()->_listener_transform_changed_notify(); - } } void Listener::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_WORLD: { bool first_listener = get_viewport()->_listener_add(this); @@ -101,24 +94,19 @@ void Listener::_notification(int p_what) { if (!get_tree()->is_node_being_edited(this)) { if (is_current()) { clear_current(); - current=true; //keep it true + current = true; //keep it true } else { - current=false; + current = false; } } get_viewport()->_listener_remove(this); - } break; - - } - } - Transform Listener::get_listener_transform() const { return get_global_transform().orthonormalized(); @@ -126,7 +114,7 @@ Transform Listener::get_listener_transform() const { void Listener::make_current() { - current=true; + current = true; if (!is_inside_tree()) return; @@ -134,27 +122,23 @@ void Listener::make_current() { get_viewport()->_listener_set(this); } - - - void Listener::clear_current() { - current=false; + current = false; if (!is_inside_tree()) return; - if (get_viewport()->get_listener()==this) { + if (get_viewport()->get_listener() == this) { get_viewport()->_listener_set(NULL); get_viewport()->_listener_make_next_current(this); } - } bool Listener::is_current() const { if (is_inside_tree() && !get_tree()->is_node_being_edited(this)) { - return get_viewport()->get_listener()==this; + return get_viewport()->get_listener() == this; } else return current; @@ -174,23 +158,19 @@ RES Listener::_get_gizmo_geometry() const { void Listener::_bind_methods() { - ClassDB::bind_method( D_METHOD("make_current"),&Listener::make_current ); - ClassDB::bind_method( D_METHOD("clear_current"),&Listener::clear_current ); - ClassDB::bind_method( D_METHOD("is_current"),&Listener::is_current ); - ClassDB::bind_method( D_METHOD("get_listener_transform"),&Listener::get_listener_transform ); + ClassDB::bind_method(D_METHOD("make_current"), &Listener::make_current); + ClassDB::bind_method(D_METHOD("clear_current"), &Listener::clear_current); + ClassDB::bind_method(D_METHOD("is_current"), &Listener::is_current); + ClassDB::bind_method(D_METHOD("get_listener_transform"), &Listener::get_listener_transform); } Listener::Listener() { - current=false; - force_change=false; + current = false; + force_change = false; set_notify_transform(true); //active=false; } - Listener::~Listener() { - } - - diff --git a/scene/3d/listener.h b/scene/3d/listener.h index 3b6e39bec..4fb2aea07 100644 --- a/scene/3d/listener.h +++ b/scene/3d/listener.h @@ -29,15 +29,14 @@ #ifndef LISTENER_H #define LISTENER_H - #include "scene/3d/spatial.h" #include "scene/main/viewport.h" class Listener : public Spatial { GDCLASS(Listener, Spatial); -private: +private: bool force_change; bool current; @@ -46,22 +45,21 @@ private: virtual bool _can_gizmo_scale() const; virtual RES _get_gizmo_geometry() const; -friend class Viewport; + friend class Viewport; void _update_audio_listener_state(); -protected: +protected: void _update_listener(); virtual void _request_listener_update(); - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); public: - void make_current(); void clear_current(); bool is_current() const; @@ -75,7 +73,6 @@ public: Listener(); ~Listener(); - }; #endif diff --git a/scene/3d/mesh_instance.cpp b/scene/3d/mesh_instance.cpp index e6bd69aed..b61232dbf 100644 --- a/scene/3d/mesh_instance.cpp +++ b/scene/3d/mesh_instance.cpp @@ -28,12 +28,12 @@ /*************************************************************************/ #include "mesh_instance.h" -#include "skeleton.h" -#include "physics_body.h" #include "body_shape.h" -#include "scene/scene_string_names.h" #include "core_string_names.h" -bool MeshInstance::_set(const StringName& p_name, const Variant& p_value) { +#include "physics_body.h" +#include "scene/scene_string_names.h" +#include "skeleton.h" +bool MeshInstance::_set(const StringName &p_name, const Variant &p_value) { //this is not _too_ bad performance wise, really. it only arrives here if the property was not set anywhere else. //add to it that it's probably found on first call to _set anyway. @@ -41,97 +41,91 @@ bool MeshInstance::_set(const StringName& p_name, const Variant& p_value) { if (!get_instance().is_valid()) return false; - - Map::Element *E = blend_shape_tracks.find(p_name); + Map::Element *E = blend_shape_tracks.find(p_name); if (E) { - E->get().value=p_value; - VisualServer::get_singleton()->instance_set_blend_shape_weight(get_instance(),E->get().idx,E->get().value); + E->get().value = p_value; + VisualServer::get_singleton()->instance_set_blend_shape_weight(get_instance(), E->get().idx, E->get().value); return true; } if (p_name.operator String().begins_with("material/")) { - int idx = p_name.operator String().get_slicec('/',1).to_int(); - if (idx>=materials.size() || idx<0) + int idx = p_name.operator String().get_slicec('/', 1).to_int(); + if (idx >= materials.size() || idx < 0) return false; - set_surface_material(idx,p_value); + set_surface_material(idx, p_value); return true; } return false; } -bool MeshInstance::_get(const StringName& p_name,Variant &r_ret) const { - +bool MeshInstance::_get(const StringName &p_name, Variant &r_ret) const { if (!get_instance().is_valid()) return false; - const Map::Element *E = blend_shape_tracks.find(p_name); + const Map::Element *E = blend_shape_tracks.find(p_name); if (E) { r_ret = E->get().value; return true; } if (p_name.operator String().begins_with("material/")) { - int idx = p_name.operator String().get_slicec('/',1).to_int(); - if (idx>=materials.size() || idx<0) + int idx = p_name.operator String().get_slicec('/', 1).to_int(); + if (idx >= materials.size() || idx < 0) return false; - r_ret=materials[idx]; + r_ret = materials[idx]; return true; } return false; } -void MeshInstance::_get_property_list( List *p_list) const { +void MeshInstance::_get_property_list(List *p_list) const { List ls; - for(const Map::Element *E=blend_shape_tracks.front();E;E=E->next()) { + for (const Map::Element *E = blend_shape_tracks.front(); E; E = E->next()) { ls.push_back(E->key()); } ls.sort(); - for(List::Element *E=ls.front();E;E=E->next()) { - p_list->push_back( PropertyInfo(Variant::REAL,E->get(),PROPERTY_HINT_RANGE,"0,1,0.01")); + for (List::Element *E = ls.front(); E; E = E->next()) { + p_list->push_back(PropertyInfo(Variant::REAL, E->get(), PROPERTY_HINT_RANGE, "0,1,0.01")); } if (mesh.is_valid()) { - for(int i=0;iget_surface_count();i++) { - p_list->push_back( PropertyInfo(Variant::OBJECT, "material/"+itos(i), PROPERTY_HINT_RESOURCE_TYPE, "Material")); + for (int i = 0; i < mesh->get_surface_count(); i++) { + p_list->push_back(PropertyInfo(Variant::OBJECT, "material/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "Material")); } } } +void MeshInstance::set_mesh(const Ref &p_mesh) { - - -void MeshInstance::set_mesh(const Ref& p_mesh) { - - if (mesh==p_mesh) + if (mesh == p_mesh) return; if (mesh.is_valid()) { - mesh->disconnect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->_mesh_changed); + mesh->disconnect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_mesh_changed); materials.clear(); } - mesh=p_mesh; + mesh = p_mesh; blend_shape_tracks.clear(); if (mesh.is_valid()) { - - for(int i=0;iget_blend_shape_count();i++) { + for (int i = 0; i < mesh->get_blend_shape_count(); i++) { BlendShapeTrack mt; - mt.idx=i; - mt.value=0; - blend_shape_tracks["blend_shapes/"+String(mesh->get_blend_shape_name(i))]=mt; + mt.idx = i; + mt.value = 0; + blend_shape_tracks["blend_shapes/" + String(mesh->get_blend_shape_name(i))] = mt; } - mesh->connect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->_mesh_changed); + mesh->connect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_mesh_changed); materials.resize(mesh->get_surface_count()); set_base(mesh->get_rid()); @@ -147,14 +141,14 @@ Ref MeshInstance::get_mesh() const { return mesh; } -void MeshInstance::_resolve_skeleton_path(){ +void MeshInstance::_resolve_skeleton_path() { if (skeleton_path.is_empty()) return; - Skeleton *skeleton=get_node(skeleton_path)?get_node(skeleton_path)->cast_to():NULL; + Skeleton *skeleton = get_node(skeleton_path) ? get_node(skeleton_path)->cast_to() : NULL; if (skeleton) - VisualServer::get_singleton()->instance_attach_skeleton( get_instance(), skeleton->get_skeleton() ); + VisualServer::get_singleton()->instance_attach_skeleton(get_instance(), skeleton->get_skeleton()); } void MeshInstance::set_skeleton_path(const NodePath &p_skeleton) { @@ -179,7 +173,7 @@ Rect3 MeshInstance::get_aabb() const { PoolVector MeshInstance::get_faces(uint32_t p_usage_flags) const { - if (!(p_usage_flags&(FACES_SOLID|FACES_ENCLOSING))) + if (!(p_usage_flags & (FACES_SOLID | FACES_ENCLOSING))) return PoolVector(); if (mesh.is_null()) @@ -188,8 +182,7 @@ PoolVector MeshInstance::get_faces(uint32_t p_usage_flags) const { return mesh->get_faces(); } - -Node* MeshInstance::create_trimesh_collision_node() { +Node *MeshInstance::create_trimesh_collision_node() { if (mesh.is_null()) return NULL; @@ -198,32 +191,28 @@ Node* MeshInstance::create_trimesh_collision_node() { if (shape.is_null()) return NULL; - StaticBody * static_body = memnew( StaticBody ); - static_body->add_shape( shape ); + StaticBody *static_body = memnew(StaticBody); + static_body->add_shape(shape); return static_body; - - } void MeshInstance::create_trimesh_collision() { - - StaticBody* static_body = create_trimesh_collision_node()->cast_to(); + StaticBody *static_body = create_trimesh_collision_node()->cast_to(); ERR_FAIL_COND(!static_body); - static_body->set_name( String(get_name()) + "_col" ); + static_body->set_name(String(get_name()) + "_col"); add_child(static_body); if (get_owner()) - static_body->set_owner( get_owner() ); - CollisionShape *cshape = memnew( CollisionShape ); + static_body->set_owner(get_owner()); + CollisionShape *cshape = memnew(CollisionShape); cshape->set_shape(static_body->get_shape(0)); static_body->add_child(cshape); if (get_owner()) - cshape->set_owner( get_owner() ); - + cshape->set_owner(get_owner()); } -Node* MeshInstance::create_convex_collision_node() { +Node *MeshInstance::create_convex_collision_node() { if (mesh.is_null()) return NULL; @@ -232,91 +221,78 @@ Node* MeshInstance::create_convex_collision_node() { if (shape.is_null()) return NULL; - StaticBody * static_body = memnew( StaticBody ); - static_body->add_shape( shape ); + StaticBody *static_body = memnew(StaticBody); + static_body->add_shape(shape); return static_body; - - } void MeshInstance::create_convex_collision() { - - StaticBody* static_body = create_convex_collision_node()->cast_to(); + StaticBody *static_body = create_convex_collision_node()->cast_to(); ERR_FAIL_COND(!static_body); - static_body->set_name( String(get_name()) + "_col" ); + static_body->set_name(String(get_name()) + "_col"); add_child(static_body); if (get_owner()) - static_body->set_owner( get_owner() ); - CollisionShape *cshape = memnew( CollisionShape ); + static_body->set_owner(get_owner()); + CollisionShape *cshape = memnew(CollisionShape); cshape->set_shape(static_body->get_shape(0)); static_body->add_child(cshape); if (get_owner()) - cshape->set_owner( get_owner() ); - - + cshape->set_owner(get_owner()); } void MeshInstance::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_TREE) { + if (p_what == NOTIFICATION_ENTER_TREE) { _resolve_skeleton_path(); } } +void MeshInstance::set_surface_material(int p_surface, const Ref &p_material) { -void MeshInstance::set_surface_material(int p_surface,const Ref& p_material) { + ERR_FAIL_INDEX(p_surface, materials.size()); - ERR_FAIL_INDEX(p_surface,materials.size()); - - materials[p_surface]=p_material; + materials[p_surface] = p_material; if (materials[p_surface].is_valid()) - VS::get_singleton()->instance_set_surface_material(get_instance(),p_surface,materials[p_surface]->get_rid()); + VS::get_singleton()->instance_set_surface_material(get_instance(), p_surface, materials[p_surface]->get_rid()); else - VS::get_singleton()->instance_set_surface_material(get_instance(),p_surface,RID()); - + VS::get_singleton()->instance_set_surface_material(get_instance(), p_surface, RID()); } Ref MeshInstance::get_surface_material(int p_surface) const { - ERR_FAIL_INDEX_V(p_surface,materials.size(),Ref()); + ERR_FAIL_INDEX_V(p_surface, materials.size(), Ref()); return materials[p_surface]; } - void MeshInstance::_mesh_changed() { - materials.resize( mesh->get_surface_count() ); + materials.resize(mesh->get_surface_count()); } void MeshInstance::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_mesh","mesh:Mesh"),&MeshInstance::set_mesh); - ClassDB::bind_method(D_METHOD("get_mesh:Mesh"),&MeshInstance::get_mesh); - ClassDB::bind_method(D_METHOD("set_skeleton_path","skeleton_path:NodePath"),&MeshInstance::set_skeleton_path); - ClassDB::bind_method(D_METHOD("get_skeleton_path:NodePath"),&MeshInstance::get_skeleton_path); + ClassDB::bind_method(D_METHOD("set_mesh", "mesh:Mesh"), &MeshInstance::set_mesh); + ClassDB::bind_method(D_METHOD("get_mesh:Mesh"), &MeshInstance::get_mesh); + ClassDB::bind_method(D_METHOD("set_skeleton_path", "skeleton_path:NodePath"), &MeshInstance::set_skeleton_path); + ClassDB::bind_method(D_METHOD("get_skeleton_path:NodePath"), &MeshInstance::get_skeleton_path); - ClassDB::bind_method(D_METHOD("create_trimesh_collision"),&MeshInstance::create_trimesh_collision); - ClassDB::set_method_flags("MeshInstance","create_trimesh_collision",METHOD_FLAGS_DEFAULT); - ClassDB::bind_method(D_METHOD("create_convex_collision"),&MeshInstance::create_convex_collision); - ClassDB::set_method_flags("MeshInstance","create_convex_collision",METHOD_FLAGS_DEFAULT); - ClassDB::bind_method(D_METHOD("_mesh_changed"),&MeshInstance::_mesh_changed); + ClassDB::bind_method(D_METHOD("create_trimesh_collision"), &MeshInstance::create_trimesh_collision); + ClassDB::set_method_flags("MeshInstance", "create_trimesh_collision", METHOD_FLAGS_DEFAULT); + ClassDB::bind_method(D_METHOD("create_convex_collision"), &MeshInstance::create_convex_collision); + ClassDB::set_method_flags("MeshInstance", "create_convex_collision", METHOD_FLAGS_DEFAULT); + ClassDB::bind_method(D_METHOD("_mesh_changed"), &MeshInstance::_mesh_changed); - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh" ), "set_mesh", "get_mesh"); - ADD_PROPERTY( PropertyInfo (Variant::NODE_PATH, "skeleton"), "set_skeleton_path", "get_skeleton_path"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh"); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "skeleton"), "set_skeleton_path", "get_skeleton_path"); } -MeshInstance::MeshInstance() -{ - skeleton_path=NodePath(".."); +MeshInstance::MeshInstance() { + skeleton_path = NodePath(".."); } - MeshInstance::~MeshInstance() { - } - - diff --git a/scene/3d/mesh_instance.h b/scene/3d/mesh_instance.h index 2d1af4698..543f407ca 100644 --- a/scene/3d/mesh_instance.h +++ b/scene/3d/mesh_instance.h @@ -37,7 +37,7 @@ */ class MeshInstance : public GeometryInstance { - GDCLASS( MeshInstance, GeometryInstance ); + GDCLASS(MeshInstance, GeometryInstance); Ref mesh; NodePath skeleton_path; @@ -46,38 +46,40 @@ class MeshInstance : public GeometryInstance { int idx; float value; - BlendShapeTrack() { idx=0; value=0; } + BlendShapeTrack() { + idx = 0; + value = 0; + } }; - Map blend_shape_tracks; + Map blend_shape_tracks; Vector > materials; void _mesh_changed(); void _resolve_skeleton_path(); protected: - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); -public: - void set_mesh(const Ref& p_mesh); +public: + void set_mesh(const Ref &p_mesh); Ref get_mesh() const; - void set_skeleton_path(const NodePath& p_skeleton); + void set_skeleton_path(const NodePath &p_skeleton); NodePath get_skeleton_path(); - void set_surface_material(int p_surface,const Ref& p_material); + void set_surface_material(int p_surface, const Ref &p_material); Ref get_surface_material(int p_surface) const; - Node* create_trimesh_collision_node(); + Node *create_trimesh_collision_node(); void create_trimesh_collision(); - Node* create_convex_collision_node(); + Node *create_convex_collision_node(); void create_convex_collision(); virtual Rect3 get_aabb() const; diff --git a/scene/3d/multimesh_instance.cpp b/scene/3d/multimesh_instance.cpp index e1acdfca5..18a747a5b 100644 --- a/scene/3d/multimesh_instance.cpp +++ b/scene/3d/multimesh_instance.cpp @@ -28,27 +28,20 @@ /*************************************************************************/ #include "multimesh_instance.h" - - - - void MultiMeshInstance::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_multimesh","multimesh"),&MultiMeshInstance::set_multimesh); - ClassDB::bind_method(D_METHOD("get_multimesh"),&MultiMeshInstance::get_multimesh); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"multimesh",PROPERTY_HINT_RESOURCE_TYPE,"MultiMesh"), "set_multimesh", "get_multimesh"); - - + ClassDB::bind_method(D_METHOD("set_multimesh", "multimesh"), &MultiMeshInstance::set_multimesh); + ClassDB::bind_method(D_METHOD("get_multimesh"), &MultiMeshInstance::get_multimesh); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "multimesh", PROPERTY_HINT_RESOURCE_TYPE, "MultiMesh"), "set_multimesh", "get_multimesh"); } -void MultiMeshInstance::set_multimesh(const Ref& p_multimesh) { +void MultiMeshInstance::set_multimesh(const Ref &p_multimesh) { - multimesh=p_multimesh; + multimesh = p_multimesh; if (multimesh.is_valid()) set_base(multimesh->get_rid()); else set_base(RID()); - } Ref MultiMeshInstance::get_multimesh() const { @@ -56,8 +49,6 @@ Ref MultiMeshInstance::get_multimesh() const { return multimesh; } - - PoolVector MultiMeshInstance::get_faces(uint32_t p_usage_flags) const { return PoolVector(); @@ -72,10 +63,7 @@ Rect3 MultiMeshInstance::get_aabb() const { } MultiMeshInstance::MultiMeshInstance() { - } MultiMeshInstance::~MultiMeshInstance() { - - } diff --git a/scene/3d/multimesh_instance.h b/scene/3d/multimesh_instance.h index 535e4275a..4a0edb563 100644 --- a/scene/3d/multimesh_instance.h +++ b/scene/3d/multimesh_instance.h @@ -37,21 +37,18 @@ */ class MultiMeshInstance : public GeometryInstance { - GDCLASS( MultiMeshInstance, GeometryInstance ); - + GDCLASS(MultiMeshInstance, GeometryInstance); Ref multimesh; -protected: - +protected: static void _bind_methods(); // bind helpers public: - virtual PoolVector get_faces(uint32_t p_usage_flags) const; - void set_multimesh(const Ref& p_multimesh); + void set_multimesh(const Ref &p_multimesh); Ref get_multimesh() const; virtual Rect3 get_aabb() const; @@ -61,4 +58,3 @@ public: }; #endif // MULTIMESH_INSTANCE_H - diff --git a/scene/3d/navigation.cpp b/scene/3d/navigation.cpp index 5c8fe6bb6..093d217cb 100644 --- a/scene/3d/navigation.cpp +++ b/scene/3d/navigation.cpp @@ -31,60 +31,58 @@ void Navigation::_navmesh_link(int p_id) { ERR_FAIL_COND(!navmesh_map.has(p_id)); - NavMesh &nm=navmesh_map[p_id]; + NavMesh &nm = navmesh_map[p_id]; ERR_FAIL_COND(nm.linked); print_line("LINK"); - PoolVector vertices=nm.navmesh->get_vertices(); + PoolVector vertices = nm.navmesh->get_vertices(); int len = vertices.size(); - if (len==0) + if (len == 0) return; - PoolVector::Read r=vertices.read(); + PoolVector::Read r = vertices.read(); - for(int i=0;iget_polygon_count();i++) { + for (int i = 0; i < nm.navmesh->get_polygon_count(); i++) { //build - List::Element *P=nm.polygons.push_back(Polygon()); - Polygon &p=P->get(); - p.owner=&nm; + List::Element *P = nm.polygons.push_back(Polygon()); + Polygon &p = P->get(); + p.owner = &nm; Vector poly = nm.navmesh->get_polygon(i); - int plen=poly.size(); - const int *indices=poly.ptr(); - bool valid=true; + int plen = poly.size(); + const int *indices = poly.ptr(); + bool valid = true; p.edges.resize(plen); Vector3 center; - float sum=0; + float sum = 0; - for(int j=0;j=len) { - valid=false; + if (idx < 0 || idx >= len) { + valid = false; break; } Polygon::Edge e; - Vector3 ep=nm.xform.xform(r[idx]); - center+=ep; - e.point=_get_point(ep); - p.edges[j]=e; + Vector3 ep = nm.xform.xform(r[idx]); + center += ep; + e.point = _get_point(ep); + p.edges[j] = e; - if (j>=2) { - Vector3 epa = nm.xform.xform(r[indices[j-2]]); - Vector3 epb = nm.xform.xform(r[indices[j-1]]); - - sum+=up.dot((epb-epa).cross(ep-epa)); + if (j >= 2) { + Vector3 epa = nm.xform.xform(r[indices[j - 2]]); + Vector3 epb = nm.xform.xform(r[indices[j - 1]]); + sum += up.dot((epb - epa).cross(ep - epa)); } - } - p.clockwise=sum>0; + p.clockwise = sum > 0; if (!valid) { nm.polygons.pop_back(); @@ -93,110 +91,106 @@ void Navigation::_navmesh_link(int p_id) { } p.center = center; - if( plen != 0 ) { + if (plen != 0) { p.center /= plen; } - //connect - for(int j=0;j::Element *C=connections.find(ek); + Map::Element *C = connections.find(ek); if (!C) { Connection c; - c.A=&p; - c.A_edge=j; - c.B=NULL; - c.B_edge=-1; - connections[ek]=c; + c.A = &p; + c.A_edge = j; + c.B = NULL; + c.B_edge = -1; + connections[ek] = c; } else { - if (C->get().B!=NULL) { + if (C->get().B != NULL) { ConnectionPending pending; - pending.polygon=&p; - pending.edge=j; - p.edges[j].P=C->get().pending.push_back(pending); + pending.polygon = &p; + pending.edge = j; + p.edges[j].P = C->get().pending.push_back(pending); continue; //print_line(String()+_get_vertex(ek.a)+" -> "+_get_vertex(ek.b)); } //ERR_CONTINUE(C->get().B!=NULL); //wut - C->get().B=&p; - C->get().B_edge=j; - C->get().A->edges[C->get().A_edge].C=&p; - C->get().A->edges[C->get().A_edge].C_edge=j; - p.edges[j].C=C->get().A; - p.edges[j].C_edge=C->get().A_edge; + C->get().B = &p; + C->get().B_edge = j; + C->get().A->edges[C->get().A_edge].C = &p; + C->get().A->edges[C->get().A_edge].C_edge = j; + p.edges[j].C = C->get().A; + p.edges[j].C_edge = C->get().A_edge; //connection successful. } } } - nm.linked=true; - + nm.linked = true; } - void Navigation::_navmesh_unlink(int p_id) { ERR_FAIL_COND(!navmesh_map.has(p_id)); - NavMesh &nm=navmesh_map[p_id]; + NavMesh &nm = navmesh_map[p_id]; ERR_FAIL_COND(!nm.linked); print_line("UNLINK"); - for (List::Element *E=nm.polygons.front();E;E=E->next()) { - + for (List::Element *E = nm.polygons.front(); E; E = E->next()) { - Polygon &p=E->get(); + Polygon &p = E->get(); int ec = p.edges.size(); - Polygon::Edge *edges=p.edges.ptr(); + Polygon::Edge *edges = p.edges.ptr(); - for(int i=0;i::Element *C=connections.find(ek); + EdgeKey ek(edges[i].point, edges[next].point); + Map::Element *C = connections.find(ek); ERR_CONTINUE(!C); if (edges[i].P) { C->get().pending.erase(edges[i].P); - edges[i].P=NULL; + edges[i].P = NULL; } else if (C->get().B) { //disconnect - C->get().B->edges[C->get().B_edge].C=NULL; - C->get().B->edges[C->get().B_edge].C_edge=-1; - C->get().A->edges[C->get().A_edge].C=NULL; - C->get().A->edges[C->get().A_edge].C_edge=-1; + C->get().B->edges[C->get().B_edge].C = NULL; + C->get().B->edges[C->get().B_edge].C_edge = -1; + C->get().A->edges[C->get().A_edge].C = NULL; + C->get().A->edges[C->get().A_edge].C_edge = -1; - if (C->get().A==&E->get()) { + if (C->get().A == &E->get()) { - C->get().A=C->get().B; - C->get().A_edge=C->get().B_edge; + C->get().A = C->get().B; + C->get().A_edge = C->get().B_edge; } - C->get().B=NULL; - C->get().B_edge=-1; + C->get().B = NULL; + C->get().B_edge = -1; if (C->get().pending.size()) { //reconnect if something is pending ConnectionPending cp = C->get().pending.front()->get(); C->get().pending.pop_front(); - C->get().B=cp.polygon; - C->get().B_edge=cp.edge; - C->get().A->edges[C->get().A_edge].C=cp.polygon; - C->get().A->edges[C->get().A_edge].C_edge=cp.edge; - cp.polygon->edges[cp.edge].C=C->get().A; - cp.polygon->edges[cp.edge].C_edge=C->get().A_edge; - cp.polygon->edges[cp.edge].P=NULL; + C->get().B = cp.polygon; + C->get().B_edge = cp.edge; + C->get().A->edges[C->get().A_edge].C = cp.polygon; + C->get().A->edges[C->get().A_edge].C_edge = cp.edge; + cp.polygon->edges[cp.edge].C = C->get().A; + cp.polygon->edges[cp.edge].C_edge = C->get().A_edge; + cp.polygon->edges[cp.edge].P = NULL; } } else { @@ -208,76 +202,68 @@ void Navigation::_navmesh_unlink(int p_id) { nm.polygons.clear(); - nm.linked=false; - - + nm.linked = false; } - -int Navigation::navmesh_create(const Ref& p_mesh, const Transform& p_xform, Object *p_owner) { +int Navigation::navmesh_create(const Ref &p_mesh, const Transform &p_xform, Object *p_owner) { int id = last_id++; NavMesh nm; - nm.linked=false; - nm.navmesh=p_mesh; - nm.xform=p_xform; - nm.owner=p_owner; - navmesh_map[id]=nm; + nm.linked = false; + nm.navmesh = p_mesh; + nm.xform = p_xform; + nm.owner = p_owner; + navmesh_map[id] = nm; _navmesh_link(id); return id; } -void Navigation::navmesh_set_transform(int p_id, const Transform& p_xform){ +void Navigation::navmesh_set_transform(int p_id, const Transform &p_xform) { ERR_FAIL_COND(!navmesh_map.has(p_id)); - NavMesh &nm=navmesh_map[p_id]; - if (nm.xform==p_xform) + NavMesh &nm = navmesh_map[p_id]; + if (nm.xform == p_xform) return; //bleh _navmesh_unlink(p_id); - nm.xform=p_xform; + nm.xform = p_xform; _navmesh_link(p_id); - - - } -void Navigation::navmesh_remove(int p_id){ +void Navigation::navmesh_remove(int p_id) { ERR_FAIL_COND(!navmesh_map.has(p_id)); _navmesh_unlink(p_id); navmesh_map.erase(p_id); - } -void Navigation::_clip_path(Vector& path, Polygon *from_poly, const Vector3& p_to_point, Polygon* p_to_poly) { +void Navigation::_clip_path(Vector &path, Polygon *from_poly, const Vector3 &p_to_point, Polygon *p_to_poly) { - Vector3 from = path[path.size()-1]; + Vector3 from = path[path.size() - 1]; - if (from.distance_to(p_to_point)prev_edge; Vector3 a = _get_vertex(from_poly->edges[pe].point); - Vector3 b = _get_vertex(from_poly->edges[(pe+1)%from_poly->edges.size()].point); + Vector3 b = _get_vertex(from_poly->edges[(pe + 1) % from_poly->edges.size()].point); - from_poly=from_poly->edges[pe].C; + from_poly = from_poly->edges[pe].C; ERR_FAIL_COND(!from_poly); - if (a.distance_to(b)>CMP_EPSILON) { + if (a.distance_to(b) > CMP_EPSILON) { Vector3 inters; - if (cut_plane.intersects_segment(a,b,&inters)) { - if (inters.distance_to(p_to_point)>CMP_EPSILON && inters.distance_to(path[path.size()-1])>CMP_EPSILON) { + if (cut_plane.intersects_segment(a, b, &inters)) { + if (inters.distance_to(p_to_point) > CMP_EPSILON && inters.distance_to(path[path.size() - 1]) > CMP_EPSILON) { path.push_back(inters); } } @@ -285,149 +271,138 @@ void Navigation::_clip_path(Vector& path, Polygon *from_poly, const Vec } } -Vector Navigation::get_simple_path(const Vector3& p_start, const Vector3& p_end, bool p_optimize) { +Vector Navigation::get_simple_path(const Vector3 &p_start, const Vector3 &p_end, bool p_optimize) { - - Polygon *begin_poly=NULL; - Polygon *end_poly=NULL; + Polygon *begin_poly = NULL; + Polygon *end_poly = NULL; Vector3 begin_point; Vector3 end_point; - float begin_d=1e20; - float end_d=1e20; - + float begin_d = 1e20; + float end_d = 1e20; - for (Map::Element*E=navmesh_map.front();E;E=E->next()) { + for (Map::Element *E = navmesh_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); - for(int i=2;iget(); + for (int i = 2; i < p.edges.size(); i++) { - Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point)); + Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point)); Vector3 spoint = f.get_closest_point_to(p_start); float dpoint = spoint.distance_to(p_start); - if (dpoint(); //no path } - - if (begin_poly==end_poly) { + if (begin_poly == end_poly) { Vector path; path.resize(2); - path[0]=begin_point; - path[1]=end_point; + path[0] = begin_point; + path[1] = end_point; //print_line("Direct Path"); return path; } + bool found_route = false; - bool found_route=false; - - List open_list; + List open_list; - for(int i=0;iedges.size();i++) { + for (int i = 0; i < begin_poly->edges.size(); i++) { if (begin_poly->edges[i].C) { - begin_poly->edges[i].C->prev_edge=begin_poly->edges[i].C_edge; - begin_poly->edges[i].C->distance=begin_poly->center.distance_to(begin_poly->edges[i].C->center); + begin_poly->edges[i].C->prev_edge = begin_poly->edges[i].C_edge; + begin_poly->edges[i].C->distance = begin_poly->center.distance_to(begin_poly->edges[i].C->center); open_list.push_back(begin_poly->edges[i].C); - if (begin_poly->edges[i].C==end_poly) { - found_route=true; + if (begin_poly->edges[i].C == end_poly) { + found_route = true; } } } + while (!found_route) { - while(!found_route) { - - if (open_list.size()==0) { + if (open_list.size() == 0) { //print_line("NOU OPEN LIST"); break; } //check open list - List::Element *least_cost_poly=NULL; - float least_cost=1e30; + List::Element *least_cost_poly = NULL; + float least_cost = 1e30; //this could be faster (cache previous results) - for (List::Element *E=open_list.front();E;E=E->next()) { - - Polygon *p=E->get(); + for (List::Element *E = open_list.front(); E; E = E->next()) { + Polygon *p = E->get(); - float cost=p->distance; - cost+=p->center.distance_to(end_point); + float cost = p->distance; + cost += p->center.distance_to(end_point); - if (costget(); + Polygon *p = least_cost_poly->get(); //open the neighbours for search - for(int i=0;iedges.size();i++) { - + for (int i = 0; i < p->edges.size(); i++) { - Polygon::Edge &e=p->edges[i]; + Polygon::Edge &e = p->edges[i]; if (!e.C) continue; float distance = p->center.distance_to(e.C->center) + p->distance; - if (e.C->prev_edge!=-1) { + if (e.C->prev_edge != -1) { //oh this was visited already, can we win the cost? - if (e.C->distance>distance) { + if (e.C->distance > distance) { - e.C->prev_edge=e.C_edge; - e.C->distance=distance; + e.C->prev_edge = e.C_edge; + e.C->distance = distance; } } else { //add to open neighbours - e.C->prev_edge=e.C_edge; - e.C->distance=distance; + e.C->prev_edge = e.C_edge; + e.C->distance = distance; open_list.push_back(e.C); - if (e.C==end_poly) { + if (e.C == end_poly) { //oh my reached end! stop algorithm - found_route=true; + found_route = true; break; - } - } } @@ -444,174 +419,164 @@ Vector Navigation::get_simple_path(const Vector3& p_start, const Vector if (p_optimize) { //string pulling - Polygon *apex_poly=end_poly; - Vector3 apex_point=end_point; - Vector3 portal_left=apex_point; - Vector3 portal_right=apex_point; - Polygon *left_poly=end_poly; - Polygon *right_poly=end_poly; - Polygon *p=end_poly; + Polygon *apex_poly = end_poly; + Vector3 apex_point = end_point; + Vector3 portal_left = apex_point; + Vector3 portal_right = apex_point; + Polygon *left_poly = end_poly; + Polygon *right_poly = end_poly; + Polygon *p = end_poly; path.push_back(end_point); - while(p) { + while (p) { Vector3 left; Vector3 right; -#define CLOCK_TANGENT(m_a,m_b,m_c) ( ((m_a)-(m_c)).cross((m_a)-(m_b)) ) +#define CLOCK_TANGENT(m_a, m_b, m_c) (((m_a) - (m_c)).cross((m_a) - (m_b))) - if (p==begin_poly) { - left=begin_point; - right=begin_point; + if (p == begin_poly) { + left = begin_point; + right = begin_point; } else { int prev = p->prev_edge; - int prev_n = (p->prev_edge+1)%p->edges.size(); + int prev_n = (p->prev_edge + 1) % p->edges.size(); left = _get_vertex(p->edges[prev].point); right = _get_vertex(p->edges[prev_n].point); //if (CLOCK_TANGENT(apex_point,left,(left+right)*0.5).dot(up) < 0){ if (p->clockwise) { - SWAP(left,right); + SWAP(left, right); } } - bool skip=false; - + bool skip = false; - if (CLOCK_TANGENT(apex_point,portal_left,left).dot(up) >= 0){ + if (CLOCK_TANGENT(apex_point, portal_left, left).dot(up) >= 0) { //process - if (portal_left==apex_point || CLOCK_TANGENT(apex_point,left,portal_right).dot(up) > 0) { - left_poly=p; - portal_left=left; + if (portal_left == apex_point || CLOCK_TANGENT(apex_point, left, portal_right).dot(up) > 0) { + left_poly = p; + portal_left = left; } else { - _clip_path(path,apex_poly,portal_right,right_poly); + _clip_path(path, apex_poly, portal_right, right_poly); - apex_point=portal_right; - p=right_poly; - left_poly=p; - apex_poly=p; - portal_left=apex_point; - portal_right=apex_point; + apex_point = portal_right; + p = right_poly; + left_poly = p; + apex_poly = p; + portal_left = apex_point; + portal_right = apex_point; path.push_back(apex_point); - skip=true; + skip = true; } } - if (!skip && CLOCK_TANGENT(apex_point,portal_right,right).dot(up) <= 0){ + if (!skip && CLOCK_TANGENT(apex_point, portal_right, right).dot(up) <= 0) { //process - if (portal_right==apex_point || CLOCK_TANGENT(apex_point,right,portal_left).dot(up) < 0) { - right_poly=p; - portal_right=right; + if (portal_right == apex_point || CLOCK_TANGENT(apex_point, right, portal_left).dot(up) < 0) { + right_poly = p; + portal_right = right; } else { - _clip_path(path,apex_poly,portal_left,left_poly); + _clip_path(path, apex_poly, portal_left, left_poly); - apex_point=portal_left; - p=left_poly; - right_poly=p; - apex_poly=p; - portal_right=apex_point; - portal_left=apex_point; + apex_point = portal_left; + p = left_poly; + right_poly = p; + apex_poly = p; + portal_right = apex_point; + portal_left = apex_point; path.push_back(apex_point); } } - if (p!=begin_poly) - p=p->edges[p->prev_edge].C; + if (p != begin_poly) + p = p->edges[p->prev_edge].C; else - p=NULL; - + p = NULL; } - if (path[path.size()-1]!=begin_point) + if (path[path.size() - 1] != begin_point) path.push_back(begin_point); path.invert(); - - - } else { //midpoints - Polygon *p=end_poly; + Polygon *p = end_poly; path.push_back(end_point); - while(true) { + while (true) { int prev = p->prev_edge; - int prev_n = (p->prev_edge+1)%p->edges.size(); - Vector3 point = (_get_vertex(p->edges[prev].point) + _get_vertex(p->edges[prev_n].point))*0.5; + int prev_n = (p->prev_edge + 1) % p->edges.size(); + Vector3 point = (_get_vertex(p->edges[prev].point) + _get_vertex(p->edges[prev_n].point)) * 0.5; path.push_back(point); p = p->edges[prev].C; - if (p==begin_poly) + if (p == begin_poly) break; } path.push_back(begin_point); - path.invert(); } return path; } - return Vector(); - } -Vector3 Navigation::get_closest_point_to_segment(const Vector3& p_from,const Vector3& p_to,const bool& p_use_collision) { - +Vector3 Navigation::get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool &p_use_collision) { - bool use_collision=p_use_collision; + bool use_collision = p_use_collision; Vector3 closest_point; - float closest_point_d=1e20; - NavMesh *closest_navmesh=NULL; + float closest_point_d = 1e20; + NavMesh *closest_navmesh = NULL; - for (Map::Element*E=navmesh_map.front();E;E=E->next()) { + for (Map::Element *E = navmesh_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); - for(int i=2;iget(); + for (int i = 2; i < p.edges.size(); i++) { - Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point)); + Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point)); Vector3 inters; - if (f.intersects_segment(p_from,p_to,&inters)) { + if (f.intersects_segment(p_from, p_to, &inters)) { if (!use_collision) { - closest_point=inters; - use_collision=true; - closest_point_d=p_from.distance_to(inters); - closest_navmesh=p.owner; - } else if (closest_point_d > inters.distance_to(p_from)){ - - closest_point=inters; - closest_point_d=p_from.distance_to(inters); - closest_navmesh=p.owner; + closest_point = inters; + use_collision = true; + closest_point_d = p_from.distance_to(inters); + closest_navmesh = p.owner; + } else if (closest_point_d > inters.distance_to(p_from)) { + + closest_point = inters; + closest_point_d = p_from.distance_to(inters); + closest_navmesh = p.owner; } } } if (!use_collision) { - for(int i=0;i::Element*E=navmesh_map.front();E;E=E->next()) { + for (Map::Element *E = navmesh_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); - for(int i=2;iget(); + for (int i = 2; i < p.edges.size(); i++) { - Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point)); + Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point)); Vector3 inters = f.get_closest_point_to(p_point); float d = inters.distance_to(p_point); - if (d::Element*E=navmesh_map.front();E;E=E->next()) { + for (Map::Element *E = navmesh_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); - for(int i=2;iget(); + for (int i = 2; i < p.edges.size(); i++) { - Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point)); + Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point)); Vector3 inters = f.get_closest_point_to(p_point); float d = inters.distance_to(p_point); - if (d::Element*E=navmesh_map.front();E;E=E->next()) { + for (Map::Element *E = navmesh_map.front(); E; E = E->next()) { if (!E->get().linked) continue; - for(List::Element *F=E->get().polygons.front();F;F=F->next()) { + for (List::Element *F = E->get().polygons.front(); F; F = F->next()) { - Polygon &p=F->get(); - for(int i=2;iget(); + for (int i = 2; i < p.edges.size(); i++) { - Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point)); + Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point)); Vector3 inters = f.get_closest_point_to(p_point); float d = inters.distance_to(p_point); - if (dget().owner; + if (d < closest_point_d) { + closest_point = inters; + closest_point_d = d; + owner = E->get().owner; } } } } return owner; - } -void Navigation::set_up_vector(const Vector3& p_up) { +void Navigation::set_up_vector(const Vector3 &p_up) { - - up=p_up; + up = p_up; } -Vector3 Navigation::get_up_vector() const{ +Vector3 Navigation::get_up_vector() const { return up; } - void Navigation::_bind_methods() { - ClassDB::bind_method(D_METHOD("navmesh_create","mesh:NavigationMesh","xform","owner"),&Navigation::navmesh_create,DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("navmesh_set_transform","id","xform"),&Navigation::navmesh_set_transform); - ClassDB::bind_method(D_METHOD("navmesh_remove","id"),&Navigation::navmesh_remove); + ClassDB::bind_method(D_METHOD("navmesh_create", "mesh:NavigationMesh", "xform", "owner"), &Navigation::navmesh_create, DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("navmesh_set_transform", "id", "xform"), &Navigation::navmesh_set_transform); + ClassDB::bind_method(D_METHOD("navmesh_remove", "id"), &Navigation::navmesh_remove); - ClassDB::bind_method(D_METHOD("get_simple_path","start","end","optimize"),&Navigation::get_simple_path,DEFVAL(true)); - ClassDB::bind_method(D_METHOD("get_closest_point_to_segment","start","end","use_collision"),&Navigation::get_closest_point_to_segment,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_closest_point","to_point"),&Navigation::get_closest_point); - ClassDB::bind_method(D_METHOD("get_closest_point_normal","to_point"),&Navigation::get_closest_point_normal); - ClassDB::bind_method(D_METHOD("get_closest_point_owner","to_point"),&Navigation::get_closest_point_owner); + ClassDB::bind_method(D_METHOD("get_simple_path", "start", "end", "optimize"), &Navigation::get_simple_path, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("get_closest_point_to_segment", "start", "end", "use_collision"), &Navigation::get_closest_point_to_segment, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_closest_point", "to_point"), &Navigation::get_closest_point); + ClassDB::bind_method(D_METHOD("get_closest_point_normal", "to_point"), &Navigation::get_closest_point_normal); + ClassDB::bind_method(D_METHOD("get_closest_point_owner", "to_point"), &Navigation::get_closest_point_owner); - ClassDB::bind_method(D_METHOD("set_up_vector","up"),&Navigation::set_up_vector); - ClassDB::bind_method(D_METHOD("get_up_vector"),&Navigation::get_up_vector); + ClassDB::bind_method(D_METHOD("set_up_vector", "up"), &Navigation::set_up_vector); + ClassDB::bind_method(D_METHOD("get_up_vector"), &Navigation::get_up_vector); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"up_vector"),"set_up_vector","get_up_vector"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "up_vector"), "set_up_vector", "get_up_vector"); } Navigation::Navigation() { - ERR_FAIL_COND( sizeof(Point)!=8 ); - cell_size=0.01; //one centimeter - last_id=1; - up=Vector3(0,1,0); + ERR_FAIL_COND(sizeof(Point) != 8); + cell_size = 0.01; //one centimeter + last_id = 1; + up = Vector3(0, 1, 0); } diff --git a/scene/3d/navigation.h b/scene/3d/navigation.h index 771e12466..6222d2bad 100644 --- a/scene/3d/navigation.h +++ b/scene/3d/navigation.h @@ -29,46 +29,43 @@ #ifndef NAVIGATION_H #define NAVIGATION_H -#include "scene/3d/spatial.h" #include "scene/3d/navigation_mesh.h" +#include "scene/3d/spatial.h" class Navigation : public Spatial { - GDCLASS( Navigation, Spatial); - + GDCLASS(Navigation, Spatial); union Point { struct { - int64_t x:21; - int64_t y:22; - int64_t z:21; + int64_t x : 21; + int64_t y : 22; + int64_t z : 21; }; uint64_t key; - bool operator<(const Point& p_key) const { return key < p_key.key; } + bool operator<(const Point &p_key) const { return key < p_key.key; } }; - struct EdgeKey { Point a; Point b; - bool operator<(const EdgeKey& p_key) const { - return (a.key==p_key.a.key)?(b.key b.key) { - SWAP(a,b); + SWAP(a, b); } } }; - struct NavMesh; struct Polygon; @@ -78,7 +75,6 @@ class Navigation : public Spatial { int edge; }; - struct Polygon { struct Edge { @@ -86,7 +82,11 @@ class Navigation : public Spatial { Polygon *C; //connection int C_edge; List::Element *P; - Edge() { C=NULL; C_edge=-1; P=NULL; } + Edge() { + C = NULL; + C_edge = -1; + P = NULL; + } }; Vector edges; @@ -97,11 +97,9 @@ class Navigation : public Spatial { int prev_edge; bool clockwise; - NavMesh *owner; }; - struct Connection { Polygon *A; @@ -111,11 +109,15 @@ class Navigation : public Spatial { List pending; - Connection() { A=NULL; B=NULL; A_edge=-1; B_edge=-1;} + Connection() { + A = NULL; + B = NULL; + A_edge = -1; + B_edge = -1; + } }; - Map connections; - + Map connections; struct NavMesh { @@ -124,62 +126,54 @@ class Navigation : public Spatial { bool linked; Ref navmesh; List polygons; - }; + _FORCE_INLINE_ Point _get_point(const Vector3 &p_pos) const { - - _FORCE_INLINE_ Point _get_point(const Vector3& p_pos) const { - - int x = int(Math::floor(p_pos.x/cell_size)); - int y = int(Math::floor(p_pos.y/cell_size)); - int z = int(Math::floor(p_pos.z/cell_size)); + int x = int(Math::floor(p_pos.x / cell_size)); + int y = int(Math::floor(p_pos.y / cell_size)); + int z = int(Math::floor(p_pos.z / cell_size)); Point p; - p.key=0; - p.x=x; - p.y=y; - p.z=z; + p.key = 0; + p.x = x; + p.y = y; + p.z = z; return p; - } - _FORCE_INLINE_ Vector3 _get_vertex(const Point& p_point) const { + _FORCE_INLINE_ Vector3 _get_vertex(const Point &p_point) const { - return Vector3(p_point.x,p_point.y,p_point.z)*cell_size; + return Vector3(p_point.x, p_point.y, p_point.z) * cell_size; } - - void _navmesh_link(int p_id); void _navmesh_unlink(int p_id); float cell_size; - Map navmesh_map; + Map navmesh_map; int last_id; Vector3 up; - void _clip_path(Vector& path,Polygon *from_poly, const Vector3& p_to_point, Polygon* p_to_poly); + void _clip_path(Vector &path, Polygon *from_poly, const Vector3 &p_to_point, Polygon *p_to_poly); protected: - static void _bind_methods(); public: - - void set_up_vector(const Vector3& p_up); + void set_up_vector(const Vector3 &p_up); Vector3 get_up_vector() const; //API should be as dynamic as possible - int navmesh_create(const Ref& p_mesh,const Transform& p_xform,Object* p_owner=NULL); - void navmesh_set_transform(int p_id, const Transform& p_xform); + int navmesh_create(const Ref &p_mesh, const Transform &p_xform, Object *p_owner = NULL); + void navmesh_set_transform(int p_id, const Transform &p_xform); void navmesh_remove(int p_id); - Vector get_simple_path(const Vector3& p_start, const Vector3& p_end,bool p_optimize=true); - Vector3 get_closest_point_to_segment(const Vector3& p_from,const Vector3& p_to,const bool& p_use_collision=false); - Vector3 get_closest_point(const Vector3& p_point); - Vector3 get_closest_point_normal(const Vector3& p_point); - Object* get_closest_point_owner(const Vector3& p_point); + Vector get_simple_path(const Vector3 &p_start, const Vector3 &p_end, bool p_optimize = true); + Vector3 get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool &p_use_collision = false); + Vector3 get_closest_point(const Vector3 &p_point); + Vector3 get_closest_point_normal(const Vector3 &p_point); + Object *get_closest_point_owner(const Vector3 &p_point); Navigation(); }; diff --git a/scene/3d/navigation_mesh.cpp b/scene/3d/navigation_mesh.cpp index 8efb9bb33..1059a9b97 100644 --- a/scene/3d/navigation_mesh.cpp +++ b/scene/3d/navigation_mesh.cpp @@ -27,23 +27,22 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "navigation_mesh.h" -#include "navigation.h" #include "mesh_instance.h" +#include "navigation.h" -void NavigationMesh::create_from_mesh(const Ref& p_mesh) { - +void NavigationMesh::create_from_mesh(const Ref &p_mesh) { - vertices=PoolVector(); + vertices = PoolVector(); clear_polygons(); - for(int i=0;iget_surface_count();i++) { + for (int i = 0; i < p_mesh->get_surface_count(); i++) { - if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES) + if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) continue; Array arr = p_mesh->surface_get_arrays(i); PoolVector varr = arr[Mesh::ARRAY_VERTEX]; PoolVector iarr = arr[Mesh::ARRAY_INDEX]; - if (varr.size()==0 || iarr.size()==0) + if (varr.size() == 0 || iarr.size() == 0) continue; int from = vertices.size(); @@ -51,34 +50,33 @@ void NavigationMesh::create_from_mesh(const Ref& p_mesh) { int rlen = iarr.size(); PoolVector::Read r = iarr.read(); - for(int j=0;j vi; vi.resize(3); - vi[0]=r[j+0]+from; - vi[1]=r[j+1]+from; - vi[2]=r[j+2]+from; + vi[0] = r[j + 0] + from; + vi[1] = r[j + 1] + from; + vi[2] = r[j + 2] + from; add_polygon(vi); } } } -void NavigationMesh::set_vertices(const PoolVector& p_vertices) { +void NavigationMesh::set_vertices(const PoolVector &p_vertices) { - vertices=p_vertices; + vertices = p_vertices; } -PoolVector NavigationMesh::get_vertices() const{ +PoolVector NavigationMesh::get_vertices() const { return vertices; } - -void NavigationMesh::_set_polygons(const Array& p_array) { +void NavigationMesh::_set_polygons(const Array &p_array) { polygons.resize(p_array.size()); - for(int i=0;i& p_polygon){ +void NavigationMesh::add_polygon(const Vector &p_polygon) { Polygon polygon; - polygon.indices=p_polygon; + polygon.indices = p_polygon; polygons.push_back(polygon); - } -int NavigationMesh::get_polygon_count() const{ +int NavigationMesh::get_polygon_count() const { return polygons.size(); } -Vector NavigationMesh::get_polygon(int p_idx){ +Vector NavigationMesh::get_polygon(int p_idx) { - ERR_FAIL_INDEX_V(p_idx,polygons.size(),Vector()); + ERR_FAIL_INDEX_V(p_idx, polygons.size(), Vector()); return polygons[p_idx].indices; } -void NavigationMesh::clear_polygons(){ +void NavigationMesh::clear_polygons() { polygons.clear(); } @@ -120,64 +116,59 @@ Ref NavigationMesh::get_debug_mesh() { if (debug_mesh.is_valid()) return debug_mesh; - - PoolVector vertices = get_vertices(); - PoolVector::Read vr=vertices.read(); + PoolVector::Read vr = vertices.read(); List faces; - for(int i=0;i p = get_polygon(i); - for(int j=2;j edge_map; + Map<_EdgeKey, bool> edge_map; PoolVector tmeshfaces; - tmeshfaces.resize(faces.size()*3); + tmeshfaces.resize(faces.size() * 3); { - PoolVector::Write tw=tmeshfaces.write(); - int tidx=0; - + PoolVector::Write tw = tmeshfaces.write(); + int tidx = 0; - for(List::Element *E=faces.front();E;E=E->next()) { + for (List::Element *E = faces.front(); E; E = E->next()) { const Face3 &f = E->get(); - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - tw[tidx++]=f.vertex[j]; + tw[tidx++] = f.vertex[j]; _EdgeKey ek; - ek.from=f.vertex[j].snapped(CMP_EPSILON); - ek.to=f.vertex[(j+1)%3].snapped(CMP_EPSILON); - if (ek.from::Element *E=edge_map.find(ek); + Map<_EdgeKey, bool>::Element *E = edge_map.find(ek); if (E) { - E->get()=false; + E->get() = false; } else { - edge_map[ek]=true; + edge_map[ek] = true; } - } } } List lines; - for(Map<_EdgeKey,bool>::Element *E=edge_map.front();E;E=E->next()) { + for (Map<_EdgeKey, bool>::Element *E = edge_map.front(); E; E = E->next()) { if (E->get()) { lines.push_back(E->key().from); @@ -189,58 +180,57 @@ Ref NavigationMesh::get_debug_mesh() { varr.resize(lines.size()); { PoolVector::Write w = varr.write(); - int idx=0; - for(List::Element *E=lines.front();E;E=E->next()) { - w[idx++]=E->get(); + int idx = 0; + for (List::Element *E = lines.front(); E; E = E->next()) { + w[idx++] = E->get(); } } - debug_mesh = Ref( memnew( Mesh ) ); + debug_mesh = Ref(memnew(Mesh)); Array arr; arr.resize(Mesh::ARRAY_MAX); - arr[Mesh::ARRAY_VERTEX]=varr; + arr[Mesh::ARRAY_VERTEX] = varr; - debug_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES,arr); + debug_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, arr); return debug_mesh; } void NavigationMesh::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_vertices","vertices"),&NavigationMesh::set_vertices); - ClassDB::bind_method(D_METHOD("get_vertices"),&NavigationMesh::get_vertices); + ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &NavigationMesh::set_vertices); + ClassDB::bind_method(D_METHOD("get_vertices"), &NavigationMesh::get_vertices); - ClassDB::bind_method(D_METHOD("add_polygon","polygon"),&NavigationMesh::add_polygon); - ClassDB::bind_method(D_METHOD("get_polygon_count"),&NavigationMesh::get_polygon_count); - ClassDB::bind_method(D_METHOD("get_polygon","idx"),&NavigationMesh::get_polygon); - ClassDB::bind_method(D_METHOD("clear_polygons"),&NavigationMesh::clear_polygons); + ClassDB::bind_method(D_METHOD("add_polygon", "polygon"), &NavigationMesh::add_polygon); + ClassDB::bind_method(D_METHOD("get_polygon_count"), &NavigationMesh::get_polygon_count); + ClassDB::bind_method(D_METHOD("get_polygon", "idx"), &NavigationMesh::get_polygon); + ClassDB::bind_method(D_METHOD("clear_polygons"), &NavigationMesh::clear_polygons); - ClassDB::bind_method(D_METHOD("_set_polygons","polygons"),&NavigationMesh::_set_polygons); - ClassDB::bind_method(D_METHOD("_get_polygons"),&NavigationMesh::_get_polygons); + ClassDB::bind_method(D_METHOD("_set_polygons", "polygons"), &NavigationMesh::_set_polygons); + ClassDB::bind_method(D_METHOD("_get_polygons"), &NavigationMesh::_get_polygons); - ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY,"vertices",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_vertices","get_vertices"); - ADD_PROPERTY(PropertyInfo(Variant::ARRAY,"polygons",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_polygons","_get_polygons"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_vertices", "get_vertices"); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "polygons", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_polygons", "_get_polygons"); } NavigationMesh::NavigationMesh() { - } void NavigationMeshInstance::set_enabled(bool p_enabled) { - if (enabled==p_enabled) + if (enabled == p_enabled) return; - enabled=p_enabled; + enabled = p_enabled; if (!is_inside_tree()) return; if (!enabled) { - if (nav_id!=-1) { + if (nav_id != -1) { navigation->navmesh_remove(nav_id); - nav_id=-1; + nav_id = -1; } } else { @@ -248,20 +238,18 @@ void NavigationMeshInstance::set_enabled(bool p_enabled) { if (navmesh.is_valid()) { - nav_id = navigation->navmesh_create(navmesh,get_relative_transform(navigation),this); + nav_id = navigation->navmesh_create(navmesh, get_relative_transform(navigation), this); } } - } if (debug_view) { - MeshInstance *dm=debug_view->cast_to(); + MeshInstance *dm = debug_view->cast_to(); if (is_enabled()) { - dm->set_material_override( get_tree()->get_debug_navigation_material() ); + dm->set_material_override(get_tree()->get_debug_navigation_material()); } else { - dm->set_material_override( get_tree()->get_debug_navigation_disabled_material() ); + dm->set_material_override(get_tree()->get_debug_navigation_disabled_material()); } - } update_gizmo(); @@ -269,104 +257,96 @@ void NavigationMeshInstance::set_enabled(bool p_enabled) { bool NavigationMeshInstance::is_enabled() const { - return enabled; } - ///////////////////////////// - void NavigationMeshInstance::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - Spatial *c=this; - while(c) { + Spatial *c = this; + while (c) { - navigation=c->cast_to(); + navigation = c->cast_to(); if (navigation) { if (enabled && navmesh.is_valid()) { - nav_id = navigation->navmesh_create(navmesh,get_relative_transform(navigation),this); + nav_id = navigation->navmesh_create(navmesh, get_relative_transform(navigation), this); } break; } - c=c->get_parent_spatial(); + c = c->get_parent_spatial(); } if (navmesh.is_valid() && get_tree()->is_debugging_navigation_hint()) { - MeshInstance *dm = memnew( MeshInstance ); - dm->set_mesh( navmesh->get_debug_mesh() ); + MeshInstance *dm = memnew(MeshInstance); + dm->set_mesh(navmesh->get_debug_mesh()); if (is_enabled()) { - dm->set_material_override( get_tree()->get_debug_navigation_material() ); + dm->set_material_override(get_tree()->get_debug_navigation_material()); } else { - dm->set_material_override( get_tree()->get_debug_navigation_disabled_material() ); + dm->set_material_override(get_tree()->get_debug_navigation_disabled_material()); } add_child(dm); - debug_view=dm; + debug_view = dm; } } break; case NOTIFICATION_TRANSFORM_CHANGED: { - if (navigation && nav_id!=-1) { - navigation->navmesh_set_transform(nav_id,get_relative_transform(navigation)); + if (navigation && nav_id != -1) { + navigation->navmesh_set_transform(nav_id, get_relative_transform(navigation)); } - - } break; case NOTIFICATION_EXIT_TREE: { if (navigation) { - if (nav_id!=-1) { + if (nav_id != -1) { navigation->navmesh_remove(nav_id); - nav_id=-1; + nav_id = -1; } } if (debug_view) { debug_view->queue_delete(); - debug_view=NULL; + debug_view = NULL; } - navigation=NULL; + navigation = NULL; } break; } } +void NavigationMeshInstance::set_navigation_mesh(const Ref &p_navmesh) { -void NavigationMeshInstance::set_navigation_mesh(const Ref& p_navmesh) { - - if (p_navmesh==navmesh) + if (p_navmesh == navmesh) return; - if (navigation && nav_id!=-1) { + if (navigation && nav_id != -1) { navigation->navmesh_remove(nav_id); - nav_id=-1; + nav_id = -1; } - navmesh=p_navmesh; + navmesh = p_navmesh; if (navigation && navmesh.is_valid() && enabled) { - nav_id = navigation->navmesh_create(navmesh,get_relative_transform(navigation),this); + nav_id = navigation->navmesh_create(navmesh, get_relative_transform(navigation), this); } - + if (debug_view && navmesh.is_valid()) { - debug_view->cast_to()->set_mesh( navmesh->get_debug_mesh() ); + debug_view->cast_to()->set_mesh(navmesh->get_debug_mesh()); } - + update_gizmo(); update_configuration_warning(); - } -Ref NavigationMeshInstance::get_navigation_mesh() const{ +Ref NavigationMeshInstance::get_navigation_mesh() const { return navmesh; } @@ -379,37 +359,35 @@ String NavigationMeshInstance::get_configuration_warning() const { if (!navmesh.is_valid()) { return TTR("A NavigationMesh resource must be set or created for this node to work."); } - const Spatial *c=this; - while(c) { + const Spatial *c = this; + while (c) { if (c->cast_to()) return String(); - c=c->get_parent()->cast_to(); + c = c->get_parent()->cast_to(); } return TTR("NavigationMeshInstance must be a child or grandchild to a Navigation node. It only provides navigation data."); } - void NavigationMeshInstance::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_navigation_mesh","navmesh"),&NavigationMeshInstance::set_navigation_mesh); - ClassDB::bind_method(D_METHOD("get_navigation_mesh"),&NavigationMeshInstance::get_navigation_mesh); + ClassDB::bind_method(D_METHOD("set_navigation_mesh", "navmesh"), &NavigationMeshInstance::set_navigation_mesh); + ClassDB::bind_method(D_METHOD("get_navigation_mesh"), &NavigationMeshInstance::get_navigation_mesh); - ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&NavigationMeshInstance::set_enabled); - ClassDB::bind_method(D_METHOD("is_enabled"),&NavigationMeshInstance::is_enabled); + ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationMeshInstance::set_enabled); + ClassDB::bind_method(D_METHOD("is_enabled"), &NavigationMeshInstance::is_enabled); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"navmesh",PROPERTY_HINT_RESOURCE_TYPE,"NavigationMesh"),"set_navigation_mesh","get_navigation_mesh"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navmesh", PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"), "set_navigation_mesh", "get_navigation_mesh"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); } NavigationMeshInstance::NavigationMeshInstance() { - debug_view=NULL; - navigation=NULL; - nav_id=-1; - enabled=true; + debug_view = NULL; + navigation = NULL; + nav_id = -1; + enabled = true; set_notify_transform(true); - } diff --git a/scene/3d/navigation_mesh.h b/scene/3d/navigation_mesh.h index e025b7ce8..fda892378 100644 --- a/scene/3d/navigation_mesh.h +++ b/scene/3d/navigation_mesh.h @@ -34,9 +34,9 @@ class Mesh; -class NavigationMesh : public Resource { +class NavigationMesh : public Resource { - GDCLASS( NavigationMesh, Resource ); + GDCLASS(NavigationMesh, Resource); PoolVector vertices; struct Polygon { @@ -50,25 +50,22 @@ class NavigationMesh : public Resource { Vector3 from; Vector3 to; - bool operator<(const _EdgeKey& p_with) const { return from==p_with.from ? to < p_with.to : from < p_with.from; } + bool operator<(const _EdgeKey &p_with) const { return from == p_with.from ? to < p_with.to : from < p_with.from; } }; - protected: - static void _bind_methods(); - void _set_polygons(const Array& p_array); + void _set_polygons(const Array &p_array); Array _get_polygons() const; public: + void create_from_mesh(const Ref &p_mesh); - void create_from_mesh(const Ref& p_mesh); - - void set_vertices(const PoolVector& p_vertices); + void set_vertices(const PoolVector &p_vertices); PoolVector get_vertices() const; - void add_polygon(const Vector& p_polygon); + void add_polygon(const Vector &p_polygon); int get_polygon_count() const; Vector get_polygon(int p_idx); void clear_polygons(); @@ -78,12 +75,11 @@ public: NavigationMesh(); }; - class Navigation; class NavigationMeshInstance : public Spatial { - GDCLASS(NavigationMeshInstance,Spatial); + GDCLASS(NavigationMeshInstance, Spatial); bool enabled; int nav_id; @@ -93,17 +89,14 @@ class NavigationMeshInstance : public Spatial { Node *debug_view; protected: - void _notification(int p_what); static void _bind_methods(); -public: - - +public: void set_enabled(bool p_enabled); bool is_enabled() const; - void set_navigation_mesh(const Ref& p_navmesh); + void set_navigation_mesh(const Ref &p_navmesh); Ref get_navigation_mesh() const; String get_configuration_warning() const; @@ -111,5 +104,4 @@ public: NavigationMeshInstance(); }; - #endif // NAVIGATION_MESH_H diff --git a/scene/3d/particles.cpp b/scene/3d/particles.cpp index 0e0c1e9dc..ea61253ac 100644 --- a/scene/3d/particles.cpp +++ b/scene/3d/particles.cpp @@ -27,8 +27,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "particles.h" -#include "servers/visual_server.h" #include "scene/resources/surface_tool.h" +#include "servers/visual_server.h" #if 0 /* diff --git a/scene/3d/particles.h b/scene/3d/particles.h index b96bd4e69..6cb1caad3 100644 --- a/scene/3d/particles.h +++ b/scene/3d/particles.h @@ -29,10 +29,10 @@ #ifndef VISUALINSTANCEPARTICLES_H #define VISUALINSTANCEPARTICLES_H +#include "rid.h" #include "scene/3d/visual_instance.h" -#include "scene/resources/material.h" #include "scene/main/timer.h" -#include "rid.h" +#include "scene/resources/material.h" /** @author Juan Linietsky diff --git a/scene/3d/path.cpp b/scene/3d/path.cpp index ead150e40..457e9e555 100644 --- a/scene/3d/path.cpp +++ b/scene/3d/path.cpp @@ -52,119 +52,108 @@ void Path::_notification(int p_what) { void Path::_curve_changed() { - if (is_inside_tree() && get_tree()->is_editor_hint()) update_gizmo(); } - -void Path::set_curve(const Ref& p_curve) { +void Path::set_curve(const Ref &p_curve) { if (curve.is_valid()) { - curve->disconnect("changed",this,"_curve_changed"); + curve->disconnect("changed", this, "_curve_changed"); } - curve=p_curve; + curve = p_curve; if (curve.is_valid()) { - curve->connect("changed",this,"_curve_changed"); + curve->connect("changed", this, "_curve_changed"); } _curve_changed(); - } -Ref Path::get_curve() const{ +Ref Path::get_curve() const { return curve; } void Path::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_curve","curve:Curve3D"),&Path::set_curve); - ClassDB::bind_method(D_METHOD("get_curve:Curve3D","curve"),&Path::get_curve); - ClassDB::bind_method(D_METHOD("_curve_changed"),&Path::_curve_changed); + ClassDB::bind_method(D_METHOD("set_curve", "curve:Curve3D"), &Path::set_curve); + ClassDB::bind_method(D_METHOD("get_curve:Curve3D", "curve"), &Path::get_curve); + ClassDB::bind_method(D_METHOD("_curve_changed"), &Path::_curve_changed); - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve3D"), "set_curve","get_curve"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve3D"), "set_curve", "get_curve"); } Path::Path() { - set_curve(Ref( memnew( Curve3D ))); //create one by default + set_curve(Ref(memnew(Curve3D))); //create one by default } - ////////////// - void PathFollow::_update_transform() { - if (!path) return; - Ref c =path->get_curve(); + Ref c = path->get_curve(); if (!c.is_valid()) return; - float o = offset; if (loop) - o=Math::fposmod(o,c->get_baked_length()); - - Vector3 pos = c->interpolate_baked(o,cubic); - Transform t=get_transform(); + o = Math::fposmod(o, c->get_baked_length()); + Vector3 pos = c->interpolate_baked(o, cubic); + Transform t = get_transform(); - if (rotation_mode!=ROTATION_NONE) { + if (rotation_mode != ROTATION_NONE) { - Vector3 n = (c->interpolate_baked(o+lookahead,cubic)-pos).normalized(); + Vector3 n = (c->interpolate_baked(o + lookahead, cubic) - pos).normalized(); - if (rotation_mode==ROTATION_Y) { + if (rotation_mode == ROTATION_Y) { - n.y=0; + n.y = 0; n.normalize(); } - if (n.length()interpolate_baked_tilt(o); - if (tilt!=0) { + if (tilt != 0) { - Basis rot(-n,tilt); //remember.. lookat will be znegative.. znegative!! we abide by opengl clan. - up=rot.xform(up); + Basis rot(-n, tilt); //remember.. lookat will be znegative.. znegative!! we abide by opengl clan. + up = rot.xform(up); } } - t.set_look_at(pos,pos+n,up); + t.set_look_at(pos, pos + n, up); } else { - t.origin=pos; + t.origin = pos; } - t.origin+=t.basis.get_axis(0)*h_offset + t.basis.get_axis(1)*v_offset; + t.origin += t.basis.get_axis(0) * h_offset + t.basis.get_axis(1) * v_offset; set_transform(t); - } void PathFollow::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { - Node *parent=get_parent(); + Node *parent = get_parent(); if (parent) { - path=parent->cast_to(); + path = parent->cast_to(); if (path) { _update_transform(); } @@ -173,16 +162,14 @@ void PathFollow::_notification(int p_what) { } break; case NOTIFICATION_EXIT_TREE: { - - path=NULL; + path = NULL; } break; } - } void PathFollow::set_cubic_interpolation(bool p_enable) { - cubic=p_enable; + cubic = p_enable; } bool PathFollow::get_cubic_interpolation() const { @@ -190,24 +177,23 @@ bool PathFollow::get_cubic_interpolation() const { return cubic; } +bool PathFollow::_set(const StringName &p_name, const Variant &p_value) { -bool PathFollow::_set(const StringName& p_name, const Variant& p_value) { - - if (p_name==SceneStringNames::get_singleton()->offset) { + if (p_name == SceneStringNames::get_singleton()->offset) { set_offset(p_value); - } else if (p_name==SceneStringNames::get_singleton()->unit_offset) { + } else if (p_name == SceneStringNames::get_singleton()->unit_offset) { set_unit_offset(p_value); - } else if (p_name==SceneStringNames::get_singleton()->rotation_mode) { + } else if (p_name == SceneStringNames::get_singleton()->rotation_mode) { set_rotation_mode(RotationMode(p_value.operator int())); - } else if (p_name==SceneStringNames::get_singleton()->v_offset) { + } else if (p_name == SceneStringNames::get_singleton()->v_offset) { set_v_offset(p_value); - } else if (p_name==SceneStringNames::get_singleton()->h_offset) { + } else if (p_name == SceneStringNames::get_singleton()->h_offset) { set_h_offset(p_value); - } else if (String(p_name)=="cubic_interp") { + } else if (String(p_name) == "cubic_interp") { set_cubic_interpolation(p_value); - } else if (String(p_name)=="loop") { + } else if (String(p_name) == "loop") { set_loop(p_value); - } else if (String(p_name)=="lookahead") { + } else if (String(p_name) == "lookahead") { set_lookahead(p_value); } else return false; @@ -215,92 +201,87 @@ bool PathFollow::_set(const StringName& p_name, const Variant& p_value) { return true; } -bool PathFollow::_get(const StringName& p_name,Variant &r_ret) const{ - - if (p_name==SceneStringNames::get_singleton()->offset) { - r_ret=get_offset(); - } else if (p_name==SceneStringNames::get_singleton()->unit_offset) { - r_ret=get_unit_offset(); - } else if (p_name==SceneStringNames::get_singleton()->rotation_mode) { - r_ret=get_rotation_mode(); - } else if (p_name==SceneStringNames::get_singleton()->v_offset) { - r_ret=get_v_offset(); - } else if (p_name==SceneStringNames::get_singleton()->h_offset) { - r_ret=get_h_offset(); - } else if (String(p_name)=="cubic_interp") { - r_ret=cubic; - } else if (String(p_name)=="loop") { - r_ret=loop; - } else if (String(p_name)=="lookahead") { - r_ret=lookahead; +bool PathFollow::_get(const StringName &p_name, Variant &r_ret) const { + + if (p_name == SceneStringNames::get_singleton()->offset) { + r_ret = get_offset(); + } else if (p_name == SceneStringNames::get_singleton()->unit_offset) { + r_ret = get_unit_offset(); + } else if (p_name == SceneStringNames::get_singleton()->rotation_mode) { + r_ret = get_rotation_mode(); + } else if (p_name == SceneStringNames::get_singleton()->v_offset) { + r_ret = get_v_offset(); + } else if (p_name == SceneStringNames::get_singleton()->h_offset) { + r_ret = get_h_offset(); + } else if (String(p_name) == "cubic_interp") { + r_ret = cubic; + } else if (String(p_name) == "loop") { + r_ret = loop; + } else if (String(p_name) == "lookahead") { + r_ret = lookahead; } else return false; return true; - } -void PathFollow::_get_property_list( List *p_list) const{ +void PathFollow::_get_property_list(List *p_list) const { - float max=10000; + float max = 10000; if (path && path->get_curve().is_valid()) - max=path->get_curve()->get_baked_length(); - p_list->push_back( PropertyInfo( Variant::REAL, "offset", PROPERTY_HINT_RANGE,"0,"+rtos(max)+",0.01")); - p_list->push_back( PropertyInfo( Variant::REAL, "unit_offset", PROPERTY_HINT_RANGE,"0,1,0.0001",PROPERTY_USAGE_EDITOR)); - p_list->push_back( PropertyInfo( Variant::REAL, "h_offset") ); - p_list->push_back( PropertyInfo( Variant::REAL, "v_offset") ); - p_list->push_back( PropertyInfo( Variant::INT, "rotation_mode", PROPERTY_HINT_ENUM,"None,Y,XY,XYZ")); - p_list->push_back( PropertyInfo( Variant::BOOL, "cubic_interp")); - p_list->push_back( PropertyInfo( Variant::BOOL, "loop")); - p_list->push_back( PropertyInfo( Variant::REAL, "lookahead",PROPERTY_HINT_RANGE,"0.001,1024.0,0.001")); + max = path->get_curve()->get_baked_length(); + p_list->push_back(PropertyInfo(Variant::REAL, "offset", PROPERTY_HINT_RANGE, "0," + rtos(max) + ",0.01")); + p_list->push_back(PropertyInfo(Variant::REAL, "unit_offset", PROPERTY_HINT_RANGE, "0,1,0.0001", PROPERTY_USAGE_EDITOR)); + p_list->push_back(PropertyInfo(Variant::REAL, "h_offset")); + p_list->push_back(PropertyInfo(Variant::REAL, "v_offset")); + p_list->push_back(PropertyInfo(Variant::INT, "rotation_mode", PROPERTY_HINT_ENUM, "None,Y,XY,XYZ")); + p_list->push_back(PropertyInfo(Variant::BOOL, "cubic_interp")); + p_list->push_back(PropertyInfo(Variant::BOOL, "loop")); + p_list->push_back(PropertyInfo(Variant::REAL, "lookahead", PROPERTY_HINT_RANGE, "0.001,1024.0,0.001")); } - void PathFollow::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_offset","offset"),&PathFollow::set_offset); - ClassDB::bind_method(D_METHOD("get_offset"),&PathFollow::get_offset); - - ClassDB::bind_method(D_METHOD("set_h_offset","h_offset"),&PathFollow::set_h_offset); - ClassDB::bind_method(D_METHOD("get_h_offset"),&PathFollow::get_h_offset); + ClassDB::bind_method(D_METHOD("set_offset", "offset"), &PathFollow::set_offset); + ClassDB::bind_method(D_METHOD("get_offset"), &PathFollow::get_offset); - ClassDB::bind_method(D_METHOD("set_v_offset","v_offset"),&PathFollow::set_v_offset); - ClassDB::bind_method(D_METHOD("get_v_offset"),&PathFollow::get_v_offset); + ClassDB::bind_method(D_METHOD("set_h_offset", "h_offset"), &PathFollow::set_h_offset); + ClassDB::bind_method(D_METHOD("get_h_offset"), &PathFollow::get_h_offset); - ClassDB::bind_method(D_METHOD("set_unit_offset","unit_offset"),&PathFollow::set_unit_offset); - ClassDB::bind_method(D_METHOD("get_unit_offset"),&PathFollow::get_unit_offset); + ClassDB::bind_method(D_METHOD("set_v_offset", "v_offset"), &PathFollow::set_v_offset); + ClassDB::bind_method(D_METHOD("get_v_offset"), &PathFollow::get_v_offset); - ClassDB::bind_method(D_METHOD("set_rotation_mode","rotation_mode"),&PathFollow::set_rotation_mode); - ClassDB::bind_method(D_METHOD("get_rotation_mode"),&PathFollow::get_rotation_mode); + ClassDB::bind_method(D_METHOD("set_unit_offset", "unit_offset"), &PathFollow::set_unit_offset); + ClassDB::bind_method(D_METHOD("get_unit_offset"), &PathFollow::get_unit_offset); - ClassDB::bind_method(D_METHOD("set_cubic_interpolation","enable"),&PathFollow::set_cubic_interpolation); - ClassDB::bind_method(D_METHOD("get_cubic_interpolation"),&PathFollow::get_cubic_interpolation); + ClassDB::bind_method(D_METHOD("set_rotation_mode", "rotation_mode"), &PathFollow::set_rotation_mode); + ClassDB::bind_method(D_METHOD("get_rotation_mode"), &PathFollow::get_rotation_mode); - ClassDB::bind_method(D_METHOD("set_loop","loop"),&PathFollow::set_loop); - ClassDB::bind_method(D_METHOD("has_loop"),&PathFollow::has_loop); + ClassDB::bind_method(D_METHOD("set_cubic_interpolation", "enable"), &PathFollow::set_cubic_interpolation); + ClassDB::bind_method(D_METHOD("get_cubic_interpolation"), &PathFollow::get_cubic_interpolation); - BIND_CONSTANT( ROTATION_NONE ); - BIND_CONSTANT( ROTATION_Y ); - BIND_CONSTANT( ROTATION_XY ); - BIND_CONSTANT( ROTATION_XYZ ); + ClassDB::bind_method(D_METHOD("set_loop", "loop"), &PathFollow::set_loop); + ClassDB::bind_method(D_METHOD("has_loop"), &PathFollow::has_loop); + BIND_CONSTANT(ROTATION_NONE); + BIND_CONSTANT(ROTATION_Y); + BIND_CONSTANT(ROTATION_XY); + BIND_CONSTANT(ROTATION_XYZ); } void PathFollow::set_offset(float p_offset) { - offset=p_offset; + offset = p_offset; if (path) _update_transform(); _change_notify("offset"); _change_notify("unit_offset"); - } void PathFollow::set_h_offset(float p_h_offset) { - h_offset=p_h_offset; + h_offset = p_h_offset; if (path) _update_transform(); - } float PathFollow::get_h_offset() const { @@ -310,10 +291,9 @@ float PathFollow::get_h_offset() const { void PathFollow::set_v_offset(float p_v_offset) { - v_offset=p_v_offset; + v_offset = p_v_offset; if (path) _update_transform(); - } float PathFollow::get_v_offset() const { @@ -321,8 +301,7 @@ float PathFollow::get_v_offset() const { return v_offset; } - -float PathFollow::get_offset() const{ +float PathFollow::get_offset() const { return offset; } @@ -330,32 +309,30 @@ float PathFollow::get_offset() const{ void PathFollow::set_unit_offset(float p_unit_offset) { if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) - set_offset(p_unit_offset*path->get_curve()->get_baked_length()); - + set_offset(p_unit_offset * path->get_curve()->get_baked_length()); } -float PathFollow::get_unit_offset() const{ +float PathFollow::get_unit_offset() const { if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) - return get_offset()/path->get_curve()->get_baked_length(); + return get_offset() / path->get_curve()->get_baked_length(); else return 0; } void PathFollow::set_lookahead(float p_lookahead) { - lookahead=p_lookahead; - + lookahead = p_lookahead; } -float PathFollow::get_lookahead() const{ +float PathFollow::get_lookahead() const { return lookahead; } void PathFollow::set_rotation_mode(RotationMode p_rotation_mode) { - rotation_mode=p_rotation_mode; + rotation_mode = p_rotation_mode; _update_transform(); } @@ -366,23 +343,22 @@ PathFollow::RotationMode PathFollow::get_rotation_mode() const { void PathFollow::set_loop(bool p_loop) { - loop=p_loop; + loop = p_loop; } -bool PathFollow::has_loop() const{ +bool PathFollow::has_loop() const { return loop; } - PathFollow::PathFollow() { - offset=0; - h_offset=0; - v_offset=0; - path=NULL; - rotation_mode=ROTATION_XYZ; - cubic=true; - loop=true; - lookahead=0.1; + offset = 0; + h_offset = 0; + v_offset = 0; + path = NULL; + rotation_mode = ROTATION_XYZ; + cubic = true; + loop = true; + lookahead = 0.1; } diff --git a/scene/3d/path.h b/scene/3d/path.h index ab6f459ba..94227799e 100644 --- a/scene/3d/path.h +++ b/scene/3d/path.h @@ -29,36 +29,33 @@ #ifndef PATH_H #define PATH_H -#include "scene/resources/curve.h" #include "scene/3d/spatial.h" +#include "scene/resources/curve.h" class Path : public Spatial { - GDCLASS( Path, Spatial ); + GDCLASS(Path, Spatial); Ref curve; void _curve_changed(); - protected: - void _notification(int p_what); static void _bind_methods(); -public: - void set_curve(const Ref& p_curve); +public: + void set_curve(const Ref &p_curve); Ref get_curve() const; - Path(); }; class PathFollow : public Spatial { - GDCLASS(PathFollow,Spatial); -public: + GDCLASS(PathFollow, Spatial); +public: enum RotationMode { ROTATION_NONE, @@ -79,17 +76,15 @@ private: void _update_transform(); - protected: - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); -public: +public: void set_offset(float p_offset); float get_offset() const; diff --git a/scene/3d/physics_body.cpp b/scene/3d/physics_body.cpp index af514a171..78a00e4a7 100644 --- a/scene/3d/physics_body.cpp +++ b/scene/3d/physics_body.cpp @@ -31,7 +31,7 @@ void PhysicsBody::_notification(int p_what) { -/* + /* switch(p_what) { case NOTIFICATION_TRANSFORM_CHANGED: { @@ -57,11 +57,10 @@ float PhysicsBody::get_inverse_mass() const { return 0; } - void PhysicsBody::set_collision_layer(uint32_t p_mask) { - layer_mask=p_mask; - PhysicsServer::get_singleton()->body_set_layer_mask(get_rid(),p_mask); + layer_mask = p_mask; + PhysicsServer::get_singleton()->body_set_layer_mask(get_rid(), p_mask); } uint32_t PhysicsBody::get_collision_layer() const { @@ -71,8 +70,8 @@ uint32_t PhysicsBody::get_collision_layer() const { void PhysicsBody::set_collision_mask(uint32_t p_mask) { - collision_mask=p_mask; - PhysicsServer::get_singleton()->body_set_collision_mask(get_rid(),p_mask); + collision_mask = p_mask; + PhysicsServer::get_singleton()->body_set_collision_mask(get_rid(), p_mask); } uint32_t PhysicsBody::get_collision_mask() const { @@ -84,36 +83,33 @@ void PhysicsBody::set_collision_mask_bit(int p_bit, bool p_value) { uint32_t mask = get_collision_mask(); if (p_value) - mask|=1<cast_to(); @@ -121,11 +117,10 @@ void PhysicsBody::add_collision_exception_with(Node* p_node) { ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type"); } ERR_FAIL_COND(!physics_body); - PhysicsServer::get_singleton()->body_add_collision_exception(get_rid(),physics_body->get_rid()); - + PhysicsServer::get_singleton()->body_add_collision_exception(get_rid(), physics_body->get_rid()); } -void PhysicsBody::remove_collision_exception_with(Node* p_node) { +void PhysicsBody::remove_collision_exception_with(Node *p_node) { ERR_FAIL_NULL(p_node); PhysicsBody *physics_body = p_node->cast_to(); @@ -133,7 +128,7 @@ void PhysicsBody::remove_collision_exception_with(Node* p_node) { ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type"); } ERR_FAIL_COND(!physics_body); - PhysicsServer::get_singleton()->body_remove_collision_exception(get_rid(),physics_body->get_rid()); + PhysicsServer::get_singleton()->body_remove_collision_exception(get_rid(), physics_body->get_rid()); } void PhysicsBody::_set_layers(uint32_t p_mask) { @@ -141,80 +136,73 @@ void PhysicsBody::_set_layers(uint32_t p_mask) { set_collision_mask(p_mask); } -uint32_t PhysicsBody::_get_layers() const{ +uint32_t PhysicsBody::_get_layers() const { return get_collision_layer(); } void PhysicsBody::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_collision_layer","layer"),&PhysicsBody::set_collision_layer); - ClassDB::bind_method(D_METHOD("get_collision_layer"),&PhysicsBody::get_collision_layer); + ClassDB::bind_method(D_METHOD("set_collision_layer", "layer"), &PhysicsBody::set_collision_layer); + ClassDB::bind_method(D_METHOD("get_collision_layer"), &PhysicsBody::get_collision_layer); - ClassDB::bind_method(D_METHOD("set_collision_mask","mask"),&PhysicsBody::set_collision_mask); - ClassDB::bind_method(D_METHOD("get_collision_mask"),&PhysicsBody::get_collision_mask); + ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &PhysicsBody::set_collision_mask); + ClassDB::bind_method(D_METHOD("get_collision_mask"), &PhysicsBody::get_collision_mask); - ClassDB::bind_method(D_METHOD("set_collision_mask_bit","bit","value"),&PhysicsBody::set_collision_mask_bit); - ClassDB::bind_method(D_METHOD("get_collision_mask_bit","bit"),&PhysicsBody::get_collision_mask_bit); + ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &PhysicsBody::set_collision_mask_bit); + ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &PhysicsBody::get_collision_mask_bit); - ClassDB::bind_method(D_METHOD("set_collision_layer_bit","bit","value"),&PhysicsBody::set_collision_layer_bit); - ClassDB::bind_method(D_METHOD("get_collision_layer_bit","bit"),&PhysicsBody::get_collision_layer_bit); + ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &PhysicsBody::set_collision_layer_bit); + ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &PhysicsBody::get_collision_layer_bit); - ClassDB::bind_method(D_METHOD("_set_layers","mask"),&PhysicsBody::_set_layers); - ClassDB::bind_method(D_METHOD("_get_layers"),&PhysicsBody::_get_layers); + ClassDB::bind_method(D_METHOD("_set_layers", "mask"), &PhysicsBody::_set_layers); + ClassDB::bind_method(D_METHOD("_get_layers"), &PhysicsBody::_get_layers); - ADD_GROUP("Collision","collision_"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"collision_layer",PROPERTY_HINT_LAYERS_3D_PHYSICS),"set_collision_layer","get_collision_layer"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"collision_mask",PROPERTY_HINT_LAYERS_3D_PHYSICS),"set_collision_mask","get_collision_mask"); + ADD_GROUP("Collision", "collision_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask"); } +PhysicsBody::PhysicsBody(PhysicsServer::BodyMode p_mode) + : CollisionObject(PhysicsServer::get_singleton()->body_create(p_mode), false) { -PhysicsBody::PhysicsBody(PhysicsServer::BodyMode p_mode) : CollisionObject( PhysicsServer::get_singleton()->body_create(p_mode), false) { - - layer_mask=1; - collision_mask=1; - + layer_mask = 1; + collision_mask = 1; } +void StaticBody::set_friction(real_t p_friction) { -void StaticBody::set_friction(real_t p_friction){ - - ERR_FAIL_COND(p_friction<0 || p_friction>1); - - friction=p_friction; - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_FRICTION,friction); + ERR_FAIL_COND(p_friction < 0 || p_friction > 1); + friction = p_friction; + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, friction); } -real_t StaticBody::get_friction() const{ +real_t StaticBody::get_friction() const { return friction; } -void StaticBody::set_bounce(real_t p_bounce){ - - ERR_FAIL_COND(p_bounce<0 || p_bounce>1); +void StaticBody::set_bounce(real_t p_bounce) { - bounce=p_bounce; - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_BOUNCE,bounce); + ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1); + bounce = p_bounce; + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, bounce); } -real_t StaticBody::get_bounce() const{ +real_t StaticBody::get_bounce() const { return bounce; } +void StaticBody::set_constant_linear_velocity(const Vector3 &p_vel) { - -void StaticBody::set_constant_linear_velocity(const Vector3& p_vel) { - - constant_linear_velocity=p_vel; - PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_LINEAR_VELOCITY,constant_linear_velocity); - + constant_linear_velocity = p_vel; + PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_LINEAR_VELOCITY, constant_linear_velocity); } -void StaticBody::set_constant_angular_velocity(const Vector3& p_vel) { +void StaticBody::set_constant_angular_velocity(const Vector3 &p_vel) { - constant_angular_velocity=p_vel; - PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_ANGULAR_VELOCITY,constant_angular_velocity); + constant_angular_velocity = p_vel; + PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_ANGULAR_VELOCITY, constant_angular_velocity); } Vector3 StaticBody::get_constant_linear_velocity() const { @@ -226,69 +214,61 @@ Vector3 StaticBody::get_constant_angular_velocity() const { return constant_angular_velocity; } - - void StaticBody::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_constant_linear_velocity","vel"),&StaticBody::set_constant_linear_velocity); - ClassDB::bind_method(D_METHOD("set_constant_angular_velocity","vel"),&StaticBody::set_constant_angular_velocity); - ClassDB::bind_method(D_METHOD("get_constant_linear_velocity"),&StaticBody::get_constant_linear_velocity); - ClassDB::bind_method(D_METHOD("get_constant_angular_velocity"),&StaticBody::get_constant_angular_velocity); + ClassDB::bind_method(D_METHOD("set_constant_linear_velocity", "vel"), &StaticBody::set_constant_linear_velocity); + ClassDB::bind_method(D_METHOD("set_constant_angular_velocity", "vel"), &StaticBody::set_constant_angular_velocity); + ClassDB::bind_method(D_METHOD("get_constant_linear_velocity"), &StaticBody::get_constant_linear_velocity); + ClassDB::bind_method(D_METHOD("get_constant_angular_velocity"), &StaticBody::get_constant_angular_velocity); - ClassDB::bind_method(D_METHOD("set_friction","friction"),&StaticBody::set_friction); - ClassDB::bind_method(D_METHOD("get_friction"),&StaticBody::get_friction); + ClassDB::bind_method(D_METHOD("set_friction", "friction"), &StaticBody::set_friction); + ClassDB::bind_method(D_METHOD("get_friction"), &StaticBody::get_friction); - ClassDB::bind_method(D_METHOD("set_bounce","bounce"),&StaticBody::set_bounce); - ClassDB::bind_method(D_METHOD("get_bounce"),&StaticBody::get_bounce); + ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &StaticBody::set_bounce); + ClassDB::bind_method(D_METHOD("get_bounce"), &StaticBody::get_bounce); - ClassDB::bind_method(D_METHOD("add_collision_exception_with","body:PhysicsBody"),&PhysicsBody::add_collision_exception_with); - ClassDB::bind_method(D_METHOD("remove_collision_exception_with","body:PhysicsBody"),&PhysicsBody::remove_collision_exception_with); + ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body:PhysicsBody"), &PhysicsBody::add_collision_exception_with); + ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body:PhysicsBody"), &PhysicsBody::remove_collision_exception_with); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_friction","get_friction"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_bounce","get_bounce"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3,"constant_linear_velocity"),"set_constant_linear_velocity","get_constant_linear_velocity"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3,"constant_angular_velocity"),"set_constant_angular_velocity","get_constant_angular_velocity"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_linear_velocity"), "set_constant_linear_velocity", "get_constant_linear_velocity"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_angular_velocity"), "set_constant_angular_velocity", "get_constant_angular_velocity"); } -StaticBody::StaticBody() : PhysicsBody(PhysicsServer::BODY_MODE_STATIC) { +StaticBody::StaticBody() + : PhysicsBody(PhysicsServer::BODY_MODE_STATIC) { - bounce=0; - friction=1; + bounce = 0; + friction = 1; } StaticBody::~StaticBody() { - - } - - - void RigidBody::_body_enter_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=contact_monitor->body_map.find(p_id); + Map::Element *E = contact_monitor->body_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(E->get().in_tree); - E->get().in_tree=true; + E->get().in_tree = true; - contact_monitor->locked=true; + contact_monitor->locked = true; - emit_signal(SceneStringNames::get_singleton()->body_entered,node); + emit_signal(SceneStringNames::get_singleton()->body_entered, node); - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_entered,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].local_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_entered, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape); } - contact_monitor->locked=false; - - + contact_monitor->locked = false; } void RigidBody::_body_exit_tree(ObjectID p_id) { @@ -296,58 +276,55 @@ void RigidBody::_body_exit_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); Node *node = obj ? obj->cast_to() : NULL; ERR_FAIL_COND(!node); - Map::Element *E=contact_monitor->body_map.find(p_id); + Map::Element *E = contact_monitor->body_map.find(p_id); ERR_FAIL_COND(!E); ERR_FAIL_COND(!E->get().in_tree); - E->get().in_tree=false; + E->get().in_tree = false; - contact_monitor->locked=true; + contact_monitor->locked = true; - emit_signal(SceneStringNames::get_singleton()->body_exited,node); + emit_signal(SceneStringNames::get_singleton()->body_exited, node); - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].local_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape); } - contact_monitor->locked=false; - + contact_monitor->locked = false; } -void RigidBody::_body_inout(int p_status, ObjectID p_instance, int p_body_shape,int p_local_shape) { +void RigidBody::_body_inout(int p_status, ObjectID p_instance, int p_body_shape, int p_local_shape) { - bool body_in = p_status==1; - ObjectID objid=p_instance; + bool body_in = p_status == 1; + ObjectID objid = p_instance; Object *obj = ObjectDB::get_instance(objid); Node *node = obj ? obj->cast_to() : NULL; - Map::Element *E=contact_monitor->body_map.find(objid); + Map::Element *E = contact_monitor->body_map.find(objid); ERR_FAIL_COND(!body_in && !E); if (body_in) { if (!E) { - E = contact_monitor->body_map.insert(objid,BodyState()); + E = contact_monitor->body_map.insert(objid, BodyState()); //E->get().rc=0; - E->get().in_tree=node && node->is_inside_tree(); + E->get().in_tree = node && node->is_inside_tree(); if (node) { - node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree,make_binds(objid)); - node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree,make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree, make_binds(objid)); + node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree, make_binds(objid)); if (E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->body_entered,node); + emit_signal(SceneStringNames::get_singleton()->body_entered, node); } } - } //E->get().rc++; if (node) - E->get().shapes.insert(ShapePair(p_body_shape,p_local_shape)); - + E->get().shapes.insert(ShapePair(p_body_shape, p_local_shape)); if (E->get().in_tree) { - emit_signal(SceneStringNames::get_singleton()->body_shape_entered,objid,node,p_body_shape,p_local_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_entered, objid, node, p_body_shape, p_local_shape); } } else { @@ -355,31 +332,27 @@ void RigidBody::_body_inout(int p_status, ObjectID p_instance, int p_body_shape, //E->get().rc--; if (node) - E->get().shapes.erase(ShapePair(p_body_shape,p_local_shape)); + E->get().shapes.erase(ShapePair(p_body_shape, p_local_shape)); bool in_tree = E->get().in_tree; if (E->get().shapes.empty()) { if (node) { - node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree); - node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree); + node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree); if (in_tree) - emit_signal(SceneStringNames::get_singleton()->body_exited,obj); - + emit_signal(SceneStringNames::get_singleton()->body_exited, obj); } contact_monitor->body_map.erase(E); } if (node && in_tree) { - emit_signal(SceneStringNames::get_singleton()->body_shape_exited,objid,obj,p_body_shape,p_local_shape); + emit_signal(SceneStringNames::get_singleton()->body_shape_exited, objid, obj, p_body_shape, p_local_shape); } - } - } - struct _RigidBodyInOut { ObjectID id; @@ -389,49 +362,49 @@ struct _RigidBodyInOut { void RigidBody::_direct_state_changed(Object *p_state) { - //eh.. fuck +//eh.. fuck #ifdef DEBUG_ENABLED - state=p_state->cast_to(); + state = p_state->cast_to(); #else - state=(PhysicsDirectBodyState*)p_state; //trust it + state = (PhysicsDirectBodyState *)p_state; //trust it #endif set_ignore_transform_notification(true); set_global_transform(state->get_transform()); - linear_velocity=state->get_linear_velocity(); - angular_velocity=state->get_angular_velocity(); - if(sleeping!=state->is_sleeping()) { - sleeping=state->is_sleeping(); + linear_velocity = state->get_linear_velocity(); + angular_velocity = state->get_angular_velocity(); + if (sleeping != state->is_sleeping()) { + sleeping = state->is_sleeping(); emit_signal(SceneStringNames::get_singleton()->sleeping_state_changed); } if (get_script_instance()) - get_script_instance()->call("_integrate_forces",state); + get_script_instance()->call("_integrate_forces", state); set_ignore_transform_notification(false); if (contact_monitor) { - contact_monitor->locked=true; + contact_monitor->locked = true; //untag all - int rc=0; - for( Map::Element *E=contact_monitor->body_map.front();E;E=E->next()) { + int rc = 0; + for (Map::Element *E = contact_monitor->body_map.front(); E; E = E->next()) { - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { - E->get().shapes[i].tagged=false; + E->get().shapes[i].tagged = false; rc++; } } - _RigidBodyInOut *toadd=(_RigidBodyInOut*)alloca(state->get_contact_count()*sizeof(_RigidBodyInOut)); - int toadd_count=0;//state->get_contact_count(); - RigidBody_RemoveAction *toremove=(RigidBody_RemoveAction*)alloca(rc*sizeof(RigidBody_RemoveAction)); - int toremove_count=0; + _RigidBodyInOut *toadd = (_RigidBodyInOut *)alloca(state->get_contact_count() * sizeof(_RigidBodyInOut)); + int toadd_count = 0; //state->get_contact_count(); + RigidBody_RemoveAction *toremove = (RigidBody_RemoveAction *)alloca(rc * sizeof(RigidBody_RemoveAction)); + int toremove_count = 0; //put the ones to add - for(int i=0;iget_contact_count();i++) { + for (int i = 0; i < state->get_contact_count(); i++) { ObjectID obj = state->get_contact_collider_id(i); int local_shape = state->get_contact_local_shape(i); @@ -439,258 +412,239 @@ void RigidBody::_direct_state_changed(Object *p_state) { //bool found=false; - Map::Element *E=contact_monitor->body_map.find(obj); + Map::Element *E = contact_monitor->body_map.find(obj); if (!E) { - toadd[toadd_count].local_shape=local_shape; - toadd[toadd_count].id=obj; - toadd[toadd_count].shape=shape; + toadd[toadd_count].local_shape = local_shape; + toadd[toadd_count].id = obj; + toadd[toadd_count].shape = shape; toadd_count++; continue; } - ShapePair sp( shape,local_shape ); + ShapePair sp(shape, local_shape); int idx = E->get().shapes.find(sp); - if (idx==-1) { + if (idx == -1) { - toadd[toadd_count].local_shape=local_shape; - toadd[toadd_count].id=obj; - toadd[toadd_count].shape=shape; + toadd[toadd_count].local_shape = local_shape; + toadd[toadd_count].id = obj; + toadd[toadd_count].shape = shape; toadd_count++; continue; } - E->get().shapes[idx].tagged=true; + E->get().shapes[idx].tagged = true; } //put the ones to remove - for( Map::Element *E=contact_monitor->body_map.front();E;E=E->next()) { + for (Map::Element *E = contact_monitor->body_map.front(); E; E = E->next()) { - for(int i=0;iget().shapes.size();i++) { + for (int i = 0; i < E->get().shapes.size(); i++) { if (!E->get().shapes[i].tagged) { - toremove[toremove_count].body_id=E->key(); - toremove[toremove_count].pair=E->get().shapes[i]; + toremove[toremove_count].body_id = E->key(); + toremove[toremove_count].pair = E->get().shapes[i]; toremove_count++; } } } - //process remotions - for(int i=0;ilocked=false; - + contact_monitor->locked = false; } - - - state=NULL; + state = NULL; } void RigidBody::_notification(int p_what) { - - } void RigidBody::set_mode(Mode p_mode) { - mode=p_mode; - switch(p_mode) { + mode = p_mode; + switch (p_mode) { case MODE_RIGID: { - PhysicsServer::get_singleton()->body_set_mode(get_rid(),PhysicsServer::BODY_MODE_RIGID); + PhysicsServer::get_singleton()->body_set_mode(get_rid(), PhysicsServer::BODY_MODE_RIGID); } break; case MODE_STATIC: { - PhysicsServer::get_singleton()->body_set_mode(get_rid(),PhysicsServer::BODY_MODE_STATIC); + PhysicsServer::get_singleton()->body_set_mode(get_rid(), PhysicsServer::BODY_MODE_STATIC); } break; case MODE_CHARACTER: { - PhysicsServer::get_singleton()->body_set_mode(get_rid(),PhysicsServer::BODY_MODE_CHARACTER); + PhysicsServer::get_singleton()->body_set_mode(get_rid(), PhysicsServer::BODY_MODE_CHARACTER); } break; case MODE_KINEMATIC: { - PhysicsServer::get_singleton()->body_set_mode(get_rid(),PhysicsServer::BODY_MODE_KINEMATIC); + PhysicsServer::get_singleton()->body_set_mode(get_rid(), PhysicsServer::BODY_MODE_KINEMATIC); } break; - } } -RigidBody::Mode RigidBody::get_mode() const{ +RigidBody::Mode RigidBody::get_mode() const { return mode; } -void RigidBody::set_mass(real_t p_mass){ +void RigidBody::set_mass(real_t p_mass) { - ERR_FAIL_COND(p_mass<=0); - mass=p_mass; + ERR_FAIL_COND(p_mass <= 0); + mass = p_mass; _change_notify("mass"); _change_notify("weight"); - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_MASS,mass); - + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_MASS, mass); } -real_t RigidBody::get_mass() const{ +real_t RigidBody::get_mass() const { return mass; } -void RigidBody::set_weight(real_t p_weight){ +void RigidBody::set_weight(real_t p_weight) { - set_mass(p_weight/9.8); + set_mass(p_weight / 9.8); } -real_t RigidBody::get_weight() const{ +real_t RigidBody::get_weight() const { - return mass*9.8; + return mass * 9.8; } +void RigidBody::set_friction(real_t p_friction) { -void RigidBody::set_friction(real_t p_friction){ - - ERR_FAIL_COND(p_friction<0 || p_friction>1); - - friction=p_friction; - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_FRICTION,friction); + ERR_FAIL_COND(p_friction < 0 || p_friction > 1); + friction = p_friction; + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, friction); } -real_t RigidBody::get_friction() const{ +real_t RigidBody::get_friction() const { return friction; } -void RigidBody::set_bounce(real_t p_bounce){ +void RigidBody::set_bounce(real_t p_bounce) { - ERR_FAIL_COND(p_bounce<0 || p_bounce>1); - - bounce=p_bounce; - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_BOUNCE,bounce); + ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1); + bounce = p_bounce; + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, bounce); } -real_t RigidBody::get_bounce() const{ +real_t RigidBody::get_bounce() const { return bounce; } +void RigidBody::set_gravity_scale(real_t p_gravity_scale) { -void RigidBody::set_gravity_scale(real_t p_gravity_scale){ - - gravity_scale=p_gravity_scale; - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_GRAVITY_SCALE,gravity_scale); - + gravity_scale = p_gravity_scale; + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_GRAVITY_SCALE, gravity_scale); } -real_t RigidBody::get_gravity_scale() const{ +real_t RigidBody::get_gravity_scale() const { return gravity_scale; } -void RigidBody::set_linear_damp(real_t p_linear_damp){ - - ERR_FAIL_COND(p_linear_damp<-1); - linear_damp=p_linear_damp; - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_LINEAR_DAMP,linear_damp); +void RigidBody::set_linear_damp(real_t p_linear_damp) { + ERR_FAIL_COND(p_linear_damp < -1); + linear_damp = p_linear_damp; + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_LINEAR_DAMP, linear_damp); } -real_t RigidBody::get_linear_damp() const{ +real_t RigidBody::get_linear_damp() const { return linear_damp; } -void RigidBody::set_angular_damp(real_t p_angular_damp){ - - ERR_FAIL_COND(p_angular_damp<-1); - angular_damp=p_angular_damp; - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_ANGULAR_DAMP,angular_damp); +void RigidBody::set_angular_damp(real_t p_angular_damp) { + ERR_FAIL_COND(p_angular_damp < -1); + angular_damp = p_angular_damp; + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_ANGULAR_DAMP, angular_damp); } -real_t RigidBody::get_angular_damp() const{ +real_t RigidBody::get_angular_damp() const { return angular_damp; } -void RigidBody::set_axis_velocity(const Vector3& p_axis) { +void RigidBody::set_axis_velocity(const Vector3 &p_axis) { - Vector3 v = state? state->get_linear_velocity() : linear_velocity; + Vector3 v = state ? state->get_linear_velocity() : linear_velocity; Vector3 axis = p_axis.normalized(); - v-=axis*axis.dot(v); - v+=p_axis; + v -= axis * axis.dot(v); + v += p_axis; if (state) { set_linear_velocity(v); } else { - PhysicsServer::get_singleton()->body_set_axis_velocity(get_rid(),p_axis); - linear_velocity=v; + PhysicsServer::get_singleton()->body_set_axis_velocity(get_rid(), p_axis); + linear_velocity = v; } } -void RigidBody::set_linear_velocity(const Vector3& p_velocity){ +void RigidBody::set_linear_velocity(const Vector3 &p_velocity) { - linear_velocity=p_velocity; + linear_velocity = p_velocity; if (state) state->set_linear_velocity(linear_velocity); else - PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_LINEAR_VELOCITY,linear_velocity); - + PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_LINEAR_VELOCITY, linear_velocity); } -Vector3 RigidBody::get_linear_velocity() const{ +Vector3 RigidBody::get_linear_velocity() const { return linear_velocity; } -void RigidBody::set_angular_velocity(const Vector3& p_velocity){ +void RigidBody::set_angular_velocity(const Vector3 &p_velocity) { - angular_velocity=p_velocity; + angular_velocity = p_velocity; if (state) state->set_angular_velocity(angular_velocity); else - PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_ANGULAR_VELOCITY,angular_velocity); + PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_ANGULAR_VELOCITY, angular_velocity); } -Vector3 RigidBody::get_angular_velocity() const{ +Vector3 RigidBody::get_angular_velocity() const { return angular_velocity; } -void RigidBody::set_use_custom_integrator(bool p_enable){ +void RigidBody::set_use_custom_integrator(bool p_enable) { - if (custom_integrator==p_enable) + if (custom_integrator == p_enable) return; - custom_integrator=p_enable; - PhysicsServer::get_singleton()->body_set_omit_force_integration(get_rid(),p_enable); - - + custom_integrator = p_enable; + PhysicsServer::get_singleton()->body_set_omit_force_integration(get_rid(), p_enable); } -bool RigidBody::is_using_custom_integrator(){ +bool RigidBody::is_using_custom_integrator() { return custom_integrator; } void RigidBody::set_sleeping(bool p_sleeping) { - sleeping=p_sleeping; - PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_SLEEPING,sleeping); - + sleeping = p_sleeping; + PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_SLEEPING, sleeping); } void RigidBody::set_can_sleep(bool p_active) { - can_sleep=p_active; - PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_CAN_SLEEP,p_active); + can_sleep = p_active; + PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_CAN_SLEEP, p_active); } bool RigidBody::is_able_to_sleep() const { @@ -705,36 +659,34 @@ bool RigidBody::is_sleeping() const { void RigidBody::set_max_contacts_reported(int p_amount) { - max_contacts_reported=p_amount; - PhysicsServer::get_singleton()->body_set_max_contacts_reported(get_rid(),p_amount); + max_contacts_reported = p_amount; + PhysicsServer::get_singleton()->body_set_max_contacts_reported(get_rid(), p_amount); } -int RigidBody::get_max_contacts_reported() const{ +int RigidBody::get_max_contacts_reported() const { return max_contacts_reported; } -void RigidBody::apply_impulse(const Vector3& p_pos, const Vector3& p_impulse) { +void RigidBody::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) { - PhysicsServer::get_singleton()->body_apply_impulse(get_rid(),p_pos,p_impulse); + PhysicsServer::get_singleton()->body_apply_impulse(get_rid(), p_pos, p_impulse); } void RigidBody::set_use_continuous_collision_detection(bool p_enable) { - ccd=p_enable; - PhysicsServer::get_singleton()->body_set_enable_continuous_collision_detection(get_rid(),p_enable); + ccd = p_enable; + PhysicsServer::get_singleton()->body_set_enable_continuous_collision_detection(get_rid(), p_enable); } bool RigidBody::is_using_continuous_collision_detection() const { - return ccd; } - void RigidBody::set_contact_monitor(bool p_enabled) { - if (p_enabled==is_contact_monitor_enabled()) + if (p_enabled == is_contact_monitor_enabled()) return; if (!p_enabled) { @@ -744,31 +696,29 @@ void RigidBody::set_contact_monitor(bool p_enabled) { } ERR_FAIL_COND(contact_monitor->locked); - for(Map::Element *E=contact_monitor->body_map.front();E;E=E->next()) { + for (Map::Element *E = contact_monitor->body_map.front(); E; E = E->next()) { //clean up mess } - memdelete( contact_monitor ); - contact_monitor=NULL; + memdelete(contact_monitor); + contact_monitor = NULL; } else { - contact_monitor = memnew( ContactMonitor ); - contact_monitor->locked=false; - + contact_monitor = memnew(ContactMonitor); + contact_monitor->locked = false; } - } bool RigidBody::is_contact_monitor_enabled() const { - return contact_monitor!=NULL; + return contact_monitor != NULL; } void RigidBody::set_axis_lock(AxisLock p_lock) { - axis_lock=p_lock; - PhysicsServer::get_singleton()->body_set_axis_lock(get_rid(),PhysicsServer::BodyAxisLock(axis_lock)); + axis_lock = p_lock; + PhysicsServer::get_singleton()->body_set_axis_lock(get_rid(), PhysicsServer::BodyAxisLock(axis_lock)); } RigidBody::AxisLock RigidBody::get_axis_lock() const { @@ -776,168 +726,161 @@ RigidBody::AxisLock RigidBody::get_axis_lock() const { return axis_lock; } - Array RigidBody::get_colliding_bodies() const { - ERR_FAIL_COND_V(!contact_monitor,Array()); + ERR_FAIL_COND_V(!contact_monitor, Array()); Array ret; ret.resize(contact_monitor->body_map.size()); - int idx=0; - for (const Map::Element *E=contact_monitor->body_map.front();E;E=E->next()) { + int idx = 0; + for (const Map::Element *E = contact_monitor->body_map.front(); E; E = E->next()) { Object *obj = ObjectDB::get_instance(E->key()); if (!obj) { - ret.resize( ret.size() -1 ); //ops + ret.resize(ret.size() - 1); //ops } else { - ret[idx++]=obj; + ret[idx++] = obj; } - } return ret; } - void RigidBody::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_mode","mode"),&RigidBody::set_mode); - ClassDB::bind_method(D_METHOD("get_mode"),&RigidBody::get_mode); + ClassDB::bind_method(D_METHOD("set_mode", "mode"), &RigidBody::set_mode); + ClassDB::bind_method(D_METHOD("get_mode"), &RigidBody::get_mode); - ClassDB::bind_method(D_METHOD("set_mass","mass"),&RigidBody::set_mass); - ClassDB::bind_method(D_METHOD("get_mass"),&RigidBody::get_mass); + ClassDB::bind_method(D_METHOD("set_mass", "mass"), &RigidBody::set_mass); + ClassDB::bind_method(D_METHOD("get_mass"), &RigidBody::get_mass); - ClassDB::bind_method(D_METHOD("set_weight","weight"),&RigidBody::set_weight); - ClassDB::bind_method(D_METHOD("get_weight"),&RigidBody::get_weight); + ClassDB::bind_method(D_METHOD("set_weight", "weight"), &RigidBody::set_weight); + ClassDB::bind_method(D_METHOD("get_weight"), &RigidBody::get_weight); - ClassDB::bind_method(D_METHOD("set_friction","friction"),&RigidBody::set_friction); - ClassDB::bind_method(D_METHOD("get_friction"),&RigidBody::get_friction); + ClassDB::bind_method(D_METHOD("set_friction", "friction"), &RigidBody::set_friction); + ClassDB::bind_method(D_METHOD("get_friction"), &RigidBody::get_friction); - ClassDB::bind_method(D_METHOD("set_bounce","bounce"),&RigidBody::set_bounce); - ClassDB::bind_method(D_METHOD("get_bounce"),&RigidBody::get_bounce); + ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &RigidBody::set_bounce); + ClassDB::bind_method(D_METHOD("get_bounce"), &RigidBody::get_bounce); - ClassDB::bind_method(D_METHOD("set_linear_velocity","linear_velocity"),&RigidBody::set_linear_velocity); - ClassDB::bind_method(D_METHOD("get_linear_velocity"),&RigidBody::get_linear_velocity); + ClassDB::bind_method(D_METHOD("set_linear_velocity", "linear_velocity"), &RigidBody::set_linear_velocity); + ClassDB::bind_method(D_METHOD("get_linear_velocity"), &RigidBody::get_linear_velocity); - ClassDB::bind_method(D_METHOD("set_angular_velocity","angular_velocity"),&RigidBody::set_angular_velocity); - ClassDB::bind_method(D_METHOD("get_angular_velocity"),&RigidBody::get_angular_velocity); + ClassDB::bind_method(D_METHOD("set_angular_velocity", "angular_velocity"), &RigidBody::set_angular_velocity); + ClassDB::bind_method(D_METHOD("get_angular_velocity"), &RigidBody::get_angular_velocity); - ClassDB::bind_method(D_METHOD("set_gravity_scale","gravity_scale"),&RigidBody::set_gravity_scale); - ClassDB::bind_method(D_METHOD("get_gravity_scale"),&RigidBody::get_gravity_scale); + ClassDB::bind_method(D_METHOD("set_gravity_scale", "gravity_scale"), &RigidBody::set_gravity_scale); + ClassDB::bind_method(D_METHOD("get_gravity_scale"), &RigidBody::get_gravity_scale); - ClassDB::bind_method(D_METHOD("set_linear_damp","linear_damp"),&RigidBody::set_linear_damp); - ClassDB::bind_method(D_METHOD("get_linear_damp"),&RigidBody::get_linear_damp); + ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &RigidBody::set_linear_damp); + ClassDB::bind_method(D_METHOD("get_linear_damp"), &RigidBody::get_linear_damp); - ClassDB::bind_method(D_METHOD("set_angular_damp","angular_damp"),&RigidBody::set_angular_damp); - ClassDB::bind_method(D_METHOD("get_angular_damp"),&RigidBody::get_angular_damp); + ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &RigidBody::set_angular_damp); + ClassDB::bind_method(D_METHOD("get_angular_damp"), &RigidBody::get_angular_damp); + ClassDB::bind_method(D_METHOD("set_max_contacts_reported", "amount"), &RigidBody::set_max_contacts_reported); + ClassDB::bind_method(D_METHOD("get_max_contacts_reported"), &RigidBody::get_max_contacts_reported); - ClassDB::bind_method(D_METHOD("set_max_contacts_reported","amount"),&RigidBody::set_max_contacts_reported); - ClassDB::bind_method(D_METHOD("get_max_contacts_reported"),&RigidBody::get_max_contacts_reported); + ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &RigidBody::set_use_custom_integrator); + ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &RigidBody::is_using_custom_integrator); - ClassDB::bind_method(D_METHOD("set_use_custom_integrator","enable"),&RigidBody::set_use_custom_integrator); - ClassDB::bind_method(D_METHOD("is_using_custom_integrator"),&RigidBody::is_using_custom_integrator); + ClassDB::bind_method(D_METHOD("set_contact_monitor", "enabled"), &RigidBody::set_contact_monitor); + ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"), &RigidBody::is_contact_monitor_enabled); - ClassDB::bind_method(D_METHOD("set_contact_monitor","enabled"),&RigidBody::set_contact_monitor); - ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"),&RigidBody::is_contact_monitor_enabled); + ClassDB::bind_method(D_METHOD("set_use_continuous_collision_detection", "enable"), &RigidBody::set_use_continuous_collision_detection); + ClassDB::bind_method(D_METHOD("is_using_continuous_collision_detection"), &RigidBody::is_using_continuous_collision_detection); - ClassDB::bind_method(D_METHOD("set_use_continuous_collision_detection","enable"),&RigidBody::set_use_continuous_collision_detection); - ClassDB::bind_method(D_METHOD("is_using_continuous_collision_detection"),&RigidBody::is_using_continuous_collision_detection); + ClassDB::bind_method(D_METHOD("set_axis_velocity", "axis_velocity"), &RigidBody::set_axis_velocity); + ClassDB::bind_method(D_METHOD("apply_impulse", "pos", "impulse"), &RigidBody::apply_impulse); - ClassDB::bind_method(D_METHOD("set_axis_velocity","axis_velocity"),&RigidBody::set_axis_velocity); - ClassDB::bind_method(D_METHOD("apply_impulse","pos","impulse"),&RigidBody::apply_impulse); + ClassDB::bind_method(D_METHOD("set_sleeping", "sleeping"), &RigidBody::set_sleeping); + ClassDB::bind_method(D_METHOD("is_sleeping"), &RigidBody::is_sleeping); - ClassDB::bind_method(D_METHOD("set_sleeping","sleeping"),&RigidBody::set_sleeping); - ClassDB::bind_method(D_METHOD("is_sleeping"),&RigidBody::is_sleeping); + ClassDB::bind_method(D_METHOD("set_can_sleep", "able_to_sleep"), &RigidBody::set_can_sleep); + ClassDB::bind_method(D_METHOD("is_able_to_sleep"), &RigidBody::is_able_to_sleep); - ClassDB::bind_method(D_METHOD("set_can_sleep","able_to_sleep"),&RigidBody::set_can_sleep); - ClassDB::bind_method(D_METHOD("is_able_to_sleep"),&RigidBody::is_able_to_sleep); + ClassDB::bind_method(D_METHOD("_direct_state_changed"), &RigidBody::_direct_state_changed); + ClassDB::bind_method(D_METHOD("_body_enter_tree"), &RigidBody::_body_enter_tree); + ClassDB::bind_method(D_METHOD("_body_exit_tree"), &RigidBody::_body_exit_tree); - ClassDB::bind_method(D_METHOD("_direct_state_changed"),&RigidBody::_direct_state_changed); - ClassDB::bind_method(D_METHOD("_body_enter_tree"),&RigidBody::_body_enter_tree); - ClassDB::bind_method(D_METHOD("_body_exit_tree"),&RigidBody::_body_exit_tree); + ClassDB::bind_method(D_METHOD("set_axis_lock", "axis_lock"), &RigidBody::set_axis_lock); + ClassDB::bind_method(D_METHOD("get_axis_lock"), &RigidBody::get_axis_lock); - ClassDB::bind_method(D_METHOD("set_axis_lock","axis_lock"),&RigidBody::set_axis_lock); - ClassDB::bind_method(D_METHOD("get_axis_lock"),&RigidBody::get_axis_lock); + ClassDB::bind_method(D_METHOD("get_colliding_bodies"), &RigidBody::get_colliding_bodies); - ClassDB::bind_method(D_METHOD("get_colliding_bodies"),&RigidBody::get_colliding_bodies); + BIND_VMETHOD(MethodInfo("_integrate_forces", PropertyInfo(Variant::OBJECT, "state:PhysicsDirectBodyState"))); - BIND_VMETHOD(MethodInfo("_integrate_forces",PropertyInfo(Variant::OBJECT,"state:PhysicsDirectBodyState"))); + ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Rigid,Static,Character,Kinematic"), "set_mode", "get_mode"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "mass", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01"), "set_mass", "get_mass"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "weight", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01", PROPERTY_USAGE_EDITOR), "set_weight", "get_weight"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "continuous_cd"), "set_use_continuous_collision_detection", "is_using_continuous_collision_detection"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "contacts_reported"), "set_max_contacts_reported", "get_max_contacts_reported"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "contact_monitor"), "set_contact_monitor", "is_contact_monitor_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sleeping"), "set_sleeping", "is_sleeping"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "can_sleep"), "set_can_sleep", "is_able_to_sleep"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "axis_lock", PROPERTY_HINT_ENUM, "Disabled,Lock X,Lock Y,Lock Z"), "set_axis_lock", "get_axis_lock"); + ADD_GROUP("Linear", "linear_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "linear_velocity"), "set_linear_velocity", "get_linear_velocity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "linear_damp", PROPERTY_HINT_RANGE, "-1,128,0.01"), "set_linear_damp", "get_linear_damp"); + ADD_GROUP("Angular", "angular_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "angular_velocity"), "set_angular_velocity", "get_angular_velocity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_damp", PROPERTY_HINT_RANGE, "-1,128,0.01"), "set_angular_damp", "get_angular_damp"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Rigid,Static,Character,Kinematic"),"set_mode","get_mode"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"mass",PROPERTY_HINT_EXP_RANGE,"0.01,65535,0.01"),"set_mass","get_mass"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"weight",PROPERTY_HINT_EXP_RANGE,"0.01,65535,0.01",PROPERTY_USAGE_EDITOR),"set_weight","get_weight"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_friction","get_friction"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_bounce","get_bounce"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"gravity_scale",PROPERTY_HINT_RANGE,"-128,128,0.01"),"set_gravity_scale","get_gravity_scale"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"custom_integrator"),"set_use_custom_integrator","is_using_custom_integrator"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"continuous_cd"),"set_use_continuous_collision_detection","is_using_continuous_collision_detection"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"contacts_reported"),"set_max_contacts_reported","get_max_contacts_reported"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"contact_monitor"),"set_contact_monitor","is_contact_monitor_enabled"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"sleeping"),"set_sleeping","is_sleeping"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"can_sleep"),"set_can_sleep","is_able_to_sleep"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"axis_lock",PROPERTY_HINT_ENUM,"Disabled,Lock X,Lock Y,Lock Z"),"set_axis_lock","get_axis_lock"); - ADD_GROUP("Linear","linear_"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"linear_velocity"),"set_linear_velocity","get_linear_velocity"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"linear_damp",PROPERTY_HINT_RANGE,"-1,128,0.01"),"set_linear_damp","get_linear_damp"); - ADD_GROUP("Angular","angular_"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"angular_velocity"),"set_angular_velocity","get_angular_velocity"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_damp",PROPERTY_HINT_RANGE,"-1,128,0.01"),"set_angular_damp","get_angular_damp"); + ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape"))); + ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape"))); + ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body"))); + ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body"))); + ADD_SIGNAL(MethodInfo("sleeping_state_changed")); - ADD_SIGNAL( MethodInfo("body_shape_entered",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"local_shape"))); - ADD_SIGNAL( MethodInfo("body_shape_exited",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"local_shape"))); - ADD_SIGNAL( MethodInfo("body_entered",PropertyInfo(Variant::OBJECT,"body"))); - ADD_SIGNAL( MethodInfo("body_exited",PropertyInfo(Variant::OBJECT,"body"))); - ADD_SIGNAL( MethodInfo("sleeping_state_changed")); - - BIND_CONSTANT( MODE_STATIC ); - BIND_CONSTANT( MODE_KINEMATIC ); - BIND_CONSTANT( MODE_RIGID ); - BIND_CONSTANT( MODE_CHARACTER ); + BIND_CONSTANT(MODE_STATIC); + BIND_CONSTANT(MODE_KINEMATIC); + BIND_CONSTANT(MODE_RIGID); + BIND_CONSTANT(MODE_CHARACTER); } -RigidBody::RigidBody() : PhysicsBody(PhysicsServer::BODY_MODE_RIGID) { +RigidBody::RigidBody() + : PhysicsBody(PhysicsServer::BODY_MODE_RIGID) { - mode=MODE_RIGID; + mode = MODE_RIGID; - bounce=0; - mass=1; - friction=1; - max_contacts_reported=0; - state=NULL; + bounce = 0; + mass = 1; + friction = 1; + max_contacts_reported = 0; + state = NULL; - gravity_scale=1; - linear_damp=-1; - angular_damp=-1; + gravity_scale = 1; + linear_damp = -1; + angular_damp = -1; //angular_velocity=0; - sleeping=false; - ccd=false; + sleeping = false; + ccd = false; - custom_integrator=false; - contact_monitor=NULL; - can_sleep=true; + custom_integrator = false; + contact_monitor = NULL; + can_sleep = true; axis_lock = AXIS_LOCK_DISABLED; - PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(),this,"_direct_state_changed"); + PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed"); } RigidBody::~RigidBody() { if (contact_monitor) - memdelete( contact_monitor ); - - - + memdelete(contact_monitor); } ////////////////////////////////////////////////////// ////////////////////////// - Variant KinematicBody::_get_collider() const { - ObjectID oid=get_collider(); - if (oid==0) + ObjectID oid = get_collider(); + if (oid == 0) return Variant(); Object *obj = ObjectDB::get_instance(oid); if (!obj) @@ -951,10 +894,9 @@ Variant KinematicBody::_get_collider() const { return obj; } - bool KinematicBody::_ignores_mode(PhysicsServer::BodyMode p_mode) const { - switch(p_mode) { + switch (p_mode) { case PhysicsServer::BODY_MODE_STATIC: return !collide_static; case PhysicsServer::BODY_MODE_KINEMATIC: return !collide_kinematic; case PhysicsServer::BODY_MODE_RIGID: return !collide_rigid; @@ -964,7 +906,7 @@ bool KinematicBody::_ignores_mode(PhysicsServer::BodyMode p_mode) const { return true; } -Vector3 KinematicBody::move(const Vector3& p_motion) { +Vector3 KinematicBody::move(const Vector3 &p_motion) { //give me back regular physics engine logic //this is madness @@ -973,32 +915,30 @@ Vector3 KinematicBody::move(const Vector3& p_motion) { //this took about a week to get right.. //but is it right? who knows at this point.. - - colliding=false; - ERR_FAIL_COND_V(!is_inside_tree(),Vector3()); + colliding = false; + ERR_FAIL_COND_V(!is_inside_tree(), Vector3()); PhysicsDirectSpaceState *dss = PhysicsServer::get_singleton()->space_get_direct_state(get_world()->get_space()); - ERR_FAIL_COND_V(!dss,Vector3()); - const int max_shapes=32; - Vector3 sr[max_shapes*2]; + ERR_FAIL_COND_V(!dss, Vector3()); + const int max_shapes = 32; + Vector3 sr[max_shapes * 2]; int res_shapes; Set exclude; exclude.insert(get_rid()); - //recover first - int recover_attempts=4; + int recover_attempts = 4; - bool collided=false; - uint32_t mask=0; + bool collided = false; + uint32_t mask = 0; if (collide_static) - mask|=PhysicsDirectSpaceState::TYPE_MASK_STATIC_BODY; + mask |= PhysicsDirectSpaceState::TYPE_MASK_STATIC_BODY; if (collide_kinematic) - mask|=PhysicsDirectSpaceState::TYPE_MASK_KINEMATIC_BODY; + mask |= PhysicsDirectSpaceState::TYPE_MASK_KINEMATIC_BODY; if (collide_rigid) - mask|=PhysicsDirectSpaceState::TYPE_MASK_RIGID_BODY; + mask |= PhysicsDirectSpaceState::TYPE_MASK_RIGID_BODY; if (collide_character) - mask|=PhysicsDirectSpaceState::TYPE_MASK_CHARACTER_BODY; + mask |= PhysicsDirectSpaceState::TYPE_MASK_CHARACTER_BODY; //print_line("motion: "+p_motion+" margin: "+rtos(margin)); @@ -1010,31 +950,28 @@ Vector3 KinematicBody::move(const Vector3& p_motion) { do { //motion recover - for(int i=0;icollide_shape(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i),m,sr,max_shapes,res_shapes,exclude,get_collision_layer(),mask)) { - collided=true; + if (dss->collide_shape(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), m, sr, max_shapes, res_shapes, exclude, get_collision_layer(), mask)) { + collided = true; } - } - - if (!collided) break; //print_line("have to recover"); Vector3 recover_motion; - bool all_outside=true; - for(int j=0;j<8;j++) { - for(int i=0;i "+b); + Vector3 a = sr[i * 2 + 0]; + Vector3 b = sr[i * 2 + 1]; +//print_line(String()+a+" -> "+b); #if 0 float d = a.distance_to(b); @@ -1045,29 +982,27 @@ Vector3 KinematicBody::move(const Vector3& p_motion) { recover_motion+=(b-a)*0.2; #else float dist = a.distance_to(b); - if (dist>CMP_EPSILON) { - Vector3 norm = (b-a).normalized(); - if (dist>margin*0.5) - all_outside=false; + if (dist > CMP_EPSILON) { + Vector3 norm = (b - a).normalized(); + if (dist > margin * 0.5) + all_outside = false; float adv = norm.dot(recover_motion); //print_line(itos(i)+" dist: "+rtos(dist)+" adv: "+rtos(adv)); - recover_motion+=norm*MAX(dist-adv,0)*0.4; + recover_motion += norm * MAX(dist - adv, 0) * 0.4; } #endif - } } - - if (recover_motion==Vector3()) { - collided=false; + if (recover_motion == Vector3()) { + collided = false; break; } //print_line("**** RECOVER: "+recover_motion); Transform gt = get_global_transform(); - gt.origin+=recover_motion; + gt.origin += recover_motion; set_global_transform(gt); recover_attempts--; @@ -1077,133 +1012,127 @@ Vector3 KinematicBody::move(const Vector3& p_motion) { } while (recover_attempts); - //move second float safe = 1.0; float unsafe = 1.0; - int best_shape=-1; + int best_shape = -1; PhysicsDirectSpaceState::ShapeRestInfo rest; //print_line("pos: "+get_global_transform().origin); //print_line("motion: "+p_motion); - - for(int i=0;icast_motion(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), p_motion,0, lsafe,lunsafe,exclude,get_collision_layer(),mask,&lrest); + bool valid = dss->cast_motion(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), p_motion, 0, lsafe, lunsafe, exclude, get_collision_layer(), mask, &lrest); //print_line("shape: "+itos(i)+" travel:"+rtos(ltravel)); if (!valid) { - safe=0; - unsafe=0; - best_shape=i; //sadly it's the best + safe = 0; + unsafe = 0; + best_shape = i; //sadly it's the best //print_line("initial stuck"); break; } - if (lsafe==1.0) { + if (lsafe == 1.0) { //print_line("initial free"); continue; } if (lsafe < safe) { //print_line("initial at "+rtos(lsafe)); - safe=lsafe; - safe=MAX(0,lsafe-0.01); - unsafe=lunsafe; - best_shape=i; - rest=lrest; + safe = lsafe; + safe = MAX(0, lsafe - 0.01); + unsafe = lunsafe; + best_shape = i; + rest = lrest; } } - //print_line("best shape: "+itos(best_shape)+" motion "+p_motion); - if (safe>=1) { + if (safe >= 1) { //not collided - colliding=false; + colliding = false; } else { - colliding=true; + colliding = true; - if (true || (safe==0 && unsafe==0)) { //use it always because it's more precise than GJK + if (true || (safe == 0 && unsafe == 0)) { //use it always because it's more precise than GJK //no advance, use rest info from collision Transform ugt = get_global_transform(); - ugt.origin+=p_motion*unsafe; + ugt.origin += p_motion * unsafe; PhysicsDirectSpaceState::ShapeRestInfo rest_info; - bool c2 = dss->rest_info(get_shape(best_shape)->get_rid(), ugt*get_shape_transform(best_shape), m,&rest,exclude,get_collision_layer(),mask); + bool c2 = dss->rest_info(get_shape(best_shape)->get_rid(), ugt * get_shape_transform(best_shape), m, &rest, exclude, get_collision_layer(), mask); if (!c2) { //should not happen, but floating point precision is so weird.. - colliding=false; + colliding = false; } //print_line("Rest Travel: "+rest.normal); - } if (colliding) { - collision=rest.point; - normal=rest.normal; - collider=rest.collider_id; - collider_vel=rest.linear_velocity; - collider_shape=rest.shape; + collision = rest.point; + normal = rest.normal; + collider = rest.collider_id; + collider_vel = rest.linear_velocity; + collider_shape = rest.shape; } } - Vector3 motion=p_motion*safe; + Vector3 motion = p_motion * safe; /* if (colliding) motion+=normal*0.001; */ Transform gt = get_global_transform(); - gt.origin+=motion; + gt.origin += motion; set_global_transform(gt); - return p_motion-motion; - + return p_motion - motion; } -Vector3 KinematicBody::move_to(const Vector3& p_position) { +Vector3 KinematicBody::move_to(const Vector3 &p_position) { - return move(p_position-get_global_transform().origin); + return move(p_position - get_global_transform().origin); } -bool KinematicBody::can_teleport_to(const Vector3& p_position) { +bool KinematicBody::can_teleport_to(const Vector3 &p_position) { - ERR_FAIL_COND_V(!is_inside_tree(),false); + ERR_FAIL_COND_V(!is_inside_tree(), false); PhysicsDirectSpaceState *dss = PhysicsServer::get_singleton()->space_get_direct_state(get_world()->get_space()); - ERR_FAIL_COND_V(!dss,false); + ERR_FAIL_COND_V(!dss, false); - uint32_t mask=0; + uint32_t mask = 0; if (collide_static) - mask|=PhysicsDirectSpaceState::TYPE_MASK_STATIC_BODY; + mask |= PhysicsDirectSpaceState::TYPE_MASK_STATIC_BODY; if (collide_kinematic) - mask|=PhysicsDirectSpaceState::TYPE_MASK_KINEMATIC_BODY; + mask |= PhysicsDirectSpaceState::TYPE_MASK_KINEMATIC_BODY; if (collide_rigid) - mask|=PhysicsDirectSpaceState::TYPE_MASK_RIGID_BODY; + mask |= PhysicsDirectSpaceState::TYPE_MASK_RIGID_BODY; if (collide_character) - mask|=PhysicsDirectSpaceState::TYPE_MASK_CHARACTER_BODY; + mask |= PhysicsDirectSpaceState::TYPE_MASK_CHARACTER_BODY; - Transform xform=get_global_transform(); - xform.origin=p_position; + Transform xform = get_global_transform(); + xform.origin = p_position; Set exclude; exclude.insert(get_rid()); - for(int i=0;iintersect_shape(get_shape(i)->get_rid(), xform * get_shape_transform(i),0,NULL,1,exclude,get_collision_layer(),mask); + bool col = dss->intersect_shape(get_shape(i)->get_rid(), xform * get_shape_transform(i), 0, NULL, 1, exclude, get_collision_layer(), mask); if (col) return false; } @@ -1213,21 +1142,19 @@ bool KinematicBody::can_teleport_to(const Vector3& p_position) { bool KinematicBody::is_colliding() const { - ERR_FAIL_COND_V(!is_inside_tree(),false); + ERR_FAIL_COND_V(!is_inside_tree(), false); return colliding; } Vector3 KinematicBody::get_collision_pos() const { - ERR_FAIL_COND_V(!colliding,Vector3()); + ERR_FAIL_COND_V(!colliding, Vector3()); return collision; - } Vector3 KinematicBody::get_collision_normal() const { - ERR_FAIL_COND_V(!colliding,Vector3()); + ERR_FAIL_COND_V(!colliding, Vector3()); return normal; - } Vector3 KinematicBody::get_collider_velocity() const { @@ -1237,18 +1164,17 @@ Vector3 KinematicBody::get_collider_velocity() const { ObjectID KinematicBody::get_collider() const { - ERR_FAIL_COND_V(!colliding,0); + ERR_FAIL_COND_V(!colliding, 0); return collider; } int KinematicBody::get_collider_shape() const { - ERR_FAIL_COND_V(!colliding,-1); + ERR_FAIL_COND_V(!colliding, -1); return collider_shape; - } void KinematicBody::set_collide_with_static_bodies(bool p_enable) { - collide_static=p_enable; + collide_static = p_enable; } bool KinematicBody::can_collide_with_static_bodies() const { @@ -1257,19 +1183,16 @@ bool KinematicBody::can_collide_with_static_bodies() const { void KinematicBody::set_collide_with_rigid_bodies(bool p_enable) { - collide_rigid=p_enable; - + collide_rigid = p_enable; } bool KinematicBody::can_collide_with_rigid_bodies() const { - return collide_rigid; } void KinematicBody::set_collide_with_kinematic_bodies(bool p_enable) { - collide_kinematic=p_enable; - + collide_kinematic = p_enable; } bool KinematicBody::can_collide_with_kinematic_bodies() const { @@ -1278,7 +1201,7 @@ bool KinematicBody::can_collide_with_kinematic_bodies() const { void KinematicBody::set_collide_with_character_bodies(bool p_enable) { - collide_character=p_enable; + collide_character = p_enable; } bool KinematicBody::can_collide_with_character_bodies() const { @@ -1287,70 +1210,63 @@ bool KinematicBody::can_collide_with_character_bodies() const { void KinematicBody::set_collision_margin(float p_margin) { - margin=p_margin; + margin = p_margin; } -float KinematicBody::get_collision_margin() const{ +float KinematicBody::get_collision_margin() const { return margin; } void KinematicBody::_bind_methods() { + ClassDB::bind_method(D_METHOD("move", "rel_vec"), &KinematicBody::move); + ClassDB::bind_method(D_METHOD("move_to", "position"), &KinematicBody::move_to); - ClassDB::bind_method(D_METHOD("move","rel_vec"),&KinematicBody::move); - ClassDB::bind_method(D_METHOD("move_to","position"),&KinematicBody::move_to); - - ClassDB::bind_method(D_METHOD("can_teleport_to","position"),&KinematicBody::can_teleport_to); - - ClassDB::bind_method(D_METHOD("is_colliding"),&KinematicBody::is_colliding); - - ClassDB::bind_method(D_METHOD("get_collision_pos"),&KinematicBody::get_collision_pos); - ClassDB::bind_method(D_METHOD("get_collision_normal"),&KinematicBody::get_collision_normal); - ClassDB::bind_method(D_METHOD("get_collider_velocity"),&KinematicBody::get_collider_velocity); - ClassDB::bind_method(D_METHOD("get_collider:Variant"),&KinematicBody::_get_collider); - ClassDB::bind_method(D_METHOD("get_collider_shape"),&KinematicBody::get_collider_shape); + ClassDB::bind_method(D_METHOD("can_teleport_to", "position"), &KinematicBody::can_teleport_to); + ClassDB::bind_method(D_METHOD("is_colliding"), &KinematicBody::is_colliding); - ClassDB::bind_method(D_METHOD("set_collide_with_static_bodies","enable"),&KinematicBody::set_collide_with_static_bodies); - ClassDB::bind_method(D_METHOD("can_collide_with_static_bodies"),&KinematicBody::can_collide_with_static_bodies); + ClassDB::bind_method(D_METHOD("get_collision_pos"), &KinematicBody::get_collision_pos); + ClassDB::bind_method(D_METHOD("get_collision_normal"), &KinematicBody::get_collision_normal); + ClassDB::bind_method(D_METHOD("get_collider_velocity"), &KinematicBody::get_collider_velocity); + ClassDB::bind_method(D_METHOD("get_collider:Variant"), &KinematicBody::_get_collider); + ClassDB::bind_method(D_METHOD("get_collider_shape"), &KinematicBody::get_collider_shape); - ClassDB::bind_method(D_METHOD("set_collide_with_kinematic_bodies","enable"),&KinematicBody::set_collide_with_kinematic_bodies); - ClassDB::bind_method(D_METHOD("can_collide_with_kinematic_bodies"),&KinematicBody::can_collide_with_kinematic_bodies); + ClassDB::bind_method(D_METHOD("set_collide_with_static_bodies", "enable"), &KinematicBody::set_collide_with_static_bodies); + ClassDB::bind_method(D_METHOD("can_collide_with_static_bodies"), &KinematicBody::can_collide_with_static_bodies); - ClassDB::bind_method(D_METHOD("set_collide_with_rigid_bodies","enable"),&KinematicBody::set_collide_with_rigid_bodies); - ClassDB::bind_method(D_METHOD("can_collide_with_rigid_bodies"),&KinematicBody::can_collide_with_rigid_bodies); + ClassDB::bind_method(D_METHOD("set_collide_with_kinematic_bodies", "enable"), &KinematicBody::set_collide_with_kinematic_bodies); + ClassDB::bind_method(D_METHOD("can_collide_with_kinematic_bodies"), &KinematicBody::can_collide_with_kinematic_bodies); - ClassDB::bind_method(D_METHOD("set_collide_with_character_bodies","enable"),&KinematicBody::set_collide_with_character_bodies); - ClassDB::bind_method(D_METHOD("can_collide_with_character_bodies"),&KinematicBody::can_collide_with_character_bodies); + ClassDB::bind_method(D_METHOD("set_collide_with_rigid_bodies", "enable"), &KinematicBody::set_collide_with_rigid_bodies); + ClassDB::bind_method(D_METHOD("can_collide_with_rigid_bodies"), &KinematicBody::can_collide_with_rigid_bodies); - ClassDB::bind_method(D_METHOD("set_collision_margin","pixels"),&KinematicBody::set_collision_margin); - ClassDB::bind_method(D_METHOD("get_collision_margin","pixels"),&KinematicBody::get_collision_margin); - - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collide_with/static"),"set_collide_with_static_bodies","can_collide_with_static_bodies"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collide_with/kinematic"),"set_collide_with_kinematic_bodies","can_collide_with_kinematic_bodies"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collide_with/rigid"),"set_collide_with_rigid_bodies","can_collide_with_rigid_bodies"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collide_with/character"),"set_collide_with_character_bodies","can_collide_with_character_bodies"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"collision/margin",PROPERTY_HINT_RANGE,"0.001,256,0.001"),"set_collision_margin","get_collision_margin"); + ClassDB::bind_method(D_METHOD("set_collide_with_character_bodies", "enable"), &KinematicBody::set_collide_with_character_bodies); + ClassDB::bind_method(D_METHOD("can_collide_with_character_bodies"), &KinematicBody::can_collide_with_character_bodies); + ClassDB::bind_method(D_METHOD("set_collision_margin", "pixels"), &KinematicBody::set_collision_margin); + ClassDB::bind_method(D_METHOD("get_collision_margin", "pixels"), &KinematicBody::get_collision_margin); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with/static"), "set_collide_with_static_bodies", "can_collide_with_static_bodies"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with/kinematic"), "set_collide_with_kinematic_bodies", "can_collide_with_kinematic_bodies"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with/rigid"), "set_collide_with_rigid_bodies", "can_collide_with_rigid_bodies"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with/character"), "set_collide_with_character_bodies", "can_collide_with_character_bodies"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "collision/margin", PROPERTY_HINT_RANGE, "0.001,256,0.001"), "set_collision_margin", "get_collision_margin"); } -KinematicBody::KinematicBody() : PhysicsBody(PhysicsServer::BODY_MODE_KINEMATIC){ +KinematicBody::KinematicBody() + : PhysicsBody(PhysicsServer::BODY_MODE_KINEMATIC) { - collide_static=true; - collide_rigid=true; - collide_kinematic=true; - collide_character=true; + collide_static = true; + collide_rigid = true; + collide_kinematic = true; + collide_character = true; - colliding=false; - collider=0; - margin=0.001; - collider_shape=0; + colliding = false; + collider = 0; + margin = 0.001; + collider_shape = 0; } -KinematicBody::~KinematicBody() { - - +KinematicBody::~KinematicBody() { } - - diff --git a/scene/3d/physics_body.h b/scene/3d/physics_body.h index 86be98f81..1cef94683 100644 --- a/scene/3d/physics_body.h +++ b/scene/3d/physics_body.h @@ -33,10 +33,9 @@ #include "servers/physics_server.h" #include "vset.h" - class PhysicsBody : public CollisionObject { - GDCLASS(PhysicsBody,CollisionObject); + GDCLASS(PhysicsBody, CollisionObject); uint32_t layer_mask; uint32_t collision_mask; @@ -45,12 +44,11 @@ class PhysicsBody : public CollisionObject { uint32_t _get_layers() const; protected: - static void _bind_methods(); void _notification(int p_what); PhysicsBody(PhysicsServer::BodyMode p_mode); -public: +public: virtual Vector3 get_linear_velocity() const; virtual Vector3 get_angular_velocity() const; virtual float get_inverse_mass() const; @@ -67,18 +65,15 @@ public: void set_collision_mask_bit(int p_bit, bool p_value); bool get_collision_mask_bit(int p_bit) const; - void add_collision_exception_with(Node* p_node); //must be physicsbody - void remove_collision_exception_with(Node* p_node); - - + void add_collision_exception_with(Node *p_node); //must be physicsbody + void remove_collision_exception_with(Node *p_node); PhysicsBody(); - }; class StaticBody : public PhysicsBody { - GDCLASS(StaticBody,PhysicsBody); + GDCLASS(StaticBody, PhysicsBody); Vector3 constant_linear_velocity; Vector3 constant_angular_velocity; @@ -86,37 +81,31 @@ class StaticBody : public PhysicsBody { real_t bounce; real_t friction; - protected: - static void _bind_methods(); public: - - void set_friction(real_t p_friction); real_t get_friction() const; void set_bounce(real_t p_bounce); real_t get_bounce() const; - - void set_constant_linear_velocity(const Vector3& p_vel); - void set_constant_angular_velocity(const Vector3& p_vel); + void set_constant_linear_velocity(const Vector3 &p_vel); + void set_constant_angular_velocity(const Vector3 &p_vel); Vector3 get_constant_linear_velocity() const; Vector3 get_constant_angular_velocity() const; StaticBody(); ~StaticBody(); - }; class RigidBody : public PhysicsBody { - GDCLASS(RigidBody,PhysicsBody); -public: + GDCLASS(RigidBody, PhysicsBody); +public: enum Mode { MODE_RIGID, MODE_STATIC, @@ -132,7 +121,6 @@ public: }; private: - bool can_sleep; PhysicsDirectBodyState *state; Mode mode; @@ -142,7 +130,7 @@ private: real_t friction; Vector3 linear_velocity; - Vector3 angular_velocity; + Vector3 angular_velocity; real_t gravity_scale; real_t linear_damp; real_t angular_damp; @@ -152,33 +140,32 @@ private: AxisLock axis_lock; - int max_contacts_reported; bool custom_integrator; - struct ShapePair { int body_shape; int local_shape; bool tagged; - bool operator<(const ShapePair& p_sp) const { - if (body_shape==p_sp.body_shape) + bool operator<(const ShapePair &p_sp) const { + if (body_shape == p_sp.body_shape) return local_shape < p_sp.local_shape; else return body_shape < p_sp.body_shape; } ShapePair() {} - ShapePair(int p_bs, int p_ls) { body_shape=p_bs; local_shape=p_ls; } + ShapePair(int p_bs, int p_ls) { + body_shape = p_bs; + local_shape = p_ls; + } }; struct RigidBody_RemoveAction { - ObjectID body_id; ShapePair pair; - }; struct BodyState { @@ -190,33 +177,28 @@ private: struct ContactMonitor { bool locked; - Map body_map; - + Map body_map; }; - ContactMonitor *contact_monitor; void _body_enter_tree(ObjectID p_id); void _body_exit_tree(ObjectID p_id); - - void _body_inout(int p_status, ObjectID p_instance, int p_body_shape,int p_local_shape); + void _body_inout(int p_status, ObjectID p_instance, int p_body_shape, int p_local_shape); void _direct_state_changed(Object *p_state); - protected: - void _notification(int p_what); static void _bind_methods(); -public: +public: void set_mode(Mode p_mode); Mode get_mode() const; void set_mass(real_t p_mass); real_t get_mass() const; - virtual float get_inverse_mass() const { return 1.0/mass; } + virtual float get_inverse_mass() const { return 1.0 / mass; } void set_weight(real_t p_weight); real_t get_weight() const; @@ -227,13 +209,13 @@ public: void set_bounce(real_t p_bounce); real_t get_bounce() const; - void set_linear_velocity(const Vector3& p_velocity); + void set_linear_velocity(const Vector3 &p_velocity); Vector3 get_linear_velocity() const; - void set_axis_velocity(const Vector3& p_axis); + void set_axis_velocity(const Vector3 &p_axis); - void set_angular_velocity(const Vector3&p_velocity); - Vector3 get_angular_velocity() const; + void set_angular_velocity(const Vector3 &p_velocity); + Vector3 get_angular_velocity() const; void set_gravity_scale(real_t p_gravity_scale); real_t get_gravity_scale() const; @@ -244,7 +226,6 @@ public: void set_angular_damp(real_t p_angular_damp); real_t get_angular_damp() const; - void set_use_custom_integrator(bool p_enable); bool is_using_custom_integrator(); @@ -268,23 +249,18 @@ public: Array get_colliding_bodies() const; - void apply_impulse(const Vector3& p_pos, const Vector3& p_impulse); + void apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse); RigidBody(); ~RigidBody(); - }; VARIANT_ENUM_CAST(RigidBody::Mode); VARIANT_ENUM_CAST(RigidBody::AxisLock); - - - - class KinematicBody : public PhysicsBody { - GDCLASS(KinematicBody,PhysicsBody); + GDCLASS(KinematicBody, PhysicsBody); float margin; bool collide_static; @@ -299,26 +275,24 @@ class KinematicBody : public PhysicsBody { ObjectID collider; int collider_shape; - - Variant _get_collider() const; _FORCE_INLINE_ bool _ignores_mode(PhysicsServer::BodyMode) const; -protected: +protected: static void _bind_methods(); -public: +public: enum { SLIDE_FLAG_FLOOR, SLIDE_FLAG_WALL, SLIDE_FLAG_ROOF }; - Vector3 move(const Vector3& p_motion); - Vector3 move_to(const Vector3& p_position); + Vector3 move(const Vector3 &p_motion); + Vector3 move_to(const Vector3 &p_position); - bool can_teleport_to(const Vector3& p_position); + bool can_teleport_to(const Vector3 &p_position); bool is_colliding() const; Vector3 get_collision_pos() const; Vector3 get_collision_normal() const; @@ -343,7 +317,6 @@ public: KinematicBody(); ~KinematicBody(); - }; #endif // PHYSICS_BODY__H diff --git a/scene/3d/physics_joint.cpp b/scene/3d/physics_joint.cpp index d48d75f46..8c20b003f 100644 --- a/scene/3d/physics_joint.cpp +++ b/scene/3d/physics_joint.cpp @@ -28,101 +28,89 @@ /*************************************************************************/ #include "physics_joint.h" - - void Joint::_update_joint(bool p_only_free) { - if (joint.is_valid()) { if (ba.is_valid() && bb.is_valid()) { if (exclude_from_collision) - PhysicsServer::get_singleton()->body_add_collision_exception(ba,bb); + PhysicsServer::get_singleton()->body_add_collision_exception(ba, bb); else - PhysicsServer::get_singleton()->body_remove_collision_exception(ba,bb); - + PhysicsServer::get_singleton()->body_remove_collision_exception(ba, bb); } PhysicsServer::get_singleton()->free(joint); - joint=RID(); - ba=RID(); - bb=RID(); + joint = RID(); + ba = RID(); + bb = RID(); } if (p_only_free || !is_inside_tree()) return; - Node *node_a = has_node( get_node_a() ) ? get_node( get_node_a() ) : (Node*)NULL; - Node *node_b = has_node( get_node_b() ) ? get_node( get_node_b() ) : (Node*)NULL; + Node *node_a = has_node(get_node_a()) ? get_node(get_node_a()) : (Node *)NULL; + Node *node_b = has_node(get_node_b()) ? get_node(get_node_b()) : (Node *)NULL; if (!node_a && !node_b) return; - PhysicsBody *body_a=node_a ? node_a->cast_to() : (PhysicsBody*)NULL; - PhysicsBody *body_b=node_b ? node_b->cast_to() : (PhysicsBody*)NULL; + PhysicsBody *body_a = node_a ? node_a->cast_to() : (PhysicsBody *)NULL; + PhysicsBody *body_b = node_b ? node_b->cast_to() : (PhysicsBody *)NULL; if (!body_a && !body_b) return; if (!body_a) { - SWAP(body_a,body_b); + SWAP(body_a, body_b); } else if (body_b) { //add a collision exception between both - PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid()); + PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid()); } - joint = _configure_joint(body_a,body_b); + joint = _configure_joint(body_a, body_b); if (joint.is_valid()) - PhysicsServer::get_singleton()->joint_set_solver_priority(joint,solver_priority); + PhysicsServer::get_singleton()->joint_set_solver_priority(joint, solver_priority); if (body_b && joint.is_valid()) { - ba=body_a->get_rid(); - bb=body_b->get_rid(); - PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid()); - + ba = body_a->get_rid(); + bb = body_b->get_rid(); + PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid()); } - } +void Joint::set_node_a(const NodePath &p_node_a) { -void Joint::set_node_a(const NodePath& p_node_a) { - - - if (a==p_node_a) + if (a == p_node_a) return; - a=p_node_a; + a = p_node_a; _update_joint(); } -NodePath Joint::get_node_a() const{ +NodePath Joint::get_node_a() const { return a; } -void Joint::set_node_b(const NodePath& p_node_b){ +void Joint::set_node_b(const NodePath &p_node_b) { - if (b==p_node_b) + if (b == p_node_b) return; - b=p_node_b; + b = p_node_b; _update_joint(); - } -NodePath Joint::get_node_b() const{ - +NodePath Joint::get_node_b() const { return b; } - void Joint::set_solver_priority(int p_priority) { - solver_priority=p_priority; + solver_priority = p_priority; if (joint.is_valid()) - PhysicsServer::get_singleton()->joint_set_solver_priority(joint,solver_priority); - + PhysicsServer::get_singleton()->joint_set_solver_priority(joint, solver_priority); } int Joint::get_solver_priority() const { @@ -130,10 +118,9 @@ int Joint::get_solver_priority() const { return solver_priority; } - void Joint::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_READY: { _update_joint(); @@ -142,95 +129,83 @@ void Joint::_notification(int p_what) { if (joint.is_valid()) { _update_joint(true); //PhysicsServer::get_singleton()->free(joint); - joint=RID(); + joint = RID(); } } break; - } - } - void Joint::set_exclude_nodes_from_collision(bool p_enable) { - if (exclude_from_collision==p_enable) + if (exclude_from_collision == p_enable) return; - exclude_from_collision=p_enable; + exclude_from_collision = p_enable; _update_joint(); } -bool Joint::get_exclude_nodes_from_collision() const{ +bool Joint::get_exclude_nodes_from_collision() const { return exclude_from_collision; } void Joint::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_node_a", "node"), &Joint::set_node_a); + ClassDB::bind_method(D_METHOD("get_node_a"), &Joint::get_node_a); - ClassDB::bind_method( D_METHOD("set_node_a","node"), &Joint::set_node_a ); - ClassDB::bind_method( D_METHOD("get_node_a"), &Joint::get_node_a ); - - ClassDB::bind_method( D_METHOD("set_node_b","node"), &Joint::set_node_b ); - ClassDB::bind_method( D_METHOD("get_node_b"), &Joint::get_node_b ); - - ClassDB::bind_method( D_METHOD("set_solver_priority","priority"), &Joint::set_solver_priority ); - ClassDB::bind_method( D_METHOD("get_solver_priority"), &Joint::get_solver_priority ); + ClassDB::bind_method(D_METHOD("set_node_b", "node"), &Joint::set_node_b); + ClassDB::bind_method(D_METHOD("get_node_b"), &Joint::get_node_b); - ClassDB::bind_method( D_METHOD("set_exclude_nodes_from_collision","enable"), &Joint::set_exclude_nodes_from_collision ); - ClassDB::bind_method( D_METHOD("get_exclude_nodes_from_collision"), &Joint::get_exclude_nodes_from_collision ); - - ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "nodes/node_a"), "set_node_a","get_node_a") ; - ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "nodes/node_b"), "set_node_b","get_node_b") ; - ADD_PROPERTY( PropertyInfo( Variant::INT, "solver/priority",PROPERTY_HINT_RANGE,"1,8,1"), "set_solver_priority","get_solver_priority") ; - - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "collision/exclude_nodes"), "set_exclude_nodes_from_collision","get_exclude_nodes_from_collision") ; + ClassDB::bind_method(D_METHOD("set_solver_priority", "priority"), &Joint::set_solver_priority); + ClassDB::bind_method(D_METHOD("get_solver_priority"), &Joint::get_solver_priority); + ClassDB::bind_method(D_METHOD("set_exclude_nodes_from_collision", "enable"), &Joint::set_exclude_nodes_from_collision); + ClassDB::bind_method(D_METHOD("get_exclude_nodes_from_collision"), &Joint::get_exclude_nodes_from_collision); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "nodes/node_a"), "set_node_a", "get_node_a"); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "nodes/node_b"), "set_node_b", "get_node_b"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "solver/priority", PROPERTY_HINT_RANGE, "1,8,1"), "set_solver_priority", "get_solver_priority"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision/exclude_nodes"), "set_exclude_nodes_from_collision", "get_exclude_nodes_from_collision"); } - - Joint::Joint() { - exclude_from_collision=true; - solver_priority=1; + exclude_from_collision = true; + solver_priority = 1; set_notify_transform(true); } - /////////////////////////////////// void PinJoint::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_param","param","value"),&PinJoint::set_param); - ClassDB::bind_method(D_METHOD("get_param","param"),&PinJoint::get_param); + ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &PinJoint::set_param); + ClassDB::bind_method(D_METHOD("get_param", "param"), &PinJoint::get_param); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/bias",PROPERTY_HINT_RANGE,"0.01,0.99,0.01"),"set_param","get_param", PARAM_BIAS ); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/damping",PROPERTY_HINT_RANGE,"0.01,8.0,0.01"),"set_param","get_param", PARAM_DAMPING ); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/impulse_clamp",PROPERTY_HINT_RANGE,"0.0,64.0,0.01"),"set_param","get_param", PARAM_IMPULSE_CLAMP ); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_BIAS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/damping", PROPERTY_HINT_RANGE, "0.01,8.0,0.01"), "set_param", "get_param", PARAM_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/impulse_clamp", PROPERTY_HINT_RANGE, "0.0,64.0,0.01"), "set_param", "get_param", PARAM_IMPULSE_CLAMP); - BIND_CONSTANT( PARAM_BIAS ); - BIND_CONSTANT( PARAM_DAMPING ); - BIND_CONSTANT( PARAM_IMPULSE_CLAMP ); + BIND_CONSTANT(PARAM_BIAS); + BIND_CONSTANT(PARAM_DAMPING); + BIND_CONSTANT(PARAM_IMPULSE_CLAMP); } -void PinJoint::set_param(Param p_param,float p_value){ +void PinJoint::set_param(Param p_param, float p_value) { - ERR_FAIL_INDEX(p_param,3); - params[p_param]=p_value; + ERR_FAIL_INDEX(p_param, 3); + params[p_param] = p_value; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->pin_joint_set_param(get_joint(),PhysicsServer::PinJointParam(p_param),p_value); + PhysicsServer::get_singleton()->pin_joint_set_param(get_joint(), PhysicsServer::PinJointParam(p_param), p_value); } -float PinJoint::get_param(Param p_param) const{ +float PinJoint::get_param(Param p_param) const { - ERR_FAIL_INDEX_V(p_param,3,0); + ERR_FAIL_INDEX_V(p_param, 3, 0); return params[p_param]; } - -RID PinJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) { - +RID PinJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) { Vector3 pinpos = get_global_transform().origin; Vector3 local_a = body_a->get_global_transform().affine_inverse().xform(pinpos); @@ -239,37 +214,29 @@ RID PinJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) { if (body_b) local_b = body_b->get_global_transform().affine_inverse().xform(pinpos); else - local_b=pinpos; + local_b = pinpos; - RID j = PhysicsServer::get_singleton()->joint_create_pin(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b); - for(int i=0;i<3;i++) { - PhysicsServer::get_singleton()->pin_joint_set_param(j,PhysicsServer::PinJointParam(i),params[i]); + RID j = PhysicsServer::get_singleton()->joint_create_pin(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b); + for (int i = 0; i < 3; i++) { + PhysicsServer::get_singleton()->pin_joint_set_param(j, PhysicsServer::PinJointParam(i), params[i]); } return j; } - PinJoint::PinJoint() { - params[PARAM_BIAS]=0.3; - params[PARAM_DAMPING]=1; - params[PARAM_IMPULSE_CLAMP]=0; - + params[PARAM_BIAS] = 0.3; + params[PARAM_DAMPING] = 1; + params[PARAM_IMPULSE_CLAMP] = 0; } - - - ///////////////////////////////////////////////// - - /////////////////////////////////// - void HingeJoint::_set_upper_limit(float p_limit) { - set_param(PARAM_LIMIT_UPPER,Math::deg2rad(p_limit)); + set_param(PARAM_LIMIT_UPPER, Math::deg2rad(p_limit)); } float HingeJoint::_get_upper_limit() const { @@ -279,95 +246,87 @@ float HingeJoint::_get_upper_limit() const { void HingeJoint::_set_lower_limit(float p_limit) { - set_param(PARAM_LIMIT_LOWER,Math::deg2rad(p_limit)); - + set_param(PARAM_LIMIT_LOWER, Math::deg2rad(p_limit)); } float HingeJoint::_get_lower_limit() const { return Math::rad2deg(get_param(PARAM_LIMIT_LOWER)); - } - void HingeJoint::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_param","param","value"),&HingeJoint::set_param); - ClassDB::bind_method(D_METHOD("get_param","param"),&HingeJoint::get_param); - - ClassDB::bind_method(D_METHOD("set_flag","flag","enabled"),&HingeJoint::set_flag); - ClassDB::bind_method(D_METHOD("get_flag","flag"),&HingeJoint::get_flag); + ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &HingeJoint::set_param); + ClassDB::bind_method(D_METHOD("get_param", "param"), &HingeJoint::get_param); - ClassDB::bind_method(D_METHOD("_set_upper_limit","upper_limit"),&HingeJoint::_set_upper_limit); - ClassDB::bind_method(D_METHOD("_get_upper_limit"),&HingeJoint::_get_upper_limit); + ClassDB::bind_method(D_METHOD("set_flag", "flag", "enabled"), &HingeJoint::set_flag); + ClassDB::bind_method(D_METHOD("get_flag", "flag"), &HingeJoint::get_flag); - ClassDB::bind_method(D_METHOD("_set_lower_limit","lower_limit"),&HingeJoint::_set_lower_limit); - ClassDB::bind_method(D_METHOD("_get_lower_limit"),&HingeJoint::_get_lower_limit); + ClassDB::bind_method(D_METHOD("_set_upper_limit", "upper_limit"), &HingeJoint::_set_upper_limit); + ClassDB::bind_method(D_METHOD("_get_upper_limit"), &HingeJoint::_get_upper_limit); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/bias",PROPERTY_HINT_RANGE,"0.01,0.99,0.01"),"set_param","get_param", PARAM_BIAS ); + ClassDB::bind_method(D_METHOD("_set_lower_limit", "lower_limit"), &HingeJoint::_set_lower_limit); + ClassDB::bind_method(D_METHOD("_get_lower_limit"), &HingeJoint::_get_lower_limit); - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"angular_limit/enable"),"set_flag","get_flag", FLAG_USE_LIMIT ); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/upper",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_upper_limit","_get_upper_limit") ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/lower",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_lower_limit","_get_lower_limit") ; - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/bias",PROPERTY_HINT_RANGE,"0.01,0.99,0.01"),"set_param","get_param", PARAM_LIMIT_BIAS ); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param","get_param", PARAM_LIMIT_SOFTNESS ); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/relaxation",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param","get_param", PARAM_LIMIT_RELAXATION ); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_BIAS); - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"motor/enable"),"set_flag","get_flag", FLAG_ENABLE_MOTOR ); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"motor/target_velocity",PROPERTY_HINT_RANGE,"0.01,4096,0.01"),"set_param","get_param", PARAM_MOTOR_TARGET_VELOCITY ); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"motor/max_impulse",PROPERTY_HINT_RANGE,"0.01,1024,0.01"),"set_param","get_param", PARAM_MOTOR_MAX_IMPULSE); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit/enable"), "set_flag", "get_flag", FLAG_USE_LIMIT); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/upper", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_upper_limit", "_get_upper_limit"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/lower", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_lower_limit", "_get_lower_limit"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_LIMIT_BIAS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param", "get_param", PARAM_LIMIT_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/relaxation", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param", "get_param", PARAM_LIMIT_RELAXATION); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "motor/enable"), "set_flag", "get_flag", FLAG_ENABLE_MOTOR); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "motor/target_velocity", PROPERTY_HINT_RANGE, "0.01,4096,0.01"), "set_param", "get_param", PARAM_MOTOR_TARGET_VELOCITY); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "motor/max_impulse", PROPERTY_HINT_RANGE, "0.01,1024,0.01"), "set_param", "get_param", PARAM_MOTOR_MAX_IMPULSE); - BIND_CONSTANT( PARAM_BIAS ); - BIND_CONSTANT( PARAM_LIMIT_UPPER ); - BIND_CONSTANT( PARAM_LIMIT_LOWER ); - BIND_CONSTANT( PARAM_LIMIT_BIAS ); - BIND_CONSTANT( PARAM_LIMIT_SOFTNESS ); - BIND_CONSTANT( PARAM_LIMIT_RELAXATION ); - BIND_CONSTANT( PARAM_MOTOR_TARGET_VELOCITY ); - BIND_CONSTANT( PARAM_MOTOR_MAX_IMPULSE ); - BIND_CONSTANT( PARAM_MAX ); - - BIND_CONSTANT( FLAG_USE_LIMIT ); - BIND_CONSTANT( FLAG_ENABLE_MOTOR ); - BIND_CONSTANT( FLAG_MAX ); + BIND_CONSTANT(PARAM_BIAS); + BIND_CONSTANT(PARAM_LIMIT_UPPER); + BIND_CONSTANT(PARAM_LIMIT_LOWER); + BIND_CONSTANT(PARAM_LIMIT_BIAS); + BIND_CONSTANT(PARAM_LIMIT_SOFTNESS); + BIND_CONSTANT(PARAM_LIMIT_RELAXATION); + BIND_CONSTANT(PARAM_MOTOR_TARGET_VELOCITY); + BIND_CONSTANT(PARAM_MOTOR_MAX_IMPULSE); + BIND_CONSTANT(PARAM_MAX); + BIND_CONSTANT(FLAG_USE_LIMIT); + BIND_CONSTANT(FLAG_ENABLE_MOTOR); + BIND_CONSTANT(FLAG_MAX); } -void HingeJoint::set_param(Param p_param,float p_value){ +void HingeJoint::set_param(Param p_param, float p_value) { - ERR_FAIL_INDEX(p_param,PARAM_MAX); - params[p_param]=p_value; + ERR_FAIL_INDEX(p_param, PARAM_MAX); + params[p_param] = p_value; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->hinge_joint_set_param(get_joint(),PhysicsServer::HingeJointParam(p_param),p_value); + PhysicsServer::get_singleton()->hinge_joint_set_param(get_joint(), PhysicsServer::HingeJointParam(p_param), p_value); update_gizmo(); - } -float HingeJoint::get_param(Param p_param) const{ +float HingeJoint::get_param(Param p_param) const { - ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); + ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return params[p_param]; } +void HingeJoint::set_flag(Flag p_flag, bool p_value) { -void HingeJoint::set_flag(Flag p_flag,bool p_value){ - - ERR_FAIL_INDEX(p_flag,FLAG_MAX); - flags[p_flag]=p_value; + ERR_FAIL_INDEX(p_flag, FLAG_MAX); + flags[p_flag] = p_value; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->hinge_joint_set_flag(get_joint(),PhysicsServer::HingeJointFlag(p_flag),p_value); + PhysicsServer::get_singleton()->hinge_joint_set_flag(get_joint(), PhysicsServer::HingeJointFlag(p_flag), p_value); update_gizmo(); } -bool HingeJoint::get_flag(Flag p_flag) const{ +bool HingeJoint::get_flag(Flag p_flag) const { - ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false); + ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false); return flags[p_flag]; } -RID HingeJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) { - +RID HingeJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) { Transform gt = get_global_transform(); Transform ainv = body_a->get_global_transform().affine_inverse(); @@ -383,48 +342,39 @@ RID HingeJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) { local_b.orthonormalize(); - RID j = PhysicsServer::get_singleton()->joint_create_hinge(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b); - for(int i=0;ihinge_joint_set_param(j,PhysicsServer::HingeJointParam(i),params[i]); + RID j = PhysicsServer::get_singleton()->joint_create_hinge(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b); + for (int i = 0; i < PARAM_MAX; i++) { + PhysicsServer::get_singleton()->hinge_joint_set_param(j, PhysicsServer::HingeJointParam(i), params[i]); } - for(int i=0;ihinge_joint_set_flag(j,PhysicsServer::HingeJointFlag(i),flags[i]); + for (int i = 0; i < FLAG_MAX; i++) { + set_flag(Flag(i), flags[i]); + PhysicsServer::get_singleton()->hinge_joint_set_flag(j, PhysicsServer::HingeJointFlag(i), flags[i]); } return j; } - HingeJoint::HingeJoint() { - params[PARAM_BIAS]=0.3; - params[PARAM_LIMIT_UPPER]=Math_PI*0.5; - params[PARAM_LIMIT_LOWER]=-Math_PI*0.5; - params[PARAM_LIMIT_BIAS]=0.3; - params[PARAM_LIMIT_SOFTNESS]=0.9; - params[PARAM_LIMIT_RELAXATION]=1.0; - params[PARAM_MOTOR_TARGET_VELOCITY]=1; - params[PARAM_MOTOR_MAX_IMPULSE]=1; - - - flags[FLAG_USE_LIMIT]=false; - flags[FLAG_ENABLE_MOTOR]=false; + params[PARAM_BIAS] = 0.3; + params[PARAM_LIMIT_UPPER] = Math_PI * 0.5; + params[PARAM_LIMIT_LOWER] = -Math_PI * 0.5; + params[PARAM_LIMIT_BIAS] = 0.3; + params[PARAM_LIMIT_SOFTNESS] = 0.9; + params[PARAM_LIMIT_RELAXATION] = 1.0; + params[PARAM_MOTOR_TARGET_VELOCITY] = 1; + params[PARAM_MOTOR_MAX_IMPULSE] = 1; + flags[FLAG_USE_LIMIT] = false; + flags[FLAG_ENABLE_MOTOR] = false; } - - - ///////////////////////////////////////////////// - ////////////////////////////////// - - void SliderJoint::_set_upper_limit_angular(float p_limit_angular) { - set_param(PARAM_ANGULAR_LIMIT_UPPER,Math::deg2rad(p_limit_angular)); + set_param(PARAM_ANGULAR_LIMIT_UPPER, Math::deg2rad(p_limit_angular)); } float SliderJoint::_get_upper_limit_angular() const { @@ -434,100 +384,91 @@ float SliderJoint::_get_upper_limit_angular() const { void SliderJoint::_set_lower_limit_angular(float p_limit_angular) { - set_param(PARAM_ANGULAR_LIMIT_LOWER,Math::deg2rad(p_limit_angular)); - + set_param(PARAM_ANGULAR_LIMIT_LOWER, Math::deg2rad(p_limit_angular)); } float SliderJoint::_get_lower_limit_angular() const { return Math::rad2deg(get_param(PARAM_ANGULAR_LIMIT_LOWER)); - } - void SliderJoint::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_param","param","value"),&SliderJoint::set_param); - ClassDB::bind_method(D_METHOD("get_param","param"),&SliderJoint::get_param); - - - ClassDB::bind_method(D_METHOD("_set_upper_limit_angular","upper_limit_angular"),&SliderJoint::_set_upper_limit_angular); - ClassDB::bind_method(D_METHOD("_get_upper_limit_angular"),&SliderJoint::_get_upper_limit_angular); - - ClassDB::bind_method(D_METHOD("_set_lower_limit_angular","lower_limit_angular"),&SliderJoint::_set_lower_limit_angular); - ClassDB::bind_method(D_METHOD("_get_lower_limit_angular"),&SliderJoint::_get_lower_limit_angular); - - - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/upper_distance",PROPERTY_HINT_RANGE,"-1024,1024,0.01"),"set_param","get_param", PARAM_LINEAR_LIMIT_UPPER); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/lower_distance",PROPERTY_HINT_RANGE,"-1024,1024,0.01"),"set_param","get_param", PARAM_LINEAR_LIMIT_LOWER); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_LIMIT_SOFTNESS); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_LIMIT_RESTITUTION); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_LIMIT_DAMPING); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_motion/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_MOTION_SOFTNESS); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_motion/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_MOTION_RESTITUTION); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_motion/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_MOTION_DAMPING); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_ortho/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_ORTHOGONAL_SOFTNESS); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_ortho/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_ORTHOGONAL_RESTITUTION); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_ortho/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_ORTHOGONAL_DAMPING); - - ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_upper_limit_angular","_get_upper_limit_angular") ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_lower_limit_angular","_get_lower_limit_angular") ; - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_LIMIT_SOFTNESS); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_LIMIT_RESTITUTION); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_LIMIT_DAMPING); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_motion/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_MOTION_SOFTNESS); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_motion/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_MOTION_RESTITUTION); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_motion/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_MOTION_DAMPING); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_ortho/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_ORTHOGONAL_SOFTNESS); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_ortho/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_ORTHOGONAL_RESTITUTION); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_ortho/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_ORTHOGONAL_DAMPING); - - - BIND_CONSTANT( PARAM_LINEAR_LIMIT_UPPER); - BIND_CONSTANT( PARAM_LINEAR_LIMIT_LOWER); - BIND_CONSTANT( PARAM_LINEAR_LIMIT_SOFTNESS); - BIND_CONSTANT( PARAM_LINEAR_LIMIT_RESTITUTION); - BIND_CONSTANT( PARAM_LINEAR_LIMIT_DAMPING); - BIND_CONSTANT( PARAM_LINEAR_MOTION_SOFTNESS); - BIND_CONSTANT( PARAM_LINEAR_MOTION_RESTITUTION); - BIND_CONSTANT( PARAM_LINEAR_MOTION_DAMPING); - BIND_CONSTANT( PARAM_LINEAR_ORTHOGONAL_SOFTNESS); - BIND_CONSTANT( PARAM_LINEAR_ORTHOGONAL_RESTITUTION); - BIND_CONSTANT( PARAM_LINEAR_ORTHOGONAL_DAMPING); - - BIND_CONSTANT( PARAM_ANGULAR_LIMIT_UPPER); - BIND_CONSTANT( PARAM_ANGULAR_LIMIT_LOWER); - BIND_CONSTANT( PARAM_ANGULAR_LIMIT_SOFTNESS); - BIND_CONSTANT( PARAM_ANGULAR_LIMIT_RESTITUTION); - BIND_CONSTANT( PARAM_ANGULAR_LIMIT_DAMPING); - BIND_CONSTANT( PARAM_ANGULAR_MOTION_SOFTNESS); - BIND_CONSTANT( PARAM_ANGULAR_MOTION_RESTITUTION); - BIND_CONSTANT( PARAM_ANGULAR_MOTION_DAMPING); - BIND_CONSTANT( PARAM_ANGULAR_ORTHOGONAL_SOFTNESS); - BIND_CONSTANT( PARAM_ANGULAR_ORTHOGONAL_RESTITUTION); - BIND_CONSTANT( PARAM_ANGULAR_ORTHOGONAL_DAMPING); - - BIND_CONSTANT( PARAM_MAX); -} - -void SliderJoint::set_param(Param p_param,float p_value){ - - ERR_FAIL_INDEX(p_param,PARAM_MAX); - params[p_param]=p_value; + ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &SliderJoint::set_param); + ClassDB::bind_method(D_METHOD("get_param", "param"), &SliderJoint::get_param); + + ClassDB::bind_method(D_METHOD("_set_upper_limit_angular", "upper_limit_angular"), &SliderJoint::_set_upper_limit_angular); + ClassDB::bind_method(D_METHOD("_get_upper_limit_angular"), &SliderJoint::_get_upper_limit_angular); + + ClassDB::bind_method(D_METHOD("_set_lower_limit_angular", "lower_limit_angular"), &SliderJoint::_set_lower_limit_angular); + ClassDB::bind_method(D_METHOD("_get_lower_limit_angular"), &SliderJoint::_get_lower_limit_angular); + + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/upper_distance", PROPERTY_HINT_RANGE, "-1024,1024,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_UPPER); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/lower_distance", PROPERTY_HINT_RANGE, "-1024,1024,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_LOWER); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_motion/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_motion/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_motion/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_ortho/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_ortho/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_ortho/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_DAMPING); + + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_upper_limit_angular", "_get_upper_limit_angular"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_lower_limit_angular", "_get_lower_limit_angular"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motion/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motion/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motion/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_ortho/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_ortho/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_ortho/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_DAMPING); + + BIND_CONSTANT(PARAM_LINEAR_LIMIT_UPPER); + BIND_CONSTANT(PARAM_LINEAR_LIMIT_LOWER); + BIND_CONSTANT(PARAM_LINEAR_LIMIT_SOFTNESS); + BIND_CONSTANT(PARAM_LINEAR_LIMIT_RESTITUTION); + BIND_CONSTANT(PARAM_LINEAR_LIMIT_DAMPING); + BIND_CONSTANT(PARAM_LINEAR_MOTION_SOFTNESS); + BIND_CONSTANT(PARAM_LINEAR_MOTION_RESTITUTION); + BIND_CONSTANT(PARAM_LINEAR_MOTION_DAMPING); + BIND_CONSTANT(PARAM_LINEAR_ORTHOGONAL_SOFTNESS); + BIND_CONSTANT(PARAM_LINEAR_ORTHOGONAL_RESTITUTION); + BIND_CONSTANT(PARAM_LINEAR_ORTHOGONAL_DAMPING); + + BIND_CONSTANT(PARAM_ANGULAR_LIMIT_UPPER); + BIND_CONSTANT(PARAM_ANGULAR_LIMIT_LOWER); + BIND_CONSTANT(PARAM_ANGULAR_LIMIT_SOFTNESS); + BIND_CONSTANT(PARAM_ANGULAR_LIMIT_RESTITUTION); + BIND_CONSTANT(PARAM_ANGULAR_LIMIT_DAMPING); + BIND_CONSTANT(PARAM_ANGULAR_MOTION_SOFTNESS); + BIND_CONSTANT(PARAM_ANGULAR_MOTION_RESTITUTION); + BIND_CONSTANT(PARAM_ANGULAR_MOTION_DAMPING); + BIND_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_SOFTNESS); + BIND_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_RESTITUTION); + BIND_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_DAMPING); + + BIND_CONSTANT(PARAM_MAX); +} + +void SliderJoint::set_param(Param p_param, float p_value) { + + ERR_FAIL_INDEX(p_param, PARAM_MAX); + params[p_param] = p_value; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->slider_joint_set_param(get_joint(),PhysicsServer::SliderJointParam(p_param),p_value); + PhysicsServer::get_singleton()->slider_joint_set_param(get_joint(), PhysicsServer::SliderJointParam(p_param), p_value); update_gizmo(); - } -float SliderJoint::get_param(Param p_param) const{ +float SliderJoint::get_param(Param p_param) const { - ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); + ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return params[p_param]; } - -RID SliderJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) { - +RID SliderJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) { Transform gt = get_global_transform(); Transform ainv = body_a->get_global_transform().affine_inverse(); @@ -543,53 +484,46 @@ RID SliderJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) { local_b.orthonormalize(); - RID j = PhysicsServer::get_singleton()->joint_create_slider(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b); - for(int i=0;islider_joint_set_param(j,PhysicsServer::SliderJointParam(i),params[i]); + RID j = PhysicsServer::get_singleton()->joint_create_slider(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b); + for (int i = 0; i < PARAM_MAX; i++) { + PhysicsServer::get_singleton()->slider_joint_set_param(j, PhysicsServer::SliderJointParam(i), params[i]); } return j; } - SliderJoint::SliderJoint() { - - - params[ PARAM_LINEAR_LIMIT_UPPER ]=1.0; - params[ PARAM_LINEAR_LIMIT_LOWER ]=-1.0; - params[ PARAM_LINEAR_LIMIT_SOFTNESS ]=1.0; - params[ PARAM_LINEAR_LIMIT_RESTITUTION]=0.7; - params[ PARAM_LINEAR_LIMIT_DAMPING]=1.0; - params[ PARAM_LINEAR_MOTION_SOFTNESS ]=1.0; - params[ PARAM_LINEAR_MOTION_RESTITUTION]=0.7; - params[ PARAM_LINEAR_MOTION_DAMPING]=0;//1.0; - params[ PARAM_LINEAR_ORTHOGONAL_SOFTNESS ]=1.0; - params[ PARAM_LINEAR_ORTHOGONAL_RESTITUTION]=0.7; - params[ PARAM_LINEAR_ORTHOGONAL_DAMPING]=1.0; - - params[ PARAM_ANGULAR_LIMIT_UPPER ]=0 ; - params[ PARAM_ANGULAR_LIMIT_LOWER ]=0 ; - params[ PARAM_ANGULAR_LIMIT_SOFTNESS ]=1.0; - params[ PARAM_ANGULAR_LIMIT_RESTITUTION]=0.7; - params[ PARAM_ANGULAR_LIMIT_DAMPING]=0;//1.0; - params[ PARAM_ANGULAR_MOTION_SOFTNESS ]=1.0; - params[ PARAM_ANGULAR_MOTION_RESTITUTION]=0.7; - params[ PARAM_ANGULAR_MOTION_DAMPING]=1.0; - params[ PARAM_ANGULAR_ORTHOGONAL_SOFTNESS ]=1.0; - params[ PARAM_ANGULAR_ORTHOGONAL_RESTITUTION]=0.7; - params[ PARAM_ANGULAR_ORTHOGONAL_DAMPING]=1.0; + params[PARAM_LINEAR_LIMIT_UPPER] = 1.0; + params[PARAM_LINEAR_LIMIT_LOWER] = -1.0; + params[PARAM_LINEAR_LIMIT_SOFTNESS] = 1.0; + params[PARAM_LINEAR_LIMIT_RESTITUTION] = 0.7; + params[PARAM_LINEAR_LIMIT_DAMPING] = 1.0; + params[PARAM_LINEAR_MOTION_SOFTNESS] = 1.0; + params[PARAM_LINEAR_MOTION_RESTITUTION] = 0.7; + params[PARAM_LINEAR_MOTION_DAMPING] = 0; //1.0; + params[PARAM_LINEAR_ORTHOGONAL_SOFTNESS] = 1.0; + params[PARAM_LINEAR_ORTHOGONAL_RESTITUTION] = 0.7; + params[PARAM_LINEAR_ORTHOGONAL_DAMPING] = 1.0; + + params[PARAM_ANGULAR_LIMIT_UPPER] = 0; + params[PARAM_ANGULAR_LIMIT_LOWER] = 0; + params[PARAM_ANGULAR_LIMIT_SOFTNESS] = 1.0; + params[PARAM_ANGULAR_LIMIT_RESTITUTION] = 0.7; + params[PARAM_ANGULAR_LIMIT_DAMPING] = 0; //1.0; + params[PARAM_ANGULAR_MOTION_SOFTNESS] = 1.0; + params[PARAM_ANGULAR_MOTION_RESTITUTION] = 0.7; + params[PARAM_ANGULAR_MOTION_DAMPING] = 1.0; + params[PARAM_ANGULAR_ORTHOGONAL_SOFTNESS] = 1.0; + params[PARAM_ANGULAR_ORTHOGONAL_RESTITUTION] = 0.7; + params[PARAM_ANGULAR_ORTHOGONAL_DAMPING] = 1.0; } - - ////////////////////////////////// - - void ConeTwistJoint::_set_swing_span(float p_limit_angular) { - set_param(PARAM_SWING_SPAN,Math::deg2rad(p_limit_angular)); + set_param(PARAM_SWING_SPAN, Math::deg2rad(p_limit_angular)); } float ConeTwistJoint::_get_swing_span() const { @@ -599,64 +533,56 @@ float ConeTwistJoint::_get_swing_span() const { void ConeTwistJoint::_set_twist_span(float p_limit_angular) { - set_param(PARAM_TWIST_SPAN,Math::deg2rad(p_limit_angular)); - + set_param(PARAM_TWIST_SPAN, Math::deg2rad(p_limit_angular)); } float ConeTwistJoint::_get_twist_span() const { return Math::rad2deg(get_param(PARAM_TWIST_SPAN)); - } - void ConeTwistJoint::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_param","param","value"),&ConeTwistJoint::set_param); - ClassDB::bind_method(D_METHOD("get_param","param"),&ConeTwistJoint::get_param); - + ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &ConeTwistJoint::set_param); + ClassDB::bind_method(D_METHOD("get_param", "param"), &ConeTwistJoint::get_param); - ClassDB::bind_method(D_METHOD("_set_swing_span","swing_span"),&ConeTwistJoint::_set_swing_span); - ClassDB::bind_method(D_METHOD("_get_swing_span"),&ConeTwistJoint::_get_swing_span); + ClassDB::bind_method(D_METHOD("_set_swing_span", "swing_span"), &ConeTwistJoint::_set_swing_span); + ClassDB::bind_method(D_METHOD("_get_swing_span"), &ConeTwistJoint::_get_swing_span); - ClassDB::bind_method(D_METHOD("_set_twist_span","twist_span"),&ConeTwistJoint::_set_twist_span); - ClassDB::bind_method(D_METHOD("_get_twist_span"),&ConeTwistJoint::_get_twist_span); + ClassDB::bind_method(D_METHOD("_set_twist_span", "twist_span"), &ConeTwistJoint::_set_twist_span); + ClassDB::bind_method(D_METHOD("_get_twist_span"), &ConeTwistJoint::_get_twist_span); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "swing_span", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_swing_span", "_get_swing_span"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "twist_span", PROPERTY_HINT_RANGE, "-40000,40000,0.1"), "_set_twist_span", "_get_twist_span"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"swing_span",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_swing_span","_get_swing_span") ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"twist_span",PROPERTY_HINT_RANGE,"-40000,40000,0.1"),"_set_twist_span","_get_twist_span") ; + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_BIAS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "relaxation", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_RELAXATION); - - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"bias",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_BIAS ); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_SOFTNESS); - ADD_PROPERTYI( PropertyInfo(Variant::REAL,"relaxation",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_RELAXATION); - - BIND_CONSTANT( PARAM_SWING_SPAN ); - BIND_CONSTANT( PARAM_TWIST_SPAN ); - BIND_CONSTANT( PARAM_BIAS ); - BIND_CONSTANT( PARAM_SOFTNESS ); - BIND_CONSTANT( PARAM_RELAXATION ); - BIND_CONSTANT( PARAM_MAX ); + BIND_CONSTANT(PARAM_SWING_SPAN); + BIND_CONSTANT(PARAM_TWIST_SPAN); + BIND_CONSTANT(PARAM_BIAS); + BIND_CONSTANT(PARAM_SOFTNESS); + BIND_CONSTANT(PARAM_RELAXATION); + BIND_CONSTANT(PARAM_MAX); } -void ConeTwistJoint::set_param(Param p_param,float p_value){ +void ConeTwistJoint::set_param(Param p_param, float p_value) { - ERR_FAIL_INDEX(p_param,PARAM_MAX); - params[p_param]=p_value; + ERR_FAIL_INDEX(p_param, PARAM_MAX); + params[p_param] = p_value; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->cone_twist_joint_set_param(get_joint(),PhysicsServer::ConeTwistJointParam(p_param),p_value); + PhysicsServer::get_singleton()->cone_twist_joint_set_param(get_joint(), PhysicsServer::ConeTwistJointParam(p_param), p_value); update_gizmo(); } -float ConeTwistJoint::get_param(Param p_param) const{ +float ConeTwistJoint::get_param(Param p_param) const { - ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); + ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return params[p_param]; } - -RID ConeTwistJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) { - +RID ConeTwistJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) { Transform gt = get_global_transform(); //Vector3 cone_twistpos = gt.origin; @@ -675,311 +601,285 @@ RID ConeTwistJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) { local_b.orthonormalize(); - RID j = PhysicsServer::get_singleton()->joint_create_cone_twist(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b); - for(int i=0;icone_twist_joint_set_param(j,PhysicsServer::ConeTwistJointParam(i),params[i]); + RID j = PhysicsServer::get_singleton()->joint_create_cone_twist(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b); + for (int i = 0; i < PARAM_MAX; i++) { + PhysicsServer::get_singleton()->cone_twist_joint_set_param(j, PhysicsServer::ConeTwistJointParam(i), params[i]); } return j; } - ConeTwistJoint::ConeTwistJoint() { - - params[ PARAM_SWING_SPAN ]=Math_PI*0.25; - params[ PARAM_TWIST_SPAN ]=Math_PI; - params[ PARAM_BIAS ]=0.3; - params[ PARAM_SOFTNESS ]=0.8; - params[ PARAM_RELAXATION ]=1.0; - + params[PARAM_SWING_SPAN] = Math_PI * 0.25; + params[PARAM_TWIST_SPAN] = Math_PI; + params[PARAM_BIAS] = 0.3; + params[PARAM_SOFTNESS] = 0.8; + params[PARAM_RELAXATION] = 1.0; } ///////////////////////////////////////////////////////////////////// - void Generic6DOFJoint::_set_angular_hi_limit_x(float p_limit_angular) { - set_param_x(PARAM_ANGULAR_UPPER_LIMIT,Math::deg2rad(p_limit_angular)); + set_param_x(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular)); } -float Generic6DOFJoint::_get_angular_hi_limit_x() const{ +float Generic6DOFJoint::_get_angular_hi_limit_x() const { return Math::rad2deg(get_param_x(PARAM_ANGULAR_UPPER_LIMIT)); - } void Generic6DOFJoint::_set_angular_lo_limit_x(float p_limit_angular) { - set_param_x(PARAM_ANGULAR_LOWER_LIMIT,Math::deg2rad(p_limit_angular)); + set_param_x(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular)); } -float Generic6DOFJoint::_get_angular_lo_limit_x() const{ +float Generic6DOFJoint::_get_angular_lo_limit_x() const { return Math::rad2deg(get_param_x(PARAM_ANGULAR_LOWER_LIMIT)); - } - void Generic6DOFJoint::_set_angular_hi_limit_y(float p_limit_angular) { - set_param_y(PARAM_ANGULAR_UPPER_LIMIT,Math::deg2rad(p_limit_angular)); + set_param_y(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular)); } -float Generic6DOFJoint::_get_angular_hi_limit_y() const{ +float Generic6DOFJoint::_get_angular_hi_limit_y() const { return Math::rad2deg(get_param_y(PARAM_ANGULAR_UPPER_LIMIT)); - } void Generic6DOFJoint::_set_angular_lo_limit_y(float p_limit_angular) { - set_param_y(PARAM_ANGULAR_LOWER_LIMIT,Math::deg2rad(p_limit_angular)); + set_param_y(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular)); } -float Generic6DOFJoint::_get_angular_lo_limit_y() const{ +float Generic6DOFJoint::_get_angular_lo_limit_y() const { return Math::rad2deg(get_param_y(PARAM_ANGULAR_LOWER_LIMIT)); - } - void Generic6DOFJoint::_set_angular_hi_limit_z(float p_limit_angular) { - set_param_z(PARAM_ANGULAR_UPPER_LIMIT,Math::deg2rad(p_limit_angular)); + set_param_z(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular)); } -float Generic6DOFJoint::_get_angular_hi_limit_z() const{ +float Generic6DOFJoint::_get_angular_hi_limit_z() const { return Math::rad2deg(get_param_z(PARAM_ANGULAR_UPPER_LIMIT)); - } void Generic6DOFJoint::_set_angular_lo_limit_z(float p_limit_angular) { - set_param_z(PARAM_ANGULAR_LOWER_LIMIT,Math::deg2rad(p_limit_angular)); + set_param_z(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular)); } -float Generic6DOFJoint::_get_angular_lo_limit_z() const{ +float Generic6DOFJoint::_get_angular_lo_limit_z() const { return Math::rad2deg(get_param_z(PARAM_ANGULAR_LOWER_LIMIT)); - } - - -void Generic6DOFJoint::_bind_methods(){ - - - ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_x","angle"),&Generic6DOFJoint::_set_angular_hi_limit_x); - ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_x"),&Generic6DOFJoint::_get_angular_hi_limit_x); - - ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_x","angle"),&Generic6DOFJoint::_set_angular_lo_limit_x); - ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_x"),&Generic6DOFJoint::_get_angular_lo_limit_x); - - ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_y","angle"),&Generic6DOFJoint::_set_angular_hi_limit_y); - ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_y"),&Generic6DOFJoint::_get_angular_hi_limit_y); - - ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_y","angle"),&Generic6DOFJoint::_set_angular_lo_limit_y); - ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_y"),&Generic6DOFJoint::_get_angular_lo_limit_y); - - ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_z","angle"),&Generic6DOFJoint::_set_angular_hi_limit_z); - ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_z"),&Generic6DOFJoint::_get_angular_hi_limit_z); - - ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_z","angle"),&Generic6DOFJoint::_set_angular_lo_limit_z); - ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_z"),&Generic6DOFJoint::_get_angular_lo_limit_z); - - ClassDB::bind_method(D_METHOD("set_param_x","param","value"),&Generic6DOFJoint::set_param_x); - ClassDB::bind_method(D_METHOD("get_param_x","param"),&Generic6DOFJoint::get_param_x); - - ClassDB::bind_method(D_METHOD("set_param_y","param","value"),&Generic6DOFJoint::set_param_y); - ClassDB::bind_method(D_METHOD("get_param_y","param"),&Generic6DOFJoint::get_param_y); - - ClassDB::bind_method(D_METHOD("set_param_z","param","value"),&Generic6DOFJoint::set_param_z); - ClassDB::bind_method(D_METHOD("get_param_z","param"),&Generic6DOFJoint::get_param_z); - - ClassDB::bind_method(D_METHOD("set_flag_x","flag","value"),&Generic6DOFJoint::set_flag_x); - ClassDB::bind_method(D_METHOD("get_flag_x","flag"),&Generic6DOFJoint::get_flag_x); - - ClassDB::bind_method(D_METHOD("set_flag_y","flag","value"),&Generic6DOFJoint::set_flag_y); - ClassDB::bind_method(D_METHOD("get_flag_y","flag"),&Generic6DOFJoint::get_flag_y); - - ClassDB::bind_method(D_METHOD("set_flag_z","flag","value"),&Generic6DOFJoint::set_flag_z); - ClassDB::bind_method(D_METHOD("get_flag_z","flag"),&Generic6DOFJoint::get_flag_z); - - - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"linear_limit_x/enabled"),"set_flag_x","get_flag_x",FLAG_ENABLE_LINEAR_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/upper_distance"),"set_param_x","get_param_x",PARAM_LINEAR_UPPER_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/lower_distance"),"set_param_x","get_param_x",PARAM_LINEAR_LOWER_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_LINEAR_LIMIT_SOFTNESS); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_LINEAR_RESTITUTION); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_LINEAR_DAMPING); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_limit_x/enabled"),"set_flag_x","get_flag_x",FLAG_ENABLE_ANGULAR_LIMIT); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_x/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_hi_limit_x","_get_angular_hi_limit_x"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_x/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_lo_limit_x","_get_angular_lo_limit_x"); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_ANGULAR_LIMIT_SOFTNESS); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_ANGULAR_RESTITUTION); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_ANGULAR_DAMPING); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/force_limit"),"set_param_x","get_param_x",PARAM_ANGULAR_FORCE_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/erp"),"set_param_x","get_param_x",PARAM_ANGULAR_ERP); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_motor_x/enabled"),"set_flag_x","get_flag_x",FLAG_ENABLE_MOTOR); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_x/target_velocity"),"set_param_x","get_param_x",PARAM_ANGULAR_MOTOR_TARGET_VELOCITY); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_x/force_limit"),"set_param_x","get_param_x",PARAM_ANGULAR_MOTOR_FORCE_LIMIT); - - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"linear_limit_y/enabled"),"set_flag_y","get_flag_y",FLAG_ENABLE_LINEAR_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/upper_distance"),"set_param_y","get_param_y",PARAM_LINEAR_UPPER_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/lower_distance"),"set_param_y","get_param_y",PARAM_LINEAR_LOWER_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_LINEAR_LIMIT_SOFTNESS); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_LINEAR_RESTITUTION); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_LINEAR_DAMPING); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_limit_y/enabled"),"set_flag_y","get_flag_y",FLAG_ENABLE_ANGULAR_LIMIT); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_y/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_hi_limit_y","_get_angular_hi_limit_y"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_y/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_lo_limit_y","_get_angular_lo_limit_y"); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_ANGULAR_LIMIT_SOFTNESS); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_ANGULAR_RESTITUTION); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_ANGULAR_DAMPING); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/force_limit"),"set_param_y","get_param_y",PARAM_ANGULAR_FORCE_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/erp"),"set_param_y","get_param_y",PARAM_ANGULAR_ERP); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_motor_y/enabled"),"set_flag_y","get_flag_y",FLAG_ENABLE_MOTOR); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_y/target_velocity"),"set_param_y","get_param_y",PARAM_ANGULAR_MOTOR_TARGET_VELOCITY); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_y/force_limit"),"set_param_y","get_param_y",PARAM_ANGULAR_MOTOR_FORCE_LIMIT); - - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"linear_limit_z/enabled"),"set_flag_z","get_flag_z",FLAG_ENABLE_LINEAR_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/upper_distance"),"set_param_z","get_param_z",PARAM_LINEAR_UPPER_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/lower_distance"),"set_param_z","get_param_z",PARAM_LINEAR_LOWER_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_LINEAR_LIMIT_SOFTNESS); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_LINEAR_RESTITUTION); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_LINEAR_DAMPING); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_limit_z/enabled"),"set_flag_z","get_flag_z",FLAG_ENABLE_ANGULAR_LIMIT); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_z/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_hi_limit_z","_get_angular_hi_limit_z"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_z/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_lo_limit_z","_get_angular_lo_limit_z"); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_ANGULAR_LIMIT_SOFTNESS); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_ANGULAR_RESTITUTION); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_ANGULAR_DAMPING); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/force_limit"),"set_param_z","get_param_z",PARAM_ANGULAR_FORCE_LIMIT); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/erp"),"set_param_z","get_param_z",PARAM_ANGULAR_ERP); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_motor_z/enabled"),"set_flag_z","get_flag_z",FLAG_ENABLE_MOTOR); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_z/target_velocity"),"set_param_z","get_param_z",PARAM_ANGULAR_MOTOR_TARGET_VELOCITY); - ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_z/force_limit"),"set_param_z","get_param_z",PARAM_ANGULAR_MOTOR_FORCE_LIMIT); - - - BIND_CONSTANT( PARAM_LINEAR_LOWER_LIMIT); - BIND_CONSTANT( PARAM_LINEAR_UPPER_LIMIT); - BIND_CONSTANT( PARAM_LINEAR_LIMIT_SOFTNESS); - BIND_CONSTANT( PARAM_LINEAR_RESTITUTION); - BIND_CONSTANT( PARAM_LINEAR_DAMPING); - BIND_CONSTANT( PARAM_ANGULAR_LOWER_LIMIT); - BIND_CONSTANT( PARAM_ANGULAR_UPPER_LIMIT); - BIND_CONSTANT( PARAM_ANGULAR_LIMIT_SOFTNESS); - BIND_CONSTANT( PARAM_ANGULAR_DAMPING); - BIND_CONSTANT( PARAM_ANGULAR_RESTITUTION); - BIND_CONSTANT( PARAM_ANGULAR_FORCE_LIMIT); - BIND_CONSTANT( PARAM_ANGULAR_ERP); - BIND_CONSTANT( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY); - BIND_CONSTANT( PARAM_ANGULAR_MOTOR_FORCE_LIMIT); - BIND_CONSTANT( PARAM_MAX); - - BIND_CONSTANT( FLAG_ENABLE_LINEAR_LIMIT); - BIND_CONSTANT( FLAG_ENABLE_ANGULAR_LIMIT); - BIND_CONSTANT( FLAG_ENABLE_MOTOR); - BIND_CONSTANT( FLAG_MAX ); -} - - -void Generic6DOFJoint::set_param_x(Param p_param,float p_value){ - - ERR_FAIL_INDEX(p_param,PARAM_MAX); - params_x[p_param]=p_value; +void Generic6DOFJoint::_bind_methods() { + + ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_x", "angle"), &Generic6DOFJoint::_set_angular_hi_limit_x); + ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_x"), &Generic6DOFJoint::_get_angular_hi_limit_x); + + ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_x", "angle"), &Generic6DOFJoint::_set_angular_lo_limit_x); + ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_x"), &Generic6DOFJoint::_get_angular_lo_limit_x); + + ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_y", "angle"), &Generic6DOFJoint::_set_angular_hi_limit_y); + ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_y"), &Generic6DOFJoint::_get_angular_hi_limit_y); + + ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_y", "angle"), &Generic6DOFJoint::_set_angular_lo_limit_y); + ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_y"), &Generic6DOFJoint::_get_angular_lo_limit_y); + + ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_z", "angle"), &Generic6DOFJoint::_set_angular_hi_limit_z); + ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_z"), &Generic6DOFJoint::_get_angular_hi_limit_z); + + ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_z", "angle"), &Generic6DOFJoint::_set_angular_lo_limit_z); + ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_z"), &Generic6DOFJoint::_get_angular_lo_limit_z); + + ClassDB::bind_method(D_METHOD("set_param_x", "param", "value"), &Generic6DOFJoint::set_param_x); + ClassDB::bind_method(D_METHOD("get_param_x", "param"), &Generic6DOFJoint::get_param_x); + + ClassDB::bind_method(D_METHOD("set_param_y", "param", "value"), &Generic6DOFJoint::set_param_y); + ClassDB::bind_method(D_METHOD("get_param_y", "param"), &Generic6DOFJoint::get_param_y); + + ClassDB::bind_method(D_METHOD("set_param_z", "param", "value"), &Generic6DOFJoint::set_param_z); + ClassDB::bind_method(D_METHOD("get_param_z", "param"), &Generic6DOFJoint::get_param_z); + + ClassDB::bind_method(D_METHOD("set_flag_x", "flag", "value"), &Generic6DOFJoint::set_flag_x); + ClassDB::bind_method(D_METHOD("get_flag_x", "flag"), &Generic6DOFJoint::get_flag_x); + + ClassDB::bind_method(D_METHOD("set_flag_y", "flag", "value"), &Generic6DOFJoint::set_flag_y); + ClassDB::bind_method(D_METHOD("get_flag_y", "flag"), &Generic6DOFJoint::get_flag_y); + + ClassDB::bind_method(D_METHOD("set_flag_z", "flag", "value"), &Generic6DOFJoint::set_flag_z); + ClassDB::bind_method(D_METHOD("get_flag_z", "flag"), &Generic6DOFJoint::get_flag_z); + + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "linear_limit_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_LINEAR_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/upper_distance"), "set_param_x", "get_param_x", PARAM_LINEAR_UPPER_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/lower_distance"), "set_param_x", "get_param_x", PARAM_LINEAR_LOWER_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_LINEAR_LIMIT_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_LINEAR_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_LINEAR_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_ANGULAR_LIMIT); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_x/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_x", "_get_angular_hi_limit_x"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_x/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_x", "_get_angular_lo_limit_x"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_LIMIT_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/force_limit"), "set_param_x", "get_param_x", PARAM_ANGULAR_FORCE_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/erp"), "set_param_x", "get_param_x", PARAM_ANGULAR_ERP); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_motor_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_MOTOR); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_x/target_velocity"), "set_param_x", "get_param_x", PARAM_ANGULAR_MOTOR_TARGET_VELOCITY); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_x/force_limit"), "set_param_x", "get_param_x", PARAM_ANGULAR_MOTOR_FORCE_LIMIT); + + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "linear_limit_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_LINEAR_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/upper_distance"), "set_param_y", "get_param_y", PARAM_LINEAR_UPPER_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/lower_distance"), "set_param_y", "get_param_y", PARAM_LINEAR_LOWER_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_LINEAR_LIMIT_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_LINEAR_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_LINEAR_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_ANGULAR_LIMIT); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_y/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_y", "_get_angular_hi_limit_y"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_y/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_y", "_get_angular_lo_limit_y"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_LIMIT_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/force_limit"), "set_param_y", "get_param_y", PARAM_ANGULAR_FORCE_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/erp"), "set_param_y", "get_param_y", PARAM_ANGULAR_ERP); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_motor_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_MOTOR); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_y/target_velocity"), "set_param_y", "get_param_y", PARAM_ANGULAR_MOTOR_TARGET_VELOCITY); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_y/force_limit"), "set_param_y", "get_param_y", PARAM_ANGULAR_MOTOR_FORCE_LIMIT); + + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "linear_limit_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_LINEAR_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/upper_distance"), "set_param_z", "get_param_z", PARAM_LINEAR_UPPER_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/lower_distance"), "set_param_z", "get_param_z", PARAM_LINEAR_LOWER_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_LINEAR_LIMIT_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_LINEAR_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_LINEAR_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_ANGULAR_LIMIT); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_z/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_z", "_get_angular_hi_limit_z"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_z/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_z", "_get_angular_lo_limit_z"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_LIMIT_SOFTNESS); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_RESTITUTION); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_DAMPING); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/force_limit"), "set_param_z", "get_param_z", PARAM_ANGULAR_FORCE_LIMIT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/erp"), "set_param_z", "get_param_z", PARAM_ANGULAR_ERP); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_motor_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_MOTOR); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_z/target_velocity"), "set_param_z", "get_param_z", PARAM_ANGULAR_MOTOR_TARGET_VELOCITY); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_z/force_limit"), "set_param_z", "get_param_z", PARAM_ANGULAR_MOTOR_FORCE_LIMIT); + + BIND_CONSTANT(PARAM_LINEAR_LOWER_LIMIT); + BIND_CONSTANT(PARAM_LINEAR_UPPER_LIMIT); + BIND_CONSTANT(PARAM_LINEAR_LIMIT_SOFTNESS); + BIND_CONSTANT(PARAM_LINEAR_RESTITUTION); + BIND_CONSTANT(PARAM_LINEAR_DAMPING); + BIND_CONSTANT(PARAM_ANGULAR_LOWER_LIMIT); + BIND_CONSTANT(PARAM_ANGULAR_UPPER_LIMIT); + BIND_CONSTANT(PARAM_ANGULAR_LIMIT_SOFTNESS); + BIND_CONSTANT(PARAM_ANGULAR_DAMPING); + BIND_CONSTANT(PARAM_ANGULAR_RESTITUTION); + BIND_CONSTANT(PARAM_ANGULAR_FORCE_LIMIT); + BIND_CONSTANT(PARAM_ANGULAR_ERP); + BIND_CONSTANT(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY); + BIND_CONSTANT(PARAM_ANGULAR_MOTOR_FORCE_LIMIT); + BIND_CONSTANT(PARAM_MAX); + + BIND_CONSTANT(FLAG_ENABLE_LINEAR_LIMIT); + BIND_CONSTANT(FLAG_ENABLE_ANGULAR_LIMIT); + BIND_CONSTANT(FLAG_ENABLE_MOTOR); + BIND_CONSTANT(FLAG_MAX); +} + +void Generic6DOFJoint::set_param_x(Param p_param, float p_value) { + + ERR_FAIL_INDEX(p_param, PARAM_MAX); + params_x[p_param] = p_value; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(),Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisParam(p_param),p_value); + PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisParam(p_param), p_value); update_gizmo(); } -float Generic6DOFJoint::get_param_x(Param p_param) const{ +float Generic6DOFJoint::get_param_x(Param p_param) const { - ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); + ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return params_x[p_param]; } -void Generic6DOFJoint::set_param_y(Param p_param,float p_value){ +void Generic6DOFJoint::set_param_y(Param p_param, float p_value) { - ERR_FAIL_INDEX(p_param,PARAM_MAX); - params_y[p_param]=p_value; + ERR_FAIL_INDEX(p_param, PARAM_MAX); + params_y[p_param] = p_value; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(),Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisParam(p_param),p_value); + PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisParam(p_param), p_value); update_gizmo(); - } -float Generic6DOFJoint::get_param_y(Param p_param) const{ +float Generic6DOFJoint::get_param_y(Param p_param) const { - ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); + ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return params_y[p_param]; } +void Generic6DOFJoint::set_param_z(Param p_param, float p_value) { -void Generic6DOFJoint::set_param_z(Param p_param,float p_value){ - - ERR_FAIL_INDEX(p_param,PARAM_MAX); - params_z[p_param]=p_value; + ERR_FAIL_INDEX(p_param, PARAM_MAX); + params_z[p_param] = p_value; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(),Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisParam(p_param),p_value); + PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisParam(p_param), p_value); update_gizmo(); } -float Generic6DOFJoint::get_param_z(Param p_param) const{ +float Generic6DOFJoint::get_param_z(Param p_param) const { - ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); + ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return params_z[p_param]; } +void Generic6DOFJoint::set_flag_x(Flag p_flag, bool p_enabled) { -void Generic6DOFJoint::set_flag_x(Flag p_flag,bool p_enabled){ - - ERR_FAIL_INDEX(p_flag,FLAG_MAX); - flags_x[p_flag]=p_enabled; + ERR_FAIL_INDEX(p_flag, FLAG_MAX); + flags_x[p_flag] = p_enabled; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(),Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisFlag(p_flag),p_enabled); + PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisFlag(p_flag), p_enabled); update_gizmo(); - } -bool Generic6DOFJoint::get_flag_x(Flag p_flag) const{ +bool Generic6DOFJoint::get_flag_x(Flag p_flag) const { - ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false); + ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false); return flags_x[p_flag]; - } -void Generic6DOFJoint::set_flag_y(Flag p_flag,bool p_enabled){ +void Generic6DOFJoint::set_flag_y(Flag p_flag, bool p_enabled) { - ERR_FAIL_INDEX(p_flag,FLAG_MAX); - flags_y[p_flag]=p_enabled; + ERR_FAIL_INDEX(p_flag, FLAG_MAX); + flags_y[p_flag] = p_enabled; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(),Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisFlag(p_flag),p_enabled); + PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisFlag(p_flag), p_enabled); update_gizmo(); } -bool Generic6DOFJoint::get_flag_y(Flag p_flag) const{ +bool Generic6DOFJoint::get_flag_y(Flag p_flag) const { - ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false); + ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false); return flags_y[p_flag]; - } -void Generic6DOFJoint::set_flag_z(Flag p_flag,bool p_enabled){ +void Generic6DOFJoint::set_flag_z(Flag p_flag, bool p_enabled) { - ERR_FAIL_INDEX(p_flag,FLAG_MAX); - flags_z[p_flag]=p_enabled; + ERR_FAIL_INDEX(p_flag, FLAG_MAX); + flags_z[p_flag] = p_enabled; if (get_joint().is_valid()) - PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(),Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisFlag(p_flag),p_enabled); + PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisFlag(p_flag), p_enabled); update_gizmo(); } -bool Generic6DOFJoint::get_flag_z(Flag p_flag) const{ +bool Generic6DOFJoint::get_flag_z(Flag p_flag) const { - ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false); + ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false); return flags_z[p_flag]; - } -RID Generic6DOFJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) { - +RID Generic6DOFJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) { Transform gt = get_global_transform(); //Vector3 cone_twistpos = gt.origin; @@ -998,87 +898,81 @@ RID Generic6DOFJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) local_b.orthonormalize(); - RID j = PhysicsServer::get_singleton()->joint_create_generic_6dof(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b); - for(int i=0;igeneric_6dof_joint_set_param(j,Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisParam(i),params_x[i]); - PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j,Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisParam(i),params_y[i]); - PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j,Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisParam(i),params_z[i]); + RID j = PhysicsServer::get_singleton()->joint_create_generic_6dof(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b); + for (int i = 0; i < PARAM_MAX; i++) { + PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j, Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisParam(i), params_x[i]); + PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j, Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisParam(i), params_y[i]); + PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j, Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisParam(i), params_z[i]); } - for(int i=0;igeneric_6dof_joint_set_flag(j,Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisFlag(i),flags_x[i]); - PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j,Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisFlag(i),flags_y[i]); - PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j,Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisFlag(i),flags_z[i]); + for (int i = 0; i < FLAG_MAX; i++) { + PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j, Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisFlag(i), flags_x[i]); + PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j, Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisFlag(i), flags_y[i]); + PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j, Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisFlag(i), flags_z[i]); } return j; } - Generic6DOFJoint::Generic6DOFJoint() { - set_param_x( PARAM_LINEAR_LOWER_LIMIT,0); - set_param_x( PARAM_LINEAR_UPPER_LIMIT,0); - set_param_x( PARAM_LINEAR_LIMIT_SOFTNESS,0.7); - set_param_x( PARAM_LINEAR_RESTITUTION,0.5); - set_param_x( PARAM_LINEAR_DAMPING,1.0); - set_param_x( PARAM_ANGULAR_LOWER_LIMIT,0); - set_param_x( PARAM_ANGULAR_UPPER_LIMIT,0); - set_param_x( PARAM_ANGULAR_LIMIT_SOFTNESS,0.5f); - set_param_x( PARAM_ANGULAR_DAMPING,1.0f); - set_param_x( PARAM_ANGULAR_RESTITUTION,0); - set_param_x( PARAM_ANGULAR_FORCE_LIMIT,0); - set_param_x( PARAM_ANGULAR_ERP,0.5); - set_param_x( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY,0); - set_param_x( PARAM_ANGULAR_MOTOR_FORCE_LIMIT,300); - - set_flag_x( FLAG_ENABLE_ANGULAR_LIMIT,true); - set_flag_x( FLAG_ENABLE_LINEAR_LIMIT,true); - set_flag_x( FLAG_ENABLE_MOTOR,false); - - set_param_y( PARAM_LINEAR_LOWER_LIMIT,0); - set_param_y( PARAM_LINEAR_UPPER_LIMIT,0); - set_param_y( PARAM_LINEAR_LIMIT_SOFTNESS,0.7); - set_param_y( PARAM_LINEAR_RESTITUTION,0.5); - set_param_y( PARAM_LINEAR_DAMPING,1.0); - set_param_y( PARAM_ANGULAR_LOWER_LIMIT,0); - set_param_y( PARAM_ANGULAR_UPPER_LIMIT,0); - set_param_y( PARAM_ANGULAR_LIMIT_SOFTNESS,0.5f); - set_param_y( PARAM_ANGULAR_DAMPING,1.0f); - set_param_y( PARAM_ANGULAR_RESTITUTION,0); - set_param_y( PARAM_ANGULAR_FORCE_LIMIT,0); - set_param_y( PARAM_ANGULAR_ERP,0.5); - set_param_y( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY,0); - set_param_y( PARAM_ANGULAR_MOTOR_FORCE_LIMIT,300); - - set_flag_y( FLAG_ENABLE_ANGULAR_LIMIT,true); - set_flag_y( FLAG_ENABLE_LINEAR_LIMIT,true); - set_flag_y( FLAG_ENABLE_MOTOR,false); - - - set_param_z( PARAM_LINEAR_LOWER_LIMIT,0); - set_param_z( PARAM_LINEAR_UPPER_LIMIT,0); - set_param_z( PARAM_LINEAR_LIMIT_SOFTNESS,0.7); - set_param_z( PARAM_LINEAR_RESTITUTION,0.5); - set_param_z( PARAM_LINEAR_DAMPING,1.0); - set_param_z( PARAM_ANGULAR_LOWER_LIMIT,0); - set_param_z( PARAM_ANGULAR_UPPER_LIMIT,0); - set_param_z( PARAM_ANGULAR_LIMIT_SOFTNESS,0.5f); - set_param_z( PARAM_ANGULAR_DAMPING,1.0f); - set_param_z( PARAM_ANGULAR_RESTITUTION,0); - set_param_z( PARAM_ANGULAR_FORCE_LIMIT,0); - set_param_z( PARAM_ANGULAR_ERP,0.5); - set_param_z( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY,0); - set_param_z( PARAM_ANGULAR_MOTOR_FORCE_LIMIT,300); - - set_flag_z( FLAG_ENABLE_ANGULAR_LIMIT,true); - set_flag_z( FLAG_ENABLE_LINEAR_LIMIT,true); - set_flag_z( FLAG_ENABLE_MOTOR,false); - + set_param_x(PARAM_LINEAR_LOWER_LIMIT, 0); + set_param_x(PARAM_LINEAR_UPPER_LIMIT, 0); + set_param_x(PARAM_LINEAR_LIMIT_SOFTNESS, 0.7); + set_param_x(PARAM_LINEAR_RESTITUTION, 0.5); + set_param_x(PARAM_LINEAR_DAMPING, 1.0); + set_param_x(PARAM_ANGULAR_LOWER_LIMIT, 0); + set_param_x(PARAM_ANGULAR_UPPER_LIMIT, 0); + set_param_x(PARAM_ANGULAR_LIMIT_SOFTNESS, 0.5f); + set_param_x(PARAM_ANGULAR_DAMPING, 1.0f); + set_param_x(PARAM_ANGULAR_RESTITUTION, 0); + set_param_x(PARAM_ANGULAR_FORCE_LIMIT, 0); + set_param_x(PARAM_ANGULAR_ERP, 0.5); + set_param_x(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY, 0); + set_param_x(PARAM_ANGULAR_MOTOR_FORCE_LIMIT, 300); + + set_flag_x(FLAG_ENABLE_ANGULAR_LIMIT, true); + set_flag_x(FLAG_ENABLE_LINEAR_LIMIT, true); + set_flag_x(FLAG_ENABLE_MOTOR, false); + + set_param_y(PARAM_LINEAR_LOWER_LIMIT, 0); + set_param_y(PARAM_LINEAR_UPPER_LIMIT, 0); + set_param_y(PARAM_LINEAR_LIMIT_SOFTNESS, 0.7); + set_param_y(PARAM_LINEAR_RESTITUTION, 0.5); + set_param_y(PARAM_LINEAR_DAMPING, 1.0); + set_param_y(PARAM_ANGULAR_LOWER_LIMIT, 0); + set_param_y(PARAM_ANGULAR_UPPER_LIMIT, 0); + set_param_y(PARAM_ANGULAR_LIMIT_SOFTNESS, 0.5f); + set_param_y(PARAM_ANGULAR_DAMPING, 1.0f); + set_param_y(PARAM_ANGULAR_RESTITUTION, 0); + set_param_y(PARAM_ANGULAR_FORCE_LIMIT, 0); + set_param_y(PARAM_ANGULAR_ERP, 0.5); + set_param_y(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY, 0); + set_param_y(PARAM_ANGULAR_MOTOR_FORCE_LIMIT, 300); + + set_flag_y(FLAG_ENABLE_ANGULAR_LIMIT, true); + set_flag_y(FLAG_ENABLE_LINEAR_LIMIT, true); + set_flag_y(FLAG_ENABLE_MOTOR, false); + + set_param_z(PARAM_LINEAR_LOWER_LIMIT, 0); + set_param_z(PARAM_LINEAR_UPPER_LIMIT, 0); + set_param_z(PARAM_LINEAR_LIMIT_SOFTNESS, 0.7); + set_param_z(PARAM_LINEAR_RESTITUTION, 0.5); + set_param_z(PARAM_LINEAR_DAMPING, 1.0); + set_param_z(PARAM_ANGULAR_LOWER_LIMIT, 0); + set_param_z(PARAM_ANGULAR_UPPER_LIMIT, 0); + set_param_z(PARAM_ANGULAR_LIMIT_SOFTNESS, 0.5f); + set_param_z(PARAM_ANGULAR_DAMPING, 1.0f); + set_param_z(PARAM_ANGULAR_RESTITUTION, 0); + set_param_z(PARAM_ANGULAR_FORCE_LIMIT, 0); + set_param_z(PARAM_ANGULAR_ERP, 0.5); + set_param_z(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY, 0); + set_param_z(PARAM_ANGULAR_MOTOR_FORCE_LIMIT, 300); + + set_flag_z(FLAG_ENABLE_ANGULAR_LIMIT, true); + set_flag_z(FLAG_ENABLE_LINEAR_LIMIT, true); + set_flag_z(FLAG_ENABLE_MOTOR, false); } - - - #if 0 void PhysicsJoint::_set(const String& p_name, const Variant& p_value) { diff --git a/scene/3d/physics_joint.h b/scene/3d/physics_joint.h index 5debe87d3..90d86d652 100644 --- a/scene/3d/physics_joint.h +++ b/scene/3d/physics_joint.h @@ -29,15 +29,14 @@ #ifndef PHYSICS_JOINT_H #define PHYSICS_JOINT_H -#include "scene/3d/spatial.h" #include "scene/3d/physics_body.h" - +#include "scene/3d/spatial.h" class Joint : public Spatial { - GDCLASS(Joint,Spatial); + GDCLASS(Joint, Spatial); - RID ba,bb; + RID ba, bb; RID joint; @@ -47,22 +46,20 @@ class Joint : public Spatial { int solver_priority; bool exclude_from_collision; - protected: - - void _update_joint(bool p_only_free=false); + void _update_joint(bool p_only_free = false); void _notification(int p_what); - virtual RID _configure_joint(PhysicsBody *body_a,PhysicsBody *body_b)=0; + virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) = 0; static void _bind_methods(); -public: - void set_node_a(const NodePath& p_node_a); +public: + void set_node_a(const NodePath &p_node_a); NodePath get_node_a() const; - void set_node_b(const NodePath& p_node_b); + void set_node_b(const NodePath &p_node_b); NodePath get_node_b() const; void set_solver_priority(int p_priority); @@ -73,31 +70,28 @@ public: RID get_joint() const { return joint; } Joint(); - }; /////////////////////////////////////////// - class PinJoint : public Joint { - GDCLASS(PinJoint,Joint); -public: + GDCLASS(PinJoint, Joint); +public: enum Param { - PARAM_BIAS=PhysicsServer::PIN_JOINT_BIAS, - PARAM_DAMPING=PhysicsServer::PIN_JOINT_DAMPING, - PARAM_IMPULSE_CLAMP=PhysicsServer::PIN_JOINT_IMPULSE_CLAMP + PARAM_BIAS = PhysicsServer::PIN_JOINT_BIAS, + PARAM_DAMPING = PhysicsServer::PIN_JOINT_DAMPING, + PARAM_IMPULSE_CLAMP = PhysicsServer::PIN_JOINT_IMPULSE_CLAMP }; protected: - float params[3]; virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b); static void _bind_methods(); -public: - void set_param(Param p_param,float p_value); +public: + void set_param(Param p_param, float p_value); float get_param(Param p_param) const; PinJoint(); @@ -105,34 +99,30 @@ public: VARIANT_ENUM_CAST(PinJoint::Param); - class HingeJoint : public Joint { - GDCLASS(HingeJoint,Joint); -public: + GDCLASS(HingeJoint, Joint); +public: enum Param { - PARAM_BIAS=PhysicsServer::HINGE_JOINT_BIAS, - PARAM_LIMIT_UPPER=PhysicsServer::HINGE_JOINT_LIMIT_UPPER, - PARAM_LIMIT_LOWER=PhysicsServer::HINGE_JOINT_LIMIT_LOWER, - PARAM_LIMIT_BIAS=PhysicsServer::HINGE_JOINT_LIMIT_BIAS, - PARAM_LIMIT_SOFTNESS=PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS, - PARAM_LIMIT_RELAXATION=PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION, - PARAM_MOTOR_TARGET_VELOCITY=PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY, - PARAM_MOTOR_MAX_IMPULSE=PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE, - PARAM_MAX=PhysicsServer::HINGE_JOINT_MAX + PARAM_BIAS = PhysicsServer::HINGE_JOINT_BIAS, + PARAM_LIMIT_UPPER = PhysicsServer::HINGE_JOINT_LIMIT_UPPER, + PARAM_LIMIT_LOWER = PhysicsServer::HINGE_JOINT_LIMIT_LOWER, + PARAM_LIMIT_BIAS = PhysicsServer::HINGE_JOINT_LIMIT_BIAS, + PARAM_LIMIT_SOFTNESS = PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS, + PARAM_LIMIT_RELAXATION = PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION, + PARAM_MOTOR_TARGET_VELOCITY = PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY, + PARAM_MOTOR_MAX_IMPULSE = PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE, + PARAM_MAX = PhysicsServer::HINGE_JOINT_MAX }; enum Flag { - FLAG_USE_LIMIT=PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT, - FLAG_ENABLE_MOTOR=PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR, - FLAG_MAX=PhysicsServer::HINGE_JOINT_FLAG_MAX + FLAG_USE_LIMIT = PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT, + FLAG_ENABLE_MOTOR = PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR, + FLAG_MAX = PhysicsServer::HINGE_JOINT_FLAG_MAX }; - - protected: - float params[PARAM_MAX]; bool flags[FLAG_MAX]; virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b); @@ -145,11 +135,10 @@ protected: float _get_lower_limit() const; public: - - void set_param(Param p_param,float p_value); + void set_param(Param p_param, float p_value); float get_param(Param p_param) const; - void set_flag(Flag p_flag,bool p_value); + void set_flag(Flag p_flag, bool p_value); bool get_flag(Flag p_flag) const; HingeJoint(); @@ -158,44 +147,40 @@ public: VARIANT_ENUM_CAST(HingeJoint::Param); VARIANT_ENUM_CAST(HingeJoint::Flag); - class SliderJoint : public Joint { - GDCLASS(SliderJoint,Joint); -public: + GDCLASS(SliderJoint, Joint); +public: enum Param { - PARAM_LINEAR_LIMIT_UPPER=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER, - PARAM_LINEAR_LIMIT_LOWER=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER, - PARAM_LINEAR_LIMIT_SOFTNESS=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS, - PARAM_LINEAR_LIMIT_RESTITUTION=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION, - PARAM_LINEAR_LIMIT_DAMPING=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_DAMPING, - PARAM_LINEAR_MOTION_SOFTNESS=PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS, - PARAM_LINEAR_MOTION_RESTITUTION=PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION, - PARAM_LINEAR_MOTION_DAMPING=PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_DAMPING, - PARAM_LINEAR_ORTHOGONAL_SOFTNESS=PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS, - PARAM_LINEAR_ORTHOGONAL_RESTITUTION=PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION, - PARAM_LINEAR_ORTHOGONAL_DAMPING=PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING, - - PARAM_ANGULAR_LIMIT_UPPER=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_UPPER, - PARAM_ANGULAR_LIMIT_LOWER=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_LOWER, - PARAM_ANGULAR_LIMIT_SOFTNESS=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS, - PARAM_ANGULAR_LIMIT_RESTITUTION=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION, - PARAM_ANGULAR_LIMIT_DAMPING=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING, - PARAM_ANGULAR_MOTION_SOFTNESS=PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS, - PARAM_ANGULAR_MOTION_RESTITUTION=PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION, - PARAM_ANGULAR_MOTION_DAMPING=PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_DAMPING, - PARAM_ANGULAR_ORTHOGONAL_SOFTNESS=PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS, - PARAM_ANGULAR_ORTHOGONAL_RESTITUTION=PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION, - PARAM_ANGULAR_ORTHOGONAL_DAMPING=PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING, - PARAM_MAX=PhysicsServer::SLIDER_JOINT_MAX + PARAM_LINEAR_LIMIT_UPPER = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER, + PARAM_LINEAR_LIMIT_LOWER = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER, + PARAM_LINEAR_LIMIT_SOFTNESS = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS, + PARAM_LINEAR_LIMIT_RESTITUTION = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION, + PARAM_LINEAR_LIMIT_DAMPING = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_DAMPING, + PARAM_LINEAR_MOTION_SOFTNESS = PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS, + PARAM_LINEAR_MOTION_RESTITUTION = PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION, + PARAM_LINEAR_MOTION_DAMPING = PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_DAMPING, + PARAM_LINEAR_ORTHOGONAL_SOFTNESS = PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS, + PARAM_LINEAR_ORTHOGONAL_RESTITUTION = PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION, + PARAM_LINEAR_ORTHOGONAL_DAMPING = PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING, + + PARAM_ANGULAR_LIMIT_UPPER = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_UPPER, + PARAM_ANGULAR_LIMIT_LOWER = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_LOWER, + PARAM_ANGULAR_LIMIT_SOFTNESS = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS, + PARAM_ANGULAR_LIMIT_RESTITUTION = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION, + PARAM_ANGULAR_LIMIT_DAMPING = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING, + PARAM_ANGULAR_MOTION_SOFTNESS = PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS, + PARAM_ANGULAR_MOTION_RESTITUTION = PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION, + PARAM_ANGULAR_MOTION_DAMPING = PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_DAMPING, + PARAM_ANGULAR_ORTHOGONAL_SOFTNESS = PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS, + PARAM_ANGULAR_ORTHOGONAL_RESTITUTION = PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION, + PARAM_ANGULAR_ORTHOGONAL_DAMPING = PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING, + PARAM_MAX = PhysicsServer::SLIDER_JOINT_MAX }; protected: - - - void _set_upper_limit_angular(float p_limit_angular); float _get_upper_limit_angular() const; @@ -205,25 +190,21 @@ protected: float params[PARAM_MAX]; virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b); static void _bind_methods(); -public: - void set_param(Param p_param,float p_value); +public: + void set_param(Param p_param, float p_value); float get_param(Param p_param) const; SliderJoint(); }; - VARIANT_ENUM_CAST(SliderJoint::Param); - - - class ConeTwistJoint : public Joint { - GDCLASS(ConeTwistJoint,Joint); -public: + GDCLASS(ConeTwistJoint, Joint); +public: enum Param { PARAM_SWING_SPAN, @@ -235,8 +216,6 @@ public: }; protected: - - void _set_swing_span(float p_limit_angular); float _get_swing_span() const; @@ -246,53 +225,48 @@ protected: float params[PARAM_MAX]; virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b); static void _bind_methods(); -public: - void set_param(Param p_param,float p_value); +public: + void set_param(Param p_param, float p_value); float get_param(Param p_param) const; ConeTwistJoint(); }; - VARIANT_ENUM_CAST(ConeTwistJoint::Param); - class Generic6DOFJoint : public Joint { - GDCLASS(Generic6DOFJoint,Joint); -public: + GDCLASS(Generic6DOFJoint, Joint); +public: enum Param { - PARAM_LINEAR_LOWER_LIMIT=PhysicsServer::G6DOF_JOINT_LINEAR_LOWER_LIMIT, - PARAM_LINEAR_UPPER_LIMIT=PhysicsServer::G6DOF_JOINT_LINEAR_UPPER_LIMIT, - PARAM_LINEAR_LIMIT_SOFTNESS=PhysicsServer::G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS, - PARAM_LINEAR_RESTITUTION=PhysicsServer::G6DOF_JOINT_LINEAR_RESTITUTION, - PARAM_LINEAR_DAMPING=PhysicsServer::G6DOF_JOINT_LINEAR_DAMPING, - PARAM_ANGULAR_LOWER_LIMIT=PhysicsServer::G6DOF_JOINT_ANGULAR_LOWER_LIMIT, - PARAM_ANGULAR_UPPER_LIMIT=PhysicsServer::G6DOF_JOINT_ANGULAR_UPPER_LIMIT, - PARAM_ANGULAR_LIMIT_SOFTNESS=PhysicsServer::G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS, - PARAM_ANGULAR_DAMPING=PhysicsServer::G6DOF_JOINT_ANGULAR_DAMPING, - PARAM_ANGULAR_RESTITUTION=PhysicsServer::G6DOF_JOINT_ANGULAR_RESTITUTION, - PARAM_ANGULAR_FORCE_LIMIT=PhysicsServer::G6DOF_JOINT_ANGULAR_FORCE_LIMIT, - PARAM_ANGULAR_ERP=PhysicsServer::G6DOF_JOINT_ANGULAR_ERP, - PARAM_ANGULAR_MOTOR_TARGET_VELOCITY=PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY, - PARAM_ANGULAR_MOTOR_FORCE_LIMIT=PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT, - PARAM_MAX=PhysicsServer::G6DOF_JOINT_MAX, + PARAM_LINEAR_LOWER_LIMIT = PhysicsServer::G6DOF_JOINT_LINEAR_LOWER_LIMIT, + PARAM_LINEAR_UPPER_LIMIT = PhysicsServer::G6DOF_JOINT_LINEAR_UPPER_LIMIT, + PARAM_LINEAR_LIMIT_SOFTNESS = PhysicsServer::G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS, + PARAM_LINEAR_RESTITUTION = PhysicsServer::G6DOF_JOINT_LINEAR_RESTITUTION, + PARAM_LINEAR_DAMPING = PhysicsServer::G6DOF_JOINT_LINEAR_DAMPING, + PARAM_ANGULAR_LOWER_LIMIT = PhysicsServer::G6DOF_JOINT_ANGULAR_LOWER_LIMIT, + PARAM_ANGULAR_UPPER_LIMIT = PhysicsServer::G6DOF_JOINT_ANGULAR_UPPER_LIMIT, + PARAM_ANGULAR_LIMIT_SOFTNESS = PhysicsServer::G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS, + PARAM_ANGULAR_DAMPING = PhysicsServer::G6DOF_JOINT_ANGULAR_DAMPING, + PARAM_ANGULAR_RESTITUTION = PhysicsServer::G6DOF_JOINT_ANGULAR_RESTITUTION, + PARAM_ANGULAR_FORCE_LIMIT = PhysicsServer::G6DOF_JOINT_ANGULAR_FORCE_LIMIT, + PARAM_ANGULAR_ERP = PhysicsServer::G6DOF_JOINT_ANGULAR_ERP, + PARAM_ANGULAR_MOTOR_TARGET_VELOCITY = PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY, + PARAM_ANGULAR_MOTOR_FORCE_LIMIT = PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT, + PARAM_MAX = PhysicsServer::G6DOF_JOINT_MAX, }; enum Flag { - FLAG_ENABLE_LINEAR_LIMIT=PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT, - FLAG_ENABLE_ANGULAR_LIMIT=PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT, - FLAG_ENABLE_MOTOR=PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_MOTOR, - FLAG_MAX=PhysicsServer::G6DOF_JOINT_FLAG_MAX + FLAG_ENABLE_LINEAR_LIMIT = PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT, + FLAG_ENABLE_ANGULAR_LIMIT = PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT, + FLAG_ENABLE_MOTOR = PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_MOTOR, + FLAG_MAX = PhysicsServer::G6DOF_JOINT_FLAG_MAX }; - protected: - - void _set_angular_hi_limit_x(float p_limit_angular); float _get_angular_hi_limit_x() const; @@ -320,34 +294,32 @@ protected: virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b); static void _bind_methods(); -public: - void set_param_x(Param p_param,float p_value); +public: + void set_param_x(Param p_param, float p_value); float get_param_x(Param p_param) const; - void set_param_y(Param p_param,float p_value); + void set_param_y(Param p_param, float p_value); float get_param_y(Param p_param) const; - void set_param_z(Param p_param,float p_value); + void set_param_z(Param p_param, float p_value); float get_param_z(Param p_param) const; - void set_flag_x(Flag p_flag,bool p_enabled); + void set_flag_x(Flag p_flag, bool p_enabled); bool get_flag_x(Flag p_flag) const; - void set_flag_y(Flag p_flag,bool p_enabled); + void set_flag_y(Flag p_flag, bool p_enabled); bool get_flag_y(Flag p_flag) const; - void set_flag_z(Flag p_flag,bool p_enabled); + void set_flag_z(Flag p_flag, bool p_enabled); bool get_flag_z(Flag p_flag) const; Generic6DOFJoint(); }; - VARIANT_ENUM_CAST(Generic6DOFJoint::Param); VARIANT_ENUM_CAST(Generic6DOFJoint::Flag); - #if 0 class PhysicsJoint : public Spatial { diff --git a/scene/3d/portal.cpp b/scene/3d/portal.cpp index 19f126123..391a74ec4 100644 --- a/scene/3d/portal.cpp +++ b/scene/3d/portal.cpp @@ -27,31 +27,31 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "portal.h" -#include "servers/visual_server.h" -#include "scene/resources/surface_tool.h" #include "global_config.h" +#include "scene/resources/surface_tool.h" +#include "servers/visual_server.h" -bool Portal::_set(const StringName& p_name, const Variant& p_value) { +bool Portal::_set(const StringName &p_name, const Variant &p_value) { - if (p_name=="shape") { - PoolVector src_coords=p_value; + if (p_name == "shape") { + PoolVector src_coords = p_value; Vector points; int src_coords_size = src_coords.size(); - ERR_FAIL_COND_V(src_coords_size%2,false); - points.resize(src_coords_size/2); - for (int i=0;i points=get_shape(); + if (p_name == "shape") { + Vector points = get_shape(); PoolVector dst_coords; - dst_coords.resize(points.size()*2); + dst_coords.resize(points.size() * 2); - for (int i=0;i *p_list) const { +void Portal::_get_property_list(List *p_list) const { - p_list->push_back( PropertyInfo( Variant::POOL_REAL_ARRAY, "shape" ) ); - p_list->push_back( PropertyInfo( Variant::BOOL, "enabled" ) ); - p_list->push_back( PropertyInfo( Variant::REAL, "disable_distance",PROPERTY_HINT_RANGE,"0,4096,0.01" ) ); - p_list->push_back( PropertyInfo( Variant::COLOR, "disabled_color") ); - p_list->push_back( PropertyInfo( Variant::REAL, "connect_range",PROPERTY_HINT_RANGE,"0.1,4096,0.01" ) ); + p_list->push_back(PropertyInfo(Variant::POOL_REAL_ARRAY, "shape")); + p_list->push_back(PropertyInfo(Variant::BOOL, "enabled")); + p_list->push_back(PropertyInfo(Variant::REAL, "disable_distance", PROPERTY_HINT_RANGE, "0,4096,0.01")); + p_list->push_back(PropertyInfo(Variant::COLOR, "disabled_color")); + p_list->push_back(PropertyInfo(Variant::REAL, "connect_range", PROPERTY_HINT_RANGE, "0.1,4096,0.01")); } - - - Rect3 Portal::get_aabb() const { return aabb; } PoolVector Portal::get_faces(uint32_t p_usage_flags) const { - if (!(p_usage_flags&FACES_ENCLOSING)) + if (!(p_usage_flags & FACES_ENCLOSING)) return PoolVector(); Vector shape = get_shape(); - if (shape.size()==0) + if (shape.size() == 0) return PoolVector(); Vector2 center; - for (int i=0;i ret; - center/=shape.size(); + center /= shape.size(); - for (int i=0;i& p_shape) { - +void Portal::set_shape(const Vector &p_shape) { VisualServer::get_singleton()->portal_set_shape(portal, p_shape); - shape=p_shape; + shape = p_shape; update_gizmo(); } @@ -150,7 +145,7 @@ Vector Portal::get_shape() const { void Portal::set_connect_range(float p_range) { - connect_range=p_range; + connect_range = p_range; //VisualServer::get_singleton()->portal_set_connect_range(portal,p_range); } @@ -159,35 +154,31 @@ float Portal::get_connect_range() const { return connect_range; } - void Portal::set_enabled(bool p_enabled) { - enabled=p_enabled; - VisualServer::get_singleton()->portal_set_enabled(portal,enabled); + enabled = p_enabled; + VisualServer::get_singleton()->portal_set_enabled(portal, enabled); } bool Portal::is_enabled() const { - return enabled; } void Portal::set_disable_distance(float p_distance) { - disable_distance=p_distance; - VisualServer::get_singleton()->portal_set_disable_distance(portal,disable_distance); - + disable_distance = p_distance; + VisualServer::get_singleton()->portal_set_disable_distance(portal, disable_distance); } float Portal::get_disable_distance() const { - return disable_distance; } -void Portal::set_disabled_color(const Color& p_disabled_color) { +void Portal::set_disabled_color(const Color &p_disabled_color) { - disabled_color=p_disabled_color; - VisualServer::get_singleton()->portal_set_disabled_color(portal,disabled_color); + disabled_color = p_disabled_color; + VisualServer::get_singleton()->portal_set_disabled_color(portal, disabled_color); } Color Portal::get_disabled_color() const { @@ -197,47 +188,40 @@ Color Portal::get_disabled_color() const { void Portal::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_shape","points"),&Portal::set_shape); - ClassDB::bind_method(D_METHOD("get_shape"),&Portal::get_shape); + ClassDB::bind_method(D_METHOD("set_shape", "points"), &Portal::set_shape); + ClassDB::bind_method(D_METHOD("get_shape"), &Portal::get_shape); - ClassDB::bind_method(D_METHOD("set_enabled","enable"),&Portal::set_enabled); - ClassDB::bind_method(D_METHOD("is_enabled"),&Portal::is_enabled); + ClassDB::bind_method(D_METHOD("set_enabled", "enable"), &Portal::set_enabled); + ClassDB::bind_method(D_METHOD("is_enabled"), &Portal::is_enabled); - ClassDB::bind_method(D_METHOD("set_disable_distance","distance"),&Portal::set_disable_distance); - ClassDB::bind_method(D_METHOD("get_disable_distance"),&Portal::get_disable_distance); + ClassDB::bind_method(D_METHOD("set_disable_distance", "distance"), &Portal::set_disable_distance); + ClassDB::bind_method(D_METHOD("get_disable_distance"), &Portal::get_disable_distance); - ClassDB::bind_method(D_METHOD("set_disabled_color","color"),&Portal::set_disabled_color); - ClassDB::bind_method(D_METHOD("get_disabled_color"),&Portal::get_disabled_color); - - ClassDB::bind_method(D_METHOD("set_connect_range","range"),&Portal::set_connect_range); - ClassDB::bind_method(D_METHOD("get_connect_range"),&Portal::get_connect_range); + ClassDB::bind_method(D_METHOD("set_disabled_color", "color"), &Portal::set_disabled_color); + ClassDB::bind_method(D_METHOD("get_disabled_color"), &Portal::get_disabled_color); + ClassDB::bind_method(D_METHOD("set_connect_range", "range"), &Portal::set_connect_range); + ClassDB::bind_method(D_METHOD("get_connect_range"), &Portal::get_connect_range); } Portal::Portal() { portal = VisualServer::get_singleton()->portal_create(); - Vector< Point2 > points; - points.push_back( Point2( -1, 1 ) ); - points.push_back( Point2( 1, 1 ) ); - points.push_back( Point2( 1, -1 ) ); - points.push_back( Point2( -1, -1 ) ); + Vector points; + points.push_back(Point2(-1, 1)); + points.push_back(Point2(1, 1)); + points.push_back(Point2(1, -1)); + points.push_back(Point2(-1, -1)); set_shape(points); // default shape - set_connect_range(0.8); set_disable_distance(50); set_enabled(true); set_base(portal); - - } - Portal::~Portal() { VisualServer::get_singleton()->free(portal); } - - diff --git a/scene/3d/portal.h b/scene/3d/portal.h index 077924c7e..018708308 100644 --- a/scene/3d/portal.h +++ b/scene/3d/portal.h @@ -34,14 +34,11 @@ @author Juan Linietsky */ - /* Portal Logic: If a portal is placed next (very close to) a similar, opposing portal, they automatically connect, otherwise, a portal connects to the parent room */ - - class Portal : public VisualInstance { GDCLASS(Portal, VisualInstance); @@ -56,17 +53,14 @@ class Portal : public VisualInstance { Rect3 aabb; - protected: - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; static void _bind_methods(); public: - virtual Rect3 get_aabb() const; virtual PoolVector get_faces(uint32_t p_usage_flags) const; @@ -76,10 +70,10 @@ public: void set_disable_distance(float p_distance); float get_disable_distance() const; - void set_disabled_color(const Color& p_disabled_color); + void set_disabled_color(const Color &p_disabled_color); Color get_disabled_color() const; - void set_shape(const Vector& p_shape); + void set_shape(const Vector &p_shape); Vector get_shape() const; void set_connect_range(float p_range); @@ -87,7 +81,6 @@ public: Portal(); ~Portal(); - }; #endif diff --git a/scene/3d/position_3d.cpp b/scene/3d/position_3d.cpp index e7403053b..ee09ed93a 100644 --- a/scene/3d/position_3d.cpp +++ b/scene/3d/position_3d.cpp @@ -29,7 +29,5 @@ #include "position_3d.h" #include "scene/resources/mesh.h" - -Position3D::Position3D() -{ +Position3D::Position3D() { } diff --git a/scene/3d/position_3d.h b/scene/3d/position_3d.h index e732c5321..dae94dfba 100644 --- a/scene/3d/position_3d.h +++ b/scene/3d/position_3d.h @@ -31,13 +31,11 @@ #include "scene/3d/spatial.h" -class Position3D : public Spatial { - - GDCLASS(Position3D,Spatial); +class Position3D : public Spatial { + GDCLASS(Position3D, Spatial); public: - Position3D(); }; diff --git a/scene/3d/proximity_group.cpp b/scene/3d/proximity_group.cpp index f0dc8cb2e..f1225b690 100644 --- a/scene/3d/proximity_group.cpp +++ b/scene/3d/proximity_group.cpp @@ -47,7 +47,7 @@ void ProximityGroup::clear_groups() { E = E->next(); }; - for (int i=0; i::Element* E = groups.find(p_name); + const Map::Element *E = groups.find(p_name); if (!E) { add_to_group(p_name); }; @@ -119,13 +119,13 @@ void ProximityGroup::_notification(int what) { switch (what) { - case NOTIFICATION_EXIT_TREE: - ++group_version; - clear_groups(); - break; - case NOTIFICATION_TRANSFORM_CHANGED: - update_groups(); - break; + case NOTIFICATION_EXIT_TREE: + ++group_version; + clear_groups(); + break; + case NOTIFICATION_TRANSFORM_CHANGED: + update_groups(); + break; }; }; @@ -138,7 +138,6 @@ void ProximityGroup::broadcast(String p_name, Variant p_params) { get_tree()->call_group_flags(SceneTree::GROUP_CALL_DEFAULT, E->key(), "_proximity_group_broadcast", p_name, p_params); E = E->next(); }; - }; void ProximityGroup::_proximity_group_broadcast(String p_name, Variant p_params) { @@ -152,13 +151,12 @@ void ProximityGroup::_proximity_group_broadcast(String p_name, Variant p_params) }; }; - void ProximityGroup::set_dispatch_mode(int p_mode) { dispatch_mode = (DispatchMode)p_mode; }; -void ProximityGroup::set_grid_radius(const Vector3& p_radius) { +void ProximityGroup::set_grid_radius(const Vector3 &p_radius) { grid_radius = p_radius; }; @@ -168,22 +166,20 @@ Vector3 ProximityGroup::get_grid_radius() const { return grid_radius; }; - void ProximityGroup::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_group_name","name"), &ProximityGroup::set_group_name); - ClassDB::bind_method(D_METHOD("broadcast","name", "parameters"), &ProximityGroup::broadcast); - ClassDB::bind_method(D_METHOD("set_dispatch_mode","mode"), &ProximityGroup::set_dispatch_mode); - ClassDB::bind_method(D_METHOD("_proximity_group_broadcast","name","params"), &ProximityGroup::_proximity_group_broadcast); - ClassDB::bind_method(D_METHOD("set_grid_radius","radius"), &ProximityGroup::set_grid_radius); + ClassDB::bind_method(D_METHOD("set_group_name", "name"), &ProximityGroup::set_group_name); + ClassDB::bind_method(D_METHOD("broadcast", "name", "parameters"), &ProximityGroup::broadcast); + ClassDB::bind_method(D_METHOD("set_dispatch_mode", "mode"), &ProximityGroup::set_dispatch_mode); + ClassDB::bind_method(D_METHOD("_proximity_group_broadcast", "name", "params"), &ProximityGroup::_proximity_group_broadcast); + ClassDB::bind_method(D_METHOD("set_grid_radius", "radius"), &ProximityGroup::set_grid_radius); ClassDB::bind_method(D_METHOD("get_grid_radius"), &ProximityGroup::get_grid_radius); - ADD_PROPERTY( PropertyInfo( Variant::VECTOR3, "grid_radius"), "set_grid_radius", "get_grid_radius"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "grid_radius"), "set_grid_radius", "get_grid_radius"); - ADD_SIGNAL( MethodInfo("broadcast", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::ARRAY, "parameters")) ); + ADD_SIGNAL(MethodInfo("broadcast", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::ARRAY, "parameters"))); }; - ProximityGroup::ProximityGroup() { group_version = 0; @@ -191,9 +187,8 @@ ProximityGroup::ProximityGroup() { grid_radius = Vector3(1, 1, 1); set_notify_transform(true); - }; -ProximityGroup::~ProximityGroup() { +ProximityGroup::~ProximityGroup(){ }; diff --git a/scene/3d/proximity_group.h b/scene/3d/proximity_group.h index 58d243697..f40ffe2ff 100644 --- a/scene/3d/proximity_group.h +++ b/scene/3d/proximity_group.h @@ -33,7 +33,7 @@ class ProximityGroup : public Spatial { - GDCLASS( ProximityGroup, Spatial ); + GDCLASS(ProximityGroup, Spatial); OBJ_CATEGORY("3D"); public: @@ -57,7 +57,7 @@ public: Vector3 grid_radius; uint32_t group_version; - void add_groups(int* p_cell, String p_base, int p_depth); + void add_groups(int *p_cell, String p_base, int p_depth); void _new_group(StringName p_name); void _proximity_group_broadcast(String p_name, Variant p_params); @@ -65,12 +65,11 @@ public: static void _bind_methods(); public: - void set_group_name(String p_group_name); void broadcast(String p_name, Variant p_params); void set_dispatch_mode(int p_mode); - void set_grid_radius(const Vector3& p_radius); + void set_grid_radius(const Vector3 &p_radius); Vector3 get_grid_radius() const; ProximityGroup(); @@ -78,4 +77,3 @@ public: }; #endif - diff --git a/scene/3d/quad.cpp b/scene/3d/quad.cpp index e740769bd..e32320681 100644 --- a/scene/3d/quad.cpp +++ b/scene/3d/quad.cpp @@ -35,39 +35,36 @@ void Quad::_update() { return; Vector3 normal; - normal[axis]=1.0; - - const int axis_order_1[3]={1,2,0}; - const int axis_order_2[3]={2,0,1}; - const int a1=axis_order_1[axis]; - const int a2=axis_order_2[axis]; - + normal[axis] = 1.0; + const int axis_order_1[3] = { 1, 2, 0 }; + const int axis_order_2[3] = { 2, 0, 1 }; + const int a1 = axis_order_1[axis]; + const int a2 = axis_order_2[axis]; PoolVector points; points.resize(4); PoolVector::Write pointsw = points.write(); - Vector2 s2 = size*0.5; + Vector2 s2 = size * 0.5; Vector2 o = offset; if (!centered) - o+=s2; - - pointsw[0][a1]=-s2.x+offset.x; - pointsw[0][a2]=s2.y+offset.y; + o += s2; - pointsw[1][a1]=s2.x+offset.x; - pointsw[1][a2]=s2.y+offset.y; + pointsw[0][a1] = -s2.x + offset.x; + pointsw[0][a2] = s2.y + offset.y; - pointsw[2][a1]=s2.x+offset.x; - pointsw[2][a2]=-s2.y+offset.y; + pointsw[1][a1] = s2.x + offset.x; + pointsw[1][a2] = s2.y + offset.y; - pointsw[3][a1]=-s2.x+offset.x; - pointsw[3][a2]=-s2.y+offset.y; + pointsw[2][a1] = s2.x + offset.x; + pointsw[2][a2] = -s2.y + offset.y; + pointsw[3][a1] = -s2.x + offset.x; + pointsw[3][a2] = -s2.y + offset.y; - aabb=Rect3(pointsw[0],Vector3()); - for(int i=1;i<4;i++) + aabb = Rect3(pointsw[0], Vector3()); + for (int i = 1; i < 4; i++) aabb.expand_to(pointsw[i]); pointsw = PoolVector::Write(); @@ -76,21 +73,19 @@ void Quad::_update() { normals.resize(4); PoolVector::Write normalsw = normals.write(); - for(int i=0;i<4;i++) - normalsw[i]=normal; - - normalsw=PoolVector::Write(); - + for (int i = 0; i < 4; i++) + normalsw[i] = normal; + normalsw = PoolVector::Write(); PoolVector uvs; uvs.resize(4); PoolVector::Write uvsw = uvs.write(); - uvsw[0]=Vector2(0,0); - uvsw[1]=Vector2(1,0); - uvsw[2]=Vector2(1,1); - uvsw[3]=Vector2(0,1); + uvsw[0] = Vector2(0, 0); + uvsw[1] = Vector2(1, 0); + uvsw[2] = Vector2(1, 1); + uvsw[3] = Vector2(0, 1); uvsw = PoolVector::Write(); @@ -98,90 +93,86 @@ void Quad::_update() { indices.resize(6); PoolVector::Write indicesw = indices.write(); - indicesw[0]=0; - indicesw[1]=1; - indicesw[2]=2; - indicesw[3]=2; - indicesw[4]=3; - indicesw[5]=0; + indicesw[0] = 0; + indicesw[1] = 1; + indicesw[2] = 2; + indicesw[3] = 2; + indicesw[4] = 3; + indicesw[5] = 0; - indicesw=PoolVector::Write(); + indicesw = PoolVector::Write(); Array arr; arr.resize(VS::ARRAY_MAX); - arr[VS::ARRAY_VERTEX]=points; - arr[VS::ARRAY_NORMAL]=normals; - arr[VS::ARRAY_TEX_UV]=uvs; - arr[VS::ARRAY_INDEX]=indices; - + arr[VS::ARRAY_VERTEX] = points; + arr[VS::ARRAY_NORMAL] = normals; + arr[VS::ARRAY_TEX_UV] = uvs; + arr[VS::ARRAY_INDEX] = indices; if (configured) { - VS::get_singleton()->mesh_remove_surface(mesh,0); + VS::get_singleton()->mesh_remove_surface(mesh, 0); } else { - configured=true; + configured = true; } - VS::get_singleton()->mesh_add_surface_from_arrays(mesh,VS::PRIMITIVE_TRIANGLES,arr); + VS::get_singleton()->mesh_add_surface_from_arrays(mesh, VS::PRIMITIVE_TRIANGLES, arr); - pending_update=false; + pending_update = false; } - void Quad::set_axis(Vector3::Axis p_axis) { - axis=p_axis; + axis = p_axis; _update(); } -Vector3::Axis Quad::get_axis() const{ +Vector3::Axis Quad::get_axis() const { return axis; } -void Quad::set_size(const Vector2& p_size){ +void Quad::set_size(const Vector2 &p_size) { - size=p_size; + size = p_size; _update(); } -Vector2 Quad::get_size() const{ +Vector2 Quad::get_size() const { return size; } -void Quad::set_offset(const Vector2& p_offset){ +void Quad::set_offset(const Vector2 &p_offset) { - offset=p_offset; + offset = p_offset; _update(); } -Vector2 Quad::get_offset() const{ +Vector2 Quad::get_offset() const { return offset; } -void Quad::set_centered(bool p_enabled){ +void Quad::set_centered(bool p_enabled) { - centered=p_enabled; + centered = p_enabled; _update(); } -bool Quad::is_centered() const{ +bool Quad::is_centered() const { return centered; } void Quad::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { if (pending_update) _update(); - } break; case NOTIFICATION_EXIT_TREE: { - pending_update=true; - + pending_update = true; } break; } @@ -197,38 +188,36 @@ Rect3 Quad::get_aabb() const { return aabb; } -void Quad::_bind_methods(){ +void Quad::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_axis","axis"),&Quad::set_axis); - ClassDB::bind_method(D_METHOD("get_axis"),&Quad::get_axis); + ClassDB::bind_method(D_METHOD("set_axis", "axis"), &Quad::set_axis); + ClassDB::bind_method(D_METHOD("get_axis"), &Quad::get_axis); - ClassDB::bind_method(D_METHOD("set_size","size"),&Quad::set_size); - ClassDB::bind_method(D_METHOD("get_size"),&Quad::get_size); + ClassDB::bind_method(D_METHOD("set_size", "size"), &Quad::set_size); + ClassDB::bind_method(D_METHOD("get_size"), &Quad::get_size); - ClassDB::bind_method(D_METHOD("set_centered","centered"),&Quad::set_centered); - ClassDB::bind_method(D_METHOD("is_centered"),&Quad::is_centered); + ClassDB::bind_method(D_METHOD("set_centered", "centered"), &Quad::set_centered); + ClassDB::bind_method(D_METHOD("is_centered"), &Quad::is_centered); - ClassDB::bind_method(D_METHOD("set_offset","offset"),&Quad::set_offset); - ClassDB::bind_method(D_METHOD("get_offset"),&Quad::get_offset); - - ADD_PROPERTY( PropertyInfo( Variant::INT, "axis", PROPERTY_HINT_ENUM,"X,Y,Z" ), "set_axis", "get_axis"); - ADD_PROPERTY( PropertyInfo( Variant::VECTOR2, "size" ), "set_size", "get_size"); - ADD_PROPERTY( PropertyInfo( Variant::VECTOR2, "offset" ), "set_offset", "get_offset"); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "centered" ), "set_centered", "is_centered"); + ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Quad::set_offset); + ClassDB::bind_method(D_METHOD("get_offset"), &Quad::get_offset); + ADD_PROPERTY(PropertyInfo(Variant::INT, "axis", PROPERTY_HINT_ENUM, "X,Y,Z"), "set_axis", "get_axis"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "size"), "set_size", "get_size"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered"); } Quad::Quad() { - pending_update=true; - centered=true; + pending_update = true; + centered = true; //offset=0; - size=Vector2(1,1); - axis=Vector3::AXIS_Z; - mesh=VisualServer::get_singleton()->mesh_create(); + size = Vector2(1, 1); + axis = Vector3::AXIS_Z; + mesh = VisualServer::get_singleton()->mesh_create(); set_base(mesh); - configured=false; - + configured = false; } Quad::~Quad() { diff --git a/scene/3d/quad.h b/scene/3d/quad.h index af91d7a1f..607d7238e 100644 --- a/scene/3d/quad.h +++ b/scene/3d/quad.h @@ -29,13 +29,12 @@ #ifndef QUAD_H #define QUAD_H - -#include "scene/3d/visual_instance.h" #include "rid.h" +#include "scene/3d/visual_instance.h" class Quad : public GeometryInstance { - GDCLASS(Quad,GeometryInstance); + GDCLASS(Quad, GeometryInstance); Vector3::Axis axis; bool centered; @@ -50,18 +49,17 @@ class Quad : public GeometryInstance { void _update(); protected: - void _notification(int p_what); static void _bind_methods(); -public: +public: void set_axis(Vector3::Axis p_axis); Vector3::Axis get_axis() const; - void set_size(const Vector2& p_sizze); + void set_size(const Vector2 &p_sizze); Vector2 get_size() const; - void set_offset(const Vector2& p_offset); + void set_offset(const Vector2 &p_offset); Vector2 get_offset() const; void set_centered(bool p_enabled); @@ -74,5 +72,4 @@ public: ~Quad(); }; - #endif // QUAD_H diff --git a/scene/3d/ray_cast.cpp b/scene/3d/ray_cast.cpp index 6be8b8944..a73114a7c 100644 --- a/scene/3d/ray_cast.cpp +++ b/scene/3d/ray_cast.cpp @@ -28,24 +28,23 @@ /*************************************************************************/ #include "ray_cast.h" -#include "servers/physics_server.h" #include "collision_object.h" -void RayCast::set_cast_to(const Vector3& p_point) { +#include "servers/physics_server.h" +void RayCast::set_cast_to(const Vector3 &p_point) { - cast_to=p_point; + cast_to = p_point; if (is_inside_tree() && (get_tree()->is_editor_hint() || get_tree()->is_debugging_collisions_hint())) update_gizmo(); - } -Vector3 RayCast::get_cast_to() const{ +Vector3 RayCast::get_cast_to() const { return cast_to; } void RayCast::set_layer_mask(uint32_t p_mask) { - layer_mask=p_mask; + layer_mask = p_mask; } uint32_t RayCast::get_layer_mask() const { @@ -55,7 +54,7 @@ uint32_t RayCast::get_layer_mask() const { void RayCast::set_type_mask(uint32_t p_mask) { - type_mask=p_mask; + type_mask = p_mask; } uint32_t RayCast::get_type_mask() const { @@ -63,13 +62,13 @@ uint32_t RayCast::get_type_mask() const { return type_mask; } -bool RayCast::is_colliding() const{ +bool RayCast::is_colliding() const { return collided; } -Object *RayCast::get_collider() const{ +Object *RayCast::get_collider() const { - if (against==0) + if (against == 0) return NULL; return ObjectDB::get_instance(against); @@ -79,37 +78,32 @@ int RayCast::get_collider_shape() const { return against_shape; } -Vector3 RayCast::get_collision_point() const{ +Vector3 RayCast::get_collision_point() const { return collision_point; } -Vector3 RayCast::get_collision_normal() const{ +Vector3 RayCast::get_collision_normal() const { return collision_normal; } - void RayCast::set_enabled(bool p_enabled) { - enabled=p_enabled; + enabled = p_enabled; if (is_inside_tree() && !get_tree()->is_editor_hint()) set_fixed_process(p_enabled); if (!p_enabled) - collided=false; - + collided = false; } - bool RayCast::is_enabled() const { - return enabled; } - void RayCast::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { @@ -118,8 +112,6 @@ void RayCast::_notification(int p_what) { } else set_fixed_process(false); - - } break; case NOTIFICATION_EXIT_TREE: { @@ -127,7 +119,6 @@ void RayCast::_notification(int p_what) { set_fixed_process(false); } - } break; case NOTIFICATION_FIXED_PROCESS: { @@ -136,35 +127,34 @@ void RayCast::_notification(int p_what) { _update_raycast_state(); - } break; } } -void RayCast::_update_raycast_state(){ +void RayCast::_update_raycast_state() { Ref w3d = get_world(); - ERR_FAIL_COND( w3d.is_null() ); + ERR_FAIL_COND(w3d.is_null()); PhysicsDirectSpaceState *dss = PhysicsServer::get_singleton()->space_get_direct_state(w3d->get_space()); - ERR_FAIL_COND( !dss ); + ERR_FAIL_COND(!dss); Transform gt = get_global_transform(); Vector3 to = cast_to; - if (to==Vector3()) - to=Vector3(0,0.01,0); + if (to == Vector3()) + to = Vector3(0, 0.01, 0); PhysicsDirectSpaceState::RayResult rr; - if (dss->intersect_ray(gt.get_origin(),gt.xform(to),rr,exclude, layer_mask, type_mask)) { + if (dss->intersect_ray(gt.get_origin(), gt.xform(to), rr, exclude, layer_mask, type_mask)) { - collided=true; - against=rr.collider_id; - collision_point=rr.position; - collision_normal=rr.normal; - against_shape=rr.shape; + collided = true; + against = rr.collider_id; + collision_point = rr.position; + collision_normal = rr.normal; + against_shape = rr.shape; } else { - collided=false; + collided = false; } } @@ -172,85 +162,82 @@ void RayCast::force_raycast_update() { _update_raycast_state(); } -void RayCast::add_exception_rid(const RID& p_rid) { +void RayCast::add_exception_rid(const RID &p_rid) { exclude.insert(p_rid); } -void RayCast::add_exception(const Object* p_object){ +void RayCast::add_exception(const Object *p_object) { ERR_FAIL_NULL(p_object); - CollisionObject *co=((Object*)p_object)->cast_to(); + CollisionObject *co = ((Object *)p_object)->cast_to(); if (!co) return; add_exception_rid(co->get_rid()); } -void RayCast::remove_exception_rid(const RID& p_rid) { +void RayCast::remove_exception_rid(const RID &p_rid) { exclude.erase(p_rid); } -void RayCast::remove_exception(const Object* p_object){ +void RayCast::remove_exception(const Object *p_object) { ERR_FAIL_NULL(p_object); - CollisionObject *co=((Object*)p_object)->cast_to(); + CollisionObject *co = ((Object *)p_object)->cast_to(); if (!co) return; remove_exception_rid(co->get_rid()); } - -void RayCast::clear_exceptions(){ +void RayCast::clear_exceptions() { exclude.clear(); } - void RayCast::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &RayCast::set_enabled); + ClassDB::bind_method(D_METHOD("is_enabled"), &RayCast::is_enabled); - ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&RayCast::set_enabled); - ClassDB::bind_method(D_METHOD("is_enabled"),&RayCast::is_enabled); - - ClassDB::bind_method(D_METHOD("set_cast_to","local_point"),&RayCast::set_cast_to); - ClassDB::bind_method(D_METHOD("get_cast_to"),&RayCast::get_cast_to); + ClassDB::bind_method(D_METHOD("set_cast_to", "local_point"), &RayCast::set_cast_to); + ClassDB::bind_method(D_METHOD("get_cast_to"), &RayCast::get_cast_to); - ClassDB::bind_method(D_METHOD("is_colliding"),&RayCast::is_colliding); - ClassDB::bind_method(D_METHOD("force_raycast_update"),&RayCast::force_raycast_update); + ClassDB::bind_method(D_METHOD("is_colliding"), &RayCast::is_colliding); + ClassDB::bind_method(D_METHOD("force_raycast_update"), &RayCast::force_raycast_update); - ClassDB::bind_method(D_METHOD("get_collider"),&RayCast::get_collider); - ClassDB::bind_method(D_METHOD("get_collider_shape"),&RayCast::get_collider_shape); - ClassDB::bind_method(D_METHOD("get_collision_point"),&RayCast::get_collision_point); - ClassDB::bind_method(D_METHOD("get_collision_normal"),&RayCast::get_collision_normal); + ClassDB::bind_method(D_METHOD("get_collider"), &RayCast::get_collider); + ClassDB::bind_method(D_METHOD("get_collider_shape"), &RayCast::get_collider_shape); + ClassDB::bind_method(D_METHOD("get_collision_point"), &RayCast::get_collision_point); + ClassDB::bind_method(D_METHOD("get_collision_normal"), &RayCast::get_collision_normal); - ClassDB::bind_method(D_METHOD("add_exception_rid","rid"),&RayCast::add_exception_rid); - ClassDB::bind_method(D_METHOD("add_exception","node"),&RayCast::add_exception); + ClassDB::bind_method(D_METHOD("add_exception_rid", "rid"), &RayCast::add_exception_rid); + ClassDB::bind_method(D_METHOD("add_exception", "node"), &RayCast::add_exception); - ClassDB::bind_method(D_METHOD("remove_exception_rid","rid"),&RayCast::remove_exception_rid); - ClassDB::bind_method(D_METHOD("remove_exception","node"),&RayCast::remove_exception); + ClassDB::bind_method(D_METHOD("remove_exception_rid", "rid"), &RayCast::remove_exception_rid); + ClassDB::bind_method(D_METHOD("remove_exception", "node"), &RayCast::remove_exception); - ClassDB::bind_method(D_METHOD("clear_exceptions"),&RayCast::clear_exceptions); + ClassDB::bind_method(D_METHOD("clear_exceptions"), &RayCast::clear_exceptions); - ClassDB::bind_method(D_METHOD("set_layer_mask","mask"),&RayCast::set_layer_mask); - ClassDB::bind_method(D_METHOD("get_layer_mask"),&RayCast::get_layer_mask); + ClassDB::bind_method(D_METHOD("set_layer_mask", "mask"), &RayCast::set_layer_mask); + ClassDB::bind_method(D_METHOD("get_layer_mask"), &RayCast::get_layer_mask); - ClassDB::bind_method(D_METHOD("set_type_mask","mask"),&RayCast::set_type_mask); - ClassDB::bind_method(D_METHOD("get_type_mask"),&RayCast::get_type_mask); + ClassDB::bind_method(D_METHOD("set_type_mask", "mask"), &RayCast::set_type_mask); + ClassDB::bind_method(D_METHOD("get_type_mask"), &RayCast::get_type_mask); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3,"cast_to"),"set_cast_to","get_cast_to"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"layer_mask",PROPERTY_HINT_LAYERS_3D_PHYSICS),"set_layer_mask","get_layer_mask"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"type_mask",PROPERTY_HINT_FLAGS,"Static,Kinematic,Rigid,Character,Area"),"set_type_mask","get_type_mask"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "cast_to"), "set_cast_to", "get_cast_to"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "layer_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_layer_mask", "get_layer_mask"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "type_mask", PROPERTY_HINT_FLAGS, "Static,Kinematic,Rigid,Character,Area"), "set_type_mask", "get_type_mask"); } RayCast::RayCast() { - enabled=false; - against=0; - collided=false; - against_shape=0; - layer_mask=1; - type_mask=PhysicsDirectSpaceState::TYPE_MASK_COLLISION; - cast_to=Vector3(0,-1,0); + enabled = false; + against = 0; + collided = false; + against_shape = 0; + layer_mask = 1; + type_mask = PhysicsDirectSpaceState::TYPE_MASK_COLLISION; + cast_to = Vector3(0, -1, 0); } diff --git a/scene/3d/ray_cast.h b/scene/3d/ray_cast.h index 32d24cc96..00a10446a 100644 --- a/scene/3d/ray_cast.h +++ b/scene/3d/ray_cast.h @@ -33,8 +33,7 @@ class RayCast : public Spatial { - GDCLASS(RayCast,Spatial); - + GDCLASS(RayCast, Spatial); bool enabled; bool collided; @@ -51,16 +50,15 @@ class RayCast : public Spatial { uint32_t type_mask; protected: - void _notification(int p_what); void _update_raycast_state(); static void _bind_methods(); -public: +public: void set_enabled(bool p_enabled); bool is_enabled() const; - void set_cast_to(const Vector3& p_point); + void set_cast_to(const Vector3 &p_point); Vector3 get_cast_to() const; void set_layer_mask(uint32_t p_mask); @@ -76,10 +74,10 @@ public: Vector3 get_collision_point() const; Vector3 get_collision_normal() const; - void add_exception_rid(const RID& p_rid); - void add_exception(const Object* p_object); - void remove_exception_rid(const RID& p_rid); - void remove_exception(const Object* p_object); + void add_exception_rid(const RID &p_rid); + void add_exception(const Object *p_object); + void remove_exception_rid(const RID &p_rid); + void remove_exception(const Object *p_object); void clear_exceptions(); RayCast(); diff --git a/scene/3d/reflection_probe.cpp b/scene/3d/reflection_probe.cpp index db18e70ae..90dbd5127 100644 --- a/scene/3d/reflection_probe.cpp +++ b/scene/3d/reflection_probe.cpp @@ -28,129 +28,119 @@ /*************************************************************************/ #include "reflection_probe.h" - void ReflectionProbe::set_intensity(float p_intensity) { - intensity=p_intensity; - VS::get_singleton()->reflection_probe_set_intensity(probe,p_intensity); + intensity = p_intensity; + VS::get_singleton()->reflection_probe_set_intensity(probe, p_intensity); } -float ReflectionProbe::get_intensity() const{ +float ReflectionProbe::get_intensity() const { return intensity; } - void ReflectionProbe::set_interior_ambient(Color p_ambient) { - interior_ambient=p_ambient; - VS::get_singleton()->reflection_probe_set_interior_ambient(probe,p_ambient); + interior_ambient = p_ambient; + VS::get_singleton()->reflection_probe_set_interior_ambient(probe, p_ambient); } void ReflectionProbe::set_interior_ambient_energy(float p_energy) { - interior_ambient_energy=p_energy; - VS::get_singleton()->reflection_probe_set_interior_ambient_energy(probe,p_energy); + interior_ambient_energy = p_energy; + VS::get_singleton()->reflection_probe_set_interior_ambient_energy(probe, p_energy); } -float ReflectionProbe::get_interior_ambient_energy() const{ +float ReflectionProbe::get_interior_ambient_energy() const { return interior_ambient_energy; } - -Color ReflectionProbe::get_interior_ambient() const{ +Color ReflectionProbe::get_interior_ambient() const { return interior_ambient; } void ReflectionProbe::set_interior_ambient_probe_contribution(float p_contribution) { - interior_ambient_probe_contribution=p_contribution; - VS::get_singleton()->reflection_probe_set_interior_ambient_probe_contribution(probe,p_contribution); + interior_ambient_probe_contribution = p_contribution; + VS::get_singleton()->reflection_probe_set_interior_ambient_probe_contribution(probe, p_contribution); } -float ReflectionProbe::get_interior_ambient_probe_contribution() const{ +float ReflectionProbe::get_interior_ambient_probe_contribution() const { return interior_ambient_probe_contribution; } +void ReflectionProbe::set_max_distance(float p_distance) { -void ReflectionProbe::set_max_distance(float p_distance){ - - max_distance=p_distance; - VS::get_singleton()->reflection_probe_set_max_distance(probe,p_distance); + max_distance = p_distance; + VS::get_singleton()->reflection_probe_set_max_distance(probe, p_distance); } -float ReflectionProbe::get_max_distance() const{ +float ReflectionProbe::get_max_distance() const { return max_distance; } +void ReflectionProbe::set_extents(const Vector3 &p_extents) { -void ReflectionProbe::set_extents(const Vector3& p_extents){ + extents = p_extents; - extents=p_extents; - - for(int i=0;i<3;i++) { - if (extents[i]<0.01) { - extents[i]=0.01; + for (int i = 0; i < 3; i++) { + if (extents[i] < 0.01) { + extents[i] = 0.01; } - if (extents[i]-0.01reflection_probe_set_extents(probe,extents); - VS::get_singleton()->reflection_probe_set_origin_offset(probe,origin_offset); + VS::get_singleton()->reflection_probe_set_extents(probe, extents); + VS::get_singleton()->reflection_probe_set_origin_offset(probe, origin_offset); _change_notify("extents"); update_gizmo(); - } -Vector3 ReflectionProbe::get_extents() const{ +Vector3 ReflectionProbe::get_extents() const { return extents; } -void ReflectionProbe::set_origin_offset(const Vector3& p_extents){ +void ReflectionProbe::set_origin_offset(const Vector3 &p_extents) { - origin_offset=p_extents; + origin_offset = p_extents; - for(int i=0;i<3;i++) { - - if (extents[i]-0.01reflection_probe_set_extents(probe,extents); - VS::get_singleton()->reflection_probe_set_origin_offset(probe,origin_offset); + VS::get_singleton()->reflection_probe_set_extents(probe, extents); + VS::get_singleton()->reflection_probe_set_origin_offset(probe, origin_offset); _change_notify("origin_offset"); update_gizmo(); } -Vector3 ReflectionProbe::get_origin_offset() const{ +Vector3 ReflectionProbe::get_origin_offset() const { return origin_offset; } -void ReflectionProbe::set_enable_box_projection(bool p_enable){ - - box_projection=p_enable; - VS::get_singleton()->reflection_probe_set_enable_box_projection(probe,p_enable); +void ReflectionProbe::set_enable_box_projection(bool p_enable) { + box_projection = p_enable; + VS::get_singleton()->reflection_probe_set_enable_box_projection(probe, p_enable); } -bool ReflectionProbe::is_box_projection_enabled() const{ +bool ReflectionProbe::is_box_projection_enabled() const { return box_projection; } - void ReflectionProbe::set_as_interior(bool p_enable) { - interior=p_enable; - VS::get_singleton()->reflection_probe_set_as_interior(probe,interior); + interior = p_enable; + VS::get_singleton()->reflection_probe_set_as_interior(probe, interior); _change_notify(); - } bool ReflectionProbe::is_set_as_interior() const { @@ -158,12 +148,10 @@ bool ReflectionProbe::is_set_as_interior() const { return interior; } - - void ReflectionProbe::set_enable_shadows(bool p_enable) { - enable_shadows=p_enable; - VS::get_singleton()->reflection_probe_set_enable_shadows(probe,p_enable); + enable_shadows = p_enable; + VS::get_singleton()->reflection_probe_set_enable_shadows(probe, p_enable); } bool ReflectionProbe::are_shadows_enabled() const { @@ -172,8 +160,8 @@ bool ReflectionProbe::are_shadows_enabled() const { void ReflectionProbe::set_cull_mask(uint32_t p_layers) { - cull_mask=p_layers; - VS::get_singleton()->reflection_probe_set_enable_shadows(probe,p_layers); + cull_mask = p_layers; + VS::get_singleton()->reflection_probe_set_enable_shadows(probe, p_layers); } uint32_t ReflectionProbe::get_cull_mask() const { @@ -181,20 +169,19 @@ uint32_t ReflectionProbe::get_cull_mask() const { } void ReflectionProbe::set_update_mode(UpdateMode p_mode) { - update_mode=p_mode; - VS::get_singleton()->reflection_probe_set_update_mode(probe,VS::ReflectionProbeUpdateMode(p_mode)); + update_mode = p_mode; + VS::get_singleton()->reflection_probe_set_update_mode(probe, VS::ReflectionProbeUpdateMode(p_mode)); } ReflectionProbe::UpdateMode ReflectionProbe::get_update_mode() const { return update_mode; } - Rect3 ReflectionProbe::get_aabb() const { Rect3 aabb; - aabb.pos=-origin_offset; - aabb.size=origin_offset+extents; + aabb.pos = -origin_offset; + aabb.size = origin_offset + extents; return aabb; } PoolVector ReflectionProbe::get_faces(uint32_t p_usage_flags) const { @@ -202,92 +189,89 @@ PoolVector ReflectionProbe::get_faces(uint32_t p_usage_flags) const { return PoolVector(); } -void ReflectionProbe::_validate_property(PropertyInfo& property) const { +void ReflectionProbe::_validate_property(PropertyInfo &property) const { - if (property.name=="interior/ambient_color" || property.name=="interior/ambient_energy" || property.name=="interior/ambient_contrib") { + if (property.name == "interior/ambient_color" || property.name == "interior/ambient_energy" || property.name == "interior/ambient_contrib") { if (!interior) { - property.usage=PROPERTY_USAGE_NOEDITOR; + property.usage = PROPERTY_USAGE_NOEDITOR; } } } void ReflectionProbe::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_intensity","intensity"),&ReflectionProbe::set_intensity); - ClassDB::bind_method(D_METHOD("get_intensity"),&ReflectionProbe::get_intensity); - - ClassDB::bind_method(D_METHOD("set_interior_ambient","ambient"),&ReflectionProbe::set_interior_ambient); - ClassDB::bind_method(D_METHOD("get_interior_ambient"),&ReflectionProbe::get_interior_ambient); - - ClassDB::bind_method(D_METHOD("set_interior_ambient_energy","ambient_energy"),&ReflectionProbe::set_interior_ambient_energy); - ClassDB::bind_method(D_METHOD("get_interior_ambient_energy"),&ReflectionProbe::get_interior_ambient_energy); - - ClassDB::bind_method(D_METHOD("set_interior_ambient_probe_contribution","ambient_probe_contribution"),&ReflectionProbe::set_interior_ambient_probe_contribution); - ClassDB::bind_method(D_METHOD("get_interior_ambient_probe_contribution"),&ReflectionProbe::get_interior_ambient_probe_contribution); + ClassDB::bind_method(D_METHOD("set_intensity", "intensity"), &ReflectionProbe::set_intensity); + ClassDB::bind_method(D_METHOD("get_intensity"), &ReflectionProbe::get_intensity); - ClassDB::bind_method(D_METHOD("set_max_distance","max_distance"),&ReflectionProbe::set_max_distance); - ClassDB::bind_method(D_METHOD("get_max_distance"),&ReflectionProbe::get_max_distance); + ClassDB::bind_method(D_METHOD("set_interior_ambient", "ambient"), &ReflectionProbe::set_interior_ambient); + ClassDB::bind_method(D_METHOD("get_interior_ambient"), &ReflectionProbe::get_interior_ambient); - ClassDB::bind_method(D_METHOD("set_extents","extents"),&ReflectionProbe::set_extents); - ClassDB::bind_method(D_METHOD("get_extents"),&ReflectionProbe::get_extents); + ClassDB::bind_method(D_METHOD("set_interior_ambient_energy", "ambient_energy"), &ReflectionProbe::set_interior_ambient_energy); + ClassDB::bind_method(D_METHOD("get_interior_ambient_energy"), &ReflectionProbe::get_interior_ambient_energy); - ClassDB::bind_method(D_METHOD("set_origin_offset","origin_offset"),&ReflectionProbe::set_origin_offset); - ClassDB::bind_method(D_METHOD("get_origin_offset"),&ReflectionProbe::get_origin_offset); + ClassDB::bind_method(D_METHOD("set_interior_ambient_probe_contribution", "ambient_probe_contribution"), &ReflectionProbe::set_interior_ambient_probe_contribution); + ClassDB::bind_method(D_METHOD("get_interior_ambient_probe_contribution"), &ReflectionProbe::get_interior_ambient_probe_contribution); - ClassDB::bind_method(D_METHOD("set_as_interior","enable"),&ReflectionProbe::set_as_interior); - ClassDB::bind_method(D_METHOD("is_set_as_interior"),&ReflectionProbe::is_set_as_interior); + ClassDB::bind_method(D_METHOD("set_max_distance", "max_distance"), &ReflectionProbe::set_max_distance); + ClassDB::bind_method(D_METHOD("get_max_distance"), &ReflectionProbe::get_max_distance); - ClassDB::bind_method(D_METHOD("set_enable_box_projection","enable"),&ReflectionProbe::set_enable_box_projection); - ClassDB::bind_method(D_METHOD("is_box_projection_enabled"),&ReflectionProbe::is_box_projection_enabled); + ClassDB::bind_method(D_METHOD("set_extents", "extents"), &ReflectionProbe::set_extents); + ClassDB::bind_method(D_METHOD("get_extents"), &ReflectionProbe::get_extents); + ClassDB::bind_method(D_METHOD("set_origin_offset", "origin_offset"), &ReflectionProbe::set_origin_offset); + ClassDB::bind_method(D_METHOD("get_origin_offset"), &ReflectionProbe::get_origin_offset); - ClassDB::bind_method(D_METHOD("set_enable_shadows","enable"),&ReflectionProbe::set_enable_shadows); - ClassDB::bind_method(D_METHOD("are_shadows_enabled"),&ReflectionProbe::are_shadows_enabled); + ClassDB::bind_method(D_METHOD("set_as_interior", "enable"), &ReflectionProbe::set_as_interior); + ClassDB::bind_method(D_METHOD("is_set_as_interior"), &ReflectionProbe::is_set_as_interior); - ClassDB::bind_method(D_METHOD("set_cull_mask","layers"),&ReflectionProbe::set_cull_mask); - ClassDB::bind_method(D_METHOD("get_cull_mask"),&ReflectionProbe::get_cull_mask); + ClassDB::bind_method(D_METHOD("set_enable_box_projection", "enable"), &ReflectionProbe::set_enable_box_projection); + ClassDB::bind_method(D_METHOD("is_box_projection_enabled"), &ReflectionProbe::is_box_projection_enabled); - ClassDB::bind_method(D_METHOD("set_update_mode","mode"),&ReflectionProbe::set_update_mode); - ClassDB::bind_method(D_METHOD("get_update_mode"),&ReflectionProbe::get_update_mode); + ClassDB::bind_method(D_METHOD("set_enable_shadows", "enable"), &ReflectionProbe::set_enable_shadows); + ClassDB::bind_method(D_METHOD("are_shadows_enabled"), &ReflectionProbe::are_shadows_enabled); - ADD_PROPERTY( PropertyInfo(Variant::INT,"update_mode",PROPERTY_HINT_ENUM,"Once,Always"),"set_update_mode","get_update_mode"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"intensity",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_intensity","get_intensity"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"max_distance",PROPERTY_HINT_RANGE,"0,16384,0.1"),"set_max_distance","get_max_distance"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"extents"),"set_extents","get_extents"); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"origin_offset"),"set_origin_offset","get_origin_offset"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"box_projection"),"set_enable_box_projection","is_box_projection_enabled"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enable_shadows"),"set_enable_shadows","are_shadows_enabled"); - ADD_PROPERTY( PropertyInfo(Variant::INT,"cull_mask",PROPERTY_HINT_LAYERS_3D_RENDER),"set_cull_mask","get_cull_mask"); + ClassDB::bind_method(D_METHOD("set_cull_mask", "layers"), &ReflectionProbe::set_cull_mask); + ClassDB::bind_method(D_METHOD("get_cull_mask"), &ReflectionProbe::get_cull_mask); - ADD_GROUP("Interior","interior_"); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"interior_enable"),"set_as_interior","is_set_as_interior"); - ADD_PROPERTY( PropertyInfo(Variant::COLOR,"interior_ambient_color",PROPERTY_HINT_COLOR_NO_ALPHA),"set_interior_ambient","get_interior_ambient"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"interior_ambient_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_interior_ambient_energy","get_interior_ambient_energy"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"interior_ambient_contrib",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_interior_ambient_probe_contribution","get_interior_ambient_probe_contribution"); + ClassDB::bind_method(D_METHOD("set_update_mode", "mode"), &ReflectionProbe::set_update_mode); + ClassDB::bind_method(D_METHOD("get_update_mode"), &ReflectionProbe::get_update_mode); + ADD_PROPERTY(PropertyInfo(Variant::INT, "update_mode", PROPERTY_HINT_ENUM, "Once,Always"), "set_update_mode", "get_update_mode"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "intensity", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_intensity", "get_intensity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "max_distance", PROPERTY_HINT_RANGE, "0,16384,0.1"), "set_max_distance", "get_max_distance"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "extents"), "set_extents", "get_extents"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "origin_offset"), "set_origin_offset", "get_origin_offset"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "box_projection"), "set_enable_box_projection", "is_box_projection_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enable_shadows"), "set_enable_shadows", "are_shadows_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "cull_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_cull_mask", "get_cull_mask"); - BIND_CONSTANT( UPDATE_ONCE ); - BIND_CONSTANT( UPDATE_ALWAYS ); + ADD_GROUP("Interior", "interior_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior_enable"), "set_as_interior", "is_set_as_interior"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "interior_ambient_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_interior_ambient", "get_interior_ambient"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "interior_ambient_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_interior_ambient_energy", "get_interior_ambient_energy"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "interior_ambient_contrib", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_interior_ambient_probe_contribution", "get_interior_ambient_probe_contribution"); + BIND_CONSTANT(UPDATE_ONCE); + BIND_CONSTANT(UPDATE_ALWAYS); } ReflectionProbe::ReflectionProbe() { - intensity=1.0; - interior_ambient=Color(0,0,0); - interior_ambient_probe_contribution=0; - interior_ambient_energy=1.0; - max_distance=0; - extents=Vector3(1,1,1); - origin_offset=Vector3(0,0,0); - box_projection=false; - interior=false; - enable_shadows=false; - cull_mask=(1<<20)-1; - update_mode=UPDATE_ONCE; - - probe=VisualServer::get_singleton()->reflection_probe_create(); - VS::get_singleton()->instance_set_base(get_instance(),probe); + intensity = 1.0; + interior_ambient = Color(0, 0, 0); + interior_ambient_probe_contribution = 0; + interior_ambient_energy = 1.0; + max_distance = 0; + extents = Vector3(1, 1, 1); + origin_offset = Vector3(0, 0, 0); + box_projection = false; + interior = false; + enable_shadows = false; + cull_mask = (1 << 20) - 1; + update_mode = UPDATE_ONCE; + + probe = VisualServer::get_singleton()->reflection_probe_create(); + VS::get_singleton()->instance_set_base(get_instance(), probe); } ReflectionProbe::~ReflectionProbe() { diff --git a/scene/3d/reflection_probe.h b/scene/3d/reflection_probe.h index cfda186d8..a2e4a18d6 100644 --- a/scene/3d/reflection_probe.h +++ b/scene/3d/reflection_probe.h @@ -30,23 +30,20 @@ #define REFLECTIONPROBE_H #include "scene/3d/visual_instance.h" -#include "scene/resources/texture.h" #include "scene/resources/sky_box.h" +#include "scene/resources/texture.h" #include "servers/visual_server.h" class ReflectionProbe : public VisualInstance { - GDCLASS(ReflectionProbe,VisualInstance); + GDCLASS(ReflectionProbe, VisualInstance); public: - enum UpdateMode { UPDATE_ONCE, UPDATE_ALWAYS, }; - private: - RID probe; float intensity; float max_distance; @@ -63,12 +60,10 @@ private: UpdateMode update_mode; protected: - static void _bind_methods(); - void _validate_property(PropertyInfo& property) const; + void _validate_property(PropertyInfo &property) const; public: - void set_intensity(float p_intensity); float get_intensity() const; @@ -84,10 +79,10 @@ public: void set_max_distance(float p_distance); float get_max_distance() const; - void set_extents(const Vector3& p_extents); + void set_extents(const Vector3 &p_extents); Vector3 get_extents() const; - void set_origin_offset(const Vector3& p_extents); + void set_origin_offset(const Vector3 &p_extents); Vector3 get_origin_offset() const; void set_as_interior(bool p_enable); @@ -108,13 +103,10 @@ public: virtual Rect3 get_aabb() const; virtual PoolVector get_faces(uint32_t p_usage_flags) const; - - ReflectionProbe(); ~ReflectionProbe(); }; - -VARIANT_ENUM_CAST( ReflectionProbe::UpdateMode ); +VARIANT_ENUM_CAST(ReflectionProbe::UpdateMode); #endif // REFLECTIONPROBE_H diff --git a/scene/3d/remote_transform.cpp b/scene/3d/remote_transform.cpp index 21ec65f5e..202206dd0 100644 --- a/scene/3d/remote_transform.cpp +++ b/scene/3d/remote_transform.cpp @@ -31,20 +31,19 @@ #include "remote_transform.h" void RemoteTransform::_update_cache() { - cache=0; + cache = 0; if (has_node(remote_node)) { Node *node = get_node(remote_node); - if (!node || this==node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) { + if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) { return; } - cache=node->get_instance_ID(); + cache = node->get_instance_ID(); } } void RemoteTransform::_update_remote() { - if (!is_inside_tree()) return; @@ -64,12 +63,11 @@ void RemoteTransform::_update_remote() { //todo make faster n->set_global_transform(get_global_transform()); - } void RemoteTransform::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_READY: { @@ -83,30 +81,26 @@ void RemoteTransform::_notification(int p_what) { if (cache) { _update_remote(); - } } break; - } } +void RemoteTransform::set_remote_node(const NodePath &p_remote_node) { -void RemoteTransform::set_remote_node(const NodePath& p_remote_node) { - - remote_node=p_remote_node; + remote_node = p_remote_node; if (is_inside_tree()) _update_cache(); update_configuration_warning(); } -NodePath RemoteTransform::get_remote_node() const{ +NodePath RemoteTransform::get_remote_node() const { return remote_node; } - String RemoteTransform::get_configuration_warning() const { if (!has_node(remote_node) || !get_node(remote_node) || !get_node(remote_node)->cast_to()) { @@ -118,16 +112,14 @@ String RemoteTransform::get_configuration_warning() const { void RemoteTransform::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_remote_node","path"),&RemoteTransform::set_remote_node); - ClassDB::bind_method(D_METHOD("get_remote_node"),&RemoteTransform::get_remote_node); + ClassDB::bind_method(D_METHOD("set_remote_node", "path"), &RemoteTransform::set_remote_node); + ClassDB::bind_method(D_METHOD("get_remote_node"), &RemoteTransform::get_remote_node); - ADD_PROPERTY( PropertyInfo(Variant::NODE_PATH,"remote_path"),"set_remote_node","get_remote_node"); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "remote_path"), "set_remote_node", "get_remote_node"); } RemoteTransform::RemoteTransform() { - cache=0; + cache = 0; set_notify_transform(true); - } - diff --git a/scene/3d/remote_transform.h b/scene/3d/remote_transform.h index 6bc4763e2..fdfd959a9 100644 --- a/scene/3d/remote_transform.h +++ b/scene/3d/remote_transform.h @@ -31,28 +31,27 @@ #include "scene/3d/spatial.h" -class RemoteTransform : public Spatial -{ - GDCLASS(RemoteTransform,Spatial); - +class RemoteTransform : public Spatial { + GDCLASS(RemoteTransform, Spatial); + NodePath remote_node; ObjectID cache; void _update_remote(); - void _update_cache(); - + void _update_cache(); + protected: static void _bind_methods(); void _notification(int p_what); + public: - void set_remote_node(const NodePath& p_remote_node); + void set_remote_node(const NodePath &p_remote_node); NodePath get_remote_node() const; - + virtual String get_configuration_warning() const; - - RemoteTransform(); + RemoteTransform(); }; #endif // REMOTETRANSFORM_H diff --git a/scene/3d/room_instance.cpp b/scene/3d/room_instance.cpp index b363c05ef..3b6ae32d1 100644 --- a/scene/3d/room_instance.cpp +++ b/scene/3d/room_instance.cpp @@ -34,44 +34,35 @@ #include "global_config.h" #include "scene/resources/surface_tool.h" - void Room::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_WORLD: { // go find parent level - Node *parent_room=get_parent(); - level=0; + Node *parent_room = get_parent(); + level = 0; - while(parent_room) { + while (parent_room) { Room *r = parent_room->cast_to(); if (r) { - level=r->level+1; + level = r->level + 1; break; } - parent_room=parent_room->get_parent(); + parent_room = parent_room->get_parent(); } - } break; case NOTIFICATION_TRANSFORM_CHANGED: { } break; case NOTIFICATION_EXIT_WORLD: { - - - } break; + } break; } - } - - - - Rect3 Room::get_aabb() const { if (room.is_null()) @@ -83,12 +74,11 @@ Rect3 Room::get_aabb() const { PoolVector Room::get_faces(uint32_t p_usage_flags) const { return PoolVector(); - } -void Room::set_room( const Ref& p_room ) { +void Room::set_room(const Ref &p_room) { - room=p_room; + room = p_room; update_gizmo(); if (room.is_valid()) { @@ -101,11 +91,8 @@ void Room::set_room( const Ref& p_room ) { if (!is_inside_tree()) return; - propagate_notification(NOTIFICATION_AREA_CHANGED); update_gizmo(); - - } Ref Room::get_room() const { @@ -113,75 +100,60 @@ Ref Room::get_room() const { return room; } -void Room::_parse_node_faces(PoolVector &all_faces,const Node *p_node) const { +void Room::_parse_node_faces(PoolVector &all_faces, const Node *p_node) const { - const VisualInstance *vi=p_node->cast_to(); + const VisualInstance *vi = p_node->cast_to(); if (vi) { - PoolVector faces=vi->get_faces(FACES_ENCLOSING); + PoolVector faces = vi->get_faces(FACES_ENCLOSING); if (faces.size()) { - int old_len=all_faces.size(); - all_faces.resize( all_faces.size() + faces.size() ); - int new_len=all_faces.size(); - PoolVector::Write all_facesw=all_faces.write(); - Face3 * all_facesptr=all_facesw.ptr(); + int old_len = all_faces.size(); + all_faces.resize(all_faces.size() + faces.size()); + int new_len = all_faces.size(); + PoolVector::Write all_facesw = all_faces.write(); + Face3 *all_facesptr = all_facesw.ptr(); - PoolVector::Read facesr=faces.read(); - const Face3 * facesptr=facesr.ptr(); + PoolVector::Read facesr = faces.read(); + const Face3 *facesptr = facesr.ptr(); - Transform tr=vi->get_relative_transform(this); + Transform tr = vi->get_relative_transform(this); - for(int i=old_len;iget_child_count(); i++) { - for (int i=0;iget_child_count();i++) { - - _parse_node_faces(all_faces,p_node->get_child(i)); + _parse_node_faces(all_faces, p_node->get_child(i)); } - } - - void Room::_bounds_changed() { update_gizmo(); } - - void Room::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_room","room:Room"),&Room::set_room ); - ClassDB::bind_method(D_METHOD("get_room:Room"),&Room::get_room ); - - - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "room/room", PROPERTY_HINT_RESOURCE_TYPE, "Area" ), "set_room", "get_room") ; + ClassDB::bind_method(D_METHOD("set_room", "room:Room"), &Room::set_room); + ClassDB::bind_method(D_METHOD("get_room:Room"), &Room::get_room); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "room/room", PROPERTY_HINT_RESOURCE_TYPE, "Area"), "set_room", "get_room"); } - Room::Room() { -// sound_enabled=false; - - level=0; - + // sound_enabled=false; + level = 0; } - Room::~Room() { - - } - diff --git a/scene/3d/room_instance.h b/scene/3d/room_instance.h index cbc1b12b7..68be5eecf 100644 --- a/scene/3d/room_instance.h +++ b/scene/3d/room_instance.h @@ -36,7 +36,6 @@ @author Juan Linietsky */ - /* RoomInstance Logic: a) Instances that belong to the room are drawn only if the room is visible (seen through portal, or player inside) b) Instances that don't belong to any room are considered to belong to the root room (RID empty) @@ -44,52 +43,38 @@ */ - - - class Room : public VisualInstance { - GDCLASS( Room, VisualInstance ); -public: - - - + GDCLASS(Room, VisualInstance); +public: private: Ref room; - int level; - void _parse_node_faces(PoolVector &all_faces,const Node *p_node) const; - + void _parse_node_faces(PoolVector &all_faces, const Node *p_node) const; void _bounds_changed(); - protected: - void _notification(int p_what); static void _bind_methods(); public: - enum { // used to notify portals that the room in which they are has changed. - NOTIFICATION_AREA_CHANGED=60 + NOTIFICATION_AREA_CHANGED = 60 }; virtual Rect3 get_aabb() const; virtual PoolVector get_faces(uint32_t p_usage_flags) const; - void set_room( const Ref& p_room ); + void set_room(const Ref &p_room); Ref get_room() const; - Room(); ~Room(); - }; - #endif // ROOM_INSTANCE_H diff --git a/scene/3d/scenario_fx.cpp b/scene/3d/scenario_fx.cpp index 145242ba7..92ee608f7 100644 --- a/scene/3d/scenario_fx.cpp +++ b/scene/3d/scenario_fx.cpp @@ -28,49 +28,42 @@ /*************************************************************************/ #include "scenario_fx.h" - - void WorldEnvironment::_notification(int p_what) { - - if (p_what==NOTIFICATION_ENTER_WORLD) { + if (p_what == NOTIFICATION_ENTER_WORLD) { if (environment.is_valid()) { if (get_world()->get_environment().is_valid()) { WARN_PRINT("World already has an environment (Another WorldEnvironment?), overriding."); } get_world()->set_environment(environment); - add_to_group("_world_environment_"+itos(get_world()->get_scenario().get_id())); - + add_to_group("_world_environment_" + itos(get_world()->get_scenario().get_id())); } - } else if (p_what==NOTIFICATION_EXIT_WORLD) { + } else if (p_what == NOTIFICATION_EXIT_WORLD) { - if (environment.is_valid() && get_world()->get_environment()==environment) { + if (environment.is_valid() && get_world()->get_environment() == environment) { get_world()->set_environment(Ref()); - remove_from_group("_world_environment_"+itos(get_world()->get_scenario().get_id())); - + remove_from_group("_world_environment_" + itos(get_world()->get_scenario().get_id())); } } } -void WorldEnvironment::set_environment(const Ref& p_environment) { +void WorldEnvironment::set_environment(const Ref &p_environment) { - if (is_inside_world() && environment.is_valid() && get_world()->get_environment()==environment) { + if (is_inside_world() && environment.is_valid() && get_world()->get_environment() == environment) { get_world()->set_environment(Ref()); - remove_from_group("_world_environment_"+itos(get_world()->get_scenario().get_id())); + remove_from_group("_world_environment_" + itos(get_world()->get_scenario().get_id())); //clean up } - - environment=p_environment; + environment = p_environment; if (is_inside_world() && environment.is_valid()) { if (get_world()->get_environment().is_valid()) { WARN_PRINT("World already has an environment (Another WorldEnvironment?), overriding."); } get_world()->set_environment(environment); - add_to_group("_world_environment_"+itos(get_world()->get_scenario().get_id())); - + add_to_group("_world_environment_" + itos(get_world()->get_scenario().get_id())); } update_configuration_warning(); @@ -86,29 +79,22 @@ String WorldEnvironment::get_configuration_warning() const { if (!is_visible_in_tree() || !is_inside_tree() || !environment.is_valid()) return String(); - List nodes; - get_tree()->get_nodes_in_group("_world_environment_"+itos(get_world()->get_scenario().get_id()),&nodes); + List nodes; + get_tree()->get_nodes_in_group("_world_environment_" + itos(get_world()->get_scenario().get_id()), &nodes); - if (nodes.size()>1) { + if (nodes.size() > 1) { return TTR("Only one WorldEnvironment is allowed per scene (or set of instanced scenes)."); } return String(); } - void WorldEnvironment::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_environment","env:Environment"),&WorldEnvironment::set_environment); - ClassDB::bind_method(D_METHOD("get_environment:Environment"),&WorldEnvironment::get_environment); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"environment",PROPERTY_HINT_RESOURCE_TYPE,"Environment"),"set_environment","get_environment"); - + ClassDB::bind_method(D_METHOD("set_environment", "env:Environment"), &WorldEnvironment::set_environment); + ClassDB::bind_method(D_METHOD("get_environment:Environment"), &WorldEnvironment::get_environment); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "environment", PROPERTY_HINT_RESOURCE_TYPE, "Environment"), "set_environment", "get_environment"); } - WorldEnvironment::WorldEnvironment() { - - } - - diff --git a/scene/3d/scenario_fx.h b/scene/3d/scenario_fx.h index ef5b70039..bbdffdc13 100644 --- a/scene/3d/scenario_fx.h +++ b/scene/3d/scenario_fx.h @@ -31,30 +31,27 @@ #include "scene/3d/spatial.h" - /** @author Juan Linietsky */ - class WorldEnvironment : public Spatial { - GDCLASS(WorldEnvironment,Spatial ); + GDCLASS(WorldEnvironment, Spatial); Ref environment; protected: - void _notification(int p_what); static void _bind_methods(); + public: - void set_environment(const Ref& p_environment); + void set_environment(const Ref &p_environment); Ref get_environment() const; String get_configuration_warning() const; WorldEnvironment(); - }; #endif diff --git a/scene/3d/skeleton.cpp b/scene/3d/skeleton.cpp index 04e82ba91..3a5453c8e 100644 --- a/scene/3d/skeleton.cpp +++ b/scene/3d/skeleton.cpp @@ -30,50 +30,48 @@ #include "message_queue.h" -#include "scene/resources/surface_tool.h" #include "core/global_config.h" +#include "scene/resources/surface_tool.h" - -bool Skeleton::_set(const StringName& p_path, const Variant& p_value) { +bool Skeleton::_set(const StringName &p_path, const Variant &p_value) { String path = p_path; if (!path.begins_with("bones/")) return false; - int which=path.get_slicec('/',1).to_int(); - String what=path.get_slicec('/',2); + int which = path.get_slicec('/', 1).to_int(); + String what = path.get_slicec('/', 2); - - if (which==bones.size() && what=="name") { + if (which == bones.size() && what == "name") { add_bone(p_value); return true; } - ERR_FAIL_INDEX_V( which, bones.size(), false ); + ERR_FAIL_INDEX_V(which, bones.size(), false); - if (what=="parent") - set_bone_parent(which, p_value ); - else if (what=="rest") + if (what == "parent") + set_bone_parent(which, p_value); + else if (what == "rest") set_bone_rest(which, p_value); - else if (what=="enabled") + else if (what == "enabled") set_bone_enabled(which, p_value); - else if (what=="pose") + else if (what == "pose") set_bone_pose(which, p_value); - else if (what=="bound_childs") { - Array children=p_value; + else if (what == "bound_childs") { + Array children = p_value; if (is_inside_tree()) { bones[which].nodes_bound.clear(); - for (int i=0;i::Element *E=bones[which].nodes_bound.front();E;E=E->next()) { + for (const List::Element *E = bones[which].nodes_bound.front(); E; E = E->next()) { - Object *obj=ObjectDB::get_instance(E->get()); + Object *obj = ObjectDB::get_instance(E->get()); ERR_CONTINUE(!obj); - Node *node=obj->cast_to(); + Node *node = obj->cast_to(); ERR_CONTINUE(!node); - NodePath path=get_path_to(node); + NodePath path = get_path_to(node); children.push_back(path); - } - r_ret=children; + r_ret = children; } else return false; return true; - } -void Skeleton::_get_property_list( List* p_list ) const { +void Skeleton::_get_property_list(List *p_list) const { - for (int i=0;ipush_back( PropertyInfo( Variant::STRING, prep+"name" ) ); - p_list->push_back( PropertyInfo( Variant::INT, prep+"parent" , PROPERTY_HINT_RANGE,"-1,"+itos(i-1)+",1") ); - p_list->push_back( PropertyInfo( Variant::TRANSFORM, prep+"rest" ) ); - p_list->push_back( PropertyInfo( Variant::BOOL, prep+"enabled" ) ); - p_list->push_back( PropertyInfo( Variant::TRANSFORM, prep+"pose", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR ) ); - p_list->push_back( PropertyInfo( Variant::ARRAY, prep+"bound_childs" ) ); + String prep = "bones/" + itos(i) + "/"; + p_list->push_back(PropertyInfo(Variant::STRING, prep + "name")); + p_list->push_back(PropertyInfo(Variant::INT, prep + "parent", PROPERTY_HINT_RANGE, "-1," + itos(i - 1) + ",1")); + p_list->push_back(PropertyInfo(Variant::TRANSFORM, prep + "rest")); + p_list->push_back(PropertyInfo(Variant::BOOL, prep + "enabled")); + p_list->push_back(PropertyInfo(Variant::TRANSFORM, prep + "pose", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR)); + p_list->push_back(PropertyInfo(Variant::ARRAY, prep + "bound_childs")); } } void Skeleton::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_WORLD: { if (dirty) { - dirty=false; + dirty = false; _make_dirty(); // property make it dirty } @@ -158,97 +154,95 @@ void Skeleton::_notification(int p_what) { } break; case NOTIFICATION_UPDATE_SKELETON: { + VisualServer *vs = VisualServer::get_singleton(); + Bone *bonesptr = &bones[0]; + int len = bones.size(); - VisualServer *vs=VisualServer::get_singleton(); - Bone *bonesptr=&bones[0]; - int len=bones.size(); - - vs->skeleton_allocate( skeleton, len ); // if same size, nothin really happens + vs->skeleton_allocate(skeleton, len); // if same size, nothin really happens // pose changed, rebuild cache of inverses if (rest_global_inverse_dirty) { // calculate global rests and invert them - for (int i=0;i=0) - b.rest_global_inverse=bonesptr[b.parent].rest_global_inverse * b.rest; + for (int i = 0; i < len; i++) { + Bone &b = bonesptr[i]; + if (b.parent >= 0) + b.rest_global_inverse = bonesptr[b.parent].rest_global_inverse * b.rest; else - b.rest_global_inverse=b.rest; + b.rest_global_inverse = b.rest; } - for (int i=0;i=0) { + if (b.parent >= 0) { - b.pose_global=bonesptr[b.parent].pose_global * pose; + b.pose_global = bonesptr[b.parent].pose_global * pose; } else { - b.pose_global=pose; + b.pose_global = pose; } } else { - if (b.parent>=0) { + if (b.parent >= 0) { - b.pose_global=bonesptr[b.parent].pose_global; + b.pose_global = bonesptr[b.parent].pose_global; } else { - b.pose_global=Transform(); + b.pose_global = Transform(); } } } else { if (b.enabled) { - Transform pose=b.pose; + Transform pose = b.pose; if (b.custom_pose_enable) { pose = b.custom_pose * pose; } - if (b.parent>=0) { + if (b.parent >= 0) { - b.pose_global=bonesptr[b.parent].pose_global * (b.rest * pose); + b.pose_global = bonesptr[b.parent].pose_global * (b.rest * pose); } else { - b.pose_global=b.rest * pose; + b.pose_global = b.rest * pose; } } else { - if (b.parent>=0) { + if (b.parent >= 0) { - b.pose_global=bonesptr[b.parent].pose_global * b.rest; + b.pose_global = bonesptr[b.parent].pose_global * b.rest; } else { - b.pose_global=b.rest; + b.pose_global = b.rest; } } } - vs->skeleton_bone_set_transform( skeleton, i, b.pose_global * b.rest_global_inverse ); + vs->skeleton_bone_set_transform(skeleton, i, b.pose_global * b.rest_global_inverse); - for(List::Element *E=b.nodes_bound.front();E;E=E->next()) { + for (List::Element *E = b.nodes_bound.front(); E; E = E->next()) { - Object *obj=ObjectDB::get_instance(E->get()); + Object *obj = ObjectDB::get_instance(E->get()); ERR_CONTINUE(!obj); Spatial *sp = obj->cast_to(); ERR_CONTINUE(!sp); @@ -256,38 +250,35 @@ void Skeleton::_notification(int p_what) { } } - dirty=false; + dirty = false; } break; } } Transform Skeleton::get_bone_transform(int p_bone) const { - ERR_FAIL_INDEX_V(p_bone,bones.size(),Transform()); + ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform()); if (dirty) - const_cast(this)->notification(NOTIFICATION_UPDATE_SKELETON); + const_cast(this)->notification(NOTIFICATION_UPDATE_SKELETON); return bones[p_bone].pose_global * bones[p_bone].rest_global_inverse; } +void Skeleton::set_bone_global_pose(int p_bone, const Transform &p_pose) { -void Skeleton::set_bone_global_pose(int p_bone,const Transform& p_pose) { + ERR_FAIL_INDEX(p_bone, bones.size()); + if (bones[p_bone].parent == -1) { - ERR_FAIL_INDEX(p_bone,bones.size()); - if (bones[p_bone].parent==-1) { - - set_bone_pose(p_bone,bones[p_bone].rest_global_inverse * p_pose); //fast + set_bone_pose(p_bone, bones[p_bone].rest_global_inverse * p_pose); //fast } else { set_bone_pose(p_bone, bones[p_bone].rest.affine_inverse() * (get_bone_global_pose(bones[p_bone].parent).affine_inverse() * p_pose)); //slow - } - } Transform Skeleton::get_bone_global_pose(int p_bone) const { - ERR_FAIL_INDEX_V(p_bone,bones.size(),Transform()); + ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform()); if (dirty) - const_cast(this)->notification(NOTIFICATION_UPDATE_SKELETON); + const_cast(this)->notification(NOTIFICATION_UPDATE_SKELETON); return bones[p_bone].pose_global; } @@ -297,28 +288,28 @@ RID Skeleton::get_skeleton() const { } // skeleton creation api -void Skeleton::add_bone(const String& p_name) { +void Skeleton::add_bone(const String &p_name) { - ERR_FAIL_COND( p_name=="" || p_name.find(":")!=-1 || p_name.find("/")!=-1 ); + ERR_FAIL_COND(p_name == "" || p_name.find(":") != -1 || p_name.find("/") != -1); - for (int i=0;i=p_bone)); + ERR_FAIL_INDEX(p_bone, bones.size()); + ERR_FAIL_COND(p_parent != -1 && (p_parent < 0 || p_parent >= p_bone)); - bones[p_bone].parent=p_parent; - rest_global_inverse_dirty=true; + bones[p_bone].parent = p_parent; + rest_global_inverse_dirty = true; _make_dirty(); } void Skeleton::unparent_bone_and_rest(int p_bone) { - ERR_FAIL_INDEX( p_bone, bones.size() ); + ERR_FAIL_INDEX(p_bone, bones.size()); - int parent=bones[p_bone].parent; - while(parent>=0) { + int parent = bones[p_bone].parent; + while (parent >= 0) { bones[p_bone].rest = bones[parent].rest * bones[p_bone].rest; - parent=bones[parent].parent; + parent = bones[parent].parent; } - bones[p_bone].parent=-1; - bones[p_bone].rest_global_inverse=bones[p_bone].rest.affine_inverse(); //same thing + bones[p_bone].parent = -1; + bones[p_bone].rest_global_inverse = bones[p_bone].rest.affine_inverse(); //same thing _make_dirty(); - } void Skeleton::set_bone_disable_rest(int p_bone, bool p_disable) { - ERR_FAIL_INDEX( p_bone, bones.size() ); - bones[p_bone].disable_rest=p_disable; - + ERR_FAIL_INDEX(p_bone, bones.size()); + bones[p_bone].disable_rest = p_disable; } bool Skeleton::is_bone_rest_disabled(int p_bone) const { - ERR_FAIL_INDEX_V( p_bone, bones.size(), false ); + ERR_FAIL_INDEX_V(p_bone, bones.size(), false); return bones[p_bone].disable_rest; } - int Skeleton::get_bone_parent(int p_bone) const { - ERR_FAIL_INDEX_V( p_bone, bones.size(), -1 ); + ERR_FAIL_INDEX_V(p_bone, bones.size(), -1); return bones[p_bone].parent; } -void Skeleton::set_bone_rest(int p_bone, const Transform& p_rest) { +void Skeleton::set_bone_rest(int p_bone, const Transform &p_rest) { - ERR_FAIL_INDEX( p_bone, bones.size() ); + ERR_FAIL_INDEX(p_bone, bones.size()); - bones[p_bone].rest=p_rest; - rest_global_inverse_dirty=true; + bones[p_bone].rest = p_rest; + rest_global_inverse_dirty = true; _make_dirty(); - } Transform Skeleton::get_bone_rest(int p_bone) const { - ERR_FAIL_INDEX_V( p_bone, bones.size(), Transform() ); + ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform()); return bones[p_bone].rest; - } void Skeleton::set_bone_enabled(int p_bone, bool p_enabled) { - ERR_FAIL_INDEX( p_bone, bones.size() ); + ERR_FAIL_INDEX(p_bone, bones.size()); - bones[p_bone].enabled=p_enabled; - rest_global_inverse_dirty=true; + bones[p_bone].enabled = p_enabled; + rest_global_inverse_dirty = true; _make_dirty(); } bool Skeleton::is_bone_enabled(int p_bone) const { - ERR_FAIL_INDEX_V( p_bone, bones.size(), false ); + ERR_FAIL_INDEX_V(p_bone, bones.size(), false); return bones[p_bone].enabled; - } -void Skeleton::bind_child_node_to_bone(int p_bone,Node *p_node) { +void Skeleton::bind_child_node_to_bone(int p_bone, Node *p_node) { ERR_FAIL_NULL(p_node); - ERR_FAIL_INDEX( p_bone, bones.size() ); + ERR_FAIL_INDEX(p_bone, bones.size()); - uint32_t id=p_node->get_instance_ID(); + uint32_t id = p_node->get_instance_ID(); - for (List::Element *E=bones[p_bone].nodes_bound.front();E;E=E->next()) { + for (List::Element *E = bones[p_bone].nodes_bound.front(); E; E = E->next()) { - if (E->get()==id) + if (E->get() == id) return; // already here } bones[p_bone].nodes_bound.push_back(id); - } -void Skeleton::unbind_child_node_from_bone(int p_bone,Node *p_node) { +void Skeleton::unbind_child_node_from_bone(int p_bone, Node *p_node) { ERR_FAIL_NULL(p_node); - ERR_FAIL_INDEX( p_bone, bones.size() ); + ERR_FAIL_INDEX(p_bone, bones.size()); - uint32_t id=p_node->get_instance_ID(); + uint32_t id = p_node->get_instance_ID(); bones[p_bone].nodes_bound.erase(id); - } -void Skeleton::get_bound_child_nodes_to_bone(int p_bone,List *p_bound) const { +void Skeleton::get_bound_child_nodes_to_bone(int p_bone, List *p_bound) const { - ERR_FAIL_INDEX( p_bone, bones.size() ); + ERR_FAIL_INDEX(p_bone, bones.size()); - for (const List::Element *E=bones[p_bone].nodes_bound.front();E;E=E->next()) { + for (const List::Element *E = bones[p_bone].nodes_bound.front(); E; E = E->next()) { - Object *obj=ObjectDB::get_instance(E->get()); + Object *obj = ObjectDB::get_instance(E->get()); ERR_CONTINUE(!obj); p_bound->push_back(obj->cast_to()); } - } void Skeleton::clear_bones() { bones.clear(); - rest_global_inverse_dirty=true; + rest_global_inverse_dirty = true; _make_dirty(); } // posing api -void Skeleton::set_bone_pose(int p_bone, const Transform& p_pose) { - - ERR_FAIL_INDEX( p_bone, bones.size() ); - ERR_FAIL_COND( !is_inside_tree() ); +void Skeleton::set_bone_pose(int p_bone, const Transform &p_pose) { + ERR_FAIL_INDEX(p_bone, bones.size()); + ERR_FAIL_COND(!is_inside_tree()); - bones[p_bone].pose=p_pose; + bones[p_bone].pose = p_pose; _make_dirty(); } Transform Skeleton::get_bone_pose(int p_bone) const { - ERR_FAIL_INDEX_V( p_bone, bones.size(), Transform() ); + ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform()); return bones[p_bone].pose; - } -void Skeleton::set_bone_custom_pose(int p_bone, const Transform& p_custom_pose) { +void Skeleton::set_bone_custom_pose(int p_bone, const Transform &p_custom_pose) { - ERR_FAIL_INDEX( p_bone, bones.size() ); + ERR_FAIL_INDEX(p_bone, bones.size()); //ERR_FAIL_COND( !is_inside_scene() ); - - bones[p_bone].custom_pose_enable=(p_custom_pose!=Transform()); - bones[p_bone].custom_pose=p_custom_pose; + bones[p_bone].custom_pose_enable = (p_custom_pose != Transform()); + bones[p_bone].custom_pose = p_custom_pose; _make_dirty(); } Transform Skeleton::get_bone_custom_pose(int p_bone) const { - ERR_FAIL_INDEX_V( p_bone, bones.size(), Transform() ); + ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform()); return bones[p_bone].custom_pose; - } - void Skeleton::_make_dirty() { if (dirty) return; if (!is_inside_tree()) { - dirty=true; + dirty = true; return; } - MessageQueue::get_singleton()->push_notification( this, NOTIFICATION_UPDATE_SKELETON ); - dirty=true; + MessageQueue::get_singleton()->push_notification(this, NOTIFICATION_UPDATE_SKELETON); + dirty = true; } - - void Skeleton::localize_rests() { - for(int i=bones.size()-1;i>=0;i--) { + for (int i = bones.size() - 1; i >= 0; i--) { - if (bones[i].parent>=0) - set_bone_rest(i,bones[bones[i].parent].rest.affine_inverse() * bones[i].rest); + if (bones[i].parent >= 0) + set_bone_rest(i, bones[bones[i].parent].rest.affine_inverse() * bones[i].rest); } } - - void Skeleton::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_bone", "name"), &Skeleton::add_bone); + ClassDB::bind_method(D_METHOD("find_bone", "name"), &Skeleton::find_bone); + ClassDB::bind_method(D_METHOD("get_bone_name", "bone_idx"), &Skeleton::get_bone_name); + ClassDB::bind_method(D_METHOD("get_bone_parent", "bone_idx"), &Skeleton::get_bone_parent); + ClassDB::bind_method(D_METHOD("set_bone_parent", "bone_idx", "parent_idx"), &Skeleton::set_bone_parent); + ClassDB::bind_method(D_METHOD("get_bone_count"), &Skeleton::get_bone_count); - ClassDB::bind_method(D_METHOD("add_bone","name"),&Skeleton::add_bone); - ClassDB::bind_method(D_METHOD("find_bone","name"),&Skeleton::find_bone); - ClassDB::bind_method(D_METHOD("get_bone_name","bone_idx"),&Skeleton::get_bone_name); - - ClassDB::bind_method(D_METHOD("get_bone_parent","bone_idx"),&Skeleton::get_bone_parent); - ClassDB::bind_method(D_METHOD("set_bone_parent","bone_idx","parent_idx"),&Skeleton::set_bone_parent); - - ClassDB::bind_method(D_METHOD("get_bone_count"),&Skeleton::get_bone_count); + ClassDB::bind_method(D_METHOD("unparent_bone_and_rest", "bone_idx"), &Skeleton::unparent_bone_and_rest); - ClassDB::bind_method(D_METHOD("unparent_bone_and_rest","bone_idx"),&Skeleton::unparent_bone_and_rest); + ClassDB::bind_method(D_METHOD("get_bone_rest", "bone_idx"), &Skeleton::get_bone_rest); + ClassDB::bind_method(D_METHOD("set_bone_rest", "bone_idx", "rest"), &Skeleton::set_bone_rest); - ClassDB::bind_method(D_METHOD("get_bone_rest","bone_idx"),&Skeleton::get_bone_rest); - ClassDB::bind_method(D_METHOD("set_bone_rest","bone_idx","rest"),&Skeleton::set_bone_rest); + ClassDB::bind_method(D_METHOD("set_bone_disable_rest", "bone_idx", "disable"), &Skeleton::set_bone_disable_rest); + ClassDB::bind_method(D_METHOD("is_bone_rest_disabled", "bone_idx"), &Skeleton::is_bone_rest_disabled); - ClassDB::bind_method(D_METHOD("set_bone_disable_rest","bone_idx","disable"),&Skeleton::set_bone_disable_rest); - ClassDB::bind_method(D_METHOD("is_bone_rest_disabled","bone_idx"),&Skeleton::is_bone_rest_disabled); + ClassDB::bind_method(D_METHOD("bind_child_node_to_bone", "bone_idx", "node:Node"), &Skeleton::bind_child_node_to_bone); + ClassDB::bind_method(D_METHOD("unbind_child_node_from_bone", "bone_idx", "node:Node"), &Skeleton::unbind_child_node_from_bone); + ClassDB::bind_method(D_METHOD("get_bound_child_nodes_to_bone", "bone_idx"), &Skeleton::_get_bound_child_nodes_to_bone); - ClassDB::bind_method(D_METHOD("bind_child_node_to_bone","bone_idx","node:Node"),&Skeleton::bind_child_node_to_bone); - ClassDB::bind_method(D_METHOD("unbind_child_node_from_bone","bone_idx","node:Node"),&Skeleton::unbind_child_node_from_bone); - ClassDB::bind_method(D_METHOD("get_bound_child_nodes_to_bone","bone_idx"),&Skeleton::_get_bound_child_nodes_to_bone); + ClassDB::bind_method(D_METHOD("clear_bones"), &Skeleton::clear_bones); - ClassDB::bind_method(D_METHOD("clear_bones"),&Skeleton::clear_bones); + ClassDB::bind_method(D_METHOD("get_bone_pose", "bone_idx"), &Skeleton::get_bone_pose); + ClassDB::bind_method(D_METHOD("set_bone_pose", "bone_idx", "pose"), &Skeleton::set_bone_pose); - ClassDB::bind_method(D_METHOD("get_bone_pose","bone_idx"),&Skeleton::get_bone_pose); - ClassDB::bind_method(D_METHOD("set_bone_pose","bone_idx","pose"),&Skeleton::set_bone_pose); + ClassDB::bind_method(D_METHOD("set_bone_global_pose", "bone_idx", "pose"), &Skeleton::set_bone_global_pose); + ClassDB::bind_method(D_METHOD("get_bone_global_pose", "bone_idx"), &Skeleton::get_bone_global_pose); - ClassDB::bind_method(D_METHOD("set_bone_global_pose","bone_idx","pose"),&Skeleton::set_bone_global_pose); - ClassDB::bind_method(D_METHOD("get_bone_global_pose","bone_idx"),&Skeleton::get_bone_global_pose); + ClassDB::bind_method(D_METHOD("get_bone_custom_pose", "bone_idx"), &Skeleton::get_bone_custom_pose); + ClassDB::bind_method(D_METHOD("set_bone_custom_pose", "bone_idx", "custom_pose"), &Skeleton::set_bone_custom_pose); - ClassDB::bind_method(D_METHOD("get_bone_custom_pose","bone_idx"),&Skeleton::get_bone_custom_pose); - ClassDB::bind_method(D_METHOD("set_bone_custom_pose","bone_idx","custom_pose"),&Skeleton::set_bone_custom_pose); + ClassDB::bind_method(D_METHOD("get_bone_transform", "bone_idx"), &Skeleton::get_bone_transform); - ClassDB::bind_method(D_METHOD("get_bone_transform","bone_idx"),&Skeleton::get_bone_transform); - - BIND_CONSTANT( NOTIFICATION_UPDATE_SKELETON ); + BIND_CONSTANT(NOTIFICATION_UPDATE_SKELETON); } - - Skeleton::Skeleton() { - rest_global_inverse_dirty=true; - dirty=false; - skeleton=VisualServer::get_singleton()->skeleton_create(); + rest_global_inverse_dirty = true; + dirty = false; + skeleton = VisualServer::get_singleton()->skeleton_create(); } - Skeleton::~Skeleton() { - VisualServer::get_singleton()->free( skeleton ); + VisualServer::get_singleton()->free(skeleton); } - - diff --git a/scene/3d/skeleton.h b/scene/3d/skeleton.h index 04eb3e900..707428972 100644 --- a/scene/3d/skeleton.h +++ b/scene/3d/skeleton.h @@ -29,15 +29,15 @@ #ifndef SKELETON_H #define SKELETON_H -#include "scene/3d/spatial.h" #include "rid.h" +#include "scene/3d/spatial.h" /** @author Juan Linietsky */ class Skeleton : public Spatial { - GDCLASS( Skeleton, Spatial ); + GDCLASS(Skeleton, Spatial); struct Bone { @@ -58,7 +58,12 @@ class Skeleton : public Spatial { List nodes_bound; - Bone() { parent=-1; enabled=true; custom_pose_enable=false; disable_rest=false; } + Bone() { + parent = -1; + enabled = true; + custom_pose_enable = false; + disable_rest = false; + } }; bool rest_global_inverse_dirty; @@ -70,41 +75,37 @@ class Skeleton : public Spatial { void _make_dirty(); bool dirty; -//bind helpers + //bind helpers Array _get_bound_child_nodes_to_bone(int p_bone) const { Array bound; - List childs; - get_bound_child_nodes_to_bone(p_bone,&childs); + List childs; + get_bound_child_nodes_to_bone(p_bone, &childs); - for (int i=0;i* p_list ) const; + bool _get(const StringName &p_name, Variant &r_ret) const; + bool _set(const StringName &p_name, const Variant &p_value); + void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); public: - enum { - NOTIFICATION_UPDATE_SKELETON=50 + NOTIFICATION_UPDATE_SKELETON = 50 }; - RID get_skeleton() const; // skeleton creation api - void add_bone(const String&p_name); + void add_bone(const String &p_name); int find_bone(String p_name) const; String get_bone_name(int p_bone) const; @@ -118,35 +119,34 @@ public: int get_bone_count() const; - void set_bone_rest(int p_bone, const Transform& p_rest); + void set_bone_rest(int p_bone, const Transform &p_rest); Transform get_bone_rest(int p_bone) const; Transform get_bone_transform(int p_bone) const; Transform get_bone_global_pose(int p_bone) const; - void set_bone_global_pose(int p_bone,const Transform& p_pose); + void set_bone_global_pose(int p_bone, const Transform &p_pose); void set_bone_enabled(int p_bone, bool p_enabled); bool is_bone_enabled(int p_bone) const; - void bind_child_node_to_bone(int p_bone,Node *p_node); - void unbind_child_node_from_bone(int p_bone,Node *p_node); - void get_bound_child_nodes_to_bone(int p_bone,List *p_bound) const; + void bind_child_node_to_bone(int p_bone, Node *p_node); + void unbind_child_node_from_bone(int p_bone, Node *p_node); + void get_bound_child_nodes_to_bone(int p_bone, List *p_bound) const; void clear_bones(); // posing api - void set_bone_pose(int p_bone, const Transform& p_pose); + void set_bone_pose(int p_bone, const Transform &p_pose); Transform get_bone_pose(int p_bone) const; - void set_bone_custom_pose(int p_bone, const Transform& p_custom_pose); + void set_bone_custom_pose(int p_bone, const Transform &p_custom_pose); Transform get_bone_custom_pose(int p_bone) const; void localize_rests(); // used for loaders and tools Skeleton(); ~Skeleton(); - }; #endif diff --git a/scene/3d/spatial.cpp b/scene/3d/spatial.cpp index 58a6a2456..1125a7a4d 100644 --- a/scene/3d/spatial.cpp +++ b/scene/3d/spatial.cpp @@ -28,8 +28,8 @@ /*************************************************************************/ #include "spatial.h" -#include "scene/main/viewport.h" #include "message_queue.h" +#include "scene/main/viewport.h" #include "scene/scene_string_names.h" /* @@ -66,10 +66,7 @@ future: no idea */ - - SpatialGizmo::SpatialGizmo() { - } void Spatial::_notify_dirty() { @@ -80,14 +77,12 @@ void Spatial::_notify_dirty() { } } - - void Spatial::_update_local_transform() const { data.local_transform.basis = Basis(); data.local_transform.basis.scale(data.scale); data.local_transform.basis.rotate(data.rotation); - data.dirty&=~DIRTY_LOCAL; + data.dirty &= ~DIRTY_LOCAL; } void Spatial::_propagate_transform_changed(Spatial *p_origin) { @@ -102,48 +97,46 @@ void Spatial::_propagate_transform_changed(Spatial *p_origin) { data.children_lock++; - for (List::Element *E=data.children.front();E;E=E->next()) { + for (List::Element *E = data.children.front(); E; E = E->next()) { if (E->get()->data.toplevel_active) continue; //don't propagate to a toplevel E->get()->_propagate_transform_changed(p_origin); } - if (data.notify_transform && !data.ignore_notification && !xform_change.in_list()) { get_tree()->xform_change_list.add(&xform_change); - } - data.dirty|=DIRTY_GLOBAL; + data.dirty |= DIRTY_GLOBAL; data.children_lock--; } void Spatial::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { Node *p = get_parent(); if (p) - data.parent=p->cast_to(); + data.parent = p->cast_to(); if (data.parent) - data.C=data.parent->data.children.push_back(this); + data.C = data.parent->data.children.push_back(this); else - data.C=NULL; + data.C = NULL; if (data.toplevel && !get_tree()->is_editor_hint()) { if (data.parent) { data.local_transform = data.parent->get_global_transform() * get_transform(); - data.dirty=DIRTY_VECTORS; //global is always dirty upon entering a scene + data.dirty = DIRTY_VECTORS; //global is always dirty upon entering a scene } - data.toplevel_active=true; + data.toplevel_active = true; } - data.dirty|=DIRTY_GLOBAL; //global is always dirty upon entering a scene + data.dirty |= DIRTY_GLOBAL; //global is always dirty upon entering a scene _notify_dirty(); notification(NOTIFICATION_ENTER_WORLD); @@ -151,38 +144,37 @@ void Spatial::_notification(int p_what) { } break; case NOTIFICATION_EXIT_TREE: { - notification(NOTIFICATION_EXIT_WORLD,true); + notification(NOTIFICATION_EXIT_WORLD, true); if (xform_change.in_list()) get_tree()->xform_change_list.remove(&xform_change); if (data.C) data.parent->data.children.erase(data.C); - data.parent=NULL; - data.C=NULL; - data.toplevel_active=false; + data.parent = NULL; + data.C = NULL; + data.toplevel_active = false; } break; case NOTIFICATION_ENTER_WORLD: { - data.inside_world=true; - data.viewport=NULL; + data.inside_world = true; + data.viewport = NULL; Node *parent = get_parent(); - while(parent && !data.viewport) { - data.viewport=parent->cast_to(); - parent=parent->get_parent(); + while (parent && !data.viewport) { + data.viewport = parent->cast_to(); + parent = parent->get_parent(); } ERR_FAIL_COND(!data.viewport); - if (get_script_instance()) { Variant::CallError err; - get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_enter_world,NULL,0); + get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_enter_world, NULL, 0); } #ifdef TOOLS_ENABLED if (get_tree()->is_editor_hint()) { //get_scene()->call_group(SceneMainLoop::GROUP_CALL_REALTIME,SceneStringNames::get_singleton()->_spatial_editor_group,SceneStringNames::get_singleton()->_request_gizmo,this); - get_tree()->call_group_flags(0,SceneStringNames::get_singleton()->_spatial_editor_group,SceneStringNames::get_singleton()->_request_gizmo,this); + get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this); if (!data.gizmo_disabled) { if (data.gizmo.is_valid()) @@ -203,15 +195,14 @@ void Spatial::_notification(int p_what) { if (get_script_instance()) { Variant::CallError err; - get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_exit_world,NULL,0); + get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_exit_world, NULL, 0); } - data.viewport=NULL; - data.inside_world=false; + data.viewport = NULL; + data.inside_world = false; } break; - case NOTIFICATION_TRANSFORM_CHANGED: { #ifdef TOOLS_ENABLED @@ -225,10 +216,10 @@ void Spatial::_notification(int p_what) { } } -void Spatial::set_transform(const Transform& p_transform) { +void Spatial::set_transform(const Transform &p_transform) { - data.local_transform=p_transform; - data.dirty|=DIRTY_VECTORS; + data.local_transform = p_transform; + data.dirty |= DIRTY_VECTORS; _change_notify("transform/translation"); _change_notify("transform/rotation"); _change_notify("transform/scale"); @@ -236,23 +227,18 @@ void Spatial::set_transform(const Transform& p_transform) { if (data.notify_local_transform) { notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED); } - - - } -void Spatial::set_global_transform(const Transform& p_transform) { +void Spatial::set_global_transform(const Transform &p_transform) { Transform xform = (data.parent && !data.toplevel_active) ? - data.parent->get_global_transform().affine_inverse() * p_transform : - p_transform; + data.parent->get_global_transform().affine_inverse() * p_transform : + p_transform; set_transform(xform); - } - Transform Spatial::get_transform() const { if (data.dirty & DIRTY_LOCAL) { @@ -275,13 +261,13 @@ Transform Spatial::get_global_transform() const { if (data.parent && !data.toplevel_active) { - data.global_transform=data.parent->get_global_transform() * data.local_transform; + data.global_transform = data.parent->get_global_transform() * data.local_transform; } else { - data.global_transform=data.local_transform; + data.global_transform = data.local_transform; } - data.dirty&=~DIRTY_GLOBAL; + data.dirty &= ~DIRTY_GLOBAL; } return data.global_transform; @@ -321,88 +307,83 @@ void Spatial::remove_child_notify(Node *p_child) { Spatial *Spatial::get_parent_spatial() const { return data.parent; - } Transform Spatial::get_relative_transform(const Node *p_parent) const { - if (p_parent==this) + if (p_parent == this) return Transform(); - ERR_FAIL_COND_V(!data.parent,Transform()); + ERR_FAIL_COND_V(!data.parent, Transform()); - if (p_parent==data.parent) + if (p_parent == data.parent) return get_transform(); else return data.parent->get_relative_transform(p_parent) * get_transform(); - } -void Spatial::set_translation(const Vector3& p_translation) { +void Spatial::set_translation(const Vector3 &p_translation) { - data.local_transform.origin=p_translation; + data.local_transform.origin = p_translation; _propagate_transform_changed(this); if (data.notify_local_transform) { notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED); } - } -void Spatial::set_rotation(const Vector3& p_euler_rad){ +void Spatial::set_rotation(const Vector3 &p_euler_rad) { - if (data.dirty&DIRTY_VECTORS) { - data.scale=data.local_transform.basis.get_scale(); - data.dirty&=~DIRTY_VECTORS; + if (data.dirty & DIRTY_VECTORS) { + data.scale = data.local_transform.basis.get_scale(); + data.dirty &= ~DIRTY_VECTORS; } - data.rotation=p_euler_rad; - data.dirty|=DIRTY_LOCAL; + data.rotation = p_euler_rad; + data.dirty |= DIRTY_LOCAL; _propagate_transform_changed(this); if (data.notify_local_transform) { notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED); } - } -void Spatial::set_rotation_in_degrees(const Vector3& p_euler_deg) { +void Spatial::set_rotation_in_degrees(const Vector3 &p_euler_deg) { set_rotation(p_euler_deg * Math_PI / 180.0); } -void Spatial::_set_rotation_deg(const Vector3& p_euler_deg) { +void Spatial::_set_rotation_deg(const Vector3 &p_euler_deg) { WARN_PRINT("Deprecated method Spatial._set_rotation_deg(): This method was renamed to set_rotation_deg. Please adapt your code accordingly, as the old method will be obsoleted."); set_rotation_in_degrees(p_euler_deg); } -void Spatial::set_scale(const Vector3& p_scale){ +void Spatial::set_scale(const Vector3 &p_scale) { - if (data.dirty&DIRTY_VECTORS) { - data.rotation=data.local_transform.basis.get_rotation(); - data.dirty&=~DIRTY_VECTORS; + if (data.dirty & DIRTY_VECTORS) { + data.rotation = data.local_transform.basis.get_rotation(); + data.dirty &= ~DIRTY_VECTORS; } - data.scale=p_scale; - data.dirty|=DIRTY_LOCAL; + data.scale = p_scale; + data.dirty |= DIRTY_LOCAL; _propagate_transform_changed(this); if (data.notify_local_transform) { notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED); } - } -Vector3 Spatial::get_translation() const{ +Vector3 Spatial::get_translation() const { return data.local_transform.origin; } -Vector3 Spatial::get_rotation() const{ +Vector3 Spatial::get_rotation() const { - if (data.dirty&DIRTY_VECTORS) { - data.scale=data.local_transform.basis.get_scale(); - data.rotation=data.local_transform.basis.get_rotation(); + if (data.dirty & DIRTY_VECTORS) { + data.scale = data.local_transform.basis.get_scale(); + data.rotation = data.local_transform.basis.get_rotation(); - data.dirty&=~DIRTY_VECTORS; + data.dirty &= ~DIRTY_VECTORS; } return data.rotation; @@ -421,19 +402,18 @@ Vector3 Spatial::_get_rotation_deg() const { return get_rotation_in_degrees(); } -Vector3 Spatial::get_scale() const{ +Vector3 Spatial::get_scale() const { - if (data.dirty&DIRTY_VECTORS) { - data.scale=data.local_transform.basis.get_scale(); - data.rotation=data.local_transform.basis.get_rotation(); + if (data.dirty & DIRTY_VECTORS) { + data.scale = data.local_transform.basis.get_scale(); + data.rotation = data.local_transform.basis.get_rotation(); - data.dirty&=~DIRTY_VECTORS; + data.dirty &= ~DIRTY_VECTORS; } return data.scale; } - void Spatial::update_gizmo() { #ifdef TOOLS_ENABLED @@ -443,12 +423,12 @@ void Spatial::update_gizmo() { return; if (data.gizmo_dirty) return; - data.gizmo_dirty=true; - MessageQueue::get_singleton()->push_call(this,"_update_gizmo"); + data.gizmo_dirty = true; + MessageQueue::get_singleton()->push_call(this, "_update_gizmo"); #endif } -void Spatial::set_gizmo(const Ref& p_gizmo) { +void Spatial::set_gizmo(const Ref &p_gizmo) { #ifdef TOOLS_ENABLED @@ -456,7 +436,7 @@ void Spatial::set_gizmo(const Ref& p_gizmo) { return; if (data.gizmo.is_valid() && is_inside_world()) data.gizmo->free(); - data.gizmo=p_gizmo; + data.gizmo = p_gizmo; if (data.gizmo.is_valid() && is_inside_world()) { data.gizmo->create(); @@ -482,7 +462,7 @@ Ref Spatial::get_gizmo() const { void Spatial::_update_gizmo() { - data.gizmo_dirty=false; + data.gizmo_dirty = false; if (data.gizmo.is_valid()) { if (is_visible_in_tree()) data.gizmo->redraw(); @@ -491,19 +471,18 @@ void Spatial::_update_gizmo() { } } - void Spatial::set_disable_gizmo(bool p_enabled) { - data.gizmo_disabled=p_enabled; + data.gizmo_disabled = p_enabled; if (!p_enabled && data.gizmo.is_valid()) - data.gizmo=Ref(); + data.gizmo = Ref(); } #endif void Spatial::set_as_toplevel(bool p_enabled) { - if (data.toplevel==p_enabled) + if (data.toplevel == p_enabled) return; if (is_inside_tree() && !get_tree()->is_editor_hint()) { @@ -512,30 +491,28 @@ void Spatial::set_as_toplevel(bool p_enabled) { else if (data.parent) set_transform(data.parent->get_global_transform().affine_inverse() * get_global_transform()); - data.toplevel=p_enabled; - data.toplevel_active=p_enabled; + data.toplevel = p_enabled; + data.toplevel_active = p_enabled; } else { - data.toplevel=p_enabled; + data.toplevel = p_enabled; } - } -bool Spatial::is_set_as_toplevel() const{ +bool Spatial::is_set_as_toplevel() const { return data.toplevel; } Ref Spatial::get_world() const { - ERR_FAIL_COND_V(!is_inside_world(),Ref()); + ERR_FAIL_COND_V(!is_inside_world(), Ref()); return data.viewport->find_world(); - } #ifdef TOOLS_ENABLED -void Spatial::set_import_transform(const Transform& p_transform) { - data.import_transform=p_transform; +void Spatial::set_import_transform(const Transform &p_transform) { + data.import_transform = p_transform; } Transform Spatial::get_import_transform() const { @@ -544,7 +521,6 @@ Transform Spatial::get_import_transform() const { } #endif - void Spatial::_propagate_visibility_changed() { notification(NOTIFICATION_VISIBILITY_CHANGED); @@ -555,22 +531,21 @@ void Spatial::_propagate_visibility_changed() { _update_gizmo(); #endif - for (List::Element*E=data.children.front();E;E=E->next()) { + for (List::Element *E = data.children.front(); E; E = E->next()) { - Spatial *c=E->get(); + Spatial *c = E->get(); if (!c || !c->data.visible) continue; c->_propagate_visibility_changed(); } } - void Spatial::show() { if (data.visible) return; - data.visible=true; + data.visible = true; if (!is_inside_tree()) return; @@ -581,35 +556,33 @@ void Spatial::show() { } } -void Spatial::hide(){ +void Spatial::hide() { if (!data.visible) return; bool was_visible = is_visible_in_tree(); - data.visible=false; + data.visible = false; if (!data.parent || was_visible) { _propagate_visibility_changed(); } - } -bool Spatial::is_visible_in_tree() const{ +bool Spatial::is_visible_in_tree() const { - const Spatial *s=this; + const Spatial *s = this; - while(s) { + while (s) { if (!s->data.visible) { return false; } - s=s->data.parent; + s = s->data.parent; } return true; } - void Spatial::set_visible(bool p_visible) { if (p_visible) @@ -623,64 +596,57 @@ bool Spatial::is_visible() const { return data.visible; } -void Spatial::rotate(const Vector3& p_normal,float p_radians) { +void Spatial::rotate(const Vector3 &p_normal, float p_radians) { - Transform t =get_transform(); - t.basis.rotate(p_normal,p_radians); + Transform t = get_transform(); + t.basis.rotate(p_normal, p_radians); set_transform(t); } void Spatial::rotate_x(float p_radians) { - Transform t =get_transform(); - t.basis.rotate(Vector3(1,0,0),p_radians); + Transform t = get_transform(); + t.basis.rotate(Vector3(1, 0, 0), p_radians); set_transform(t); - } -void Spatial::rotate_y(float p_radians){ +void Spatial::rotate_y(float p_radians) { - Transform t =get_transform(); - t.basis.rotate(Vector3(0,1,0),p_radians); + Transform t = get_transform(); + t.basis.rotate(Vector3(0, 1, 0), p_radians); set_transform(t); - } -void Spatial::rotate_z(float p_radians){ +void Spatial::rotate_z(float p_radians) { - Transform t =get_transform(); - t.basis.rotate(Vector3(0,0,1),p_radians); + Transform t = get_transform(); + t.basis.rotate(Vector3(0, 0, 1), p_radians); set_transform(t); - } -void Spatial::translate(const Vector3& p_offset){ +void Spatial::translate(const Vector3 &p_offset) { - Transform t =get_transform(); + Transform t = get_transform(); t.translate(p_offset); set_transform(t); - } -void Spatial::scale(const Vector3& p_ratio){ +void Spatial::scale(const Vector3 &p_ratio) { - Transform t =get_transform(); + Transform t = get_transform(); t.basis.scale(p_ratio); set_transform(t); - } -void Spatial::global_rotate(const Vector3& p_normal,float p_radians){ +void Spatial::global_rotate(const Vector3 &p_normal, float p_radians) { - Basis rotation(p_normal,p_radians); + Basis rotation(p_normal, p_radians); Transform t = get_global_transform(); - t.basis= rotation * t.basis; + t.basis = rotation * t.basis; set_global_transform(t); - } -void Spatial::global_translate(const Vector3& p_offset){ +void Spatial::global_translate(const Vector3 &p_offset) { Transform t = get_global_transform(); - t.origin+=p_offset; + t.origin += p_offset; set_global_transform(t); - } void Spatial::orthonormalize() { @@ -688,44 +654,40 @@ void Spatial::orthonormalize() { Transform t = get_transform(); t.orthonormalize(); set_transform(t); - } void Spatial::set_identity() { set_transform(Transform()); - } - -void Spatial::look_at(const Vector3& p_target, const Vector3& p_up_normal) { +void Spatial::look_at(const Vector3 &p_target, const Vector3 &p_up_normal) { Transform lookat; - lookat.origin=get_global_transform().origin; - if (lookat.origin==p_target) { + lookat.origin = get_global_transform().origin; + if (lookat.origin == p_target) { ERR_EXPLAIN("Node origin and target are in the same position, look_at() failed"); ERR_FAIL(); } - if (p_up_normal.cross(p_target-lookat.origin)==Vector3()) { + if (p_up_normal.cross(p_target - lookat.origin) == Vector3()) { ERR_EXPLAIN("Up vector and direction between node origin and target are aligned, look_at() failed"); ERR_FAIL(); } - lookat=lookat.looking_at(p_target,p_up_normal); + lookat = lookat.looking_at(p_target, p_up_normal); set_global_transform(lookat); } -void Spatial::look_at_from_pos(const Vector3& p_pos,const Vector3& p_target, const Vector3& p_up_normal) { +void Spatial::look_at_from_pos(const Vector3 &p_pos, const Vector3 &p_target, const Vector3 &p_up_normal) { Transform lookat; - lookat.origin=p_pos; - lookat=lookat.looking_at(p_target,p_up_normal); + lookat.origin = p_pos; + lookat = lookat.looking_at(p_target, p_up_normal); set_global_transform(lookat); - } void Spatial::set_notify_transform(bool p_enable) { - data.notify_transform=p_enable; + data.notify_transform = p_enable; } bool Spatial::is_transform_notification_enabled() const { @@ -733,7 +695,7 @@ bool Spatial::is_transform_notification_enabled() const { } void Spatial::set_notify_local_transform(bool p_enable) { - data.notify_local_transform=p_enable; + data.notify_local_transform = p_enable; } bool Spatial::is_local_transform_notification_enabled() const { @@ -742,37 +704,37 @@ bool Spatial::is_local_transform_notification_enabled() const { void Spatial::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_transform","local"), &Spatial::set_transform); + ClassDB::bind_method(D_METHOD("set_transform", "local"), &Spatial::set_transform); ClassDB::bind_method(D_METHOD("get_transform"), &Spatial::get_transform); - ClassDB::bind_method(D_METHOD("set_translation","translation"), &Spatial::set_translation); + ClassDB::bind_method(D_METHOD("set_translation", "translation"), &Spatial::set_translation); ClassDB::bind_method(D_METHOD("get_translation"), &Spatial::get_translation); - ClassDB::bind_method(D_METHOD("set_rotation","rotation_rad"), &Spatial::set_rotation); + ClassDB::bind_method(D_METHOD("set_rotation", "rotation_rad"), &Spatial::set_rotation); ClassDB::bind_method(D_METHOD("get_rotation"), &Spatial::get_rotation); - ClassDB::bind_method(D_METHOD("set_rotation_deg","rotation_deg"), &Spatial::set_rotation_in_degrees); + ClassDB::bind_method(D_METHOD("set_rotation_deg", "rotation_deg"), &Spatial::set_rotation_in_degrees); ClassDB::bind_method(D_METHOD("get_rotation_deg"), &Spatial::get_rotation_in_degrees); - ClassDB::bind_method(D_METHOD("set_scale","scale"), &Spatial::set_scale); + ClassDB::bind_method(D_METHOD("set_scale", "scale"), &Spatial::set_scale); ClassDB::bind_method(D_METHOD("get_scale"), &Spatial::get_scale); - ClassDB::bind_method(D_METHOD("set_global_transform","global"), &Spatial::set_global_transform); + ClassDB::bind_method(D_METHOD("set_global_transform", "global"), &Spatial::set_global_transform); ClassDB::bind_method(D_METHOD("get_global_transform"), &Spatial::get_global_transform); ClassDB::bind_method(D_METHOD("get_parent_spatial"), &Spatial::get_parent_spatial); - ClassDB::bind_method(D_METHOD("set_ignore_transform_notification","enabled"), &Spatial::set_ignore_transform_notification); - ClassDB::bind_method(D_METHOD("set_as_toplevel","enable"), &Spatial::set_as_toplevel); + ClassDB::bind_method(D_METHOD("set_ignore_transform_notification", "enabled"), &Spatial::set_ignore_transform_notification); + ClassDB::bind_method(D_METHOD("set_as_toplevel", "enable"), &Spatial::set_as_toplevel); ClassDB::bind_method(D_METHOD("is_set_as_toplevel"), &Spatial::is_set_as_toplevel); ClassDB::bind_method(D_METHOD("get_world:World"), &Spatial::get_world); // TODO: Obsolete those two methods (old name) properly (GH-4397) - ClassDB::bind_method(D_METHOD("_set_rotation_deg","rotation_deg"), &Spatial::_set_rotation_deg); + ClassDB::bind_method(D_METHOD("_set_rotation_deg", "rotation_deg"), &Spatial::_set_rotation_deg); ClassDB::bind_method(D_METHOD("_get_rotation_deg"), &Spatial::_get_rotation_deg); #ifdef TOOLS_ENABLED ClassDB::bind_method(D_METHOD("_update_gizmo"), &Spatial::_update_gizmo); ClassDB::bind_method(D_METHOD("_set_import_transform"), &Spatial::set_import_transform); ClassDB::bind_method(D_METHOD("_get_import_transform"), &Spatial::get_import_transform); - ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM,"_import_transform",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_import_transform","_get_import_transform"); + ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "_import_transform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_import_transform", "_get_import_transform"); #endif ClassDB::bind_method(D_METHOD("update_gizmo"), &Spatial::update_gizmo); - ClassDB::bind_method(D_METHOD("set_gizmo","gizmo:SpatialGizmo"), &Spatial::set_gizmo); + ClassDB::bind_method(D_METHOD("set_gizmo", "gizmo:SpatialGizmo"), &Spatial::set_gizmo); ClassDB::bind_method(D_METHOD("get_gizmo:SpatialGizmo"), &Spatial::get_gizmo); ClassDB::bind_method(D_METHOD("set_visible"), &Spatial::set_visible); @@ -781,84 +743,77 @@ void Spatial::_bind_methods() { ClassDB::bind_method(D_METHOD("show"), &Spatial::show); ClassDB::bind_method(D_METHOD("hide"), &Spatial::hide); - ClassDB::bind_method(D_METHOD("set_notify_local_transform","enable"), &Spatial::set_notify_local_transform); + ClassDB::bind_method(D_METHOD("set_notify_local_transform", "enable"), &Spatial::set_notify_local_transform); ClassDB::bind_method(D_METHOD("is_local_transform_notification_enabled"), &Spatial::is_local_transform_notification_enabled); - ClassDB::bind_method(D_METHOD("set_notify_transform","enable"), &Spatial::set_notify_transform); + ClassDB::bind_method(D_METHOD("set_notify_transform", "enable"), &Spatial::set_notify_transform); ClassDB::bind_method(D_METHOD("is_transform_notification_enabled"), &Spatial::is_transform_notification_enabled); - void rotate(const Vector3& p_normal,float p_radians); + void rotate(const Vector3 &p_normal, float p_radians); void rotate_x(float p_radians); void rotate_y(float p_radians); void rotate_z(float p_radians); - void translate(const Vector3& p_offset); - void scale(const Vector3& p_ratio); - void global_rotate(const Vector3& p_normal,float p_radians); - void global_translate(const Vector3& p_offset); - - ClassDB::bind_method( D_METHOD("rotate","normal","radians"),&Spatial::rotate ); - ClassDB::bind_method( D_METHOD("global_rotate","normal","radians"),&Spatial::global_rotate ); - ClassDB::bind_method( D_METHOD("rotate_x","radians"),&Spatial::rotate_x ); - ClassDB::bind_method( D_METHOD("rotate_y","radians"),&Spatial::rotate_y ); - ClassDB::bind_method( D_METHOD("rotate_z","radians"),&Spatial::rotate_z ); - ClassDB::bind_method( D_METHOD("translate","offset"),&Spatial::translate ); - ClassDB::bind_method( D_METHOD("global_translate","offset"),&Spatial::global_translate ); - ClassDB::bind_method( D_METHOD("orthonormalize"),&Spatial::orthonormalize ); - ClassDB::bind_method( D_METHOD("set_identity"),&Spatial::set_identity ); - - ClassDB::bind_method( D_METHOD("look_at","target","up"),&Spatial::look_at ); - ClassDB::bind_method( D_METHOD("look_at_from_pos","pos","target","up"),&Spatial::look_at_from_pos ); - - BIND_CONSTANT( NOTIFICATION_TRANSFORM_CHANGED ); - BIND_CONSTANT( NOTIFICATION_ENTER_WORLD ); - BIND_CONSTANT( NOTIFICATION_EXIT_WORLD ); - BIND_CONSTANT( NOTIFICATION_VISIBILITY_CHANGED ); + void translate(const Vector3 &p_offset); + void scale(const Vector3 &p_ratio); + void global_rotate(const Vector3 &p_normal, float p_radians); + void global_translate(const Vector3 &p_offset); + + ClassDB::bind_method(D_METHOD("rotate", "normal", "radians"), &Spatial::rotate); + ClassDB::bind_method(D_METHOD("global_rotate", "normal", "radians"), &Spatial::global_rotate); + ClassDB::bind_method(D_METHOD("rotate_x", "radians"), &Spatial::rotate_x); + ClassDB::bind_method(D_METHOD("rotate_y", "radians"), &Spatial::rotate_y); + ClassDB::bind_method(D_METHOD("rotate_z", "radians"), &Spatial::rotate_z); + ClassDB::bind_method(D_METHOD("translate", "offset"), &Spatial::translate); + ClassDB::bind_method(D_METHOD("global_translate", "offset"), &Spatial::global_translate); + ClassDB::bind_method(D_METHOD("orthonormalize"), &Spatial::orthonormalize); + ClassDB::bind_method(D_METHOD("set_identity"), &Spatial::set_identity); + + ClassDB::bind_method(D_METHOD("look_at", "target", "up"), &Spatial::look_at); + ClassDB::bind_method(D_METHOD("look_at_from_pos", "pos", "target", "up"), &Spatial::look_at_from_pos); + + BIND_CONSTANT(NOTIFICATION_TRANSFORM_CHANGED); + BIND_CONSTANT(NOTIFICATION_ENTER_WORLD); + BIND_CONSTANT(NOTIFICATION_EXIT_WORLD); + BIND_CONSTANT(NOTIFICATION_VISIBILITY_CHANGED); //ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM,"transform/global",PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR ), "set_global_transform", "get_global_transform") ; - ADD_GROUP("Transform",""); - ADD_PROPERTYNZ( PropertyInfo(Variant::TRANSFORM,"transform",PROPERTY_HINT_NONE,""), "set_transform", "get_transform") ; - ADD_PROPERTYNZ( PropertyInfo(Variant::TRANSFORM,"global_transform",PROPERTY_HINT_NONE,"",0), "set_global_transform", "get_global_transform") ; - ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"translation",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR), "set_translation", "get_translation") ; - ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"rotation_deg",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR), "set_rotation_deg", "get_rotation_deg") ; - ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"rotation",PROPERTY_HINT_NONE,"",0), "set_rotation", "get_rotation") ; - ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"scale",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR), "set_scale", "get_scale") ; - ADD_GROUP("Visibility",""); - ADD_PROPERTYNO( PropertyInfo(Variant::BOOL,"visible"), "set_visible", "is_visible") ; + ADD_GROUP("Transform", ""); + ADD_PROPERTYNZ(PropertyInfo(Variant::TRANSFORM, "transform", PROPERTY_HINT_NONE, ""), "set_transform", "get_transform"); + ADD_PROPERTYNZ(PropertyInfo(Variant::TRANSFORM, "global_transform", PROPERTY_HINT_NONE, "", 0), "set_global_transform", "get_global_transform"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "translation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_translation", "get_translation"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation_deg", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_rotation_deg", "get_rotation_deg"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation", PROPERTY_HINT_NONE, "", 0), "set_rotation", "get_rotation"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_scale", "get_scale"); + ADD_GROUP("Visibility", ""); + ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "visible"), "set_visible", "is_visible"); //ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM,"transform/local"), "set_transform", "get_transform") ; - ADD_SIGNAL( MethodInfo("visibility_changed" ) ); - + ADD_SIGNAL(MethodInfo("visibility_changed")); } +Spatial::Spatial() + : xform_change(this) { -Spatial::Spatial() : xform_change(this) -{ + data.dirty = DIRTY_NONE; + data.children_lock = 0; - data.dirty=DIRTY_NONE; - data.children_lock=0; - - data.ignore_notification=false; - data.toplevel=false; - data.toplevel_active=false; - data.scale=Vector3(1,1,1); - data.viewport=NULL; - data.inside_world=false; - data.visible=true; + data.ignore_notification = false; + data.toplevel = false; + data.toplevel_active = false; + data.scale = Vector3(1, 1, 1); + data.viewport = NULL; + data.inside_world = false; + data.visible = true; #ifdef TOOLS_ENABLED - data.gizmo_disabled=false; - data.gizmo_dirty=false; + data.gizmo_disabled = false; + data.gizmo_dirty = false; #endif - data.notify_local_transform=false; - data.notify_transform=false; - data.parent=NULL; - data.C=NULL; - + data.notify_local_transform = false; + data.notify_transform = false; + data.parent = NULL; + data.C = NULL; } - Spatial::~Spatial() { - } - - diff --git a/scene/3d/spatial.h b/scene/3d/spatial.h index 72daa472b..e5817883d 100644 --- a/scene/3d/spatial.h +++ b/scene/3d/spatial.h @@ -38,39 +38,34 @@ class SpatialGizmo : public Reference { - GDCLASS(SpatialGizmo,Reference); - + GDCLASS(SpatialGizmo, Reference); public: - - virtual void create()=0; - virtual void transform()=0; - virtual void clear()=0; - virtual void redraw()=0; - virtual void free()=0; + virtual void create() = 0; + virtual void transform() = 0; + virtual void clear() = 0; + virtual void redraw() = 0; + virtual void free() = 0; SpatialGizmo(); }; - class Spatial : public Node { - GDCLASS( Spatial, Node ); + GDCLASS(Spatial, Node); OBJ_CATEGORY("3D"); enum TransformDirty { - DIRTY_NONE=0, - DIRTY_VECTORS=1, - DIRTY_LOCAL=2, - DIRTY_GLOBAL=4 + DIRTY_NONE = 0, + DIRTY_VECTORS = 1, + DIRTY_LOCAL = 2, + DIRTY_GLOBAL = 4 }; mutable SelfList xform_change; struct Data { - - mutable Transform global_transform; mutable Transform local_transform; mutable Vector3 rotation; @@ -80,15 +75,14 @@ class Spatial : public Node { Viewport *viewport; - bool toplevel_active; bool toplevel; bool inside_world; int children_lock; Spatial *parent; - List children; - List::Element *C; + List children; + List::Element *C; bool ignore_notification; bool notify_local_transform; @@ -112,15 +106,13 @@ class Spatial : public Node { void _propagate_transform_changed(Spatial *p_origin); // Deprecated, should be removed in a future version. - void _set_rotation_deg(const Vector3& p_euler_deg); + void _set_rotation_deg(const Vector3 &p_euler_deg); Vector3 _get_rotation_deg() const; void _propagate_visibility_changed(); - protected: - - _FORCE_INLINE_ void set_ignore_transform_notification(bool p_ignore) { data.ignore_notification=p_ignore; } + _FORCE_INLINE_ void set_ignore_transform_notification(bool p_ignore) { data.ignore_notification = p_ignore; } _FORCE_INLINE_ void _update_local_transform() const; @@ -128,33 +120,31 @@ protected: static void _bind_methods(); public: - enum { - NOTIFICATION_TRANSFORM_CHANGED=SceneTree::NOTIFICATION_TRANSFORM_CHANGED, - NOTIFICATION_ENTER_WORLD=41, - NOTIFICATION_EXIT_WORLD=42, - NOTIFICATION_VISIBILITY_CHANGED=43, - NOTIFICATION_LOCAL_TRANSFORM_CHANGED=44, + NOTIFICATION_TRANSFORM_CHANGED = SceneTree::NOTIFICATION_TRANSFORM_CHANGED, + NOTIFICATION_ENTER_WORLD = 41, + NOTIFICATION_EXIT_WORLD = 42, + NOTIFICATION_VISIBILITY_CHANGED = 43, + NOTIFICATION_LOCAL_TRANSFORM_CHANGED = 44, }; Spatial *get_parent_spatial() const; - Ref get_world() const; - void set_translation(const Vector3& p_translation); - void set_rotation(const Vector3& p_euler_rad); - void set_rotation_in_degrees(const Vector3& p_euler_deg); - void set_scale(const Vector3& p_scale); + void set_translation(const Vector3 &p_translation); + void set_rotation(const Vector3 &p_euler_rad); + void set_rotation_in_degrees(const Vector3 &p_euler_deg); + void set_scale(const Vector3 &p_scale); Vector3 get_translation() const; Vector3 get_rotation() const; Vector3 get_rotation_in_degrees() const; Vector3 get_scale() const; - void set_transform(const Transform& p_transform); - void set_global_transform(const Transform& p_transform); + void set_transform(const Transform &p_transform); + void set_global_transform(const Transform &p_transform); Transform get_transform() const; Transform get_global_transform() const; @@ -164,24 +154,24 @@ public: void set_disable_gizmo(bool p_enabled); void update_gizmo(); - void set_gizmo(const Ref& p_gizmo); + void set_gizmo(const Ref &p_gizmo); Ref get_gizmo() const; _FORCE_INLINE_ bool is_inside_world() const { return data.inside_world; } Transform get_relative_transform(const Node *p_parent) const; - void rotate(const Vector3& p_normal,float p_radians); + void rotate(const Vector3 &p_normal, float p_radians); void rotate_x(float p_radians); void rotate_y(float p_radians); void rotate_z(float p_radians); - void translate(const Vector3& p_offset); - void scale(const Vector3& p_ratio); - void global_rotate(const Vector3& p_normal,float p_radians); - void global_translate(const Vector3& p_offset); + void translate(const Vector3 &p_offset); + void scale(const Vector3 &p_ratio); + void global_rotate(const Vector3 &p_normal, float p_radians); + void global_translate(const Vector3 &p_offset); - void look_at(const Vector3& p_target, const Vector3& p_up_normal); - void look_at_from_pos(const Vector3& p_pos,const Vector3& p_target, const Vector3& p_up_normal); + void look_at(const Vector3 &p_target, const Vector3 &p_up_normal); + void look_at_from_pos(const Vector3 &p_pos, const Vector3 &p_target, const Vector3 &p_up_normal); void set_notify_transform(bool p_enable); bool is_transform_notification_enabled() const; @@ -199,13 +189,12 @@ public: bool is_visible_in_tree() const; #ifdef TOOLS_ENABLED - void set_import_transform(const Transform& p_transform) ; + void set_import_transform(const Transform &p_transform); Transform get_import_transform() const; #endif Spatial(); ~Spatial(); - }; #endif diff --git a/scene/3d/spatial_indexer.cpp b/scene/3d/spatial_indexer.cpp index 6d6c272c2..cddbf9a4e 100644 --- a/scene/3d/spatial_indexer.cpp +++ b/scene/3d/spatial_indexer.cpp @@ -30,8 +30,8 @@ #if 0 -#include "proximity_area.h" #include "camera.h" +#include "proximity_area.h" #include "scene/scene_string_names.h" void SpatialIndexer::add_camera(Camera* p_camera) { diff --git a/scene/3d/sprite_3d.cpp b/scene/3d/sprite_3d.cpp index 5adb7050f..062e3943b 100644 --- a/scene/3d/sprite_3d.cpp +++ b/scene/3d/sprite_3d.cpp @@ -27,9 +27,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "sprite_3d.h" -#include "scene/scene_string_names.h" #include "core_string_names.h" - +#include "scene/scene_string_names.h" Color SpriteBase3D::_get_color_accum() { @@ -37,15 +36,15 @@ Color SpriteBase3D::_get_color_accum() { return color_accum; if (parent_sprite) - color_accum=parent_sprite->_get_color_accum(); + color_accum = parent_sprite->_get_color_accum(); else - color_accum=Color(1,1,1,1); + color_accum = Color(1, 1, 1, 1); - color_accum.r*=modulate.r; - color_accum.g*=modulate.g; - color_accum.b*=modulate.b; - color_accum.a*=modulate.a; - color_dirty=false; + color_accum.r *= modulate.r; + color_accum.g *= modulate.g; + color_accum.b *= modulate.b; + color_accum.a *= modulate.a; + color_dirty = false; return color_accum; } @@ -54,10 +53,10 @@ void SpriteBase3D::_propagate_color_changed() { if (color_dirty) return; - color_dirty=true; + color_dirty = true; _queue_update(); - for (List::Element *E=children.front();E;E=E->next()) { + for (List::Element *E = children.front(); E; E = E->next()) { E->get()->_propagate_color_changed(); } @@ -65,40 +64,36 @@ void SpriteBase3D::_propagate_color_changed() { void SpriteBase3D::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_TREE) { + if (p_what == NOTIFICATION_ENTER_TREE) { if (!pending_update) _im_update(); - Node *parent=get_parent(); + Node *parent = get_parent(); if (parent) { - parent_sprite=parent->cast_to(); + parent_sprite = parent->cast_to(); if (parent_sprite) { - pI=parent_sprite->children.push_back(this); + pI = parent_sprite->children.push_back(this); } } } - if (p_what==NOTIFICATION_EXIT_TREE) { - + if (p_what == NOTIFICATION_EXIT_TREE) { if (parent_sprite) { parent_sprite->children.erase(pI); - pI=NULL; - parent_sprite=NULL; + pI = NULL; + parent_sprite = NULL; } } - } - void SpriteBase3D::set_centered(bool p_center) { - centered=p_center; + centered = p_center; _queue_update(); - } bool SpriteBase3D::is_centered() const { @@ -106,11 +101,10 @@ bool SpriteBase3D::is_centered() const { return centered; } -void SpriteBase3D::set_offset(const Point2& p_offset) { +void SpriteBase3D::set_offset(const Point2 &p_offset) { - offset=p_offset; + offset = p_offset; _queue_update(); - } Point2 SpriteBase3D::get_offset() const { @@ -119,7 +113,7 @@ Point2 SpriteBase3D::get_offset() const { void SpriteBase3D::set_flip_h(bool p_flip) { - hflip=p_flip; + hflip = p_flip; _queue_update(); } bool SpriteBase3D::is_flipped_h() const { @@ -129,7 +123,7 @@ bool SpriteBase3D::is_flipped_h() const { void SpriteBase3D::set_flip_v(bool p_flip) { - vflip=p_flip; + vflip = p_flip; _queue_update(); } bool SpriteBase3D::is_flipped_v() const { @@ -137,24 +131,21 @@ bool SpriteBase3D::is_flipped_v() const { return vflip; } +void SpriteBase3D::set_modulate(const Color &p_color) { - -void SpriteBase3D::set_modulate(const Color& p_color) { - - modulate=p_color; + modulate = p_color; _propagate_color_changed(); _queue_update(); } -Color SpriteBase3D::get_modulate() const{ +Color SpriteBase3D::get_modulate() const { return modulate; } - void SpriteBase3D::set_pixel_size(float p_amount) { - pixel_size=p_amount; + pixel_size = p_amount; _queue_update(); } float SpriteBase3D::get_pixel_size() const { @@ -164,7 +155,7 @@ float SpriteBase3D::get_pixel_size() const { void SpriteBase3D::set_opacity(float p_amount) { - opacity=p_amount; + opacity = p_amount; _queue_update(); } float SpriteBase3D::get_opacity() const { @@ -172,10 +163,9 @@ float SpriteBase3D::get_opacity() const { return opacity; } - void SpriteBase3D::set_axis(Vector3::Axis p_axis) { - axis=p_axis; + axis = p_axis; _queue_update(); } Vector3::Axis SpriteBase3D::get_axis() const { @@ -183,30 +173,24 @@ Vector3::Axis SpriteBase3D::get_axis() const { return axis; } - - void SpriteBase3D::_im_update() { - _draw(); - - pending_update=false; + pending_update = false; //texture->draw_rect_region(ci,dst_rect,src_rect,modulate); - } -void SpriteBase3D::_queue_update(){ +void SpriteBase3D::_queue_update() { - if (pending_update) + if (pending_update) return; - pending_update=true; + pending_update = true; call_deferred(SceneStringNames::get_singleton()->_im_update); } - Rect3 SpriteBase3D::get_aabb() const { return aabb; @@ -214,135 +198,119 @@ Rect3 SpriteBase3D::get_aabb() const { PoolVector SpriteBase3D::get_faces(uint32_t p_usage_flags) const { return PoolVector(); - } -void SpriteBase3D::set_draw_flag(DrawFlags p_flag,bool p_enable) { +void SpriteBase3D::set_draw_flag(DrawFlags p_flag, bool p_enable) { - ERR_FAIL_INDEX(p_flag,FLAG_MAX); - flags[p_flag]=p_enable; + ERR_FAIL_INDEX(p_flag, FLAG_MAX); + flags[p_flag] = p_enable; _queue_update(); } -bool SpriteBase3D::get_draw_flag(DrawFlags p_flag) const{ - ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false); +bool SpriteBase3D::get_draw_flag(DrawFlags p_flag) const { + ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false); return flags[p_flag]; } -void SpriteBase3D::set_alpha_cut_mode(AlphaCutMode p_mode){ +void SpriteBase3D::set_alpha_cut_mode(AlphaCutMode p_mode) { - ERR_FAIL_INDEX(p_mode,3); - alpha_cut=p_mode; + ERR_FAIL_INDEX(p_mode, 3); + alpha_cut = p_mode; _queue_update(); - } -SpriteBase3D::AlphaCutMode SpriteBase3D::get_alpha_cut_mode() const{ +SpriteBase3D::AlphaCutMode SpriteBase3D::get_alpha_cut_mode() const { return alpha_cut; } - void SpriteBase3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_centered", "centered"), &SpriteBase3D::set_centered); + ClassDB::bind_method(D_METHOD("is_centered"), &SpriteBase3D::is_centered); - ClassDB::bind_method(D_METHOD("set_centered","centered"),&SpriteBase3D::set_centered); - ClassDB::bind_method(D_METHOD("is_centered"),&SpriteBase3D::is_centered); - - ClassDB::bind_method(D_METHOD("set_offset","offset"),&SpriteBase3D::set_offset); - ClassDB::bind_method(D_METHOD("get_offset"),&SpriteBase3D::get_offset); - - ClassDB::bind_method(D_METHOD("set_flip_h","flip_h"),&SpriteBase3D::set_flip_h); - ClassDB::bind_method(D_METHOD("is_flipped_h"),&SpriteBase3D::is_flipped_h); - - ClassDB::bind_method(D_METHOD("set_flip_v","flip_v"),&SpriteBase3D::set_flip_v); - ClassDB::bind_method(D_METHOD("is_flipped_v"),&SpriteBase3D::is_flipped_v); + ClassDB::bind_method(D_METHOD("set_offset", "offset"), &SpriteBase3D::set_offset); + ClassDB::bind_method(D_METHOD("get_offset"), &SpriteBase3D::get_offset); + ClassDB::bind_method(D_METHOD("set_flip_h", "flip_h"), &SpriteBase3D::set_flip_h); + ClassDB::bind_method(D_METHOD("is_flipped_h"), &SpriteBase3D::is_flipped_h); - ClassDB::bind_method(D_METHOD("set_modulate","modulate"),&SpriteBase3D::set_modulate); - ClassDB::bind_method(D_METHOD("get_modulate"),&SpriteBase3D::get_modulate); + ClassDB::bind_method(D_METHOD("set_flip_v", "flip_v"), &SpriteBase3D::set_flip_v); + ClassDB::bind_method(D_METHOD("is_flipped_v"), &SpriteBase3D::is_flipped_v); - ClassDB::bind_method(D_METHOD("set_opacity","opacity"),&SpriteBase3D::set_opacity); - ClassDB::bind_method(D_METHOD("get_opacity"),&SpriteBase3D::get_opacity); + ClassDB::bind_method(D_METHOD("set_modulate", "modulate"), &SpriteBase3D::set_modulate); + ClassDB::bind_method(D_METHOD("get_modulate"), &SpriteBase3D::get_modulate); - ClassDB::bind_method(D_METHOD("set_pixel_size","pixel_size"),&SpriteBase3D::set_pixel_size); - ClassDB::bind_method(D_METHOD("get_pixel_size"),&SpriteBase3D::get_pixel_size); + ClassDB::bind_method(D_METHOD("set_opacity", "opacity"), &SpriteBase3D::set_opacity); + ClassDB::bind_method(D_METHOD("get_opacity"), &SpriteBase3D::get_opacity); - ClassDB::bind_method(D_METHOD("set_axis","axis"),&SpriteBase3D::set_axis); - ClassDB::bind_method(D_METHOD("get_axis"),&SpriteBase3D::get_axis); + ClassDB::bind_method(D_METHOD("set_pixel_size", "pixel_size"), &SpriteBase3D::set_pixel_size); + ClassDB::bind_method(D_METHOD("get_pixel_size"), &SpriteBase3D::get_pixel_size); - ClassDB::bind_method(D_METHOD("set_draw_flag","flag","enabled"),&SpriteBase3D::set_draw_flag); - ClassDB::bind_method(D_METHOD("get_draw_flag","flag"),&SpriteBase3D::get_draw_flag); + ClassDB::bind_method(D_METHOD("set_axis", "axis"), &SpriteBase3D::set_axis); + ClassDB::bind_method(D_METHOD("get_axis"), &SpriteBase3D::get_axis); - ClassDB::bind_method(D_METHOD("set_alpha_cut_mode","mode"),&SpriteBase3D::set_alpha_cut_mode); - ClassDB::bind_method(D_METHOD("get_alpha_cut_mode"),&SpriteBase3D::get_alpha_cut_mode); + ClassDB::bind_method(D_METHOD("set_draw_flag", "flag", "enabled"), &SpriteBase3D::set_draw_flag); + ClassDB::bind_method(D_METHOD("get_draw_flag", "flag"), &SpriteBase3D::get_draw_flag); - ClassDB::bind_method(D_METHOD("get_item_rect"),&SpriteBase3D::get_item_rect); + ClassDB::bind_method(D_METHOD("set_alpha_cut_mode", "mode"), &SpriteBase3D::set_alpha_cut_mode); + ClassDB::bind_method(D_METHOD("get_alpha_cut_mode"), &SpriteBase3D::get_alpha_cut_mode); - ClassDB::bind_method(D_METHOD("_queue_update"),&SpriteBase3D::_queue_update); - ClassDB::bind_method(D_METHOD("_im_update"),&SpriteBase3D::_im_update); + ClassDB::bind_method(D_METHOD("get_item_rect"), &SpriteBase3D::get_item_rect); + ClassDB::bind_method(D_METHOD("_queue_update"), &SpriteBase3D::_queue_update); + ClassDB::bind_method(D_METHOD("_im_update"), &SpriteBase3D::_im_update); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "centered"), "set_centered","is_centered"); - ADD_PROPERTY( PropertyInfo( Variant::VECTOR2, "offset"), "set_offset","get_offset"); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "flip_h"), "set_flip_h","is_flipped_h"); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "flip_v"), "set_flip_v","is_flipped_v"); - ADD_PROPERTY( PropertyInfo( Variant::COLOR, "modulate"), "set_modulate","get_modulate"); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "opacity",PROPERTY_HINT_RANGE,"0,1,0.01"), "set_opacity","get_opacity"); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "pixel_size",PROPERTY_HINT_RANGE,"0.0001,128,0.0001"), "set_pixel_size","get_pixel_size"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "axis",PROPERTY_HINT_ENUM,"X-Axis,Y-Axis,Z-Axis"), "set_axis","get_axis"); - ADD_GROUP("Flags",""); - ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "transparent"), "set_draw_flag","get_draw_flag",FLAG_TRANSPARENT); - ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "shaded"), "set_draw_flag","get_draw_flag",FLAG_SHADED); - ADD_PROPERTY( PropertyInfo( Variant::INT, "alpha_cut",PROPERTY_HINT_ENUM,"Disabled,Discard,Opaque Pre-Pass"), "set_alpha_cut_mode","get_alpha_cut_mode"); - - - BIND_CONSTANT( FLAG_TRANSPARENT ); - BIND_CONSTANT( FLAG_SHADED ); - BIND_CONSTANT( FLAG_MAX ); - - BIND_CONSTANT( ALPHA_CUT_DISABLED ); - BIND_CONSTANT( ALPHA_CUT_DISCARD ); - BIND_CONSTANT( ALPHA_CUT_OPAQUE_PREPASS ); - + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate"), "set_modulate", "get_modulate"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "opacity", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_opacity", "get_opacity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "pixel_size", PROPERTY_HINT_RANGE, "0.0001,128,0.0001"), "set_pixel_size", "get_pixel_size"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "axis", PROPERTY_HINT_ENUM, "X-Axis,Y-Axis,Z-Axis"), "set_axis", "get_axis"); + ADD_GROUP("Flags", ""); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "transparent"), "set_draw_flag", "get_draw_flag", FLAG_TRANSPARENT); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "shaded"), "set_draw_flag", "get_draw_flag", FLAG_SHADED); + ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_cut", PROPERTY_HINT_ENUM, "Disabled,Discard,Opaque Pre-Pass"), "set_alpha_cut_mode", "get_alpha_cut_mode"); + BIND_CONSTANT(FLAG_TRANSPARENT); + BIND_CONSTANT(FLAG_SHADED); + BIND_CONSTANT(FLAG_MAX); + BIND_CONSTANT(ALPHA_CUT_DISABLED); + BIND_CONSTANT(ALPHA_CUT_DISCARD); + BIND_CONSTANT(ALPHA_CUT_OPAQUE_PREPASS); } - - - SpriteBase3D::SpriteBase3D() { - color_dirty=true; - centered=true; - hflip=false; - vflip=false; - parent_sprite=NULL; - pI=NULL; - - for(int i=0;iimmediate_create(); set_base(immediate); } - SpriteBase3D::~SpriteBase3D() { VisualServer::get_singleton()->free(immediate); } - /////////////////////////////////////////// - void Sprite3D::_draw() { RID immediate = get_immediate(); @@ -351,7 +319,7 @@ void Sprite3D::_draw() { if (!texture.is_valid()) return; //no texuture no life Vector2 tsize = texture->get_size(); - if (tsize.x==0 || tsize.y==0) + if (tsize.x == 0 || tsize.y == 0) return; Size2i s; @@ -359,130 +327,122 @@ void Sprite3D::_draw() { if (region) { - s=region_rect.size; - src_rect=region_rect; + s = region_rect.size; + src_rect = region_rect; } else { s = texture->get_size(); - s=s/Size2i(hframes,vframes); - - src_rect.size=s; - src_rect.pos.x+=(frame%hframes)*s.x; - src_rect.pos.y+=(frame/hframes)*s.y; + s = s / Size2i(hframes, vframes); + src_rect.size = s; + src_rect.pos.x += (frame % hframes) * s.x; + src_rect.pos.y += (frame / hframes) * s.y; } - Point2i ofs=get_offset(); + Point2i ofs = get_offset(); if (is_centered()) - ofs-=s/2; - - Rect2i dst_rect(ofs,s); + ofs -= s / 2; + Rect2i dst_rect(ofs, s); Rect2 final_rect; Rect2 final_src_rect; - if (!texture->get_rect_region(dst_rect,src_rect,final_rect,final_src_rect)) + if (!texture->get_rect_region(dst_rect, src_rect, final_rect, final_src_rect)) return; - - if (final_rect.size.x==0 || final_rect.size.y==0) + if (final_rect.size.x == 0 || final_rect.size.y == 0) return; - Color color=_get_color_accum(); - color.a*=get_opacity(); + Color color = _get_color_accum(); + color.a *= get_opacity(); - float pixel_size=get_pixel_size(); + float pixel_size = get_pixel_size(); - Vector2 vertices[4]={ + Vector2 vertices[4] = { - (final_rect.pos+Vector2(0,final_rect.size.y)) * pixel_size, - (final_rect.pos+final_rect.size) * pixel_size, - (final_rect.pos+Vector2(final_rect.size.x,0)) * pixel_size, + (final_rect.pos + Vector2(0, final_rect.size.y)) * pixel_size, + (final_rect.pos + final_rect.size) * pixel_size, + (final_rect.pos + Vector2(final_rect.size.x, 0)) * pixel_size, final_rect.pos * pixel_size, - }; - Vector2 uvs[4]={ + Vector2 uvs[4] = { final_src_rect.pos / tsize, - (final_src_rect.pos+Vector2(final_src_rect.size.x,0)) / tsize, - (final_src_rect.pos+final_src_rect.size) / tsize, - (final_src_rect.pos+Vector2(0,final_src_rect.size.y)) / tsize, + (final_src_rect.pos + Vector2(final_src_rect.size.x, 0)) / tsize, + (final_src_rect.pos + final_src_rect.size) / tsize, + (final_src_rect.pos + Vector2(0, final_src_rect.size.y)) / tsize, }; if (is_flipped_h()) { - SWAP(uvs[0],uvs[1]); - SWAP(uvs[2],uvs[3]); + SWAP(uvs[0], uvs[1]); + SWAP(uvs[2], uvs[3]); } if (is_flipped_v()) { - SWAP(uvs[0],uvs[3]); - SWAP(uvs[1],uvs[2]); + SWAP(uvs[0], uvs[3]); + SWAP(uvs[1], uvs[2]); } - Vector3 normal; int axis = get_axis(); - normal[axis]=1.0; + normal[axis] = 1.0; - RID mat = VS::get_singleton()->material_2d_get(get_draw_flag(FLAG_SHADED),get_draw_flag(FLAG_TRANSPARENT),get_alpha_cut_mode()==ALPHA_CUT_DISCARD,get_alpha_cut_mode()==ALPHA_CUT_OPAQUE_PREPASS); - VS::get_singleton()->immediate_set_material(immediate,mat); + RID mat = VS::get_singleton()->material_2d_get(get_draw_flag(FLAG_SHADED), get_draw_flag(FLAG_TRANSPARENT), get_alpha_cut_mode() == ALPHA_CUT_DISCARD, get_alpha_cut_mode() == ALPHA_CUT_OPAQUE_PREPASS); + VS::get_singleton()->immediate_set_material(immediate, mat); - VS::get_singleton()->immediate_begin(immediate,VS::PRIMITIVE_TRIANGLE_FAN,texture->get_rid()); + VS::get_singleton()->immediate_begin(immediate, VS::PRIMITIVE_TRIANGLE_FAN, texture->get_rid()); int x_axis = ((axis + 1) % 3); int y_axis = ((axis + 2) % 3); - if (axis!=Vector3::AXIS_Z) { - SWAP(x_axis,y_axis); + if (axis != Vector3::AXIS_Z) { + SWAP(x_axis, y_axis); - for(int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { //uvs[i] = Vector2(1.0,1.0)-uvs[i]; //SWAP(vertices[i].x,vertices[i].y); - if (axis==Vector3::AXIS_Y) { - vertices[i].y = - vertices[i].y; - } else if (axis==Vector3::AXIS_X) { - vertices[i].x = - vertices[i].x; + if (axis == Vector3::AXIS_Y) { + vertices[i].y = -vertices[i].y; + } else if (axis == Vector3::AXIS_X) { + vertices[i].x = -vertices[i].x; } } } Rect3 aabb; - for(int i=0;i<4;i++) { - VS::get_singleton()->immediate_normal(immediate,normal); - VS::get_singleton()->immediate_color(immediate,color); - VS::get_singleton()->immediate_uv(immediate,uvs[i]); + for (int i = 0; i < 4; i++) { + VS::get_singleton()->immediate_normal(immediate, normal); + VS::get_singleton()->immediate_color(immediate, color); + VS::get_singleton()->immediate_uv(immediate, uvs[i]); Vector3 vtx; - vtx[x_axis]=vertices[i][0]; - vtx[y_axis]=vertices[i][1]; - VS::get_singleton()->immediate_vertex(immediate,vtx); - if (i==0) { - aabb.pos=vtx; - aabb.size=Vector3(); + vtx[x_axis] = vertices[i][0]; + vtx[y_axis] = vertices[i][1]; + VS::get_singleton()->immediate_vertex(immediate, vtx); + if (i == 0) { + aabb.pos = vtx; + aabb.size = Vector3(); } else { aabb.expand_to(vtx); } } set_aabb(aabb); VS::get_singleton()->immediate_end(immediate); - - } -void Sprite3D::set_texture(const Ref& p_texture) { +void Sprite3D::set_texture(const Ref &p_texture) { - if (p_texture==texture) + if (p_texture == texture) return; if (texture.is_valid()) { - texture->disconnect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->_queue_update); + texture->disconnect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_queue_update); } - texture=p_texture; + texture = p_texture; if (texture.is_valid()) { texture->set_flags(texture->get_flags()); //remove repeat from texture, it looks bad in sprites - texture->connect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->_queue_update); + texture->connect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_queue_update); } _queue_update(); - } Ref Sprite3D::get_texture() const { @@ -492,22 +452,22 @@ Ref Sprite3D::get_texture() const { void Sprite3D::set_region(bool p_region) { - if (p_region==region) + if (p_region == region) return; - region=p_region; + region = p_region; _queue_update(); } -bool Sprite3D::is_region() const{ +bool Sprite3D::is_region() const { return region; } -void Sprite3D::set_region_rect(const Rect2& p_region_rect) { +void Sprite3D::set_region_rect(const Rect2 &p_region_rect) { - bool changed=region_rect!=p_region_rect; - region_rect=p_region_rect; + bool changed = region_rect != p_region_rect; + region_rect = p_region_rect; if (region && changed) { _queue_update(); } @@ -520,14 +480,13 @@ Rect2 Sprite3D::get_region_rect() const { void Sprite3D::set_frame(int p_frame) { - ERR_FAIL_INDEX(p_frame,vframes*hframes); + ERR_FAIL_INDEX(p_frame, vframes * hframes); if (frame != p_frame) - frame=p_frame; + frame = p_frame; _queue_update(); emit_signal(SceneStringNames::get_singleton()->frame_changed); - } int Sprite3D::get_frame() const { @@ -537,8 +496,8 @@ int Sprite3D::get_frame() const { void Sprite3D::set_vframes(int p_amount) { - ERR_FAIL_COND(p_amount<1); - vframes=p_amount; + ERR_FAIL_COND(p_amount < 1); + vframes = p_amount; _queue_update(); _change_notify("frame"); } @@ -549,8 +508,8 @@ int Sprite3D::get_vframes() const { void Sprite3D::set_hframes(int p_amount) { - ERR_FAIL_COND(p_amount<1); - hframes=p_amount; + ERR_FAIL_COND(p_amount < 1); + hframes = p_amount; _queue_update(); _change_notify("frame"); } @@ -562,7 +521,7 @@ int Sprite3D::get_hframes() const { Rect2 Sprite3D::get_item_rect() const { if (texture.is_null()) - return Rect2(0,0,1,1); + return Rect2(0, 0, 1, 1); /* if (texture.is_null()) return CanvasItem::get_item_rect(); @@ -572,72 +531,68 @@ Rect2 Sprite3D::get_item_rect() const { if (region) { - s=region_rect.size; + s = region_rect.size; } else { s = texture->get_size(); - s=s/Point2(hframes,vframes); + s = s / Point2(hframes, vframes); } - Point2i ofs=get_offset(); + Point2i ofs = get_offset(); if (is_centered()) - ofs-=s/2; + ofs -= s / 2; - if (s==Size2(0,0)) - s=Size2(1,1); + if (s == Size2(0, 0)) + s = Size2(1, 1); - return Rect2(ofs,s); + return Rect2(ofs, s); } +void Sprite3D::_validate_property(PropertyInfo &property) const { -void Sprite3D::_validate_property(PropertyInfo& property) const { - - if (property.name=="frame") { + if (property.name == "frame") { - property.hint=PROPERTY_HINT_SPRITE_FRAME; + property.hint = PROPERTY_HINT_SPRITE_FRAME; - property.hint_string="0,"+itos(vframes*hframes-1)+",1"; + property.hint_string = "0," + itos(vframes * hframes - 1) + ",1"; } } void Sprite3D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_texture","texture:Texture"),&Sprite3D::set_texture); - ClassDB::bind_method(D_METHOD("get_texture:Texture"),&Sprite3D::get_texture); + ClassDB::bind_method(D_METHOD("set_texture", "texture:Texture"), &Sprite3D::set_texture); + ClassDB::bind_method(D_METHOD("get_texture:Texture"), &Sprite3D::get_texture); - ClassDB::bind_method(D_METHOD("set_region","enabled"),&Sprite3D::set_region); - ClassDB::bind_method(D_METHOD("is_region"),&Sprite3D::is_region); + ClassDB::bind_method(D_METHOD("set_region", "enabled"), &Sprite3D::set_region); + ClassDB::bind_method(D_METHOD("is_region"), &Sprite3D::is_region); - ClassDB::bind_method(D_METHOD("set_region_rect","rect"),&Sprite3D::set_region_rect); - ClassDB::bind_method(D_METHOD("get_region_rect"),&Sprite3D::get_region_rect); + ClassDB::bind_method(D_METHOD("set_region_rect", "rect"), &Sprite3D::set_region_rect); + ClassDB::bind_method(D_METHOD("get_region_rect"), &Sprite3D::get_region_rect); - ClassDB::bind_method(D_METHOD("set_frame","frame"),&Sprite3D::set_frame); - ClassDB::bind_method(D_METHOD("get_frame"),&Sprite3D::get_frame); + ClassDB::bind_method(D_METHOD("set_frame", "frame"), &Sprite3D::set_frame); + ClassDB::bind_method(D_METHOD("get_frame"), &Sprite3D::get_frame); - ClassDB::bind_method(D_METHOD("set_vframes","vframes"),&Sprite3D::set_vframes); - ClassDB::bind_method(D_METHOD("get_vframes"),&Sprite3D::get_vframes); + ClassDB::bind_method(D_METHOD("set_vframes", "vframes"), &Sprite3D::set_vframes); + ClassDB::bind_method(D_METHOD("get_vframes"), &Sprite3D::get_vframes); - ClassDB::bind_method(D_METHOD("set_hframes","hframes"),&Sprite3D::set_hframes); - ClassDB::bind_method(D_METHOD("get_hframes"),&Sprite3D::get_hframes); + ClassDB::bind_method(D_METHOD("set_hframes", "hframes"), &Sprite3D::set_hframes); + ClassDB::bind_method(D_METHOD("get_hframes"), &Sprite3D::get_hframes); - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_texture","get_texture"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "vframes",PROPERTY_HINT_RANGE,"1,16384,1"), "set_vframes","get_vframes"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "hframes",PROPERTY_HINT_RANGE,"1,16384,1"), "set_hframes","get_hframes"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "frame",PROPERTY_HINT_SPRITE_FRAME), "set_frame","get_frame"); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "region"), "set_region","is_region"); - ADD_PROPERTY( PropertyInfo( Variant::RECT2, "region_rect"), "set_region_rect","get_region_rect"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "vframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_vframes", "get_vframes"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "hframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_hframes", "get_hframes"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "frame", PROPERTY_HINT_SPRITE_FRAME), "set_frame", "get_frame"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "region"), "set_region", "is_region"); + ADD_PROPERTY(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect"); ADD_SIGNAL(MethodInfo("frame_changed")); - } Sprite3D::Sprite3D() { - - region=false; - frame=0; - vframes=1; - hframes=1; - + region = false; + frame = 0; + vframes = 1; + hframes = 1; } //////////////////////////////////////// @@ -853,22 +808,18 @@ AnimatedSprite3D::AnimatedSprite3D() { frame=0; } - - #endif - void AnimatedSprite3D::_draw() { RID immediate = get_immediate(); VS::get_singleton()->immediate_clear(immediate); - if (frames.is_null()) { return; } - if (frame<0) { + if (frame < 0) { return; } @@ -876,195 +827,185 @@ void AnimatedSprite3D::_draw() { return; } - - Ref texture = frames->get_frame(animation,frame); + Ref texture = frames->get_frame(animation, frame); if (!texture.is_valid()) return; //no texuture no life Vector2 tsize = texture->get_size(); - if (tsize.x==0 || tsize.y==0) + if (tsize.x == 0 || tsize.y == 0) return; - Size2i s=tsize; + Size2i s = tsize; Rect2i src_rect; - src_rect.size=s; + src_rect.size = s; - Point2i ofs=get_offset(); + Point2i ofs = get_offset(); if (is_centered()) - ofs-=s/2; - - Rect2i dst_rect(ofs,s); + ofs -= s / 2; + Rect2i dst_rect(ofs, s); Rect2 final_rect; Rect2 final_src_rect; - if (!texture->get_rect_region(dst_rect,src_rect,final_rect,final_src_rect)) + if (!texture->get_rect_region(dst_rect, src_rect, final_rect, final_src_rect)) return; - - if (final_rect.size.x==0 || final_rect.size.y==0) + if (final_rect.size.x == 0 || final_rect.size.y == 0) return; - Color color=_get_color_accum(); - color.a*=get_opacity(); + Color color = _get_color_accum(); + color.a *= get_opacity(); - float pixel_size=get_pixel_size(); + float pixel_size = get_pixel_size(); - Vector2 vertices[4]={ + Vector2 vertices[4] = { - (final_rect.pos+Vector2(0,final_rect.size.y)) * pixel_size, - (final_rect.pos+final_rect.size) * pixel_size, - (final_rect.pos+Vector2(final_rect.size.x,0)) * pixel_size, + (final_rect.pos + Vector2(0, final_rect.size.y)) * pixel_size, + (final_rect.pos + final_rect.size) * pixel_size, + (final_rect.pos + Vector2(final_rect.size.x, 0)) * pixel_size, final_rect.pos * pixel_size, - }; - Vector2 uvs[4]={ + Vector2 uvs[4] = { final_src_rect.pos / tsize, - (final_src_rect.pos+Vector2(final_src_rect.size.x,0)) / tsize, - (final_src_rect.pos+final_src_rect.size) / tsize, - (final_src_rect.pos+Vector2(0,final_src_rect.size.y)) / tsize, + (final_src_rect.pos + Vector2(final_src_rect.size.x, 0)) / tsize, + (final_src_rect.pos + final_src_rect.size) / tsize, + (final_src_rect.pos + Vector2(0, final_src_rect.size.y)) / tsize, }; if (is_flipped_h()) { - SWAP(uvs[0],uvs[1]); - SWAP(uvs[2],uvs[3]); + SWAP(uvs[0], uvs[1]); + SWAP(uvs[2], uvs[3]); } if (is_flipped_v()) { - SWAP(uvs[0],uvs[3]); - SWAP(uvs[1],uvs[2]); + SWAP(uvs[0], uvs[3]); + SWAP(uvs[1], uvs[2]); } - Vector3 normal; int axis = get_axis(); - normal[axis]=1.0; + normal[axis] = 1.0; - RID mat = VS::get_singleton()->material_2d_get(get_draw_flag(FLAG_SHADED),get_draw_flag(FLAG_TRANSPARENT),get_alpha_cut_mode()==ALPHA_CUT_DISCARD,get_alpha_cut_mode()==ALPHA_CUT_OPAQUE_PREPASS); - VS::get_singleton()->immediate_set_material(immediate,mat); + RID mat = VS::get_singleton()->material_2d_get(get_draw_flag(FLAG_SHADED), get_draw_flag(FLAG_TRANSPARENT), get_alpha_cut_mode() == ALPHA_CUT_DISCARD, get_alpha_cut_mode() == ALPHA_CUT_OPAQUE_PREPASS); + VS::get_singleton()->immediate_set_material(immediate, mat); - VS::get_singleton()->immediate_begin(immediate,VS::PRIMITIVE_TRIANGLE_FAN,texture->get_rid()); + VS::get_singleton()->immediate_begin(immediate, VS::PRIMITIVE_TRIANGLE_FAN, texture->get_rid()); int x_axis = ((axis + 1) % 3); int y_axis = ((axis + 2) % 3); - if (axis!=Vector3::AXIS_Z) { - SWAP(x_axis,y_axis); + if (axis != Vector3::AXIS_Z) { + SWAP(x_axis, y_axis); - for(int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { //uvs[i] = Vector2(1.0,1.0)-uvs[i]; //SWAP(vertices[i].x,vertices[i].y); - if (axis==Vector3::AXIS_Y) { - vertices[i].y = - vertices[i].y; - } else if (axis==Vector3::AXIS_X) { - vertices[i].x = - vertices[i].x; + if (axis == Vector3::AXIS_Y) { + vertices[i].y = -vertices[i].y; + } else if (axis == Vector3::AXIS_X) { + vertices[i].x = -vertices[i].x; } } } Rect3 aabb; - for(int i=0;i<4;i++) { - VS::get_singleton()->immediate_normal(immediate,normal); - VS::get_singleton()->immediate_color(immediate,color); - VS::get_singleton()->immediate_uv(immediate,uvs[i]); + for (int i = 0; i < 4; i++) { + VS::get_singleton()->immediate_normal(immediate, normal); + VS::get_singleton()->immediate_color(immediate, color); + VS::get_singleton()->immediate_uv(immediate, uvs[i]); Vector3 vtx; - vtx[x_axis]=vertices[i][0]; - vtx[y_axis]=vertices[i][1]; - VS::get_singleton()->immediate_vertex(immediate,vtx); - if (i==0) { - aabb.pos=vtx; - aabb.size=Vector3(); + vtx[x_axis] = vertices[i][0]; + vtx[y_axis] = vertices[i][1]; + VS::get_singleton()->immediate_vertex(immediate, vtx); + if (i == 0) { + aabb.pos = vtx; + aabb.size = Vector3(); } else { aabb.expand_to(vtx); } } set_aabb(aabb); VS::get_singleton()->immediate_end(immediate); - } - - -void AnimatedSprite3D::_validate_property(PropertyInfo& property) const { +void AnimatedSprite3D::_validate_property(PropertyInfo &property) const { if (!frames.is_valid()) return; - if (property.name=="animation") { + if (property.name == "animation") { - property.hint=PROPERTY_HINT_ENUM; + property.hint = PROPERTY_HINT_ENUM; List names; frames->get_animation_list(&names); names.sort_custom(); - bool current_found=false; + bool current_found = false; - for (List::Element *E=names.front();E;E=E->next()) { + for (List::Element *E = names.front(); E; E = E->next()) { if (E->prev()) { - property.hint_string+=","; + property.hint_string += ","; } - property.hint_string+=String(E->get()); - if (animation==E->get()) { - current_found=true; + property.hint_string += String(E->get()); + if (animation == E->get()) { + current_found = true; } } if (!current_found) { - if (property.hint_string==String()) { - property.hint_string=String(animation); + if (property.hint_string == String()) { + property.hint_string = String(animation); } else { - property.hint_string=String(animation)+","+property.hint_string; + property.hint_string = String(animation) + "," + property.hint_string; } } } + if (property.name == "frame") { - if (property.name=="frame") { - - property.hint=PROPERTY_HINT_RANGE; + property.hint = PROPERTY_HINT_RANGE; if (frames->has_animation(animation)) { - property.hint_string="0,"+itos(frames->get_frame_count(animation)-1)+",1"; + property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1"; } else { - property.hint_string="0,0,0"; + property.hint_string = "0,0,0"; } } - } void AnimatedSprite3D::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_INTERNAL_PROCESS: { if (frames.is_null()) return; if (!frames->has_animation(animation)) return; - if (frame<0) + if (frame < 0) return; float speed = frames->get_animation_speed(animation); - if (speed==0) + if (speed == 0) return; //do nothing float remaining = get_process_delta_time(); - while(remaining) { + while (remaining) { - if (timeout<=0) { + if (timeout <= 0) { - timeout=1.0/speed; + timeout = 1.0 / speed; int fc = frames->get_frame_count(animation); - if (frame>=fc-1) { + if (frame >= fc - 1) { if (frames->get_animation_loop(animation)) { - frame=0; + frame = 0; } else { - frame=fc-1; + frame = fc - 1; } } else { frame++; @@ -1074,9 +1015,9 @@ void AnimatedSprite3D::_notification(int p_what) { _change_notify("frame"); } - float to_process = MIN(timeout,remaining); - remaining-=to_process; - timeout-=to_process; + float to_process = MIN(timeout, remaining); + remaining -= to_process; + timeout -= to_process; } } break; #if 0 @@ -1137,30 +1078,26 @@ void AnimatedSprite3D::_notification(int p_what) { } break; #endif } - } void AnimatedSprite3D::set_sprite_frames(const Ref &p_frames) { if (frames.is_valid()) - frames->disconnect("changed",this,"_res_changed"); - frames=p_frames; + frames->disconnect("changed", this, "_res_changed"); + frames = p_frames; if (frames.is_valid()) - frames->connect("changed",this,"_res_changed"); + frames->connect("changed", this, "_res_changed"); if (!frames.is_valid()) { - frame=0; + frame = 0; } else { set_frame(frame); } - - _change_notify(); _reset_timeout(); _queue_update(); update_configuration_warning(); - } Ref AnimatedSprite3D::get_sprite_frames() const { @@ -1176,55 +1113,48 @@ void AnimatedSprite3D::set_frame(int p_frame) { if (frames->has_animation(animation)) { int limit = frames->get_frame_count(animation); - if (p_frame>=limit) - p_frame=limit-1; - + if (p_frame >= limit) + p_frame = limit - 1; } - if (p_frame<0) - p_frame=0; + if (p_frame < 0) + p_frame = 0; - - if (frame==p_frame) + if (frame == p_frame) return; - frame=p_frame; + frame = p_frame; _reset_timeout(); _queue_update(); _change_notify("frame"); emit_signal(SceneStringNames::get_singleton()->frame_changed); - - - } int AnimatedSprite3D::get_frame() const { return frame; } - - Rect2 AnimatedSprite3D::get_item_rect() const { - if (!frames.is_valid() || !frames->has_animation(animation) || frame<0 || frame>=frames->get_frame_count(animation)) { - return Rect2(0,0,1,1); + if (!frames.is_valid() || !frames->has_animation(animation) || frame < 0 || frame >= frames->get_frame_count(animation)) { + return Rect2(0, 0, 1, 1); } Ref t; if (animation) - t = frames->get_frame(animation,frame); + t = frames->get_frame(animation, frame); if (t.is_null()) - return Rect2(0,0,1,1); + return Rect2(0, 0, 1, 1); Size2i s = t->get_size(); - Point2 ofs=offset; + Point2 ofs = offset; if (centered) - ofs-=s/2; + ofs -= s / 2; - if (s==Size2(0,0)) - s=Size2(1,1); + if (s == Size2(0, 0)) + s = Size2(1, 1); - return Rect2(ofs,s); + return Rect2(ofs, s); } void AnimatedSprite3D::_res_changed() { @@ -1237,9 +1167,9 @@ void AnimatedSprite3D::_res_changed() { void AnimatedSprite3D::_set_playing(bool p_playing) { - if (playing==p_playing) + if (playing == p_playing) return; - playing=p_playing; + playing = p_playing; _reset_timeout(); set_process_internal(playing); } @@ -1249,14 +1179,14 @@ bool AnimatedSprite3D::_is_playing() const { return playing; } -void AnimatedSprite3D::play(const StringName& p_animation) { +void AnimatedSprite3D::play(const StringName &p_animation) { if (p_animation) set_animation(p_animation); _set_playing(true); } -void AnimatedSprite3D::stop(){ +void AnimatedSprite3D::stop() { _set_playing(false); } @@ -1273,29 +1203,28 @@ void AnimatedSprite3D::_reset_timeout() { if (frames.is_valid() && frames->has_animation(animation)) { float speed = frames->get_animation_speed(animation); - if (speed>0) { - timeout=1.0/speed; + if (speed > 0) { + timeout = 1.0 / speed; } else { - timeout=0; + timeout = 0; } } else { - timeout=0; + timeout = 0; } - } -void AnimatedSprite3D::set_animation(const StringName& p_animation){ +void AnimatedSprite3D::set_animation(const StringName &p_animation) { - if (animation==p_animation) + if (animation == p_animation) return; - animation=p_animation; + animation = p_animation; _reset_timeout(); set_frame(0); _change_notify(); _queue_update(); } -StringName AnimatedSprite3D::get_animation() const{ +StringName AnimatedSprite3D::get_animation() const { return animation; } @@ -1311,44 +1240,36 @@ String AnimatedSprite3D::get_configuration_warning() const { void AnimatedSprite3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_sprite_frames", "sprite_frames:SpriteFrames"), &AnimatedSprite3D::set_sprite_frames); + ClassDB::bind_method(D_METHOD("get_sprite_frames:SpriteFrames"), &AnimatedSprite3D::get_sprite_frames); - ClassDB::bind_method(D_METHOD("set_sprite_frames","sprite_frames:SpriteFrames"),&AnimatedSprite3D::set_sprite_frames); - ClassDB::bind_method(D_METHOD("get_sprite_frames:SpriteFrames"),&AnimatedSprite3D::get_sprite_frames); + ClassDB::bind_method(D_METHOD("set_animation", "animation"), &AnimatedSprite3D::set_animation); + ClassDB::bind_method(D_METHOD("get_animation"), &AnimatedSprite3D::get_animation); - ClassDB::bind_method(D_METHOD("set_animation","animation"),&AnimatedSprite3D::set_animation); - ClassDB::bind_method(D_METHOD("get_animation"),&AnimatedSprite3D::get_animation); + ClassDB::bind_method(D_METHOD("_set_playing", "playing"), &AnimatedSprite3D::_set_playing); + ClassDB::bind_method(D_METHOD("_is_playing"), &AnimatedSprite3D::_is_playing); - ClassDB::bind_method(D_METHOD("_set_playing","playing"),&AnimatedSprite3D::_set_playing); - ClassDB::bind_method(D_METHOD("_is_playing"),&AnimatedSprite3D::_is_playing); + ClassDB::bind_method(D_METHOD("play", "anim"), &AnimatedSprite3D::play, DEFVAL(StringName())); + ClassDB::bind_method(D_METHOD("stop"), &AnimatedSprite3D::stop); + ClassDB::bind_method(D_METHOD("is_playing"), &AnimatedSprite3D::is_playing); - ClassDB::bind_method(D_METHOD("play","anim"),&AnimatedSprite3D::play,DEFVAL(StringName())); - ClassDB::bind_method(D_METHOD("stop"),&AnimatedSprite3D::stop); - ClassDB::bind_method(D_METHOD("is_playing"),&AnimatedSprite3D::is_playing); + ClassDB::bind_method(D_METHOD("set_frame", "frame"), &AnimatedSprite3D::set_frame); + ClassDB::bind_method(D_METHOD("get_frame"), &AnimatedSprite3D::get_frame); - - ClassDB::bind_method(D_METHOD("set_frame","frame"),&AnimatedSprite3D::set_frame); - ClassDB::bind_method(D_METHOD("get_frame"),&AnimatedSprite3D::get_frame); - - ClassDB::bind_method(D_METHOD("_res_changed"),&AnimatedSprite3D::_res_changed); + ClassDB::bind_method(D_METHOD("_res_changed"), &AnimatedSprite3D::_res_changed); ADD_SIGNAL(MethodInfo("frame_changed")); - ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "frames",PROPERTY_HINT_RESOURCE_TYPE,"SpriteFrames"), "set_sprite_frames","get_sprite_frames"); - ADD_PROPERTY( PropertyInfo( Variant::STRING, "animation"), "set_animation","get_animation"); - ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "frame",PROPERTY_HINT_SPRITE_FRAME), "set_frame","get_frame"); - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "playing"), "_set_playing","_is_playing"); - - + ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "animation"), "set_animation", "get_animation"); + ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "frame", PROPERTY_HINT_SPRITE_FRAME), "set_frame", "get_frame"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "playing"), "_set_playing", "_is_playing"); } AnimatedSprite3D::AnimatedSprite3D() { - frame=0; - playing=false; - animation="default"; - timeout=0; - - + frame = 0; + playing = false; + animation = "default"; + timeout = 0; } - - diff --git a/scene/3d/sprite_3d.h b/scene/3d/sprite_3d.h index a14ce4049..d1de4e1b8 100644 --- a/scene/3d/sprite_3d.h +++ b/scene/3d/sprite_3d.h @@ -29,15 +29,14 @@ #ifndef SPRITE_3D_H #define SPRITE_3D_H -#include "scene/3d/visual_instance.h" #include "scene/2d/animated_sprite.h" - +#include "scene/3d/visual_instance.h" class SpriteBase3D : public GeometryInstance { - GDCLASS(SpriteBase3D,GeometryInstance); -public: + GDCLASS(SpriteBase3D, GeometryInstance); +public: enum DrawFlags { FLAG_TRANSPARENT, FLAG_SHADED, @@ -52,14 +51,12 @@ public: }; private: - - bool color_dirty; Color color_accum; SpriteBase3D *parent_sprite; - List children; - List::Element *pI; + List children; + List::Element *pI; bool centered; Point2 offset; @@ -67,7 +64,6 @@ private: bool hflip; bool vflip; - Color modulate; float opacity; @@ -82,24 +78,22 @@ private: bool pending_update; void _im_update(); - void _propagate_color_changed(); protected: - Color _get_color_accum(); void _notification(int p_what); static void _bind_methods(); - virtual void _draw()=0; - _FORCE_INLINE_ void set_aabb(const Rect3& p_aabb) { aabb=p_aabb; } - _FORCE_INLINE_ RID& get_immediate() { return immediate; } + virtual void _draw() = 0; + _FORCE_INLINE_ void set_aabb(const Rect3 &p_aabb) { aabb = p_aabb; } + _FORCE_INLINE_ RID &get_immediate() { return immediate; } void _queue_update(); -public: +public: void set_centered(bool p_center); bool is_centered() const; - void set_offset(const Point2& p_offset); + void set_offset(const Point2 &p_offset); Point2 get_offset() const; void set_flip_h(bool p_flip); @@ -111,10 +105,10 @@ public: void set_region(bool p_region); bool is_region() const; - void set_region_rect(const Rect2& p_region_rect); + void set_region_rect(const Rect2 &p_region_rect); Rect2 get_region_rect() const; - void set_modulate(const Color& p_color); + void set_modulate(const Color &p_color); Color get_modulate() const; void set_opacity(float p_amount); @@ -126,13 +120,13 @@ public: void set_axis(Vector3::Axis p_amount); Vector3::Axis get_axis() const; - void set_draw_flag(DrawFlags p_flag,bool p_enable); + void set_draw_flag(DrawFlags p_flag, bool p_enable); bool get_draw_flag(DrawFlags p_flag) const; void set_alpha_cut_mode(AlphaCutMode p_mode); AlphaCutMode get_alpha_cut_mode() const; - virtual Rect2 get_item_rect() const=0; + virtual Rect2 get_item_rect() const = 0; virtual Rect3 get_aabb() const; virtual PoolVector get_faces(uint32_t p_usage_flags) const; @@ -141,13 +135,11 @@ public: ~SpriteBase3D(); }; - class Sprite3D : public SpriteBase3D { - GDCLASS(Sprite3D,SpriteBase3D); + GDCLASS(Sprite3D, SpriteBase3D); Ref texture; - bool region; Rect2 region_rect; @@ -155,22 +147,21 @@ class Sprite3D : public SpriteBase3D { int vframes; int hframes; + protected: virtual void _draw(); static void _bind_methods(); - virtual void _validate_property(PropertyInfo& property) const; -public: - + virtual void _validate_property(PropertyInfo &property) const; - - void set_texture(const Ref& p_texture); +public: + void set_texture(const Ref &p_texture); Ref get_texture() const; void set_region(bool p_region); bool is_region() const; - void set_region_rect(const Rect2& p_region_rect); + void set_region_rect(const Rect2 &p_region_rect); Rect2 get_region_rect() const; void set_frame(int p_frame); @@ -219,12 +210,9 @@ public: }; #endif - - - class AnimatedSprite3D : public SpriteBase3D { - GDCLASS(AnimatedSprite3D,SpriteBase3D); + GDCLASS(AnimatedSprite3D, SpriteBase3D); Ref frames; bool playing; @@ -247,39 +235,32 @@ class AnimatedSprite3D : public SpriteBase3D { void _set_playing(bool p_playing); bool _is_playing() const; - protected: - virtual void _draw(); static void _bind_methods(); void _notification(int p_what); - virtual void _validate_property(PropertyInfo& property) const; + virtual void _validate_property(PropertyInfo &property) const; public: - - - void set_sprite_frames(const Ref &p_frames); Ref get_sprite_frames() const; - void play(const StringName& p_animation=StringName()); + void play(const StringName &p_animation = StringName()); void stop(); bool is_playing() const; - void set_animation(const StringName& p_animation); + void set_animation(const StringName &p_animation); StringName get_animation() const; void set_frame(int p_frame); int get_frame() const; - virtual Rect2 get_item_rect() const; virtual String get_configuration_warning() const; AnimatedSprite3D(); }; - VARIANT_ENUM_CAST(SpriteBase3D::DrawFlags); VARIANT_ENUM_CAST(SpriteBase3D::AlphaCutMode); #endif // SPRITE_3D_H diff --git a/scene/3d/test_cube.cpp b/scene/3d/test_cube.cpp index c52e59603..bab1d1e1c 100644 --- a/scene/3d/test_cube.cpp +++ b/scene/3d/test_cube.cpp @@ -29,25 +29,19 @@ #include "test_cube.h" #include "servers/visual_server.h" - - Rect3 TestCube::get_aabb() const { - return Rect3( Vector3(-1,-1,-1), Vector3(2, 2, 2 ) ); + return Rect3(Vector3(-1, -1, -1), Vector3(2, 2, 2)); } PoolVector TestCube::get_faces(uint32_t p_usage_flags) const { return PoolVector(); } - TestCube::TestCube() { set_base(VisualServer::get_singleton()->get_test_cube()); } - TestCube::~TestCube() { } - - diff --git a/scene/3d/test_cube.h b/scene/3d/test_cube.h index 4860bacd8..d03bea7b6 100644 --- a/scene/3d/test_cube.h +++ b/scene/3d/test_cube.h @@ -29,29 +29,24 @@ #ifndef TEST_CUBE_H #define TEST_CUBE_H - -#include "scene/3d/visual_instance.h" #include "rid.h" - +#include "scene/3d/visual_instance.h" /** @author Juan Linietsky */ class TestCube : public GeometryInstance { - GDCLASS( TestCube, GeometryInstance ); + GDCLASS(TestCube, GeometryInstance); RID instance; - public: - virtual Rect3 get_aabb() const; virtual PoolVector get_faces(uint32_t p_usage_flags) const; TestCube(); ~TestCube(); - }; #endif diff --git a/scene/3d/vehicle_body.cpp b/scene/3d/vehicle_body.cpp index 4b32c62d1..4a647fe68 100644 --- a/scene/3d/vehicle_body.cpp +++ b/scene/3d/vehicle_body.cpp @@ -30,78 +30,70 @@ #define ROLLING_INFLUENCE_FIX -class btVehicleJacobianEntry -{ +class btVehicleJacobianEntry { public: - - Vector3 m_linearJointAxis; - Vector3 m_aJ; - Vector3 m_bJ; - Vector3 m_0MinvJt; - Vector3 m_1MinvJt; + Vector3 m_linearJointAxis; + Vector3 m_aJ; + Vector3 m_bJ; + Vector3 m_0MinvJt; + Vector3 m_1MinvJt; //Optimization: can be stored in the w/last component of one of the vectors - real_t m_Adiag; + real_t m_Adiag; real_t getDiagonal() const { return m_Adiag; } - btVehicleJacobianEntry() {}; - //constraint between two different rigidbodies - btVehicleJacobianEntry( - const Basis& world2A, - const Basis& world2B, - const Vector3& rel_pos1, - const Vector3& rel_pos2, - const Vector3& jointAxis, - const Vector3& inertiaInvA, + btVehicleJacobianEntry(){}; + //constraint between two different rigidbodies + btVehicleJacobianEntry( + const Basis &world2A, + const Basis &world2B, + const Vector3 &rel_pos1, + const Vector3 &rel_pos2, + const Vector3 &jointAxis, + const Vector3 &inertiaInvA, const real_t massInvA, - const Vector3& inertiaInvB, + const Vector3 &inertiaInvB, const real_t massInvB) - :m_linearJointAxis(jointAxis) - { - m_aJ = world2A.xform(rel_pos1.cross(m_linearJointAxis)); - m_bJ = world2B.xform(rel_pos2.cross(-m_linearJointAxis)); - m_0MinvJt = inertiaInvA * m_aJ; - m_1MinvJt = inertiaInvB * m_bJ; - m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ); - - //btAssert(m_Adiag > real_t(0.0)); - } - - real_t getRelativeVelocity(const Vector3& linvelA,const Vector3& angvelA,const Vector3& linvelB,const Vector3& angvelB) - { - Vector3 linrel = linvelA - linvelB; - Vector3 angvela = angvelA * m_aJ; - Vector3 angvelb = angvelB * m_bJ; - linrel *= m_linearJointAxis; - angvela += angvelb; - angvela += linrel; - real_t rel_vel2 = angvela[0]+angvela[1]+angvela[2]; - return rel_vel2 + CMP_EPSILON; - } - + : m_linearJointAxis(jointAxis) { + m_aJ = world2A.xform(rel_pos1.cross(m_linearJointAxis)); + m_bJ = world2B.xform(rel_pos2.cross(-m_linearJointAxis)); + m_0MinvJt = inertiaInvA * m_aJ; + m_1MinvJt = inertiaInvB * m_bJ; + m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ); + + //btAssert(m_Adiag > real_t(0.0)); + } + real_t getRelativeVelocity(const Vector3 &linvelA, const Vector3 &angvelA, const Vector3 &linvelB, const Vector3 &angvelB) { + Vector3 linrel = linvelA - linvelB; + Vector3 angvela = angvelA * m_aJ; + Vector3 angvelb = angvelB * m_bJ; + linrel *= m_linearJointAxis; + angvela += angvelb; + angvela += linrel; + real_t rel_vel2 = angvela[0] + angvela[1] + angvela[2]; + return rel_vel2 + CMP_EPSILON; + } }; void VehicleWheel::_notification(int p_what) { - - if (p_what==NOTIFICATION_ENTER_TREE) { + if (p_what == NOTIFICATION_ENTER_TREE) { if (!get_parent()) return; VehicleBody *cb = get_parent()->cast_to(); if (!cb) return; - body=cb; - local_xform=get_transform(); + body = cb; + local_xform = get_transform(); cb->wheels.push_back(this); m_chassisConnectionPointCS = get_transform().origin; m_wheelDirectionCS = -get_transform().basis.get_axis(Vector3::AXIS_Y).normalized(); m_wheelAxleCS = get_transform().basis.get_axis(Vector3::AXIS_X).normalized(); - } - if (p_what==NOTIFICATION_EXIT_TREE) { + if (p_what == NOTIFICATION_EXIT_TREE) { if (!get_parent()) return; @@ -109,34 +101,27 @@ void VehicleWheel::_notification(int p_what) { if (!cb) return; cb->wheels.erase(this); - body=NULL; + body = NULL; } - } - void VehicleWheel::_update(PhysicsDirectBodyState *s) { - - if (m_raycastInfo.m_isInContact) { - real_t project= m_raycastInfo.m_contactNormalWS.dot( m_raycastInfo.m_wheelDirectionWS ); - Vector3 chassis_velocity_at_contactPoint; + real_t project = m_raycastInfo.m_contactNormalWS.dot(m_raycastInfo.m_wheelDirectionWS); + Vector3 chassis_velocity_at_contactPoint; Vector3 relpos = m_raycastInfo.m_contactPointWS - s->get_transform().origin; chassis_velocity_at_contactPoint = s->get_linear_velocity() + - (s->get_angular_velocity()).cross(relpos);// * mPos); + (s->get_angular_velocity()).cross(relpos); // * mPos); - real_t projVel = m_raycastInfo.m_contactNormalWS.dot( chassis_velocity_at_contactPoint ); - if ( project >= real_t(-0.1)) - { + real_t projVel = m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint); + if (project >= real_t(-0.1)) { m_suspensionRelativeVelocity = real_t(0.0); m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1); - } - else - { + } else { real_t inv = real_t(-1.) / project; m_suspensionRelativeVelocity = projVel * inv; m_clippedInvContactDotSuspension = inv; @@ -144,7 +129,7 @@ void VehicleWheel::_update(PhysicsDirectBodyState *s) { } - else // Not in contact : position wheel in a nice (rest length) position + else // Not in contact : position wheel in a nice (rest length) position { m_raycastInfo.m_suspensionLength = m_suspensionRestLength; m_suspensionRelativeVelocity = real_t(0.0); @@ -155,160 +140,150 @@ void VehicleWheel::_update(PhysicsDirectBodyState *s) { void VehicleWheel::set_radius(float p_radius) { - m_wheelRadius=p_radius; + m_wheelRadius = p_radius; update_gizmo(); } -float VehicleWheel::get_radius() const{ +float VehicleWheel::get_radius() const { return m_wheelRadius; } -void VehicleWheel::set_suspension_rest_length(float p_length){ +void VehicleWheel::set_suspension_rest_length(float p_length) { - m_suspensionRestLength=p_length; + m_suspensionRestLength = p_length; update_gizmo(); } -float VehicleWheel::get_suspension_rest_length() const{ +float VehicleWheel::get_suspension_rest_length() const { return m_suspensionRestLength; } -void VehicleWheel::set_suspension_travel(float p_length){ +void VehicleWheel::set_suspension_travel(float p_length) { - m_maxSuspensionTravelCm=p_length/0.01; + m_maxSuspensionTravelCm = p_length / 0.01; } -float VehicleWheel::get_suspension_travel() const{ +float VehicleWheel::get_suspension_travel() const { - return m_maxSuspensionTravelCm*0.01; + return m_maxSuspensionTravelCm * 0.01; } -void VehicleWheel::set_suspension_stiffness(float p_value){ +void VehicleWheel::set_suspension_stiffness(float p_value) { - m_suspensionStiffness=p_value; + m_suspensionStiffness = p_value; } -float VehicleWheel::get_suspension_stiffness() const{ +float VehicleWheel::get_suspension_stiffness() const { return m_suspensionStiffness; } -void VehicleWheel::set_suspension_max_force(float p_value){ +void VehicleWheel::set_suspension_max_force(float p_value) { - m_maxSuspensionForce=p_value; + m_maxSuspensionForce = p_value; } -float VehicleWheel::get_suspension_max_force() const{ +float VehicleWheel::get_suspension_max_force() const { return m_maxSuspensionForce; } -void VehicleWheel::set_damping_compression(float p_value){ +void VehicleWheel::set_damping_compression(float p_value) { - m_wheelsDampingCompression=p_value; + m_wheelsDampingCompression = p_value; } -float VehicleWheel::get_damping_compression() const{ +float VehicleWheel::get_damping_compression() const { return m_wheelsDampingCompression; } -void VehicleWheel::set_damping_relaxation(float p_value){ +void VehicleWheel::set_damping_relaxation(float p_value) { - m_wheelsDampingRelaxation=p_value; + m_wheelsDampingRelaxation = p_value; } -float VehicleWheel::get_damping_relaxation() const{ +float VehicleWheel::get_damping_relaxation() const { return m_wheelsDampingRelaxation; } void VehicleWheel::set_friction_slip(float p_value) { - m_frictionSlip=p_value; + m_frictionSlip = p_value; } -float VehicleWheel::get_friction_slip() const{ +float VehicleWheel::get_friction_slip() const { return m_frictionSlip; } - void VehicleWheel::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_radius", "length"), &VehicleWheel::set_radius); + ClassDB::bind_method(D_METHOD("get_radius"), &VehicleWheel::get_radius); - ClassDB::bind_method(D_METHOD("set_radius","length"),&VehicleWheel::set_radius); - ClassDB::bind_method(D_METHOD("get_radius"),&VehicleWheel::get_radius); - - ClassDB::bind_method(D_METHOD("set_suspension_rest_length","length"),&VehicleWheel::set_suspension_rest_length); - ClassDB::bind_method(D_METHOD("get_suspension_rest_length"),&VehicleWheel::get_suspension_rest_length); - - ClassDB::bind_method(D_METHOD("set_suspension_travel","length"),&VehicleWheel::set_suspension_travel); - ClassDB::bind_method(D_METHOD("get_suspension_travel"),&VehicleWheel::get_suspension_travel); - - ClassDB::bind_method(D_METHOD("set_suspension_stiffness","length"),&VehicleWheel::set_suspension_stiffness); - ClassDB::bind_method(D_METHOD("get_suspension_stiffness"),&VehicleWheel::get_suspension_stiffness); - - ClassDB::bind_method(D_METHOD("set_suspension_max_force","length"),&VehicleWheel::set_suspension_max_force); - ClassDB::bind_method(D_METHOD("get_suspension_max_force"),&VehicleWheel::get_suspension_max_force); + ClassDB::bind_method(D_METHOD("set_suspension_rest_length", "length"), &VehicleWheel::set_suspension_rest_length); + ClassDB::bind_method(D_METHOD("get_suspension_rest_length"), &VehicleWheel::get_suspension_rest_length); + ClassDB::bind_method(D_METHOD("set_suspension_travel", "length"), &VehicleWheel::set_suspension_travel); + ClassDB::bind_method(D_METHOD("get_suspension_travel"), &VehicleWheel::get_suspension_travel); - ClassDB::bind_method(D_METHOD("set_damping_compression","length"),&VehicleWheel::set_damping_compression); - ClassDB::bind_method(D_METHOD("get_damping_compression"),&VehicleWheel::get_damping_compression); + ClassDB::bind_method(D_METHOD("set_suspension_stiffness", "length"), &VehicleWheel::set_suspension_stiffness); + ClassDB::bind_method(D_METHOD("get_suspension_stiffness"), &VehicleWheel::get_suspension_stiffness); - ClassDB::bind_method(D_METHOD("set_damping_relaxation","length"),&VehicleWheel::set_damping_relaxation); - ClassDB::bind_method(D_METHOD("get_damping_relaxation"),&VehicleWheel::get_damping_relaxation); + ClassDB::bind_method(D_METHOD("set_suspension_max_force", "length"), &VehicleWheel::set_suspension_max_force); + ClassDB::bind_method(D_METHOD("get_suspension_max_force"), &VehicleWheel::get_suspension_max_force); - ClassDB::bind_method(D_METHOD("set_use_as_traction","enable"),&VehicleWheel::set_use_as_traction); - ClassDB::bind_method(D_METHOD("is_used_as_traction"),&VehicleWheel::is_used_as_traction); + ClassDB::bind_method(D_METHOD("set_damping_compression", "length"), &VehicleWheel::set_damping_compression); + ClassDB::bind_method(D_METHOD("get_damping_compression"), &VehicleWheel::get_damping_compression); - ClassDB::bind_method(D_METHOD("set_use_as_steering","enable"),&VehicleWheel::set_use_as_steering); - ClassDB::bind_method(D_METHOD("is_used_as_steering"),&VehicleWheel::is_used_as_steering); + ClassDB::bind_method(D_METHOD("set_damping_relaxation", "length"), &VehicleWheel::set_damping_relaxation); + ClassDB::bind_method(D_METHOD("get_damping_relaxation"), &VehicleWheel::get_damping_relaxation); - ClassDB::bind_method(D_METHOD("set_friction_slip","length"),&VehicleWheel::set_friction_slip); - ClassDB::bind_method(D_METHOD("get_friction_slip"),&VehicleWheel::get_friction_slip); + ClassDB::bind_method(D_METHOD("set_use_as_traction", "enable"), &VehicleWheel::set_use_as_traction); + ClassDB::bind_method(D_METHOD("is_used_as_traction"), &VehicleWheel::is_used_as_traction); + ClassDB::bind_method(D_METHOD("set_use_as_steering", "enable"), &VehicleWheel::set_use_as_steering); + ClassDB::bind_method(D_METHOD("is_used_as_steering"), &VehicleWheel::is_used_as_steering); + ClassDB::bind_method(D_METHOD("set_friction_slip", "length"), &VehicleWheel::set_friction_slip); + ClassDB::bind_method(D_METHOD("get_friction_slip"), &VehicleWheel::get_friction_slip); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_as_traction"),"set_use_as_traction","is_used_as_traction"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_as_steering"),"set_use_as_steering","is_used_as_steering"); - ADD_GROUP("Wheel","wheel_"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"wheel_radius"),"set_radius","get_radius"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"wheel_rest_length"),"set_suspension_rest_length","get_suspension_rest_length"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"wheel_friction_slip"),"set_friction_slip","get_friction_slip"); - ADD_GROUP("Suspension","suspension_"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"suspension_travel"),"set_suspension_travel","get_suspension_travel"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"suspension_stiffness"),"set_suspension_stiffness","get_suspension_stiffness"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"suspension_max_force"),"set_suspension_max_force","get_suspension_max_force"); - ADD_GROUP("Damping","damping_"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"damping_compression"),"set_damping_compression","get_damping_compression"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"damping_relaxation"),"set_damping_relaxation","get_damping_relaxation"); - + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_traction"), "set_use_as_traction", "is_used_as_traction"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_steering"), "set_use_as_steering", "is_used_as_steering"); + ADD_GROUP("Wheel", "wheel_"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_radius"), "set_radius", "get_radius"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_rest_length"), "set_suspension_rest_length", "get_suspension_rest_length"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_friction_slip"), "set_friction_slip", "get_friction_slip"); + ADD_GROUP("Suspension", "suspension_"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_travel"), "set_suspension_travel", "get_suspension_travel"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_stiffness"), "set_suspension_stiffness", "get_suspension_stiffness"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_max_force"), "set_suspension_max_force", "get_suspension_max_force"); + ADD_GROUP("Damping", "damping_"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping_compression"), "set_damping_compression", "get_damping_compression"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping_relaxation"), "set_damping_relaxation", "get_damping_relaxation"); } - void VehicleWheel::set_use_as_traction(bool p_enable) { - engine_traction=p_enable; + engine_traction = p_enable; } -bool VehicleWheel::is_used_as_traction() const{ +bool VehicleWheel::is_used_as_traction() const { return engine_traction; } +void VehicleWheel::set_use_as_steering(bool p_enabled) { -void VehicleWheel::set_use_as_steering(bool p_enabled){ - - steers=p_enabled; + steers = p_enabled; } -bool VehicleWheel::is_used_as_steering() const{ +bool VehicleWheel::is_used_as_steering() const { return steers; } - VehicleWheel::VehicleWheel() { - - steers=false; - engine_traction=false; + steers = false; + engine_traction = false; m_steering = real_t(0.); //m_engineForce = real_t(0.); @@ -318,7 +293,7 @@ VehicleWheel::VehicleWheel() { m_rollInfluence = real_t(0.1); m_suspensionRestLength = 0.15; - m_wheelRadius = 0.5;//0.28; + m_wheelRadius = 0.5; //0.28; m_suspensionStiffness = 5.88; m_wheelsDampingCompression = 0.83; m_wheelsDampingRelaxation = 0.88; @@ -327,15 +302,14 @@ VehicleWheel::VehicleWheel() { m_maxSuspensionTravelCm = 500; m_maxSuspensionForce = 6000; - m_suspensionRelativeVelocity=0; - m_clippedInvContactDotSuspension=1.0; - m_raycastInfo.m_isInContact=false; + m_suspensionRelativeVelocity = 0; + m_clippedInvContactDotSuspension = 1.0; + m_raycastInfo.m_isInContact = false; - body=NULL; + body = NULL; } - -void VehicleBody::_update_wheel_transform(VehicleWheel& wheel ,PhysicsDirectBodyState *s) { +void VehicleBody::_update_wheel_transform(VehicleWheel &wheel, PhysicsDirectBodyState *s) { wheel.m_raycastInfo.m_isInContact = false; @@ -346,31 +320,31 @@ void VehicleBody::_update_wheel_transform(VehicleWheel& wheel ,PhysicsDirectBody } */ - wheel.m_raycastInfo.m_hardPointWS = chassisTrans.xform( wheel.m_chassisConnectionPointCS ); + wheel.m_raycastInfo.m_hardPointWS = chassisTrans.xform(wheel.m_chassisConnectionPointCS); //wheel.m_raycastInfo.m_hardPointWS+=s->get_linear_velocity()*s->get_step(); - wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.get_basis().xform( wheel.m_wheelDirectionCS).normalized(); - wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.get_basis().xform( wheel.m_wheelAxleCS ).normalized(); + wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.get_basis().xform(wheel.m_wheelDirectionCS).normalized(); + wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.get_basis().xform(wheel.m_wheelAxleCS).normalized(); } -void VehicleBody::_update_wheel(int p_idx,PhysicsDirectBodyState *s) { +void VehicleBody::_update_wheel(int p_idx, PhysicsDirectBodyState *s) { - VehicleWheel& wheel = *wheels[p_idx]; - _update_wheel_transform(wheel,s); + VehicleWheel &wheel = *wheels[p_idx]; + _update_wheel_transform(wheel, s); Vector3 up = -wheel.m_raycastInfo.m_wheelDirectionWS; - const Vector3& right = wheel.m_raycastInfo.m_wheelAxleWS; + const Vector3 &right = wheel.m_raycastInfo.m_wheelAxleWS; Vector3 fwd = up.cross(right); fwd = fwd.normalized(); //up = right.cross(fwd); //up.normalize(); //rotate around steering over de wheelAxleWS - real_t steering = wheel.steers?m_steeringValue:0.0; + real_t steering = wheel.steers ? m_steeringValue : 0.0; //print_line(itos(p_idx)+": "+rtos(steering)); - Basis steeringMat(up,steering); + Basis steeringMat(up, steering); - Basis rotatingMat(right,-wheel.m_rotation); + Basis rotatingMat(right, -wheel.m_rotation); /* if (p_idx==1) @@ -378,82 +352,69 @@ void VehicleBody::_update_wheel(int p_idx,PhysicsDirectBodyState *s) { */ Basis basis2( - right[0],up[0],fwd[0], - right[1],up[1],fwd[1], - right[2],up[2],fwd[2] - ); + right[0], up[0], fwd[0], + right[1], up[1], fwd[1], + right[2], up[2], fwd[2]); wheel.m_worldTransform.set_basis(steeringMat * rotatingMat * basis2); //wheel.m_worldTransform.set_basis(basis2 * (steeringMat * rotatingMat)); wheel.m_worldTransform.set_origin( - wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength - ); - + wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength); } +real_t VehicleBody::_ray_cast(int p_idx, PhysicsDirectBodyState *s) { -real_t VehicleBody::_ray_cast(int p_idx,PhysicsDirectBodyState *s) { - - - VehicleWheel& wheel = *wheels[p_idx]; - - _update_wheel_transform(wheel,s); + VehicleWheel &wheel = *wheels[p_idx]; + _update_wheel_transform(wheel, s); real_t depth = -1; - real_t raylen = wheel.m_suspensionRestLength+wheel.m_wheelRadius; + real_t raylen = wheel.m_suspensionRestLength + wheel.m_wheelRadius; Vector3 rayvector = wheel.m_raycastInfo.m_wheelDirectionWS * (raylen); Vector3 source = wheel.m_raycastInfo.m_hardPointWS; wheel.m_raycastInfo.m_contactPointWS = source + rayvector; - const Vector3& target = wheel.m_raycastInfo.m_contactPointWS; - source-=wheel.m_wheelRadius * wheel.m_raycastInfo.m_wheelDirectionWS; + const Vector3 &target = wheel.m_raycastInfo.m_contactPointWS; + source -= wheel.m_wheelRadius * wheel.m_raycastInfo.m_wheelDirectionWS; real_t param = real_t(0.); - PhysicsDirectSpaceState::RayResult rr; + PhysicsDirectSpaceState *ss = s->get_space_state(); - PhysicsDirectSpaceState *ss=s->get_space_state(); - - bool col = ss->intersect_ray(source,target,rr,exclude); - + bool col = ss->intersect_ray(source, target, rr, exclude); wheel.m_raycastInfo.m_groundObject = 0; - if (col) - { + if (col) { //print_line("WHEEL "+itos(p_idx)+" FROM "+source+" TO: "+target); //print_line("WHEEL "+itos(p_idx)+" COLLIDE? "+itos(col)); - param = source.distance_to(rr.position)/source.distance_to(target); + param = source.distance_to(rr.position) / source.distance_to(target); depth = raylen * param; - wheel.m_raycastInfo.m_contactNormalWS = rr.normal; + wheel.m_raycastInfo.m_contactNormalWS = rr.normal; wheel.m_raycastInfo.m_isInContact = true; if (rr.collider) - wheel.m_raycastInfo.m_groundObject=rr.collider->cast_to(); - + wheel.m_raycastInfo.m_groundObject = rr.collider->cast_to(); - real_t hitDistance = param*raylen; + real_t hitDistance = param * raylen; wheel.m_raycastInfo.m_suspensionLength = hitDistance - wheel.m_wheelRadius; //clamp on max suspension travel - real_t minSuspensionLength = wheel.m_suspensionRestLength - wheel.m_maxSuspensionTravelCm*real_t(0.01); - real_t maxSuspensionLength = wheel.m_suspensionRestLength+ wheel.m_maxSuspensionTravelCm*real_t(0.01); - if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength) - { + real_t minSuspensionLength = wheel.m_suspensionRestLength - wheel.m_maxSuspensionTravelCm * real_t(0.01); + real_t maxSuspensionLength = wheel.m_suspensionRestLength + wheel.m_maxSuspensionTravelCm * real_t(0.01); + if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength) { wheel.m_raycastInfo.m_suspensionLength = minSuspensionLength; } - if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength) - { + if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength) { wheel.m_raycastInfo.m_suspensionLength = maxSuspensionLength; } wheel.m_raycastInfo.m_contactPointWS = rr.position; - real_t denominator= wheel.m_raycastInfo.m_contactNormalWS.dot( wheel.m_raycastInfo.m_wheelDirectionWS ); + real_t denominator = wheel.m_raycastInfo.m_contactNormalWS.dot(wheel.m_raycastInfo.m_wheelDirectionWS); Vector3 chassis_velocity_at_contactPoint; //Vector3 relpos = wheel.m_raycastInfo.m_contactPointWS-getRigidBody()->getCenterOfMassPosition(); @@ -461,72 +422,58 @@ real_t VehicleBody::_ray_cast(int p_idx,PhysicsDirectBodyState *s) { //chassis_velocity_at_contactPoint = getRigidBody()->getVelocityInLocalPoint(relpos); chassis_velocity_at_contactPoint = s->get_linear_velocity() + - (s->get_angular_velocity()).cross(wheel.m_raycastInfo.m_contactPointWS-s->get_transform().origin);// * mPos); - + (s->get_angular_velocity()).cross(wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin); // * mPos); - real_t projVel = wheel.m_raycastInfo.m_contactNormalWS.dot( chassis_velocity_at_contactPoint ); + real_t projVel = wheel.m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint); - if ( denominator >= real_t(-0.1)) - { + if (denominator >= real_t(-0.1)) { wheel.m_suspensionRelativeVelocity = real_t(0.0); wheel.m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1); - } - else - { + } else { real_t inv = real_t(-1.) / denominator; wheel.m_suspensionRelativeVelocity = projVel * inv; wheel.m_clippedInvContactDotSuspension = inv; } - } else - { + } else { wheel.m_raycastInfo.m_isInContact = false; //put wheel info as in rest position wheel.m_raycastInfo.m_suspensionLength = wheel.m_suspensionRestLength; wheel.m_suspensionRelativeVelocity = real_t(0.0); - wheel.m_raycastInfo.m_contactNormalWS = - wheel.m_raycastInfo.m_wheelDirectionWS; + wheel.m_raycastInfo.m_contactNormalWS = -wheel.m_raycastInfo.m_wheelDirectionWS; wheel.m_clippedInvContactDotSuspension = real_t(1.0); } return depth; } - -void VehicleBody::_update_suspension(PhysicsDirectBodyState *s) -{ +void VehicleBody::_update_suspension(PhysicsDirectBodyState *s) { real_t chassisMass = mass; - for (int w_it=0; w_it real_t(1.1)) - { + if (normalLenSqr > real_t(1.1)) { impulse = real_t(0.); return; } @@ -569,16 +509,16 @@ void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vec rel_pos2 = pos2 - body2->get_global_transform().origin; //this jacobian entry could be re-used for all iterations - Vector3 vel1 = s->get_linear_velocity() + (s->get_angular_velocity()).cross(rel_pos1);// * mPos); + Vector3 vel1 = s->get_linear_velocity() + (s->get_angular_velocity()).cross(rel_pos1); // * mPos); Vector3 vel2; if (body2) - vel2=body2->get_linear_velocity() + body2->get_angular_velocity().cross(rel_pos2); + vel2 = body2->get_linear_velocity() + body2->get_angular_velocity().cross(rel_pos2); Vector3 vel = vel1 - vel2; Basis b2trans; - float b2invmass=0; + float b2invmass = 0; Vector3 b2lv; Vector3 b2av; Vector3 b2invinertia; //todo @@ -590,24 +530,21 @@ void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vec b2av = body2->get_angular_velocity(); } - - btVehicleJacobianEntry jac(s->get_transform().basis.transposed(), - b2trans, - rel_pos1, - rel_pos2, - normal, - s->get_inverse_inertia_tensor().get_main_diagonal(), - 1.0/mass, - b2invinertia, - b2invmass); + b2trans, + rel_pos1, + rel_pos2, + normal, + s->get_inverse_inertia_tensor().get_main_diagonal(), + 1.0 / mass, + b2invinertia, + b2invmass); real_t rel_vel = jac.getRelativeVelocity( - s->get_linear_velocity(), - s->get_transform().basis.transposed().xform(s->get_angular_velocity()), - b2lv, - b2trans.xform(b2av)); - + s->get_linear_velocity(), + s->get_transform().basis.transposed().xform(s->get_angular_velocity()), + b2lv, + b2trans.xform(b2av)); rel_vel = normal.dot(vel); @@ -615,32 +552,28 @@ void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vec real_t contactDamping = real_t(0.4); #define ONLY_USE_LINEAR_MASS #ifdef ONLY_USE_LINEAR_MASS - real_t massTerm = real_t(1.) / ((1.0/mass) + b2invmass); - impulse = - contactDamping * rel_vel * massTerm; + real_t massTerm = real_t(1.) / ((1.0 / mass) + b2invmass); + impulse = -contactDamping * rel_vel * massTerm; #else real_t velocityImpulse = -contactDamping * rel_vel * jacDiagABInv; impulse = velocityImpulse; #endif - } - - -VehicleBody::btVehicleWheelContactPoint::btVehicleWheelContactPoint(PhysicsDirectBodyState *s,PhysicsBody* body1,const Vector3& frictionPosWorld,const Vector3& frictionDirectionWorld, real_t maxImpulse) - :m_s(s), - m_body1(body1), - m_frictionPositionWorld(frictionPosWorld), - m_frictionDirectionWorld(frictionDirectionWorld), - m_maxImpulse(maxImpulse) -{ - float denom0=0; - float denom1=0; +VehicleBody::btVehicleWheelContactPoint::btVehicleWheelContactPoint(PhysicsDirectBodyState *s, PhysicsBody *body1, const Vector3 &frictionPosWorld, const Vector3 &frictionDirectionWorld, real_t maxImpulse) + : m_s(s), + m_body1(body1), + m_frictionPositionWorld(frictionPosWorld), + m_frictionDirectionWorld(frictionDirectionWorld), + m_maxImpulse(maxImpulse) { + float denom0 = 0; + float denom1 = 0; { Vector3 r0 = frictionPosWorld - s->get_transform().origin; Vector3 c0 = (r0).cross(frictionDirectionWorld); Vector3 vec = s->get_inverse_inertia_tensor().xform_inv(c0).cross(r0); - denom0= s->get_inverse_mass() + frictionDirectionWorld.dot(vec); + denom0 = s->get_inverse_mass() + frictionDirectionWorld.dot(vec); } /* TODO: Why is this code unused? @@ -654,30 +587,28 @@ VehicleBody::btVehicleWheelContactPoint::btVehicleWheelContactPoint(PhysicsDirec } */ - real_t relaxation = 1.f; - m_jacDiagABInv = relaxation/(denom0+denom1); + real_t relaxation = 1.f; + m_jacDiagABInv = relaxation / (denom0 + denom1); } +real_t VehicleBody::_calc_rolling_friction(btVehicleWheelContactPoint &contactPoint) { -real_t VehicleBody::_calc_rolling_friction(btVehicleWheelContactPoint& contactPoint) { - - real_t j1=0.f; + real_t j1 = 0.f; - const Vector3& contactPosWorld = contactPoint.m_frictionPositionWorld; + const Vector3 &contactPosWorld = contactPoint.m_frictionPositionWorld; Vector3 rel_pos1 = contactPosWorld - contactPoint.m_s->get_transform().origin; Vector3 rel_pos2; if (contactPoint.m_body1) rel_pos2 = contactPosWorld - contactPoint.m_body1->get_global_transform().origin; - real_t maxImpulse = contactPoint.m_maxImpulse; + real_t maxImpulse = contactPoint.m_maxImpulse; - Vector3 vel1 = contactPoint.m_s->get_linear_velocity() + (contactPoint.m_s->get_angular_velocity()).cross(rel_pos1);// * mPos); + Vector3 vel1 = contactPoint.m_s->get_linear_velocity() + (contactPoint.m_s->get_angular_velocity()).cross(rel_pos1); // * mPos); Vector3 vel2; if (contactPoint.m_body1) { - vel2=contactPoint.m_body1->get_linear_velocity() + contactPoint.m_body1->get_angular_velocity().cross(rel_pos2); - + vel2 = contactPoint.m_body1->get_linear_velocity() + contactPoint.m_body1->get_angular_velocity().cross(rel_pos2); } Vector3 vel = vel1 - vel2; @@ -687,10 +618,9 @@ real_t VehicleBody::_calc_rolling_friction(btVehicleWheelContactPoint& contactPo // calculate j that moves us to zero relative velocity j1 = -vrel * contactPoint.m_jacDiagABInv; - return CLAMP(j1,-maxImpulse,maxImpulse); + return CLAMP(j1, -maxImpulse, maxImpulse); } - static const real_t sideFrictionStiffness2 = real_t(1.0); void VehicleBody::_update_friction(PhysicsDirectBodyState *s) { @@ -706,37 +636,31 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) { int numWheelsOnGround = 0; - //collapse all those loops into one! - for (int i=0;iget_step(); - } else - { + if (wheelInfo.m_raycastInfo.m_isInContact) { + if (engine_force != 0.f) { + rollingFriction = -engine_force * s->get_step(); + } else { real_t defaultRollingFrictionImpulse = 0.f; - float cbrake = MAX(wheelInfo.m_brake,brake); + float cbrake = MAX(wheelInfo.m_brake, brake); real_t maxImpulse = cbrake ? cbrake : defaultRollingFrictionImpulse; - btVehicleWheelContactPoint contactPt(s,wheelInfo.m_raycastInfo.m_groundObject,wheelInfo.m_raycastInfo.m_contactPointWS,m_forwardWS[wheel],maxImpulse); + btVehicleWheelContactPoint contactPt(s, wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS, m_forwardWS[wheel], maxImpulse); rollingFriction = _calc_rolling_friction(contactPt); } } //switch between active rolling (throttle), braking and non-active rolling friction (no throttle/break) - - - m_forwardImpulse[wheel] = real_t(0.); - wheelInfo.m_skidInfo= real_t(1.); + wheelInfo.m_skidInfo = real_t(1.); - if (wheelInfo.m_raycastInfo.m_isInContact) - { - wheelInfo.m_skidInfo= real_t(1.); + if (wheelInfo.m_raycastInfo.m_isInContact) { + wheelInfo.m_skidInfo = real_t(1.); real_t maximp = wheelInfo.m_wheelsSuspensionForce * s->get_step() * wheelInfo.m_frictionSlip; real_t maximpSide = maximp; real_t maximpSquared = maximp * maximpSide; + m_forwardImpulse[wheel] = rollingFriction; //wheelInfo.m_engineForce* timeStep; - m_forwardImpulse[wheel] = rollingFriction;//wheelInfo.m_engineForce* timeStep; + real_t x = (m_forwardImpulse[wheel]) * fwdFactor; + real_t y = (m_sideImpulse[wheel]) * sideFactor; - real_t x = (m_forwardImpulse[wheel] ) * fwdFactor; - real_t y = (m_sideImpulse[wheel] ) * sideFactor; + real_t impulseSquared = (x * x + y * y); - real_t impulseSquared = (x*x + y*y); - - if (impulseSquared > maximpSquared) - { + if (impulseSquared > maximpSquared) { sliding = true; real_t factor = maximp / Math::sqrt(impulseSquared); @@ -819,22 +729,14 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) { wheelInfo.m_skidInfo *= factor; } } - } } - - - - if (sliding) - { - for (int wheel = 0;wheel < wheels.size(); wheel++) - { - if (m_sideImpulse[wheel] != real_t(0.)) - { - if (wheels[wheel]->m_skidInfo< real_t(1.)) - { - m_forwardImpulse[wheel] *= wheels[wheel]->m_skidInfo; + if (sliding) { + for (int wheel = 0; wheel < wheels.size(); wheel++) { + if (m_sideImpulse[wheel] != real_t(0.)) { + if (wheels[wheel]->m_skidInfo < real_t(1.)) { + m_forwardImpulse[wheel] *= wheels[wheel]->m_skidInfo; m_sideImpulse[wheel] *= wheels[wheel]->m_skidInfo; } } @@ -843,36 +745,32 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) { // apply the impulses { - for (int wheel = 0;wheelget_transform().origin; + s->get_transform().origin; - if (m_forwardImpulse[wheel] != real_t(0.)) - { - s->apply_impulse(rel_pos,m_forwardWS[wheel]*(m_forwardImpulse[wheel])); + if (m_forwardImpulse[wheel] != real_t(0.)) { + s->apply_impulse(rel_pos, m_forwardWS[wheel] * (m_forwardImpulse[wheel])); } - if (m_sideImpulse[wheel] != real_t(0.)) - { - PhysicsBody* groundObject = wheelInfo.m_raycastInfo.m_groundObject; + if (m_sideImpulse[wheel] != real_t(0.)) { + PhysicsBody *groundObject = wheelInfo.m_raycastInfo.m_groundObject; Vector3 rel_pos2; if (groundObject) { - rel_pos2=wheelInfo.m_raycastInfo.m_contactPointWS - groundObject->get_global_transform().origin; + rel_pos2 = wheelInfo.m_raycastInfo.m_contactPointWS - groundObject->get_global_transform().origin; } - Vector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel]; #if defined ROLLING_INFLUENCE_FIX // fix. It only worked if car's up was along Y - VT. - Vector3 vChassisWorldUp = s->get_transform().basis.transposed()[1];//getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis); - rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f-wheelInfo.m_rollInfluence)); + Vector3 vChassisWorldUp = s->get_transform().basis.transposed()[1]; //getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis); + rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f - wheelInfo.m_rollInfluence)); #else rel_pos[1] *= wheelInfo.m_rollInfluence; //? #endif - s->apply_impulse(rel_pos,sideImp); + s->apply_impulse(rel_pos, sideImp); //apply friction impulse on the ground //todo @@ -880,74 +778,62 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) { } } } - - } - void VehicleBody::_direct_state_changed(Object *p_state) { - PhysicsDirectBodyState *s = p_state->cast_to(); set_ignore_transform_notification(true); set_global_transform(s->get_transform()); set_ignore_transform_notification(false); - float step = s->get_step(); - for(int i=0;iset_transform(s->get_transform().inverse() * wheels[i]->m_worldTransform); } _update_suspension(s); - for(int i=0;i wheel.m_maxSuspensionForce) - { + if (suspensionForce > wheel.m_maxSuspensionForce) { suspensionForce = wheel.m_maxSuspensionForce; } Vector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step; Vector3 relpos = wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin; - s->apply_impulse(relpos,impulse); + s->apply_impulse(relpos, impulse); //getRigidBody()->applyImpulse(impulse, relpos); - } - _update_friction(s); - - for (int i=0;iget_transform().origin; - Vector3 vel = s->get_linear_velocity() + (s->get_angular_velocity()).cross(relpos);// * mPos); + Vector3 vel = s->get_linear_velocity() + (s->get_angular_velocity()).cross(relpos); // * mPos); - if (wheel.m_raycastInfo.m_isInContact) - { - const Transform& chassisWorldTransform = s->get_transform(); + if (wheel.m_raycastInfo.m_isInContact) { + const Transform &chassisWorldTransform = s->get_transform(); - Vector3 fwd ( - chassisWorldTransform.basis[0][Vector3::AXIS_Z], - chassisWorldTransform.basis[1][Vector3::AXIS_Z], - chassisWorldTransform.basis[2][Vector3::AXIS_Z]); + Vector3 fwd( + chassisWorldTransform.basis[0][Vector3::AXIS_Z], + chassisWorldTransform.basis[1][Vector3::AXIS_Z], + chassisWorldTransform.basis[2][Vector3::AXIS_Z]); real_t proj = fwd.dot(wheel.m_raycastInfo.m_contactNormalWS); fwd -= wheel.m_raycastInfo.m_contactNormalWS * proj; @@ -957,126 +843,115 @@ void VehicleBody::_direct_state_changed(Object *p_state) { wheel.m_deltaRotation = (proj2 * step) / (wheel.m_wheelRadius); wheel.m_rotation += wheel.m_deltaRotation; - } else - { + } else { wheel.m_rotation += wheel.m_deltaRotation; } - wheel.m_deltaRotation *= real_t(0.99);//damping of rotation when not in contact - + wheel.m_deltaRotation *= real_t(0.99); //damping of rotation when not in contact } linear_velocity = s->get_linear_velocity(); } void VehicleBody::set_mass(real_t p_mass) { - mass=p_mass; - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_MASS,mass); + mass = p_mass; + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_MASS, mass); } -real_t VehicleBody::get_mass() const{ +real_t VehicleBody::get_mass() const { return mass; } - void VehicleBody::set_friction(real_t p_friction) { - friction=p_friction; - PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_FRICTION,friction); + friction = p_friction; + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, friction); } -real_t VehicleBody::get_friction() const{ +real_t VehicleBody::get_friction() const { return friction; } void VehicleBody::set_engine_force(float p_force) { - engine_force=p_force; + engine_force = p_force; } -float VehicleBody::get_engine_force() const{ +float VehicleBody::get_engine_force() const { return engine_force; } -void VehicleBody::set_brake(float p_brake){ +void VehicleBody::set_brake(float p_brake) { - brake=p_brake; + brake = p_brake; } -float VehicleBody::get_brake() const{ +float VehicleBody::get_brake() const { return brake; } -void VehicleBody::set_steering(float p_steering){ +void VehicleBody::set_steering(float p_steering) { - m_steeringValue=p_steering; + m_steeringValue = p_steering; } -float VehicleBody::get_steering() const{ +float VehicleBody::get_steering() const { return m_steeringValue; } -Vector3 VehicleBody::get_linear_velocity() const -{ +Vector3 VehicleBody::get_linear_velocity() const { return linear_velocity; } -void VehicleBody::_bind_methods(){ - - ClassDB::bind_method(D_METHOD("set_mass","mass"),&VehicleBody::set_mass); - ClassDB::bind_method(D_METHOD("get_mass"),&VehicleBody::get_mass); - - ClassDB::bind_method(D_METHOD("set_friction","friction"),&VehicleBody::set_friction); - ClassDB::bind_method(D_METHOD("get_friction"),&VehicleBody::get_friction); +void VehicleBody::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_engine_force","engine_force"),&VehicleBody::set_engine_force); - ClassDB::bind_method(D_METHOD("get_engine_force"),&VehicleBody::get_engine_force); + ClassDB::bind_method(D_METHOD("set_mass", "mass"), &VehicleBody::set_mass); + ClassDB::bind_method(D_METHOD("get_mass"), &VehicleBody::get_mass); - ClassDB::bind_method(D_METHOD("set_brake","brake"),&VehicleBody::set_brake); - ClassDB::bind_method(D_METHOD("get_brake"),&VehicleBody::get_brake); + ClassDB::bind_method(D_METHOD("set_friction", "friction"), &VehicleBody::set_friction); + ClassDB::bind_method(D_METHOD("get_friction"), &VehicleBody::get_friction); - ClassDB::bind_method(D_METHOD("set_steering","steering"),&VehicleBody::set_steering); - ClassDB::bind_method(D_METHOD("get_steering"),&VehicleBody::get_steering); + ClassDB::bind_method(D_METHOD("set_engine_force", "engine_force"), &VehicleBody::set_engine_force); + ClassDB::bind_method(D_METHOD("get_engine_force"), &VehicleBody::get_engine_force); - ClassDB::bind_method(D_METHOD("get_linear_velocity"),&VehicleBody::get_linear_velocity); + ClassDB::bind_method(D_METHOD("set_brake", "brake"), &VehicleBody::set_brake); + ClassDB::bind_method(D_METHOD("get_brake"), &VehicleBody::get_brake); - ClassDB::bind_method(D_METHOD("_direct_state_changed"),&VehicleBody::_direct_state_changed); + ClassDB::bind_method(D_METHOD("set_steering", "steering"), &VehicleBody::set_steering); + ClassDB::bind_method(D_METHOD("get_steering"), &VehicleBody::get_steering); - ADD_GROUP("Motion",""); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"engine_force",PROPERTY_HINT_RANGE,"0.00,1024.0,0.01"),"set_engine_force","get_engine_force"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"brake",PROPERTY_HINT_RANGE,"0.0,1.0,0.01"),"set_brake","get_brake"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"steering",PROPERTY_HINT_RANGE,"-180,180.0,0.01"),"set_steering","get_steering"); - ADD_GROUP("Mass",""); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"mass",PROPERTY_HINT_RANGE,"0.01,65536,0.01"),"set_mass","get_mass"); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0.01,1,0.01"),"set_friction","get_friction"); + ClassDB::bind_method(D_METHOD("get_linear_velocity"), &VehicleBody::get_linear_velocity); + ClassDB::bind_method(D_METHOD("_direct_state_changed"), &VehicleBody::_direct_state_changed); + ADD_GROUP("Motion", ""); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "engine_force", PROPERTY_HINT_RANGE, "0.00,1024.0,0.01"), "set_engine_force", "get_engine_force"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "brake", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_brake", "get_brake"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "steering", PROPERTY_HINT_RANGE, "-180,180.0,0.01"), "set_steering", "get_steering"); + ADD_GROUP("Mass", ""); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "mass", PROPERTY_HINT_RANGE, "0.01,65536,0.01"), "set_mass", "get_mass"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0.01,1,0.01"), "set_friction", "get_friction"); } +VehicleBody::VehicleBody() + : PhysicsBody(PhysicsServer::BODY_MODE_RIGID) { - -VehicleBody::VehicleBody() : PhysicsBody(PhysicsServer::BODY_MODE_RIGID) { - - - m_pitchControl=0; + m_pitchControl = 0; m_currentVehicleSpeedKmHour = real_t(0.); m_steeringValue = real_t(0.); - engine_force=0; - brake=0; + engine_force = 0; + brake = 0; + friction = 1; - - friction=1; - - ccd=false; + ccd = false; exclude.insert(get_rid()); - PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(),this,"_direct_state_changed"); + PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed"); set_mass(40); } - diff --git a/scene/3d/vehicle_body.h b/scene/3d/vehicle_body.h index 273e63d74..55b521cfa 100644 --- a/scene/3d/vehicle_body.h +++ b/scene/3d/vehicle_body.h @@ -35,20 +35,18 @@ class VehicleBody; class VehicleWheel : public Spatial { - GDCLASS(VehicleWheel,Spatial); - -friend class VehicleBody; + GDCLASS(VehicleWheel, Spatial); + friend class VehicleBody; Transform m_worldTransform; Transform local_xform; bool engine_traction; bool steers; - - Vector3 m_chassisConnectionPointCS; //const - Vector3 m_wheelDirectionCS;//const - Vector3 m_wheelAxleCS; // const or modified by steering + Vector3 m_chassisConnectionPointCS; //const + Vector3 m_wheelDirectionCS; //const + Vector3 m_wheelAxleCS; // const or modified by steering real_t m_suspensionRestLength; real_t m_maxSuspensionTravelCm; @@ -65,30 +63,29 @@ friend class VehicleBody; //btVector3 m_wheelAxleCS; // const or modified by steering ? - real_t m_steering; - real_t m_rotation; - real_t m_deltaRotation; - real_t m_rollInfluence; + real_t m_steering; + real_t m_rotation; + real_t m_deltaRotation; + real_t m_rollInfluence; //real_t m_engineForce; - real_t m_brake; + real_t m_brake; - real_t m_clippedInvContactDotSuspension; - real_t m_suspensionRelativeVelocity; + real_t m_clippedInvContactDotSuspension; + real_t m_suspensionRelativeVelocity; //calculated by suspension - real_t m_wheelsSuspensionForce; - real_t m_skidInfo; - + real_t m_wheelsSuspensionForce; + real_t m_skidInfo; struct RaycastInfo { //set by raycaster - Vector3 m_contactNormalWS;//contactnormal - Vector3 m_contactPointWS;//raycast hitpoint - real_t m_suspensionLength; - Vector3 m_hardPointWS;//raycast starting point - Vector3 m_wheelDirectionWS; //direction in worldspace - Vector3 m_wheelAxleWS; // axle in worldspace + Vector3 m_contactNormalWS; //contactnormal + Vector3 m_contactPointWS; //raycast hitpoint + real_t m_suspensionLength; + Vector3 m_hardPointWS; //raycast starting point + Vector3 m_wheelDirectionWS; //direction in worldspace + Vector3 m_wheelAxleWS; // axle in worldspace bool m_isInContact; - PhysicsBody* m_groundObject; //could be general void* ptr + PhysicsBody *m_groundObject; //could be general void* ptr } m_raycastInfo; void _update(PhysicsDirectBodyState *s); @@ -98,7 +95,6 @@ protected: static void _bind_methods(); public: - void set_radius(float p_radius); float get_radius() const; @@ -130,13 +126,11 @@ public: bool is_used_as_steering() const; VehicleWheel(); - }; - class VehicleBody : public PhysicsBody { - GDCLASS(VehicleBody,PhysicsBody); + GDCLASS(VehicleBody, PhysicsBody); real_t mass; real_t friction; @@ -145,52 +139,48 @@ class VehicleBody : public PhysicsBody { float brake; Vector3 linear_velocity; - Vector3 angular_velocity; + Vector3 angular_velocity; bool ccd; - real_t m_pitchControl; - real_t m_steeringValue; - real_t m_currentVehicleSpeedKmHour; + real_t m_pitchControl; + real_t m_steeringValue; + real_t m_currentVehicleSpeedKmHour; Set exclude; - Vector m_forwardWS; - Vector m_axle; - Vector m_forwardImpulse; - Vector m_sideImpulse; + Vector m_forwardWS; + Vector m_axle; + Vector m_forwardImpulse; + Vector m_sideImpulse; struct btVehicleWheelContactPoint { PhysicsDirectBodyState *m_s; - PhysicsBody* m_body1; - Vector3 m_frictionPositionWorld; - Vector3 m_frictionDirectionWorld; - real_t m_jacDiagABInv; - real_t m_maxImpulse; + PhysicsBody *m_body1; + Vector3 m_frictionPositionWorld; + Vector3 m_frictionDirectionWorld; + real_t m_jacDiagABInv; + real_t m_maxImpulse; - - btVehicleWheelContactPoint(PhysicsDirectBodyState *s,PhysicsBody* body1,const Vector3& frictionPosWorld,const Vector3& frictionDirectionWorld, real_t maxImpulse); + btVehicleWheelContactPoint(PhysicsDirectBodyState *s, PhysicsBody *body1, const Vector3 &frictionPosWorld, const Vector3 &frictionDirectionWorld, real_t maxImpulse); }; - void _resolve_single_bilateral(PhysicsDirectBodyState *s, const Vector3& pos1, PhysicsBody* body2, const Vector3& pos2, const Vector3& normal, real_t& impulse); - real_t _calc_rolling_friction(btVehicleWheelContactPoint& contactPoint); + void _resolve_single_bilateral(PhysicsDirectBodyState *s, const Vector3 &pos1, PhysicsBody *body2, const Vector3 &pos2, const Vector3 &normal, real_t &impulse); + real_t _calc_rolling_friction(btVehicleWheelContactPoint &contactPoint); void _update_friction(PhysicsDirectBodyState *s); void _update_suspension(PhysicsDirectBodyState *s); - real_t _ray_cast(int p_idx,PhysicsDirectBodyState *s); - void _update_wheel_transform(VehicleWheel& wheel ,PhysicsDirectBodyState *s); - void _update_wheel(int p_idx,PhysicsDirectBodyState *s); - - + real_t _ray_cast(int p_idx, PhysicsDirectBodyState *s); + void _update_wheel_transform(VehicleWheel &wheel, PhysicsDirectBodyState *s); + void _update_wheel(int p_idx, PhysicsDirectBodyState *s); -friend class VehicleWheel; - Vector wheels; + friend class VehicleWheel; + Vector wheels; static void _bind_methods(); void _direct_state_changed(Object *p_state); -public: - +public: void set_mass(real_t p_mass); real_t get_mass() const; diff --git a/scene/3d/visibility_notifier.cpp b/scene/3d/visibility_notifier.cpp index 0633846b5..909ac002b 100644 --- a/scene/3d/visibility_notifier.cpp +++ b/scene/3d/visibility_notifier.cpp @@ -28,71 +28,64 @@ /*************************************************************************/ #include "visibility_notifier.h" -#include "scene/scene_string_names.h" #include "scene/3d/physics_body.h" #include "scene/animation/animation_player.h" #include "scene/scene_string_names.h" +#include "scene/scene_string_names.h" -void VisibilityNotifier::_enter_camera(Camera* p_camera) { +void VisibilityNotifier::_enter_camera(Camera *p_camera) { ERR_FAIL_COND(cameras.has(p_camera)); cameras.insert(p_camera); - if (cameras.size()==1) { + if (cameras.size() == 1) { emit_signal(SceneStringNames::get_singleton()->screen_entered); _screen_enter(); } - emit_signal(SceneStringNames::get_singleton()->camera_entered,p_camera); - + emit_signal(SceneStringNames::get_singleton()->camera_entered, p_camera); } -void VisibilityNotifier::_exit_camera(Camera* p_camera){ +void VisibilityNotifier::_exit_camera(Camera *p_camera) { ERR_FAIL_COND(!cameras.has(p_camera)); cameras.erase(p_camera); - emit_signal(SceneStringNames::get_singleton()->camera_exited,p_camera); - if (cameras.size()==0) { + emit_signal(SceneStringNames::get_singleton()->camera_exited, p_camera); + if (cameras.size() == 0) { emit_signal(SceneStringNames::get_singleton()->screen_exited); _screen_exit(); - } } +void VisibilityNotifier::set_aabb(const Rect3 &p_aabb) { -void VisibilityNotifier::set_aabb(const Rect3& p_aabb){ - - if (aabb==p_aabb) + if (aabb == p_aabb) return; - aabb=p_aabb; + aabb = p_aabb; if (is_inside_world()) { - get_world()->_update_notifier(this,get_global_transform().xform(aabb)); + get_world()->_update_notifier(this, get_global_transform().xform(aabb)); } _change_notify("aabb"); update_gizmo(); } -Rect3 VisibilityNotifier::get_aabb() const{ +Rect3 VisibilityNotifier::get_aabb() const { return aabb; } - void VisibilityNotifier::_notification(int p_what) { - - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_WORLD: { - - get_world()->_register_notifier(this,get_global_transform().xform(aabb)); + get_world()->_register_notifier(this, get_global_transform().xform(aabb)); } break; case NOTIFICATION_TRANSFORM_CHANGED: { - - get_world()->_update_notifier(this,get_global_transform().xform(aabb)); + get_world()->_update_notifier(this, get_global_transform().xform(aabb)); } break; case NOTIFICATION_EXIT_WORLD: { @@ -101,76 +94,65 @@ void VisibilityNotifier::_notification(int p_what) { } } - bool VisibilityNotifier::is_on_screen() const { - return cameras.size()!=0; + return cameras.size() != 0; } -void VisibilityNotifier::_bind_methods(){ +void VisibilityNotifier::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_aabb","rect"),&VisibilityNotifier::set_aabb); - ClassDB::bind_method(D_METHOD("get_aabb"),&VisibilityNotifier::get_aabb); - ClassDB::bind_method(D_METHOD("is_on_screen"),&VisibilityNotifier::is_on_screen); + ClassDB::bind_method(D_METHOD("set_aabb", "rect"), &VisibilityNotifier::set_aabb); + ClassDB::bind_method(D_METHOD("get_aabb"), &VisibilityNotifier::get_aabb); + ClassDB::bind_method(D_METHOD("is_on_screen"), &VisibilityNotifier::is_on_screen); - ADD_PROPERTY( PropertyInfo(Variant::RECT3,"aabb"),"set_aabb","get_aabb"); + ADD_PROPERTY(PropertyInfo(Variant::RECT3, "aabb"), "set_aabb", "get_aabb"); - ADD_SIGNAL( MethodInfo("camera_entered",PropertyInfo(Variant::OBJECT,"camera",PROPERTY_HINT_RESOURCE_TYPE,"Camera")) ); - ADD_SIGNAL( MethodInfo("camera_exited",PropertyInfo(Variant::OBJECT,"camera",PROPERTY_HINT_RESOURCE_TYPE,"Camera")) ); - ADD_SIGNAL( MethodInfo("screen_entered")); - ADD_SIGNAL( MethodInfo("screen_exited")); + ADD_SIGNAL(MethodInfo("camera_entered", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera"))); + ADD_SIGNAL(MethodInfo("camera_exited", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera"))); + ADD_SIGNAL(MethodInfo("screen_entered")); + ADD_SIGNAL(MethodInfo("screen_exited")); } - VisibilityNotifier::VisibilityNotifier() { - aabb=Rect3(Vector3(-1,-1,-1),Vector3(2,2,2)); + aabb = Rect3(Vector3(-1, -1, -1), Vector3(2, 2, 2)); set_notify_transform(true); - } - - - - ////////////////////////////////////// - void VisibilityEnabler::_screen_enter() { + for (Map::Element *E = nodes.front(); E; E = E->next()) { - for(Map::Element *E=nodes.front();E;E=E->next()) { - - _change_node_state(E->key(),true); + _change_node_state(E->key(), true); } - visible=true; + visible = true; } void VisibilityEnabler::_screen_exit() { - for(Map::Element *E=nodes.front();E;E=E->next()) { + for (Map::Element *E = nodes.front(); E; E = E->next()) { - _change_node_state(E->key(),false); + _change_node_state(E->key(), false); } - visible=false; + visible = false; } -void VisibilityEnabler::_find_nodes(Node* p_node) { - +void VisibilityEnabler::_find_nodes(Node *p_node) { - bool add=false; + bool add = false; Variant meta; if (enabler[ENABLER_FREEZE_BODIES]) { RigidBody *rb = p_node->cast_to(); - if (rb && ((rb->get_mode()==RigidBody::MODE_CHARACTER || (rb->get_mode()==RigidBody::MODE_RIGID && !rb->is_able_to_sleep())))) { + if (rb && ((rb->get_mode() == RigidBody::MODE_CHARACTER || (rb->get_mode() == RigidBody::MODE_RIGID && !rb->is_able_to_sleep())))) { - - add=true; - meta=rb->get_mode(); + add = true; + meta = rb->get_mode(); } } @@ -178,63 +160,58 @@ void VisibilityEnabler::_find_nodes(Node* p_node) { AnimationPlayer *ap = p_node->cast_to(); if (ap) { - add=true; + add = true; } } if (add) { - p_node->connect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed",varray(p_node),CONNECT_ONESHOT); - nodes[p_node]=meta; - _change_node_state(p_node,false); + p_node->connect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed", varray(p_node), CONNECT_ONESHOT); + nodes[p_node] = meta; + _change_node_state(p_node, false); } - for(int i=0;iget_child_count();i++) { + for (int i = 0; i < p_node->get_child_count(); i++) { Node *c = p_node->get_child(i); - if (c->get_filename()!=String()) + if (c->get_filename() != String()) continue; //skip, instance _find_nodes(c); } - } -void VisibilityEnabler::_notification(int p_what){ +void VisibilityEnabler::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_TREE) { + if (p_what == NOTIFICATION_ENTER_TREE) { if (get_tree()->is_editor_hint()) return; - Node *from = this; //find where current scene starts - while(from->get_parent() && from->get_filename()==String()) - from=from->get_parent(); + while (from->get_parent() && from->get_filename() == String()) + from = from->get_parent(); _find_nodes(from); - } - if (p_what==NOTIFICATION_EXIT_TREE) { + if (p_what == NOTIFICATION_EXIT_TREE) { if (get_tree()->is_editor_hint()) return; - - for (Map::Element *E=nodes.front();E;E=E->next()) { + for (Map::Element *E = nodes.front(); E; E = E->next()) { if (!visible) - _change_node_state(E->key(),true); - E->key()->disconnect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed"); + _change_node_state(E->key(), true); + E->key()->disconnect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed"); } nodes.clear(); - } } -void VisibilityEnabler::_change_node_state(Node* p_node,bool p_enabled) { +void VisibilityEnabler::_change_node_state(Node *p_node, bool p_enabled) { ERR_FAIL_COND(!nodes.has(p_node)); @@ -246,59 +223,52 @@ void VisibilityEnabler::_change_node_state(Node* p_node,bool p_enabled) { } { - AnimationPlayer *ap=p_node->cast_to(); + AnimationPlayer *ap = p_node->cast_to(); if (ap) { ap->set_active(p_enabled); } } - } - -void VisibilityEnabler::_node_removed(Node* p_node) { +void VisibilityEnabler::_node_removed(Node *p_node) { if (!visible) - _change_node_state(p_node,true); - p_node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed"); + _change_node_state(p_node, true); + p_node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed"); nodes.erase(p_node); - } -void VisibilityEnabler::_bind_methods(){ +void VisibilityEnabler::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_enabler","enabler","enabled"),&VisibilityEnabler::set_enabler); - ClassDB::bind_method(D_METHOD("is_enabler_enabled","enabler"),&VisibilityEnabler::is_enabler_enabled); - ClassDB::bind_method(D_METHOD("_node_removed"),&VisibilityEnabler::_node_removed); + ClassDB::bind_method(D_METHOD("set_enabler", "enabler", "enabled"), &VisibilityEnabler::set_enabler); + ClassDB::bind_method(D_METHOD("is_enabler_enabled", "enabler"), &VisibilityEnabler::is_enabler_enabled); + ClassDB::bind_method(D_METHOD("_node_removed"), &VisibilityEnabler::_node_removed); - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"pause_animations"),"set_enabler","is_enabler_enabled", ENABLER_PAUSE_ANIMATIONS ); - ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"freeze_bodies"),"set_enabler","is_enabler_enabled", ENABLER_FREEZE_BODIES); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "pause_animations"), "set_enabler", "is_enabler_enabled", ENABLER_PAUSE_ANIMATIONS); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "freeze_bodies"), "set_enabler", "is_enabler_enabled", ENABLER_FREEZE_BODIES); - BIND_CONSTANT( ENABLER_FREEZE_BODIES ); - BIND_CONSTANT( ENABLER_PAUSE_ANIMATIONS ); - BIND_CONSTANT( ENABLER_MAX); + BIND_CONSTANT(ENABLER_FREEZE_BODIES); + BIND_CONSTANT(ENABLER_PAUSE_ANIMATIONS); + BIND_CONSTANT(ENABLER_MAX); } -void VisibilityEnabler::set_enabler(Enabler p_enabler,bool p_enable){ - - ERR_FAIL_INDEX(p_enabler,ENABLER_MAX); - enabler[p_enabler]=p_enable; +void VisibilityEnabler::set_enabler(Enabler p_enabler, bool p_enable) { + ERR_FAIL_INDEX(p_enabler, ENABLER_MAX); + enabler[p_enabler] = p_enable; } -bool VisibilityEnabler::is_enabler_enabled(Enabler p_enabler) const{ +bool VisibilityEnabler::is_enabler_enabled(Enabler p_enabler) const { - ERR_FAIL_INDEX_V(p_enabler,ENABLER_MAX,false); + ERR_FAIL_INDEX_V(p_enabler, ENABLER_MAX, false); return enabler[p_enabler]; - } VisibilityEnabler::VisibilityEnabler() { - for(int i=0;i cameras; + Set cameras; Rect3 aabb; protected: - virtual void _screen_enter() {} virtual void _screen_exit() {} void _notification(int p_what); static void _bind_methods(); -friend class SpatialIndexer; + friend class SpatialIndexer; - void _enter_camera(Camera* p_camera); - void _exit_camera(Camera* p_camera); + void _enter_camera(Camera *p_camera); + void _exit_camera(Camera *p_camera); public: - - void set_aabb(const Rect3& p_aabb); + void set_aabb(const Rect3 &p_aabb); Rect3 get_aabb() const; bool is_on_screen() const; VisibilityNotifier(); }; - class VisibilityEnabler : public VisibilityNotifier { - GDCLASS(VisibilityEnabler,VisibilityNotifier); -public: + GDCLASS(VisibilityEnabler, VisibilityNotifier); +public: enum Enabler { ENABLER_PAUSE_ANIMATIONS, ENABLER_FREEZE_BODIES, @@ -74,33 +71,29 @@ public: }; protected: - virtual void _screen_enter(); virtual void _screen_exit(); bool visible; - void _find_nodes(Node* p_node); + void _find_nodes(Node *p_node); - Map nodes; - void _node_removed(Node* p_node); + Map nodes; + void _node_removed(Node *p_node); bool enabler[ENABLER_MAX]; - void _change_node_state(Node* p_node,bool p_enabled); + void _change_node_state(Node *p_node, bool p_enabled); void _notification(int p_what); static void _bind_methods(); public: - - void set_enabler(Enabler p_enabler,bool p_enable); + void set_enabler(Enabler p_enabler, bool p_enable); bool is_enabler_enabled(Enabler p_enabler) const; VisibilityEnabler(); - }; VARIANT_ENUM_CAST(VisibilityEnabler::Enabler); - #endif // VISIBILITY_NOTIFIER_H diff --git a/scene/3d/visual_instance.cpp b/scene/3d/visual_instance.cpp index bbcd54b36..852881abd 100644 --- a/scene/3d/visual_instance.cpp +++ b/scene/3d/visual_instance.cpp @@ -28,39 +28,37 @@ /*************************************************************************/ #include "visual_instance.h" -#include "servers/visual_server.h" #include "room_instance.h" #include "scene/scene_string_names.h" +#include "servers/visual_server.h" #include "skeleton.h" Rect3 VisualInstance::get_transformed_aabb() const { - return get_global_transform().xform( get_aabb() ); + return get_global_transform().xform(get_aabb()); } - void VisualInstance::_update_visibility() { if (!is_inside_tree()) return; _change_notify("visible"); - VS::get_singleton()->instance_set_visible(get_instance(),is_visible_in_tree()); + VS::get_singleton()->instance_set_visible(get_instance(), is_visible_in_tree()); } - void VisualInstance::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_WORLD: { // CHECK ROOM - Spatial * parent = get_parent_spatial(); - Room *room=NULL; + Spatial *parent = get_parent_spatial(); + Room *room = NULL; bool is_geom = cast_to(); - /* while(parent) { + /* while(parent) { room = parent->cast_to(); if (room) @@ -74,11 +72,9 @@ void VisualInstance::_notification(int p_what) { parent=parent->get_parent_spatial(); }*/ - - if (room) { - VisualServer::get_singleton()->instance_set_room(instance,room->get_instance()); + VisualServer::get_singleton()->instance_set_room(instance, room->get_instance()); } // CHECK SKELETON => moving skeleton attaching logic to MeshInstance /* @@ -87,21 +83,20 @@ void VisualInstance::_notification(int p_what) { VisualServer::get_singleton()->instance_attach_skeleton( instance, skeleton->get_skeleton() ); */ - VisualServer::get_singleton()->instance_set_scenario( instance, get_world()->get_scenario() ); + VisualServer::get_singleton()->instance_set_scenario(instance, get_world()->get_scenario()); _update_visibility(); - } break; case NOTIFICATION_TRANSFORM_CHANGED: { Transform gt = get_global_transform(); - VisualServer::get_singleton()->instance_set_transform(instance,gt); + VisualServer::get_singleton()->instance_set_transform(instance, gt); } break; case NOTIFICATION_EXIT_WORLD: { - VisualServer::get_singleton()->instance_set_scenario( instance, RID() ); - VisualServer::get_singleton()->instance_set_room(instance,RID()); - VisualServer::get_singleton()->instance_attach_skeleton( instance, RID() ); + VisualServer::get_singleton()->instance_set_scenario(instance, RID()); + VisualServer::get_singleton()->instance_set_room(instance, RID()); + VisualServer::get_singleton()->instance_attach_skeleton(instance, RID()); //VS::get_singleton()->instance_geometry_set_baked_light_sampler(instance, RID() ); } break; @@ -109,7 +104,6 @@ void VisualInstance::_notification(int p_what) { _update_visibility(); } break; - } } @@ -125,8 +119,8 @@ RID VisualInstance::_get_visual_instance_rid() const { void VisualInstance::set_layer_mask(uint32_t p_mask) { - layers=p_mask; - VisualServer::get_singleton()->instance_set_layer_mask(instance,p_mask); + layers = p_mask; + VisualServer::get_singleton()->instance_set_layer_mask(instance, p_mask); } uint32_t VisualInstance::get_layer_mask() const { @@ -134,76 +128,62 @@ uint32_t VisualInstance::get_layer_mask() const { return layers; } - void VisualInstance::_bind_methods() { - ClassDB::bind_method(D_METHOD("_get_visual_instance_rid"),&VisualInstance::_get_visual_instance_rid); - ClassDB::bind_method(D_METHOD("set_base","base"), &VisualInstance::set_base); - ClassDB::bind_method(D_METHOD("set_layer_mask","mask"), &VisualInstance::set_layer_mask); + ClassDB::bind_method(D_METHOD("_get_visual_instance_rid"), &VisualInstance::_get_visual_instance_rid); + ClassDB::bind_method(D_METHOD("set_base", "base"), &VisualInstance::set_base); + ClassDB::bind_method(D_METHOD("set_layer_mask", "mask"), &VisualInstance::set_layer_mask); ClassDB::bind_method(D_METHOD("get_layer_mask"), &VisualInstance::get_layer_mask); ClassDB::bind_method(D_METHOD("get_transformed_aabb"), &VisualInstance::get_transformed_aabb); - ADD_PROPERTY( PropertyInfo( Variant::INT, "layers",PROPERTY_HINT_LAYERS_3D_RENDER), "set_layer_mask", "get_layer_mask"); - - + ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_3D_RENDER), "set_layer_mask", "get_layer_mask"); } +void VisualInstance::set_base(const RID &p_base) { -void VisualInstance::set_base(const RID& p_base) { - - VisualServer::get_singleton()->instance_set_base(instance,p_base); + VisualServer::get_singleton()->instance_set_base(instance, p_base); } - -VisualInstance::VisualInstance() -{ +VisualInstance::VisualInstance() { instance = VisualServer::get_singleton()->instance_create(); - VisualServer::get_singleton()->instance_attach_object_instance_ID( instance, get_instance_ID() ); - layers=1; + VisualServer::get_singleton()->instance_attach_object_instance_ID(instance, get_instance_ID()); + layers = 1; set_notify_transform(true); } - VisualInstance::~VisualInstance() { VisualServer::get_singleton()->free(instance); } +void GeometryInstance::set_material_override(const Ref &p_material) { - - -void GeometryInstance::set_material_override(const Ref& p_material) { - - material_override=p_material; - VS::get_singleton()->instance_geometry_set_material_override(get_instance(),p_material.is_valid() ? p_material->get_rid() : RID()); + material_override = p_material; + VS::get_singleton()->instance_geometry_set_material_override(get_instance(), p_material.is_valid() ? p_material->get_rid() : RID()); } -Ref GeometryInstance::get_material_override() const{ +Ref GeometryInstance::get_material_override() const { return material_override; } +void GeometryInstance::set_lod_min_distance(float p_dist) { - -void GeometryInstance::set_lod_min_distance(float p_dist){ - - lod_min_distance=p_dist; - VS::get_singleton()->instance_geometry_set_draw_range(get_instance(),lod_min_distance,lod_max_distance,lod_min_hysteresis,lod_max_hysteresis); + lod_min_distance = p_dist; + VS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis); } -float GeometryInstance::get_lod_min_distance() const{ +float GeometryInstance::get_lod_min_distance() const { return lod_min_distance; } - void GeometryInstance::set_lod_max_distance(float p_dist) { - lod_max_distance=p_dist; - VS::get_singleton()->instance_geometry_set_draw_range(get_instance(),lod_min_distance,lod_max_distance,lod_min_hysteresis,lod_max_hysteresis); - + lod_max_distance = p_dist; + VS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis); } float GeometryInstance::get_lod_max_distance() const { @@ -211,23 +191,21 @@ float GeometryInstance::get_lod_max_distance() const { return lod_max_distance; } -void GeometryInstance::set_lod_min_hysteresis(float p_dist){ +void GeometryInstance::set_lod_min_hysteresis(float p_dist) { - lod_min_hysteresis=p_dist; - VS::get_singleton()->instance_geometry_set_draw_range(get_instance(),lod_min_distance,lod_max_distance,lod_min_hysteresis,lod_max_hysteresis); + lod_min_hysteresis = p_dist; + VS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis); } -float GeometryInstance::get_lod_min_hysteresis() const{ +float GeometryInstance::get_lod_min_hysteresis() const { return lod_min_hysteresis; } - void GeometryInstance::set_lod_max_hysteresis(float p_dist) { - lod_max_hysteresis=p_dist; - VS::get_singleton()->instance_geometry_set_draw_range(get_instance(),lod_min_distance,lod_max_distance,lod_min_hysteresis,lod_max_hysteresis); - + lod_max_hysteresis = p_dist; + VS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis); } float GeometryInstance::get_lod_max_hysteresis() const { @@ -235,64 +213,53 @@ float GeometryInstance::get_lod_max_hysteresis() const { return lod_max_hysteresis; } - void GeometryInstance::_notification(int p_what) { - if (p_what==NOTIFICATION_ENTER_WORLD) { + if (p_what == NOTIFICATION_ENTER_WORLD) { if (flags[FLAG_USE_BAKED_LIGHT]) { - } - - } else if (p_what==NOTIFICATION_EXIT_WORLD) { + } else if (p_what == NOTIFICATION_EXIT_WORLD) { if (flags[FLAG_USE_BAKED_LIGHT]) { - - } - } - } -void GeometryInstance::set_flag(Flags p_flag,bool p_value) { +void GeometryInstance::set_flag(Flags p_flag, bool p_value) { - ERR_FAIL_INDEX(p_flag,FLAG_MAX); - if (p_flag==FLAG_CAST_SHADOW) { + ERR_FAIL_INDEX(p_flag, FLAG_MAX); + if (p_flag == FLAG_CAST_SHADOW) { if (p_value == true) { set_cast_shadows_setting(SHADOW_CASTING_SETTING_ON); - } - else { + } else { set_cast_shadows_setting(SHADOW_CASTING_SETTING_OFF); } } - if (flags[p_flag]==p_value) + if (flags[p_flag] == p_value) return; - flags[p_flag]=p_value; - VS::get_singleton()->instance_geometry_set_flag(get_instance(),(VS::InstanceFlags)p_flag,p_value); - if (p_flag==FLAG_USE_BAKED_LIGHT) { - + flags[p_flag] = p_value; + VS::get_singleton()->instance_geometry_set_flag(get_instance(), (VS::InstanceFlags)p_flag, p_value); + if (p_flag == FLAG_USE_BAKED_LIGHT) { } } -bool GeometryInstance::get_flag(Flags p_flag) const{ +bool GeometryInstance::get_flag(Flags p_flag) const { - ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false); + ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false); if (p_flag == FLAG_CAST_SHADOW) { if (shadow_casting_setting == SHADOW_CASTING_SETTING_OFF) { return false; - } - else { + } else { return true; } } return flags[p_flag]; - } void GeometryInstance::set_cast_shadows_setting(ShadowCastingSetting p_shadow_casting_setting) { @@ -307,99 +274,90 @@ GeometryInstance::ShadowCastingSetting GeometryInstance::get_cast_shadows_settin return shadow_casting_setting; } - - - void GeometryInstance::set_extra_cull_margin(float p_margin) { - ERR_FAIL_COND(p_margin<0); - extra_cull_margin=p_margin; - VS::get_singleton()->instance_set_extra_visibility_margin(get_instance(),extra_cull_margin); + ERR_FAIL_COND(p_margin < 0); + extra_cull_margin = p_margin; + VS::get_singleton()->instance_set_extra_visibility_margin(get_instance(), extra_cull_margin); } -float GeometryInstance::get_extra_cull_margin() const{ +float GeometryInstance::get_extra_cull_margin() const { return extra_cull_margin; } void GeometryInstance::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_material_override","material"), &GeometryInstance::set_material_override); + ClassDB::bind_method(D_METHOD("set_material_override", "material"), &GeometryInstance::set_material_override); ClassDB::bind_method(D_METHOD("get_material_override"), &GeometryInstance::get_material_override); - ClassDB::bind_method(D_METHOD("set_flag","flag","value"), &GeometryInstance::set_flag); - ClassDB::bind_method(D_METHOD("get_flag","flag"), &GeometryInstance::get_flag); + ClassDB::bind_method(D_METHOD("set_flag", "flag", "value"), &GeometryInstance::set_flag); + ClassDB::bind_method(D_METHOD("get_flag", "flag"), &GeometryInstance::get_flag); ClassDB::bind_method(D_METHOD("set_cast_shadows_setting", "shadow_casting_setting"), &GeometryInstance::set_cast_shadows_setting); ClassDB::bind_method(D_METHOD("get_cast_shadows_setting"), &GeometryInstance::get_cast_shadows_setting); - ClassDB::bind_method(D_METHOD("set_lod_max_hysteresis","mode"), &GeometryInstance::set_lod_max_hysteresis); + ClassDB::bind_method(D_METHOD("set_lod_max_hysteresis", "mode"), &GeometryInstance::set_lod_max_hysteresis); ClassDB::bind_method(D_METHOD("get_lod_max_hysteresis"), &GeometryInstance::get_lod_max_hysteresis); - ClassDB::bind_method(D_METHOD("set_lod_max_distance","mode"), &GeometryInstance::set_lod_max_distance); + ClassDB::bind_method(D_METHOD("set_lod_max_distance", "mode"), &GeometryInstance::set_lod_max_distance); ClassDB::bind_method(D_METHOD("get_lod_max_distance"), &GeometryInstance::get_lod_max_distance); - ClassDB::bind_method(D_METHOD("set_lod_min_hysteresis","mode"), &GeometryInstance::set_lod_min_hysteresis); + ClassDB::bind_method(D_METHOD("set_lod_min_hysteresis", "mode"), &GeometryInstance::set_lod_min_hysteresis); ClassDB::bind_method(D_METHOD("get_lod_min_hysteresis"), &GeometryInstance::get_lod_min_hysteresis); - ClassDB::bind_method(D_METHOD("set_lod_min_distance","mode"), &GeometryInstance::set_lod_min_distance); + ClassDB::bind_method(D_METHOD("set_lod_min_distance", "mode"), &GeometryInstance::set_lod_min_distance); ClassDB::bind_method(D_METHOD("get_lod_min_distance"), &GeometryInstance::get_lod_min_distance); - - ClassDB::bind_method(D_METHOD("set_extra_cull_margin","margin"), &GeometryInstance::set_extra_cull_margin); + ClassDB::bind_method(D_METHOD("set_extra_cull_margin", "margin"), &GeometryInstance::set_extra_cull_margin); ClassDB::bind_method(D_METHOD("get_extra_cull_margin"), &GeometryInstance::get_extra_cull_margin); - ClassDB::bind_method(D_METHOD("get_aabb"),&GeometryInstance::get_aabb); + ClassDB::bind_method(D_METHOD("get_aabb"), &GeometryInstance::get_aabb); - - ADD_GROUP("Geometry",""); - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "material_override",PROPERTY_HINT_RESOURCE_TYPE,"Material"), "set_material_override", "get_material_override"); + ADD_GROUP("Geometry", ""); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material_override", PROPERTY_HINT_RESOURCE_TYPE, "Material"), "set_material_override", "get_material_override"); ADD_PROPERTY(PropertyInfo(Variant::INT, "cast_shadow", PROPERTY_HINT_ENUM, "Off,On,Double-Sided,Shadows Only"), "set_cast_shadows_setting", "get_cast_shadows_setting"); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "extra_cull_margin",PROPERTY_HINT_RANGE,"0,16384,0"), "set_extra_cull_margin", "get_extra_cull_margin"); - ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "use_as_billboard"), "set_flag", "get_flag",FLAG_BILLBOARD); - ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "use_as_y_billboard"), "set_flag", "get_flag",FLAG_BILLBOARD_FIX_Y); - ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "use_depth_scale"), "set_flag", "get_flag",FLAG_DEPH_SCALE); - ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "visible_in_all_rooms"), "set_flag", "get_flag",FLAG_VISIBLE_IN_ALL_ROOMS); - ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "use_in_baked_light"), "set_flag", "get_flag",FLAG_USE_BAKED_LIGHT); - - ADD_GROUP("LOD","lod_"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "lod_min_distance",PROPERTY_HINT_RANGE,"0,32768,0.01"), "set_lod_min_distance", "get_lod_min_distance"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "lod_min_hysteresis",PROPERTY_HINT_RANGE,"0,32768,0.01"), "set_lod_min_hysteresis", "get_lod_min_hysteresis"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "lod_max_distance",PROPERTY_HINT_RANGE,"0,32768,0.01"), "set_lod_max_distance", "get_lod_max_distance"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "lod_max_hysteresis",PROPERTY_HINT_RANGE,"0,32768,0.01"), "set_lod_max_hysteresis", "get_lod_max_hysteresis"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "extra_cull_margin", PROPERTY_HINT_RANGE, "0,16384,0"), "set_extra_cull_margin", "get_extra_cull_margin"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "use_as_billboard"), "set_flag", "get_flag", FLAG_BILLBOARD); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "use_as_y_billboard"), "set_flag", "get_flag", FLAG_BILLBOARD_FIX_Y); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "use_depth_scale"), "set_flag", "get_flag", FLAG_DEPH_SCALE); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "visible_in_all_rooms"), "set_flag", "get_flag", FLAG_VISIBLE_IN_ALL_ROOMS); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "use_in_baked_light"), "set_flag", "get_flag", FLAG_USE_BAKED_LIGHT); + + ADD_GROUP("LOD", "lod_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_min_distance", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_min_distance", "get_lod_min_distance"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_min_hysteresis", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_min_hysteresis", "get_lod_min_hysteresis"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_max_distance", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_max_distance", "get_lod_max_distance"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_max_hysteresis", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_max_hysteresis", "get_lod_max_hysteresis"); //ADD_SIGNAL( MethodInfo("visibility_changed")); - BIND_CONSTANT(FLAG_CAST_SHADOW ); - BIND_CONSTANT(FLAG_BILLBOARD ); - BIND_CONSTANT(FLAG_BILLBOARD_FIX_Y ); - BIND_CONSTANT(FLAG_DEPH_SCALE ); - BIND_CONSTANT(FLAG_VISIBLE_IN_ALL_ROOMS ); - BIND_CONSTANT(FLAG_MAX ); + BIND_CONSTANT(FLAG_CAST_SHADOW); + BIND_CONSTANT(FLAG_BILLBOARD); + BIND_CONSTANT(FLAG_BILLBOARD_FIX_Y); + BIND_CONSTANT(FLAG_DEPH_SCALE); + BIND_CONSTANT(FLAG_VISIBLE_IN_ALL_ROOMS); + BIND_CONSTANT(FLAG_MAX); BIND_CONSTANT(SHADOW_CASTING_SETTING_OFF); BIND_CONSTANT(SHADOW_CASTING_SETTING_ON); BIND_CONSTANT(SHADOW_CASTING_SETTING_DOUBLE_SIDED); BIND_CONSTANT(SHADOW_CASTING_SETTING_SHADOWS_ONLY); - } GeometryInstance::GeometryInstance() { - lod_min_distance=0; - lod_max_distance=0; - lod_min_hysteresis=0; - lod_max_hysteresis=0; + lod_min_distance = 0; + lod_max_distance = 0; + lod_min_hysteresis = 0; + lod_max_hysteresis = 0; - for(int i=0;iinstance_geometry_set_baked_light_texture_index(get_instance(),0); - - } diff --git a/scene/3d/visual_instance.h b/scene/3d/visual_instance.h index 5955dae23..9f1cba923 100644 --- a/scene/3d/visual_instance.h +++ b/scene/3d/visual_instance.h @@ -29,85 +29,77 @@ #ifndef VISUAL_INSTANCE_H #define VISUAL_INSTANCE_H -#include "scene/3d/spatial.h" #include "face3.h" #include "rid.h" +#include "scene/3d/spatial.h" #include "scene/resources/material.h" /** @author Juan Linietsky */ class VisualInstance : public Spatial { - GDCLASS( VisualInstance, Spatial ); + GDCLASS(VisualInstance, Spatial); OBJ_CATEGORY("3D Visual Nodes"); RID instance; uint32_t layers; - RID _get_visual_instance_rid() const; - - protected: - void _update_visibility(); void _notification(int p_what); static void _bind_methods(); -public: +public: enum GetFacesFlags { - FACES_SOLID=1, // solid geometry - FACES_ENCLOSING=2, - FACES_DYNAMIC=4 // dynamic object geometry + FACES_SOLID = 1, // solid geometry + FACES_ENCLOSING = 2, + FACES_DYNAMIC = 4 // dynamic object geometry }; RID get_instance() const; - virtual Rect3 get_aabb() const=0; - virtual PoolVector get_faces(uint32_t p_usage_flags) const=0; + virtual Rect3 get_aabb() const = 0; + virtual PoolVector get_faces(uint32_t p_usage_flags) const = 0; virtual Rect3 get_transformed_aabb() const; // helper - void set_base(const RID& p_base); + void set_base(const RID &p_base); void set_layer_mask(uint32_t p_mask); uint32_t get_layer_mask() const; - VisualInstance(); ~VisualInstance(); - }; class BakedLight; class GeometryInstance : public VisualInstance { - GDCLASS( GeometryInstance, VisualInstance ); -public: + GDCLASS(GeometryInstance, VisualInstance); +public: enum Flags { - FLAG_CAST_SHADOW=VS::INSTANCE_FLAG_CAST_SHADOW, - FLAG_BILLBOARD=VS::INSTANCE_FLAG_BILLBOARD, - FLAG_BILLBOARD_FIX_Y=VS::INSTANCE_FLAG_BILLBOARD_FIX_Y, - FLAG_DEPH_SCALE=VS::INSTANCE_FLAG_DEPH_SCALE, - FLAG_VISIBLE_IN_ALL_ROOMS=VS::INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS, - FLAG_USE_BAKED_LIGHT=VS::INSTANCE_FLAG_USE_BAKED_LIGHT, - FLAG_MAX=VS::INSTANCE_FLAG_MAX, + FLAG_CAST_SHADOW = VS::INSTANCE_FLAG_CAST_SHADOW, + FLAG_BILLBOARD = VS::INSTANCE_FLAG_BILLBOARD, + FLAG_BILLBOARD_FIX_Y = VS::INSTANCE_FLAG_BILLBOARD_FIX_Y, + FLAG_DEPH_SCALE = VS::INSTANCE_FLAG_DEPH_SCALE, + FLAG_VISIBLE_IN_ALL_ROOMS = VS::INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS, + FLAG_USE_BAKED_LIGHT = VS::INSTANCE_FLAG_USE_BAKED_LIGHT, + FLAG_MAX = VS::INSTANCE_FLAG_MAX, }; - enum ShadowCastingSetting { - SHADOW_CASTING_SETTING_OFF=VS::SHADOW_CASTING_SETTING_OFF, + SHADOW_CASTING_SETTING_OFF = VS::SHADOW_CASTING_SETTING_OFF, SHADOW_CASTING_SETTING_ON = VS::SHADOW_CASTING_SETTING_ON, - SHADOW_CASTING_SETTING_DOUBLE_SIDED=VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED, - SHADOW_CASTING_SETTING_SHADOWS_ONLY=VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY + SHADOW_CASTING_SETTING_DOUBLE_SIDED = VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED, + SHADOW_CASTING_SETTING_SHADOWS_ONLY = VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY }; private: - bool flags[FLAG_MAX]; ShadowCastingSetting shadow_casting_setting; Ref material_override; @@ -119,12 +111,11 @@ private: float extra_cull_margin; protected: - void _notification(int p_what); static void _bind_methods(); -public: - void set_flag(Flags p_flag,bool p_value); +public: + void set_flag(Flags p_flag, bool p_value); bool get_flag(Flags p_flag) const; void set_cast_shadows_setting(ShadowCastingSetting p_shadow_casting_setting); @@ -142,7 +133,7 @@ public: void set_lod_max_hysteresis(float p_dist); float get_lod_max_hysteresis() const; - void set_material_override(const Ref& p_material); + void set_material_override(const Ref &p_material); Ref get_material_override() const; void set_extra_cull_margin(float p_margin); @@ -151,8 +142,7 @@ public: GeometryInstance(); }; -VARIANT_ENUM_CAST( GeometryInstance::Flags ); -VARIANT_ENUM_CAST( GeometryInstance::ShadowCastingSetting ); - +VARIANT_ENUM_CAST(GeometryInstance::Flags); +VARIANT_ENUM_CAST(GeometryInstance::ShadowCastingSetting); #endif diff --git a/scene/animation/animation_cache.cpp b/scene/animation/animation_cache.cpp index 960356d9c..93fbde519 100644 --- a/scene/animation/animation_cache.cpp +++ b/scene/animation/animation_cache.cpp @@ -28,8 +28,6 @@ /*************************************************************************/ #include "animation_cache.h" - - void AnimationCache::_node_exit_tree(Node *p_node) { //it is one shot, so it disconnects upon arrival @@ -38,47 +36,41 @@ void AnimationCache::_node_exit_tree(Node *p_node) { connected_nodes.erase(p_node); - for(int i=0;iget()->disconnect("tree_exited",this,"_node_exit_tree"); + connected_nodes.front()->get()->disconnect("tree_exited", this, "_node_exit_tree"); connected_nodes.erase(connected_nodes.front()); } path_cache.clear(); - cache_valid=false; - cache_dirty=true; + cache_valid = false; + cache_dirty = true; } - void AnimationCache::_update_cache() { - cache_valid=false; + cache_valid = false; ERR_FAIL_COND(!root); ERR_FAIL_COND(!root->is_inside_tree()); ERR_FAIL_COND(animation.is_null()); - for(int i=0;iget_track_count();i++) { - - + for (int i = 0; i < animation->get_track_count(); i++) { NodePath np = animation->track_get_path(i); @@ -86,146 +78,127 @@ void AnimationCache::_update_cache() { if (!node) { path_cache.push_back(Path()); - ERR_EXPLAIN("Invalid Track Path in Animation: "+np); + ERR_EXPLAIN("Invalid Track Path in Animation: " + np); ERR_CONTINUE(!node); } - Path path; Ref res; if (np.get_subname_count()) { - - if (animation->track_get_type(i)==Animation::TYPE_TRANSFORM) { + if (animation->track_get_type(i) == Animation::TYPE_TRANSFORM) { path_cache.push_back(Path()); - ERR_EXPLAIN("Transform tracks can't have a subpath: "+np); - ERR_CONTINUE(animation->track_get_type(i)==Animation::TYPE_TRANSFORM); - + ERR_EXPLAIN("Transform tracks can't have a subpath: " + np); + ERR_CONTINUE(animation->track_get_type(i) == Animation::TYPE_TRANSFORM); } RES res; - for(int j=0;jget(np.get_subname(j)) : res->get(np.get_subname(j)); + for (int j = 0; j < np.get_subname_count(); j++) { + res = j == 0 ? node->get(np.get_subname(j)) : res->get(np.get_subname(j)); if (res.is_null()) break; - } if (res.is_null()) { path_cache.push_back(Path()); - ERR_EXPLAIN("Invalid Track SubPath in Animation: "+np); + ERR_EXPLAIN("Invalid Track SubPath in Animation: " + np); ERR_CONTINUE(res.is_null()); } - path.resource=res; - path.object=res.ptr(); + path.resource = res; + path.object = res.ptr(); } else { - - if (animation->track_get_type(i)==Animation::TYPE_TRANSFORM) { + if (animation->track_get_type(i) == Animation::TYPE_TRANSFORM) { StringName property = np.get_property(); String ps = property; - Spatial *sp = node->cast_to(); if (!sp) { path_cache.push_back(Path()); - ERR_EXPLAIN("Transform track not of type Spatial: "+np); + ERR_EXPLAIN("Transform track not of type Spatial: " + np); ERR_CONTINUE(!sp); } - if (ps!="") { + if (ps != "") { Skeleton *sk = node->cast_to(); if (!sk) { path_cache.push_back(Path()); - ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton!: "+np); + ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton!: " + np); ERR_CONTINUE(!sk); } int idx = sk->find_bone(ps); - if (idx==-1) { + if (idx == -1) { path_cache.push_back(Path()); - ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton Bone!: "+np); - ERR_CONTINUE(idx==-1); - + ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton Bone!: " + np); + ERR_CONTINUE(idx == -1); } - path.bone_idx=idx; - path.skeleton=sk; - + path.bone_idx = idx; + path.skeleton = sk; } - path.spatial=sp; - + path.spatial = sp; } - path.node=node; - path.object=node; - + path.node = node; + path.object = node; } - if (animation->track_get_type(i)==Animation::TYPE_VALUE) { + if (animation->track_get_type(i) == Animation::TYPE_VALUE) { - if (np.get_property().operator String()=="") { + if (np.get_property().operator String() == "") { path_cache.push_back(Path()); - ERR_EXPLAIN("Value Track lacks property: "+np); - ERR_CONTINUE(np.get_property().operator String()==""); - + ERR_EXPLAIN("Value Track lacks property: " + np); + ERR_CONTINUE(np.get_property().operator String() == ""); } - path.property=np.get_property(); + path.property = np.get_property(); - } else if (animation->track_get_type(i)==Animation::TYPE_METHOD) { + } else if (animation->track_get_type(i) == Animation::TYPE_METHOD) { - if (np.get_property().operator String()!="") { + if (np.get_property().operator String() != "") { path_cache.push_back(Path()); - ERR_EXPLAIN("Method Track has property: "+np); - ERR_CONTINUE(np.get_property().operator String()!=""); - + ERR_EXPLAIN("Method Track has property: " + np); + ERR_CONTINUE(np.get_property().operator String() != ""); } - } - - path.valid=true; + path.valid = true; path_cache.push_back(path); if (!connected_nodes.has(path.node)) { connected_nodes.insert(path.node); - path.node->connect("tree_exited",this,"_node_exit_tree",Node::make_binds(path.node),CONNECT_ONESHOT); + path.node->connect("tree_exited", this, "_node_exit_tree", Node::make_binds(path.node), CONNECT_ONESHOT); } - - - } - - - cache_dirty=false; - cache_valid=true; + cache_dirty = false; + cache_valid = true; } -void AnimationCache::set_track_transform(int p_idx,const Transform& p_transform) { +void AnimationCache::set_track_transform(int p_idx, const Transform &p_transform) { if (cache_dirty) _update_cache(); ERR_FAIL_COND(!cache_valid); - ERR_FAIL_INDEX(p_idx,path_cache.size()); + ERR_FAIL_INDEX(p_idx, path_cache.size()); Path &p = path_cache[p_idx]; if (!p.valid) return; @@ -234,47 +207,42 @@ void AnimationCache::set_track_transform(int p_idx,const Transform& p_transform) ERR_FAIL_COND(!p.spatial); if (p.skeleton) { - p.skeleton->set_bone_pose(p.bone_idx,p_transform); + p.skeleton->set_bone_pose(p.bone_idx, p_transform); } else { p.spatial->set_transform(p_transform); } - } -void AnimationCache::set_track_value(int p_idx,const Variant& p_value) { +void AnimationCache::set_track_value(int p_idx, const Variant &p_value) { if (cache_dirty) _update_cache(); ERR_FAIL_COND(!cache_valid); - ERR_FAIL_INDEX(p_idx,path_cache.size()); + ERR_FAIL_INDEX(p_idx, path_cache.size()); Path &p = path_cache[p_idx]; if (!p.valid) return; ERR_FAIL_COND(!p.object); - p.object->set(p.property,p_value); + p.object->set(p.property, p_value); } - -void AnimationCache::call_track(int p_idx,const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { +void AnimationCache::call_track(int p_idx, const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { if (cache_dirty) _update_cache(); - ERR_FAIL_COND(!cache_valid); - ERR_FAIL_INDEX(p_idx,path_cache.size()); + ERR_FAIL_INDEX(p_idx, path_cache.size()); Path &p = path_cache[p_idx]; if (!p.valid) return; ERR_FAIL_COND(!p.object); - p.object->call(p_method,p_args,p_argcount,r_error); - + p.object->call(p_method, p_args, p_argcount, r_error); } - void AnimationCache::set_all(float p_time, float p_delta) { if (cache_dirty) @@ -283,104 +251,100 @@ void AnimationCache::set_all(float p_time, float p_delta) { ERR_FAIL_COND(!cache_valid); int tc = animation->get_track_count(); - for(int i=0;itrack_get_type(i)) { + switch (animation->track_get_type(i)) { case Animation::TYPE_TRANSFORM: { - Vector3 loc,scale; + Vector3 loc, scale; Quat rot; - animation->transform_track_interpolate(i,p_time,&loc,&rot,&scale); - Transform tr( Basis(rot), loc ); + animation->transform_track_interpolate(i, p_time, &loc, &rot, &scale); + Transform tr(Basis(rot), loc); tr.basis.scale(scale); - set_track_transform(i,tr); - + set_track_transform(i, tr); } break; case Animation::TYPE_VALUE: { - if (animation->value_track_get_update_mode(i)==Animation::UPDATE_CONTINUOUS || (animation->value_track_get_update_mode(i)==Animation::UPDATE_DISCRETE && p_delta==0)) { - Variant v = animation->value_track_interpolate(i,p_time); - set_track_value(i,v); + if (animation->value_track_get_update_mode(i) == Animation::UPDATE_CONTINUOUS || (animation->value_track_get_update_mode(i) == Animation::UPDATE_DISCRETE && p_delta == 0)) { + Variant v = animation->value_track_interpolate(i, p_time); + set_track_value(i, v); } else { List indices; - animation->value_track_get_key_indices(i,p_time,p_delta,&indices); + animation->value_track_get_key_indices(i, p_time, p_delta, &indices); - for(List::Element *E=indices.front();E;E=E->next()) { + for (List::Element *E = indices.front(); E; E = E->next()) { - Variant v = animation->track_get_key_value(i,E->get()); - set_track_value(i,v); + Variant v = animation->track_get_key_value(i, E->get()); + set_track_value(i, v); } - } } break; case Animation::TYPE_METHOD: { List indices; - animation->method_track_get_key_indices(i,p_time,p_delta,&indices); + animation->method_track_get_key_indices(i, p_time, p_delta, &indices); - for(List::Element *E=indices.front();E;E=E->next()) { + for (List::Element *E = indices.front(); E; E = E->next()) { - Vector args = animation->method_track_get_params(i,E->get()); - StringName name = animation->method_track_get_name(i,E->get()); + Vector args = animation->method_track_get_params(i, E->get()); + StringName name = animation->method_track_get_name(i, E->get()); Variant::CallError err; if (!args.size()) { - call_track(i,name,NULL,0,err); + call_track(i, name, NULL, 0, err); } else { - Vector argptrs; + Vector argptrs; argptrs.resize(args.size()); - for(int j=0;j& p_animation) { +void AnimationCache::set_animation(const Ref &p_animation) { _clear_cache(); if (animation.is_valid()) - animation->disconnect("changed",this,"_animation_changed"); + animation->disconnect("changed", this, "_animation_changed"); - animation=p_animation; + animation = p_animation; if (animation.is_valid()) - animation->connect("changed",this,"_animation_changed"); + animation->connect("changed", this, "_animation_changed"); } void AnimationCache::_bind_methods() { - ClassDB::bind_method(D_METHOD("_node_exit_tree"),&AnimationCache::_node_exit_tree); - ClassDB::bind_method(D_METHOD("_animation_changed"),&AnimationCache::_animation_changed); + ClassDB::bind_method(D_METHOD("_node_exit_tree"), &AnimationCache::_node_exit_tree); + ClassDB::bind_method(D_METHOD("_animation_changed"), &AnimationCache::_animation_changed); } -void AnimationCache::set_root(Node* p_root) { +void AnimationCache::set_root(Node *p_root) { _clear_cache(); - root=p_root; + root = p_root; } AnimationCache::AnimationCache() { - root=NULL; - cache_dirty=true; - cache_valid=false; + root = NULL; + cache_dirty = true; + cache_valid = false; } diff --git a/scene/animation/animation_cache.h b/scene/animation/animation_cache.h index 75e004c81..1668c6251 100644 --- a/scene/animation/animation_cache.h +++ b/scene/animation/animation_cache.h @@ -29,12 +29,12 @@ #ifndef ANIMATION_CACHE_H #define ANIMATION_CACHE_H -#include "scene/resources/animation.h" #include "scene/3d/skeleton.h" +#include "scene/resources/animation.h" class AnimationCache : public Object { - GDCLASS(AnimationCache,Object); + GDCLASS(AnimationCache, Object); struct Path { @@ -47,10 +47,17 @@ class AnimationCache : public Object { int bone_idx; StringName property; bool valid; - Path() { object=NULL; skeleton=NULL; node=NULL; bone_idx=-1; valid=false; spatial=NULL; } + Path() { + object = NULL; + skeleton = NULL; + node = NULL; + bone_idx = -1; + valid = false; + spatial = NULL; + } }; - Set connected_nodes; + Set connected_nodes; Vector path_cache; Node *root; @@ -65,19 +72,17 @@ class AnimationCache : public Object { void _animation_changed(); protected: - static void _bind_methods(); public: + void set_track_transform(int p_idx, const Transform &p_transform); + void set_track_value(int p_idx, const Variant &p_value); + void call_track(int p_idx, const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error); - void set_track_transform(int p_idx,const Transform& p_transform); - void set_track_value(int p_idx,const Variant& p_value); - void call_track(int p_idx,const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error); - - void set_all(float p_time, float p_delta=0); + void set_all(float p_time, float p_delta = 0); - void set_animation(const Ref& p_animation); - void set_root(Node* p_root); + void set_animation(const Ref &p_animation); + void set_root(Node *p_root); AnimationCache(); }; diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp index e9f1904fe..dc9aa1758 100644 --- a/scene/animation/animation_player.cpp +++ b/scene/animation/animation_player.cpp @@ -31,111 +31,104 @@ #include "message_queue.h" #include "scene/scene_string_names.h" -bool AnimationPlayer::_set(const StringName& p_name, const Variant& p_value) { +bool AnimationPlayer::_set(const StringName &p_name, const Variant &p_value) { - String name=p_name; + String name = p_name; - if (p_name==SceneStringNames::get_singleton()->playback_speed || p_name==SceneStringNames::get_singleton()->speed) { //bw compatibility + if (p_name == SceneStringNames::get_singleton()->playback_speed || p_name == SceneStringNames::get_singleton()->speed) { //bw compatibility set_speed_scale(p_value); - } else if (p_name==SceneStringNames::get_singleton()->playback_active) { + } else if (p_name == SceneStringNames::get_singleton()->playback_active) { set_active(p_value); } else if (name.begins_with("playback/play")) { - String which=p_value; + String which = p_value; - - if (which=="[stop]") + if (which == "[stop]") stop(); else play(which); } else if (name.begins_with("anims/")) { + String which = name.get_slicec('/', 1); - String which=name.get_slicec('/',1); - - add_animation(which,p_value); + add_animation(which, p_value); } else if (name.begins_with("next/")) { + String which = name.get_slicec('/', 1); + animation_set_next(which, p_value); - String which=name.get_slicec('/',1); - animation_set_next(which,p_value); - - } else if (p_name==SceneStringNames::get_singleton()->blend_times) { + } else if (p_name == SceneStringNames::get_singleton()->blend_times) { - Array array=p_value; + Array array = p_value; int len = array.size(); - ERR_FAIL_COND_V(len%3,false); + ERR_FAIL_COND_V(len % 3, false); + for (int i = 0; i < len / 3; i++) { - for(int i=0;iautoplay) { - autoplay=p_value; + } else if (p_name == SceneStringNames::get_singleton()->autoplay) { + autoplay = p_value; } else return false; return true; - } -bool AnimationPlayer::_get(const StringName& p_name,Variant &r_ret) const { +bool AnimationPlayer::_get(const StringName &p_name, Variant &r_ret) const { - String name=p_name; + String name = p_name; - if (name=="playback/speed") { //bw compatibility + if (name == "playback/speed") { //bw compatibility - r_ret=speed_scale; - } else if (name=="playback/active") { + r_ret = speed_scale; + } else if (name == "playback/active") { - r_ret=is_active(); - } else if (name=="playback/play") { + r_ret = is_active(); + } else if (name == "playback/play") { if (is_active() && is_playing()) - r_ret=playback.assigned; + r_ret = playback.assigned; else - r_ret="[stop]"; + r_ret = "[stop]"; } else if (name.begins_with("anims/")) { - String which=name.get_slicec('/',1); + String which = name.get_slicec('/', 1); - r_ret= get_animation(which).get_ref_ptr(); + r_ret = get_animation(which).get_ref_ptr(); } else if (name.begins_with("next/")) { - String which=name.get_slicec('/',1); + String which = name.get_slicec('/', 1); - r_ret= animation_get_next(which); + r_ret = animation_get_next(which); - - } else if (name=="blend_times") { + } else if (name == "blend_times") { Vector keys; - for(Map::Element *E=blend_times.front();E;E=E->next()) { + for (Map::Element *E = blend_times.front(); E; E = E->next()) { keys.ordered_insert(E->key()); } Array array; - for(int i=0;i *p_list) const { - - - +void AnimationPlayer::_get_property_list(List *p_list) const { List names; List anim_names; - for( Map::Element *E=animation_set.front();E;E=E->next()) { + for (Map::Element *E = animation_set.front(); E; E = E->next()) { - anim_names.push_back( PropertyInfo( Variant::OBJECT, "anims/"+String(E->key()), PROPERTY_HINT_RESOURCE_TYPE, "Animation",PROPERTY_USAGE_NOEDITOR) ); - if (E->get().next!=StringName()) - anim_names.push_back( PropertyInfo( Variant::STRING, "next/"+String(E->key()), PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR) ); + anim_names.push_back(PropertyInfo(Variant::OBJECT, "anims/" + String(E->key()), PROPERTY_HINT_RESOURCE_TYPE, "Animation", PROPERTY_USAGE_NOEDITOR)); + if (E->get().next != StringName()) + anim_names.push_back(PropertyInfo(Variant::STRING, "next/" + String(E->key()), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); names.push_back(E->key()); } anim_names.sort(); - for( List::Element *E=anim_names.front();E;E=E->next()) { + for (List::Element *E = anim_names.front(); E; E = E->next()) { p_list->push_back(E->get()); } @@ -170,34 +160,30 @@ void AnimationPlayer::_get_property_list( List *p_list) const { names.sort(); names.push_front("[stop]"); String hint; - for(List::Element *E=names.front();E;E=E->next()) { + for (List::Element *E = names.front(); E; E = E->next()) { - if (E!=names.front()) - hint+=","; - hint+=E->get(); + if (E != names.front()) + hint += ","; + hint += E->get(); } - p_list->push_back( PropertyInfo( Variant::STRING, "playback/play", PROPERTY_HINT_ENUM, hint,PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_ANIMATE_AS_TRIGGER) ); - p_list->push_back( PropertyInfo( Variant::BOOL, "playback/active", PROPERTY_HINT_NONE,"" ) ); - p_list->push_back( PropertyInfo( Variant::REAL, "playback/speed", PROPERTY_HINT_RANGE, "-64,64,0.01") ); - + p_list->push_back(PropertyInfo(Variant::STRING, "playback/play", PROPERTY_HINT_ENUM, hint, PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ANIMATE_AS_TRIGGER)); + p_list->push_back(PropertyInfo(Variant::BOOL, "playback/active", PROPERTY_HINT_NONE, "")); + p_list->push_back(PropertyInfo(Variant::REAL, "playback/speed", PROPERTY_HINT_RANGE, "-64,64,0.01")); } - - - p_list->push_back( PropertyInfo( Variant::ARRAY, "blend_times", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR) ); - p_list->push_back( PropertyInfo( Variant::STRING, "autoplay", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR) ); - + p_list->push_back(PropertyInfo(Variant::ARRAY, "blend_times", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::STRING, "autoplay", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); } void AnimationPlayer::advance(float p_time) { - _animation_process( p_time ); + _animation_process(p_time); } void AnimationPlayer::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { @@ -218,19 +204,19 @@ void AnimationPlayer::_notification(int p_what) { } } break; case NOTIFICATION_INTERNAL_PROCESS: { - if (animation_process_mode==ANIMATION_PROCESS_FIXED) + if (animation_process_mode == ANIMATION_PROCESS_FIXED) break; if (processing) - _animation_process( get_process_delta_time() ); + _animation_process(get_process_delta_time()); } break; case NOTIFICATION_INTERNAL_FIXED_PROCESS: { - if (animation_process_mode==ANIMATION_PROCESS_IDLE) + if (animation_process_mode == ANIMATION_PROCESS_IDLE) break; if (processing) - _animation_process( get_fixed_process_delta_time() ); + _animation_process(get_fixed_process_delta_time()); } break; case NOTIFICATION_EXIT_TREE: { @@ -240,174 +226,164 @@ void AnimationPlayer::_notification(int p_what) { } } -void AnimationPlayer::_generate_node_caches(AnimationData* p_anim) { +void AnimationPlayer::_generate_node_caches(AnimationData *p_anim) { Node *parent = get_node(root); ERR_FAIL_COND(!parent); - Animation *a=p_anim->animation.operator->(); + Animation *a = p_anim->animation.operator->(); - p_anim->node_cache.resize( a->get_track_count() ); + p_anim->node_cache.resize(a->get_track_count()); - for (int i=0;iget_track_count();i++) { + for (int i = 0; i < a->get_track_count(); i++) { - p_anim->node_cache[i]=NULL; + p_anim->node_cache[i] = NULL; RES resource; - Node *child = parent->get_node_and_resource(a->track_get_path(i),resource); + Node *child = parent->get_node_and_resource(a->track_get_path(i), resource); if (!child) { - ERR_EXPLAIN("On Animation: '"+p_anim->name+"', couldn't resolve track: '"+String(a->track_get_path(i))+"'"); + ERR_EXPLAIN("On Animation: '" + p_anim->name + "', couldn't resolve track: '" + String(a->track_get_path(i)) + "'"); } ERR_CONTINUE(!child); // couldn't find the child node - uint32_t id=resource.is_valid()?resource->get_instance_ID():child->get_instance_ID(); - int bone_idx=-1; + uint32_t id = resource.is_valid() ? resource->get_instance_ID() : child->get_instance_ID(); + int bone_idx = -1; if (a->track_get_path(i).get_property() && child->cast_to()) { - bone_idx = child->cast_to()->find_bone( a->track_get_path(i).get_property() ); - if (bone_idx==-1) { + bone_idx = child->cast_to()->find_bone(a->track_get_path(i).get_property()); + if (bone_idx == -1) { continue; } } { - if (!child->is_connected("tree_exited",this,"_node_removed")) - child->connect("tree_exited",this,"_node_removed",make_binds(child),CONNECT_ONESHOT); + if (!child->is_connected("tree_exited", this, "_node_removed")) + child->connect("tree_exited", this, "_node_removed", make_binds(child), CONNECT_ONESHOT); } TrackNodeCacheKey key; - key.id=id; - key.bone_idx=bone_idx; - + key.id = id; + key.bone_idx = bone_idx; if (node_cache_map.has(key)) { - p_anim->node_cache[i]=&node_cache_map[key]; + p_anim->node_cache[i] = &node_cache_map[key]; } else { + node_cache_map[key] = TrackNodeCache(); - node_cache_map[key]=TrackNodeCache(); - - p_anim->node_cache[i]=&node_cache_map[key]; - p_anim->node_cache[i]->path=a->track_get_path(i); - p_anim->node_cache[i]->node=child; - p_anim->node_cache[i]->resource=resource; - p_anim->node_cache[i]->node_2d=child->cast_to(); - if (a->track_get_type(i)==Animation::TYPE_TRANSFORM) { + p_anim->node_cache[i] = &node_cache_map[key]; + p_anim->node_cache[i]->path = a->track_get_path(i); + p_anim->node_cache[i]->node = child; + p_anim->node_cache[i]->resource = resource; + p_anim->node_cache[i]->node_2d = child->cast_to(); + if (a->track_get_type(i) == Animation::TYPE_TRANSFORM) { // special cases and caches for transform tracks // cache spatial - p_anim->node_cache[i]->spatial=child->cast_to(); + p_anim->node_cache[i]->spatial = child->cast_to(); // cache skeleton - p_anim->node_cache[i]->skeleton=child->cast_to(); + p_anim->node_cache[i]->skeleton = child->cast_to(); if (p_anim->node_cache[i]->skeleton) { - StringName bone_name=a->track_get_path(i).get_property(); - if (bone_name.operator String()!="") { + StringName bone_name = a->track_get_path(i).get_property(); + if (bone_name.operator String() != "") { - p_anim->node_cache[i]->bone_idx=p_anim->node_cache[i]->skeleton->find_bone(bone_name); - if (p_anim->node_cache[i]->bone_idx<0) { + p_anim->node_cache[i]->bone_idx = p_anim->node_cache[i]->skeleton->find_bone(bone_name); + if (p_anim->node_cache[i]->bone_idx < 0) { // broken track (nonexistent bone) - p_anim->node_cache[i]->skeleton=NULL; - p_anim->node_cache[i]->spatial=NULL; + p_anim->node_cache[i]->skeleton = NULL; + p_anim->node_cache[i]->spatial = NULL; printf("bone is %ls\n", String(bone_name).c_str()); - ERR_CONTINUE( p_anim->node_cache[i]->bone_idx<0 ); + ERR_CONTINUE(p_anim->node_cache[i]->bone_idx < 0); } else { } } else { // no property, just use spatialnode - p_anim->node_cache[i]->skeleton=NULL; + p_anim->node_cache[i]->skeleton = NULL; } - } } } - if (a->track_get_type(i)==Animation::TYPE_VALUE) { + if (a->track_get_type(i) == Animation::TYPE_VALUE) { StringName property = a->track_get_path(i).get_property(); if (!p_anim->node_cache[i]->property_anim.has(property)) { TrackNodeCache::PropertyAnim pa; - pa.prop=property; - pa.object=resource.is_valid()?(Object*)resource.ptr():(Object*)child; - pa.special=SP_NONE; - pa.owner=p_anim->node_cache[i]; + pa.prop = property; + pa.object = resource.is_valid() ? (Object *)resource.ptr() : (Object *)child; + pa.special = SP_NONE; + pa.owner = p_anim->node_cache[i]; if (false && p_anim->node_cache[i]->node_2d) { - if (pa.prop==SceneStringNames::get_singleton()->transform_pos) - pa.special=SP_NODE2D_POS; - else if (pa.prop==SceneStringNames::get_singleton()->transform_rot) - pa.special=SP_NODE2D_ROT; - else if (pa.prop==SceneStringNames::get_singleton()->transform_scale) - pa.special=SP_NODE2D_SCALE; + if (pa.prop == SceneStringNames::get_singleton()->transform_pos) + pa.special = SP_NODE2D_POS; + else if (pa.prop == SceneStringNames::get_singleton()->transform_rot) + pa.special = SP_NODE2D_ROT; + else if (pa.prop == SceneStringNames::get_singleton()->transform_scale) + pa.special = SP_NODE2D_SCALE; } - p_anim->node_cache[i]->property_anim[property]=pa; + p_anim->node_cache[i]->property_anim[property] = pa; } } } } - -void AnimationPlayer::_animation_process_animation(AnimationData* p_anim,float p_time, float p_delta,float p_interp, bool p_allow_discrete) { +void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, float p_time, float p_delta, float p_interp, bool p_allow_discrete) { if (p_anim->node_cache.size() != p_anim->animation->get_track_count()) { // animation hasn't been "node-cached" _generate_node_caches(p_anim); } + ERR_FAIL_COND(p_anim->node_cache.size() != p_anim->animation->get_track_count()); - ERR_FAIL_COND( p_anim->node_cache.size() != p_anim->animation->get_track_count() ); - - - Animation *a=p_anim->animation.operator->(); + Animation *a = p_anim->animation.operator->(); bool can_call = is_inside_tree() && !get_tree()->is_editor_hint(); - for (int i=0;iget_track_count();i++) { + for (int i = 0; i < a->get_track_count(); i++) { - TrackNodeCache *nc=p_anim->node_cache[i]; + TrackNodeCache *nc = p_anim->node_cache[i]; if (!nc) // no node cache for this track, skip it continue; - if (a->track_get_key_count(i)==0) + if (a->track_get_key_count(i) == 0) continue; // do nothing if track is empty - switch(a->track_get_type(i)) { + switch (a->track_get_type(i)) { case Animation::TYPE_TRANSFORM: { if (!nc->spatial) continue; - Vector3 loc; Quat rot; Vector3 scale; - - Error err = a->transform_track_interpolate(i,p_time,&loc,&rot,&scale); + Error err = a->transform_track_interpolate(i, p_time, &loc, &rot, &scale); //ERR_CONTINUE(err!=OK); //used for testing, should be removed - - if (err!=OK) + if (err != OK) continue; - if (nc->accum_pass!=accum_pass) { - ERR_CONTINUE( cache_update_size >= NODE_CACHE_UPDATE_MAX ); - cache_update[cache_update_size++]=nc; - nc->accum_pass=accum_pass; - nc->loc_accum=loc; - nc->rot_accum=rot; - nc->scale_accum=scale; + if (nc->accum_pass != accum_pass) { + ERR_CONTINUE(cache_update_size >= NODE_CACHE_UPDATE_MAX); + cache_update[cache_update_size++] = nc; + nc->accum_pass = accum_pass; + nc->loc_accum = loc; + nc->rot_accum = rot; + nc->scale_accum = scale; } else { - nc->loc_accum=nc->loc_accum.linear_interpolate(loc,p_interp); - nc->rot_accum=nc->rot_accum.slerp(rot,p_interp); - nc->scale_accum=nc->scale_accum.linear_interpolate(scale,p_interp); - + nc->loc_accum = nc->loc_accum.linear_interpolate(loc, p_interp); + nc->rot_accum = nc->rot_accum.slerp(rot, p_interp); + nc->scale_accum = nc->scale_accum.linear_interpolate(scale, p_interp); } } break; @@ -418,82 +394,76 @@ void AnimationPlayer::_animation_process_animation(AnimationData* p_anim,float p //StringName property=a->track_get_path(i).get_property(); - Map::Element *E=nc->property_anim.find(a->track_get_path(i).get_property()); + Map::Element *E = nc->property_anim.find(a->track_get_path(i).get_property()); ERR_CONTINUE(!E); //should it continue, or create a new one? TrackNodeCache::PropertyAnim *pa = &E->get(); + if (a->value_track_get_update_mode(i) == Animation::UPDATE_CONTINUOUS || (p_delta == 0 && a->value_track_get_update_mode(i) == Animation::UPDATE_DISCRETE)) { //delta == 0 means seek - if (a->value_track_get_update_mode(i)==Animation::UPDATE_CONTINUOUS || (p_delta==0 && a->value_track_get_update_mode(i)==Animation::UPDATE_DISCRETE)) { //delta == 0 means seek - - - Variant value=a->value_track_interpolate(i,p_time); + Variant value = a->value_track_interpolate(i, p_time); //thanks to trigger mode, this should be solved now.. /* if (p_delta==0 && value.get_type()==Variant::STRING) continue; // doing this with strings is messy, should find another way */ - if (pa->accum_pass!=accum_pass) { - ERR_CONTINUE( cache_update_prop_size >= NODE_CACHE_UPDATE_MAX ); - cache_update_prop[cache_update_prop_size++]=pa; - pa->value_accum=value; - pa->accum_pass=accum_pass; + if (pa->accum_pass != accum_pass) { + ERR_CONTINUE(cache_update_prop_size >= NODE_CACHE_UPDATE_MAX); + cache_update_prop[cache_update_prop_size++] = pa; + pa->value_accum = value; + pa->accum_pass = accum_pass; } else { - Variant::interpolate(pa->value_accum,value,p_interp,pa->value_accum); + Variant::interpolate(pa->value_accum, value, p_interp, pa->value_accum); } - - } else if (p_allow_discrete && p_delta!=0) { + } else if (p_allow_discrete && p_delta != 0) { List indices; - a->value_track_get_key_indices(i,p_time,p_delta,&indices); - + a->value_track_get_key_indices(i, p_time, p_delta, &indices); - for(List::Element *F=indices.front();F;F=F->next()) { + for (List::Element *F = indices.front(); F; F = F->next()) { - Variant value=a->track_get_key_value(i,F->get()); - switch(pa->special) { + Variant value = a->track_get_key_value(i, F->get()); + switch (pa->special) { case SP_NONE: { bool valid; - pa->object->set(pa->prop,value,&valid); //you are not speshul + pa->object->set(pa->prop, value, &valid); //you are not speshul #ifdef DEBUG_ENABLED if (!valid) { - ERR_PRINTS("Failed setting track value '"+String(pa->owner->path)+"'. Check if property exists or the type of key is valid"); + ERR_PRINTS("Failed setting track value '" + String(pa->owner->path) + "'. Check if property exists or the type of key is valid"); } #endif } break; case SP_NODE2D_POS: { #ifdef DEBUG_ENABLED - if (value.get_type()!=Variant::VECTOR2) { - ERR_PRINTS("Position key at time "+rtos(p_time)+" in Animation Track '"+String(pa->owner->path)+"' not of type Vector2()"); + if (value.get_type() != Variant::VECTOR2) { + ERR_PRINTS("Position key at time " + rtos(p_time) + " in Animation Track '" + String(pa->owner->path) + "' not of type Vector2()"); } #endif - static_cast(pa->object)->set_position(value); + static_cast(pa->object)->set_position(value); } break; case SP_NODE2D_ROT: { #ifdef DEBUG_ENABLED if (value.is_num()) { - ERR_PRINTS("Rotation key at time "+rtos(p_time)+" in Animation Track '"+String(pa->owner->path)+"' not numerical"); + ERR_PRINTS("Rotation key at time " + rtos(p_time) + " in Animation Track '" + String(pa->owner->path) + "' not numerical"); } #endif - static_cast(pa->object)->set_rotation(Math::deg2rad((double)value)); + static_cast(pa->object)->set_rotation(Math::deg2rad((double)value)); } break; case SP_NODE2D_SCALE: { #ifdef DEBUG_ENABLED - if (value.get_type()!=Variant::VECTOR2) { - ERR_PRINTS("Scale key at time "+rtos(p_time)+" in Animation Track '"+String(pa->owner->path)+"' not of type Vector2()"); + if (value.get_type() != Variant::VECTOR2) { + ERR_PRINTS("Scale key at time " + rtos(p_time) + " in Animation Track '" + String(pa->owner->path) + "' not of type Vector2()"); } #endif - static_cast(pa->object)->set_scale(value); + static_cast(pa->object)->set_scale(value); } break; } - } - } } break; @@ -501,154 +471,142 @@ void AnimationPlayer::_animation_process_animation(AnimationData* p_anim,float p if (!nc->node) continue; - if (p_delta==0) + if (p_delta == 0) continue; if (!p_allow_discrete) break; List indices; - a->method_track_get_key_indices(i,p_time,p_delta,&indices); + a->method_track_get_key_indices(i, p_time, p_delta, &indices); - for(List::Element *E=indices.front();E;E=E->next()) { + for (List::Element *E = indices.front(); E; E = E->next()) { - StringName method=a->method_track_get_name(i,E->get()); - Vector params=a->method_track_get_params(i,E->get()); + StringName method = a->method_track_get_name(i, E->get()); + Vector params = a->method_track_get_params(i, E->get()); - int s=params.size(); + int s = params.size(); - ERR_CONTINUE( s > VARIANT_ARG_MAX ); + ERR_CONTINUE(s > VARIANT_ARG_MAX); if (can_call) { MessageQueue::get_singleton()->push_call( - nc->node, - method, - s>=1 ? params[0] : Variant(), - s>=2 ? params[1] : Variant(), - s>=3 ? params[2] : Variant(), - s>=4 ? params[3] : Variant(), - s>=5 ? params[4] : Variant() - ); + nc->node, + method, + s >= 1 ? params[0] : Variant(), + s >= 2 ? params[1] : Variant(), + s >= 3 ? params[2] : Variant(), + s >= 4 ? params[3] : Variant(), + s >= 5 ? params[4] : Variant()); } } - } break; } } } -void AnimationPlayer::_animation_process_data(PlaybackData &cd,float p_delta,float p_blend) { +void AnimationPlayer::_animation_process_data(PlaybackData &cd, float p_delta, float p_blend) { - float delta=p_delta*speed_scale*cd.speed_scale; - bool backwards=delta<0; - float next_pos=cd.pos+delta; + float delta = p_delta * speed_scale * cd.speed_scale; + bool backwards = delta < 0; + float next_pos = cd.pos + delta; - float len=cd.from->animation->get_length(); - bool loop=cd.from->animation->has_loop(); + float len = cd.from->animation->get_length(); + bool loop = cd.from->animation->has_loop(); if (!loop) { - if (next_pos<0) - next_pos=0; - else if (next_pos>len) - next_pos=len; + if (next_pos < 0) + next_pos = 0; + else if (next_pos > len) + next_pos = len; // fix delta - delta=next_pos-cd.pos; + delta = next_pos - cd.pos; if (&cd == &playback.current) { - if (!backwards && cd.pos < len && next_pos==len /*&& playback.blend.empty()*/) { + if (!backwards && cd.pos < len && next_pos == len /*&& playback.blend.empty()*/) { //playback finished - end_notify=true; + end_notify = true; } - if (backwards && cd.pos > 0 && next_pos==0 /*&& playback.blend.empty()*/) { + if (backwards && cd.pos > 0 && next_pos == 0 /*&& playback.blend.empty()*/) { //playback finished - end_notify=true; + end_notify = true; } - } } else { - next_pos=Math::fposmod(next_pos,len); - + next_pos = Math::fposmod(next_pos, len); } - cd.pos=next_pos; - - _animation_process_animation(cd.from,cd.pos,delta,p_blend,&cd == &playback.current); - - + cd.pos = next_pos; + _animation_process_animation(cd.from, cd.pos, delta, p_blend, &cd == &playback.current); } void AnimationPlayer::_animation_process2(float p_delta) { - - Playback &c=playback; + Playback &c = playback; accum_pass++; - _animation_process_data(c.current,p_delta,1.0f); + _animation_process_data(c.current, p_delta, 1.0f); List::Element *prev = NULL; - for (List::Element *E=c.blend.back();E;E=prev) { + for (List::Element *E = c.blend.back(); E; E = prev) { - Blend& b=E->get(); - float blend=b.blend_left/b.blend_time; - _animation_process_data(b.data,p_delta,blend); + Blend &b = E->get(); + float blend = b.blend_left / b.blend_time; + _animation_process_data(b.data, p_delta, blend); - b.blend_left-=Math::absf(speed_scale*p_delta); + b.blend_left -= Math::absf(speed_scale * p_delta); prev = E->prev(); - if (b.blend_left<0) { + if (b.blend_left < 0) { c.blend.erase(E); } } - - } void AnimationPlayer::_animation_update_transforms() { + for (int i = 0; i < cache_update_size; i++) { - for (int i=0;iaccum_pass!=accum_pass ); + ERR_CONTINUE(nc->accum_pass != accum_pass); if (nc->spatial) { Transform t; - t.origin=nc->loc_accum; - t.basis=nc->rot_accum; - t.basis.scale( nc->scale_accum ); + t.origin = nc->loc_accum; + t.basis = nc->rot_accum; + t.basis.scale(nc->scale_accum); - if (nc->skeleton && nc->bone_idx>=0) { + if (nc->skeleton && nc->bone_idx >= 0) { - nc->skeleton->set_bone_pose( nc->bone_idx, t ); + nc->skeleton->set_bone_pose(nc->bone_idx, t); } else if (nc->spatial) { nc->spatial->set_transform(t); } } - } - cache_update_size=0; + cache_update_size = 0; - for (int i=0;iaccum_pass!=accum_pass ); + ERR_CONTINUE(pa->accum_pass != accum_pass); #if 1 -/* switch(pa->special) { + /* switch(pa->special) { case SP_NONE: pa->object->set(pa->prop,pa->value_accum); break; //you are not speshul @@ -657,63 +615,61 @@ void AnimationPlayer::_animation_update_transforms() { case SP_NODE2D_SCALE: static_cast(pa->object)->set_scale(pa->value_accum); break; }*/ - switch(pa->special) { + switch (pa->special) { case SP_NONE: { bool valid; - pa->object->set(pa->prop,pa->value_accum,&valid); //you are not speshul + pa->object->set(pa->prop, pa->value_accum, &valid); //you are not speshul #ifdef DEBUG_ENABLED if (!valid) { - ERR_PRINTS("Failed setting key at time "+rtos(playback.current.pos)+" in Animation '"+get_current_animation()+"', Track '"+String(pa->owner->path)+"'. Check if property exists or the type of key is right for the property"); + ERR_PRINTS("Failed setting key at time " + rtos(playback.current.pos) + " in Animation '" + get_current_animation() + "', Track '" + String(pa->owner->path) + "'. Check if property exists or the type of key is right for the property"); } #endif } break; case SP_NODE2D_POS: { #ifdef DEBUG_ENABLED - if (pa->value_accum.get_type()!=Variant::VECTOR2) { - ERR_PRINTS("Position key at time "+rtos(playback.current.pos)+" in Animation '"+get_current_animation()+"', Track '"+String(pa->owner->path)+"' not of type Vector2()"); + if (pa->value_accum.get_type() != Variant::VECTOR2) { + ERR_PRINTS("Position key at time " + rtos(playback.current.pos) + " in Animation '" + get_current_animation() + "', Track '" + String(pa->owner->path) + "' not of type Vector2()"); } #endif - static_cast(pa->object)->set_position(pa->value_accum); + static_cast(pa->object)->set_position(pa->value_accum); } break; case SP_NODE2D_ROT: { #ifdef DEBUG_ENABLED if (pa->value_accum.is_num()) { - ERR_PRINTS("Rotation key at time "+rtos(playback.current.pos)+" in Animation '"+get_current_animation()+"', Track '"+String(pa->owner->path)+"' not numerical"); + ERR_PRINTS("Rotation key at time " + rtos(playback.current.pos) + " in Animation '" + get_current_animation() + "', Track '" + String(pa->owner->path) + "' not numerical"); } #endif - static_cast(pa->object)->set_rotation(Math::deg2rad((double)pa->value_accum)); + static_cast(pa->object)->set_rotation(Math::deg2rad((double)pa->value_accum)); } break; case SP_NODE2D_SCALE: { #ifdef DEBUG_ENABLED - if (pa->value_accum.get_type()!=Variant::VECTOR2) { - ERR_PRINTS("Scale key at time "+rtos(playback.current.pos)+" in Animation '"+get_current_animation()+"', Track '"+String(pa->owner->path)+"' not of type Vector2()"); + if (pa->value_accum.get_type() != Variant::VECTOR2) { + ERR_PRINTS("Scale key at time " + rtos(playback.current.pos) + " in Animation '" + get_current_animation() + "', Track '" + String(pa->owner->path) + "' not of type Vector2()"); } #endif - static_cast(pa->object)->set_scale(pa->value_accum); + static_cast(pa->object)->set_scale(pa->value_accum); } break; } #else - pa->object->set(pa->prop,pa->value_accum); + pa->object->set(pa->prop, pa->value_accum); #endif } - cache_update_prop_size=0; + cache_update_prop_size = 0; } void AnimationPlayer::_animation_process(float p_delta) { - - //bool any_active=false; if (playback.current.from) { - end_notify=false; + end_notify = false; _animation_process2(p_delta); _animation_update_transforms(); if (end_notify) { @@ -722,46 +678,44 @@ void AnimationPlayer::_animation_process(float p_delta) { play(queued.front()->get()); String new_name = playback.assigned; queued.pop_front(); - end_notify=false; + end_notify = false; emit_signal(SceneStringNames::get_singleton()->animation_changed, old, new_name); } else { - //stop(); + //stop(); playing = false; _set_process(false); - end_notify=false; - emit_signal(SceneStringNames::get_singleton()->animation_finished,playback.assigned); + end_notify = false; + emit_signal(SceneStringNames::get_singleton()->animation_finished, playback.assigned); } } } else { _set_process(false); } - } - -Error AnimationPlayer::add_animation(const StringName& p_name, const Ref& p_animation) { +Error AnimationPlayer::add_animation(const StringName &p_name, const Ref &p_animation) { #ifdef DEBUG_ENABLED - ERR_EXPLAIN("Invalid animation name: "+String(p_name)); - ERR_FAIL_COND_V( String(p_name).find("/")!=-1 || String(p_name).find(":")!=-1 || String(p_name).find(",")!=-1 || String(p_name).find("[")!=-1, ERR_INVALID_PARAMETER ); + ERR_EXPLAIN("Invalid animation name: " + String(p_name)); + ERR_FAIL_COND_V(String(p_name).find("/") != -1 || String(p_name).find(":") != -1 || String(p_name).find(",") != -1 || String(p_name).find("[") != -1, ERR_INVALID_PARAMETER); #endif - ERR_FAIL_COND_V( p_animation.is_null() , ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_animation.is_null(), ERR_INVALID_PARAMETER); //print_line("Add anim: "+String(p_name)+" name: "+p_animation->get_name()); if (animation_set.has(p_name)) { _unref_anim(animation_set[p_name].animation); - animation_set[p_name].animation=p_animation; + animation_set[p_name].animation = p_animation; clear_caches(); } else { AnimationData ad; - ad.animation=p_animation; - ad.name=p_name; - animation_set[p_name]=ad; + ad.animation = p_animation; + ad.name = p_name; + animation_set[p_name] = ad; } _ref_anim(p_animation); @@ -769,9 +723,9 @@ Error AnimationPlayer::add_animation(const StringName& p_name, const Ref& p_anim) { +void AnimationPlayer::_ref_anim(const Ref &p_anim) { if (used_anims.has(p_anim)) used_anims[p_anim]++; else { - used_anims[p_anim]=1; - Ref(p_anim)->connect("changed",this,"_animation_changed"); + used_anims[p_anim] = 1; + Ref(p_anim)->connect("changed", this, "_animation_changed"); } - } -void AnimationPlayer::_unref_anim(const Ref& p_anim) { +void AnimationPlayer::_unref_anim(const Ref &p_anim) { ERR_FAIL_COND(!used_anims.has(p_anim)); - - int & n = used_anims[p_anim]; + int &n = used_anims[p_anim]; n--; - if (n==0) { + if (n == 0) { - Ref(p_anim)->disconnect("changed",this,"_animation_changed"); + Ref(p_anim)->disconnect("changed", this, "_animation_changed"); used_anims.erase(p_anim); } - } +void AnimationPlayer::rename_animation(const StringName &p_name, const StringName &p_new_name) { -void AnimationPlayer::rename_animation(const StringName& p_name,const StringName& p_new_name) { - - - ERR_FAIL_COND(!animation_set.has(p_name) ); - ERR_FAIL_COND( String(p_new_name).find("/")!=-1 || String(p_new_name).find(":")!=-1 ); - ERR_FAIL_COND( animation_set.has(p_new_name) ); + ERR_FAIL_COND(!animation_set.has(p_name)); + ERR_FAIL_COND(String(p_new_name).find("/") != -1 || String(p_new_name).find(":") != -1); + ERR_FAIL_COND(animation_set.has(p_new_name)); //print_line("Rename anim: "+String(p_name)+" name: "+String(p_new_name)); stop_all(); AnimationData ad = animation_set[p_name]; - ad.name=p_new_name; + ad.name = p_new_name; animation_set.erase(p_name); - animation_set[p_new_name]=ad; + animation_set[p_new_name] = ad; List to_erase; - Map to_insert; - for(Map::Element *E=blend_times.front();E;E=E->next()) { - - BlendKey bk=E->key(); - BlendKey new_bk=bk; - bool erase=false; - if (bk.from==p_name) { - new_bk.from=p_new_name; - erase=true; + Map to_insert; + for (Map::Element *E = blend_times.front(); E; E = E->next()) { + + BlendKey bk = E->key(); + BlendKey new_bk = bk; + bool erase = false; + if (bk.from == p_name) { + new_bk.from = p_new_name; + erase = true; } - if (bk.to==p_name) { - new_bk.to=p_new_name; - erase=true; + if (bk.to == p_name) { + new_bk.to = p_new_name; + erase = true; } if (erase) { to_erase.push_back(bk); - to_insert[new_bk]=E->get(); + to_insert[new_bk] = E->get(); } } - while(to_erase.size()) { + while (to_erase.size()) { blend_times.erase(to_erase.front()->get()); to_erase.pop_front(); } - while(to_insert.size()) { - blend_times[to_insert.front()->key()]=to_insert.front()->get(); + while (to_insert.size()) { + blend_times[to_insert.front()->key()] = to_insert.front()->get(); to_insert.erase(to_insert.front()); } - if (autoplay==p_name) - autoplay=p_new_name; + if (autoplay == p_name) + autoplay = p_new_name; clear_caches(); _change_notify(); } - -bool AnimationPlayer::has_animation(const StringName& p_name) const { +bool AnimationPlayer::has_animation(const StringName &p_name) const { return animation_set.has(p_name); } -Ref AnimationPlayer::get_animation(const StringName& p_name) const { +Ref AnimationPlayer::get_animation(const StringName &p_name) const { - ERR_FAIL_COND_V( !animation_set.has(p_name), Ref() ); + ERR_FAIL_COND_V(!animation_set.has(p_name), Ref()); - const AnimationData& data = animation_set[p_name]; + const AnimationData &data = animation_set[p_name]; return data.animation; - } -void AnimationPlayer::get_animation_list( List * p_animations) const { +void AnimationPlayer::get_animation_list(List *p_animations) const { List anims; - for( Map::Element *E=animation_set.front();E;E=E->next()) { + for (Map::Element *E = animation_set.front(); E; E = E->next()) { anims.push_back(E->key()); } anims.sort(); - for(List::Element *E=anims.front();E;E=E->next()) { + for (List::Element *E = anims.front(); E; E = E->next()) { p_animations->push_back(E->get()); } - } -void AnimationPlayer::set_blend_time(const StringName& p_animation1, const StringName& p_animation2, float p_time) { +void AnimationPlayer::set_blend_time(const StringName &p_animation1, const StringName &p_animation2, float p_time) { - ERR_FAIL_COND(p_time<0); + ERR_FAIL_COND(p_time < 0); BlendKey bk; - bk.from=p_animation1; - bk.to=p_animation2; - if (p_time==0) + bk.from = p_animation1; + bk.to = p_animation2; + if (p_time == 0) blend_times.erase(bk); else - blend_times[bk]=p_time; - + blend_times[bk] = p_time; } - -float AnimationPlayer::get_blend_time( const StringName& p_animation1, const StringName& p_animation2) const { +float AnimationPlayer::get_blend_time(const StringName &p_animation1, const StringName &p_animation2) const { BlendKey bk; - bk.from=p_animation1; - bk.to=p_animation2; + bk.from = p_animation1; + bk.to = p_animation2; if (blend_times.has(bk)) return blend_times[bk]; else return 0; - - } - -void AnimationPlayer::queue(const StringName& p_name) { +void AnimationPlayer::queue(const StringName &p_name) { if (!is_playing()) play(p_name); @@ -938,73 +878,73 @@ void AnimationPlayer::clear_queue() { queued.clear(); }; -void AnimationPlayer::play_backwards(const StringName& p_name,float p_custom_blend) { +void AnimationPlayer::play_backwards(const StringName &p_name, float p_custom_blend) { - play(p_name,p_custom_blend,-1,true); + play(p_name, p_custom_blend, -1, true); } -void AnimationPlayer::play(const StringName& p_name, float p_custom_blend, float p_custom_scale,bool p_from_end) { +void AnimationPlayer::play(const StringName &p_name, float p_custom_blend, float p_custom_scale, bool p_from_end) { //printf("animation is %ls\n", String(p_name).c_str()); //ERR_FAIL_COND(!is_inside_scene()); - StringName name=p_name; + StringName name = p_name; - if (String(name)=="") - name=playback.assigned; + if (String(name) == "") + name = playback.assigned; if (!animation_set.has(name)) { - ERR_EXPLAIN("Animation not found: "+name); + ERR_EXPLAIN("Animation not found: " + name); ERR_FAIL(); } - Playback &c=playback; + Playback &c = playback; if (c.current.from) { - float blend_time=0; + float blend_time = 0; // find if it can blend BlendKey bk; - bk.from=c.current.from->name; - bk.to=name; + bk.from = c.current.from->name; + bk.to = name; - if (p_custom_blend>=0) { - blend_time=p_custom_blend; + if (p_custom_blend >= 0) { + blend_time = p_custom_blend; } else if (blend_times.has(bk)) { - blend_time=blend_times[bk]; + blend_time = blend_times[bk]; } else { - bk.from="*"; + bk.from = "*"; if (blend_times.has(bk)) { - blend_time=blend_times[bk]; + blend_time = blend_times[bk]; } else { - bk.from=c.current.from->name; - bk.to="*"; + bk.from = c.current.from->name; + bk.to = "*"; if (blend_times.has(bk)) { - blend_time=blend_times[bk]; + blend_time = blend_times[bk]; } } } - if (p_custom_blend<0 && blend_time==0 && default_blend_time) - blend_time=default_blend_time; - if (blend_time>0) { + if (p_custom_blend < 0 && blend_time == 0 && default_blend_time) + blend_time = default_blend_time; + if (blend_time > 0) { Blend b; - b.data=c.current; - b.blend_time=b.blend_left=blend_time; + b.data = c.current; + b.blend_time = b.blend_left = blend_time; c.blend.push_back(b); } } - c.current.from=&animation_set[name]; - c.current.pos=p_from_end ? c.current.from->animation->get_length() : 0; - c.current.speed_scale=p_custom_scale; - c.assigned=p_name; + c.current.from = &animation_set[name]; + c.current.pos = p_from_end ? c.current.from->animation->get_length() : 0; + c.current.speed_scale = p_custom_scale; + c.assigned = p_name; if (!end_notify) queued.clear(); @@ -1013,20 +953,19 @@ void AnimationPlayer::play(const StringName& p_name, float p_custom_blend, float emit_signal(SceneStringNames::get_singleton()->animation_started, c.assigned); - if (is_inside_tree() && get_tree()->is_editor_hint()) + if (is_inside_tree() && get_tree()->is_editor_hint()) return; // no next in this case - - StringName next=animation_get_next(p_name); - if (next!=StringName() && animation_set.has(next)) { + StringName next = animation_get_next(p_name); + if (next != StringName() && animation_set.has(next)) { queue(next); } } bool AnimationPlayer::is_playing() const { - return playing; - /* + return playing; + /* if (playback.current.from==NULL) return false; @@ -1040,30 +979,29 @@ bool AnimationPlayer::is_playing() const { return true; */ } -void AnimationPlayer::set_current_animation(const String& p_anim) { +void AnimationPlayer::set_current_animation(const String &p_anim) { if (is_playing()) { play(p_anim); } else { ERR_FAIL_COND(!animation_set.has(p_anim)); - playback.current.pos=0; - playback.current.from=&animation_set[p_anim]; - playback.assigned=p_anim; + playback.current.pos = 0; + playback.current.from = &animation_set[p_anim]; + playback.assigned = p_anim; } } String AnimationPlayer::get_current_animation() const { return (playback.assigned); - } void AnimationPlayer::stop(bool p_reset) { - Playback &c=playback; + Playback &c = playback; c.blend.clear(); if (p_reset) { - c.current.from=NULL; + c.current.from = NULL; } _set_process(false); queued.clear(); @@ -1075,22 +1013,18 @@ void AnimationPlayer::stop_all() { stop(); _set_process(false); // always process when starting an animation - } void AnimationPlayer::set_speed_scale(float p_speed) { - speed_scale=p_speed; - - + speed_scale = p_speed; } float AnimationPlayer::get_speed_scale() const { return speed_scale; } -void AnimationPlayer::seek(float p_time,bool p_update) { - +void AnimationPlayer::seek(float p_time, bool p_update) { if (!playback.current.from) { if (playback.assigned) @@ -1098,13 +1032,13 @@ void AnimationPlayer::seek(float p_time,bool p_update) { ERR_FAIL_COND(!playback.current.from); } - playback.current.pos=p_time; + playback.current.pos = p_time; if (p_update) { _animation_process(0); } } -void AnimationPlayer::seek_delta(float p_time,float p_delta) { +void AnimationPlayer::seek_delta(float p_time, float p_delta) { if (!playback.current.from) { if (playback.assigned) @@ -1112,30 +1046,27 @@ void AnimationPlayer::seek_delta(float p_time,float p_delta) { ERR_FAIL_COND(!playback.current.from); } - - playback.current.pos=p_time-p_delta; - if (speed_scale!=0.0) - p_delta/=speed_scale; + playback.current.pos = p_time - p_delta; + if (speed_scale != 0.0) + p_delta /= speed_scale; _animation_process(p_delta); //playback.current.pos=p_time; - } bool AnimationPlayer::is_valid() const { return (playback.current.from); - } float AnimationPlayer::get_current_animation_pos() const { - ERR_FAIL_COND_V(!playback.current.from,0); + ERR_FAIL_COND_V(!playback.current.from, 0); return playback.current.pos; } float AnimationPlayer::get_current_animation_length() const { - ERR_FAIL_COND_V(!playback.current.from,0); + ERR_FAIL_COND_V(!playback.current.from, 0); return playback.current.from->animation->get_length(); } @@ -1151,27 +1082,24 @@ void AnimationPlayer::_node_removed(Node *p_node) { void AnimationPlayer::clear_caches() { - node_cache_map.clear(); - for( Map::Element *E=animation_set.front();E;E=E->next()) { + for (Map::Element *E = animation_set.front(); E; E = E->next()) { E->get().node_cache.clear(); } - cache_update_size=0; - cache_update_prop_size=0; + cache_update_size = 0; + cache_update_prop_size = 0; } void AnimationPlayer::set_active(bool p_active) { - if (active==p_active) + if (active == p_active) return; - active=p_active; - _set_process(processing,true); - - + active = p_active; + _set_process(processing, true); } bool AnimationPlayer::is_active() const { @@ -1179,90 +1107,85 @@ bool AnimationPlayer::is_active() const { return active; } -StringName AnimationPlayer::find_animation(const Ref& p_animation) const { +StringName AnimationPlayer::find_animation(const Ref &p_animation) const { - for( Map::Element *E=animation_set.front();E;E=E->next()) { + for (Map::Element *E = animation_set.front(); E; E = E->next()) { - if (E->get().animation==p_animation) + if (E->get().animation == p_animation) return E->key(); } return ""; } -void AnimationPlayer::set_autoplay(const String& p_name) { +void AnimationPlayer::set_autoplay(const String &p_name) { - autoplay=p_name; + autoplay = p_name; } -String AnimationPlayer::get_autoplay() const{ +String AnimationPlayer::get_autoplay() const { return autoplay; } void AnimationPlayer::set_animation_process_mode(AnimationProcessMode p_mode) { - if (animation_process_mode==p_mode) + if (animation_process_mode == p_mode) return; bool pr = processing; if (pr) _set_process(false); - animation_process_mode=p_mode; + animation_process_mode = p_mode; if (pr) _set_process(true); - } -AnimationPlayer::AnimationProcessMode AnimationPlayer::get_animation_process_mode() const{ +AnimationPlayer::AnimationProcessMode AnimationPlayer::get_animation_process_mode() const { return animation_process_mode; } +void AnimationPlayer::_set_process(bool p_process, bool p_force) { -void AnimationPlayer::_set_process(bool p_process,bool p_force) { - - if (processing==p_process && !p_force) + if (processing == p_process && !p_force) return; - switch(animation_process_mode) { + switch (animation_process_mode) { case ANIMATION_PROCESS_FIXED: set_fixed_process_internal(p_process && active); break; case ANIMATION_PROCESS_IDLE: set_process_internal(p_process && active); break; } - processing=p_process; + processing = p_process; } -void AnimationPlayer::animation_set_next(const StringName& p_animation, const StringName& p_next) { +void AnimationPlayer::animation_set_next(const StringName &p_animation, const StringName &p_next) { ERR_FAIL_COND(!animation_set.has(p_animation)); - animation_set[p_animation].next=p_next; - + animation_set[p_animation].next = p_next; } -StringName AnimationPlayer::animation_get_next(const StringName& p_animation) const{ +StringName AnimationPlayer::animation_get_next(const StringName &p_animation) const { if (!animation_set.has(p_animation)) return StringName(); return animation_set[p_animation].next; - } void AnimationPlayer::set_default_blend_time(float p_default) { - default_blend_time=p_default; + default_blend_time = p_default; } float AnimationPlayer::get_default_blend_time() const { - return default_blend_time; + return default_blend_time; } +void AnimationPlayer::set_root(const NodePath &p_root) { -void AnimationPlayer::set_root(const NodePath& p_root) { - - root=p_root; + root = p_root; clear_caches(); } @@ -1271,111 +1194,105 @@ NodePath AnimationPlayer::get_root() const { return root; } -void AnimationPlayer::get_argument_options(const StringName& p_function,int p_idx,List*r_options) const { +void AnimationPlayer::get_argument_options(const StringName &p_function, int p_idx, List *r_options) const { String pf = p_function; - if (p_function=="play" || p_function=="remove_animation" || p_function=="has_animation" || p_function=="queue") { + if (p_function == "play" || p_function == "remove_animation" || p_function == "has_animation" || p_function == "queue") { List al; get_animation_list(&al); - for (List::Element *E=al.front();E;E=E->next()) { + for (List::Element *E = al.front(); E; E = E->next()) { - r_options->push_back("\""+String(E->get())+"\""); + r_options->push_back("\"" + String(E->get()) + "\""); } } - Node::get_argument_options(p_function,p_idx,r_options); + Node::get_argument_options(p_function, p_idx, r_options); } void AnimationPlayer::_bind_methods() { - ClassDB::bind_method(D_METHOD("_node_removed"),&AnimationPlayer::_node_removed); - ClassDB::bind_method(D_METHOD("_animation_changed"),&AnimationPlayer::_animation_changed); + ClassDB::bind_method(D_METHOD("_node_removed"), &AnimationPlayer::_node_removed); + ClassDB::bind_method(D_METHOD("_animation_changed"), &AnimationPlayer::_animation_changed); - ClassDB::bind_method(D_METHOD("add_animation","name","animation:Animation"),&AnimationPlayer::add_animation); - ClassDB::bind_method(D_METHOD("remove_animation","name"),&AnimationPlayer::remove_animation); - ClassDB::bind_method(D_METHOD("rename_animation","name","newname"),&AnimationPlayer::rename_animation); - ClassDB::bind_method(D_METHOD("has_animation","name"),&AnimationPlayer::has_animation); - ClassDB::bind_method(D_METHOD("get_animation:Animation","name"),&AnimationPlayer::get_animation); - ClassDB::bind_method(D_METHOD("get_animation_list"),&AnimationPlayer::_get_animation_list); + ClassDB::bind_method(D_METHOD("add_animation", "name", "animation:Animation"), &AnimationPlayer::add_animation); + ClassDB::bind_method(D_METHOD("remove_animation", "name"), &AnimationPlayer::remove_animation); + ClassDB::bind_method(D_METHOD("rename_animation", "name", "newname"), &AnimationPlayer::rename_animation); + ClassDB::bind_method(D_METHOD("has_animation", "name"), &AnimationPlayer::has_animation); + ClassDB::bind_method(D_METHOD("get_animation:Animation", "name"), &AnimationPlayer::get_animation); + ClassDB::bind_method(D_METHOD("get_animation_list"), &AnimationPlayer::_get_animation_list); ClassDB::bind_method(D_METHOD("animation_set_next", "anim_from", "anim_to"), &AnimationPlayer::animation_set_next); ClassDB::bind_method(D_METHOD("animation_get_next", "anim_from"), &AnimationPlayer::animation_get_next); - ClassDB::bind_method(D_METHOD("set_blend_time","anim_from","anim_to","sec"),&AnimationPlayer::set_blend_time); - ClassDB::bind_method(D_METHOD("get_blend_time","anim_from","anim_to"),&AnimationPlayer::get_blend_time); + ClassDB::bind_method(D_METHOD("set_blend_time", "anim_from", "anim_to", "sec"), &AnimationPlayer::set_blend_time); + ClassDB::bind_method(D_METHOD("get_blend_time", "anim_from", "anim_to"), &AnimationPlayer::get_blend_time); - ClassDB::bind_method(D_METHOD("set_default_blend_time","sec"),&AnimationPlayer::set_default_blend_time); - ClassDB::bind_method(D_METHOD("get_default_blend_time"),&AnimationPlayer::get_default_blend_time); + ClassDB::bind_method(D_METHOD("set_default_blend_time", "sec"), &AnimationPlayer::set_default_blend_time); + ClassDB::bind_method(D_METHOD("get_default_blend_time"), &AnimationPlayer::get_default_blend_time); - ClassDB::bind_method(D_METHOD("play","name","custom_blend","custom_speed","from_end"),&AnimationPlayer::play,DEFVAL(""),DEFVAL(-1),DEFVAL(1.0),DEFVAL(false)); - ClassDB::bind_method(D_METHOD("play_backwards","name","custom_blend"),&AnimationPlayer::play_backwards,DEFVAL(""),DEFVAL(-1)); - ClassDB::bind_method(D_METHOD("stop","reset"),&AnimationPlayer::stop,DEFVAL(true)); - ClassDB::bind_method(D_METHOD("stop_all"),&AnimationPlayer::stop_all); - ClassDB::bind_method(D_METHOD("is_playing"),&AnimationPlayer::is_playing); - ClassDB::bind_method(D_METHOD("set_current_animation","anim"),&AnimationPlayer::set_current_animation); - ClassDB::bind_method(D_METHOD("get_current_animation"),&AnimationPlayer::get_current_animation); - ClassDB::bind_method(D_METHOD("queue","name"),&AnimationPlayer::queue); - ClassDB::bind_method(D_METHOD("clear_queue"),&AnimationPlayer::clear_queue); + ClassDB::bind_method(D_METHOD("play", "name", "custom_blend", "custom_speed", "from_end"), &AnimationPlayer::play, DEFVAL(""), DEFVAL(-1), DEFVAL(1.0), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("play_backwards", "name", "custom_blend"), &AnimationPlayer::play_backwards, DEFVAL(""), DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("stop", "reset"), &AnimationPlayer::stop, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("stop_all"), &AnimationPlayer::stop_all); + ClassDB::bind_method(D_METHOD("is_playing"), &AnimationPlayer::is_playing); + ClassDB::bind_method(D_METHOD("set_current_animation", "anim"), &AnimationPlayer::set_current_animation); + ClassDB::bind_method(D_METHOD("get_current_animation"), &AnimationPlayer::get_current_animation); + ClassDB::bind_method(D_METHOD("queue", "name"), &AnimationPlayer::queue); + ClassDB::bind_method(D_METHOD("clear_queue"), &AnimationPlayer::clear_queue); - ClassDB::bind_method(D_METHOD("set_active","active"),&AnimationPlayer::set_active); - ClassDB::bind_method(D_METHOD("is_active"),&AnimationPlayer::is_active); + ClassDB::bind_method(D_METHOD("set_active", "active"), &AnimationPlayer::set_active); + ClassDB::bind_method(D_METHOD("is_active"), &AnimationPlayer::is_active); - ClassDB::bind_method(D_METHOD("set_speed_scale","speed"),&AnimationPlayer::set_speed_scale); - ClassDB::bind_method(D_METHOD("get_speed_scale"),&AnimationPlayer::get_speed_scale); + ClassDB::bind_method(D_METHOD("set_speed_scale", "speed"), &AnimationPlayer::set_speed_scale); + ClassDB::bind_method(D_METHOD("get_speed_scale"), &AnimationPlayer::get_speed_scale); - ClassDB::bind_method(D_METHOD("set_autoplay","name"),&AnimationPlayer::set_autoplay); - ClassDB::bind_method(D_METHOD("get_autoplay"),&AnimationPlayer::get_autoplay); + ClassDB::bind_method(D_METHOD("set_autoplay", "name"), &AnimationPlayer::set_autoplay); + ClassDB::bind_method(D_METHOD("get_autoplay"), &AnimationPlayer::get_autoplay); - ClassDB::bind_method(D_METHOD("set_root","path"),&AnimationPlayer::set_root); - ClassDB::bind_method(D_METHOD("get_root"),&AnimationPlayer::get_root); + ClassDB::bind_method(D_METHOD("set_root", "path"), &AnimationPlayer::set_root); + ClassDB::bind_method(D_METHOD("get_root"), &AnimationPlayer::get_root); - ClassDB::bind_method(D_METHOD("seek","pos_sec","update"),&AnimationPlayer::seek,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_pos"),&AnimationPlayer::get_current_animation_pos); + ClassDB::bind_method(D_METHOD("seek", "pos_sec", "update"), &AnimationPlayer::seek, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_pos"), &AnimationPlayer::get_current_animation_pos); - ClassDB::bind_method(D_METHOD("find_animation","animation:Animation"),&AnimationPlayer::find_animation); + ClassDB::bind_method(D_METHOD("find_animation", "animation:Animation"), &AnimationPlayer::find_animation); - ClassDB::bind_method(D_METHOD("clear_caches"),&AnimationPlayer::clear_caches); + ClassDB::bind_method(D_METHOD("clear_caches"), &AnimationPlayer::clear_caches); - ClassDB::bind_method(D_METHOD("set_animation_process_mode","mode"),&AnimationPlayer::set_animation_process_mode); - ClassDB::bind_method(D_METHOD("get_animation_process_mode"),&AnimationPlayer::get_animation_process_mode); + ClassDB::bind_method(D_METHOD("set_animation_process_mode", "mode"), &AnimationPlayer::set_animation_process_mode); + ClassDB::bind_method(D_METHOD("get_animation_process_mode"), &AnimationPlayer::get_animation_process_mode); - ClassDB::bind_method(D_METHOD("get_current_animation_pos"),&AnimationPlayer::get_current_animation_pos); - ClassDB::bind_method(D_METHOD("get_current_animation_length"),&AnimationPlayer::get_current_animation_length); + ClassDB::bind_method(D_METHOD("get_current_animation_pos"), &AnimationPlayer::get_current_animation_pos); + ClassDB::bind_method(D_METHOD("get_current_animation_length"), &AnimationPlayer::get_current_animation_length); - ClassDB::bind_method(D_METHOD("advance","delta"),&AnimationPlayer::advance); + ClassDB::bind_method(D_METHOD("advance", "delta"), &AnimationPlayer::advance); + ADD_GROUP("Playback", "playback_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_animation_process_mode", "get_animation_process_mode"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "playback_default_blend_time", PROPERTY_HINT_RANGE, "0,4096,0.01"), "set_default_blend_time", "get_default_blend_time"); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_node"), "set_root", "get_root"); - ADD_GROUP("Playback","playback_"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_animation_process_mode", "get_animation_process_mode"); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "playback_default_blend_time", PROPERTY_HINT_RANGE, "0,4096,0.01"), "set_default_blend_time", "get_default_blend_time"); - ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "root_node"), "set_root", "get_root"); + ADD_SIGNAL(MethodInfo("animation_finished", PropertyInfo(Variant::STRING, "name"))); + ADD_SIGNAL(MethodInfo("animation_changed", PropertyInfo(Variant::STRING, "old_name"), PropertyInfo(Variant::STRING, "new_name"))); + ADD_SIGNAL(MethodInfo("animation_started", PropertyInfo(Variant::STRING, "name"))); - ADD_SIGNAL( MethodInfo("animation_finished", PropertyInfo(Variant::STRING,"name")) ); - ADD_SIGNAL( MethodInfo("animation_changed", PropertyInfo(Variant::STRING,"old_name"), PropertyInfo(Variant::STRING,"new_name")) ); - ADD_SIGNAL( MethodInfo("animation_started", PropertyInfo(Variant::STRING,"name")) ); - - BIND_CONSTANT( ANIMATION_PROCESS_FIXED ); - BIND_CONSTANT( ANIMATION_PROCESS_IDLE ); + BIND_CONSTANT(ANIMATION_PROCESS_FIXED); + BIND_CONSTANT(ANIMATION_PROCESS_IDLE); } AnimationPlayer::AnimationPlayer() { - - accum_pass=1; - cache_update_size=0; - cache_update_prop_size=0; - speed_scale=1; - end_notify=false; - animation_process_mode=ANIMATION_PROCESS_IDLE; - processing=false; - default_blend_time=0; - root=SceneStringNames::get_singleton()->path_pp; + accum_pass = 1; + cache_update_size = 0; + cache_update_prop_size = 0; + speed_scale = 1; + end_notify = false; + animation_process_mode = ANIMATION_PROCESS_IDLE; + processing = false; + default_blend_time = 0; + root = SceneStringNames::get_singleton()->path_pp; playing = false; - active=true; + active = true; } - -AnimationPlayer::~AnimationPlayer() -{ +AnimationPlayer::~AnimationPlayer() { } - - diff --git a/scene/animation/animation_player.h b/scene/animation/animation_player.h index 7fab65121..b5679d62f 100644 --- a/scene/animation/animation_player.h +++ b/scene/animation/animation_player.h @@ -29,35 +29,31 @@ #ifndef ANIMATION_PLAYER_H #define ANIMATION_PLAYER_H - -#include "scene/resources/animation.h" -#include "scene/3d/spatial.h" -#include "scene/3d/skeleton.h" #include "scene/2d/node_2d.h" +#include "scene/3d/skeleton.h" +#include "scene/3d/spatial.h" +#include "scene/resources/animation.h" /** @author Juan Linietsky */ class AnimationPlayer : public Node { - GDCLASS( AnimationPlayer, Node ); + GDCLASS(AnimationPlayer, Node); OBJ_CATEGORY("Animation Nodes"); public: - enum AnimationProcessMode { ANIMATION_PROCESS_FIXED, ANIMATION_PROCESS_IDLE, }; private: - enum { - NODE_CACHE_UPDATE_MAX=1024, - BLEND_FROM_MAX=3 + NODE_CACHE_UPDATE_MAX = 1024, + BLEND_FROM_MAX = 3 }; - enum SpecialProperty { SP_NONE, SP_NODE2D_POS, @@ -71,8 +67,8 @@ private: uint32_t id; RES resource; Node *node; - Spatial* spatial; - Node2D* node_2d; + Spatial *spatial; + Node2D *node_2d; Skeleton *skeleton; int bone_idx; // accumulated transforms @@ -90,14 +86,22 @@ private: Object *object; Variant value_accum; uint64_t accum_pass; - PropertyAnim() { accum_pass=0; object=NULL; } + PropertyAnim() { + accum_pass = 0; + object = NULL; + } }; - Map property_anim; - - - TrackNodeCache() { skeleton=NULL; spatial=NULL; node=NULL; accum_pass=0; bone_idx=-1; node_2d=NULL; } + Map property_anim; + TrackNodeCache() { + skeleton = NULL; + spatial = NULL; + node = NULL; + accum_pass = 0; + bone_idx = -1; + node_2d = NULL; + } }; struct TrackNodeCacheKey { @@ -105,36 +109,34 @@ private: uint32_t id; int bone_idx; - inline bool operator<(const TrackNodeCacheKey& p_right) const { + inline bool operator<(const TrackNodeCacheKey &p_right) const { - if (idp_right.id) + else if (id > p_right.id) return false; else - return bone_idx node_cache_map; + Map node_cache_map; - TrackNodeCache* cache_update[NODE_CACHE_UPDATE_MAX]; + TrackNodeCache *cache_update[NODE_CACHE_UPDATE_MAX]; int cache_update_size; - TrackNodeCache::PropertyAnim* cache_update_prop[NODE_CACHE_UPDATE_MAX]; + TrackNodeCache::PropertyAnim *cache_update_prop[NODE_CACHE_UPDATE_MAX]; int cache_update_prop_size; - Map,int> used_anims; + Map, int> used_anims; uint64_t accum_pass; - float speed_scale; - float default_blend_time; - + float speed_scale; + float default_blend_time; struct AnimationData { String name; StringName next; - Vector node_cache; + Vector node_cache; Ref animation; - }; Map animation_set; @@ -142,27 +144,23 @@ private: StringName from; StringName to; - bool operator<(const BlendKey& bk) const { return from==bk.from?String(to) blend_times; - + Map blend_times; struct PlaybackData { - AnimationData* from; + AnimationData *from; float pos; float speed_scale; PlaybackData() { - pos=0; - speed_scale=1.0; - from=NULL; - + pos = 0; + speed_scale = 1.0; + from = NULL; } - }; struct Blend { @@ -174,8 +172,8 @@ private: Blend() { - blend_left=0; - blend_time=0; + blend_left = 0; + blend_time = 0; } }; @@ -197,75 +195,73 @@ private: NodePath root; - void _animation_process_animation(AnimationData* p_anim,float p_time, float p_delta,float p_interp, bool p_allow_discrete=true); + void _animation_process_animation(AnimationData *p_anim, float p_time, float p_delta, float p_interp, bool p_allow_discrete = true); - void _generate_node_caches(AnimationData* p_anim); - void _animation_process_data(PlaybackData &cd,float p_delta,float p_blend); + void _generate_node_caches(AnimationData *p_anim); + void _animation_process_data(PlaybackData &cd, float p_delta, float p_blend); void _animation_process2(float p_delta); void _animation_update_transforms(); void _animation_process(float p_delta); void _node_removed(Node *p_node); -// bind helpers + // bind helpers PoolVector _get_animation_list() const { List animations; get_animation_list(&animations); PoolVector ret; - while(animations.size()) { + while (animations.size()) { - ret.push_back( animations.front()->get()); + ret.push_back(animations.front()->get()); animations.pop_front(); } return ret; } void _animation_changed(); - void _ref_anim(const Ref& p_anim); - void _unref_anim(const Ref& p_anim); + void _ref_anim(const Ref &p_anim); + void _unref_anim(const Ref &p_anim); + void _set_process(bool p_process, bool p_force = false); - void _set_process(bool p_process,bool p_force=false); - - bool playing; + bool playing; protected: - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); public: + StringName find_animation(const Ref &p_animation) const; - StringName find_animation(const Ref& p_animation) const; - - Error add_animation(const StringName& p_name, const Ref& p_animation); - void remove_animation(const StringName& p_name); - void rename_animation(const StringName& p_name,const StringName& p_new_name); - bool has_animation(const StringName& p_name) const; - Ref get_animation(const StringName& p_name) const; - void get_animation_list( List * p_animations) const; + Error add_animation(const StringName &p_name, const Ref &p_animation); + void remove_animation(const StringName &p_name); + void rename_animation(const StringName &p_name, const StringName &p_new_name); + bool has_animation(const StringName &p_name) const; + Ref get_animation(const StringName &p_name) const; + void get_animation_list(List *p_animations) const; - void set_blend_time(const StringName& p_animation1, const StringName& p_animation2, float p_time); - float get_blend_time( const StringName& p_animation1, const StringName& p_animation2) const; + void set_blend_time(const StringName &p_animation1, const StringName &p_animation2, float p_time); + float get_blend_time(const StringName &p_animation1, const StringName &p_animation2) const; - void animation_set_next(const StringName& p_animation, const StringName& p_next); - StringName animation_get_next(const StringName& p_animation) const; + void animation_set_next(const StringName &p_animation, const StringName &p_next); + StringName animation_get_next(const StringName &p_animation) const; - void set_default_blend_time(float p_default); - float get_default_blend_time() const; + void set_default_blend_time(float p_default); + float get_default_blend_time() const; - void play(const StringName& p_name=StringName(),float p_custom_blend=-1,float p_custom_scale=1.0,bool p_from_end=false); - void play_backwards(const StringName& p_name=StringName(),float p_custom_blend=-1); - void queue(const StringName& p_name); + void play(const StringName &p_name = StringName(), float p_custom_blend = -1, float p_custom_scale = 1.0, bool p_from_end = false); + void play_backwards(const StringName &p_name = StringName(), float p_custom_blend = -1); + void queue(const StringName &p_name); void clear_queue(); - void stop(bool p_reset=true); + void stop(bool p_reset = true); bool is_playing() const; String get_current_animation() const; - void set_current_animation(const String& p_anim); + void set_current_animation(const String &p_anim); void stop_all(); void set_active(bool p_active); bool is_active() const; @@ -274,34 +270,30 @@ public: void set_speed_scale(float p_speed); float get_speed_scale() const; - void set_autoplay(const String& pname); + void set_autoplay(const String &pname); String get_autoplay() const; void set_animation_process_mode(AnimationProcessMode p_mode); AnimationProcessMode get_animation_process_mode() const; - void seek(float p_time,bool p_update=false); - void seek_delta(float p_time,float p_delta); + void seek(float p_time, bool p_update = false); + void seek_delta(float p_time, float p_delta); float get_current_animation_pos() const; float get_current_animation_length() const; void advance(float p_time); - void set_root(const NodePath& p_root); + void set_root(const NodePath &p_root); NodePath get_root() const; void clear_caches(); ///< must be called by hand if an animation was modified after added - void get_argument_options(const StringName& p_function,int p_idx,List*r_options) const; - + void get_argument_options(const StringName &p_function, int p_idx, List *r_options) const; AnimationPlayer(); ~AnimationPlayer(); - }; - -VARIANT_ENUM_CAST( AnimationPlayer::AnimationProcessMode ); - +VARIANT_ENUM_CAST(AnimationPlayer::AnimationProcessMode); #endif diff --git a/scene/animation/animation_tree_player.cpp b/scene/animation/animation_tree_player.cpp index d7e98ddd2..6f4279526 100644 --- a/scene/animation/animation_tree_player.cpp +++ b/scene/animation/animation_tree_player.cpp @@ -31,7 +31,6 @@ #include "scene/scene_string_names.h" - void AnimationTreePlayer::set_animation_process_mode(AnimationProcessMode p_mode) { if (animation_process_mode == p_mode) @@ -43,322 +42,312 @@ void AnimationTreePlayer::set_animation_process_mode(AnimationProcessMode p_mode animation_process_mode = p_mode; if (pr) _set_process(true); - } -AnimationTreePlayer::AnimationProcessMode AnimationTreePlayer::get_animation_process_mode() const{ +AnimationTreePlayer::AnimationProcessMode AnimationTreePlayer::get_animation_process_mode() const { return animation_process_mode; } -void AnimationTreePlayer::_set_process(bool p_process, bool p_force) -{ +void AnimationTreePlayer::_set_process(bool p_process, bool p_force) { if (processing == p_process && !p_force) return; switch (animation_process_mode) { - case ANIMATION_PROCESS_FIXED: set_fixed_process_internal(p_process && active); break; - case ANIMATION_PROCESS_IDLE: set_process_internal(p_process && active); break; + case ANIMATION_PROCESS_FIXED: set_fixed_process_internal(p_process && active); break; + case ANIMATION_PROCESS_IDLE: set_process_internal(p_process && active); break; } processing = p_process; } +bool AnimationTreePlayer::_set(const StringName &p_name, const Variant &p_value) { -bool AnimationTreePlayer::_set(const StringName& p_name, const Variant& p_value) { - - if (String(p_name)=="base_path") { + if (String(p_name) == "base_path") { set_base_path(p_value); return true; } - if (String(p_name)=="master_player") { + if (String(p_name) == "master_player") { set_master_player(p_value); return true; } - if(String(p_name) == SceneStringNames::get_singleton()->playback_active) { + if (String(p_name) == SceneStringNames::get_singleton()->playback_active) { set_active(p_value); return true; } - if (String(p_name)!="data") + if (String(p_name) != "data") return false; + Dictionary data = p_value; - Dictionary data=p_value; + Array nodes = data.get_valid("nodes"); - Array nodes=data.get_valid("nodes"); - - for(int i=0;i::Element *E=node_map.front();E;E=E->next()) { + for (Map::Element *E = node_map.front(); E; E = E->next()) { NodeBase *n = node_map[E->key()]; Dictionary node; - node["id"]=E->key(); - node["pos"]=n->pos; - - switch(n->type) { - case NODE_OUTPUT: node["type"]= "output"; break; - case NODE_ANIMATION: node["type"]= "animation"; break; - case NODE_ONESHOT: node["type"]= "oneshot"; break; - case NODE_MIX: node["type"]= "mix"; break; - case NODE_BLEND2: node["type"]= "blend2"; break; - case NODE_BLEND3: node["type"]= "blend3"; break; - case NODE_BLEND4: node["type"]= "blend4"; break; - case NODE_TIMESCALE: node["type"]= "timescale"; break; - case NODE_TIMESEEK: node["type"]= "timeseek"; break; - case NODE_TRANSITION: node["type"]= "transition"; break; - default: node["type"]= ""; break; + node["id"] = E->key(); + node["pos"] = n->pos; + + switch (n->type) { + case NODE_OUTPUT: node["type"] = "output"; break; + case NODE_ANIMATION: node["type"] = "animation"; break; + case NODE_ONESHOT: node["type"] = "oneshot"; break; + case NODE_MIX: node["type"] = "mix"; break; + case NODE_BLEND2: node["type"] = "blend2"; break; + case NODE_BLEND3: node["type"] = "blend3"; break; + case NODE_BLEND4: node["type"] = "blend4"; break; + case NODE_TIMESCALE: node["type"] = "timescale"; break; + case NODE_TIMESEEK: node["type"] = "timeseek"; break; + case NODE_TRANSITION: node["type"] = "transition"; break; + default: node["type"] = ""; break; } - switch(n->type) { + switch (n->type) { case NODE_OUTPUT: { } break; case NODE_ANIMATION: { - AnimationNode *an = static_cast(n); - if (master!=NodePath() && an->from!="") { - node["from"]=an->from; + AnimationNode *an = static_cast(n); + if (master != NodePath() && an->from != "") { + node["from"] = an->from; } else { - node["animation"]=an->animation; + node["animation"] = an->animation; } Array k; List keys; an->filter.get_key_list(&keys); k.resize(keys.size()); - int i=0; - for(List::Element *E=keys.front();E;E=E->next()) { - k[i++]=E->get(); + int i = 0; + for (List::Element *E = keys.front(); E; E = E->next()) { + k[i++] = E->get(); } - node["filter"]=k; - } break; + node["filter"] = k; + } break; case NODE_ONESHOT: { - OneShotNode *osn = static_cast(n); - node["fade_in"]=osn->fade_in; - node["fade_out"]=osn->fade_out; - node["mix"]=osn->mix; - node["autorestart"]=osn->autorestart; - node["autorestart_delay"]=osn->autorestart_delay; - node["autorestart_random_delay"]=osn->autorestart_random_delay; + OneShotNode *osn = static_cast(n); + node["fade_in"] = osn->fade_in; + node["fade_out"] = osn->fade_out; + node["mix"] = osn->mix; + node["autorestart"] = osn->autorestart; + node["autorestart_delay"] = osn->autorestart_delay; + node["autorestart_random_delay"] = osn->autorestart_random_delay; Array k; List keys; osn->filter.get_key_list(&keys); k.resize(keys.size()); - int i=0; - for(List::Element *E=keys.front();E;E=E->next()) { - k[i++]=E->get(); + int i = 0; + for (List::Element *E = keys.front(); E; E = E->next()) { + k[i++] = E->get(); } - node["filter"]=k; + node["filter"] = k; } break; case NODE_MIX: { - MixNode *mn = static_cast(n); - node["mix"]=mn->amount; + MixNode *mn = static_cast(n); + node["mix"] = mn->amount; } break; case NODE_BLEND2: { - Blend2Node *bn = static_cast(n); - node["blend"]=bn->value; + Blend2Node *bn = static_cast(n); + node["blend"] = bn->value; Array k; List keys; bn->filter.get_key_list(&keys); k.resize(keys.size()); - int i=0; - for(List::Element *E=keys.front();E;E=E->next()) { - k[i++]=E->get(); + int i = 0; + for (List::Element *E = keys.front(); E; E = E->next()) { + k[i++] = E->get(); } - node["filter"]=k; + node["filter"] = k; } break; case NODE_BLEND3: { - Blend3Node *bn = static_cast(n); - node["blend"]=bn->value; + Blend3Node *bn = static_cast(n); + node["blend"] = bn->value; } break; case NODE_BLEND4: { - Blend4Node *bn = static_cast(n); - node["blend"]=bn->value; + Blend4Node *bn = static_cast(n); + node["blend"] = bn->value; } break; case NODE_TIMESCALE: { - TimeScaleNode *tsn = static_cast(n); - node["scale"]=tsn->scale; + TimeScaleNode *tsn = static_cast(n); + node["scale"] = tsn->scale; } break; case NODE_TIMESEEK: { } break; case NODE_TRANSITION: { - TransitionNode *tn = static_cast(n); - node["xfade"]=tn->xfade; + TransitionNode *tn = static_cast(n); + node["xfade"] = tn->xfade; Array transitions; - for(int i=0;iinput_data.size();i++) { + for (int i = 0; i < tn->input_data.size(); i++) { Dictionary d; - d["auto_advance"]=tn->input_data[i].auto_advance; + d["auto_advance"] = tn->input_data[i].auto_advance; transitions.push_back(d); - } - node["transitions"]=transitions; + node["transitions"] = transitions; } break; default: {}; @@ -367,39 +356,38 @@ bool AnimationTreePlayer::_get(const StringName& p_name,Variant &r_ret) const { nodes.push_back(node); } - data["nodes"]=nodes; + data["nodes"] = nodes; //connectiosn List connections; get_connection_list(&connections); Array connections_arr; - connections_arr.resize(connections.size()*3); + connections_arr.resize(connections.size() * 3); - int idx=0; - for (List::Element *E=connections.front();E;E=E->next()) { + int idx = 0; + for (List::Element *E = connections.front(); E; E = E->next()) { - connections_arr.set(idx+0,E->get().src_node); - connections_arr.set(idx+1,E->get().dst_node); - connections_arr.set(idx+2,E->get().dst_input); + connections_arr.set(idx + 0, E->get().src_node); + connections_arr.set(idx + 1, E->get().dst_node); + connections_arr.set(idx + 2, E->get().dst_input); - idx+=3; + idx += 3; } - data["connections"]=connections_arr; - data["active"]=active; - data["master"]=master; + data["connections"] = connections_arr; + data["active"] = active; + data["master"] = master; - r_ret=data; + r_ret = data; return true; - } -void AnimationTreePlayer::_get_property_list( List *p_list) const { +void AnimationTreePlayer::_get_property_list(List *p_list) const { - p_list->push_back( PropertyInfo(Variant::NODE_PATH,"base_path" ) ); - p_list->push_back( PropertyInfo(Variant::NODE_PATH,"master_player" ) ); - p_list->push_back( PropertyInfo(Variant::DICTIONARY,"data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_NETWORK) ); + p_list->push_back(PropertyInfo(Variant::NODE_PATH, "base_path")); + p_list->push_back(PropertyInfo(Variant::NODE_PATH, "master_player")); + p_list->push_back(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_NETWORK)); } void AnimationTreePlayer::advance(float p_time) { @@ -409,7 +397,7 @@ void AnimationTreePlayer::advance(float p_time) { void AnimationTreePlayer::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { @@ -421,38 +409,37 @@ void AnimationTreePlayer::_notification(int p_what) { } } break; case NOTIFICATION_READY: { - dirty_caches=true; - if (master!=NodePath()) { + dirty_caches = true; + if (master != NodePath()) { _update_sources(); } } break; case NOTIFICATION_INTERNAL_PROCESS: { - if (animation_process_mode==ANIMATION_PROCESS_FIXED) + if (animation_process_mode == ANIMATION_PROCESS_FIXED) break; if (processing) - _process_animation( get_process_delta_time() ); + _process_animation(get_process_delta_time()); } break; case NOTIFICATION_INTERNAL_FIXED_PROCESS: { - if (animation_process_mode==ANIMATION_PROCESS_IDLE) + if (animation_process_mode == ANIMATION_PROCESS_IDLE) break; if (processing) _process_animation(get_fixed_process_delta_time()); } break; } - } -void AnimationTreePlayer::_compute_weights(float *p_fallback_weight, HashMap *p_weights, float p_coeff, const HashMap *p_filter, float p_filtered_coeff) { +void AnimationTreePlayer::_compute_weights(float *p_fallback_weight, HashMap *p_weights, float p_coeff, const HashMap *p_filter, float p_filtered_coeff) { if (p_filter != NULL) { List key_list; p_filter->get_key_list(&key_list); - for (List::Element *E = key_list.front();E; E=E->next()) { + for (List::Element *E = key_list.front(); E; E = E->next()) { if ((*p_filter)[E->get()]) { @@ -463,45 +450,43 @@ void AnimationTreePlayer::_compute_weights(float *p_fallback_weight, HashMaphas(E->get())) { - (*p_weights)[E->get()] *= p_coeff; + (*p_weights)[E->get()] *= p_coeff; } } } List key_list; p_weights->get_key_list(&key_list); - - for (List::Element *E = key_list.front();E;E=E->next()) { + + for (List::Element *E = key_list.front(); E; E = E->next()) { if (p_filter == NULL || !p_filter->has(E->get())) { (*p_weights)[E->get()] *= p_coeff; } } *p_fallback_weight *= p_coeff; - } - -float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode **r_prev_anim, float p_time, bool p_seek, float p_fallback_weight, HashMap* p_weights) { +float AnimationTreePlayer::_process_node(const StringName &p_node, AnimationNode **r_prev_anim, float p_time, bool p_seek, float p_fallback_weight, HashMap *p_weights) { ERR_FAIL_COND_V(!node_map.has(p_node), 0); - NodeBase *nb=node_map[p_node]; + NodeBase *nb = node_map[p_node]; //transform to seconds... - switch(nb->type) { + switch (nb->type) { case NODE_OUTPUT: { - NodeOut *on = static_cast(nb); + NodeOut *on = static_cast(nb); HashMap weights; - return _process_node(on->inputs[0].node,r_prev_anim,p_time,p_seek, p_fallback_weight, &weights); + return _process_node(on->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, &weights); } break; case NODE_ANIMATION: { - AnimationNode *an = static_cast(nb); + AnimationNode *an = static_cast(nb); float rem = 0; if (!an->animation.is_null()) { @@ -512,11 +497,11 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode //const Animation *a = an->animation.operator->(); if (p_seek) { - an->time=p_time; - an->step=0; + an->time = p_time; + an->step = 0; } else { - an->time=MAX(0,an->time+p_time); - an->step=p_time; + an->time = MAX(0, an->time + p_time); + an->step = p_time; } float anim_size = an->animation->get_length(); @@ -524,16 +509,16 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode if (an->animation->has_loop()) { if (anim_size) - an->time=Math::fposmod(an->time,anim_size); + an->time = Math::fposmod(an->time, anim_size); } else if (an->time > anim_size) { - an->time=anim_size; + an->time = anim_size; } - an->skip=true; + an->skip = true; - for (List::Element *E=an->tref.front();E;E=E->next()) { + for (List::Element *E = an->tref.front(); E; E = E->next()) { NodePath track_path = an->animation->track_get_path(E->get().local_track); if (an->filter.has(track_path) && an->filter[track_path]) { E->get().weight = 0; @@ -545,114 +530,111 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode E->get().weight = p_fallback_weight; } } - if (E->get().weight>CMP_EPSILON) - an->skip=false; + if (E->get().weight > CMP_EPSILON) + an->skip = false; } rem = anim_size - an->time; - } - if (!(*r_prev_anim)) - active_list=an; + active_list = an; else - (*r_prev_anim)->next=an; + (*r_prev_anim)->next = an; - an->next=NULL; - *r_prev_anim=an; + an->next = NULL; + *r_prev_anim = an; return rem; - } break; case NODE_ONESHOT: { - OneShotNode *osn = static_cast(nb); + OneShotNode *osn = static_cast(nb); if (!osn->active) { //make it as if this node doesn't exist, pass input 0 by. - return _process_node(osn->inputs[0].node,r_prev_anim,p_time,p_seek, p_fallback_weight, p_weights); + return _process_node(osn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights); } float os_seek = p_seek; if (p_seek) - osn->time=p_time; + osn->time = p_time; if (osn->start) { - osn->time=0; + osn->time = 0; os_seek = true; } float blend; - if (osn->timefade_in) { + if (osn->time < osn->fade_in) { - if (osn->fade_in>0) - blend = osn->time/osn->fade_in; + if (osn->fade_in > 0) + blend = osn->time / osn->fade_in; else - blend=0; //wtf + blend = 0; //wtf - } else if (!osn->start && osn->remainingfade_out) { + } else if (!osn->start && osn->remaining < osn->fade_out) { if (osn->fade_out) - blend=(osn->remaining/osn->fade_out); + blend = (osn->remaining / osn->fade_out); else - blend=1.0; + blend = 1.0; } else - blend=1.0; + blend = 1.0; float main_rem; float os_rem; HashMap os_weights(*p_weights); float os_fallback_weight = p_fallback_weight; - _compute_weights(&p_fallback_weight, p_weights, osn->mix?1.0 : 1.0 - blend, &osn->filter, 1.0); + _compute_weights(&p_fallback_weight, p_weights, osn->mix ? 1.0 : 1.0 - blend, &osn->filter, 1.0); _compute_weights(&os_fallback_weight, &os_weights, blend, &osn->filter, 0.0); - main_rem = _process_node(osn->inputs[0].node,r_prev_anim,p_time,p_seek, p_fallback_weight, p_weights); - os_rem = _process_node(osn->inputs[1].node,r_prev_anim,p_time,os_seek, os_fallback_weight, &os_weights); + main_rem = _process_node(osn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights); + os_rem = _process_node(osn->inputs[1].node, r_prev_anim, p_time, os_seek, os_fallback_weight, &os_weights); if (osn->start) { - osn->remaining=os_rem; - osn->start=false; + osn->remaining = os_rem; + osn->start = false; } if (!p_seek) { - osn->time+=p_time; - osn->remaining=os_rem; - if (osn->remaining<=0) - osn->active=false; + osn->time += p_time; + osn->remaining = os_rem; + if (osn->remaining <= 0) + osn->active = false; } - return MAX(main_rem,osn->remaining); + return MAX(main_rem, osn->remaining); } break; case NODE_MIX: { - MixNode *mn = static_cast(nb); + MixNode *mn = static_cast(nb); HashMap mn_weights(*p_weights); float mn_fallback_weight = p_fallback_weight; _compute_weights(&mn_fallback_weight, &mn_weights, mn->amount); - float rem = _process_node(mn->inputs[0].node,r_prev_anim, p_time,p_seek,p_fallback_weight,p_weights); - _process_node(mn->inputs[1].node,r_prev_anim,p_time,p_seek,mn_fallback_weight,&mn_weights); + float rem = _process_node(mn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights); + _process_node(mn->inputs[1].node, r_prev_anim, p_time, p_seek, mn_fallback_weight, &mn_weights); return rem; } break; case NODE_BLEND2: { - Blend2Node *bn = static_cast(nb); + Blend2Node *bn = static_cast(nb); HashMap bn_weights(*p_weights); float bn_fallback_weight = p_fallback_weight; - _compute_weights(&p_fallback_weight,p_weights, 1.0 - bn->value, &bn->filter, 1.0); - _compute_weights(&bn_fallback_weight,&bn_weights, bn->value, &bn->filter, 0.0); - float rem = _process_node(bn->inputs[0].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights); - _process_node(bn->inputs[1].node,r_prev_anim,p_time,p_seek,bn_fallback_weight,&bn_weights); + _compute_weights(&p_fallback_weight, p_weights, 1.0 - bn->value, &bn->filter, 1.0); + _compute_weights(&bn_fallback_weight, &bn_weights, bn->value, &bn->filter, 0.0); + float rem = _process_node(bn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights); + _process_node(bn->inputs[1].node, r_prev_anim, p_time, p_seek, bn_fallback_weight, &bn_weights); return rem; } break; case NODE_BLEND3: { - Blend3Node *bn = static_cast(nb); + Blend3Node *bn = static_cast(nb); float rem; float blend, lower_blend, upper_blend; @@ -670,18 +652,18 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode float upper_fallback_weight = p_fallback_weight; HashMap lower_weights(*p_weights); float lower_fallback_weight = p_fallback_weight; - _compute_weights(&upper_fallback_weight,&upper_weights, upper_blend); - _compute_weights(&p_fallback_weight,p_weights, blend); - _compute_weights(&lower_fallback_weight,&lower_weights, lower_blend); + _compute_weights(&upper_fallback_weight, &upper_weights, upper_blend); + _compute_weights(&p_fallback_weight, p_weights, blend); + _compute_weights(&lower_fallback_weight, &lower_weights, lower_blend); - rem = _process_node(bn->inputs[1].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights); - _process_node(bn->inputs[0].node,r_prev_anim,p_time,p_seek,lower_fallback_weight,&lower_weights); - _process_node(bn->inputs[2].node,r_prev_anim,p_time,p_seek,upper_fallback_weight,&upper_weights); + rem = _process_node(bn->inputs[1].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights); + _process_node(bn->inputs[0].node, r_prev_anim, p_time, p_seek, lower_fallback_weight, &lower_weights); + _process_node(bn->inputs[2].node, r_prev_anim, p_time, p_seek, upper_fallback_weight, &upper_weights); return rem; } break; case NODE_BLEND4: { - Blend4Node *bn = static_cast(nb); + Blend4Node *bn = static_cast(nb); HashMap weights1(*p_weights); float fallback_weight1 = p_fallback_weight; @@ -690,26 +672,26 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode HashMap weights3(*p_weights); float fallback_weight3 = p_fallback_weight; - _compute_weights(&p_fallback_weight,p_weights, 1.0-bn->value.x); - _compute_weights(&fallback_weight1,&weights1, bn->value.x); - _compute_weights(&fallback_weight2,&weights2, 1.0-bn->value.y); - _compute_weights(&fallback_weight3,&weights3, bn->value.y); + _compute_weights(&p_fallback_weight, p_weights, 1.0 - bn->value.x); + _compute_weights(&fallback_weight1, &weights1, bn->value.x); + _compute_weights(&fallback_weight2, &weights2, 1.0 - bn->value.y); + _compute_weights(&fallback_weight3, &weights3, bn->value.y); - float rem = _process_node(bn->inputs[0].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights); - _process_node(bn->inputs[1].node,r_prev_anim,p_time,p_seek,fallback_weight1,&weights1); - float rem2 = _process_node(bn->inputs[2].node,r_prev_anim,p_time,p_seek,fallback_weight2,&weights2); - _process_node(bn->inputs[3].node,r_prev_anim,p_time,p_seek,fallback_weight3,&weights3); + float rem = _process_node(bn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights); + _process_node(bn->inputs[1].node, r_prev_anim, p_time, p_seek, fallback_weight1, &weights1); + float rem2 = _process_node(bn->inputs[2].node, r_prev_anim, p_time, p_seek, fallback_weight2, &weights2); + _process_node(bn->inputs[3].node, r_prev_anim, p_time, p_seek, fallback_weight3, &weights3); - return MAX(rem,rem2); + return MAX(rem, rem2); } break; case NODE_TIMESCALE: { - TimeScaleNode *tsn = static_cast(nb); + TimeScaleNode *tsn = static_cast(nb); float rem; if (p_seek) - rem = _process_node(tsn->inputs[0].node,r_prev_anim,p_time,true,p_fallback_weight,p_weights); + rem = _process_node(tsn->inputs[0].node, r_prev_anim, p_time, true, p_fallback_weight, p_weights); else - rem = _process_node(tsn->inputs[0].node,r_prev_anim,p_time*tsn->scale,false,p_fallback_weight,p_weights); + rem = _process_node(tsn->inputs[0].node, r_prev_anim, p_time * tsn->scale, false, p_fallback_weight, p_weights); if (tsn->scale == 0) return Math_INF; else @@ -718,105 +700,96 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode } break; case NODE_TIMESEEK: { - TimeSeekNode *tsn = static_cast(nb); - if (tsn->seek_pos>=0 && !p_seek) { + TimeSeekNode *tsn = static_cast(nb); + if (tsn->seek_pos >= 0 && !p_seek) { p_time = tsn->seek_pos; p_seek = true; } - tsn->seek_pos=-1; + tsn->seek_pos = -1; - return _process_node(tsn->inputs[0].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights); + return _process_node(tsn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights); - } break; + } break; case NODE_TRANSITION: { - TransitionNode *tn = static_cast(nb); + TransitionNode *tn = static_cast(nb); HashMap prev_weights(*p_weights); float prev_fallback_weight = p_fallback_weight; - if (tn->prev<0) { // process current animation, check for transition + if (tn->prev < 0) { // process current animation, check for transition - float rem = _process_node(tn->inputs[tn->current].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights); + float rem = _process_node(tn->inputs[tn->current].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights); if (p_seek) - tn->time=p_time; + tn->time = p_time; else - tn->time+=p_time; + tn->time += p_time; if (tn->input_data[tn->current].auto_advance && rem <= tn->xfade) { - tn->set_current((tn->current+1) % tn->inputs.size()); + tn->set_current((tn->current + 1) % tn->inputs.size()); } - return rem; - } else { // cross-fading from tn->prev to tn->current + } else { // cross-fading from tn->prev to tn->current - - float blend = tn->xfade? (tn->prev_xfading/tn->xfade) : 1; + float blend = tn->xfade ? (tn->prev_xfading / tn->xfade) : 1; float rem; - _compute_weights(&p_fallback_weight,p_weights, 1.0-blend); - _compute_weights(&prev_fallback_weight,&prev_weights, blend); + _compute_weights(&p_fallback_weight, p_weights, 1.0 - blend); + _compute_weights(&prev_fallback_weight, &prev_weights, blend); if (!p_seek && tn->switched) { //just switched, seek to start of current - rem = _process_node(tn->inputs[tn->current].node,r_prev_anim,0,true,p_fallback_weight,p_weights); + rem = _process_node(tn->inputs[tn->current].node, r_prev_anim, 0, true, p_fallback_weight, p_weights); } else { - rem = _process_node(tn->inputs[tn->current].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights); - + rem = _process_node(tn->inputs[tn->current].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights); } - tn->switched=false; + tn->switched = false; - if (p_seek) { // don't seek prev animation - _process_node(tn->inputs[tn->prev].node,r_prev_anim,0,false,prev_fallback_weight,&prev_weights); - tn->time=p_time; + if (p_seek) { // don't seek prev animation + _process_node(tn->inputs[tn->prev].node, r_prev_anim, 0, false, prev_fallback_weight, &prev_weights); + tn->time = p_time; } else { - _process_node(tn->inputs[tn->prev].node,r_prev_anim,p_time,false,prev_fallback_weight,&prev_weights); - tn->time+=p_time; - tn->prev_xfading-=p_time; - if (tn->prev_xfading<0) { + _process_node(tn->inputs[tn->prev].node, r_prev_anim, p_time, false, prev_fallback_weight, &prev_weights); + tn->time += p_time; + tn->prev_xfading -= p_time; + if (tn->prev_xfading < 0) { - tn->prev=-1; + tn->prev = -1; } - } return rem; } - } break; default: {} } - - return 0; } - void AnimationTreePlayer::_process_animation(float p_delta) { - if (last_error!=CONNECT_OK) + if (last_error != CONNECT_OK) return; if (dirty_caches) _recompute_caches(); - - active_list=NULL; - AnimationNode *prev=NULL; + active_list = NULL; + AnimationNode *prev = NULL; if (reset_request) { - _process_node(out_name,&prev, 0, true); - reset_request=false; + _process_node(out_name, &prev, 0, true); + reset_request = false; } else - _process_node(out_name,&prev, p_delta); + _process_node(out_name, &prev, p_delta); if (dirty_caches) { //some animation changed.. ignore this pass @@ -825,19 +798,17 @@ void AnimationTreePlayer::_process_animation(float p_delta) { //update the tracks.. - - /* STEP 1 CLEAR TRACKS */ - for(TrackMap::Element *E=track_map.front();E;E=E->next()) { + for (TrackMap::Element *E = track_map.front(); E; E = E->next()) { Track &t = E->get(); t.loc.zero(); - t.rot=Quat(); - t.scale.x=0; - t.scale.y=0; - t.scale.z=0; + t.rot = Quat(); + t.scale.x = 0; + t.scale.y = 0; + t.scale.z = 0; t.value = t.object->get(t.property); t.value.zero(); @@ -845,634 +816,554 @@ void AnimationTreePlayer::_process_animation(float p_delta) { t.skip = false; } - /* STEP 2 PROCESS ANIMATIONS */ - AnimationNode *anim_list=active_list; + AnimationNode *anim_list = active_list; Quat empty_rot; - - while(anim_list) { + while (anim_list) { if (!anim_list->animation.is_null() && !anim_list->skip) { //check if animation is meaningful Animation *a = anim_list->animation.operator->(); - for(List::Element *E=anim_list->tref.front();E;E=E->next()) { - + for (List::Element *E = anim_list->tref.front(); E; E = E->next()) { AnimationNode::TrackRef &tr = E->get(); - if (tr.track==NULL || tr.local_track<0 || tr.weight < CMP_EPSILON) + if (tr.track == NULL || tr.local_track < 0 || tr.weight < CMP_EPSILON) continue; - switch(a->track_get_type(tr.local_track)) { + switch (a->track_get_type(tr.local_track)) { case Animation::TYPE_TRANSFORM: { ///< Transform a node or a bone. Vector3 loc; Quat rot; Vector3 scale; - a->transform_track_interpolate(tr.local_track,anim_list->time,&loc,&rot,&scale); + a->transform_track_interpolate(tr.local_track, anim_list->time, &loc, &rot, &scale); - tr.track->loc+=loc*tr.weight; + tr.track->loc += loc * tr.weight; - scale.x-=1.0; - scale.y-=1.0; - scale.z-=1.0; - tr.track->scale+=scale*tr.weight; - - tr.track->rot = tr.track->rot * empty_rot.slerp(rot,tr.weight); + scale.x -= 1.0; + scale.y -= 1.0; + scale.z -= 1.0; + tr.track->scale += scale * tr.weight; + tr.track->rot = tr.track->rot * empty_rot.slerp(rot, tr.weight); } break; case Animation::TYPE_VALUE: { ///< Set a value in a property, can be interpolated. - if (a->value_track_get_update_mode(tr.local_track)==Animation::UPDATE_CONTINUOUS) { - Variant value = a->value_track_interpolate(tr.local_track,anim_list->time); - Variant::blend(tr.track->value,value,tr.weight,tr.track->value); + if (a->value_track_get_update_mode(tr.local_track) == Animation::UPDATE_CONTINUOUS) { + Variant value = a->value_track_interpolate(tr.local_track, anim_list->time); + Variant::blend(tr.track->value, value, tr.weight, tr.track->value); } else { - int index = a->track_find_key(tr.local_track,anim_list->time); + int index = a->track_find_key(tr.local_track, anim_list->time); tr.track->value = a->track_get_key_value(tr.local_track, index); } } break; case Animation::TYPE_METHOD: { ///< Call any method on a specific node. List indices; - a->method_track_get_key_indices(tr.local_track,anim_list->time,anim_list->step,&indices); - for(List::Element *E=indices.front();E;E=E->next()) { + a->method_track_get_key_indices(tr.local_track, anim_list->time, anim_list->step, &indices); + for (List::Element *E = indices.front(); E; E = E->next()) { - StringName method = a->method_track_get_name(tr.local_track,E->get()); - Vector args=a->method_track_get_params(tr.local_track,E->get()); + StringName method = a->method_track_get_name(tr.local_track, E->get()); + Vector args = a->method_track_get_params(tr.local_track, E->get()); args.resize(VARIANT_ARG_MAX); - tr.track->object->call(method,args[0],args[1],args[2],args[3],args[4]); + tr.track->object->call(method, args[0], args[1], args[2], args[3], args[4]); } } break; } - } } - anim_list=anim_list->next; + anim_list = anim_list->next; } /* STEP 3 APPLY TRACKS */ - for(TrackMap::Element *E=track_map.front();E;E=E->next()) { + for (TrackMap::Element *E = track_map.front(); E; E = E->next()) { Track &t = E->get(); if (t.skip || !t.object) continue; - if(t.property) { // value track - t.object->set(t.property,t.value); + if (t.property) { // value track + t.object->set(t.property, t.value); continue; } Transform xform; - xform.basis=t.rot; - xform.origin=t.loc; + xform.basis = t.rot; + xform.origin = t.loc; - t.scale.x+=1.0; - t.scale.y+=1.0; - t.scale.z+=1.0; + t.scale.x += 1.0; + t.scale.y += 1.0; + t.scale.z += 1.0; xform.basis.scale(t.scale); - if (t.bone_idx>=0) { + if (t.bone_idx >= 0) { if (t.skeleton) - t.skeleton->set_bone_pose(t.bone_idx,xform); + t.skeleton->set_bone_pose(t.bone_idx, xform); } else if (t.spatial) { t.spatial->set_transform(xform); } } - - - } +void AnimationTreePlayer::add_node(NodeType p_type, const StringName &p_node) { -void AnimationTreePlayer::add_node(NodeType p_type, const StringName& p_node) { + ERR_FAIL_COND(p_type == NODE_OUTPUT); + ERR_FAIL_COND(node_map.has(p_node)); - ERR_FAIL_COND( p_type == NODE_OUTPUT ); - ERR_FAIL_COND( node_map.has(p_node)); + NodeBase *n = NULL; - NodeBase *n=NULL; - - switch(p_type) { + switch (p_type) { case NODE_ANIMATION: { - n = memnew( AnimationNode ); + n = memnew(AnimationNode); } break; case NODE_ONESHOT: { - n = memnew( OneShotNode ); + n = memnew(OneShotNode); } break; case NODE_MIX: { - n = memnew( MixNode ); + n = memnew(MixNode); } break; case NODE_BLEND2: { - n = memnew( Blend2Node ); + n = memnew(Blend2Node); } break; case NODE_BLEND3: { - n = memnew( Blend3Node ); + n = memnew(Blend3Node); } break; case NODE_BLEND4: { - n = memnew( Blend4Node ); + n = memnew(Blend4Node); } break; case NODE_TIMESCALE: { - n = memnew( TimeScaleNode ); - + n = memnew(TimeScaleNode); } break; case NODE_TIMESEEK: { - n = memnew( TimeSeekNode ); + n = memnew(TimeSeekNode); } break; case NODE_TRANSITION: { - n = memnew( TransitionNode ); - + n = memnew(TransitionNode); } break; default: {} } //n->name+=" "+itos(p_node); - node_map[p_node]=n; + node_map[p_node] = n; } +StringName AnimationTreePlayer::node_get_input_source(const StringName &p_node, int p_input) const { -StringName AnimationTreePlayer::node_get_input_source(const StringName& p_node,int p_input) const { - - ERR_FAIL_COND_V(!node_map.has(p_node),StringName()); - ERR_FAIL_INDEX_V( p_input,node_map[p_node]->inputs.size(),StringName() ); + ERR_FAIL_COND_V(!node_map.has(p_node), StringName()); + ERR_FAIL_INDEX_V(p_input, node_map[p_node]->inputs.size(), StringName()); return node_map[p_node]->inputs[p_input].node; - } +int AnimationTreePlayer::node_get_input_count(const StringName &p_node) const { -int AnimationTreePlayer::node_get_input_count(const StringName& p_node) const { - - ERR_FAIL_COND_V(!node_map.has(p_node),-1); + ERR_FAIL_COND_V(!node_map.has(p_node), -1); return node_map[p_node]->inputs.size(); - } -#define GET_NODE( m_type, m_cast )\ - ERR_FAIL_COND(!node_map.has(p_node));\ - ERR_EXPLAIN("Invalid parameter for node type.");\ - ERR_FAIL_COND(node_map[p_node]->type!=m_type);\ - m_cast *n = static_cast( node_map[p_node] );\ - - - -void AnimationTreePlayer::animation_node_set_animation(const StringName& p_node,const Ref& p_animation) { - - GET_NODE( NODE_ANIMATION, AnimationNode ); - n->animation=p_animation; - dirty_caches=true; +#define GET_NODE(m_type, m_cast) \ + ERR_FAIL_COND(!node_map.has(p_node)); \ + ERR_EXPLAIN("Invalid parameter for node type."); \ + ERR_FAIL_COND(node_map[p_node]->type != m_type); \ + m_cast *n = static_cast(node_map[p_node]); +void AnimationTreePlayer::animation_node_set_animation(const StringName &p_node, const Ref &p_animation) { + GET_NODE(NODE_ANIMATION, AnimationNode); + n->animation = p_animation; + dirty_caches = true; } -void AnimationTreePlayer::animation_node_set_master_animation(const StringName& p_node,const String& p_master_animation) { +void AnimationTreePlayer::animation_node_set_master_animation(const StringName &p_node, const String &p_master_animation) { - GET_NODE( NODE_ANIMATION, AnimationNode ); - n->from=p_master_animation; - dirty_caches=true; - if (master!=NodePath()) + GET_NODE(NODE_ANIMATION, AnimationNode); + n->from = p_master_animation; + dirty_caches = true; + if (master != NodePath()) _update_sources(); - - } -void AnimationTreePlayer::animation_node_set_filter_path(const StringName& p_node,const NodePath& p_track_path,bool p_filter) { +void AnimationTreePlayer::animation_node_set_filter_path(const StringName &p_node, const NodePath &p_track_path, bool p_filter) { - GET_NODE( NODE_ANIMATION, AnimationNode ); + GET_NODE(NODE_ANIMATION, AnimationNode); if (p_filter) - n->filter[p_track_path]=true; + n->filter[p_track_path] = true; else n->filter.erase(p_track_path); - } -void AnimationTreePlayer::animation_node_set_get_filtered_paths(const StringName& p_node,List *r_paths) const{ +void AnimationTreePlayer::animation_node_set_get_filtered_paths(const StringName &p_node, List *r_paths) const { - GET_NODE( NODE_ANIMATION, AnimationNode ); + GET_NODE(NODE_ANIMATION, AnimationNode); n->filter.get_key_list(r_paths); } -void AnimationTreePlayer::oneshot_node_set_fadein_time(const StringName& p_node,float p_time) { - - GET_NODE( NODE_ONESHOT, OneShotNode ); - n->fade_in=p_time; +void AnimationTreePlayer::oneshot_node_set_fadein_time(const StringName &p_node, float p_time) { + GET_NODE(NODE_ONESHOT, OneShotNode); + n->fade_in = p_time; } +void AnimationTreePlayer::oneshot_node_set_fadeout_time(const StringName &p_node, float p_time) { -void AnimationTreePlayer::oneshot_node_set_fadeout_time(const StringName& p_node,float p_time) { - - GET_NODE( NODE_ONESHOT, OneShotNode ); - n->fade_out=p_time; - - + GET_NODE(NODE_ONESHOT, OneShotNode); + n->fade_out = p_time; } -void AnimationTreePlayer::oneshot_node_set_mix_mode(const StringName& p_node,bool p_mix) { +void AnimationTreePlayer::oneshot_node_set_mix_mode(const StringName &p_node, bool p_mix) { - GET_NODE( NODE_ONESHOT, OneShotNode ); - n->mix=p_mix; + GET_NODE(NODE_ONESHOT, OneShotNode); + n->mix = p_mix; } +void AnimationTreePlayer::oneshot_node_set_autorestart(const StringName &p_node, bool p_active) { -void AnimationTreePlayer::oneshot_node_set_autorestart(const StringName& p_node,bool p_active) { - - GET_NODE( NODE_ONESHOT, OneShotNode ); - n->autorestart=p_active; - + GET_NODE(NODE_ONESHOT, OneShotNode); + n->autorestart = p_active; } -void AnimationTreePlayer::oneshot_node_set_autorestart_delay(const StringName& p_node,float p_time) { - - GET_NODE( NODE_ONESHOT, OneShotNode ); - n->autorestart_delay=p_time; +void AnimationTreePlayer::oneshot_node_set_autorestart_delay(const StringName &p_node, float p_time) { + GET_NODE(NODE_ONESHOT, OneShotNode); + n->autorestart_delay = p_time; } -void AnimationTreePlayer::oneshot_node_set_autorestart_random_delay(const StringName& p_node,float p_time) { - - GET_NODE( NODE_ONESHOT, OneShotNode ); - n->autorestart_random_delay=p_time; +void AnimationTreePlayer::oneshot_node_set_autorestart_random_delay(const StringName &p_node, float p_time) { + GET_NODE(NODE_ONESHOT, OneShotNode); + n->autorestart_random_delay = p_time; } -void AnimationTreePlayer::oneshot_node_start(const StringName& p_node) { - - GET_NODE( NODE_ONESHOT, OneShotNode ); - n->active=true; - n->start=true; +void AnimationTreePlayer::oneshot_node_start(const StringName &p_node) { + GET_NODE(NODE_ONESHOT, OneShotNode); + n->active = true; + n->start = true; } +void AnimationTreePlayer::oneshot_node_stop(const StringName &p_node) { -void AnimationTreePlayer::oneshot_node_stop(const StringName& p_node) { - - GET_NODE( NODE_ONESHOT, OneShotNode ); - n->active=false; - + GET_NODE(NODE_ONESHOT, OneShotNode); + n->active = false; } +void AnimationTreePlayer::oneshot_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable) { -void AnimationTreePlayer::oneshot_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable) { - - GET_NODE( NODE_ONESHOT, OneShotNode ); + GET_NODE(NODE_ONESHOT, OneShotNode); if (p_enable) - n->filter[p_filter]=true; + n->filter[p_filter] = true; else n->filter.erase(p_filter); - } -void AnimationTreePlayer::oneshot_node_set_get_filtered_paths(const StringName& p_node,List *r_paths) const{ +void AnimationTreePlayer::oneshot_node_set_get_filtered_paths(const StringName &p_node, List *r_paths) const { - GET_NODE( NODE_ONESHOT, OneShotNode ); + GET_NODE(NODE_ONESHOT, OneShotNode); n->filter.get_key_list(r_paths); } +void AnimationTreePlayer::mix_node_set_amount(const StringName &p_node, float p_amount) { -void AnimationTreePlayer::mix_node_set_amount(const StringName& p_node,float p_amount) { - - GET_NODE( NODE_MIX, MixNode ); - n->amount=p_amount; - + GET_NODE(NODE_MIX, MixNode); + n->amount = p_amount; } +void AnimationTreePlayer::blend2_node_set_amount(const StringName &p_node, float p_amount) { -void AnimationTreePlayer::blend2_node_set_amount(const StringName& p_node,float p_amount) { - - GET_NODE( NODE_BLEND2, Blend2Node ); - n->value=p_amount; - + GET_NODE(NODE_BLEND2, Blend2Node); + n->value = p_amount; } -void AnimationTreePlayer::blend2_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable) { +void AnimationTreePlayer::blend2_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable) { - GET_NODE( NODE_BLEND2, Blend2Node ); + GET_NODE(NODE_BLEND2, Blend2Node); if (p_enable) - n->filter[p_filter]=true; + n->filter[p_filter] = true; else n->filter.erase(p_filter); - } -void AnimationTreePlayer::blend2_node_set_get_filtered_paths(const StringName& p_node,List *r_paths) const{ +void AnimationTreePlayer::blend2_node_set_get_filtered_paths(const StringName &p_node, List *r_paths) const { - GET_NODE( NODE_BLEND2, Blend2Node ); + GET_NODE(NODE_BLEND2, Blend2Node); n->filter.get_key_list(r_paths); } +void AnimationTreePlayer::blend3_node_set_amount(const StringName &p_node, float p_amount) { -void AnimationTreePlayer::blend3_node_set_amount(const StringName& p_node,float p_amount) { - - GET_NODE( NODE_BLEND3, Blend3Node ); - n->value=p_amount; - + GET_NODE(NODE_BLEND3, Blend3Node); + n->value = p_amount; } -void AnimationTreePlayer::blend4_node_set_amount(const StringName& p_node,const Vector2& p_amount) { - - GET_NODE( NODE_BLEND4, Blend4Node ); - n->value=p_amount; +void AnimationTreePlayer::blend4_node_set_amount(const StringName &p_node, const Vector2 &p_amount) { + GET_NODE(NODE_BLEND4, Blend4Node); + n->value = p_amount; } -void AnimationTreePlayer::timescale_node_set_scale(const StringName& p_node,float p_scale) { - - - GET_NODE( NODE_TIMESCALE, TimeScaleNode ); - n->scale=p_scale; +void AnimationTreePlayer::timescale_node_set_scale(const StringName &p_node, float p_scale) { + GET_NODE(NODE_TIMESCALE, TimeScaleNode); + n->scale = p_scale; } -void AnimationTreePlayer::timeseek_node_seek(const StringName& p_node,float p_pos) { - - - GET_NODE( NODE_TIMESEEK, TimeSeekNode ); - n->seek_pos=p_pos; +void AnimationTreePlayer::timeseek_node_seek(const StringName &p_node, float p_pos) { + GET_NODE(NODE_TIMESEEK, TimeSeekNode); + n->seek_pos = p_pos; } -void AnimationTreePlayer::transition_node_set_input_count(const StringName& p_node, int p_inputs) { - +void AnimationTreePlayer::transition_node_set_input_count(const StringName &p_node, int p_inputs) { - GET_NODE( NODE_TRANSITION, TransitionNode ); - ERR_FAIL_COND(p_inputs<1); + GET_NODE(NODE_TRANSITION, TransitionNode); + ERR_FAIL_COND(p_inputs < 1); n->inputs.resize(p_inputs); n->input_data.resize(p_inputs); - last_error=_cycle_test(out_name); - + last_error = _cycle_test(out_name); } -void AnimationTreePlayer::transition_node_set_input_auto_advance(const StringName& p_node, int p_input,bool p_auto_advance) { +void AnimationTreePlayer::transition_node_set_input_auto_advance(const StringName &p_node, int p_input, bool p_auto_advance) { - GET_NODE( NODE_TRANSITION, TransitionNode ); - ERR_FAIL_INDEX(p_input,n->input_data.size()); - - n->input_data[p_input].auto_advance=p_auto_advance; + GET_NODE(NODE_TRANSITION, TransitionNode); + ERR_FAIL_INDEX(p_input, n->input_data.size()); + n->input_data[p_input].auto_advance = p_auto_advance; } -void AnimationTreePlayer::transition_node_set_xfade_time(const StringName& p_node, float p_time) { - +void AnimationTreePlayer::transition_node_set_xfade_time(const StringName &p_node, float p_time) { - GET_NODE( NODE_TRANSITION, TransitionNode ); - n->xfade=p_time; + GET_NODE(NODE_TRANSITION, TransitionNode); + n->xfade = p_time; } void AnimationTreePlayer::TransitionNode::set_current(int p_current) { - ERR_FAIL_INDEX(p_current,inputs.size()); + ERR_FAIL_INDEX(p_current, inputs.size()); - if (current==p_current) + if (current == p_current) return; - prev=current; - prev_xfading=xfade; - prev_time=time; - time=0; - current=p_current; - switched=true; + prev = current; + prev_xfading = xfade; + prev_time = time; + time = 0; + current = p_current; + switched = true; } -void AnimationTreePlayer::transition_node_set_current(const StringName& p_node, int p_current) { +void AnimationTreePlayer::transition_node_set_current(const StringName &p_node, int p_current) { - GET_NODE( NODE_TRANSITION, TransitionNode ); + GET_NODE(NODE_TRANSITION, TransitionNode); n->set_current(p_current); } - -void AnimationTreePlayer::node_set_pos(const StringName& p_node, const Vector2& p_pos) { +void AnimationTreePlayer::node_set_pos(const StringName &p_node, const Vector2 &p_pos) { ERR_FAIL_COND(!node_map.has(p_node)); - node_map[p_node]->pos=p_pos; - + node_map[p_node]->pos = p_pos; } -AnimationTreePlayer::NodeType AnimationTreePlayer::node_get_type(const StringName& p_node) const { +AnimationTreePlayer::NodeType AnimationTreePlayer::node_get_type(const StringName &p_node) const { - ERR_FAIL_COND_V(!node_map.has(p_node),NODE_OUTPUT); + ERR_FAIL_COND_V(!node_map.has(p_node), NODE_OUTPUT); return node_map[p_node]->type; - } -Point2 AnimationTreePlayer::node_get_pos(const StringName& p_node) const { +Point2 AnimationTreePlayer::node_get_pos(const StringName &p_node) const { - ERR_FAIL_COND_V(!node_map.has(p_node),Point2()); + ERR_FAIL_COND_V(!node_map.has(p_node), Point2()); return node_map[p_node]->pos; - - } -#define GET_NODE_V( m_type, m_cast, m_ret )\ - ERR_FAIL_COND_V(!node_map.has(p_node),m_ret);\ - ERR_EXPLAIN("Invalid parameter for node type.");\ - ERR_FAIL_COND_V(node_map[p_node]->type!=m_type,m_ret);\ - m_cast *n = static_cast( node_map[p_node] );\ +#define GET_NODE_V(m_type, m_cast, m_ret) \ + ERR_FAIL_COND_V(!node_map.has(p_node), m_ret); \ + ERR_EXPLAIN("Invalid parameter for node type."); \ + ERR_FAIL_COND_V(node_map[p_node]->type != m_type, m_ret); \ + m_cast *n = static_cast(node_map[p_node]); -Ref AnimationTreePlayer::animation_node_get_animation(const StringName& p_node) const { +Ref AnimationTreePlayer::animation_node_get_animation(const StringName &p_node) const { GET_NODE_V(NODE_ANIMATION, AnimationNode, Ref()); return n->animation; - } -String AnimationTreePlayer::animation_node_get_master_animation(const StringName& p_node) const { +String AnimationTreePlayer::animation_node_get_master_animation(const StringName &p_node) const { GET_NODE_V(NODE_ANIMATION, AnimationNode, String()); return n->from; - } -bool AnimationTreePlayer::animation_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const { +bool AnimationTreePlayer::animation_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const { - GET_NODE_V(NODE_ANIMATION, AnimationNode, 0 ); + GET_NODE_V(NODE_ANIMATION, AnimationNode, 0); return n->filter.has(p_path); } -float AnimationTreePlayer::oneshot_node_get_fadein_time(const StringName& p_node) const { +float AnimationTreePlayer::oneshot_node_get_fadein_time(const StringName &p_node) const { - - GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 ); + GET_NODE_V(NODE_ONESHOT, OneShotNode, 0); return n->fade_in; - } -float AnimationTreePlayer::oneshot_node_get_fadeout_time(const StringName& p_node) const { +float AnimationTreePlayer::oneshot_node_get_fadeout_time(const StringName &p_node) const { - GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 ); + GET_NODE_V(NODE_ONESHOT, OneShotNode, 0); return n->fade_out; - } -bool AnimationTreePlayer::oneshot_node_get_mix_mode(const StringName& p_node) const { +bool AnimationTreePlayer::oneshot_node_get_mix_mode(const StringName &p_node) const { - GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 ); + GET_NODE_V(NODE_ONESHOT, OneShotNode, 0); return n->mix; - } -bool AnimationTreePlayer::oneshot_node_has_autorestart(const StringName& p_node) const { +bool AnimationTreePlayer::oneshot_node_has_autorestart(const StringName &p_node) const { - GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 ); + GET_NODE_V(NODE_ONESHOT, OneShotNode, 0); return n->autorestart; - } -float AnimationTreePlayer::oneshot_node_get_autorestart_delay(const StringName& p_node) const { +float AnimationTreePlayer::oneshot_node_get_autorestart_delay(const StringName &p_node) const { - GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 ); + GET_NODE_V(NODE_ONESHOT, OneShotNode, 0); return n->autorestart_delay; - } -float AnimationTreePlayer::oneshot_node_get_autorestart_random_delay(const StringName& p_node) const { +float AnimationTreePlayer::oneshot_node_get_autorestart_random_delay(const StringName &p_node) const { - GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 ); + GET_NODE_V(NODE_ONESHOT, OneShotNode, 0); return n->autorestart_random_delay; - } -bool AnimationTreePlayer::oneshot_node_is_active(const StringName& p_node) const { - +bool AnimationTreePlayer::oneshot_node_is_active(const StringName &p_node) const { - GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 ); + GET_NODE_V(NODE_ONESHOT, OneShotNode, 0); return n->active; - } -bool AnimationTreePlayer::oneshot_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const { +bool AnimationTreePlayer::oneshot_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const { - GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 ); + GET_NODE_V(NODE_ONESHOT, OneShotNode, 0); return n->filter.has(p_path); } +float AnimationTreePlayer::mix_node_get_amount(const StringName &p_node) const { -float AnimationTreePlayer::mix_node_get_amount(const StringName& p_node) const { - - GET_NODE_V(NODE_MIX, MixNode, 0 ); + GET_NODE_V(NODE_MIX, MixNode, 0); return n->amount; - } -float AnimationTreePlayer::blend2_node_get_amount(const StringName& p_node) const { +float AnimationTreePlayer::blend2_node_get_amount(const StringName &p_node) const { - GET_NODE_V(NODE_BLEND2, Blend2Node, 0 ); + GET_NODE_V(NODE_BLEND2, Blend2Node, 0); return n->value; - } -bool AnimationTreePlayer::blend2_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const { +bool AnimationTreePlayer::blend2_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const { - GET_NODE_V(NODE_BLEND2, Blend2Node, 0 ); + GET_NODE_V(NODE_BLEND2, Blend2Node, 0); return n->filter.has(p_path); } -float AnimationTreePlayer::blend3_node_get_amount(const StringName& p_node) const { - +float AnimationTreePlayer::blend3_node_get_amount(const StringName &p_node) const { - GET_NODE_V(NODE_BLEND3, Blend3Node, 0 ); + GET_NODE_V(NODE_BLEND3, Blend3Node, 0); return n->value; - } -Vector2 AnimationTreePlayer::blend4_node_get_amount(const StringName& p_node) const { +Vector2 AnimationTreePlayer::blend4_node_get_amount(const StringName &p_node) const { - GET_NODE_V(NODE_BLEND4, Blend4Node, Vector2() ); + GET_NODE_V(NODE_BLEND4, Blend4Node, Vector2()); return n->value; - } -float AnimationTreePlayer::timescale_node_get_scale(const StringName& p_node) const { +float AnimationTreePlayer::timescale_node_get_scale(const StringName &p_node) const { - GET_NODE_V(NODE_TIMESCALE, TimeScaleNode, 0 ); + GET_NODE_V(NODE_TIMESCALE, TimeScaleNode, 0); return n->scale; - } -void AnimationTreePlayer::transition_node_delete_input(const StringName& p_node, int p_input) { +void AnimationTreePlayer::transition_node_delete_input(const StringName &p_node, int p_input) { GET_NODE(NODE_TRANSITION, TransitionNode); - ERR_FAIL_INDEX(p_input,n->inputs.size()); + ERR_FAIL_INDEX(p_input, n->inputs.size()); - if (n->inputs.size()<=1) + if (n->inputs.size() <= 1) return; - n->inputs.remove(p_input); n->input_data.remove(p_input); - last_error=_cycle_test(out_name); + last_error = _cycle_test(out_name); } +int AnimationTreePlayer::transition_node_get_input_count(const StringName &p_node) const { -int AnimationTreePlayer::transition_node_get_input_count(const StringName& p_node) const { - - GET_NODE_V(NODE_TRANSITION, TransitionNode, 0 ); + GET_NODE_V(NODE_TRANSITION, TransitionNode, 0); return n->inputs.size(); } -bool AnimationTreePlayer::transition_node_has_input_auto_advance(const StringName& p_node, int p_input) const { +bool AnimationTreePlayer::transition_node_has_input_auto_advance(const StringName &p_node, int p_input) const { - GET_NODE_V(NODE_TRANSITION, TransitionNode, false ); - ERR_FAIL_INDEX_V(p_input,n->inputs.size(),false); + GET_NODE_V(NODE_TRANSITION, TransitionNode, false); + ERR_FAIL_INDEX_V(p_input, n->inputs.size(), false); return n->input_data[p_input].auto_advance; - } -float AnimationTreePlayer::transition_node_get_xfade_time(const StringName& p_node) const { +float AnimationTreePlayer::transition_node_get_xfade_time(const StringName &p_node) const { - GET_NODE_V(NODE_TRANSITION, TransitionNode, 0 ); + GET_NODE_V(NODE_TRANSITION, TransitionNode, 0); return n->xfade; - } -int AnimationTreePlayer::transition_node_get_current(const StringName& p_node) const { +int AnimationTreePlayer::transition_node_get_current(const StringName &p_node) const { - GET_NODE_V(NODE_TRANSITION, TransitionNode, -1 ); + GET_NODE_V(NODE_TRANSITION, TransitionNode, -1); return n->current; - } - /*misc */ +/*misc */ void AnimationTreePlayer::get_node_list(List *p_node_list) const { - for(Map::Element *E=node_map.front();E;E=E->next()) { + for (Map::Element *E = node_map.front(); E; E = E->next()) { - p_node_list->push_back( E->key() ); + p_node_list->push_back(E->key()); } } -void AnimationTreePlayer::remove_node(const StringName& p_node) { +void AnimationTreePlayer::remove_node(const StringName &p_node) { - ERR_FAIL_COND( !node_map.has(p_node) ); + ERR_FAIL_COND(!node_map.has(p_node)); ERR_EXPLAIN("Node 0 (output) can't be removed."); - ERR_FAIL_COND( p_node == out_name ); + ERR_FAIL_COND(p_node == out_name); - for(Map::Element *E=node_map.front();E;E=E->next()) { + for (Map::Element *E = node_map.front(); E; E = E->next()) { NodeBase *nb = E->get(); - for(int i=0;iinputs.size();i++) { + for (int i = 0; i < nb->inputs.size(); i++) { - if (nb->inputs[i].node==p_node) - nb->inputs[i].node=StringName(); + if (nb->inputs[i].node == p_node) + nb->inputs[i].node = StringName(); } } node_map.erase(p_node); // compute last error again, just in case - last_error=_cycle_test(out_name); - dirty_caches=true; + last_error = _cycle_test(out_name); + dirty_caches = true; } - -AnimationTreePlayer::ConnectError AnimationTreePlayer::_cycle_test(const StringName& p_at_node) { +AnimationTreePlayer::ConnectError AnimationTreePlayer::_cycle_test(const StringName &p_at_node) { ERR_FAIL_COND_V(!node_map.has(p_at_node), CONNECT_INCOMPLETE); @@ -1480,11 +1371,10 @@ AnimationTreePlayer::ConnectError AnimationTreePlayer::_cycle_test(const StringN if (nb->cycletest) return CONNECT_CYCLE; + nb->cycletest = true; - nb->cycletest=true; - - for(int i=0;iinputs.size();i++) { - if (nb->inputs[i].node==StringName()) + for (int i = 0; i < nb->inputs.size(); i++) { + if (nb->inputs[i].node == StringName()) return CONNECT_INCOMPLETE; ConnectError _err = _cycle_test(nb->inputs[i].node); @@ -1495,195 +1385,184 @@ AnimationTreePlayer::ConnectError AnimationTreePlayer::_cycle_test(const StringN return CONNECT_OK; } +Error AnimationTreePlayer::connect_nodes(const StringName &p_src_node, const StringName &p_dst_node, int p_dst_input) { -Error AnimationTreePlayer::connect_nodes(const StringName& p_src_node,const StringName& p_dst_node, int p_dst_input) { - - ERR_FAIL_COND_V( !node_map.has(p_src_node) , ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V( !node_map.has(p_dst_node) , ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V( p_src_node==p_dst_node , ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(!node_map.has(p_src_node), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(!node_map.has(p_dst_node), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_src_node == p_dst_node, ERR_INVALID_PARAMETER); //NodeBase *src = node_map[p_src_node]; NodeBase *dst = node_map[p_dst_node]; - ERR_FAIL_INDEX_V( p_dst_input, dst->inputs.size(), ERR_INVALID_PARAMETER); + ERR_FAIL_INDEX_V(p_dst_input, dst->inputs.size(), ERR_INVALID_PARAMETER); //int oldval = dst->inputs[p_dst_input].node; - for(Map::Element *E=node_map.front();E;E=E->next()) { + for (Map::Element *E = node_map.front(); E; E = E->next()) { NodeBase *nb = E->get(); - for(int i=0;iinputs.size();i++) { + for (int i = 0; i < nb->inputs.size(); i++) { - if (nb->inputs[i].node==p_src_node) - nb->inputs[i].node=StringName(); + if (nb->inputs[i].node == p_src_node) + nb->inputs[i].node = StringName(); } } - dst->inputs[p_dst_input].node=p_src_node; + dst->inputs[p_dst_input].node = p_src_node; - for(Map::Element *E=node_map.front();E;E=E->next()) { + for (Map::Element *E = node_map.front(); E; E = E->next()) { NodeBase *nb = E->get(); - nb->cycletest=false; + nb->cycletest = false; } - last_error=_cycle_test(out_name); + last_error = _cycle_test(out_name); if (last_error) { - if (last_error==CONNECT_INCOMPLETE) + if (last_error == CONNECT_INCOMPLETE) return ERR_UNCONFIGURED; - else if (last_error==CONNECT_CYCLE) + else if (last_error == CONNECT_CYCLE) return ERR_CYCLIC_LINK; } - dirty_caches=true; + dirty_caches = true; return OK; } -bool AnimationTreePlayer::are_nodes_connected(const StringName& p_src_node,const StringName& p_dst_node, int p_dst_input) const { +bool AnimationTreePlayer::are_nodes_connected(const StringName &p_src_node, const StringName &p_dst_node, int p_dst_input) const { - ERR_FAIL_COND_V( !node_map.has(p_src_node) , false); - ERR_FAIL_COND_V( !node_map.has(p_dst_node) , false); - ERR_FAIL_COND_V( p_src_node==p_dst_node , false); + ERR_FAIL_COND_V(!node_map.has(p_src_node), false); + ERR_FAIL_COND_V(!node_map.has(p_dst_node), false); + ERR_FAIL_COND_V(p_src_node == p_dst_node, false); NodeBase *dst = node_map[p_dst_node]; - return dst->inputs[p_dst_input].node==p_src_node; - + return dst->inputs[p_dst_input].node == p_src_node; } -void AnimationTreePlayer::disconnect_nodes(const StringName& p_node, int p_input) { +void AnimationTreePlayer::disconnect_nodes(const StringName &p_node, int p_input) { - ERR_FAIL_COND( !node_map.has(p_node)); + ERR_FAIL_COND(!node_map.has(p_node)); NodeBase *dst = node_map[p_node]; - ERR_FAIL_INDEX(p_input,dst->inputs.size()); - dst->inputs[p_input].node=StringName(); - last_error=CONNECT_INCOMPLETE; - dirty_caches=true; + ERR_FAIL_INDEX(p_input, dst->inputs.size()); + dst->inputs[p_input].node = StringName(); + last_error = CONNECT_INCOMPLETE; + dirty_caches = true; } +void AnimationTreePlayer::get_connection_list(List *p_connections) const { -void AnimationTreePlayer::get_connection_list( List *p_connections) const { - - for(Map::Element *E=node_map.front();E;E=E->next()) { + for (Map::Element *E = node_map.front(); E; E = E->next()) { NodeBase *nb = E->get(); - for(int i=0;iinputs.size();i++) { + for (int i = 0; i < nb->inputs.size(); i++) { - if (nb->inputs[i].node!=StringName()) { + if (nb->inputs[i].node != StringName()) { Connection c; - c.src_node=nb->inputs[i].node; - c.dst_node=E->key(); - c.dst_input=i; + c.src_node = nb->inputs[i].node; + c.dst_node = E->key(); + c.dst_input = i; p_connections->push_back(c); } } } } -AnimationTreePlayer::Track* AnimationTreePlayer::_find_track(const NodePath& p_path) { +AnimationTreePlayer::Track *AnimationTreePlayer::_find_track(const NodePath &p_path) { - Node *parent=get_node(base_path); - ERR_FAIL_COND_V(!parent,NULL); + Node *parent = get_node(base_path); + ERR_FAIL_COND_V(!parent, NULL); RES resource; - Node *child=parent->get_node_and_resource(p_path,resource); + Node *child = parent->get_node_and_resource(p_path, resource); if (!child) { - String err = "Animation track references unknown Node: '"+String(p_path)+"'."; + String err = "Animation track references unknown Node: '" + String(p_path) + "'."; WARN_PRINT(err.ascii().get_data()); return NULL; } - ObjectID id=child->get_instance_ID(); + ObjectID id = child->get_instance_ID(); StringName property; - int bone_idx=-1; + int bone_idx = -1; if (p_path.get_property()) { if (child->cast_to()) - bone_idx = child->cast_to()->find_bone( p_path.get_property() ); - if (bone_idx==-1) - property=p_path.get_property(); + bone_idx = child->cast_to()->find_bone(p_path.get_property()); + if (bone_idx == -1) + property = p_path.get_property(); } TrackKey key; - key.id=id; - key.bone_idx=bone_idx; - key.property=property; + key.id = id; + key.bone_idx = bone_idx; + key.property = property; if (!track_map.has(key)) { Track tr; - tr.id=id; - tr.object=resource.is_valid()?(Object*)resource.ptr():(Object*)child; - tr.skeleton=child->cast_to(); - tr.spatial=child->cast_to(); - tr.bone_idx=bone_idx; - tr.property=property; - - track_map[key]=tr; + tr.id = id; + tr.object = resource.is_valid() ? (Object *)resource.ptr() : (Object *)child; + tr.skeleton = child->cast_to(); + tr.spatial = child->cast_to(); + tr.bone_idx = bone_idx; + tr.property = property; + + track_map[key] = tr; } return &track_map[key]; - } void AnimationTreePlayer::_recompute_caches() { track_map.clear(); _recompute_caches(out_name); - dirty_caches=false; + dirty_caches = false; } -void AnimationTreePlayer::_recompute_caches(const StringName& p_node) { +void AnimationTreePlayer::_recompute_caches(const StringName &p_node) { - ERR_FAIL_COND( !node_map.has(p_node) ); + ERR_FAIL_COND(!node_map.has(p_node)); NodeBase *nb = node_map[p_node]; - if (nb->type==NODE_ANIMATION) { + if (nb->type == NODE_ANIMATION) { - AnimationNode *an = static_cast(nb); + AnimationNode *an = static_cast(nb); an->tref.clear(); if (!an->animation.is_null()) { - Ref a = an->animation; - for(int i=0;ianimation->get_track_count();i++) { - + for (int i = 0; i < an->animation->get_track_count(); i++) { Track *tr = _find_track(a->track_get_path(i)); if (!tr) continue; AnimationNode::TrackRef tref; - tref.local_track=i; - tref.track=tr; - tref.weight=0; + tref.local_track = i; + tref.track = tr; + tref.weight = 0; an->tref.push_back(tref); - } } } - for(int i=0;iinputs.size();i++) { + for (int i = 0; i < nb->inputs.size(); i++) { _recompute_caches(nb->inputs[i].node); } - } void AnimationTreePlayer::recompute_caches() { - dirty_caches=true; - + dirty_caches = true; } - - - /* playback */ +/* playback */ void AnimationTreePlayer::set_active(bool p_active) { @@ -1699,7 +1578,6 @@ void AnimationTreePlayer::set_active(bool p_active) { bool AnimationTreePlayer::is_active() const { return active; - } AnimationTreePlayer::ConnectError AnimationTreePlayer::get_last_error() const { @@ -1709,33 +1587,31 @@ AnimationTreePlayer::ConnectError AnimationTreePlayer::get_last_error() const { void AnimationTreePlayer::reset() { - - reset_request=true; + reset_request = true; } +void AnimationTreePlayer::set_base_path(const NodePath &p_path) { -void AnimationTreePlayer::set_base_path(const NodePath& p_path) { - - base_path=p_path; + base_path = p_path; recompute_caches(); } -NodePath AnimationTreePlayer::get_base_path() const{ +NodePath AnimationTreePlayer::get_base_path() const { return base_path; } -void AnimationTreePlayer::set_master_player(const NodePath& p_path) { +void AnimationTreePlayer::set_master_player(const NodePath &p_path) { - if (p_path==master) + if (p_path == master) return; - master=p_path; + master = p_path; _update_sources(); recompute_caches(); } -NodePath AnimationTreePlayer::get_master_player() const{ +NodePath AnimationTreePlayer::get_master_player() const { return master; } @@ -1746,25 +1622,24 @@ PoolVector AnimationTreePlayer::_get_node_list() { get_node_list(&nl); PoolVector ret; ret.resize(nl.size()); - int idx=0; - for(List::Element *E=nl.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (List::Element *E = nl.front(); E; E = E->next()) { + ret.set(idx++, E->get()); } return ret; } - void AnimationTreePlayer::_update_sources() { - if (master==NodePath()) + if (master == NodePath()) return; if (!is_inside_tree()) return; Node *m = get_node(master); if (!m) { - master=NodePath(); + master = NodePath(); ERR_FAIL_COND(!m); } @@ -1772,197 +1647,187 @@ void AnimationTreePlayer::_update_sources() { if (!ap) { - master=NodePath(); + master = NodePath(); ERR_FAIL_COND(!ap); } - for (Map::Element *E=node_map.front();E;E=E->next()) { + for (Map::Element *E = node_map.front(); E; E = E->next()) { - if (E->get()->type==NODE_ANIMATION) { + if (E->get()->type == NODE_ANIMATION) { - AnimationNode *an = static_cast(E->get()); + AnimationNode *an = static_cast(E->get()); - if (an->from!="") { + if (an->from != "") { an->animation = ap->get_animation(an->from); } } } - - } -bool AnimationTreePlayer::node_exists(const StringName& p_name) const { +bool AnimationTreePlayer::node_exists(const StringName &p_name) const { return (node_map.has(p_name)); } -Error AnimationTreePlayer::node_rename(const StringName& p_node,const StringName& p_new_name) { +Error AnimationTreePlayer::node_rename(const StringName &p_node, const StringName &p_new_name) { - if (p_new_name==p_node) + if (p_new_name == p_node) return OK; - ERR_FAIL_COND_V(!node_map.has(p_node),ERR_ALREADY_EXISTS); - ERR_FAIL_COND_V(node_map.has(p_new_name),ERR_ALREADY_EXISTS); - ERR_FAIL_COND_V(p_new_name==StringName(),ERR_INVALID_DATA); - ERR_FAIL_COND_V(p_node==out_name,ERR_INVALID_DATA); - ERR_FAIL_COND_V(p_new_name==out_name,ERR_INVALID_DATA); + ERR_FAIL_COND_V(!node_map.has(p_node), ERR_ALREADY_EXISTS); + ERR_FAIL_COND_V(node_map.has(p_new_name), ERR_ALREADY_EXISTS); + ERR_FAIL_COND_V(p_new_name == StringName(), ERR_INVALID_DATA); + ERR_FAIL_COND_V(p_node == out_name, ERR_INVALID_DATA); + ERR_FAIL_COND_V(p_new_name == out_name, ERR_INVALID_DATA); - for(Map::Element *E=node_map.front();E;E=E->next()) { + for (Map::Element *E = node_map.front(); E; E = E->next()) { NodeBase *nb = E->get(); - for(int i=0;iinputs.size();i++) { + for (int i = 0; i < nb->inputs.size(); i++) { - if (nb->inputs[i].node==p_node) { - nb->inputs[i].node=p_new_name; + if (nb->inputs[i].node == p_node) { + nb->inputs[i].node = p_new_name; } } } - node_map[p_new_name]=node_map[p_node]; + node_map[p_new_name] = node_map[p_node]; node_map.erase(p_node); return OK; - } - void AnimationTreePlayer::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_node","type","id"),&AnimationTreePlayer::add_node); - - ClassDB::bind_method(D_METHOD("node_exists","node"),&AnimationTreePlayer::node_exists); - ClassDB::bind_method(D_METHOD("node_rename","node","new_name"),&AnimationTreePlayer::node_rename); - - ClassDB::bind_method(D_METHOD("node_get_type","id"),&AnimationTreePlayer::node_get_type); - ClassDB::bind_method(D_METHOD("node_get_input_count","id"),&AnimationTreePlayer::node_get_input_count); - ClassDB::bind_method(D_METHOD("node_get_input_source","id","idx"),&AnimationTreePlayer::node_get_input_source); + ClassDB::bind_method(D_METHOD("add_node", "type", "id"), &AnimationTreePlayer::add_node); - ClassDB::bind_method(D_METHOD("animation_node_set_animation","id","animation:Animation"),&AnimationTreePlayer::animation_node_set_animation); - ClassDB::bind_method(D_METHOD("animation_node_get_animation:Animation","id"),&AnimationTreePlayer::animation_node_get_animation); + ClassDB::bind_method(D_METHOD("node_exists", "node"), &AnimationTreePlayer::node_exists); + ClassDB::bind_method(D_METHOD("node_rename", "node", "new_name"), &AnimationTreePlayer::node_rename); - ClassDB::bind_method(D_METHOD("animation_node_set_master_animation","id","source"),&AnimationTreePlayer::animation_node_set_master_animation); - ClassDB::bind_method(D_METHOD("animation_node_get_master_animation","id"),&AnimationTreePlayer::animation_node_get_master_animation); - ClassDB::bind_method(D_METHOD("animation_node_set_filter_path","id","path","enable"),&AnimationTreePlayer::animation_node_set_filter_path); + ClassDB::bind_method(D_METHOD("node_get_type", "id"), &AnimationTreePlayer::node_get_type); + ClassDB::bind_method(D_METHOD("node_get_input_count", "id"), &AnimationTreePlayer::node_get_input_count); + ClassDB::bind_method(D_METHOD("node_get_input_source", "id", "idx"), &AnimationTreePlayer::node_get_input_source); - ClassDB::bind_method(D_METHOD("oneshot_node_set_fadein_time","id","time_sec"),&AnimationTreePlayer::oneshot_node_set_fadein_time); - ClassDB::bind_method(D_METHOD("oneshot_node_get_fadein_time","id"),&AnimationTreePlayer::oneshot_node_get_fadein_time); + ClassDB::bind_method(D_METHOD("animation_node_set_animation", "id", "animation:Animation"), &AnimationTreePlayer::animation_node_set_animation); + ClassDB::bind_method(D_METHOD("animation_node_get_animation:Animation", "id"), &AnimationTreePlayer::animation_node_get_animation); - ClassDB::bind_method(D_METHOD("oneshot_node_set_fadeout_time","id","time_sec"),&AnimationTreePlayer::oneshot_node_set_fadeout_time); - ClassDB::bind_method(D_METHOD("oneshot_node_get_fadeout_time","id"),&AnimationTreePlayer::oneshot_node_get_fadeout_time); + ClassDB::bind_method(D_METHOD("animation_node_set_master_animation", "id", "source"), &AnimationTreePlayer::animation_node_set_master_animation); + ClassDB::bind_method(D_METHOD("animation_node_get_master_animation", "id"), &AnimationTreePlayer::animation_node_get_master_animation); + ClassDB::bind_method(D_METHOD("animation_node_set_filter_path", "id", "path", "enable"), &AnimationTreePlayer::animation_node_set_filter_path); + ClassDB::bind_method(D_METHOD("oneshot_node_set_fadein_time", "id", "time_sec"), &AnimationTreePlayer::oneshot_node_set_fadein_time); + ClassDB::bind_method(D_METHOD("oneshot_node_get_fadein_time", "id"), &AnimationTreePlayer::oneshot_node_get_fadein_time); - ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart","id","enable"),&AnimationTreePlayer::oneshot_node_set_autorestart); - ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart_delay","id","delay_sec"),&AnimationTreePlayer::oneshot_node_set_autorestart_delay); - ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart_random_delay","id","rand_sec"),&AnimationTreePlayer::oneshot_node_set_autorestart_random_delay); + ClassDB::bind_method(D_METHOD("oneshot_node_set_fadeout_time", "id", "time_sec"), &AnimationTreePlayer::oneshot_node_set_fadeout_time); + ClassDB::bind_method(D_METHOD("oneshot_node_get_fadeout_time", "id"), &AnimationTreePlayer::oneshot_node_get_fadeout_time); + ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart", "id", "enable"), &AnimationTreePlayer::oneshot_node_set_autorestart); + ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart_delay", "id", "delay_sec"), &AnimationTreePlayer::oneshot_node_set_autorestart_delay); + ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart_random_delay", "id", "rand_sec"), &AnimationTreePlayer::oneshot_node_set_autorestart_random_delay); - ClassDB::bind_method(D_METHOD("oneshot_node_has_autorestart","id"),&AnimationTreePlayer::oneshot_node_has_autorestart); - ClassDB::bind_method(D_METHOD("oneshot_node_get_autorestart_delay","id"),&AnimationTreePlayer::oneshot_node_get_autorestart_delay); - ClassDB::bind_method(D_METHOD("oneshot_node_get_autorestart_random_delay","id"),&AnimationTreePlayer::oneshot_node_get_autorestart_random_delay); + ClassDB::bind_method(D_METHOD("oneshot_node_has_autorestart", "id"), &AnimationTreePlayer::oneshot_node_has_autorestart); + ClassDB::bind_method(D_METHOD("oneshot_node_get_autorestart_delay", "id"), &AnimationTreePlayer::oneshot_node_get_autorestart_delay); + ClassDB::bind_method(D_METHOD("oneshot_node_get_autorestart_random_delay", "id"), &AnimationTreePlayer::oneshot_node_get_autorestart_random_delay); - ClassDB::bind_method(D_METHOD("oneshot_node_start","id"),&AnimationTreePlayer::oneshot_node_start); - ClassDB::bind_method(D_METHOD("oneshot_node_stop","id"),&AnimationTreePlayer::oneshot_node_stop); - ClassDB::bind_method(D_METHOD("oneshot_node_is_active","id"),&AnimationTreePlayer::oneshot_node_is_active); - ClassDB::bind_method(D_METHOD("oneshot_node_set_filter_path","id","path","enable"),&AnimationTreePlayer::oneshot_node_set_filter_path); + ClassDB::bind_method(D_METHOD("oneshot_node_start", "id"), &AnimationTreePlayer::oneshot_node_start); + ClassDB::bind_method(D_METHOD("oneshot_node_stop", "id"), &AnimationTreePlayer::oneshot_node_stop); + ClassDB::bind_method(D_METHOD("oneshot_node_is_active", "id"), &AnimationTreePlayer::oneshot_node_is_active); + ClassDB::bind_method(D_METHOD("oneshot_node_set_filter_path", "id", "path", "enable"), &AnimationTreePlayer::oneshot_node_set_filter_path); - ClassDB::bind_method(D_METHOD("mix_node_set_amount","id","ratio"),&AnimationTreePlayer::mix_node_set_amount); - ClassDB::bind_method(D_METHOD("mix_node_get_amount","id"),&AnimationTreePlayer::mix_node_get_amount); + ClassDB::bind_method(D_METHOD("mix_node_set_amount", "id", "ratio"), &AnimationTreePlayer::mix_node_set_amount); + ClassDB::bind_method(D_METHOD("mix_node_get_amount", "id"), &AnimationTreePlayer::mix_node_get_amount); - ClassDB::bind_method(D_METHOD("blend2_node_set_amount","id","blend"),&AnimationTreePlayer::blend2_node_set_amount); - ClassDB::bind_method(D_METHOD("blend2_node_get_amount","id"),&AnimationTreePlayer::blend2_node_get_amount); - ClassDB::bind_method(D_METHOD("blend2_node_set_filter_path","id","path","enable"),&AnimationTreePlayer::blend2_node_set_filter_path); + ClassDB::bind_method(D_METHOD("blend2_node_set_amount", "id", "blend"), &AnimationTreePlayer::blend2_node_set_amount); + ClassDB::bind_method(D_METHOD("blend2_node_get_amount", "id"), &AnimationTreePlayer::blend2_node_get_amount); + ClassDB::bind_method(D_METHOD("blend2_node_set_filter_path", "id", "path", "enable"), &AnimationTreePlayer::blend2_node_set_filter_path); - ClassDB::bind_method(D_METHOD("blend3_node_set_amount","id","blend"),&AnimationTreePlayer::blend3_node_set_amount); - ClassDB::bind_method(D_METHOD("blend3_node_get_amount","id"),&AnimationTreePlayer::blend3_node_get_amount); + ClassDB::bind_method(D_METHOD("blend3_node_set_amount", "id", "blend"), &AnimationTreePlayer::blend3_node_set_amount); + ClassDB::bind_method(D_METHOD("blend3_node_get_amount", "id"), &AnimationTreePlayer::blend3_node_get_amount); - ClassDB::bind_method(D_METHOD("blend4_node_set_amount","id","blend"),&AnimationTreePlayer::blend4_node_set_amount); - ClassDB::bind_method(D_METHOD("blend4_node_get_amount","id"),&AnimationTreePlayer::blend4_node_get_amount); + ClassDB::bind_method(D_METHOD("blend4_node_set_amount", "id", "blend"), &AnimationTreePlayer::blend4_node_set_amount); + ClassDB::bind_method(D_METHOD("blend4_node_get_amount", "id"), &AnimationTreePlayer::blend4_node_get_amount); - ClassDB::bind_method(D_METHOD("timescale_node_set_scale","id","scale"),&AnimationTreePlayer::timescale_node_set_scale); - ClassDB::bind_method(D_METHOD("timescale_node_get_scale","id"),&AnimationTreePlayer::timescale_node_get_scale); + ClassDB::bind_method(D_METHOD("timescale_node_set_scale", "id", "scale"), &AnimationTreePlayer::timescale_node_set_scale); + ClassDB::bind_method(D_METHOD("timescale_node_get_scale", "id"), &AnimationTreePlayer::timescale_node_get_scale); - ClassDB::bind_method(D_METHOD("timeseek_node_seek","id","pos_sec"),&AnimationTreePlayer::timeseek_node_seek); + ClassDB::bind_method(D_METHOD("timeseek_node_seek", "id", "pos_sec"), &AnimationTreePlayer::timeseek_node_seek); - ClassDB::bind_method(D_METHOD("transition_node_set_input_count","id","count"),&AnimationTreePlayer::transition_node_set_input_count); - ClassDB::bind_method(D_METHOD("transition_node_get_input_count","id"),&AnimationTreePlayer::transition_node_get_input_count); - ClassDB::bind_method(D_METHOD("transition_node_delete_input","id","input_idx"),&AnimationTreePlayer::transition_node_delete_input); + ClassDB::bind_method(D_METHOD("transition_node_set_input_count", "id", "count"), &AnimationTreePlayer::transition_node_set_input_count); + ClassDB::bind_method(D_METHOD("transition_node_get_input_count", "id"), &AnimationTreePlayer::transition_node_get_input_count); + ClassDB::bind_method(D_METHOD("transition_node_delete_input", "id", "input_idx"), &AnimationTreePlayer::transition_node_delete_input); - ClassDB::bind_method(D_METHOD("transition_node_set_input_auto_advance","id","input_idx","enable"),&AnimationTreePlayer::transition_node_set_input_auto_advance); - ClassDB::bind_method(D_METHOD("transition_node_has_input_auto_advance","id","input_idx"),&AnimationTreePlayer::transition_node_has_input_auto_advance); + ClassDB::bind_method(D_METHOD("transition_node_set_input_auto_advance", "id", "input_idx", "enable"), &AnimationTreePlayer::transition_node_set_input_auto_advance); + ClassDB::bind_method(D_METHOD("transition_node_has_input_auto_advance", "id", "input_idx"), &AnimationTreePlayer::transition_node_has_input_auto_advance); - ClassDB::bind_method(D_METHOD("transition_node_set_xfade_time","id","time_sec"),&AnimationTreePlayer::transition_node_set_xfade_time); - ClassDB::bind_method(D_METHOD("transition_node_get_xfade_time","id"),&AnimationTreePlayer::transition_node_get_xfade_time); + ClassDB::bind_method(D_METHOD("transition_node_set_xfade_time", "id", "time_sec"), &AnimationTreePlayer::transition_node_set_xfade_time); + ClassDB::bind_method(D_METHOD("transition_node_get_xfade_time", "id"), &AnimationTreePlayer::transition_node_get_xfade_time); - ClassDB::bind_method(D_METHOD("transition_node_set_current","id","input_idx"),&AnimationTreePlayer::transition_node_set_current); - ClassDB::bind_method(D_METHOD("transition_node_get_current","id"),&AnimationTreePlayer::transition_node_get_current); + ClassDB::bind_method(D_METHOD("transition_node_set_current", "id", "input_idx"), &AnimationTreePlayer::transition_node_set_current); + ClassDB::bind_method(D_METHOD("transition_node_get_current", "id"), &AnimationTreePlayer::transition_node_get_current); + ClassDB::bind_method(D_METHOD("node_set_pos", "id", "screen_pos"), &AnimationTreePlayer::node_set_pos); + ClassDB::bind_method(D_METHOD("node_get_pos", "id"), &AnimationTreePlayer::node_get_pos); - ClassDB::bind_method(D_METHOD("node_set_pos","id","screen_pos"),&AnimationTreePlayer::node_set_pos); - ClassDB::bind_method(D_METHOD("node_get_pos","id"),&AnimationTreePlayer::node_get_pos); + ClassDB::bind_method(D_METHOD("remove_node", "id"), &AnimationTreePlayer::remove_node); + ClassDB::bind_method(D_METHOD("connect_nodes", "id", "dst_id", "dst_input_idx"), &AnimationTreePlayer::connect_nodes); + ClassDB::bind_method(D_METHOD("are_nodes_connected", "id", "dst_id", "dst_input_idx"), &AnimationTreePlayer::are_nodes_connected); + ClassDB::bind_method(D_METHOD("disconnect_nodes", "id", "dst_input_idx"), &AnimationTreePlayer::disconnect_nodes); - ClassDB::bind_method(D_METHOD("remove_node","id"),&AnimationTreePlayer::remove_node); - ClassDB::bind_method(D_METHOD("connect_nodes","id","dst_id","dst_input_idx"),&AnimationTreePlayer::connect_nodes); - ClassDB::bind_method(D_METHOD("are_nodes_connected","id","dst_id","dst_input_idx"),&AnimationTreePlayer::are_nodes_connected); - ClassDB::bind_method(D_METHOD("disconnect_nodes","id","dst_input_idx"),&AnimationTreePlayer::disconnect_nodes); + ClassDB::bind_method(D_METHOD("set_active", "enabled"), &AnimationTreePlayer::set_active); + ClassDB::bind_method(D_METHOD("is_active"), &AnimationTreePlayer::is_active); - ClassDB::bind_method(D_METHOD("set_active","enabled"),&AnimationTreePlayer::set_active); - ClassDB::bind_method(D_METHOD("is_active"),&AnimationTreePlayer::is_active); + ClassDB::bind_method(D_METHOD("set_base_path", "path"), &AnimationTreePlayer::set_base_path); + ClassDB::bind_method(D_METHOD("get_base_path"), &AnimationTreePlayer::get_base_path); - ClassDB::bind_method(D_METHOD("set_base_path","path"),&AnimationTreePlayer::set_base_path); - ClassDB::bind_method(D_METHOD("get_base_path"),&AnimationTreePlayer::get_base_path); + ClassDB::bind_method(D_METHOD("set_master_player", "nodepath"), &AnimationTreePlayer::set_master_player); + ClassDB::bind_method(D_METHOD("get_master_player"), &AnimationTreePlayer::get_master_player); - ClassDB::bind_method(D_METHOD("set_master_player","nodepath"),&AnimationTreePlayer::set_master_player); - ClassDB::bind_method(D_METHOD("get_master_player"),&AnimationTreePlayer::get_master_player); + ClassDB::bind_method(D_METHOD("get_node_list"), &AnimationTreePlayer::_get_node_list); - ClassDB::bind_method(D_METHOD("get_node_list"),&AnimationTreePlayer::_get_node_list); - - ClassDB::bind_method(D_METHOD("set_animation_process_mode","mode"),&AnimationTreePlayer::set_animation_process_mode); - ClassDB::bind_method(D_METHOD("get_animation_process_mode"),&AnimationTreePlayer::get_animation_process_mode); + ClassDB::bind_method(D_METHOD("set_animation_process_mode", "mode"), &AnimationTreePlayer::set_animation_process_mode); + ClassDB::bind_method(D_METHOD("get_animation_process_mode"), &AnimationTreePlayer::get_animation_process_mode); ClassDB::bind_method(D_METHOD("advance", "delta"), &AnimationTreePlayer::advance); + ClassDB::bind_method(D_METHOD("reset"), &AnimationTreePlayer::reset); - ClassDB::bind_method(D_METHOD("reset"),&AnimationTreePlayer::reset); - - ClassDB::bind_method(D_METHOD("recompute_caches"),&AnimationTreePlayer::recompute_caches); + ClassDB::bind_method(D_METHOD("recompute_caches"), &AnimationTreePlayer::recompute_caches); - ADD_GROUP("Playback","playback_"); + ADD_GROUP("Playback", "playback_"); ADD_PROPERTY(PropertyInfo(Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_animation_process_mode", "get_animation_process_mode"); - BIND_CONSTANT( NODE_OUTPUT ); - BIND_CONSTANT( NODE_ANIMATION ); - BIND_CONSTANT( NODE_ONESHOT ); - BIND_CONSTANT( NODE_MIX ); - BIND_CONSTANT( NODE_BLEND2 ); - BIND_CONSTANT( NODE_BLEND3 ); - BIND_CONSTANT( NODE_BLEND4 ); - BIND_CONSTANT( NODE_TIMESCALE ); - BIND_CONSTANT( NODE_TIMESEEK ); - BIND_CONSTANT( NODE_TRANSITION ); + BIND_CONSTANT(NODE_OUTPUT); + BIND_CONSTANT(NODE_ANIMATION); + BIND_CONSTANT(NODE_ONESHOT); + BIND_CONSTANT(NODE_MIX); + BIND_CONSTANT(NODE_BLEND2); + BIND_CONSTANT(NODE_BLEND3); + BIND_CONSTANT(NODE_BLEND4); + BIND_CONSTANT(NODE_TIMESCALE); + BIND_CONSTANT(NODE_TIMESEEK); + BIND_CONSTANT(NODE_TRANSITION); } - AnimationTreePlayer::AnimationTreePlayer() { - active_list=NULL; - out = memnew( NodeOut ) ; - out_name="out"; - out->pos=Point2(40,40); - node_map.insert( out_name , out); + active_list = NULL; + out = memnew(NodeOut); + out_name = "out"; + out->pos = Point2(40, 40); + node_map.insert(out_name, out); animation_process_mode = ANIMATION_PROCESS_IDLE; processing = false; - active=false; - dirty_caches=true; - reset_request=true; - last_error=CONNECT_INCOMPLETE; - base_path=String(".."); + active = false; + dirty_caches = true; + reset_request = true; + last_error = CONNECT_INCOMPLETE; + base_path = String(".."); } - AnimationTreePlayer::~AnimationTreePlayer() { - while(node_map.size()) { - memdelete( node_map.front()->get() ); - node_map.erase( node_map.front() ); + while (node_map.size()) { + memdelete(node_map.front()->get()); + node_map.erase(node_map.front()); } } diff --git a/scene/animation/animation_tree_player.h b/scene/animation/animation_tree_player.h index 5e118be03..35fce9b15 100644 --- a/scene/animation/animation_tree_player.h +++ b/scene/animation/animation_tree_player.h @@ -29,16 +29,14 @@ #ifndef ANIMATION_TREE_PLAYER_H #define ANIMATION_TREE_PLAYER_H - -#include "scene/resources/animation.h" -#include "scene/3d/spatial.h" -#include "scene/3d/skeleton.h" #include "animation_player.h" - +#include "scene/3d/skeleton.h" +#include "scene/3d/spatial.h" +#include "scene/resources/animation.h" class AnimationTreePlayer : public Node { - GDCLASS( AnimationTreePlayer, Node ); + GDCLASS(AnimationTreePlayer, Node); OBJ_CATEGORY("Animation Nodes"); public: @@ -71,10 +69,9 @@ public: }; private: - enum { - DISCONNECTED=-1, + DISCONNECTED = -1, }; struct TrackKey { @@ -83,23 +80,22 @@ private: StringName property; int bone_idx; - inline bool operator<(const TrackKey& p_right) const { + inline bool operator<(const TrackKey &p_right) const { - if (id==p_right.id) { - if (bone_idx==p_right.bone_idx) { - return property TrackMap; + typedef Map TrackMap; TrackMap track_map; - struct Input { StringName node; @@ -132,23 +126,24 @@ private: NodeType type; Point2 pos; - Vector inputs; NodeBase() { cycletest = false; }; - virtual ~NodeBase() { cycletest=false; } + virtual ~NodeBase() { cycletest = false; } }; struct NodeOut : public NodeBase { - NodeOut() { type=NODE_OUTPUT; inputs.resize(1); } + NodeOut() { + type = NODE_OUTPUT; + inputs.resize(1); + } }; struct AnimationNode : public NodeBase { Ref animation; - struct TrackRef { int local_track; Track *track; @@ -163,13 +158,17 @@ private: String from; bool skip; - HashMap filter; + HashMap filter; - AnimationNode() { type=NODE_ANIMATION; next=NULL; last_version=0; skip=false; } + AnimationNode() { + type = NODE_ANIMATION; + next = NULL; + last_version = 0; + skip = false; + } }; - - struct OneShotNode : public NodeBase { + struct OneShotNode : public NodeBase { bool active; bool start; @@ -181,52 +180,84 @@ private: float autorestart_random_delay; bool mix; - float time; float remaining; float autorestart_remaining; - HashMap filter; - - OneShotNode() { type=NODE_ONESHOT; fade_in=0; fade_out=0; inputs.resize(2); autorestart=false; autorestart_delay=1; autorestart_remaining=0; mix=false; active=false; start=false;} + HashMap filter; + + OneShotNode() { + type = NODE_ONESHOT; + fade_in = 0; + fade_out = 0; + inputs.resize(2); + autorestart = false; + autorestart_delay = 1; + autorestart_remaining = 0; + mix = false; + active = false; + start = false; + } }; struct MixNode : public NodeBase { float amount; - MixNode() { type=NODE_MIX; inputs.resize(2); } + MixNode() { + type = NODE_MIX; + inputs.resize(2); + } }; - struct Blend2Node : public NodeBase { + struct Blend2Node : public NodeBase { float value; - HashMap filter; - Blend2Node() { type=NODE_BLEND2; value=0; inputs.resize(2); } + HashMap filter; + Blend2Node() { + type = NODE_BLEND2; + value = 0; + inputs.resize(2); + } }; struct Blend3Node : public NodeBase { float value; - Blend3Node() { type=NODE_BLEND3; value=0; inputs.resize(3); } + Blend3Node() { + type = NODE_BLEND3; + value = 0; + inputs.resize(3); + } }; struct Blend4Node : public NodeBase { Point2 value; - Blend4Node() { type=NODE_BLEND4; inputs.resize(4); } + Blend4Node() { + type = NODE_BLEND4; + inputs.resize(4); + } }; struct TimeScaleNode : public NodeBase { float scale; - TimeScaleNode() { type=NODE_TIMESCALE; scale=1; inputs.resize(1); } + TimeScaleNode() { + type = NODE_TIMESCALE; + scale = 1; + inputs.resize(1); + } }; struct TimeSeekNode : public NodeBase { float seek_pos; - TimeSeekNode() { type=NODE_TIMESEEK; inputs.resize(1); seek_pos=-1; } + TimeSeekNode() { + type = NODE_TIMESEEK; + inputs.resize(1); + seek_pos = -1; + } }; struct TransitionNode : public NodeBase { @@ -234,7 +265,7 @@ private: struct InputData { bool auto_advance; - InputData() { auto_advance=false; } + InputData() { auto_advance = false; } }; Vector input_data; @@ -244,23 +275,30 @@ private: int prev; bool switched; - float time; int current; float xfade; - TransitionNode() { type=NODE_TRANSITION; xfade=0; inputs.resize(1); input_data.resize(1); current=0; prev=-1; prev_time=0; prev_xfading=0; switched=false; } + TransitionNode() { + type = NODE_TRANSITION; + xfade = 0; + inputs.resize(1); + input_data.resize(1); + current = 0; + prev = -1; + prev_time = 0; + prev_xfading = 0; + switched = false; + } void set_current(int p_current); }; - void _update_sources(); StringName out_name; NodeOut *out; - NodePath base_path; NodePath master; @@ -270,141 +308,132 @@ private: bool processing; bool active; bool dirty_caches; - Map node_map; + Map node_map; // return time left to finish animation - float _process_node(const StringName& p_node,AnimationNode **r_prev_anim,float p_step, bool p_seek=false, float p_fallback_weight = 1.0, HashMap* p_weights = NULL); + float _process_node(const StringName &p_node, AnimationNode **r_prev_anim, float p_step, bool p_seek = false, float p_fallback_weight = 1.0, HashMap *p_weights = NULL); void _process_animation(float p_delta); bool reset_request; ConnectError _cycle_test(const StringName &p_at_node); - Track* _find_track(const NodePath& p_path); + Track *_find_track(const NodePath &p_path); void _recompute_caches(); - void _recompute_caches(const StringName& p_node); + void _recompute_caches(const StringName &p_node); PoolVector _get_node_list(); - - void _compute_weights(float *p_fallback_weight, HashMap *p_weights, float p_coeff, const HashMap *p_filter = NULL, float p_filtered_coeff = 0); - -protected: - + void _compute_weights(float *p_fallback_weight, HashMap *p_weights, float p_coeff, const HashMap *p_filter = NULL, float p_filtered_coeff = 0); - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List *p_list) const; +protected: + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); - public: + void add_node(NodeType p_type, const StringName &p_node); // nodes must be >0 node 0 is built-in (exit) + bool node_exists(const StringName &p_name) const; - - void add_node(NodeType p_type, const StringName& p_node); // nodes must be >0 node 0 is built-in (exit) - bool node_exists(const StringName& p_name) const; - - Error node_rename(const StringName& p_node,const StringName& p_new_name); - int node_get_input_count(const StringName& p_node) const; - StringName node_get_input_source(const StringName& p_node,int p_input) const; + Error node_rename(const StringName &p_node, const StringName &p_new_name); + int node_get_input_count(const StringName &p_node) const; + StringName node_get_input_source(const StringName &p_node, int p_input) const; /* ANIMATION NODE */ - void animation_node_set_animation(const StringName& p_node,const Ref& p_animation); - Ref animation_node_get_animation(const StringName& p_node) const; - void animation_node_set_master_animation(const StringName& p_node,const String& p_master_animation); - String animation_node_get_master_animation(const StringName& p_node) const; + void animation_node_set_animation(const StringName &p_node, const Ref &p_animation); + Ref animation_node_get_animation(const StringName &p_node) const; + void animation_node_set_master_animation(const StringName &p_node, const String &p_master_animation); + String animation_node_get_master_animation(const StringName &p_node) const; - void animation_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable); - void animation_node_set_get_filtered_paths(const StringName& p_node,List *r_paths) const; - bool animation_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const; + void animation_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable); + void animation_node_set_get_filtered_paths(const StringName &p_node, List *r_paths) const; + bool animation_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const; /* ONE SHOT NODE */ - void oneshot_node_set_fadein_time(const StringName& p_node,float p_time); - void oneshot_node_set_fadeout_time(const StringName& p_node,float p_time); + void oneshot_node_set_fadein_time(const StringName &p_node, float p_time); + void oneshot_node_set_fadeout_time(const StringName &p_node, float p_time); - float oneshot_node_get_fadein_time(const StringName& p_node) const; - float oneshot_node_get_fadeout_time(const StringName& p_node) const; + float oneshot_node_get_fadein_time(const StringName &p_node) const; + float oneshot_node_get_fadeout_time(const StringName &p_node) const; - void oneshot_node_set_autorestart(const StringName& p_node,bool p_active); - void oneshot_node_set_autorestart_delay(const StringName& p_node,float p_time); - void oneshot_node_set_autorestart_random_delay(const StringName& p_node,float p_time); + void oneshot_node_set_autorestart(const StringName &p_node, bool p_active); + void oneshot_node_set_autorestart_delay(const StringName &p_node, float p_time); + void oneshot_node_set_autorestart_random_delay(const StringName &p_node, float p_time); - bool oneshot_node_has_autorestart(const StringName& p_node) const; - float oneshot_node_get_autorestart_delay(const StringName& p_node) const; - float oneshot_node_get_autorestart_random_delay(const StringName& p_node) const; + bool oneshot_node_has_autorestart(const StringName &p_node) const; + float oneshot_node_get_autorestart_delay(const StringName &p_node) const; + float oneshot_node_get_autorestart_random_delay(const StringName &p_node) const; - void oneshot_node_set_mix_mode(const StringName& p_node,bool p_enabled); - bool oneshot_node_get_mix_mode(const StringName& p_node) const; + void oneshot_node_set_mix_mode(const StringName &p_node, bool p_enabled); + bool oneshot_node_get_mix_mode(const StringName &p_node) const; - void oneshot_node_start(const StringName& p_node); - void oneshot_node_stop(const StringName& p_node); - bool oneshot_node_is_active(const StringName& p_node) const; - - void oneshot_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable); - void oneshot_node_set_get_filtered_paths(const StringName& p_node,List *r_paths) const; - bool oneshot_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const; + void oneshot_node_start(const StringName &p_node); + void oneshot_node_stop(const StringName &p_node); + bool oneshot_node_is_active(const StringName &p_node) const; + void oneshot_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable); + void oneshot_node_set_get_filtered_paths(const StringName &p_node, List *r_paths) const; + bool oneshot_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const; /* MIX/BLEND NODES */ - void mix_node_set_amount(const StringName& p_node,float p_amount); - float mix_node_get_amount(const StringName& p_node) const; + void mix_node_set_amount(const StringName &p_node, float p_amount); + float mix_node_get_amount(const StringName &p_node) const; - void blend2_node_set_amount(const StringName& p_node,float p_amount); - float blend2_node_get_amount(const StringName& p_node) const; - void blend2_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable); - void blend2_node_set_get_filtered_paths(const StringName& p_node,List *r_paths) const; - bool blend2_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const; + void blend2_node_set_amount(const StringName &p_node, float p_amount); + float blend2_node_get_amount(const StringName &p_node) const; + void blend2_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable); + void blend2_node_set_get_filtered_paths(const StringName &p_node, List *r_paths) const; + bool blend2_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const; - void blend3_node_set_amount(const StringName& p_node,float p_amount); - float blend3_node_get_amount(const StringName& p_node) const; + void blend3_node_set_amount(const StringName &p_node, float p_amount); + float blend3_node_get_amount(const StringName &p_node) const; - void blend4_node_set_amount(const StringName& p_node,const Point2& p_amount); - Point2 blend4_node_get_amount(const StringName& p_node) const; + void blend4_node_set_amount(const StringName &p_node, const Point2 &p_amount); + Point2 blend4_node_get_amount(const StringName &p_node) const; /* TIMESCALE/TIMESEEK NODES */ - void timescale_node_set_scale(const StringName& p_node,float p_scale); - float timescale_node_get_scale(const StringName& p_node) const; + void timescale_node_set_scale(const StringName &p_node, float p_scale); + float timescale_node_get_scale(const StringName &p_node) const; - void timeseek_node_seek(const StringName& p_node,float p_pos); + void timeseek_node_seek(const StringName &p_node, float p_pos); /* TRANSITION NODE */ - void transition_node_set_input_count(const StringName& p_node, int p_inputs); // used for transition node - int transition_node_get_input_count(const StringName& p_node) const; - void transition_node_delete_input(const StringName& p_node, int p_input); // used for transition node - - void transition_node_set_input_auto_advance(const StringName& p_node, int p_input,bool p_auto_advance); // used for transition node - bool transition_node_has_input_auto_advance(const StringName& p_node, int p_input) const; + void transition_node_set_input_count(const StringName &p_node, int p_inputs); // used for transition node + int transition_node_get_input_count(const StringName &p_node) const; + void transition_node_delete_input(const StringName &p_node, int p_input); // used for transition node - void transition_node_set_xfade_time(const StringName& p_node, float p_time); // used for transition node - float transition_node_get_xfade_time(const StringName& p_node) const; + void transition_node_set_input_auto_advance(const StringName &p_node, int p_input, bool p_auto_advance); // used for transition node + bool transition_node_has_input_auto_advance(const StringName &p_node, int p_input) const; - void transition_node_set_current(const StringName& p_node, int p_current); - int transition_node_get_current(const StringName& p_node) const; + void transition_node_set_xfade_time(const StringName &p_node, float p_time); // used for transition node + float transition_node_get_xfade_time(const StringName &p_node) const; + void transition_node_set_current(const StringName &p_node, int p_current); + int transition_node_get_current(const StringName &p_node) const; - void node_set_pos(const StringName& p_node, const Vector2& p_pos); //for display + void node_set_pos(const StringName &p_node, const Vector2 &p_pos); //for display /* GETS */ - Point2 node_get_pos(const StringName& p_node) const; //for display + Point2 node_get_pos(const StringName &p_node) const; //for display - NodeType node_get_type(const StringName& p_node) const; + NodeType node_get_type(const StringName &p_node) const; void get_node_list(List *p_node_list) const; - void remove_node(const StringName& p_node); + void remove_node(const StringName &p_node); - Error connect_nodes(const StringName& p_src_node,const StringName& p_dst_node, int p_dst_input); - bool are_nodes_connected(const StringName& p_src_node,const StringName& p_dst_node, int p_input) const; - void disconnect_nodes(const StringName& p_src_node, int p_input); + Error connect_nodes(const StringName &p_src_node, const StringName &p_dst_node, int p_dst_input); + bool are_nodes_connected(const StringName &p_src_node, const StringName &p_dst_node, int p_input) const; + void disconnect_nodes(const StringName &p_src_node, int p_input); - void set_base_path(const NodePath& p_path); + void set_base_path(const NodePath &p_path); NodePath get_base_path() const; - void set_master_player(const NodePath& p_path); + void set_master_player(const NodePath &p_path); NodePath get_master_player() const; struct Connection { @@ -414,7 +443,7 @@ public: int dst_input; }; - void get_connection_list( List *p_connections) const; + void get_connection_list(List *p_connections) const; /* playback */ @@ -436,12 +465,9 @@ public: AnimationTreePlayer(); ~AnimationTreePlayer(); - }; -VARIANT_ENUM_CAST( AnimationTreePlayer::NodeType ); -VARIANT_ENUM_CAST( AnimationTreePlayer::AnimationProcessMode ); +VARIANT_ENUM_CAST(AnimationTreePlayer::NodeType); +VARIANT_ENUM_CAST(AnimationTreePlayer::AnimationProcessMode); #endif // ANIMATION_TREE_PLAYER_H - - diff --git a/scene/animation/tween.cpp b/scene/animation/tween.cpp index c422e765b..c455d20b1 100644 --- a/scene/animation/tween.cpp +++ b/scene/animation/tween.cpp @@ -29,63 +29,60 @@ #include "tween.h" #include "method_bind_ext.inc" -void Tween::_add_pending_command(StringName p_key - ,const Variant& p_arg1 ,const Variant& p_arg2 ,const Variant& p_arg3 ,const Variant& p_arg4 ,const Variant& p_arg5 - ,const Variant& p_arg6 ,const Variant& p_arg7 ,const Variant& p_arg8 ,const Variant& p_arg9 ,const Variant& p_arg10 -) { +void Tween::_add_pending_command(StringName p_key, const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5, const Variant &p_arg6, const Variant &p_arg7, const Variant &p_arg8, const Variant &p_arg9, const Variant &p_arg10) { pending_commands.push_back(PendingCommand()); - PendingCommand& cmd = pending_commands.back()->get(); + PendingCommand &cmd = pending_commands.back()->get(); cmd.key = p_key; - int& count = cmd.args; - if(p_arg10.get_type() != Variant::NIL) + int &count = cmd.args; + if (p_arg10.get_type() != Variant::NIL) count = 10; - else if(p_arg9.get_type() != Variant::NIL) + else if (p_arg9.get_type() != Variant::NIL) count = 9; - else if(p_arg8.get_type() != Variant::NIL) + else if (p_arg8.get_type() != Variant::NIL) count = 8; - else if(p_arg7.get_type() != Variant::NIL) + else if (p_arg7.get_type() != Variant::NIL) count = 7; - else if(p_arg6.get_type() != Variant::NIL) + else if (p_arg6.get_type() != Variant::NIL) count = 6; - else if(p_arg5.get_type() != Variant::NIL) + else if (p_arg5.get_type() != Variant::NIL) count = 5; - else if(p_arg4.get_type() != Variant::NIL) + else if (p_arg4.get_type() != Variant::NIL) count = 4; - else if(p_arg3.get_type() != Variant::NIL) + else if (p_arg3.get_type() != Variant::NIL) count = 3; - else if(p_arg2.get_type() != Variant::NIL) + else if (p_arg2.get_type() != Variant::NIL) count = 2; - else if(p_arg1.get_type() != Variant::NIL) + else if (p_arg1.get_type() != Variant::NIL) count = 1; - if(count > 0) + if (count > 0) cmd.arg[0] = p_arg1; - if(count > 1) + if (count > 1) cmd.arg[1] = p_arg2; - if(count > 2) + if (count > 2) cmd.arg[2] = p_arg3; - if(count > 3) + if (count > 3) cmd.arg[3] = p_arg4; - if(count > 4) + if (count > 4) cmd.arg[4] = p_arg5; - if(count > 5) + if (count > 5) cmd.arg[5] = p_arg6; - if(count > 6) + if (count > 6) cmd.arg[6] = p_arg7; - if(count > 7) + if (count > 7) cmd.arg[7] = p_arg8; - if(count > 8) + if (count > 8) cmd.arg[8] = p_arg9; - if(count > 9) + if (count > 9) cmd.arg[9] = p_arg10; } void Tween::_process_pending_commands() { - for(List::Element *E=pending_commands.front();E;E=E->next()) { + for (List::Element *E = pending_commands.front(); E; E = E->next()) { - PendingCommand& cmd = E->get(); + PendingCommand &cmd = E->get(); Variant::CallError err; Variant *arg[10] = { &cmd.arg[0], @@ -99,41 +96,40 @@ void Tween::_process_pending_commands() { &cmd.arg[8], &cmd.arg[9], }; - this->call(cmd.key, (const Variant **) arg, cmd.args, err); + this->call(cmd.key, (const Variant **)arg, cmd.args, err); } pending_commands.clear(); } -bool Tween::_set(const StringName& p_name, const Variant& p_value) { +bool Tween::_set(const StringName &p_name, const Variant &p_value) { - String name=p_name; + String name = p_name; - if (name=="playback/speed" || name=="speed") { //bw compatibility + if (name == "playback/speed" || name == "speed") { //bw compatibility set_speed_scale(p_value); - } else if (name=="playback/active") { + } else if (name == "playback/active") { set_active(p_value); - } else if (name=="playback/repeat") { + } else if (name == "playback/repeat") { set_repeat(p_value); - } return true; } -bool Tween::_get(const StringName& p_name,Variant &r_ret) const { +bool Tween::_get(const StringName &p_name, Variant &r_ret) const { - String name=p_name; + String name = p_name; - if (name=="playback/speed") { //bw compatibility + if (name == "playback/speed") { //bw compatibility - r_ret=speed_scale; - } else if (name=="playback/active") { + r_ret = speed_scale; + } else if (name == "playback/active") { - r_ret=is_active(); - } else if(name=="playback/repeat") { + r_ret = is_active(); + } else if (name == "playback/repeat") { - r_ret=is_repeat(); + r_ret = is_repeat(); } return true; @@ -141,14 +137,14 @@ bool Tween::_get(const StringName& p_name,Variant &r_ret) const { void Tween::_get_property_list(List *p_list) const { - p_list->push_back( PropertyInfo( Variant::BOOL, "playback/active", PROPERTY_HINT_NONE,"" ) ); - p_list->push_back( PropertyInfo( Variant::BOOL, "playback/repeat", PROPERTY_HINT_NONE,"" ) ); - p_list->push_back( PropertyInfo( Variant::REAL, "playback/speed", PROPERTY_HINT_RANGE, "-64,64,0.01") ); + p_list->push_back(PropertyInfo(Variant::BOOL, "playback/active", PROPERTY_HINT_NONE, "")); + p_list->push_back(PropertyInfo(Variant::BOOL, "playback/repeat", PROPERTY_HINT_NONE, "")); + p_list->push_back(PropertyInfo(Variant::REAL, "playback/speed", PROPERTY_HINT_RANGE, "-64,64,0.01")); } void Tween::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_ENTER_TREE: { @@ -163,19 +159,19 @@ void Tween::_notification(int p_what) { } break; case NOTIFICATION_INTERNAL_PROCESS: { - if (tween_process_mode==TWEEN_PROCESS_FIXED) + if (tween_process_mode == TWEEN_PROCESS_FIXED) break; if (processing) - _tween_process( get_process_delta_time() ); + _tween_process(get_process_delta_time()); } break; case NOTIFICATION_INTERNAL_FIXED_PROCESS: { - if (tween_process_mode==TWEEN_PROCESS_IDLE) + if (tween_process_mode == TWEEN_PROCESS_IDLE) break; if (processing) - _tween_process( get_fixed_process_delta_time() ); + _tween_process(get_fixed_process_delta_time()); } break; case NOTIFICATION_EXIT_TREE: { @@ -186,46 +182,46 @@ void Tween::_notification(int p_what) { void Tween::_bind_methods() { - ClassDB::bind_method(D_METHOD("is_active"),&Tween::is_active ); - ClassDB::bind_method(D_METHOD("set_active","active"),&Tween::set_active ); - - ClassDB::bind_method(D_METHOD("is_repeat"),&Tween::is_repeat ); - ClassDB::bind_method(D_METHOD("set_repeat","repeat"),&Tween::set_repeat ); - - ClassDB::bind_method(D_METHOD("set_speed_scale","speed"),&Tween::set_speed_scale); - ClassDB::bind_method(D_METHOD("get_speed_scale"),&Tween::get_speed_scale); - - ClassDB::bind_method(D_METHOD("set_tween_process_mode","mode"),&Tween::set_tween_process_mode); - ClassDB::bind_method(D_METHOD("get_tween_process_mode"),&Tween::get_tween_process_mode); - - ClassDB::bind_method(D_METHOD("start"),&Tween::start ); - ClassDB::bind_method(D_METHOD("reset","object","key"),&Tween::reset, DEFVAL("") ); - ClassDB::bind_method(D_METHOD("reset_all"),&Tween::reset_all ); - ClassDB::bind_method(D_METHOD("stop","object","key"),&Tween::stop, DEFVAL("") ); - ClassDB::bind_method(D_METHOD("stop_all"),&Tween::stop_all ); - ClassDB::bind_method(D_METHOD("resume","object","key"),&Tween::resume, DEFVAL("") ); - ClassDB::bind_method(D_METHOD("resume_all"),&Tween::resume_all ); - ClassDB::bind_method(D_METHOD("remove","object","key"),&Tween::remove, DEFVAL("") ); - ClassDB::bind_method(D_METHOD("_remove","object","key","first_only"),&Tween::_remove ); - ClassDB::bind_method(D_METHOD("remove_all"),&Tween::remove_all ); - ClassDB::bind_method(D_METHOD("seek","time"),&Tween::seek ); - ClassDB::bind_method(D_METHOD("tell"),&Tween::tell ); - ClassDB::bind_method(D_METHOD("get_runtime"),&Tween::get_runtime ); - - ClassDB::bind_method(D_METHOD("interpolate_property","object","property","initial_val","final_val","duration","trans_type","ease_type","delay"),&Tween::interpolate_property, DEFVAL(0) ); - ClassDB::bind_method(D_METHOD("interpolate_method","object","method","initial_val","final_val","duration","trans_type","ease_type","delay"),&Tween::interpolate_method, DEFVAL(0) ); - ClassDB::bind_method(D_METHOD("interpolate_callback","object","duration","callback","arg1", "arg2","arg3","arg4","arg5"),&Tween::interpolate_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()) ); - ClassDB::bind_method(D_METHOD("interpolate_deferred_callback","object","duration","callback","arg1","arg2","arg3","arg4","arg5"),&Tween::interpolate_deferred_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()) ); - ClassDB::bind_method(D_METHOD("follow_property","object","property","initial_val","target","target_property","duration","trans_type","ease_type","delay"),&Tween::follow_property, DEFVAL(0) ); - ClassDB::bind_method(D_METHOD("follow_method","object","method","initial_val","target","target_method","duration","trans_type","ease_type","delay"),&Tween::follow_method, DEFVAL(0) ); - ClassDB::bind_method(D_METHOD("targeting_property","object","property","initial","initial_val","final_val","duration","trans_type","ease_type","delay"),&Tween::targeting_property, DEFVAL(0) ); - ClassDB::bind_method(D_METHOD("targeting_method","object","method","initial","initial_method","final_val","duration","trans_type","ease_type","delay"),&Tween::targeting_method, DEFVAL(0) ); - - ADD_SIGNAL( MethodInfo("tween_started", PropertyInfo( Variant::OBJECT,"object"), PropertyInfo( Variant::STRING,"key")) ); - ADD_SIGNAL( MethodInfo("tween_step", PropertyInfo( Variant::OBJECT,"object"), PropertyInfo( Variant::STRING,"key"), PropertyInfo( Variant::REAL,"elapsed"), PropertyInfo( Variant::OBJECT,"value")) ); - ADD_SIGNAL( MethodInfo("tween_completed", PropertyInfo( Variant::OBJECT,"object"), PropertyInfo( Variant::STRING,"key")) ); - - ADD_PROPERTY( PropertyInfo( Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_tween_process_mode", "get_tween_process_mode"); + ClassDB::bind_method(D_METHOD("is_active"), &Tween::is_active); + ClassDB::bind_method(D_METHOD("set_active", "active"), &Tween::set_active); + + ClassDB::bind_method(D_METHOD("is_repeat"), &Tween::is_repeat); + ClassDB::bind_method(D_METHOD("set_repeat", "repeat"), &Tween::set_repeat); + + ClassDB::bind_method(D_METHOD("set_speed_scale", "speed"), &Tween::set_speed_scale); + ClassDB::bind_method(D_METHOD("get_speed_scale"), &Tween::get_speed_scale); + + ClassDB::bind_method(D_METHOD("set_tween_process_mode", "mode"), &Tween::set_tween_process_mode); + ClassDB::bind_method(D_METHOD("get_tween_process_mode"), &Tween::get_tween_process_mode); + + ClassDB::bind_method(D_METHOD("start"), &Tween::start); + ClassDB::bind_method(D_METHOD("reset", "object", "key"), &Tween::reset, DEFVAL("")); + ClassDB::bind_method(D_METHOD("reset_all"), &Tween::reset_all); + ClassDB::bind_method(D_METHOD("stop", "object", "key"), &Tween::stop, DEFVAL("")); + ClassDB::bind_method(D_METHOD("stop_all"), &Tween::stop_all); + ClassDB::bind_method(D_METHOD("resume", "object", "key"), &Tween::resume, DEFVAL("")); + ClassDB::bind_method(D_METHOD("resume_all"), &Tween::resume_all); + ClassDB::bind_method(D_METHOD("remove", "object", "key"), &Tween::remove, DEFVAL("")); + ClassDB::bind_method(D_METHOD("_remove", "object", "key", "first_only"), &Tween::_remove); + ClassDB::bind_method(D_METHOD("remove_all"), &Tween::remove_all); + ClassDB::bind_method(D_METHOD("seek", "time"), &Tween::seek); + ClassDB::bind_method(D_METHOD("tell"), &Tween::tell); + ClassDB::bind_method(D_METHOD("get_runtime"), &Tween::get_runtime); + + ClassDB::bind_method(D_METHOD("interpolate_property", "object", "property", "initial_val", "final_val", "duration", "trans_type", "ease_type", "delay"), &Tween::interpolate_property, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("interpolate_method", "object", "method", "initial_val", "final_val", "duration", "trans_type", "ease_type", "delay"), &Tween::interpolate_method, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("interpolate_callback", "object", "duration", "callback", "arg1", "arg2", "arg3", "arg4", "arg5"), &Tween::interpolate_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("interpolate_deferred_callback", "object", "duration", "callback", "arg1", "arg2", "arg3", "arg4", "arg5"), &Tween::interpolate_deferred_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("follow_property", "object", "property", "initial_val", "target", "target_property", "duration", "trans_type", "ease_type", "delay"), &Tween::follow_property, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("follow_method", "object", "method", "initial_val", "target", "target_method", "duration", "trans_type", "ease_type", "delay"), &Tween::follow_method, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("targeting_property", "object", "property", "initial", "initial_val", "final_val", "duration", "trans_type", "ease_type", "delay"), &Tween::targeting_property, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("targeting_method", "object", "method", "initial", "initial_method", "final_val", "duration", "trans_type", "ease_type", "delay"), &Tween::targeting_method, DEFVAL(0)); + + ADD_SIGNAL(MethodInfo("tween_started", PropertyInfo(Variant::OBJECT, "object"), PropertyInfo(Variant::STRING, "key"))); + ADD_SIGNAL(MethodInfo("tween_step", PropertyInfo(Variant::OBJECT, "object"), PropertyInfo(Variant::STRING, "key"), PropertyInfo(Variant::REAL, "elapsed"), PropertyInfo(Variant::OBJECT, "value"))); + ADD_SIGNAL(MethodInfo("tween_completed", PropertyInfo(Variant::OBJECT, "object"), PropertyInfo(Variant::STRING, "key"))); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_tween_process_mode", "get_tween_process_mode"); BIND_CONSTANT(TWEEN_PROCESS_FIXED); BIND_CONSTANT(TWEEN_PROCESS_IDLE); @@ -248,9 +244,9 @@ void Tween::_bind_methods() { BIND_CONSTANT(EASE_OUT_IN); } -Variant& Tween::_get_initial_val(InterpolateData& p_data) { +Variant &Tween::_get_initial_val(InterpolateData &p_data) { - switch(p_data.type) { + switch (p_data.type) { case INTER_PROPERTY: case INTER_METHOD: case FOLLOW_PROPERTY: @@ -260,31 +256,30 @@ Variant& Tween::_get_initial_val(InterpolateData& p_data) { case TARGETING_PROPERTY: case TARGETING_METHOD: { - Object *object = ObjectDB::get_instance(p_data.target_id); - ERR_FAIL_COND_V(object == NULL,p_data.initial_val); + Object *object = ObjectDB::get_instance(p_data.target_id); + ERR_FAIL_COND_V(object == NULL, p_data.initial_val); - static Variant initial_val; - if(p_data.type == TARGETING_PROPERTY) { + static Variant initial_val; + if (p_data.type == TARGETING_PROPERTY) { - bool valid = false; - initial_val = object->get(p_data.target_key, &valid); - ERR_FAIL_COND_V(!valid,p_data.initial_val); - } else { + bool valid = false; + initial_val = object->get(p_data.target_key, &valid); + ERR_FAIL_COND_V(!valid, p_data.initial_val); + } else { - Variant::CallError error; - initial_val = object->call(p_data.target_key, NULL, 0, error); - ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK,p_data.initial_val); - } - return initial_val; + Variant::CallError error; + initial_val = object->call(p_data.target_key, NULL, 0, error); + ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK, p_data.initial_val); } - break; + return initial_val; + } break; } return p_data.delta_val; } -Variant& Tween::_get_delta_val(InterpolateData& p_data) { +Variant &Tween::_get_delta_val(InterpolateData &p_data) { - switch(p_data.type) { + switch (p_data.type) { case INTER_PROPERTY: case INTER_METHOD: return p_data.delta_val; @@ -292,72 +287,68 @@ Variant& Tween::_get_delta_val(InterpolateData& p_data) { case FOLLOW_PROPERTY: case FOLLOW_METHOD: { - Object *target = ObjectDB::get_instance(p_data.target_id); - ERR_FAIL_COND_V(target == NULL,p_data.initial_val); - - Variant final_val; + Object *target = ObjectDB::get_instance(p_data.target_id); + ERR_FAIL_COND_V(target == NULL, p_data.initial_val); - if(p_data.type == FOLLOW_PROPERTY) { + Variant final_val; - bool valid = false; - final_val = target->get(p_data.target_key, &valid); - ERR_FAIL_COND_V(!valid,p_data.initial_val); - } else { + if (p_data.type == FOLLOW_PROPERTY) { - Variant::CallError error; - final_val = target->call(p_data.target_key, NULL, 0, error); - ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK,p_data.initial_val); - } + bool valid = false; + final_val = target->get(p_data.target_key, &valid); + ERR_FAIL_COND_V(!valid, p_data.initial_val); + } else { - // convert INT to REAL is better for interpolaters - if(final_val.get_type() == Variant::INT) final_val = final_val.operator real_t(); - _calc_delta_val(p_data.initial_val, final_val, p_data.delta_val); - return p_data.delta_val; + Variant::CallError error; + final_val = target->call(p_data.target_key, NULL, 0, error); + ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK, p_data.initial_val); } - break; + + // convert INT to REAL is better for interpolaters + if (final_val.get_type() == Variant::INT) final_val = final_val.operator real_t(); + _calc_delta_val(p_data.initial_val, final_val, p_data.delta_val); + return p_data.delta_val; + } break; case TARGETING_PROPERTY: case TARGETING_METHOD: { - Variant initial_val = _get_initial_val(p_data); - // convert INT to REAL is better for interpolaters - if(initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t(); + Variant initial_val = _get_initial_val(p_data); + // convert INT to REAL is better for interpolaters + if (initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t(); - //_calc_delta_val(p_data.initial_val, p_data.final_val, p_data.delta_val); - _calc_delta_val(initial_val, p_data.final_val, p_data.delta_val); - return p_data.delta_val; - } - break; + //_calc_delta_val(p_data.initial_val, p_data.final_val, p_data.delta_val); + _calc_delta_val(initial_val, p_data.final_val, p_data.delta_val); + return p_data.delta_val; + } break; } return p_data.initial_val; } -Variant Tween::_run_equation(InterpolateData& p_data) { +Variant Tween::_run_equation(InterpolateData &p_data) { - Variant& initial_val = _get_initial_val(p_data); - Variant& delta_val = _get_delta_val(p_data); + Variant &initial_val = _get_initial_val(p_data); + Variant &delta_val = _get_delta_val(p_data); Variant result; -#define APPLY_EQUATION(element)\ +#define APPLY_EQUATION(element) \ r.element = _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, i.element, d.element, p_data.duration); - switch(initial_val.get_type()) - { + switch (initial_val.get_type()) { - case Variant::BOOL: - result = ( _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, initial_val, delta_val, p_data.duration)) >= 0.5; - break; + case Variant::BOOL: + result = (_run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, initial_val, delta_val, p_data.duration)) >= 0.5; + break; - case Variant::INT: - result = (int) _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (int) initial_val, (int) delta_val, p_data.duration); - break; + case Variant::INT: + result = (int)_run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (int)initial_val, (int)delta_val, p_data.duration); + break; - case Variant::REAL: - result = _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (real_t) initial_val, (real_t) delta_val, p_data.duration); - break; + case Variant::REAL: + result = _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (real_t)initial_val, (real_t)delta_val, p_data.duration); + break; - case Variant::VECTOR2: - { + case Variant::VECTOR2: { Vector2 i = initial_val; Vector2 d = delta_val; Vector2 r; @@ -366,11 +357,9 @@ Variant Tween::_run_equation(InterpolateData& p_data) { APPLY_EQUATION(y); result = r; - } - break; + } break; - case Variant::VECTOR3: - { + case Variant::VECTOR3: { Vector3 i = initial_val; Vector3 d = delta_val; Vector3 r; @@ -380,11 +369,9 @@ Variant Tween::_run_equation(InterpolateData& p_data) { APPLY_EQUATION(z); result = r; - } - break; + } break; - case Variant::BASIS: - { + case Variant::BASIS: { Basis i = initial_val; Basis d = delta_val; Basis r; @@ -400,11 +387,9 @@ Variant Tween::_run_equation(InterpolateData& p_data) { APPLY_EQUATION(elements[2][2]); result = r; - } - break; + } break; - case Variant::TRANSFORM2D: - { + case Variant::TRANSFORM2D: { Transform2D i = initial_val; Transform2D d = delta_val; Transform2D r; @@ -417,10 +402,8 @@ Variant Tween::_run_equation(InterpolateData& p_data) { APPLY_EQUATION(elements[2][1]); result = r; - } - break; - case Variant::QUAT: - { + } break; + case Variant::QUAT: { Quat i = initial_val; Quat d = delta_val; Quat r; @@ -431,10 +414,8 @@ Variant Tween::_run_equation(InterpolateData& p_data) { APPLY_EQUATION(w); result = r; - } - break; - case Variant::RECT3: - { + } break; + case Variant::RECT3: { Rect3 i = initial_val; Rect3 d = delta_val; Rect3 r; @@ -447,10 +428,8 @@ Variant Tween::_run_equation(InterpolateData& p_data) { APPLY_EQUATION(size.z); result = r; - } - break; - case Variant::TRANSFORM: - { + } break; + case Variant::TRANSFORM: { Transform i = initial_val; Transform d = delta_val; Transform r; @@ -469,10 +448,8 @@ Variant Tween::_run_equation(InterpolateData& p_data) { APPLY_EQUATION(origin.z); result = r; - } - break; - case Variant::COLOR: - { + } break; + case Variant::COLOR: { Color i = initial_val; Color d = delta_val; Color r; @@ -483,47 +460,44 @@ Variant Tween::_run_equation(InterpolateData& p_data) { APPLY_EQUATION(a); result = r; - } - break; + } break; }; #undef APPLY_EQUATION return result; } -bool Tween::_apply_tween_value(InterpolateData& p_data, Variant& value) { +bool Tween::_apply_tween_value(InterpolateData &p_data, Variant &value) { Object *object = ObjectDB::get_instance(p_data.id); ERR_FAIL_COND_V(object == NULL, false); - switch(p_data.type) { + switch (p_data.type) { case INTER_PROPERTY: case FOLLOW_PROPERTY: - case TARGETING_PROPERTY: - { - bool valid = false; - object->set(p_data.key,value, &valid); - return valid; - } + case TARGETING_PROPERTY: { + bool valid = false; + object->set(p_data.key, value, &valid); + return valid; + } case INTER_METHOD: case FOLLOW_METHOD: - case TARGETING_METHOD: - { - Variant::CallError error; - if (value.get_type() != Variant::NIL) { - Variant *arg[1] = { &value }; - object->call(p_data.key, (const Variant **) arg, 1, error); - } else { - object->call(p_data.key, NULL, 0, error); - } - - if(error.error == Variant::CallError::CALL_OK) - return true; - return false; + case TARGETING_METHOD: { + Variant::CallError error; + if (value.get_type() != Variant::NIL) { + Variant *arg[1] = { &value }; + object->call(p_data.key, (const Variant **)arg, 1, error); + } else { + object->call(p_data.key, NULL, 0, error); } + if (error.error == Variant::CallError::CALL_OK) + return true; + return false; + } + case INTER_CALLBACK: break; }; @@ -538,118 +512,122 @@ void Tween::_tween_process(float p_delta) { return; p_delta *= speed_scale; - pending_update ++; + pending_update++; // if repeat and all interpolates was finished then reset all interpolates - if(repeat) { + if (repeat) { bool all_finished = true; - for(List::Element *E=interpolates.front();E;E=E->next()) { + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); + InterpolateData &data = E->get(); - if(!data.finish) { + if (!data.finish) { all_finished = false; break; } } - if(all_finished) + if (all_finished) reset_all(); } - for(List::Element *E=interpolates.front();E;E=E->next()) { + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); - if(!data.active || data.finish) + InterpolateData &data = E->get(); + if (!data.active || data.finish) continue; Object *object = ObjectDB::get_instance(data.id); - if(object == NULL) + if (object == NULL) continue; bool prev_delaying = data.elapsed <= data.delay; data.elapsed += p_delta; - if(data.elapsed < data.delay) + if (data.elapsed < data.delay) continue; - else if(prev_delaying) { + else if (prev_delaying) { - emit_signal("tween_started",object,data.key); + emit_signal("tween_started", object, data.key); _apply_tween_value(data, data.initial_val); } - if(data.elapsed > (data.delay + data.duration)) { + if (data.elapsed > (data.delay + data.duration)) { data.elapsed = data.delay + data.duration; data.finish = true; } - switch(data.type) - { - case INTER_PROPERTY: - case INTER_METHOD: - break; - case INTER_CALLBACK: - if(data.finish) { + switch (data.type) { + case INTER_PROPERTY: + case INTER_METHOD: + break; + case INTER_CALLBACK: + if (data.finish) { - Variant::CallError error; - if (data.call_deferred) { - - switch (data.args) { - case 0: - object->call_deferred(data.key); break; - case 1: - object->call_deferred(data.key, data.arg[0]); break; - case 2: - object->call_deferred(data.key, data.arg[0], data.arg[1]); break; - case 3: - object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2]); break; - case 4: - object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2], data.arg[3]); break; - case 5: - object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2], data.arg[3], data.arg[4]); break; + Variant::CallError error; + if (data.call_deferred) { + + switch (data.args) { + case 0: + object->call_deferred(data.key); + break; + case 1: + object->call_deferred(data.key, data.arg[0]); + break; + case 2: + object->call_deferred(data.key, data.arg[0], data.arg[1]); + break; + case 3: + object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2]); + break; + case 4: + object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2], data.arg[3]); + break; + case 5: + object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2], data.arg[3], data.arg[4]); + break; + } + + } else { + Variant *arg[5] = { + &data.arg[0], + &data.arg[1], + &data.arg[2], + &data.arg[3], + &data.arg[4], + }; + object->call(data.key, (const Variant **)arg, data.args, error); } - - } - else { - Variant *arg[5] = { - &data.arg[0], - &data.arg[1], - &data.arg[2], - &data.arg[3], - &data.arg[4], - }; - object->call(data.key, (const Variant **) arg, data.args, error); + if (!repeat) + call_deferred("_remove", object, data.key, true); } - if (!repeat) - call_deferred("_remove", object, data.key, true); - } - continue; + continue; } Variant result = _run_equation(data); - emit_signal("tween_step",object,data.key,data.elapsed,result); + emit_signal("tween_step", object, data.key, data.elapsed, result); _apply_tween_value(data, result); if (data.finish) { - emit_signal("tween_completed",object,data.key); + emit_signal("tween_completed", object, data.key); // not repeat mode, remove completed action if (!repeat) call_deferred("_remove", object, data.key, true); } } - pending_update --; + pending_update--; } void Tween::set_tween_process_mode(TweenProcessMode p_mode) { - if (tween_process_mode==p_mode) + if (tween_process_mode == p_mode) return; bool pr = processing; if (pr) _set_process(false); - tween_process_mode=p_mode; + tween_process_mode = p_mode; if (pr) _set_process(true); } @@ -659,18 +637,18 @@ Tween::TweenProcessMode Tween::get_tween_process_mode() const { return tween_process_mode; } -void Tween::_set_process(bool p_process,bool p_force) { +void Tween::_set_process(bool p_process, bool p_force) { - if (processing==p_process && !p_force) + if (processing == p_process && !p_force) return; - switch(tween_process_mode) { + switch (tween_process_mode) { case TWEEN_PROCESS_FIXED: set_fixed_process_internal(p_process && active); break; case TWEEN_PROCESS_IDLE: set_process_internal(p_process && active); break; } - processing=p_process; + processing = p_process; } bool Tween::is_active() const { @@ -680,11 +658,11 @@ bool Tween::is_active() const { void Tween::set_active(bool p_active) { - if (active==p_active) + if (active == p_active) return; - active=p_active; - _set_process(processing,true); + active = p_active; + _set_process(processing, true); } bool Tween::is_repeat() const { @@ -699,7 +677,7 @@ void Tween::set_repeat(bool p_repeat) { void Tween::set_speed_scale(float p_speed) { - speed_scale=p_speed; + speed_scale = p_speed; } float Tween::get_speed_scale() const { @@ -716,54 +694,54 @@ bool Tween::start() { bool Tween::reset(Object *p_object, String p_key) { - pending_update ++; - for(List::Element *E=interpolates.front();E;E=E->next()) { + pending_update++; + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); + InterpolateData &data = E->get(); Object *object = ObjectDB::get_instance(data.id); - if(object == NULL) + if (object == NULL) continue; - if(object == p_object && (data.key == p_key || p_key == "")) { + if (object == p_object && (data.key == p_key || p_key == "")) { data.elapsed = 0; data.finish = false; - if(data.delay == 0) + if (data.delay == 0) _apply_tween_value(data, data.initial_val); } } - pending_update --; + pending_update--; return true; } bool Tween::reset_all() { - pending_update ++; - for(List::Element *E=interpolates.front();E;E=E->next()) { + pending_update++; + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); + InterpolateData &data = E->get(); data.elapsed = 0; data.finish = false; - if(data.delay == 0) + if (data.delay == 0) _apply_tween_value(data, data.initial_val); } - pending_update --; + pending_update--; return true; } bool Tween::stop(Object *p_object, String p_key) { - pending_update ++; - for(List::Element *E=interpolates.front();E;E=E->next()) { + pending_update++; + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); + InterpolateData &data = E->get(); Object *object = ObjectDB::get_instance(data.id); - if(object == NULL) + if (object == NULL) continue; - if(object == p_object && (data.key == p_key || p_key == "")) + if (object == p_object && (data.key == p_key || p_key == "")) data.active = false; } - pending_update --; + pending_update--; return true; } @@ -772,13 +750,13 @@ bool Tween::stop_all() { set_active(false); _set_process(false); - pending_update ++; - for(List::Element *E=interpolates.front();E;E=E->next()) { + pending_update++; + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); + InterpolateData &data = E->get(); data.active = false; } - pending_update --; + pending_update--; return true; } @@ -787,17 +765,17 @@ bool Tween::resume(Object *p_object, String p_key) { set_active(true); _set_process(true); - pending_update ++; - for(List::Element *E=interpolates.front();E;E=E->next()) { + pending_update++; + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); + InterpolateData &data = E->get(); Object *object = ObjectDB::get_instance(data.id); - if(object == NULL) + if (object == NULL) continue; - if(object == p_object && (data.key == p_key || p_key == "")) + if (object == p_object && (data.key == p_key || p_key == "")) data.active = true; } - pending_update --; + pending_update--; return true; } @@ -806,13 +784,13 @@ bool Tween::resume_all() { set_active(true); _set_process(true); - pending_update ++; - for(List::Element *E=interpolates.front();E;E=E->next()) { + pending_update++; + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); + InterpolateData &data = E->get(); data.active = true; } - pending_update --; + pending_update--; return true; } @@ -823,32 +801,32 @@ bool Tween::remove(Object *p_object, String p_key) { void Tween::_remove(Object *p_object, String p_key, bool first_only) { - if(pending_update != 0) { + if (pending_update != 0) { call_deferred("_remove", p_object, p_key, first_only); return; } List::Element *> for_removal; - for(List::Element *E=interpolates.front();E;E=E->next()) { + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); + InterpolateData &data = E->get(); Object *object = ObjectDB::get_instance(data.id); - if(object == NULL) + if (object == NULL) continue; - if(object == p_object && (data.key == p_key || p_key == "")) { + if (object == p_object && (data.key == p_key || p_key == "")) { for_removal.push_back(E); if (first_only) { break; } } } - for(List::Element *>::Element *E=for_removal.front();E;E=E->next()) { + for (List::Element *>::Element *E = for_removal.front(); E; E = E->next()) { interpolates.erase(E->get()); } } bool Tween::remove_all() { - if(pending_update != 0) { + if (pending_update != 0) { call_deferred("remove_all"); return true; } @@ -860,89 +838,87 @@ bool Tween::remove_all() { bool Tween::seek(real_t p_time) { - pending_update ++; - for(List::Element *E=interpolates.front();E;E=E->next()) { + pending_update++; + for (List::Element *E = interpolates.front(); E; E = E->next()) { - InterpolateData& data = E->get(); + InterpolateData &data = E->get(); data.elapsed = p_time; - if(data.elapsed < data.delay) { + if (data.elapsed < data.delay) { data.finish = false; continue; - } - else if(data.elapsed >= (data.delay + data.duration)) { + } else if (data.elapsed >= (data.delay + data.duration)) { data.finish = true; data.elapsed = (data.delay + data.duration); } else data.finish = false; - switch(data.type) - { - case INTER_PROPERTY: - case INTER_METHOD: - break; - case INTER_CALLBACK: - continue; + switch (data.type) { + case INTER_PROPERTY: + case INTER_METHOD: + break; + case INTER_CALLBACK: + continue; } Variant result = _run_equation(data); _apply_tween_value(data, result); } - pending_update --; + pending_update--; return true; } real_t Tween::tell() const { - pending_update ++; + pending_update++; real_t pos = 0; - for(const List::Element *E=interpolates.front();E;E=E->next()) { + for (const List::Element *E = interpolates.front(); E; E = E->next()) { - const InterpolateData& data = E->get(); - if(data.elapsed > pos) + const InterpolateData &data = E->get(); + if (data.elapsed > pos) pos = data.elapsed; } - pending_update --; + pending_update--; return pos; } real_t Tween::get_runtime() const { - pending_update ++; + pending_update++; real_t runtime = 0; - for(const List::Element *E=interpolates.front();E;E=E->next()) { + for (const List::Element *E = interpolates.front(); E; E = E->next()) { - const InterpolateData& data = E->get(); + const InterpolateData &data = E->get(); real_t t = data.delay + data.duration; - if(t > runtime) + if (t > runtime) runtime = t; } - pending_update --; + pending_update--; return runtime; } -bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final_val, Variant& p_delta_val) { +bool Tween::_calc_delta_val(const Variant &p_initial_val, const Variant &p_final_val, Variant &p_delta_val) { - const Variant& initial_val = p_initial_val; - const Variant& final_val = p_final_val; - Variant& delta_val = p_delta_val; + const Variant &initial_val = p_initial_val; + const Variant &final_val = p_final_val; + Variant &delta_val = p_delta_val; - switch(initial_val.get_type()) { + switch (initial_val.get_type()) { case Variant::BOOL: //delta_val = p_final_val; - delta_val = (int) p_final_val - (int) p_initial_val; + delta_val = (int)p_final_val - (int)p_initial_val; break; case Variant::INT: - delta_val = (int) final_val - (int) initial_val; + delta_val = (int)final_val - (int)initial_val; break; case Variant::REAL: - delta_val = (real_t) final_val - (real_t) initial_val; + delta_val = (real_t)final_val - (real_t)initial_val; break; case Variant::VECTOR2: @@ -953,11 +929,10 @@ bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final delta_val = final_val.operator Vector3() - initial_val.operator Vector3(); break; - case Variant::BASIS: - { - Basis i = initial_val; - Basis f = final_val; - delta_val = Basis(f.elements[0][0] - i.elements[0][0], + case Variant::BASIS: { + Basis i = initial_val; + Basis f = final_val; + delta_val = Basis(f.elements[0][0] - i.elements[0][0], f.elements[0][1] - i.elements[0][1], f.elements[0][2] - i.elements[0][2], f.elements[1][0] - i.elements[1][0], @@ -965,41 +940,34 @@ bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final f.elements[1][2] - i.elements[1][2], f.elements[2][0] - i.elements[2][0], f.elements[2][1] - i.elements[2][1], - f.elements[2][2] - i.elements[2][2] - ); - } - break; + f.elements[2][2] - i.elements[2][2]); + } break; - case Variant::TRANSFORM2D: - { - Transform2D i = initial_val; - Transform2D f = final_val; - Transform2D d = Transform2D(); - d[0][0] = f.elements[0][0] - i.elements[0][0]; - d[0][1] = f.elements[0][1] - i.elements[0][1]; - d[1][0] = f.elements[1][0] - i.elements[1][0]; - d[1][1] = f.elements[1][1] - i.elements[1][1]; - d[2][0] = f.elements[2][0] - i.elements[2][0]; - d[2][1] = f.elements[2][1] - i.elements[2][1]; - delta_val = d; - } - break; + case Variant::TRANSFORM2D: { + Transform2D i = initial_val; + Transform2D f = final_val; + Transform2D d = Transform2D(); + d[0][0] = f.elements[0][0] - i.elements[0][0]; + d[0][1] = f.elements[0][1] - i.elements[0][1]; + d[1][0] = f.elements[1][0] - i.elements[1][0]; + d[1][1] = f.elements[1][1] - i.elements[1][1]; + d[2][0] = f.elements[2][0] - i.elements[2][0]; + d[2][1] = f.elements[2][1] - i.elements[2][1]; + delta_val = d; + } break; case Variant::QUAT: delta_val = final_val.operator Quat() - initial_val.operator Quat(); break; - case Variant::RECT3: - { - Rect3 i = initial_val; - Rect3 f = final_val; - delta_val = Rect3(f.pos - i.pos, f.size - i.size); - } - break; - case Variant::TRANSFORM: - { - Transform i = initial_val; - Transform f = final_val; - Transform d; - d.set(f.basis.elements[0][0] - i.basis.elements[0][0], + case Variant::RECT3: { + Rect3 i = initial_val; + Rect3 f = final_val; + delta_val = Rect3(f.pos - i.pos, f.size - i.size); + } break; + case Variant::TRANSFORM: { + Transform i = initial_val; + Transform f = final_val; + Transform d; + d.set(f.basis.elements[0][0] - i.basis.elements[0][0], f.basis.elements[0][1] - i.basis.elements[0][1], f.basis.elements[0][2] - i.basis.elements[0][2], f.basis.elements[1][0] - i.basis.elements[1][0], @@ -1010,19 +978,15 @@ bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final f.basis.elements[2][2] - i.basis.elements[2][2], f.origin.x - i.origin.x, f.origin.y - i.origin.y, - f.origin.z - i.origin.z - ); + f.origin.z - i.origin.z); - delta_val = d; - } - break; - case Variant::COLOR: - { - Color i = initial_val; - Color f = final_val; - delta_val = Color(f.r - i.r, f.g - i.g, f.b - i.b, f.a - i.a); - } - break; + delta_val = d; + } break; + case Variant::COLOR: { + Color i = initial_val; + Color f = final_val; + delta_val = Color(f.r - i.r, f.g - i.g, f.b - i.b, f.a - i.a); + } break; default: ERR_PRINT("Invalid param type, except(int/real/vector2/vector/matrix/matrix32/quat/aabb/transform/color)"); @@ -1031,31 +995,14 @@ bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final return true; } -bool Tween::interpolate_property(Object *p_object - , String p_property - , Variant p_initial_val - , Variant p_final_val - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay -) { - if(pending_update != 0) { - _add_pending_command("interpolate_property" - , p_object - , p_property - , p_initial_val - , p_final_val - , p_duration - , p_trans_type - , p_ease_type - , p_delay - ); +bool Tween::interpolate_property(Object *p_object, String p_property, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { + if (pending_update != 0) { + _add_pending_command("interpolate_property", p_object, p_property, p_initial_val, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); return true; } // convert INT to REAL is better for interpolaters - if(p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t(); - if(p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t(); + if (p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t(); + if (p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t(); ERR_FAIL_COND_V(p_object == NULL, false); ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false); @@ -1066,7 +1013,7 @@ bool Tween::interpolate_property(Object *p_object ERR_FAIL_COND_V(p_delay < 0, false); bool prop_valid = false; - p_object->get(p_property,&prop_valid); + p_object->get(p_property, &prop_valid); ERR_FAIL_COND_V(!prop_valid, false); InterpolateData data; @@ -1084,38 +1031,21 @@ bool Tween::interpolate_property(Object *p_object data.ease_type = p_ease_type; data.delay = p_delay; - if(!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) + if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) return false; interpolates.push_back(data); return true; } -bool Tween::interpolate_method(Object *p_object - , String p_method - , Variant p_initial_val - , Variant p_final_val - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay -) { - if(pending_update != 0) { - _add_pending_command("interpolate_method" - , p_object - , p_method - , p_initial_val - , p_final_val - , p_duration - , p_trans_type - , p_ease_type - , p_delay - ); +bool Tween::interpolate_method(Object *p_object, String p_method, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { + if (pending_update != 0) { + _add_pending_command("interpolate_method", p_object, p_method, p_initial_val, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); return true; } // convert INT to REAL is better for interpolaters - if(p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t(); - if(p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t(); + if (p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t(); + if (p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t(); ERR_FAIL_COND_V(p_object == NULL, false); ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false); @@ -1143,30 +1073,17 @@ bool Tween::interpolate_method(Object *p_object data.ease_type = p_ease_type; data.delay = p_delay; - if(!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) + if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) return false; interpolates.push_back(data); return true; } -bool Tween::interpolate_callback(Object *p_object - , real_t p_duration - , String p_callback - , VARIANT_ARG_DECLARE -) { - - if(pending_update != 0) { - _add_pending_command("interpolate_callback" - , p_object - , p_duration - , p_callback - , p_arg1 - , p_arg2 - , p_arg3 - , p_arg4 - , p_arg5 - ); +bool Tween::interpolate_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE) { + + if (pending_update != 0) { + _add_pending_command("interpolate_callback", p_object, p_duration, p_callback, p_arg1, p_arg2, p_arg3, p_arg4, p_arg5); return true; } @@ -1189,19 +1106,19 @@ bool Tween::interpolate_callback(Object *p_object data.duration = p_duration; data.delay = 0; - int args=0; - if (p_arg5.get_type()!=Variant::NIL) - args=5; - else if (p_arg4.get_type()!=Variant::NIL) - args=4; - else if (p_arg3.get_type()!=Variant::NIL) - args=3; - else if (p_arg2.get_type()!=Variant::NIL) - args=2; - else if (p_arg1.get_type()!=Variant::NIL) - args=1; + int args = 0; + if (p_arg5.get_type() != Variant::NIL) + args = 5; + else if (p_arg4.get_type() != Variant::NIL) + args = 4; + else if (p_arg3.get_type() != Variant::NIL) + args = 3; + else if (p_arg2.get_type() != Variant::NIL) + args = 2; + else if (p_arg1.get_type() != Variant::NIL) + args = 1; else - args=0; + args = 0; data.args = args; data.arg[0] = p_arg1; @@ -1210,29 +1127,16 @@ bool Tween::interpolate_callback(Object *p_object data.arg[3] = p_arg4; data.arg[4] = p_arg5; - pending_update ++; + pending_update++; interpolates.push_back(data); - pending_update --; + pending_update--; return true; } -bool Tween::interpolate_deferred_callback(Object *p_object - , real_t p_duration - , String p_callback - , VARIANT_ARG_DECLARE -) { - - if(pending_update != 0) { - _add_pending_command("interpolate_deferred_callback" - , p_object - , p_duration - , p_callback - , p_arg1 - , p_arg2 - , p_arg3 - , p_arg4 - , p_arg5 - ); +bool Tween::interpolate_deferred_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE) { + + if (pending_update != 0) { + _add_pending_command("interpolate_deferred_callback", p_object, p_duration, p_callback, p_arg1, p_arg2, p_arg3, p_arg4, p_arg5); return true; } ERR_FAIL_COND_V(p_object == NULL, false); @@ -1254,19 +1158,19 @@ bool Tween::interpolate_deferred_callback(Object *p_object data.duration = p_duration; data.delay = 0; - int args=0; - if (p_arg5.get_type()!=Variant::NIL) - args=5; - else if (p_arg4.get_type()!=Variant::NIL) - args=4; - else if (p_arg3.get_type()!=Variant::NIL) - args=3; - else if (p_arg2.get_type()!=Variant::NIL) - args=2; - else if (p_arg1.get_type()!=Variant::NIL) - args=1; + int args = 0; + if (p_arg5.get_type() != Variant::NIL) + args = 5; + else if (p_arg4.get_type() != Variant::NIL) + args = 4; + else if (p_arg3.get_type() != Variant::NIL) + args = 3; + else if (p_arg2.get_type() != Variant::NIL) + args = 2; + else if (p_arg1.get_type() != Variant::NIL) + args = 1; else - args=0; + args = 0; data.args = args; data.arg[0] = p_arg1; @@ -1275,38 +1179,19 @@ bool Tween::interpolate_deferred_callback(Object *p_object data.arg[3] = p_arg4; data.arg[4] = p_arg5; - pending_update ++; + pending_update++; interpolates.push_back(data); - pending_update --; + pending_update--; return true; } -bool Tween::follow_property(Object *p_object - , String p_property - , Variant p_initial_val - , Object *p_target - , String p_target_property - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay -) { - if(pending_update != 0) { - _add_pending_command("follow_property" - , p_object - , p_property - , p_initial_val - , p_target - , p_target_property - , p_duration - , p_trans_type - , p_ease_type - , p_delay - ); +bool Tween::follow_property(Object *p_object, String p_property, Variant p_initial_val, Object *p_target, String p_target_property, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { + if (pending_update != 0) { + _add_pending_command("follow_property", p_object, p_property, p_initial_val, p_target, p_target_property, p_duration, p_trans_type, p_ease_type, p_delay); return true; } // convert INT to REAL is better for interpolaters - if(p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t(); + if (p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t(); ERR_FAIL_COND_V(p_object == NULL, false); ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false); @@ -1318,15 +1203,15 @@ bool Tween::follow_property(Object *p_object ERR_FAIL_COND_V(p_delay < 0, false); bool prop_valid = false; - p_object->get(p_property,&prop_valid); + p_object->get(p_property, &prop_valid); ERR_FAIL_COND_V(!prop_valid, false); bool target_prop_valid = false; - Variant target_val = p_target->get(p_target_property,&target_prop_valid); + Variant target_val = p_target->get(p_target_property, &target_prop_valid); ERR_FAIL_COND_V(!target_prop_valid, false); // convert INT to REAL is better for interpolaters - if(target_val.get_type() == Variant::INT) target_val = target_val.operator real_t(); + if (target_val.get_type() == Variant::INT) target_val = target_val.operator real_t(); ERR_FAIL_COND_V(target_val.get_type() != p_initial_val.get_type(), false); InterpolateData data; @@ -1349,32 +1234,13 @@ bool Tween::follow_property(Object *p_object return true; } -bool Tween::follow_method(Object *p_object - , String p_method - , Variant p_initial_val - , Object *p_target - , String p_target_method - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay -) { - if(pending_update != 0) { - _add_pending_command("follow_method" - , p_object - , p_method - , p_initial_val - , p_target - , p_target_method - , p_duration - , p_trans_type - , p_ease_type - , p_delay - ); +bool Tween::follow_method(Object *p_object, String p_method, Variant p_initial_val, Object *p_target, String p_target_method, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { + if (pending_update != 0) { + _add_pending_command("follow_method", p_object, p_method, p_initial_val, p_target, p_target_method, p_duration, p_trans_type, p_ease_type, p_delay); return true; } // convert INT to REAL is better for interpolaters - if(p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t(); + if (p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t(); ERR_FAIL_COND_V(p_object == NULL, false); ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false); @@ -1395,7 +1261,7 @@ bool Tween::follow_method(Object *p_object ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK, false); // convert INT to REAL is better for interpolaters - if(target_val.get_type() == Variant::INT) target_val = target_val.operator real_t(); + if (target_val.get_type() == Variant::INT) target_val = target_val.operator real_t(); ERR_FAIL_COND_V(target_val.get_type() != p_initial_val.get_type(), false); InterpolateData data; @@ -1418,32 +1284,13 @@ bool Tween::follow_method(Object *p_object return true; } -bool Tween::targeting_property(Object *p_object - , String p_property - , Object *p_initial - , String p_initial_property - , Variant p_final_val - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay -) { - if(pending_update != 0) { - _add_pending_command("targeting_property" - , p_object - , p_property - , p_initial - , p_initial_property - , p_final_val - , p_duration - , p_trans_type - , p_ease_type - , p_delay - ); +bool Tween::targeting_property(Object *p_object, String p_property, Object *p_initial, String p_initial_property, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { + if (pending_update != 0) { + _add_pending_command("targeting_property", p_object, p_property, p_initial, p_initial_property, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); return true; } // convert INT to REAL is better for interpolaters - if(p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t(); + if (p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t(); ERR_FAIL_COND_V(p_object == NULL, false); ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false); @@ -1455,15 +1302,15 @@ bool Tween::targeting_property(Object *p_object ERR_FAIL_COND_V(p_delay < 0, false); bool prop_valid = false; - p_object->get(p_property,&prop_valid); + p_object->get(p_property, &prop_valid); ERR_FAIL_COND_V(!prop_valid, false); bool initial_prop_valid = false; - Variant initial_val = p_initial->get(p_initial_property,&initial_prop_valid); + Variant initial_val = p_initial->get(p_initial_property, &initial_prop_valid); ERR_FAIL_COND_V(!initial_prop_valid, false); // convert INT to REAL is better for interpolaters - if(initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t(); + if (initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t(); ERR_FAIL_COND_V(initial_val.get_type() != p_final_val.get_type(), false); InterpolateData data; @@ -1483,40 +1330,20 @@ bool Tween::targeting_property(Object *p_object data.ease_type = p_ease_type; data.delay = p_delay; - if(!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) + if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) return false; interpolates.push_back(data); return true; } - -bool Tween::targeting_method(Object *p_object - , String p_method - , Object *p_initial - , String p_initial_method - , Variant p_final_val - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay -) { - if(pending_update != 0) { - _add_pending_command("targeting_method" - , p_object - , p_method - , p_initial - , p_initial_method - , p_final_val - , p_duration - , p_trans_type - , p_ease_type - , p_delay - ); +bool Tween::targeting_method(Object *p_object, String p_method, Object *p_initial, String p_initial_method, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { + if (pending_update != 0) { + _add_pending_command("targeting_method", p_object, p_method, p_initial, p_initial_method, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); return true; } // convert INT to REAL is better for interpolaters - if(p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t(); + if (p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t(); ERR_FAIL_COND_V(p_object == NULL, false); ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false); @@ -1537,7 +1364,7 @@ bool Tween::targeting_method(Object *p_object ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK, false); // convert INT to REAL is better for interpolaters - if(initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t(); + if (initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t(); ERR_FAIL_COND_V(initial_val.get_type() != p_final_val.get_type(), false); InterpolateData data; @@ -1557,7 +1384,7 @@ bool Tween::targeting_method(Object *p_object data.ease_type = p_ease_type; data.delay = p_delay; - if(!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) + if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) return false; interpolates.push_back(data); @@ -1567,14 +1394,13 @@ bool Tween::targeting_method(Object *p_object Tween::Tween() { //String autoplay; - tween_process_mode=TWEEN_PROCESS_IDLE; - processing=false; - active=false; - repeat=false; - speed_scale=1; - pending_update=0; + tween_process_mode = TWEEN_PROCESS_IDLE; + processing = false; + active = false; + repeat = false; + speed_scale = 1; + pending_update = 0; } Tween::~Tween() { - } diff --git a/scene/animation/tween.h b/scene/animation/tween.h index 07c2e90da..84f866f43 100644 --- a/scene/animation/tween.h +++ b/scene/animation/tween.h @@ -31,10 +31,9 @@ #include "scene/main/node.h" - class Tween : public Node { - GDCLASS( Tween, Node ); + GDCLASS(Tween, Node); public: enum TweenProcessMode { @@ -42,30 +41,30 @@ public: TWEEN_PROCESS_IDLE, }; - enum TransitionType { - TRANS_LINEAR, - TRANS_SINE, - TRANS_QUINT, - TRANS_QUART, - TRANS_QUAD, - TRANS_EXPO, - TRANS_ELASTIC, - TRANS_CUBIC, - TRANS_CIRC, - TRANS_BOUNCE, - TRANS_BACK, + enum TransitionType { + TRANS_LINEAR, + TRANS_SINE, + TRANS_QUINT, + TRANS_QUART, + TRANS_QUAD, + TRANS_EXPO, + TRANS_ELASTIC, + TRANS_CUBIC, + TRANS_CIRC, + TRANS_BOUNCE, + TRANS_BACK, TRANS_COUNT, - }; + }; - enum EaseType { - EASE_IN, - EASE_OUT, - EASE_IN_OUT, + enum EaseType { + EASE_IN, + EASE_OUT, + EASE_IN_OUT, EASE_OUT_IN, EASE_COUNT, - }; + }; private: enum InterpolateType { @@ -117,45 +116,32 @@ private: }; List pending_commands; - void _add_pending_command(StringName p_key - ,const Variant& p_arg1=Variant() - ,const Variant& p_arg2=Variant() - ,const Variant& p_arg3=Variant() - ,const Variant& p_arg4=Variant() - ,const Variant& p_arg5=Variant() - ,const Variant& p_arg6=Variant() - ,const Variant& p_arg7=Variant() - ,const Variant& p_arg8=Variant() - ,const Variant& p_arg9=Variant() - ,const Variant& p_arg10=Variant() - ); + void _add_pending_command(StringName p_key, const Variant &p_arg1 = Variant(), const Variant &p_arg2 = Variant(), const Variant &p_arg3 = Variant(), const Variant &p_arg4 = Variant(), const Variant &p_arg5 = Variant(), const Variant &p_arg6 = Variant(), const Variant &p_arg7 = Variant(), const Variant &p_arg8 = Variant(), const Variant &p_arg9 = Variant(), const Variant &p_arg10 = Variant()); void _process_pending_commands(); typedef real_t (*interpolater)(real_t t, real_t b, real_t c, real_t d); static interpolater interpolaters[TRANS_COUNT][EASE_COUNT]; real_t _run_equation(TransitionType p_trans_type, EaseType p_ease_type, real_t t, real_t b, real_t c, real_t d); - Variant& _get_delta_val(InterpolateData& p_data); - Variant& _get_initial_val(InterpolateData& p_data); - Variant _run_equation(InterpolateData& p_data); - bool _calc_delta_val(const Variant& p_initial_val, const Variant& p_final_val, Variant& p_delta_val); - bool _apply_tween_value(InterpolateData& p_data, Variant& value); + Variant &_get_delta_val(InterpolateData &p_data); + Variant &_get_initial_val(InterpolateData &p_data); + Variant _run_equation(InterpolateData &p_data); + bool _calc_delta_val(const Variant &p_initial_val, const Variant &p_final_val, Variant &p_delta_val); + bool _apply_tween_value(InterpolateData &p_data, Variant &value); void _tween_process(float p_delta); - void _set_process(bool p_process,bool p_force=false); + void _set_process(bool p_process, bool p_force = false); void _remove(Object *p_node, String p_key, bool first_only); protected: - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; void _get_property_list(List *p_list) const; void _notification(int p_what); static void _bind_methods(); public: - bool is_active() const; void set_active(bool p_active); @@ -182,89 +168,28 @@ public: real_t tell() const; real_t get_runtime() const; - bool interpolate_property(Object *p_node - , String p_property - , Variant p_initial_val - , Variant p_final_val - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay = 0 - ); - - bool interpolate_method(Object *p_node - , String p_method - , Variant p_initial_val - , Variant p_final_val - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay = 0 - ); - - bool interpolate_callback(Object *p_object - , real_t p_duration - , String p_callback - , VARIANT_ARG_DECLARE - ); - - bool interpolate_deferred_callback(Object *p_object - , real_t p_duration - , String p_callback - , VARIANT_ARG_DECLARE - ); - - bool follow_property(Object *p_node - , String p_property - , Variant p_initial_val - , Object *p_target - , String p_target_property - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay = 0 - ); - - bool follow_method(Object *p_node - , String p_method - , Variant p_initial_val - , Object *p_target - , String p_target_method - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay = 0 - ); - - bool targeting_property(Object *p_node - , String p_property - , Object *p_initial - , String p_initial_property - , Variant p_final_val - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay = 0 - ); - - bool targeting_method(Object *p_node - , String p_method - , Object *p_initial - , String p_initial_method - , Variant p_final_val - , real_t p_duration - , TransitionType p_trans_type - , EaseType p_ease_type - , real_t p_delay = 0 - ); + bool interpolate_property(Object *p_node, String p_property, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0); + + bool interpolate_method(Object *p_node, String p_method, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0); + + bool interpolate_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE); + + bool interpolate_deferred_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE); + + bool follow_property(Object *p_node, String p_property, Variant p_initial_val, Object *p_target, String p_target_property, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0); + + bool follow_method(Object *p_node, String p_method, Variant p_initial_val, Object *p_target, String p_target_method, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0); + + bool targeting_property(Object *p_node, String p_property, Object *p_initial, String p_initial_property, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0); + + bool targeting_method(Object *p_node, String p_method, Object *p_initial, String p_initial_method, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0); Tween(); ~Tween(); }; -VARIANT_ENUM_CAST( Tween::TweenProcessMode ); -VARIANT_ENUM_CAST( Tween::TransitionType ); -VARIANT_ENUM_CAST( Tween::EaseType ); +VARIANT_ENUM_CAST(Tween::TweenProcessMode); +VARIANT_ENUM_CAST(Tween::TransitionType); +VARIANT_ENUM_CAST(Tween::EaseType); #endif - diff --git a/scene/animation/tween_interpolaters.cpp b/scene/animation/tween_interpolaters.cpp index 25a27252f..ef55b63ed 100644 --- a/scene/animation/tween_interpolaters.cpp +++ b/scene/animation/tween_interpolaters.cpp @@ -34,355 +34,278 @@ const real_t pi = 3.1415926535898; // linear /////////////////////////////////////////////////////////////////////////// namespace linear { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - return c * t / d + b; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + return c * t / d + b; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - return c * t / d + b; - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + return c * t / d + b; +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - return c * t / d + b; - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + return c * t / d + b; +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return c * t / d + b; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return c * t / d + b; +} }; /////////////////////////////////////////////////////////////////////////// // sine /////////////////////////////////////////////////////////////////////////// namespace sine { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - return -c * cos(t / d * (pi / 2)) + c + b; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + return -c * cos(t / d * (pi / 2)) + c + b; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - return c * sin(t / d * (pi / 2)) + b; - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + return c * sin(t / d * (pi / 2)) + b; +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - return -c / 2 * (cos(pi * t / d) - 1) + b; - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + return -c / 2 * (cos(pi * t / d) - 1) + b; +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; /////////////////////////////////////////////////////////////////////////// // quint /////////////////////////////////////////////////////////////////////////// namespace quint { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - return c * pow(t / d, 5) + b; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + return c * pow(t / d, 5) + b; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - return c * (pow(t / d - 1, 5) + 1) + b; - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + return c * (pow(t / d - 1, 5) + 1) + b; +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - t = t / d * 2; - if (t < 1) return c / 2 * pow(t, 5) + b; - return c / 2 * (pow(t - 2, 5) + 2) + b; - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + t = t / d * 2; + if (t < 1) return c / 2 * pow(t, 5) + b; + return c / 2 * (pow(t - 2, 5) + 2) + b; +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; /////////////////////////////////////////////////////////////////////////// // quart /////////////////////////////////////////////////////////////////////////// namespace quart { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - return c * pow(t / d, 4) + b; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + return c * pow(t / d, 4) + b; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - return -c * (pow(t / d - 1, 4) - 1) + b; - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + return -c * (pow(t / d - 1, 4) - 1) + b; +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - t = t / d * 2; - if (t < 1) return c / 2 * pow(t, 4) + b; - return -c / 2 * (pow(t - 2, 4) - 2) + b; - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + t = t / d * 2; + if (t < 1) return c / 2 * pow(t, 4) + b; + return -c / 2 * (pow(t - 2, 4) - 2) + b; +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; /////////////////////////////////////////////////////////////////////////// // quad /////////////////////////////////////////////////////////////////////////// namespace quad { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - return c * pow(t / d, 2) + b; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + return c * pow(t / d, 2) + b; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - t = t / d; - return -c * t * (t - 2) + b; - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + t = t / d; + return -c * t * (t - 2) + b; +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - t = t / d * 2; - if (t < 1) return c / 2 * pow(t, 2) + b; - return -c / 2 * ((t - 1) * (t - 3) - 1) + b; - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + t = t / d * 2; + if (t < 1) return c / 2 * pow(t, 2) + b; + return -c / 2 * ((t - 1) * (t - 3) - 1) + b; +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; /////////////////////////////////////////////////////////////////////////// // expo /////////////////////////////////////////////////////////////////////////// namespace expo { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - if (t == 0) return b; - return c * pow(2, 10 * (t / d - 1)) + b - c * 0.001; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + if (t == 0) return b; + return c * pow(2, 10 * (t / d - 1)) + b - c * 0.001; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - if (t == d) return b + c; - return c * 1.001 * (-pow(2, -10 * t / d) + 1) + b; - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + if (t == d) return b + c; + return c * 1.001 * (-pow(2, -10 * t / d) + 1) + b; +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - if (t == 0) return b; - if (t == d) return b + c; - t = t / d * 2; - if (t < 1) return c / 2 * pow(2, 10 * (t - 1)) + b - c * 0.0005; - return c / 2 * 1.0005 * (-pow(2, -10 * (t - 1)) + 2) + b; - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + if (t == 0) return b; + if (t == d) return b + c; + t = t / d * 2; + if (t < 1) return c / 2 * pow(2, 10 * (t - 1)) + b - c * 0.0005; + return c / 2 * 1.0005 * (-pow(2, -10 * (t - 1)) + 2) + b; +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; /////////////////////////////////////////////////////////////////////////// // elastic /////////////////////////////////////////////////////////////////////////// namespace elastic { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - if (t == 0) return b; - if ((t /= d) == 1) return b + c; - float p = d * 0.3f; - float a = c; - float s = p / 4; - float postFix = a * pow(2,10 * (t -= 1)); // this is a fix, again, with post-increment operators - return -(postFix * sin((t * d - s) * (2 * pi) / p )) + b; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + if (t == 0) return b; + if ((t /= d) == 1) return b + c; + float p = d * 0.3f; + float a = c; + float s = p / 4; + float postFix = a * pow(2, 10 * (t -= 1)); // this is a fix, again, with post-increment operators + return -(postFix * sin((t * d - s) * (2 * pi) / p)) + b; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - if (t == 0) return b; - if ((t /= d) == 1) return b + c; - float p = d * 0.3f; - float a = c; - float s = p / 4; - return (a * pow(2, -10 * t) * sin((t * d - s) * (2 * pi) / p ) + c + b); - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + if (t == 0) return b; + if ((t /= d) == 1) return b + c; + float p = d * 0.3f; + float a = c; + float s = p / 4; + return (a * pow(2, -10 * t) * sin((t * d - s) * (2 * pi) / p) + c + b); +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - if (t == 0) return b; - if ((t /= d / 2) == 2) return b + c; - float p = d * (0.3f * 1.5f); - float a = c; - float s = p / 4; - - if (t < 1) { - float postFix = a * pow(2, 10 * (t -= 1)); // postIncrement is evil - return -0.5f * (postFix * sin((t * d - s) * (2 * pi) / p)) + b; - } - float postFix = a * pow(2, -10 * (t -= 1)); // postIncrement is evil - return postFix * sin((t * d - s) * (2 * pi) / p ) * 0.5f + c + b; - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + if (t == 0) return b; + if ((t /= d / 2) == 2) return b + c; + float p = d * (0.3f * 1.5f); + float a = c; + float s = p / 4; - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; + if (t < 1) { + float postFix = a * pow(2, 10 * (t -= 1)); // postIncrement is evil + return -0.5f * (postFix * sin((t * d - s) * (2 * pi) / p)) + b; } + float postFix = a * pow(2, -10 * (t -= 1)); // postIncrement is evil + return postFix * sin((t * d - s) * (2 * pi) / p) * 0.5f + c + b; +} + +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; /////////////////////////////////////////////////////////////////////////// // cubic /////////////////////////////////////////////////////////////////////////// namespace cubic { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - return c * (t /= d) * t * t + b; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + return c * (t /= d) * t * t + b; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - t = t / d - 1; - return c * (t * t * t + 1) + b; - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + t = t / d - 1; + return c * (t * t * t + 1) + b; +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; - return c / 2 * ((t -= 2) * t * t + 2) + b; - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; + return c / 2 * ((t -= 2) * t * t + 2) + b; +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; /////////////////////////////////////////////////////////////////////////// // circ /////////////////////////////////////////////////////////////////////////// namespace circ { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - return -c * (sqrt(1 - (t /= d) * t) - 1) + b; // TODO: ehrich: operation with t is undefined - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + return -c * (sqrt(1 - (t /= d) * t) - 1) + b; // TODO: ehrich: operation with t is undefined +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - return c * sqrt(1 - (t = t / d - 1) * t) + b; // TODO: ehrich: operation with t is undefined - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + return c * sqrt(1 - (t = t / d - 1) * t) + b; // TODO: ehrich: operation with t is undefined +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - if ((t /= d / 2) < 1) return -c / 2 * (sqrt(1 - t * t) - 1) + b; - return c / 2 * (sqrt(1 - t * (t -= 2)) + 1) + b; // TODO: ehrich: operation with t is undefined - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + if ((t /= d / 2) < 1) return -c / 2 * (sqrt(1 - t * t) - 1) + b; + return c / 2 * (sqrt(1 - t * (t -= 2)) + 1) + b; // TODO: ehrich: operation with t is undefined +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; /////////////////////////////////////////////////////////////////////////// // bounce /////////////////////////////////////////////////////////////////////////// namespace bounce { - static real_t out(real_t t, real_t b, real_t c, real_t d); +static real_t out(real_t t, real_t b, real_t c, real_t d); - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - return c - out(d - t, 0, c, d) + b; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + return c - out(d - t, 0, c, d) + b; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - if ((t /= d) < (1 / 2.75f)) { - return c*(7.5625f*t*t) + b; - } else if (t < (2/2.75f)) { - float postFix = t-=(1.5f/2.75f); - return c*(7.5625f*(postFix)*t + .75f) + b; - } else if (t < (2.5/2.75)) { - float postFix = t-=(2.25f/2.75f); - return c*(7.5625f*(postFix)*t + .9375f) + b; - } else { - float postFix = t-=(2.625f/2.75f); - return c*(7.5625f*(postFix)*t + .984375f) + b; - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + if ((t /= d) < (1 / 2.75f)) { + return c * (7.5625f * t * t) + b; + } else if (t < (2 / 2.75f)) { + float postFix = t -= (1.5f / 2.75f); + return c * (7.5625f * (postFix)*t + .75f) + b; + } else if (t < (2.5 / 2.75)) { + float postFix = t -= (2.25f / 2.75f); + return c * (7.5625f * (postFix)*t + .9375f) + b; + } else { + float postFix = t -= (2.625f / 2.75f); + return c * (7.5625f * (postFix)*t + .984375f) + b; } +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? in(t * 2, b, c / 2, d) - : out((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? in(t * 2, b, c / 2, d) : out((t * 2) - d, b + c / 2, c / 2, d); +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; /////////////////////////////////////////////////////////////////////////// // back /////////////////////////////////////////////////////////////////////////// namespace back { - static real_t in(real_t t, real_t b, real_t c, real_t d) - { - float s = 1.70158f; - float postFix = t /= d; - return c * (postFix) * t * ((s + 1) * t - s) + b; - } +static real_t in(real_t t, real_t b, real_t c, real_t d) { + float s = 1.70158f; + float postFix = t /= d; + return c * (postFix)*t * ((s + 1) * t - s) + b; +} - static real_t out(real_t t, real_t b, real_t c, real_t d) - { - float s = 1.70158f; - return c * ((t = t / d- 1) * t * ((s + 1) * t + s) + 1) + b; // TODO: ehrich: operation with t is undefined - } +static real_t out(real_t t, real_t b, real_t c, real_t d) { + float s = 1.70158f; + return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; // TODO: ehrich: operation with t is undefined +} - static real_t in_out(real_t t, real_t b, real_t c, real_t d) - { - float s = 1.70158f; - if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b; // TODO: ehrich: operation with s is undefined - float postFix = t -= 2; - return c / 2 * ((postFix) * t * (((s *= (1.525f)) + 1) * t + s) + 2) + b; // TODO: ehrich: operation with s is undefined - } +static real_t in_out(real_t t, real_t b, real_t c, real_t d) { + float s = 1.70158f; + if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b; // TODO: ehrich: operation with s is undefined + float postFix = t -= 2; + return c / 2 * ((postFix)*t * (((s *= (1.525f)) + 1) * t + s) + 2) + b; // TODO: ehrich: operation with s is undefined +} - static real_t out_in(real_t t, real_t b, real_t c, real_t d) - { - return (t < d / 2) - ? out(t * 2, b, c / 2, d) - : in((t * 2) - d, b + c / 2, c / 2, d) - ; - } +static real_t out_in(real_t t, real_t b, real_t c, real_t d) { + return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d); +} }; Tween::interpolater Tween::interpolaters[Tween::TRANS_COUNT][Tween::EASE_COUNT] = { @@ -405,4 +328,3 @@ real_t Tween::_run_equation(TransitionType p_trans_type, EaseType p_ease_type, r ERR_FAIL_COND_V(cb == NULL, b); return cb(t, b, c, d); } - diff --git a/scene/audio/audio_player.cpp b/scene/audio/audio_player.cpp index 97eaea70b..1ee31a94d 100644 --- a/scene/audio/audio_player.cpp +++ b/scene/audio/audio_player.cpp @@ -28,7 +28,6 @@ /*************************************************************************/ #include "audio_player.h" - void AudioPlayer::_mix_audio() { if (!stream_playback.is_valid()) { @@ -39,10 +38,9 @@ void AudioPlayer::_mix_audio() { return; } - if (setseek>=0.0) { + if (setseek >= 0.0) { stream_playback->start(setseek); - setseek=-1.0; //reset seek - + setseek = -1.0; //reset seek } int bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus); @@ -52,67 +50,63 @@ void AudioPlayer::_mix_audio() { int buffer_size = mix_buffer.size(); //mix - stream_playback->mix(buffer,1.0,buffer_size); + stream_playback->mix(buffer, 1.0, buffer_size); //multiply volume interpolating to avoid clicks if this changes float vol = Math::db2linear(mix_volume_db); - float vol_inc = (Math::db2linear(volume_db) - vol)/float(buffer_size); + float vol_inc = (Math::db2linear(volume_db) - vol) / float(buffer_size); - for(int i=0;iget_speaker_mode()==AudioServer::SPEAKER_MODE_STEREO) { - targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,0); + if (AudioServer::get_singleton()->get_speaker_mode() == AudioServer::SPEAKER_MODE_STEREO) { + targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 0); } else { - switch(mix_target) { + switch (mix_target) { case MIX_TARGET_STEREO: { - targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,1); + targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 1); } break; case MIX_TARGET_SURROUND: { - targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,1); - targets[1]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,2); - if (AudioServer::get_singleton()->get_speaker_mode()==AudioServer::SPEAKER_SURROUND_71) { - targets[2]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,3); + targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 1); + targets[1] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 2); + if (AudioServer::get_singleton()->get_speaker_mode() == AudioServer::SPEAKER_SURROUND_71) { + targets[2] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 3); } } break; case MIX_TARGET_CENTER: { - targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,0); + targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 0); } break; - } } - for(int c=0;c<3;c++) { + for (int c = 0; c < 3; c++) { if (!targets[c]) break; - for(int i=0;iadd_callback(_mix_audios,this); + AudioServer::get_singleton()->add_callback(_mix_audios, this); if (autoplay && !get_tree()->is_editor_hint()) { play(); } } - if (p_what==NOTIFICATION_EXIT_TREE) { - - AudioServer::get_singleton()->remove_callback(_mix_audios,this); + if (p_what == NOTIFICATION_EXIT_TREE) { + AudioServer::get_singleton()->remove_callback(_mix_audios, this); } } @@ -125,12 +119,12 @@ void AudioPlayer::set_stream(Ref p_stream) { if (stream_playback.is_valid()) { stream_playback.unref(); stream.unref(); - active=false; - setseek=-1; + active = false; + setseek = -1; } - stream=p_stream; - stream_playback=p_stream->instance_playback(); + stream = p_stream; + stream_playback = p_stream->instance_playback(); if (stream_playback.is_null()) { stream.unref(); @@ -138,7 +132,6 @@ void AudioPlayer::set_stream(Ref p_stream) { } AudioServer::get_singleton()->unlock(); - } Ref AudioPlayer::get_stream() const { @@ -148,7 +141,7 @@ Ref AudioPlayer::get_stream() const { void AudioPlayer::set_volume_db(float p_volume) { - volume_db=p_volume; + volume_db = p_volume; } float AudioPlayer::get_volume_db() const { @@ -158,26 +151,24 @@ float AudioPlayer::get_volume_db() const { void AudioPlayer::play(float p_from_pos) { if (stream_playback.is_valid()) { - mix_volume_db=volume_db; //reset volume ramp - setseek=p_from_pos; - active=true; + mix_volume_db = volume_db; //reset volume ramp + setseek = p_from_pos; + active = true; } } void AudioPlayer::seek(float p_seconds) { if (stream_playback.is_valid()) { - setseek=p_seconds; + setseek = p_seconds; } } -void AudioPlayer::stop() { +void AudioPlayer::stop() { if (stream_playback.is_valid()) { - active=false; + active = false; } - - } bool AudioPlayer::is_playing() const { @@ -189,7 +180,7 @@ bool AudioPlayer::is_playing() const { return false; } -float AudioPlayer::get_pos() { +float AudioPlayer::get_pos() { if (stream_playback.is_valid()) { return stream_playback->get_pos(); @@ -198,39 +189,38 @@ float AudioPlayer::get_pos() { return 0; } -void AudioPlayer::set_bus(const StringName& p_bus) { +void AudioPlayer::set_bus(const StringName &p_bus) { //if audio is active, must lock this AudioServer::get_singleton()->lock(); - bus=p_bus; + bus = p_bus; AudioServer::get_singleton()->unlock(); - } StringName AudioPlayer::get_bus() const { - for(int i=0;iget_bus_count();i++) { - if (AudioServer::get_singleton()->get_bus_name(i)==bus) { + for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) { + if (AudioServer::get_singleton()->get_bus_name(i) == bus) { return bus; } } return "Master"; } -void AudioPlayer::set_autoplay(bool p_enable) { +void AudioPlayer::set_autoplay(bool p_enable) { - autoplay=p_enable; + autoplay = p_enable; } -bool AudioPlayer::is_autoplay_enabled() { +bool AudioPlayer::is_autoplay_enabled() { return autoplay; } void AudioPlayer::set_mix_target(MixTarget p_target) { - mix_target=p_target; + mix_target = p_target; } -AudioPlayer::MixTarget AudioPlayer::get_mix_target() const{ +AudioPlayer::MixTarget AudioPlayer::get_mix_target() const { return mix_target; } @@ -247,20 +237,19 @@ bool AudioPlayer::_is_active() const { return active; } +void AudioPlayer::_validate_property(PropertyInfo &property) const { -void AudioPlayer::_validate_property(PropertyInfo& property) const { - - if (property.name=="bus") { + if (property.name == "bus") { String options; - for(int i=0;iget_bus_count();i++) { - if (i>0) - options+=","; + for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) { + if (i > 0) + options += ","; String name = AudioServer::get_singleton()->get_bus_name(i); - options+=name; + options += name; } - property.hint_string=options; + property.hint_string = options; } } @@ -271,59 +260,52 @@ void AudioPlayer::_bus_layout_changed() { void AudioPlayer::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_stream","stream:AudioStream"),&AudioPlayer::set_stream); - ClassDB::bind_method(D_METHOD("get_stream"),&AudioPlayer::get_stream); - - ClassDB::bind_method(D_METHOD("set_volume_db","volume_db"),&AudioPlayer::set_volume_db); - ClassDB::bind_method(D_METHOD("get_volume_db"),&AudioPlayer::get_volume_db); + ClassDB::bind_method(D_METHOD("set_stream", "stream:AudioStream"), &AudioPlayer::set_stream); + ClassDB::bind_method(D_METHOD("get_stream"), &AudioPlayer::get_stream); - ClassDB::bind_method(D_METHOD("play","from_pos"),&AudioPlayer::play,DEFVAL(0.0)); - ClassDB::bind_method(D_METHOD("seek","to_pos"),&AudioPlayer::seek); - ClassDB::bind_method(D_METHOD("stop"),&AudioPlayer::stop); + ClassDB::bind_method(D_METHOD("set_volume_db", "volume_db"), &AudioPlayer::set_volume_db); + ClassDB::bind_method(D_METHOD("get_volume_db"), &AudioPlayer::get_volume_db); - ClassDB::bind_method(D_METHOD("is_playing"),&AudioPlayer::is_playing); - ClassDB::bind_method(D_METHOD("get_pos"),&AudioPlayer::get_pos); + ClassDB::bind_method(D_METHOD("play", "from_pos"), &AudioPlayer::play, DEFVAL(0.0)); + ClassDB::bind_method(D_METHOD("seek", "to_pos"), &AudioPlayer::seek); + ClassDB::bind_method(D_METHOD("stop"), &AudioPlayer::stop); - ClassDB::bind_method(D_METHOD("set_bus","bus"),&AudioPlayer::set_bus); - ClassDB::bind_method(D_METHOD("get_bus"),&AudioPlayer::get_bus); + ClassDB::bind_method(D_METHOD("is_playing"), &AudioPlayer::is_playing); + ClassDB::bind_method(D_METHOD("get_pos"), &AudioPlayer::get_pos); - ClassDB::bind_method(D_METHOD("set_autoplay","enable"),&AudioPlayer::set_autoplay); - ClassDB::bind_method(D_METHOD("is_autoplay_enabled"),&AudioPlayer::is_autoplay_enabled); + ClassDB::bind_method(D_METHOD("set_bus", "bus"), &AudioPlayer::set_bus); + ClassDB::bind_method(D_METHOD("get_bus"), &AudioPlayer::get_bus); - ClassDB::bind_method(D_METHOD("set_mix_target","mix_target"),&AudioPlayer::set_mix_target); - ClassDB::bind_method(D_METHOD("get_mix_target"),&AudioPlayer::get_mix_target); + ClassDB::bind_method(D_METHOD("set_autoplay", "enable"), &AudioPlayer::set_autoplay); + ClassDB::bind_method(D_METHOD("is_autoplay_enabled"), &AudioPlayer::is_autoplay_enabled); - ClassDB::bind_method(D_METHOD("_set_playing","enable"),&AudioPlayer::_set_playing); - ClassDB::bind_method(D_METHOD("_is_active"),&AudioPlayer::_is_active); + ClassDB::bind_method(D_METHOD("set_mix_target", "mix_target"), &AudioPlayer::set_mix_target); + ClassDB::bind_method(D_METHOD("get_mix_target"), &AudioPlayer::get_mix_target); - ClassDB::bind_method(D_METHOD("_bus_layout_changed"),&AudioPlayer::_bus_layout_changed); + ClassDB::bind_method(D_METHOD("_set_playing", "enable"), &AudioPlayer::_set_playing); + ClassDB::bind_method(D_METHOD("_is_active"), &AudioPlayer::_is_active); + ClassDB::bind_method(D_METHOD("_bus_layout_changed"), &AudioPlayer::_bus_layout_changed); - ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"stream",PROPERTY_HINT_RESOURCE_TYPE,"AudioStream"),"set_stream","get_stream") ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"volume_db",PROPERTY_HINT_RANGE,"-80,24"),"set_volume_db","get_volume_db") ; - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"playing",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR),"_set_playing","_is_active" ); - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"autoplay"),"set_autoplay","is_autoplay_enabled") ; - ADD_PROPERTY( PropertyInfo(Variant::INT,"mix_target",PROPERTY_HINT_ENUM,"Stereo,Surround,Center"),"set_mix_target","get_mix_target"); - ADD_PROPERTY( PropertyInfo(Variant::STRING,"bus",PROPERTY_HINT_ENUM,""),"set_bus","get_bus"); - + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "volume_db", PROPERTY_HINT_RANGE, "-80,24"), "set_volume_db", "get_volume_db"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "_set_playing", "_is_active"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autoplay"), "set_autoplay", "is_autoplay_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "mix_target", PROPERTY_HINT_ENUM, "Stereo,Surround,Center"), "set_mix_target", "get_mix_target"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "bus", PROPERTY_HINT_ENUM, ""), "set_bus", "get_bus"); } AudioPlayer::AudioPlayer() { - mix_volume_db=0; - volume_db=0; - autoplay=false; - setseek=-1; - active=false; - mix_target=MIX_TARGET_STEREO; + mix_volume_db = 0; + volume_db = 0; + autoplay = false; + setseek = -1; + active = false; + mix_target = MIX_TARGET_STEREO; - AudioServer::get_singleton()->connect("bus_layout_changed",this,"_bus_layout_changed"); + AudioServer::get_singleton()->connect("bus_layout_changed", this, "_bus_layout_changed"); } - - AudioPlayer::~AudioPlayer() { - - } - diff --git a/scene/audio/audio_player.h b/scene/audio/audio_player.h index 6e34dfce1..0d7862618 100644 --- a/scene/audio/audio_player.h +++ b/scene/audio/audio_player.h @@ -32,18 +32,17 @@ #include "scene/main/node.h" #include "servers/audio/audio_stream.h" - class AudioPlayer : public Node { - GDCLASS( AudioPlayer, Node ) + GDCLASS(AudioPlayer, Node) public: - enum MixTarget { MIX_TARGET_STEREO, MIX_TARGET_SURROUND, MIX_TARGET_CENTER }; + private: Ref stream_playback; Ref stream; @@ -60,7 +59,7 @@ private: MixTarget mix_target; void _mix_audio(); - static void _mix_audios(void *self) { reinterpret_cast(self)->_mix_audio(); } + static void _mix_audios(void *self) { reinterpret_cast(self)->_mix_audio(); } void _set_playing(bool p_enable); bool _is_active() const; @@ -68,25 +67,24 @@ private: void _bus_layout_changed(); protected: - - void _validate_property(PropertyInfo& property) const; + void _validate_property(PropertyInfo &property) const; void _notification(int p_what); static void _bind_methods(); -public: +public: void set_stream(Ref p_stream); Ref get_stream() const; void set_volume_db(float p_volume); float get_volume_db() const; - void play(float p_from_pos=0.0); + void play(float p_from_pos = 0.0); void seek(float p_seconds); void stop(); bool is_playing() const; float get_pos(); - void set_bus(const StringName& p_bus); + void set_bus(const StringName &p_bus); StringName get_bus() const; void set_autoplay(bool p_enable); diff --git a/scene/gui/base_button.cpp b/scene/gui/base_button.cpp index 79b607e2e..eceee8e31 100644 --- a/scene/gui/base_button.cpp +++ b/scene/gui/base_button.cpp @@ -29,17 +29,16 @@ #include "base_button.h" #include "os/keyboard.h" #include "print_string.h" -#include "scene/scene_string_names.h" #include "scene/main/viewport.h" - +#include "scene/scene_string_names.h" void BaseButton::_unpress_group() { if (!button_group.is_valid()) return; - for (Set::Element *E=button_group->buttons.front();E;E=E->next()) { - if (E->get()==this) + for (Set::Element *E = button_group->buttons.front(); E; E = E->next()) { + if (E->get() == this) continue; E->get()->set_pressed(false); @@ -48,23 +47,22 @@ void BaseButton::_unpress_group() { void BaseButton::_gui_input(InputEvent p_event) { - if (status.disabled) // no interaction with disabled button return; - switch(p_event.type) { + switch (p_event.type) { case InputEvent::MOUSE_BUTTON: { - const InputEventMouseButton &b=p_event.mouse_button; + const InputEventMouseButton &b = p_event.mouse_button; - if ( status.disabled || b.button_index!=1 ) + if (status.disabled || b.button_index != 1) return; if (status.pressing_button) break; - if (action_mode==ACTION_MODE_BUTTON_PRESS) { + if (action_mode == ACTION_MODE_BUTTON_PRESS) { if (b.pressed) { @@ -72,47 +70,43 @@ void BaseButton::_gui_input(InputEvent p_event) { if (!toggle_mode) { //mouse press attempt - status.press_attempt=true; - status.pressing_inside=true; + status.press_attempt = true; + status.pressing_inside = true; pressed(); if (get_script_instance()) { Variant::CallError ce; - get_script_instance()->call(SceneStringNames::get_singleton()->_pressed,NULL,0,ce); + get_script_instance()->call(SceneStringNames::get_singleton()->_pressed, NULL, 0, ce); } emit_signal("pressed"); _unpress_group(); - } else { - status.pressed=!status.pressed; + status.pressed = !status.pressed; pressed(); if (get_script_instance()) { Variant::CallError ce; - get_script_instance()->call(SceneStringNames::get_singleton()->_pressed,NULL,0,ce); + get_script_instance()->call(SceneStringNames::get_singleton()->_pressed, NULL, 0, ce); } emit_signal("pressed"); _unpress_group(); - toggled(status.pressed); - emit_signal("toggled",status.pressed); - + emit_signal("toggled", status.pressed); } - } else { emit_signal("button_up"); -/* this is pointless if (status.press_attempt && status.pressing_inside) { + /* this is pointless if (status.press_attempt && status.pressing_inside) { //released(); emit_signal("released"); } */ - status.press_attempt=false; + status.press_attempt = false; } update(); break; @@ -120,59 +114,54 @@ void BaseButton::_gui_input(InputEvent p_event) { if (b.pressed) { - status.press_attempt=true; - status.pressing_inside=true; + status.press_attempt = true; + status.pressing_inside = true; emit_signal("button_down"); } else { emit_signal("button_up"); - if (status.press_attempt &&status.pressing_inside) { + if (status.press_attempt && status.pressing_inside) { if (!toggle_mode) { //mouse press attempt pressed(); if (get_script_instance()) { Variant::CallError ce; - get_script_instance()->call(SceneStringNames::get_singleton()->_pressed,NULL,0,ce); + get_script_instance()->call(SceneStringNames::get_singleton()->_pressed, NULL, 0, ce); } emit_signal("pressed"); } else { - status.pressed=!status.pressed; + status.pressed = !status.pressed; pressed(); emit_signal("pressed"); toggled(status.pressed); - emit_signal("toggled",status.pressed); + emit_signal("toggled", status.pressed); if (get_script_instance()) { - get_script_instance()->call(SceneStringNames::get_singleton()->_toggled,status.pressed); + get_script_instance()->call(SceneStringNames::get_singleton()->_toggled, status.pressed); } - - } _unpress_group(); - - } - status.press_attempt=false; - + status.press_attempt = false; } update(); } break; case InputEvent::MOUSE_MOTION: { - if (status.press_attempt && status.pressing_button==0) { - bool last_press_inside=status.pressing_inside; - status.pressing_inside=has_point(Point2(p_event.mouse_motion.x,p_event.mouse_motion.y)); - if (last_press_inside!=status.pressing_inside) + if (status.press_attempt && status.pressing_button == 0) { + bool last_press_inside = status.pressing_inside; + status.pressing_inside = has_point(Point2(p_event.mouse_motion.x, p_event.mouse_motion.y)); + if (last_press_inside != status.pressing_inside) update(); } } break; @@ -180,7 +169,6 @@ void BaseButton::_gui_input(InputEvent p_event) { case InputEvent::JOYPAD_BUTTON: case InputEvent::KEY: { - if (p_event.is_echo()) { break; } @@ -189,7 +177,7 @@ void BaseButton::_gui_input(InputEvent p_event) { break; } - if (status.press_attempt && status.pressing_button==0) { + if (status.press_attempt && status.pressing_button == 0) { break; } @@ -198,8 +186,8 @@ void BaseButton::_gui_input(InputEvent p_event) { if (p_event.is_pressed()) { status.pressing_button++; - status.press_attempt=true; - status.pressing_inside=true; + status.press_attempt = true; + status.pressing_inside = true; emit_signal("button_down"); } else if (status.press_attempt) { @@ -210,8 +198,8 @@ void BaseButton::_gui_input(InputEvent p_event) { if (status.pressing_button) break; - status.press_attempt=false; - status.pressing_inside=false; + status.press_attempt = false; + status.pressing_inside = false; emit_signal("button_up"); @@ -221,83 +209,75 @@ void BaseButton::_gui_input(InputEvent p_event) { emit_signal("pressed"); } else { - status.pressed=!status.pressed; + status.pressed = !status.pressed; pressed(); emit_signal("pressed"); toggled(status.pressed); if (get_script_instance()) { - get_script_instance()->call(SceneStringNames::get_singleton()->_toggled,status.pressed); + get_script_instance()->call(SceneStringNames::get_singleton()->_toggled, status.pressed); } - emit_signal("toggled",status.pressed); + emit_signal("toggled", status.pressed); } _unpress_group(); - } accept_event(); update(); - } } - } } void BaseButton::_notification(int p_what) { + if (p_what == NOTIFICATION_MOUSE_ENTER) { - if (p_what==NOTIFICATION_MOUSE_ENTER) { - - status.hovering=true; + status.hovering = true; update(); } - if (p_what==NOTIFICATION_MOUSE_EXIT) { - status.hovering=false; + if (p_what == NOTIFICATION_MOUSE_EXIT) { + status.hovering = false; update(); } - if (p_what==NOTIFICATION_DRAG_BEGIN) { + if (p_what == NOTIFICATION_DRAG_BEGIN) { if (status.press_attempt) { - status.press_attempt=false; - status.pressing_button=0; + status.press_attempt = false; + status.pressing_button = 0; update(); } } - - if (p_what==NOTIFICATION_FOCUS_ENTER) { - - status.hovering=true; + + if (p_what == NOTIFICATION_FOCUS_ENTER) { + + status.hovering = true; update(); } - if (p_what==NOTIFICATION_FOCUS_EXIT) { + if (p_what == NOTIFICATION_FOCUS_EXIT) { if (status.pressing_button && status.press_attempt) { - status.press_attempt=false; - status.pressing_button=0; - status.hovering=false; + status.press_attempt = false; + status.pressing_button = 0; + status.hovering = false; update(); } else if (status.hovering) { - status.hovering=false; + status.hovering = false; update(); } } - if (p_what==NOTIFICATION_ENTER_TREE) { - - + if (p_what == NOTIFICATION_ENTER_TREE) { } - if (p_what==NOTIFICATION_EXIT_TREE) { - - + if (p_what == NOTIFICATION_EXIT_TREE) { } - if (p_what==NOTIFICATION_VISIBILITY_CHANGED && !is_visible_in_tree()) { + if (p_what == NOTIFICATION_VISIBILITY_CHANGED && !is_visible_in_tree()) { if (!toggle_mode) { status.pressed = false; @@ -318,12 +298,10 @@ void BaseButton::pressed() { void BaseButton::toggled(bool p_pressed) { if (get_script_instance()) { - get_script_instance()->call("toggled",p_pressed); + get_script_instance()->call("toggled", p_pressed); } - } - void BaseButton::set_disabled(bool p_disabled) { status.disabled = p_disabled; @@ -344,26 +322,25 @@ void BaseButton::set_pressed(bool p_pressed) { if (!toggle_mode) return; - if (status.pressed==p_pressed) + if (status.pressed == p_pressed) return; _change_notify("pressed"); - status.pressed=p_pressed; + status.pressed = p_pressed; if (p_pressed) { _unpress_group(); - } update(); } -bool BaseButton::is_pressing() const{ +bool BaseButton::is_pressing() const { return status.press_attempt; } bool BaseButton::is_pressed() const { - return toggle_mode?status.pressed:status.press_attempt; + return toggle_mode ? status.pressed : status.press_attempt; } bool BaseButton::is_hovered() const { @@ -378,8 +355,7 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const { }; //print_line("press attempt: "+itos(status.press_attempt)+" hover: "+itos(status.hovering)+" pressed: "+itos(status.pressed)); - if (status.press_attempt==false && status.hovering && !status.pressed) { - + if (status.press_attempt == false && status.hovering && !status.pressed) { return DRAW_HOVER; } else { @@ -388,12 +364,12 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const { bool pressing; if (status.press_attempt) { - pressing=status.pressing_inside; + pressing = status.pressing_inside; if (status.pressed) - pressing=!pressing; + pressing = !pressing; } else { - pressing=status.pressed; + pressing = status.pressed; } if (pressing) @@ -407,7 +383,7 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const { void BaseButton::set_toggle_mode(bool p_on) { - toggle_mode=p_on; + toggle_mode = p_on; } bool BaseButton::is_toggle_mode() const { @@ -417,7 +393,7 @@ bool BaseButton::is_toggle_mode() const { void BaseButton::set_action_mode(ActionMode p_mode) { - action_mode=p_mode; + action_mode = p_mode; } BaseButton::ActionMode BaseButton::get_action_mode() const { @@ -429,7 +405,7 @@ void BaseButton::set_enabled_focus_mode(FocusMode p_mode) { enabled_focus_mode = p_mode; if (!status.disabled) { - set_focus_mode( p_mode ); + set_focus_mode(p_mode); } } @@ -438,16 +414,16 @@ Control::FocusMode BaseButton::get_enabled_focus_mode() const { return enabled_focus_mode; } -void BaseButton::set_shortcut(const Ref& p_shortcut) { +void BaseButton::set_shortcut(const Ref &p_shortcut) { if (shortcut.is_null() == p_shortcut.is_null()) return; - shortcut=p_shortcut; + shortcut = p_shortcut; set_process_unhandled_input(shortcut.is_valid()); } -Ref BaseButton:: get_shortcut() const { +Ref BaseButton::get_shortcut() const { return shortcut; } @@ -460,41 +436,39 @@ void BaseButton::_unhandled_input(InputEvent p_event) { if (is_toggle_mode()) { set_pressed(!is_pressed()); - emit_signal("toggled",is_pressed()); + emit_signal("toggled", is_pressed()); } emit_signal("pressed"); } } -String BaseButton::get_tooltip(const Point2& p_pos) const { +String BaseButton::get_tooltip(const Point2 &p_pos) const { - String tooltip=Control::get_tooltip(p_pos); + String tooltip = Control::get_tooltip(p_pos); if (shortcut.is_valid() && shortcut->is_valid()) { - if (tooltip.find("$sc")!=-1) { - tooltip=tooltip.replace_first("$sc","("+shortcut->get_as_text()+")"); + if (tooltip.find("$sc") != -1) { + tooltip = tooltip.replace_first("$sc", "(" + shortcut->get_as_text() + ")"); } else { - tooltip+=" ("+shortcut->get_as_text()+")"; + tooltip += " (" + shortcut->get_as_text() + ")"; } } return tooltip; } - -void BaseButton::set_button_group(const Ref& p_group) { +void BaseButton::set_button_group(const Ref &p_group) { if (button_group.is_valid()) { button_group->buttons.erase(this); } - button_group=p_group; + button_group = p_group; if (button_group.is_valid()) { button_group->buttons.insert(this); } update(); //checkbox changes to radio if set a buttongroup - } Ref BaseButton::get_button_group() const { @@ -502,103 +476,94 @@ Ref BaseButton::get_button_group() const { return button_group; } - void BaseButton::_bind_methods() { - ClassDB::bind_method(D_METHOD("_gui_input"),&BaseButton::_gui_input); - ClassDB::bind_method(D_METHOD("_unhandled_input"),&BaseButton::_unhandled_input); - ClassDB::bind_method(D_METHOD("set_pressed","pressed"),&BaseButton::set_pressed); - ClassDB::bind_method(D_METHOD("is_pressed"),&BaseButton::is_pressed); - ClassDB::bind_method(D_METHOD("is_hovered"),&BaseButton::is_hovered); - ClassDB::bind_method(D_METHOD("set_toggle_mode","enabled"),&BaseButton::set_toggle_mode); - ClassDB::bind_method(D_METHOD("is_toggle_mode"),&BaseButton::is_toggle_mode); - ClassDB::bind_method(D_METHOD("set_disabled","disabled"),&BaseButton::set_disabled); - ClassDB::bind_method(D_METHOD("is_disabled"),&BaseButton::is_disabled); - ClassDB::bind_method(D_METHOD("set_action_mode","mode"),&BaseButton::set_action_mode); - ClassDB::bind_method(D_METHOD("get_action_mode"),&BaseButton::get_action_mode); - ClassDB::bind_method(D_METHOD("get_draw_mode"),&BaseButton::get_draw_mode); - ClassDB::bind_method(D_METHOD("set_enabled_focus_mode","mode"),&BaseButton::set_enabled_focus_mode); - ClassDB::bind_method(D_METHOD("get_enabled_focus_mode"),&BaseButton::get_enabled_focus_mode); - - ClassDB::bind_method(D_METHOD("set_shortcut","shortcut"),&BaseButton::set_shortcut); - ClassDB::bind_method(D_METHOD("get_shortcut"),&BaseButton::get_shortcut); - - ClassDB::bind_method(D_METHOD("set_button_group","button_group"),&BaseButton::set_button_group); - ClassDB::bind_method(D_METHOD("get_button_group"),&BaseButton::get_button_group); + ClassDB::bind_method(D_METHOD("_gui_input"), &BaseButton::_gui_input); + ClassDB::bind_method(D_METHOD("_unhandled_input"), &BaseButton::_unhandled_input); + ClassDB::bind_method(D_METHOD("set_pressed", "pressed"), &BaseButton::set_pressed); + ClassDB::bind_method(D_METHOD("is_pressed"), &BaseButton::is_pressed); + ClassDB::bind_method(D_METHOD("is_hovered"), &BaseButton::is_hovered); + ClassDB::bind_method(D_METHOD("set_toggle_mode", "enabled"), &BaseButton::set_toggle_mode); + ClassDB::bind_method(D_METHOD("is_toggle_mode"), &BaseButton::is_toggle_mode); + ClassDB::bind_method(D_METHOD("set_disabled", "disabled"), &BaseButton::set_disabled); + ClassDB::bind_method(D_METHOD("is_disabled"), &BaseButton::is_disabled); + ClassDB::bind_method(D_METHOD("set_action_mode", "mode"), &BaseButton::set_action_mode); + ClassDB::bind_method(D_METHOD("get_action_mode"), &BaseButton::get_action_mode); + ClassDB::bind_method(D_METHOD("get_draw_mode"), &BaseButton::get_draw_mode); + ClassDB::bind_method(D_METHOD("set_enabled_focus_mode", "mode"), &BaseButton::set_enabled_focus_mode); + ClassDB::bind_method(D_METHOD("get_enabled_focus_mode"), &BaseButton::get_enabled_focus_mode); + + ClassDB::bind_method(D_METHOD("set_shortcut", "shortcut"), &BaseButton::set_shortcut); + ClassDB::bind_method(D_METHOD("get_shortcut"), &BaseButton::get_shortcut); + + ClassDB::bind_method(D_METHOD("set_button_group", "button_group"), &BaseButton::set_button_group); + ClassDB::bind_method(D_METHOD("get_button_group"), &BaseButton::get_button_group); BIND_VMETHOD(MethodInfo("_pressed")); - BIND_VMETHOD(MethodInfo("_toggled",PropertyInfo(Variant::BOOL,"pressed"))); - - ADD_SIGNAL( MethodInfo("pressed" ) ); - ADD_SIGNAL( MethodInfo("button_up") ); - ADD_SIGNAL( MethodInfo("button_down") ); - ADD_SIGNAL( MethodInfo("toggled", PropertyInfo( Variant::BOOL,"pressed") ) ); - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "disabled"), "set_disabled", "is_disabled"); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "toggle_mode"), "set_toggle_mode", "is_toggle_mode"); - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "is_pressed"), "set_pressed", "is_pressed"); - ADD_PROPERTYNO( PropertyInfo( Variant::INT, "action_mode",PROPERTY_HINT_ENUM,"Button Press,Button Release"), "set_action_mode", "get_action_mode"); - ADD_PROPERTY( PropertyInfo( Variant::INT,"enabled_focus_mode", PROPERTY_HINT_ENUM, "None,Click,All" ), "set_enabled_focus_mode", "get_enabled_focus_mode") ; - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "shortcut",PROPERTY_HINT_RESOURCE_TYPE,"ShortCut"), "set_shortcut", "get_shortcut"); - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "group",PROPERTY_HINT_RESOURCE_TYPE,"ButtonGroup"), "set_button_group", "get_button_group"); - - - BIND_CONSTANT( DRAW_NORMAL ); - BIND_CONSTANT( DRAW_PRESSED ); - BIND_CONSTANT( DRAW_HOVER ); - BIND_CONSTANT( DRAW_DISABLED ); - - BIND_CONSTANT( ACTION_MODE_BUTTON_PRESS ); - BIND_CONSTANT( ACTION_MODE_BUTTON_RELEASE ); - - + BIND_VMETHOD(MethodInfo("_toggled", PropertyInfo(Variant::BOOL, "pressed"))); + + ADD_SIGNAL(MethodInfo("pressed")); + ADD_SIGNAL(MethodInfo("button_up")); + ADD_SIGNAL(MethodInfo("button_down")); + ADD_SIGNAL(MethodInfo("toggled", PropertyInfo(Variant::BOOL, "pressed"))); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "disabled"), "set_disabled", "is_disabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "toggle_mode"), "set_toggle_mode", "is_toggle_mode"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "is_pressed"), "set_pressed", "is_pressed"); + ADD_PROPERTYNO(PropertyInfo(Variant::INT, "action_mode", PROPERTY_HINT_ENUM, "Button Press,Button Release"), "set_action_mode", "get_action_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "enabled_focus_mode", PROPERTY_HINT_ENUM, "None,Click,All"), "set_enabled_focus_mode", "get_enabled_focus_mode"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut", PROPERTY_HINT_RESOURCE_TYPE, "ShortCut"), "set_shortcut", "get_shortcut"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "group", PROPERTY_HINT_RESOURCE_TYPE, "ButtonGroup"), "set_button_group", "get_button_group"); + + BIND_CONSTANT(DRAW_NORMAL); + BIND_CONSTANT(DRAW_PRESSED); + BIND_CONSTANT(DRAW_HOVER); + BIND_CONSTANT(DRAW_DISABLED); + + BIND_CONSTANT(ACTION_MODE_BUTTON_PRESS); + BIND_CONSTANT(ACTION_MODE_BUTTON_RELEASE); } BaseButton::BaseButton() { - toggle_mode=false; - status.pressed=false; - status.press_attempt=false; - status.hovering=false; - status.pressing_inside=false; + toggle_mode = false; + status.pressed = false; + status.press_attempt = false; + status.hovering = false; + status.pressing_inside = false; status.disabled = false; - status.pressing_button=0; - set_focus_mode( FOCUS_ALL ); + status.pressing_button = 0; + set_focus_mode(FOCUS_ALL); enabled_focus_mode = FOCUS_ALL; - action_mode=ACTION_MODE_BUTTON_RELEASE; - + action_mode = ACTION_MODE_BUTTON_RELEASE; if (button_group.is_valid()) { button_group->buttons.erase(this); } - - } -BaseButton::~BaseButton() -{ +BaseButton::~BaseButton() { } -void ButtonGroup::get_buttons(List *r_buttons) { +void ButtonGroup::get_buttons(List *r_buttons) { - for (Set::Element *E=buttons.front();E;E=E->next()) { + for (Set::Element *E = buttons.front(); E; E = E->next()) { r_buttons->push_back(E->get()); } } -BaseButton* ButtonGroup::get_pressed_button() { +BaseButton *ButtonGroup::get_pressed_button() { - for (Set::Element *E=buttons.front();E;E=E->next()) { + for (Set::Element *E = buttons.front(); E; E = E->next()) { if (E->get()->is_pressed()) return E->get(); } return NULL; - } void ButtonGroup::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_pressed_button:BaseButton"),&ButtonGroup::get_pressed_button); + ClassDB::bind_method(D_METHOD("get_pressed_button:BaseButton"), &ButtonGroup::get_pressed_button); } ButtonGroup::ButtonGroup() { diff --git a/scene/gui/base_button.h b/scene/gui/base_button.h index def4ff753..e382df61c 100644 --- a/scene/gui/base_button.h +++ b/scene/gui/base_button.h @@ -34,21 +34,19 @@ @author Juan Linietsky */ - class ButtonGroup; class BaseButton : public Control { - GDCLASS( BaseButton, Control ); -public: + GDCLASS(BaseButton, Control); +public: enum ActionMode { ACTION_MODE_BUTTON_PRESS, ACTION_MODE_BUTTON_RELEASE, }; private: - bool toggle_mode; FocusMode enabled_focus_mode; Ref shortcut; @@ -66,17 +64,11 @@ private: } status; - Ref button_group; - void _unpress_group(); protected: - - - - virtual void pressed(); virtual void toggled(bool p_pressed); static void _bind_methods(); @@ -85,7 +77,6 @@ protected: void _notification(int p_what); public: - enum DrawMode { DRAW_NORMAL, DRAW_PRESSED, @@ -114,35 +105,33 @@ public: void set_enabled_focus_mode(FocusMode p_mode); FocusMode get_enabled_focus_mode() const; - void set_shortcut(const Ref& p_shortcut); + void set_shortcut(const Ref &p_shortcut); Ref get_shortcut() const; - virtual String get_tooltip(const Point2& p_pos) const; + virtual String get_tooltip(const Point2 &p_pos) const; - void set_button_group(const Ref& p_group); + void set_button_group(const Ref &p_group); Ref get_button_group() const; BaseButton(); ~BaseButton(); - }; -VARIANT_ENUM_CAST( BaseButton::DrawMode ) -VARIANT_ENUM_CAST( BaseButton::ActionMode ) - - +VARIANT_ENUM_CAST(BaseButton::DrawMode) +VARIANT_ENUM_CAST(BaseButton::ActionMode) class ButtonGroup : public Resource { - GDCLASS(ButtonGroup,Resource) -friend class BaseButton; - Set buttons; + GDCLASS(ButtonGroup, Resource) + friend class BaseButton; + Set buttons; + protected: static void _bind_methods(); -public: - BaseButton* get_pressed_button(); - void get_buttons(List *r_buttons); +public: + BaseButton *get_pressed_button(); + void get_buttons(List *r_buttons); ButtonGroup(); }; diff --git a/scene/gui/box_container.cpp b/scene/gui/box_container.cpp index 1f6e0392d..7c1487c42 100644 --- a/scene/gui/box_container.cpp +++ b/scene/gui/box_container.cpp @@ -27,8 +27,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "box_container.h" -#include "margin_container.h" #include "label.h" +#include "margin_container.h" struct _MinSizeCache { @@ -41,110 +41,105 @@ void BoxContainer::_resort() { /** First pass, determine minimum size AND amount of stretchable elements */ + Size2i new_size = get_size(); - Size2i new_size=get_size(); + int sep = get_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer"); - int sep=get_constant("separation");//,vertical?"VBoxContainer":"HBoxContainer"); + bool first = true; + int children_count = 0; + int stretch_min = 0; + int stretch_avail = 0; + float stretch_ratio_total = 0; + Map min_size_cache; - bool first=true; - int children_count=0; - int stretch_min=0; - int stretch_avail=0; - float stretch_ratio_total=0; - Map min_size_cache; - - for(int i=0;icast_to(); + for (int i = 0; i < get_child_count(); i++) { + Control *c = get_child(i)->cast_to(); if (!c || !c->is_visible_in_tree()) continue; if (c->is_set_as_toplevel()) continue; - Size2i size=c->get_combined_minimum_size(); + Size2i size = c->get_combined_minimum_size(); _MinSizeCache msc; if (vertical) { /* VERTICAL */ - stretch_min+=size.height; - msc.min_size=size.height; - msc.will_stretch=c->get_v_size_flags() & SIZE_EXPAND; + stretch_min += size.height; + msc.min_size = size.height; + msc.will_stretch = c->get_v_size_flags() & SIZE_EXPAND; } else { /* HORIZONTAL */ - stretch_min+=size.width; - msc.min_size=size.width; - msc.will_stretch=c->get_h_size_flags() & SIZE_EXPAND; + stretch_min += size.width; + msc.min_size = size.width; + msc.will_stretch = c->get_h_size_flags() & SIZE_EXPAND; } if (msc.will_stretch) { - stretch_avail+=msc.min_size; - stretch_ratio_total+=c->get_stretch_ratio(); + stretch_avail += msc.min_size; + stretch_ratio_total += c->get_stretch_ratio(); } - msc.final_size=msc.min_size; - min_size_cache[c]=msc; + msc.final_size = msc.min_size; + min_size_cache[c] = msc; children_count++; } - if (children_count==0) + if (children_count == 0) return; - int stretch_max = (vertical? new_size.height : new_size.width ) - (children_count-1) * sep; + int stretch_max = (vertical ? new_size.height : new_size.width) - (children_count - 1) * sep; int stretch_diff = stretch_max - stretch_min; - if (stretch_diff<0) { + if (stretch_diff < 0) { //avoid negative stretch space - stretch_max=stretch_min; - stretch_diff=0; + stretch_max = stretch_min; + stretch_diff = 0; } - stretch_avail+=stretch_diff; //available stretch space. + stretch_avail += stretch_diff; //available stretch space. /** Second, pass sucessively to discard elements that can't be stretched, this will run while stretchable elements exist */ - bool has_stretched = false; - while(stretch_ratio_total>0) { // first of all, dont even be here if no stretchable objects exist + while (stretch_ratio_total > 0) { // first of all, dont even be here if no stretchable objects exist has_stretched = true; - bool refit_successful=true; //assume refit-test will go well + bool refit_successful = true; //assume refit-test will go well - for(int i=0;icast_to(); + Control *c = get_child(i)->cast_to(); if (!c || !c->is_visible_in_tree()) continue; if (c->is_set_as_toplevel()) continue; ERR_FAIL_COND(!min_size_cache.has(c)); - _MinSizeCache &msc=min_size_cache[c]; + _MinSizeCache &msc = min_size_cache[c]; if (msc.will_stretch) { //wants to stretch //let's see if it can really stretch - int final_pixel_size=stretch_avail * c->get_stretch_ratio() / stretch_ratio_total; - if (final_pixel_sizeget_stretch_ratio() / stretch_ratio_total; + if (final_pixel_size < msc.min_size) { //if available stretching area is too small for widget, //then remove it from stretching area - msc.will_stretch=false; - stretch_ratio_total-=c->get_stretch_ratio(); - refit_successful=false; - stretch_avail-=msc.min_size; - msc.final_size=msc.min_size; + msc.will_stretch = false; + stretch_ratio_total -= c->get_stretch_ratio(); + refit_successful = false; + stretch_avail -= msc.min_size; + msc.final_size = msc.min_size; break; } else { - msc.final_size=final_pixel_size; + msc.final_size = final_pixel_size; } } } if (refit_successful) //uf refit went well, break break; - } - /** Final pass, draw and stretch elements **/ - - int ofs=0; + int ofs = 0; if (!has_stretched) { switch (align) { case ALIGN_BEGIN: @@ -158,70 +153,64 @@ void BoxContainer::_resort() { } } - first=true; - int idx=0; + first = true; + int idx = 0; - for(int i=0;icast_to(); + Control *c = get_child(i)->cast_to(); if (!c || !c->is_visible_in_tree()) continue; if (c->is_set_as_toplevel()) continue; - _MinSizeCache &msc=min_size_cache[c]; - + _MinSizeCache &msc = min_size_cache[c]; if (first) - first=false; + first = false; else - ofs+=sep; + ofs += sep; - int from=ofs; - int to=ofs+msc.final_size; + int from = ofs; + int to = ofs + msc.final_size; - - if (msc.will_stretch && idx==children_count-1) { + if (msc.will_stretch && idx == children_count - 1) { //adjust so the last one always fits perfect //compensating for numerical imprecision - to=vertical?new_size.height:new_size.width; - + to = vertical ? new_size.height : new_size.width; } - int size=to-from; + int size = to - from; Rect2 rect; if (vertical) { - rect=Rect2(0,from,new_size.width,size); + rect = Rect2(0, from, new_size.width, size); } else { - rect=Rect2(from,0,size,new_size.height); - + rect = Rect2(from, 0, size, new_size.height); } - fit_child_in_rect(c,rect); + fit_child_in_rect(c, rect); - ofs=to; + ofs = to; idx++; } - } Size2 BoxContainer::get_minimum_size() const { - /* Calculate MINIMUM SIZE */ Size2i minimum; - int sep=get_constant("separation");//,vertical?"VBoxContainer":"HBoxContainer"); + int sep = get_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer"); - bool first=true; + bool first = true; - for(int i=0;icast_to(); + for (int i = 0; i < get_child_count(); i++) { + Control *c = get_child(i)->cast_to(); if (!c) continue; if (c->is_set_as_toplevel()) @@ -231,27 +220,26 @@ Size2 BoxContainer::get_minimum_size() const { continue; } - Size2i size=c->get_combined_minimum_size(); + Size2i size = c->get_combined_minimum_size(); if (vertical) { /* VERTICAL */ - if ( size.width > minimum.width ) { - minimum.width=size.width; + if (size.width > minimum.width) { + minimum.width = size.width; } - minimum.height+=size.height+(first?0:sep); + minimum.height += size.height + (first ? 0 : sep); } else { /* HORIZONTAL */ - if ( size.height > minimum.height ) { - minimum.height=size.height; + if (size.height > minimum.height) { + minimum.height = size.height; } - minimum.width+=size.width+(first?0:sep); - + minimum.width += size.width + (first ? 0 : sep); } - first=false; + first = false; } return minimum; @@ -259,7 +247,7 @@ Size2 BoxContainer::get_minimum_size() const { void BoxContainer::_notification(int p_what) { - switch(p_what) { + switch (p_what) { case NOTIFICATION_SORT_CHILDREN: { @@ -279,7 +267,7 @@ BoxContainer::AlignMode BoxContainer::get_alignment() const { void BoxContainer::add_spacer(bool p_begin) { - Control *c = memnew( Control ); + Control *c = memnew(Control); c->set_mouse_filter(MOUSE_FILTER_PASS); //allow spacer to pass mouse events if (vertical) @@ -289,12 +277,12 @@ void BoxContainer::add_spacer(bool p_begin) { add_child(c); if (p_begin) - move_child(c,0); + move_child(c, 0); } BoxContainer::BoxContainer(bool p_vertical) { - vertical=p_vertical; + vertical = p_vertical; align = ALIGN_BEGIN; //set_ignore_mouse(true); set_mouse_filter(MOUSE_FILTER_PASS); @@ -302,24 +290,23 @@ BoxContainer::BoxContainer(bool p_vertical) { void BoxContainer::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_spacer","begin"),&BoxContainer::add_spacer); - ClassDB::bind_method(D_METHOD("get_alignment"),&BoxContainer::get_alignment); - ClassDB::bind_method(D_METHOD("set_alignment","alignment"),&BoxContainer::set_alignment); - - BIND_CONSTANT( ALIGN_BEGIN ); - BIND_CONSTANT( ALIGN_CENTER ); - BIND_CONSTANT( ALIGN_END ); + ClassDB::bind_method(D_METHOD("add_spacer", "begin"), &BoxContainer::add_spacer); + ClassDB::bind_method(D_METHOD("get_alignment"), &BoxContainer::get_alignment); + ClassDB::bind_method(D_METHOD("set_alignment", "alignment"), &BoxContainer::set_alignment); - ADD_PROPERTY( PropertyInfo(Variant::INT,"alignment", PROPERTY_HINT_ENUM, "Begin,Center,End"), "set_alignment","get_alignment") ; + BIND_CONSTANT(ALIGN_BEGIN); + BIND_CONSTANT(ALIGN_CENTER); + BIND_CONSTANT(ALIGN_END); + ADD_PROPERTY(PropertyInfo(Variant::INT, "alignment", PROPERTY_HINT_ENUM, "Begin,Center,End"), "set_alignment", "get_alignment"); } -MarginContainer* VBoxContainer::add_margin_child(const String& p_label,Control *p_control,bool p_expand) { +MarginContainer *VBoxContainer::add_margin_child(const String &p_label, Control *p_control, bool p_expand) { - Label *l = memnew( Label ); + Label *l = memnew(Label); l->set_text(p_label); add_child(l); - MarginContainer *mc = memnew( MarginContainer ); + MarginContainer *mc = memnew(MarginContainer); mc->add_child(p_control); add_child(mc); if (p_expand) diff --git a/scene/gui/box_container.h b/scene/gui/box_container.h index c428ec132..04b074896 100644 --- a/scene/gui/box_container.h +++ b/scene/gui/box_container.h @@ -33,10 +33,9 @@ class BoxContainer : public Container { - GDCLASS(BoxContainer,Container); + GDCLASS(BoxContainer, Container); public: - enum AlignMode { ALIGN_BEGIN, ALIGN_CENTER, @@ -48,44 +47,42 @@ private: AlignMode align; void _resort(); -protected: +protected: void _notification(int p_what); static void _bind_methods(); -public: - void add_spacer(bool p_begin=false); +public: + void add_spacer(bool p_begin = false); void set_alignment(AlignMode p_align); AlignMode get_alignment() const; virtual Size2 get_minimum_size() const; - BoxContainer(bool p_vertical=false); + BoxContainer(bool p_vertical = false); }; - class HBoxContainer : public BoxContainer { - GDCLASS(HBoxContainer,BoxContainer); + GDCLASS(HBoxContainer, BoxContainer); public: - - HBoxContainer() : BoxContainer(false) {} + HBoxContainer() + : BoxContainer(false) {} }; - class MarginContainer; class VBoxContainer : public BoxContainer { - GDCLASS(VBoxContainer,BoxContainer); + GDCLASS(VBoxContainer, BoxContainer); public: + MarginContainer *add_margin_child(const String &p_label, Control *p_control, bool p_expand = false); - MarginContainer* add_margin_child(const String& p_label,Control *p_control,bool p_expand=false); - - VBoxContainer() : BoxContainer(true) {} + VBoxContainer() + : BoxContainer(true) {} }; VARIANT_ENUM_CAST(BoxContainer::AlignMode); diff --git a/scene/gui/button.cpp b/scene/gui/button.cpp index de2ccfb0b..23915c51a 100644 --- a/scene/gui/button.cpp +++ b/scene/gui/button.cpp @@ -27,86 +27,83 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "button.h" -#include "servers/visual_server.h" #include "print_string.h" +#include "servers/visual_server.h" #include "translation.h" - Size2 Button::get_minimum_size() const { - Size2 minsize=get_font("font")->get_string_size( xl_text ); + Size2 minsize = get_font("font")->get_string_size(xl_text); if (clip_text) - minsize.width=0; + minsize.width = 0; Ref _icon; if (icon.is_null() && has_icon("icon")) - _icon=Control::get_icon("icon"); + _icon = Control::get_icon("icon"); else - _icon=icon; + _icon = icon; if (!_icon.is_null()) { - minsize.height=MAX( minsize.height, _icon->get_height() ); - minsize.width+=_icon->get_width(); - if (xl_text!="") - minsize.width+=get_constant("hseparation"); + minsize.height = MAX(minsize.height, _icon->get_height()); + minsize.width += _icon->get_width(); + if (xl_text != "") + minsize.width += get_constant("hseparation"); } - return get_stylebox("normal" )->get_minimum_size() + minsize; - + return get_stylebox("normal")->get_minimum_size() + minsize; } - void Button::_notification(int p_what) { - if (p_what==NOTIFICATION_TRANSLATION_CHANGED) { + if (p_what == NOTIFICATION_TRANSLATION_CHANGED) { - xl_text=XL_MESSAGE(text); + xl_text = XL_MESSAGE(text); minimum_size_changed(); update(); } - if (p_what==NOTIFICATION_DRAW) { + if (p_what == NOTIFICATION_DRAW) { RID ci = get_canvas_item(); - Size2 size=get_size(); + Size2 size = get_size(); Color color; //print_line(get_text()+": "+itos(is_flat())+" hover "+itos(get_draw_mode())); Ref style = get_stylebox("normal"); - switch( get_draw_mode() ) { + switch (get_draw_mode()) { case DRAW_NORMAL: { style = get_stylebox("normal"); if (!flat) - style->draw( ci, Rect2(Point2(0,0), size) ); - color=get_color("font_color"); + style->draw(ci, Rect2(Point2(0, 0), size)); + color = get_color("font_color"); } break; case DRAW_PRESSED: { style = get_stylebox("pressed"); - style->draw( ci, Rect2(Point2(0,0), size) ); + style->draw(ci, Rect2(Point2(0, 0), size)); if (has_color("font_color_pressed")) - color=get_color("font_color_pressed"); + color = get_color("font_color_pressed"); else - color=get_color("font_color"); + color = get_color("font_color"); } break; case DRAW_HOVER: { style = get_stylebox("hover"); - style->draw( ci, Rect2(Point2(0,0), size) ); - color=get_color("font_color_hover"); + style->draw(ci, Rect2(Point2(0, 0), size)); + color = get_color("font_color_hover"); } break; case DRAW_DISABLED: { style = get_stylebox("disabled"); - style->draw( ci, Rect2(Point2(0,0), size) ); - color=get_color("font_color_disabled"); + style->draw(ci, Rect2(Point2(0, 0), size)); + color = get_color("font_color_disabled"); } break; } @@ -114,58 +111,54 @@ void Button::_notification(int p_what) { if (has_focus()) { Ref style = get_stylebox("focus"); - style->draw(ci,Rect2(Point2(),size)); + style->draw(ci, Rect2(Point2(), size)); } - Ref font=get_font("font"); + Ref font = get_font("font"); Ref _icon; if (icon.is_null() && has_icon("icon")) - _icon=Control::get_icon("icon"); + _icon = Control::get_icon("icon"); else - _icon=icon; + _icon = icon; - Point2 icon_ofs = (!_icon.is_null())?Point2( _icon->get_width() + get_constant("hseparation"), 0):Point2(); - int text_clip=size.width - style->get_minimum_size().width - icon_ofs.width; - Point2 text_ofs = (size - style->get_minimum_size() - icon_ofs - font->get_string_size( xl_text ) )/2.0; + Point2 icon_ofs = (!_icon.is_null()) ? Point2(_icon->get_width() + get_constant("hseparation"), 0) : Point2(); + int text_clip = size.width - style->get_minimum_size().width - icon_ofs.width; + Point2 text_ofs = (size - style->get_minimum_size() - icon_ofs - font->get_string_size(xl_text)) / 2.0; - switch(align) { + switch (align) { case ALIGN_LEFT: { text_ofs.x = style->get_margin(MARGIN_LEFT) + icon_ofs.x; - text_ofs.y+=style->get_offset().y; + text_ofs.y += style->get_offset().y; } break; case ALIGN_CENTER: { - if (text_ofs.x<0) - text_ofs.x=0; - text_ofs+=icon_ofs; - text_ofs+=style->get_offset(); + if (text_ofs.x < 0) + text_ofs.x = 0; + text_ofs += icon_ofs; + text_ofs += style->get_offset(); } break; case ALIGN_RIGHT: { - text_ofs.x=size.x - style->get_margin(MARGIN_RIGHT) - font->get_string_size( xl_text ).x; - text_ofs.y+=style->get_offset().y; + text_ofs.x = size.x - style->get_margin(MARGIN_RIGHT) - font->get_string_size(xl_text).x; + text_ofs.y += style->get_offset().y; } break; } - - text_ofs.y+=font->get_ascent(); - font->draw( ci, text_ofs.floor(), xl_text, color,clip_text?text_clip:-1); + text_ofs.y += font->get_ascent(); + font->draw(ci, text_ofs.floor(), xl_text, color, clip_text ? text_clip : -1); if (!_icon.is_null()) { - int valign = size.height-style->get_minimum_size().y; + int valign = size.height - style->get_minimum_size().y; - _icon->draw(ci,style->get_offset()+Point2(0, Math::floor( (valign-_icon->get_height())/2.0 ) ),is_disabled()?Color(1,1,1,0.4):Color(1,1,1) ); + _icon->draw(ci, style->get_offset() + Point2(0, Math::floor((valign - _icon->get_height()) / 2.0)), is_disabled() ? Color(1, 1, 1, 0.4) : Color(1, 1, 1)); } - - - } } -void Button::set_text(const String& p_text) { +void Button::set_text(const String &p_text) { - if (text==p_text) + if (text == p_text) return; - text=p_text; - xl_text=XL_MESSAGE(p_text); + text = p_text; + xl_text = XL_MESSAGE(p_text); update(); _change_notify("text"); minimum_size_changed(); @@ -175,12 +168,11 @@ String Button::get_text() const { return text; } +void Button::set_icon(const Ref &p_icon) { -void Button::set_icon(const Ref& p_icon) { - - if (icon==p_icon) + if (icon == p_icon) return; - icon=p_icon; + icon = p_icon; update(); _change_notify("icon"); minimum_size_changed(); @@ -193,7 +185,7 @@ Ref Button::get_icon() const { void Button::set_flat(bool p_flat) { - flat=p_flat; + flat = p_flat; update(); _change_notify("flat"); } @@ -205,7 +197,7 @@ bool Button::is_flat() const { void Button::set_clip_text(bool p_clip_text) { - clip_text=p_clip_text; + clip_text = p_clip_text; update(); minimum_size_changed(); } @@ -217,7 +209,7 @@ bool Button::get_clip_text() const { void Button::set_text_align(TextAlign p_align) { - align=p_align; + align = p_align; update(); } @@ -228,41 +220,36 @@ Button::TextAlign Button::get_text_align() const { void Button::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_text","text"),&Button::set_text); - ClassDB::bind_method(D_METHOD("get_text"),&Button::get_text); - ClassDB::bind_method(D_METHOD("set_button_icon","texture:Texture"),&Button::set_icon); - ClassDB::bind_method(D_METHOD("get_button_icon:Texture"),&Button::get_icon); - ClassDB::bind_method(D_METHOD("set_flat","enabled"),&Button::set_flat); - ClassDB::bind_method(D_METHOD("set_clip_text","enabled"),&Button::set_clip_text); - ClassDB::bind_method(D_METHOD("get_clip_text"),&Button::get_clip_text); - ClassDB::bind_method(D_METHOD("set_text_align","align"),&Button::set_text_align); - ClassDB::bind_method(D_METHOD("get_text_align"),&Button::get_text_align); - ClassDB::bind_method(D_METHOD("is_flat"),&Button::is_flat); - - BIND_CONSTANT( ALIGN_LEFT ); - BIND_CONSTANT( ALIGN_CENTER ); - BIND_CONSTANT( ALIGN_RIGHT ); - - ADD_PROPERTYNZ( PropertyInfo( Variant::STRING, "text", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_DEFAULT_INTL ), "set_text","get_text") ; - ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture" ), "set_button_icon","get_button_icon") ; - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "flat" ), "set_flat","is_flat") ; - ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "clip_text" ), "set_clip_text","get_clip_text") ; - ADD_PROPERTYNO( PropertyInfo( Variant::INT, "align",PROPERTY_HINT_ENUM,"Left,Center,Right" ), "set_text_align","get_text_align") ; - + ClassDB::bind_method(D_METHOD("set_text", "text"), &Button::set_text); + ClassDB::bind_method(D_METHOD("get_text"), &Button::get_text); + ClassDB::bind_method(D_METHOD("set_button_icon", "texture:Texture"), &Button::set_icon); + ClassDB::bind_method(D_METHOD("get_button_icon:Texture"), &Button::get_icon); + ClassDB::bind_method(D_METHOD("set_flat", "enabled"), &Button::set_flat); + ClassDB::bind_method(D_METHOD("set_clip_text", "enabled"), &Button::set_clip_text); + ClassDB::bind_method(D_METHOD("get_clip_text"), &Button::get_clip_text); + ClassDB::bind_method(D_METHOD("set_text_align", "align"), &Button::set_text_align); + ClassDB::bind_method(D_METHOD("get_text_align"), &Button::get_text_align); + ClassDB::bind_method(D_METHOD("is_flat"), &Button::is_flat); + + BIND_CONSTANT(ALIGN_LEFT); + BIND_CONSTANT(ALIGN_CENTER); + BIND_CONSTANT(ALIGN_RIGHT); + + ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text"); + ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_button_icon", "get_button_icon"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat"); + ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "clip_text"), "set_clip_text", "get_clip_text"); + ADD_PROPERTYNO(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right"), "set_text_align", "get_text_align"); } Button::Button(const String &p_text) { - flat=false; - clip_text=false; + flat = false; + clip_text = false; set_mouse_filter(MOUSE_FILTER_STOP); set_text(p_text); - align=ALIGN_CENTER; + align = ALIGN_CENTER; } - -Button::~Button() -{ +Button::~Button() { } - - diff --git a/scene/gui/button.h b/scene/gui/button.h index 2fd3a0cac..38605bd3e 100644 --- a/scene/gui/button.h +++ b/scene/gui/button.h @@ -34,14 +34,11 @@ @author Juan Linietsky */ - - class Button : public BaseButton { - GDCLASS( Button, BaseButton ); -public: - + GDCLASS(Button, BaseButton); +public: enum TextAlign { ALIGN_LEFT, ALIGN_CENTER, @@ -49,7 +46,6 @@ public: }; private: - bool flat; String text; String xl_text; @@ -57,20 +53,18 @@ private: bool clip_text; TextAlign align; - protected: - virtual Size2 get_minimum_size() const; void _notification(int p_what); static void _bind_methods(); -public: -// +public: + // - void set_text(const String& p_text); + void set_text(const String &p_text); String get_text() const; - void set_icon(const Ref& p_icon); + void set_icon(const Ref &p_icon); Ref get_icon() const; void set_flat(bool p_flat); @@ -82,13 +76,10 @@ public: void set_text_align(TextAlign p_align); TextAlign get_text_align() const; - - Button(const String& p_text=String()); + Button(const String &p_text = String()); ~Button(); - }; - VARIANT_ENUM_CAST(Button::TextAlign); #endif diff --git a/scene/gui/button_array.cpp b/scene/gui/button_array.cpp index 2fd5f0df8..c1cb9ad85 100644 --- a/scene/gui/button_array.cpp +++ b/scene/gui/button_array.cpp @@ -28,46 +28,44 @@ /*************************************************************************/ #include "button_array.h" +bool ButtonArray::_set(const StringName &p_name, const Variant &p_value) { -bool ButtonArray::_set(const StringName& p_name, const Variant& p_value) { - - String n=String(p_name); + String n = String(p_name); if (n.begins_with("button/")) { - String what = n.get_slicec('/',1); - if (what=="count") { - int new_size=p_value; - if (new_size>0 && buttons.size()==0) { - selected=0; + String what = n.get_slicec('/', 1); + if (what == "count") { + int new_size = p_value; + if (new_size > 0 && buttons.size() == 0) { + selected = 0; } if (new_size < buttons.size()) { - if (selected>=new_size) - selected=new_size-1; + if (selected >= new_size) + selected = new_size - 1; } buttons.resize(new_size); _change_notify(); minimum_size_changed(); - } else if (what=="align") { + } else if (what == "align") { set_align(Align(p_value.operator int())); - } else if (what=="selected") { + } else if (what == "selected") { set_selected(p_value); } else if (what == "min_button_size") { min_button_size = p_value; } else { - int idx=what.to_int(); - ERR_FAIL_INDEX_V(idx,buttons.size(),false); - String f = n.get_slicec('/',2); - if (f=="text") { - buttons[idx].text=p_value; - buttons[idx].xl_text=XL_MESSAGE(p_value); - } else if (f=="tooltip") - buttons[idx].tooltip=p_value; - else if (f=="icon") - buttons[idx].icon=p_value; + int idx = what.to_int(); + ERR_FAIL_INDEX_V(idx, buttons.size(), false); + String f = n.get_slicec('/', 2); + if (f == "text") { + buttons[idx].text = p_value; + buttons[idx].xl_text = XL_MESSAGE(p_value); + } else if (f == "tooltip") + buttons[idx].tooltip = p_value; + else if (f == "icon") + buttons[idx].icon = p_value; else return false; - } update(); @@ -75,36 +73,34 @@ bool ButtonArray::_set(const StringName& p_name, const Variant& p_value) { } return false; - } -bool ButtonArray::_get(const StringName& p_name,Variant &r_ret) const { +bool ButtonArray::_get(const StringName &p_name, Variant &r_ret) const { - String n=String(p_name); + String n = String(p_name); if (n.begins_with("button/")) { - String what = n.get_slicec('/',1); - if (what=="count") { - r_ret=buttons.size(); - } else if (what=="align") { - r_ret=get_align(); - } else if (what=="selected") { - r_ret=get_selected(); - } else if (what == "min_button_size"){ + String what = n.get_slicec('/', 1); + if (what == "count") { + r_ret = buttons.size(); + } else if (what == "align") { + r_ret = get_align(); + } else if (what == "selected") { + r_ret = get_selected(); + } else if (what == "min_button_size") { r_ret = min_button_size; } else { - int idx=what.to_int(); - ERR_FAIL_INDEX_V(idx,buttons.size(),false); - String f = n.get_slicec('/',2); - if (f=="text") - r_ret=buttons[idx].text; - else if (f=="tooltip") - r_ret=buttons[idx].tooltip; - else if (f=="icon") - r_ret=buttons[idx].icon; + int idx = what.to_int(); + ERR_FAIL_INDEX_V(idx, buttons.size(), false); + String f = n.get_slicec('/', 2); + if (f == "text") + r_ret = buttons[idx].text; + else if (f == "tooltip") + r_ret = buttons[idx].tooltip; + else if (f == "icon") + r_ret = buttons[idx].icon; else return false; - } return true; @@ -112,24 +108,22 @@ bool ButtonArray::_get(const StringName& p_name,Variant &r_ret) const { return false; } -void ButtonArray::_get_property_list( List *p_list) const { - - p_list->push_back( PropertyInfo( Variant::INT, "button/count",PROPERTY_HINT_RANGE,"0,512,1")); - p_list->push_back( PropertyInfo( Variant::INT, "button/min_button_size",PROPERTY_HINT_RANGE,"0,1024,1")); - p_list->push_back( PropertyInfo( Variant::INT, "button/align",PROPERTY_HINT_ENUM,"Begin,Center,End,Fill,Expand")); - for(int i=0;ipush_back( PropertyInfo( Variant::STRING, base+"text")); - p_list->push_back( PropertyInfo( Variant::STRING, base+"tooltip")); - p_list->push_back( PropertyInfo( Variant::OBJECT, base+"icon",PROPERTY_HINT_RESOURCE_TYPE,"Texture")); +void ButtonArray::_get_property_list(List *p_list) const { + + p_list->push_back(PropertyInfo(Variant::INT, "button/count", PROPERTY_HINT_RANGE, "0,512,1")); + p_list->push_back(PropertyInfo(Variant::INT, "button/min_button_size", PROPERTY_HINT_RANGE, "0,1024,1")); + p_list->push_back(PropertyInfo(Variant::INT, "button/align", PROPERTY_HINT_ENUM, "Begin,Center,End,Fill,Expand")); + for (int i = 0; i < buttons.size(); i++) { + String base = "button/" + itos(i) + "/"; + p_list->push_back(PropertyInfo(Variant::STRING, base + "text")); + p_list->push_back(PropertyInfo(Variant::STRING, base + "tooltip")); + p_list->push_back(PropertyInfo(Variant::OBJECT, base + "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture")); } - if (buttons.size()>0) { - p_list->push_back( PropertyInfo( Variant::INT, "button/selected",PROPERTY_HINT_RANGE,"0,"+itos(buttons.size()-1)+",1")); + if (buttons.size() > 0) { + p_list->push_back(PropertyInfo(Variant::INT, "button/selected", PROPERTY_HINT_RANGE, "0," + itos(buttons.size() - 1) + ",1")); } - } - Size2 ButtonArray::get_minimum_size() const { Ref style_normal = get_stylebox("normal"); @@ -141,54 +135,51 @@ Size2 ButtonArray::get_minimum_size() const { Size2 minsize; - for(int i=0;i sb = i==selected ? style_selected : style_normal; - Ref f = i==selected ? font_selected : font_normal; + Ref sb = i == selected ? style_selected : style_normal; + Ref f = i == selected ? font_selected : font_normal; Size2 ms; ms = f->get_string_size(buttons[i].xl_text); if (buttons[i].icon.is_valid()) { Size2 bs = buttons[i].icon->get_size(); - ms.height = MAX(ms.height,bs.height); - ms.width+=bs.width+icon_sep; + ms.height = MAX(ms.height, bs.height); + ms.width += bs.width + icon_sep; } - ms+=sb->get_minimum_size(); + ms += sb->get_minimum_size(); - buttons[i]._ms_cache=ms[orientation]; - - minsize[orientation]+=ms[orientation]; - if (i>0) - minsize[orientation]+=button_sep; - minsize[!orientation] = MAX(minsize[!orientation],ms[!orientation]); + buttons[i]._ms_cache = ms[orientation]; + minsize[orientation] += ms[orientation]; + if (i > 0) + minsize[orientation] += button_sep; + minsize[!orientation] = MAX(minsize[!orientation], ms[!orientation]); } return minsize; - - } void ButtonArray::_notification(int p_what) { - switch(p_what) { - case NOTIFICATION_MOUSE_EXIT:{ - hover=-1; + switch (p_what) { + case NOTIFICATION_MOUSE_EXIT: { + hover = -1; update(); - }break; - case NOTIFICATION_READY:{ + } break; + case NOTIFICATION_READY: { MethodInfo mi; - mi.name="mouse_sub_enter"; + mi.name = "mouse_sub_enter"; add_user_signal(mi); - }break; + } break; case NOTIFICATION_DRAW: { - Size2 size=get_size(); - Size2 minsize=get_combined_minimum_size(); + Size2 size = get_size(); + Size2 minsize = get_combined_minimum_size(); Ref style_normal = get_stylebox("normal"); Ref style_selected = get_stylebox("selected"); Ref style_focus = get_stylebox("focus"); @@ -200,188 +191,174 @@ void ButtonArray::_notification(int p_what) { Color color_normal = get_color("font_color"); Color color_selected = get_color("font_color_selected"); - int sep=button_sep; - int ofs=0; - int expand=0; + int sep = button_sep; + int ofs = 0; + int expand = 0; - switch(align) { + switch (align) { case ALIGN_BEGIN: { - ofs=0; + ofs = 0; } break; case ALIGN_CENTER: { - ofs=Math::floor((size[orientation] - minsize[orientation])/2); + ofs = Math::floor((size[orientation] - minsize[orientation]) / 2); } break; case ALIGN_END: { - ofs=Math::floor((size[orientation] - minsize[orientation])); + ofs = Math::floor((size[orientation] - minsize[orientation])); } break; case ALIGN_FILL: { - if (buttons.size()>1) - sep+=Math::floor((size[orientation]- minsize[orientation])/(buttons.size()-1.0)); - ofs=0; + if (buttons.size() > 1) + sep += Math::floor((size[orientation] - minsize[orientation]) / (buttons.size() - 1.0)); + ofs = 0; } break; case ALIGN_EXPAND_FILL: { - ofs=0; - expand=size[orientation] - minsize[orientation]; + ofs = 0; + expand = size[orientation] - minsize[orientation]; } break; - - - } - int op_size = orientation==VERTICAL ? size.width : size.height; - + int op_size = orientation == VERTICAL ? size.width : size.height; - for(int i=0;i0) { - s+=expand/buttons.size(); + int s = ms; + if (expand > 0) { + s += expand / buttons.size(); } - if(min_button_size != -1 && s < min_button_size){ + if (min_button_size != -1 && s < min_button_size) { s = min_button_size; } Rect2 r; - r.pos[orientation]=ofs; - r.pos[!orientation]=0; - r.size[orientation]=s; - r.size[!orientation]=op_size; + r.pos[orientation] = ofs; + r.pos[!orientation] = 0; + r.size[orientation] = s; + r.size[!orientation] = op_size; Ref f; Color c; Point2 sbsize; Point2 sbofs; - if (i==selected) { - draw_style_box(style_selected,r); - sbsize=style_selected->get_minimum_size(); - sbofs=style_selected->get_offset(); - f=font_selected; - c=color_selected; + if (i == selected) { + draw_style_box(style_selected, r); + sbsize = style_selected->get_minimum_size(); + sbofs = style_selected->get_offset(); + f = font_selected; + c = color_selected; if (has_focus()) - draw_style_box(style_focus,r); + draw_style_box(style_focus, r); } else { - if (hover==i) - draw_style_box(style_hover,r); + if (hover == i) + draw_style_box(style_hover, r); else if (!flat) - draw_style_box(style_normal,r); - sbsize=style_normal->get_minimum_size(); - sbofs=style_normal->get_offset(); - f=font_normal; - c=color_normal; + draw_style_box(style_normal, r); + sbsize = style_normal->get_minimum_size(); + sbofs = style_normal->get_offset(); + f = font_normal; + c = color_normal; } Size2 ssize = f->get_string_size(buttons[i].xl_text); if (buttons[i].icon.is_valid()) { - ssize.x+=buttons[i].icon->get_width(); + ssize.x += buttons[i].icon->get_width(); } - Point2 text_ofs=((r.size-ssize-sbsize)/2.0+Point2(0,f->get_ascent())).floor()+sbofs; + Point2 text_ofs = ((r.size - ssize - sbsize) / 2.0 + Point2(0, f->get_ascent())).floor() + sbofs; if (buttons[i].icon.is_valid()) { - draw_texture(buttons[i].icon,r.pos+Point2(text_ofs.x,Math::floor((r.size.height-buttons[i].icon->get_height())/2.0))); - text_ofs.x+=buttons[i].icon->get_width()+icon_sep; - + draw_texture(buttons[i].icon, r.pos + Point2(text_ofs.x, Math::floor((r.size.height - buttons[i].icon->get_height()) / 2.0))); + text_ofs.x += buttons[i].icon->get_width() + icon_sep; } - draw_string(f,text_ofs+r.pos,buttons[i].xl_text,c); - buttons[i]._pos_cache=ofs; - buttons[i]._size_cache=s; + draw_string(f, text_ofs + r.pos, buttons[i].xl_text, c); + buttons[i]._pos_cache = ofs; + buttons[i]._size_cache = s; - ofs+=s; - ofs+=sep; + ofs += s; + ofs += sep; } } break; } } - -void ButtonArray::_gui_input(const InputEvent& p_event) { +void ButtonArray::_gui_input(const InputEvent &p_event) { if ( - ( (orientation==HORIZONTAL && p_event.is_action("ui_left") ) || - (orientation==VERTICAL && p_event.is_action("ui_up") ) ) - && p_event.is_pressed() && selected>0) { - set_selected(selected-1); - accept_event(); - emit_signal("button_selected",selected); - return; - + ((orientation == HORIZONTAL && p_event.is_action("ui_left")) || + (orientation == VERTICAL && p_event.is_action("ui_up"))) && + p_event.is_pressed() && selected > 0) { + set_selected(selected - 1); + accept_event(); + emit_signal("button_selected", selected); + return; } if ( - ( (orientation==HORIZONTAL && p_event.is_action("ui_right") ) || - (orientation==VERTICAL && p_event.is_action("ui_down") ) ) - && p_event.is_pressed() && selected<(buttons.size()-1)) { - set_selected(selected+1); - accept_event(); - emit_signal("button_selected",selected); - return; - + ((orientation == HORIZONTAL && p_event.is_action("ui_right")) || + (orientation == VERTICAL && p_event.is_action("ui_down"))) && + p_event.is_pressed() && selected < (buttons.size() - 1)) { + set_selected(selected + 1); + accept_event(); + emit_signal("button_selected", selected); + return; } - if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index==BUTTON_LEFT) { + if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index == BUTTON_LEFT) { - int ofs = orientation==HORIZONTAL ? p_event.mouse_button.x: p_event.mouse_button.y; + int ofs = orientation == HORIZONTAL ? p_event.mouse_button.x : p_event.mouse_button.y; - for(int i=0;i=buttons[i]._pos_cache && ofs= buttons[i]._pos_cache && ofs < buttons[i]._pos_cache + buttons[i]._size_cache) { set_selected(i); - emit_signal("button_selected",i); + emit_signal("button_selected", i); return; } - } } - if (p_event.type==InputEvent::MOUSE_MOTION) { + if (p_event.type == InputEvent::MOUSE_MOTION) { - int ofs = orientation==HORIZONTAL ? p_event.mouse_motion.x: p_event.mouse_motion.y; - int new_hover=-1; - for(int i=0;i=buttons[i]._pos_cache && ofs= buttons[i]._pos_cache && ofs < buttons[i]._pos_cache + buttons[i]._size_cache) { - new_hover=i; + new_hover = i; break; } - } - if (new_hover!=hover) { - hover=new_hover; + if (new_hover != hover) { + hover = new_hover; emit_signal("mouse_sub_enter"); update(); } } - - } -String ButtonArray::get_tooltip(const Point2& p_pos) const { +String ButtonArray::get_tooltip(const Point2 &p_pos) const { - int ofs = orientation==HORIZONTAL ? p_pos.x: p_pos.y; - for(int i=0;i=buttons[i]._pos_cache && ofs= buttons[i]._pos_cache && ofs < buttons[i]._pos_cache + buttons[i]._size_cache) return buttons[i].tooltip; - } return Control::get_tooltip(p_pos); } void ButtonArray::set_align(Align p_align) { - align=p_align; + align = p_align; update(); - } ButtonArray::Align ButtonArray::get_align() const { @@ -391,7 +368,7 @@ ButtonArray::Align ButtonArray::get_align() const { void ButtonArray::set_flat(bool p_flat) { - flat=p_flat; + flat = p_flat; update(); } @@ -400,79 +377,74 @@ bool ButtonArray::is_flat() const { return flat; } - -void ButtonArray::add_button(const String& p_text,const String& p_tooltip) { +void ButtonArray::add_button(const String &p_text, const String &p_tooltip) { Button button; - button.text=p_text; - button.xl_text=XL_MESSAGE(p_text); - button.tooltip=p_tooltip; + button.text = p_text; + button.xl_text = XL_MESSAGE(p_text); + button.tooltip = p_tooltip; buttons.push_back(button); update(); - if (selected==-1) - selected=0; + if (selected == -1) + selected = 0; minimum_size_changed(); } -void ButtonArray::add_icon_button(const Ref& p_icon,const String& p_text,const String& p_tooltip) { +void ButtonArray::add_icon_button(const Ref &p_icon, const String &p_text, const String &p_tooltip) { Button button; - button.text=p_text; - button.xl_text=XL_MESSAGE(p_text); - button.icon=p_icon; - button.tooltip=p_tooltip; + button.text = p_text; + button.xl_text = XL_MESSAGE(p_text); + button.icon = p_icon; + button.tooltip = p_tooltip; buttons.push_back(button); - if (selected==-1) - selected=0; + if (selected == -1) + selected = 0; update(); - } -void ButtonArray::set_button_text(int p_button, const String& p_text) { +void ButtonArray::set_button_text(int p_button, const String &p_text) { - ERR_FAIL_INDEX(p_button,buttons.size()); - buttons[p_button].text=p_text; - buttons[p_button].xl_text=XL_MESSAGE(p_text); + ERR_FAIL_INDEX(p_button, buttons.size()); + buttons[p_button].text = p_text; + buttons[p_button].xl_text = XL_MESSAGE(p_text); update(); minimum_size_changed(); - } -void ButtonArray::set_button_tooltip(int p_button, const String& p_text) { - - ERR_FAIL_INDEX(p_button,buttons.size()); - buttons[p_button].tooltip=p_text; +void ButtonArray::set_button_tooltip(int p_button, const String &p_text) { + ERR_FAIL_INDEX(p_button, buttons.size()); + buttons[p_button].tooltip = p_text; } -void ButtonArray::set_button_icon(int p_button, const Ref& p_icon) { +void ButtonArray::set_button_icon(int p_button, const Ref &p_icon) { - ERR_FAIL_INDEX(p_button,buttons.size()); - buttons[p_button].icon=p_icon; + ERR_FAIL_INDEX(p_button, buttons.size()); + buttons[p_button].icon = p_icon; update(); minimum_size_changed(); } String ButtonArray::get_button_text(int p_button) const { - ERR_FAIL_INDEX_V(p_button,buttons.size(),""); + ERR_FAIL_INDEX_V(p_button, buttons.size(), ""); return buttons[p_button].text; } String ButtonArray::get_button_tooltip(int p_button) const { - ERR_FAIL_INDEX_V(p_button,buttons.size(),""); + ERR_FAIL_INDEX_V(p_button, buttons.size(), ""); return buttons[p_button].tooltip; } Ref ButtonArray::get_button_icon(int p_button) const { - ERR_FAIL_INDEX_V(p_button,buttons.size(),Ref()); + ERR_FAIL_INDEX_V(p_button, buttons.size(), Ref()); return buttons[p_button].icon; - } int ButtonArray::get_selected() const { @@ -487,30 +459,29 @@ int ButtonArray::get_hovered() const { void ButtonArray::set_selected(int p_selected) { - ERR_FAIL_INDEX(p_selected,buttons.size()); - selected=p_selected; + ERR_FAIL_INDEX(p_selected, buttons.size()); + selected = p_selected; update(); - } void ButtonArray::erase_button(int p_button) { - ERR_FAIL_INDEX(p_button,buttons.size()); + ERR_FAIL_INDEX(p_button, buttons.size()); buttons.remove(p_button); - if (p_button>=selected) + if (p_button >= selected) selected--; - if (selected<0) - selected=0; - if (selected>=buttons.size()) - selected=buttons.size()-1; + if (selected < 0) + selected = 0; + if (selected >= buttons.size()) + selected = buttons.size() - 1; update(); } -void ButtonArray::clear(){ +void ButtonArray::clear() { buttons.clear(); - selected=-1; + selected = -1; update(); } @@ -521,53 +492,50 @@ int ButtonArray::get_button_count() const { void ButtonArray::get_translatable_strings(List *p_strings) const { - - for(int i=0;ipush_back(buttons[i].text); p_strings->push_back(buttons[i].tooltip); } } - void ButtonArray::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_button","text","tooltip"),&ButtonArray::add_button,DEFVAL("")); - ClassDB::bind_method(D_METHOD("add_icon_button","icon:Texture","text","tooltip"),&ButtonArray::add_icon_button,DEFVAL(""),DEFVAL("")); - ClassDB::bind_method(D_METHOD("set_button_text","button_idx","text"),&ButtonArray::set_button_text); - ClassDB::bind_method(D_METHOD("set_button_tooltip","button_idx","text"),&ButtonArray::set_button_tooltip); - ClassDB::bind_method(D_METHOD("set_button_icon","button_idx","icon:Texture"),&ButtonArray::set_button_icon); - ClassDB::bind_method(D_METHOD("get_button_text","button_idx"),&ButtonArray::get_button_text); - ClassDB::bind_method(D_METHOD("get_button_tooltip","button_idx"),&ButtonArray::get_button_tooltip); - ClassDB::bind_method(D_METHOD("get_button_icon:Texture","button_idx"),&ButtonArray::get_button_icon); - ClassDB::bind_method(D_METHOD("get_button_count"),&ButtonArray::get_button_count); - ClassDB::bind_method(D_METHOD("set_flat","enabled"),&ButtonArray::set_flat); - ClassDB::bind_method(D_METHOD("is_flat"),&ButtonArray::is_flat); - ClassDB::bind_method(D_METHOD("get_selected"),&ButtonArray::get_selected); - ClassDB::bind_method(D_METHOD("get_hovered"),&ButtonArray::get_hovered); - ClassDB::bind_method(D_METHOD("set_selected","button_idx"),&ButtonArray::set_selected); - ClassDB::bind_method(D_METHOD("erase_button","button_idx"),&ButtonArray::erase_button); - ClassDB::bind_method(D_METHOD("clear"),&ButtonArray::clear); - - ClassDB::bind_method(D_METHOD("_gui_input"),&ButtonArray::_gui_input); - - BIND_CONSTANT( ALIGN_BEGIN ); - BIND_CONSTANT( ALIGN_CENTER ); - BIND_CONSTANT( ALIGN_END ); - BIND_CONSTANT( ALIGN_FILL ); - BIND_CONSTANT( ALIGN_EXPAND_FILL ); - - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "flat" ), "set_flat","is_flat") ; - - ADD_SIGNAL( MethodInfo("button_selected",PropertyInfo(Variant::INT,"button_idx"))); - + ClassDB::bind_method(D_METHOD("add_button", "text", "tooltip"), &ButtonArray::add_button, DEFVAL("")); + ClassDB::bind_method(D_METHOD("add_icon_button", "icon:Texture", "text", "tooltip"), &ButtonArray::add_icon_button, DEFVAL(""), DEFVAL("")); + ClassDB::bind_method(D_METHOD("set_button_text", "button_idx", "text"), &ButtonArray::set_button_text); + ClassDB::bind_method(D_METHOD("set_button_tooltip", "button_idx", "text"), &ButtonArray::set_button_tooltip); + ClassDB::bind_method(D_METHOD("set_button_icon", "button_idx", "icon:Texture"), &ButtonArray::set_button_icon); + ClassDB::bind_method(D_METHOD("get_button_text", "button_idx"), &ButtonArray::get_button_text); + ClassDB::bind_method(D_METHOD("get_button_tooltip", "button_idx"), &ButtonArray::get_button_tooltip); + ClassDB::bind_method(D_METHOD("get_button_icon:Texture", "button_idx"), &ButtonArray::get_button_icon); + ClassDB::bind_method(D_METHOD("get_button_count"), &ButtonArray::get_button_count); + ClassDB::bind_method(D_METHOD("set_flat", "enabled"), &ButtonArray::set_flat); + ClassDB::bind_method(D_METHOD("is_flat"), &ButtonArray::is_flat); + ClassDB::bind_method(D_METHOD("get_selected"), &ButtonArray::get_selected); + ClassDB::bind_method(D_METHOD("get_hovered"), &ButtonArray::get_hovered); + ClassDB::bind_method(D_METHOD("set_selected", "button_idx"), &ButtonArray::set_selected); + ClassDB::bind_method(D_METHOD("erase_button", "button_idx"), &ButtonArray::erase_button); + ClassDB::bind_method(D_METHOD("clear"), &ButtonArray::clear); + + ClassDB::bind_method(D_METHOD("_gui_input"), &ButtonArray::_gui_input); + + BIND_CONSTANT(ALIGN_BEGIN); + BIND_CONSTANT(ALIGN_CENTER); + BIND_CONSTANT(ALIGN_END); + BIND_CONSTANT(ALIGN_FILL); + BIND_CONSTANT(ALIGN_EXPAND_FILL); + + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat"); + + ADD_SIGNAL(MethodInfo("button_selected", PropertyInfo(Variant::INT, "button_idx"))); } ButtonArray::ButtonArray(Orientation p_orientation) { - orientation=p_orientation; - selected=-1; + orientation = p_orientation; + selected = -1; set_focus_mode(FOCUS_ALL); - hover=-1; - flat=false; + hover = -1; + flat = false; min_button_size = -1; } diff --git a/scene/gui/button_array.h b/scene/gui/button_array.h index 4865ef037..dac130e79 100644 --- a/scene/gui/button_array.h +++ b/scene/gui/button_array.h @@ -34,6 +34,7 @@ class ButtonArray : public Control { GDCLASS(ButtonArray, Control); + public: enum Align { ALIGN_BEGIN, @@ -42,8 +43,8 @@ public: ALIGN_FILL, ALIGN_EXPAND_FILL }; -private: +private: Orientation orientation; Align align; @@ -64,19 +65,17 @@ private: double min_button_size; Vector