diff options
Diffstat (limited to 'scene/resources')
53 files changed, 1882 insertions, 4503 deletions
diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp index b371266c83..50f3015814 100644 --- a/scene/resources/animation.cpp +++ b/scene/resources/animation.cpp @@ -4754,17 +4754,17 @@ void Animation::compress(uint32_t p_page_size, uint32_t p_fps, float p_split_tol // The frame has advanced, time to validate the previous frame uint32_t current_page_size = base_page_size; - for (uint32_t i = 0; i < data_tracks.size(); i++) { - uint32_t track_size = data_tracks[i].data.size(); // track size - track_size += data_tracks[i].get_temp_packet_size(); // Add the temporary data + for (const AnimationCompressionDataState &state : data_tracks) { + uint32_t track_size = state.data.size(); // track size + track_size += state.get_temp_packet_size(); // Add the temporary data if (track_size > Compression::MAX_DATA_TRACK_SIZE) { rollback = true; //track to large, time track can't point to keys any longer, because key offset is 12 bits break; } current_page_size += track_size; } - for (uint32_t i = 0; i < time_tracks.size(); i++) { - current_page_size += time_tracks[i].packets.size() * 4; // time packet is 32 bits + for (const AnimationCompressionTimeState &state : time_tracks) { + current_page_size += state.packets.size() * 4; // time packet is 32 bits } if (!rollback && current_page_size > p_page_size) { @@ -4776,22 +4776,22 @@ void Animation::compress(uint32_t p_page_size, uint32_t p_fps, float p_split_tol if (rollback) { // Not valid any longer, so rollback and commit page - for (uint32_t i = 0; i < data_tracks.size(); i++) { - data_tracks[i].temp_packets.resize(data_tracks[i].validated_packet_count); + for (AnimationCompressionDataState &state : data_tracks) { + state.temp_packets.resize(state.validated_packet_count); } - for (uint32_t i = 0; i < time_tracks.size(); i++) { - time_tracks[i].key_index = time_tracks[i].validated_key_index; //rollback key - time_tracks[i].packets.resize(time_tracks[i].validated_packet_count); + for (AnimationCompressionTimeState &state : time_tracks) { + state.key_index = state.validated_key_index; //rollback key + state.packets.resize(state.validated_packet_count); } } else { // All valid, so save rollback information - for (uint32_t i = 0; i < data_tracks.size(); i++) { - data_tracks[i].validated_packet_count = data_tracks[i].temp_packets.size(); + for (AnimationCompressionDataState &state : data_tracks) { + state.validated_packet_count = state.temp_packets.size(); } - for (uint32_t i = 0; i < time_tracks.size(); i++) { - time_tracks[i].validated_key_index = time_tracks[i].key_index; - time_tracks[i].validated_packet_count = time_tracks[i].packets.size(); + for (AnimationCompressionTimeState &state : time_tracks) { + state.validated_key_index = state.key_index; + state.validated_packet_count = state.packets.size(); } // Accept this frame as the frame being processed (as long as it exists) @@ -4976,8 +4976,8 @@ void Animation::compress(uint32_t p_page_size, uint32_t p_fps, float p_split_tol } uint32_t new_size = 0; - for (uint32_t i = 0; i < compression.pages.size(); i++) { - new_size += compression.pages[i].data.size(); + for (const Compression::Page &page : compression.pages) { + new_size += page.data.size(); } print_line("Original size: " + itos(orig_size) + " - Compressed size: " + itos(new_size) + " " + String::num(float(new_size) / float(orig_size) * 100, 2) + "% pages: " + itos(compression.pages.size())); @@ -5289,8 +5289,8 @@ int Animation::_get_compressed_key_count(uint32_t p_compressed_track) const { int key_count = 0; - for (uint32_t i = 0; i < compression.pages.size(); i++) { - const uint8_t *page_data = compression.pages[i].data.ptr(); + for (const Compression::Page &page : compression.pages) { + const uint8_t *page_data = page.data.ptr(); // Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported. const uint32_t *indices = (const uint32_t *)page_data; const uint16_t *time_keys = (const uint16_t *)&page_data[indices[p_compressed_track * 3 + 0]]; @@ -5323,8 +5323,8 @@ bool Animation::_fetch_compressed_by_index(uint32_t p_compressed_track, int p_in ERR_FAIL_COND_V(!compression.enabled, false); ERR_FAIL_UNSIGNED_INDEX_V(p_compressed_track, compression.bounds.size(), false); - for (uint32_t i = 0; i < compression.pages.size(); i++) { - const uint8_t *page_data = compression.pages[i].data.ptr(); + for (const Compression::Page &page : compression.pages) { + const uint8_t *page_data = page.data.ptr(); // Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported. const uint32_t *indices = (const uint32_t *)page_data; const uint16_t *time_keys = (const uint16_t *)&page_data[indices[p_compressed_track * 3 + 0]]; @@ -5374,7 +5374,7 @@ bool Animation::_fetch_compressed_by_index(uint32_t p_compressed_track, int p_in } } - r_time = compression.pages[i].time_offset + double(frame) / double(compression.fps); + r_time = page.time_offset + double(frame) / double(compression.fps); for (uint32_t l = 0; l < COMPONENTS; l++) { r_value[l] = decode[l]; } diff --git a/scene/resources/audio_stream_polyphonic.cpp b/scene/resources/audio_stream_polyphonic.cpp new file mode 100644 index 0000000000..f7299b0789 --- /dev/null +++ b/scene/resources/audio_stream_polyphonic.cpp @@ -0,0 +1,274 @@ +/**************************************************************************/ +/* audio_stream_polyphonic.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#include "audio_stream_polyphonic.h" +#include "scene/main/scene_tree.h" + +Ref<AudioStreamPlayback> AudioStreamPolyphonic::instantiate_playback() { + Ref<AudioStreamPlaybackPolyphonic> playback; + playback.instantiate(); + playback->streams.resize(polyphony); + return playback; +} + +String AudioStreamPolyphonic::get_stream_name() const { + return "AudioStreamPolyphonic"; +} + +bool AudioStreamPolyphonic::is_monophonic() const { + return true; // This avoids stream players to instantiate more than one of these. +} + +void AudioStreamPolyphonic::set_polyphony(int p_voices) { + ERR_FAIL_COND(p_voices < 0 || p_voices > 128); + polyphony = p_voices; +} +int AudioStreamPolyphonic::get_polyphony() const { + return polyphony; +} + +void AudioStreamPolyphonic::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_polyphony", "voices"), &AudioStreamPolyphonic::set_polyphony); + ClassDB::bind_method(D_METHOD("get_polyphony"), &AudioStreamPolyphonic::get_polyphony); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "polyphony", PROPERTY_HINT_RANGE, "1,128,1"), "set_polyphony", "get_polyphony"); +} + +AudioStreamPolyphonic::AudioStreamPolyphonic() { +} + +//////////////////////// + +void AudioStreamPlaybackPolyphonic::start(double p_from_pos) { + if (active) { + stop(); + } + + active = true; +} + +void AudioStreamPlaybackPolyphonic::stop() { + if (!active) { + return; + } + + bool locked = false; + for (Stream &s : streams) { + if (s.active.is_set()) { + // Need locking because something may still be mixing. + locked = true; + AudioServer::get_singleton()->lock(); + } + s.active.clear(); + s.finish_request.clear(); + s.stream_playback.unref(); + s.stream.unref(); + } + if (locked) { + AudioServer::get_singleton()->unlock(); + } + + active = false; +} + +bool AudioStreamPlaybackPolyphonic::is_playing() const { + return active; +} + +int AudioStreamPlaybackPolyphonic::get_loop_count() const { + return 0; +} + +double AudioStreamPlaybackPolyphonic::get_playback_position() const { + return 0; +} +void AudioStreamPlaybackPolyphonic::seek(double p_time) { + // Ignored. +} + +void AudioStreamPlaybackPolyphonic::tag_used_streams() { + for (Stream &s : streams) { + if (s.active.is_set()) { + s.stream_playback->tag_used_streams(); + } + } +} + +int AudioStreamPlaybackPolyphonic::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) { + if (!active) { + return 0; + } + + // Pre-clear buffer. + for (int i = 0; i < p_frames; i++) { + p_buffer[i] = AudioFrame(0, 0); + } + + for (Stream &s : streams) { + if (!s.active.is_set()) { + continue; + } + + float volume_db = s.volume_db; // Copy because it can be overridden at any time. + float next_volume = Math::db_to_linear(volume_db); + s.prev_volume_db = volume_db; + + if (s.finish_request.is_set()) { + if (s.pending_play.is_set()) { + // Did not get the chance to play, was finalized too soon. + s.active.clear(); + continue; + } + next_volume = 0; + } + + if (s.pending_play.is_set()) { + s.stream_playback->start(s.play_offset); + s.pending_play.clear(); + } + float prev_volume = Math::db_to_linear(s.prev_volume_db); + + float volume_inc = (next_volume - prev_volume) / float(p_frames); + + int todo = p_frames; + int offset = 0; + float volume = prev_volume; + + bool stream_done = false; + + while (todo) { + int to_mix = MIN(todo, int(INTERNAL_BUFFER_LEN)); + int mixed = s.stream_playback->mix(internal_buffer, s.pitch_scale, to_mix); + + for (int i = 0; i < to_mix; i++) { + p_buffer[offset + i] += internal_buffer[i] * volume; + volume += volume_inc; + } + + if (mixed < to_mix) { + // Stream is done. + s.active.clear(); + stream_done = true; + break; + } + + todo -= to_mix; + offset += to_mix; + } + + if (stream_done) { + continue; + } + + if (s.finish_request.is_set()) { + s.active.clear(); + } + } + + return p_frames; +} + +AudioStreamPlaybackPolyphonic::ID AudioStreamPlaybackPolyphonic::play_stream(const Ref<AudioStream> &p_stream, float p_from_offset, float p_volume_db, float p_pitch_scale) { + ERR_FAIL_COND_V(p_stream.is_null(), INVALID_ID); + for (uint32_t i = 0; i < streams.size(); i++) { + if (!streams[i].active.is_set()) { + // Can use this stream, as it's not active. + streams[i].stream = p_stream; + streams[i].stream_playback = streams[i].stream->instantiate_playback(); + streams[i].play_offset = p_from_offset; + streams[i].volume_db = p_volume_db; + streams[i].prev_volume_db = p_volume_db; + streams[i].pitch_scale = p_pitch_scale; + streams[i].id = id_counter++; + streams[i].finish_request.clear(); + streams[i].pending_play.set(); + streams[i].active.set(); + return (ID(i) << INDEX_SHIFT) | ID(streams[i].id); + } + } + + return INVALID_ID; +} + +AudioStreamPlaybackPolyphonic::Stream *AudioStreamPlaybackPolyphonic::_find_stream(int64_t p_id) { + uint32_t index = p_id >> INDEX_SHIFT; + if (index >= streams.size()) { + return nullptr; + } + if (!streams[index].active.is_set()) { + return nullptr; // Not active, no longer exists. + } + int64_t id = p_id & ID_MASK; + if (streams[index].id != id) { + return nullptr; + } + return &streams[index]; +} + +void AudioStreamPlaybackPolyphonic::set_stream_volume(ID p_stream_id, float p_volume_db) { + Stream *s = _find_stream(p_stream_id); + if (!s) { + return; + } + s->volume_db = p_volume_db; +} + +void AudioStreamPlaybackPolyphonic::set_stream_pitch_scale(ID p_stream_id, float p_pitch_scale) { + Stream *s = _find_stream(p_stream_id); + if (!s) { + return; + } + s->pitch_scale = p_pitch_scale; +} + +bool AudioStreamPlaybackPolyphonic::is_stream_playing(ID p_stream_id) const { + return const_cast<AudioStreamPlaybackPolyphonic *>(this)->_find_stream(p_stream_id) != nullptr; +} + +void AudioStreamPlaybackPolyphonic::stop_stream(ID p_stream_id) { + Stream *s = _find_stream(p_stream_id); + if (!s) { + return; + } + s->finish_request.set(); +} + +void AudioStreamPlaybackPolyphonic::_bind_methods() { + ClassDB::bind_method(D_METHOD("play_stream", "stream", "from_offset", "volume_db", "pitch_scale"), &AudioStreamPlaybackPolyphonic::play_stream, DEFVAL(0), DEFVAL(0), DEFVAL(1.0)); + ClassDB::bind_method(D_METHOD("set_stream_volume", "stream", "volume_db"), &AudioStreamPlaybackPolyphonic::set_stream_volume); + ClassDB::bind_method(D_METHOD("set_stream_pitch_scale", "stream", "pitch_scale"), &AudioStreamPlaybackPolyphonic::set_stream_pitch_scale); + ClassDB::bind_method(D_METHOD("is_stream_playing", "stream"), &AudioStreamPlaybackPolyphonic::is_stream_playing); + ClassDB::bind_method(D_METHOD("stop_stream", "stream"), &AudioStreamPlaybackPolyphonic::stop_stream); + + BIND_CONSTANT(INVALID_ID); +} + +AudioStreamPlaybackPolyphonic::AudioStreamPlaybackPolyphonic() { +} diff --git a/scene/resources/skeleton_modification_stack_3d.h b/scene/resources/audio_stream_polyphonic.h index fd490c49e9..e414401b6f 100644 --- a/scene/resources/skeleton_modification_stack_3d.h +++ b/scene/resources/audio_stream_polyphonic.h @@ -1,5 +1,5 @@ /**************************************************************************/ -/* skeleton_modification_stack_3d.h */ +/* audio_stream_polyphonic.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,64 +28,92 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ -#ifndef SKELETON_MODIFICATION_STACK_3D_H -#define SKELETON_MODIFICATION_STACK_3D_H +#ifndef AUDIO_STREAM_POLYPHONIC_H +#define AUDIO_STREAM_POLYPHONIC_H #include "core/templates/local_vector.h" -#include "scene/3d/skeleton_3d.h" +#include "servers/audio/audio_stream.h" -class Skeleton3D; -class SkeletonModification3D; +class AudioStreamPolyphonic : public AudioStream { + GDCLASS(AudioStreamPolyphonic, AudioStream) + int polyphony = 32; -class SkeletonModificationStack3D : public Resource { - GDCLASS(SkeletonModificationStack3D, Resource); - friend class Skeleton3D; - friend class SkeletonModification3D; - -protected: static void _bind_methods(); - virtual void _get_property_list(List<PropertyInfo> *p_list) const; - virtual bool _set(const StringName &p_path, const Variant &p_value); - virtual bool _get(const StringName &p_path, Variant &r_ret) const; public: - Skeleton3D *skeleton = nullptr; - bool is_setup = false; - bool enabled = false; - real_t strength = 1.0; - - enum EXECUTION_MODE { - execution_mode_process, - execution_mode_physics_process, + virtual Ref<AudioStreamPlayback> instantiate_playback() override; + virtual String get_stream_name() const override; + virtual bool is_monophonic() const override; + + void set_polyphony(int p_voices); + int get_polyphony() const; + + AudioStreamPolyphonic(); +}; + +class AudioStreamPlaybackPolyphonic : public AudioStreamPlayback { + GDCLASS(AudioStreamPlaybackPolyphonic, AudioStreamPlayback) + + enum { + INTERNAL_BUFFER_LEN = 128, + ID_MASK = 0xFFFFFFFF, + INDEX_SHIFT = 32 + }; + struct Stream { + SafeFlag active; + SafeFlag pending_play; + SafeFlag finish_request; + float play_offset = 0; + float pitch_scale = 1.0; + Ref<AudioStream> stream; + Ref<AudioStreamPlayback> stream_playback; + float prev_volume_db = 0; + float volume_db = 0; + uint32_t id = 0; + + Stream() : + active(false), pending_play(false), finish_request(false) {} }; - LocalVector<Ref<SkeletonModification3D>> modifications = LocalVector<Ref<SkeletonModification3D>>(); - int modifications_count = 0; + LocalVector<Stream> streams; + AudioFrame internal_buffer[INTERNAL_BUFFER_LEN]; - virtual void setup(); - virtual void execute(real_t p_delta, int p_execution_mode); + bool active = false; + uint32_t id_counter = 1; + + _FORCE_INLINE_ Stream *_find_stream(int64_t p_id); + + friend class AudioStreamPolyphonic; + +protected: + static void _bind_methods(); + +public: + typedef int64_t ID; + enum { + INVALID_ID = -1 + }; - void enable_all_modifications(bool p_enable); - Ref<SkeletonModification3D> get_modification(int p_mod_idx) const; - void add_modification(Ref<SkeletonModification3D> p_mod); - void delete_modification(int p_mod_idx); - void set_modification(int p_mod_idx, Ref<SkeletonModification3D> p_mod); + virtual void start(double p_from_pos = 0.0) override; + virtual void stop() override; + virtual bool is_playing() const override; - void set_modification_count(int p_count); - int get_modification_count() const; + virtual int get_loop_count() const override; //times it looped - void set_skeleton(Skeleton3D *p_skeleton); - Skeleton3D *get_skeleton() const; + virtual double get_playback_position() const override; + virtual void seek(double p_time) override; - bool get_is_setup() const; + virtual void tag_used_streams() override; - void set_enabled(bool p_enabled); - bool get_enabled() const; + virtual int mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) override; - void set_strength(real_t p_strength); - real_t get_strength() const; + ID play_stream(const Ref<AudioStream> &p_stream, float p_from_offset = 0, float p_volume_db = 0, float p_pitch_scale = 1.0); + void set_stream_volume(ID p_stream_id, float p_volume_db); + void set_stream_pitch_scale(ID p_stream_id, float p_pitch_scale); + bool is_stream_playing(ID p_stream_id) const; + void stop_stream(ID p_stream_id); - SkeletonModificationStack3D(); + AudioStreamPlaybackPolyphonic(); }; -#endif // SKELETON_MODIFICATION_STACK_3D_H +#endif // AUDIO_STREAM_POLYPHONIC_H diff --git a/scene/resources/camera_attributes.cpp b/scene/resources/camera_attributes.cpp index b5e302cce5..61df56523d 100644 --- a/scene/resources/camera_attributes.cpp +++ b/scene/resources/camera_attributes.cpp @@ -286,10 +286,10 @@ void CameraAttributesPractical::_bind_methods() { ADD_GROUP("DOF Blur", "dof_blur_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dof_blur_far_enabled"), "set_dof_blur_far_enabled", "is_dof_blur_far_enabled"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_far_distance", PROPERTY_HINT_RANGE, "0.01,8192,0.01,exp,suffix:m"), "set_dof_blur_far_distance", "get_dof_blur_far_distance"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_far_transition", PROPERTY_HINT_RANGE, "0.01,8192,0.01,exp"), "set_dof_blur_far_transition", "get_dof_blur_far_transition"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_far_transition", PROPERTY_HINT_RANGE, "-1,8192,0.01,exp"), "set_dof_blur_far_transition", "get_dof_blur_far_transition"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dof_blur_near_enabled"), "set_dof_blur_near_enabled", "is_dof_blur_near_enabled"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_near_distance", PROPERTY_HINT_RANGE, "0.01,8192,0.01,exp,suffix:m"), "set_dof_blur_near_distance", "get_dof_blur_near_distance"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_near_transition", PROPERTY_HINT_RANGE, "0.01,8192,0.01,exp"), "set_dof_blur_near_transition", "get_dof_blur_near_transition"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_near_transition", PROPERTY_HINT_RANGE, "-1,8192,0.01,exp"), "set_dof_blur_near_transition", "get_dof_blur_near_transition"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dof_blur_amount", "get_dof_blur_amount"); ADD_GROUP("Auto Exposure", "auto_exposure_"); diff --git a/scene/resources/convex_polygon_shape_2d.cpp b/scene/resources/convex_polygon_shape_2d.cpp index d92d4fa4a4..e51b48a4b1 100644 --- a/scene/resources/convex_polygon_shape_2d.cpp +++ b/scene/resources/convex_polygon_shape_2d.cpp @@ -82,7 +82,7 @@ void ConvexPolygonShape2D::draw(const RID &p_to_rid, const Color &p_color) { if (is_collision_outline_enabled()) { RenderingServer::get_singleton()->canvas_item_add_polyline(p_to_rid, points, col); // Draw the last segment as it's not drawn by `canvas_item_add_polyline()`. - RenderingServer::get_singleton()->canvas_item_add_line(p_to_rid, points[points.size() - 1], points[0], p_color, 1.0, true); + RenderingServer::get_singleton()->canvas_item_add_line(p_to_rid, points[points.size() - 1], points[0], p_color, 1.0); } } diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp index 4d3eec6333..7a865691d9 100644 --- a/scene/resources/default_theme/default_theme.cpp +++ b/scene/resources/default_theme/default_theme.cpp @@ -53,7 +53,7 @@ static const int default_corner_radius = 3; static Ref<StyleBoxFlat> make_flat_stylebox(Color p_color, float p_margin_left = default_margin, float p_margin_top = default_margin, float p_margin_right = default_margin, float p_margin_bottom = default_margin, int p_corner_radius = default_corner_radius, bool p_draw_center = true, int p_border_width = 0) { Ref<StyleBoxFlat> style(memnew(StyleBoxFlat)); style->set_bg_color(p_color); - style->set_default_margin_individual(p_margin_left * scale, p_margin_top * scale, p_margin_right * scale, p_margin_bottom * scale); + style->set_content_margin_individual(p_margin_left * scale, p_margin_top * scale, p_margin_right * scale, p_margin_bottom * scale); style->set_corner_radius_all(p_corner_radius); style->set_anti_aliased(true); @@ -67,10 +67,10 @@ static Ref<StyleBoxFlat> make_flat_stylebox(Color p_color, float p_margin_left = } static Ref<StyleBoxFlat> sb_expand(Ref<StyleBoxFlat> p_sbox, float p_left, float p_top, float p_right, float p_bottom) { - p_sbox->set_expand_margin_size(SIDE_LEFT, p_left * scale); - p_sbox->set_expand_margin_size(SIDE_TOP, p_top * scale); - p_sbox->set_expand_margin_size(SIDE_RIGHT, p_right * scale); - p_sbox->set_expand_margin_size(SIDE_BOTTOM, p_bottom * scale); + p_sbox->set_expand_margin(SIDE_LEFT, p_left * scale); + p_sbox->set_expand_margin(SIDE_TOP, p_top * scale); + p_sbox->set_expand_margin(SIDE_RIGHT, p_right * scale); + p_sbox->set_expand_margin(SIDE_BOTTOM, p_bottom * scale); return p_sbox; } @@ -93,7 +93,7 @@ static Ref<ImageTexture> generate_icon(int p_index) { static Ref<StyleBox> make_empty_stylebox(float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_bottom = -1) { Ref<StyleBox> style(memnew(StyleBoxEmpty)); - style->set_default_margin_individual(p_margin_left * scale, p_margin_top * scale, p_margin_right * scale, p_margin_bottom * scale); + style->set_content_margin_individual(p_margin_left * scale, p_margin_top * scale, p_margin_right * scale, p_margin_bottom * scale); return style; } @@ -148,7 +148,7 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const const Ref<StyleBoxFlat> button_disabled = make_flat_stylebox(style_disabled_color); Ref<StyleBoxFlat> focus = make_flat_stylebox(style_focus_color, default_margin, default_margin, default_margin, default_margin, default_corner_radius, false, 2); // Make the focus outline appear to be flush with the buttons it's focusing. - focus->set_expand_margin_size_all(2 * scale); + focus->set_expand_margin_all(2 * scale); theme->set_stylebox("normal", "Button", button_normal); theme->set_stylebox("hover", "Button", button_hover); @@ -279,9 +279,9 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const // CheckBox Ref<StyleBox> cbx_empty = memnew(StyleBoxEmpty); - cbx_empty->set_default_margin_all(4 * scale); + cbx_empty->set_content_margin_all(4 * scale); Ref<StyleBox> cbx_focus = focus; - cbx_focus->set_default_margin_all(4 * scale); + cbx_focus->set_content_margin_all(4 * scale); theme->set_stylebox("normal", "CheckBox", cbx_empty); theme->set_stylebox("pressed", "CheckBox", cbx_empty); @@ -317,7 +317,7 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const // CheckButton Ref<StyleBox> cb_empty = memnew(StyleBoxEmpty); - cb_empty->set_default_margin_individual(6 * scale, 4 * scale, 6 * scale, 4 * scale); + cb_empty->set_content_margin_individual(6 * scale, 4 * scale, 6 * scale, 4 * scale); theme->set_stylebox("normal", "CheckButton", cb_empty); theme->set_stylebox("pressed", "CheckButton", cb_empty); @@ -634,10 +634,10 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const Ref<StyleBoxLine> separator_horizontal = memnew(StyleBoxLine); separator_horizontal->set_thickness(Math::round(scale)); separator_horizontal->set_color(style_separator_color); - separator_horizontal->set_default_margin_individual(default_margin, 0, default_margin, 0); + separator_horizontal->set_content_margin_individual(default_margin, 0, default_margin, 0); Ref<StyleBoxLine> separator_vertical = separator_horizontal->duplicate(); separator_vertical->set_vertical(true); - separator_vertical->set_default_margin_individual(0, default_margin, 0, default_margin); + separator_vertical->set_content_margin_individual(0, default_margin, 0, default_margin); // Always display a border for PopupMenus so they can be distinguished from their background. Ref<StyleBoxFlat> style_popup_panel = make_flat_stylebox(style_popup_color); diff --git a/scene/resources/environment.cpp b/scene/resources/environment.cpp index 746f2f8f9b..8b4656414d 100644 --- a/scene/resources/environment.cpp +++ b/scene/resources/environment.cpp @@ -1043,6 +1043,18 @@ void Environment::_validate_property(PropertyInfo &p_property) const { } } + if (p_property.name == "ambient_light_color" || p_property.name == "ambient_light_energy") { + if (ambient_source == AMBIENT_SOURCE_DISABLED) { + p_property.usage = PROPERTY_USAGE_NO_EDITOR; + } + } + + if (p_property.name == "ambient_light_sky_contribution") { + if (ambient_source == AMBIENT_SOURCE_DISABLED || ambient_source == AMBIENT_SOURCE_COLOR) { + p_property.usage = PROPERTY_USAGE_NO_EDITOR; + } + } + if (p_property.name == "fog_aerial_perspective") { if (bg_mode != BG_SKY) { p_property.usage = PROPERTY_USAGE_NO_EDITOR; diff --git a/scene/resources/immediate_mesh.cpp b/scene/resources/immediate_mesh.cpp index 2254c19327..48d609da97 100644 --- a/scene/resources/immediate_mesh.cpp +++ b/scene/resources/immediate_mesh.cpp @@ -41,8 +41,8 @@ void ImmediateMesh::surface_set_color(const Color &p_color) { if (!uses_colors) { colors.resize(vertices.size()); - for (uint32_t i = 0; i < colors.size(); i++) { - colors[i] = p_color; + for (Color &color : colors) { + color = p_color; } uses_colors = true; } @@ -54,8 +54,8 @@ void ImmediateMesh::surface_set_normal(const Vector3 &p_normal) { if (!uses_normals) { normals.resize(vertices.size()); - for (uint32_t i = 0; i < normals.size(); i++) { - normals[i] = p_normal; + for (Vector3 &normal : normals) { + normal = p_normal; } uses_normals = true; } @@ -66,8 +66,8 @@ void ImmediateMesh::surface_set_tangent(const Plane &p_tangent) { ERR_FAIL_COND_MSG(!surface_active, "Not creating any surface. Use surface_begin() to do it."); if (!uses_tangents) { tangents.resize(vertices.size()); - for (uint32_t i = 0; i < tangents.size(); i++) { - tangents[i] = p_tangent; + for (Plane &tangent : tangents) { + tangent = p_tangent; } uses_tangents = true; } @@ -78,8 +78,8 @@ void ImmediateMesh::surface_set_uv(const Vector2 &p_uv) { ERR_FAIL_COND_MSG(!surface_active, "Not creating any surface. Use surface_begin() to do it."); if (!uses_uvs) { uvs.resize(vertices.size()); - for (uint32_t i = 0; i < uvs.size(); i++) { - uvs[i] = p_uv; + for (Vector2 &uv : uvs) { + uv = p_uv; } uses_uvs = true; } @@ -90,8 +90,8 @@ void ImmediateMesh::surface_set_uv2(const Vector2 &p_uv2) { ERR_FAIL_COND_MSG(!surface_active, "Not creating any surface. Use surface_begin() to do it."); if (!uses_uv2s) { uv2s.resize(vertices.size()); - for (uint32_t i = 0; i < uv2s.size(); i++) { - uv2s[i] = p_uv2; + for (Vector2 &uv : uv2s) { + uv = p_uv2; } uses_uv2s = true; } @@ -194,25 +194,20 @@ void ImmediateMesh::surface_end() { if (uses_normals) { uint32_t *normal = (uint32_t *)&surface_vertex_ptr[i * vertex_stride + normal_offset]; - Vector3 n = normals[i] * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5); + Vector2 n = normals[i].octahedron_encode(); uint32_t value = 0; - value |= CLAMP(int(n.x * 1023.0), 0, 1023); - value |= CLAMP(int(n.y * 1023.0), 0, 1023) << 10; - value |= CLAMP(int(n.z * 1023.0), 0, 1023) << 20; + value |= (uint16_t)CLAMP(n.x * 65535, 0, 65535); + value |= (uint16_t)CLAMP(n.y * 65535, 0, 65535) << 16; *normal = value; } if (uses_tangents) { uint32_t *tangent = (uint32_t *)&surface_vertex_ptr[i * vertex_stride + tangent_offset]; - Plane t = tangents[i]; + Vector2 t = tangents[i].normal.octahedron_tangent_encode(tangents[i].d); uint32_t value = 0; - value |= CLAMP(int((t.normal.x * 0.5 + 0.5) * 1023.0), 0, 1023); - value |= CLAMP(int((t.normal.y * 0.5 + 0.5) * 1023.0), 0, 1023) << 10; - value |= CLAMP(int((t.normal.z * 0.5 + 0.5) * 1023.0), 0, 1023) << 20; - if (t.d > 0) { - value |= 3UL << 30; - } + value |= (uint16_t)CLAMP(t.x * 65535, 0, 65535); + value |= (uint16_t)CLAMP(t.y * 65535, 0, 65535) << 16; *tangent = value; } @@ -346,7 +341,7 @@ TypedArray<Array> ImmediateMesh::surface_get_blend_shape_arrays(int p_surface) c Dictionary ImmediateMesh::surface_get_lods(int p_surface) const { return Dictionary(); } -uint32_t ImmediateMesh::surface_get_format(int p_idx) const { +BitField<Mesh::ArrayFormat> ImmediateMesh::surface_get_format(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, int(surfaces.size()), 0); return surfaces[p_idx].format; } diff --git a/scene/resources/immediate_mesh.h b/scene/resources/immediate_mesh.h index 9407ecd98c..bf07c82a0c 100644 --- a/scene/resources/immediate_mesh.h +++ b/scene/resources/immediate_mesh.h @@ -99,7 +99,7 @@ public: virtual Array surface_get_arrays(int p_surface) const override; virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override; virtual Dictionary surface_get_lods(int p_surface) const override; - virtual uint32_t surface_get_format(int p_idx) const override; + virtual BitField<ArrayFormat> surface_get_format(int p_idx) const override; virtual PrimitiveType surface_get_primitive_type(int p_idx) const override; virtual void surface_set_material(int p_idx, const Ref<Material> &p_material) override; virtual Ref<Material> surface_get_material(int p_idx) const override; diff --git a/scene/resources/importer_mesh.cpp b/scene/resources/importer_mesh.cpp index eefa5aa14a..55b633a40c 100644 --- a/scene/resources/importer_mesh.cpp +++ b/scene/resources/importer_mesh.cpp @@ -364,9 +364,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli const LocalVector<Pair<int, int>> &close_verts = E->value; bool found = false; - for (unsigned int k = 0; k < close_verts.size(); k++) { - const Pair<int, int> &idx = close_verts[k]; - + for (const Pair<int, int> &idx : close_verts) { bool is_uvs_close = (!uvs_ptr || uvs_ptr[j].distance_squared_to(uvs_ptr[idx.second]) < CMP_EPSILON2); bool is_uv2s_close = (!uv2s_ptr || uv2s_ptr[j].distance_squared_to(uv2s_ptr[idx.second]) < CMP_EPSILON2); ERR_FAIL_INDEX(idx.second, normals.size()); @@ -599,8 +597,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli const LocalVector<int> &corners = vertex_corners[j]; const Vector3 &vertex_normal = normals_ptr[j]; - for (unsigned int k = 0; k < corners.size(); k++) { - const int &corner_idx = corners[k]; + for (const int &corner_idx : corners) { const Vector3 &ray_normal = ray_normals[corner_idx]; if (ray_normal.length_squared() < CMP_EPSILON2) { @@ -635,8 +632,8 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli split_vertex_indices.push_back(j); split_vertex_normals.push_back(n); int new_idx = split_vertex_count++; - for (unsigned int l = 0; l < group_indices.size(); l++) { - new_indices_ptr[group_indices[l]] = new_idx; + for (const int &index : group_indices) { + new_indices_ptr[index] = new_idx; } } } @@ -1241,10 +1238,10 @@ Error ImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform, } //generate surfaces - for (unsigned int i = 0; i < surfaces_tools.size(); i++) { - surfaces_tools[i]->index(); - Array arrays = surfaces_tools[i]->commit_to_arrays(); - add_surface(surfaces_tools[i]->get_primitive_type(), arrays, Array(), Dictionary(), surfaces_tools[i]->get_material(), surfaces_tools[i]->get_meta("name")); + for (Ref<SurfaceTool> &tool : surfaces_tools) { + tool->index(); + Array arrays = tool->commit_to_arrays(); + add_surface(tool->get_primitive_type(), arrays, Array(), Dictionary(), tool->get_material(), tool->get_meta("name")); } set_lightmap_size_hint(Size2(size_x, size_y)); diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp index d5c3f7730b..9c3a2ffb87 100644 --- a/scene/resources/material.cpp +++ b/scene/resources/material.cpp @@ -149,11 +149,36 @@ Material::~Material() { bool ShaderMaterial::_set(const StringName &p_name, const Variant &p_value) { if (shader.is_valid()) { - StringName pr = shader->remap_parameter(p_name); - if (pr) { - set_shader_parameter(pr, p_value); + const StringName *sn = remap_cache.getptr(p_name); + if (sn) { + set_shader_parameter(*sn, p_value); + return true; + } + String s = p_name; + if (s.begins_with("shader_parameter/")) { + String param = s.replace_first("shader_parameter/", ""); + remap_cache[s] = param; + set_shader_parameter(param, p_value); return true; } +#ifndef DISABLE_DEPRECATED + // Compatibility remaps are only needed here. + if (s.begins_with("param/")) { + s = s.replace_first("param/", "shader_parameter/"); + } else if (s.begins_with("shader_param/")) { + s = s.replace_first("shader_param/", "shader_parameter/"); + } else if (s.begins_with("shader_uniform/")) { + s = s.replace_first("shader_uniform/", "shader_parameter/"); + } else { + return false; // Not a shader parameter. + } + + WARN_PRINT("This material (containing shader with path: '" + shader->get_path() + "') uses an old deprecated parameter names. Consider re-saving this resource (or scene which contains it) in order for it to continue working in future versions."); + String param = s.replace_first("shader_parameter/", ""); + remap_cache[s] = param; + set_shader_parameter(param, p_value); + return true; +#endif } return false; @@ -161,9 +186,10 @@ bool ShaderMaterial::_set(const StringName &p_name, const Variant &p_value) { bool ShaderMaterial::_get(const StringName &p_name, Variant &r_ret) const { if (shader.is_valid()) { - StringName pr = shader->remap_parameter(p_name); - if (pr) { - r_ret = get_shader_parameter(pr); + const StringName *sn = remap_cache.getptr(p_name); + if (sn) { + // Only return a parameter if it was previously set. + r_ret = get_shader_parameter(*sn); return true; } } @@ -247,6 +273,12 @@ void ShaderMaterial::_get_property_list(List<PropertyInfo> *p_list) const { PropertyInfo info = E->get(); info.name = "shader_parameter/" + info.name; + if (!param_cache.has(E->get().name)) { + // Property has never been edited, retrieve with default value. + Variant default_value = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), E->get().name); + param_cache.insert(E->get().name, default_value); + remap_cache.insert(info.name, E->get().name); + } groups[last_group][last_subgroup].push_back(info); } @@ -275,11 +307,10 @@ void ShaderMaterial::_get_property_list(List<PropertyInfo> *p_list) const { bool ShaderMaterial::_property_can_revert(const StringName &p_name) const { if (shader.is_valid()) { - StringName pr = shader->remap_parameter(p_name); + const StringName *pr = remap_cache.getptr(p_name); if (pr) { - Variant default_value = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), pr); - Variant current_value; - _get(p_name, current_value); + Variant default_value = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), *pr); + Variant current_value = get_shader_parameter(*pr); return default_value.get_type() != Variant::NIL && default_value != current_value; } } @@ -288,9 +319,9 @@ bool ShaderMaterial::_property_can_revert(const StringName &p_name) const { bool ShaderMaterial::_property_get_revert(const StringName &p_name, Variant &r_property) const { if (shader.is_valid()) { - StringName pr = shader->remap_parameter(p_name); - if (pr) { - r_property = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), pr); + const StringName *pr = remap_cache.getptr(p_name); + if (*pr) { + r_property = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), *pr); return true; } } @@ -791,6 +822,14 @@ void BaseMaterial3D::_update_shader() { code += "uniform vec4 refraction_texture_channel;\n"; } + if (features[FEATURE_REFRACTION]) { + code += "uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_linear_mipmap;"; + } + + if (proximity_fade_enabled) { + code += "uniform sampler2D depth_texture : hint_depth_texture, repeat_disable, filter_nearest;"; + } + if (features[FEATURE_NORMAL_MAPPING]) { code += "uniform sampler2D texture_normal : hint_roughness_normal," + texfilter_str + ";\n"; code += "uniform float normal_scale : hint_range(-16,16);\n"; @@ -1228,7 +1267,7 @@ void BaseMaterial3D::_update_shader() { code += " vec2 ref_ofs = SCREEN_UV - ref_normal.xy * dot(texture(texture_refraction,base_uv),refraction_texture_channel) * refraction;\n"; } code += " float ref_amount = 1.0 - albedo.a * albedo_tex.a;\n"; - code += " EMISSION += textureLod(SCREEN_TEXTURE,ref_ofs,ROUGHNESS * 8.0).rgb * ref_amount;\n"; + code += " EMISSION += textureLod(screen_texture,ref_ofs,ROUGHNESS * 8.0).rgb * ref_amount;\n"; code += " ALBEDO *= 1.0 - ref_amount;\n"; code += " ALPHA = 1.0;\n"; @@ -1246,7 +1285,7 @@ void BaseMaterial3D::_update_shader() { } if (proximity_fade_enabled) { - code += " float depth_tex = textureLod(DEPTH_TEXTURE,SCREEN_UV,0.0).r;\n"; + code += " float depth_tex = textureLod(depth_texture,SCREEN_UV,0.0).r;\n"; code += " vec4 world_pos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV*2.0-1.0,depth_tex,1.0);\n"; code += " world_pos.xyz/=world_pos.w;\n"; code += " ALPHA*=clamp(1.0-smoothstep(world_pos.z+proximity_fade_distance,world_pos.z,VERTEX.z),0.0,1.0);\n"; diff --git a/scene/resources/material.h b/scene/resources/material.h index f1777d31f4..83c7a09cc4 100644 --- a/scene/resources/material.h +++ b/scene/resources/material.h @@ -82,7 +82,8 @@ class ShaderMaterial : public Material { GDCLASS(ShaderMaterial, Material); Ref<Shader> shader; - HashMap<StringName, Variant> param_cache; + mutable HashMap<StringName, StringName> remap_cache; + mutable HashMap<StringName, Variant> param_cache; protected: bool _set(const StringName &p_name, const Variant &p_value); diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp index 07baa0ad96..991e060e94 100644 --- a/scene/resources/mesh.cpp +++ b/scene/resources/mesh.cpp @@ -75,7 +75,7 @@ Dictionary Mesh::surface_get_lods(int p_surface) const { return ret; } -uint32_t Mesh::surface_get_format(int p_idx) const { +BitField<Mesh::ArrayFormat> Mesh::surface_get_format(int p_idx) const { uint32_t ret = 0; GDVIRTUAL_REQUIRED_CALL(_surface_get_format, p_idx, ret); return ret; @@ -189,6 +189,7 @@ Ref<TriangleMesh> Mesh::generate_triangle_mesh() const { if (primitive == PRIMITIVE_TRIANGLES) { for (int j = 0; j < ic; j++) { int index = ir[j]; + ERR_FAIL_COND_V(index >= vc, Ref<TriangleMesh>()); facesw[widx++] = vr[index]; } } else { // PRIMITIVE_TRIANGLE_STRIP @@ -658,35 +659,36 @@ void Mesh::_bind_methods() { BIND_ENUM_CONSTANT(ARRAY_CUSTOM_RGBA_FLOAT); BIND_ENUM_CONSTANT(ARRAY_CUSTOM_MAX); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_VERTEX); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_NORMAL); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_TANGENT); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_COLOR); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV2); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM0); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM1); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM2); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM3); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_BONES); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_WEIGHTS); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_INDEX); - - BIND_ENUM_CONSTANT(ARRAY_FORMAT_BLEND_SHAPE_MASK); - - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM_BASE); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM_BITS); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM0_SHIFT); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM1_SHIFT); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM2_SHIFT); - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM3_SHIFT); - - BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM_MASK); - BIND_ENUM_CONSTANT(ARRAY_COMPRESS_FLAGS_BASE); - - BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_2D_VERTICES); - BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_DYNAMIC_UPDATE); - BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_8_BONE_WEIGHTS); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_VERTEX); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_NORMAL); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_TANGENT); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_COLOR); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_TEX_UV); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_TEX_UV2); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM0); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM1); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM2); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM3); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_BONES); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_WEIGHTS); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_INDEX); + + BIND_BITFIELD_FLAG(ARRAY_FORMAT_BLEND_SHAPE_MASK); + + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM_BASE); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM_BITS); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM0_SHIFT); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM1_SHIFT); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM2_SHIFT); + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM3_SHIFT); + + BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM_MASK); + BIND_BITFIELD_FLAG(ARRAY_COMPRESS_FLAGS_BASE); + + BIND_BITFIELD_FLAG(ARRAY_FLAG_USE_2D_VERTICES); + BIND_BITFIELD_FLAG(ARRAY_FLAG_USE_DYNAMIC_UPDATE); + BIND_BITFIELD_FLAG(ARRAY_FLAG_USE_8_BONE_WEIGHTS); + BIND_BITFIELD_FLAG(ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY); BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_NORMALIZED); BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_RELATIVE); @@ -1120,17 +1122,6 @@ bool ArrayMesh::_set(const StringName &p_name, const Variant &p_value) { } int idx = sname.substr(8, sl - 8).to_int(); - // This is a bit of a hack to ensure compatibility with older material - // overrides that start indexing at 1. - // We assume that idx 0 is always read first, if its not, this won't work. - if (idx == 0) { - surface_index_0 = true; - } - if (!surface_index_0) { - // This means the file was created when the indexing started at 1, so decrease by one. - idx--; - } - String what = sname.get_slicec('/', 1); if (what == "material") { surface_set_material(idx, p_value); @@ -1554,7 +1545,8 @@ void ArrayMesh::_recompute_aabb() { } // TODO: Need to add binding to add_surface using future MeshSurfaceData object. -void ArrayMesh::add_surface(uint32_t p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data, const Vector<AABB> &p_bone_aabbs, const Vector<RS::SurfaceData::LOD> &p_lods) { +void ArrayMesh::add_surface(BitField<ArrayFormat> p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data, const Vector<AABB> &p_bone_aabbs, const Vector<RS::SurfaceData::LOD> &p_lods) { + ERR_FAIL_COND(surfaces.size() == RS::MAX_MESH_SURFACES); _create_if_empty(); Surface s; @@ -1589,7 +1581,8 @@ void ArrayMesh::add_surface(uint32_t p_format, PrimitiveType p_primitive, const emit_changed(); } -void ArrayMesh::add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes, const Dictionary &p_lods, uint32_t p_flags) { +void ArrayMesh::add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes, const Dictionary &p_lods, BitField<ArrayFormat> p_flags) { + ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size()); ERR_FAIL_COND(p_arrays.size() != ARRAY_MAX); RS::SurfaceData surface; @@ -1705,7 +1698,7 @@ int ArrayMesh::surface_get_array_index_len(int p_idx) const { return surfaces[p_idx].index_array_length; } -uint32_t ArrayMesh::surface_get_format(int p_idx) const { +BitField<Mesh::ArrayFormat> ArrayMesh::surface_get_format(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, surfaces.size(), 0); return surfaces[p_idx].format; } @@ -2058,7 +2051,7 @@ void ArrayMesh::_bind_methods() { ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ArrayMesh::set_blend_shape_mode); ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ArrayMesh::get_blend_shape_mode); - ClassDB::bind_method(D_METHOD("add_surface_from_arrays", "primitive", "arrays", "blend_shapes", "lods", "compress_flags"), &ArrayMesh::add_surface_from_arrays, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("add_surface_from_arrays", "primitive", "arrays", "blend_shapes", "lods", "flags"), &ArrayMesh::add_surface_from_arrays, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(0)); ClassDB::bind_method(D_METHOD("clear_surfaces"), &ArrayMesh::clear_surfaces); ClassDB::bind_method(D_METHOD("surface_update_vertex_region", "surf_idx", "offset", "data"), &ArrayMesh::surface_update_vertex_region); ClassDB::bind_method(D_METHOD("surface_update_attribute_region", "surf_idx", "offset", "data"), &ArrayMesh::surface_update_attribute_region); diff --git a/scene/resources/mesh.h b/scene/resources/mesh.h index f62f060682..1baa466312 100644 --- a/scene/resources/mesh.h +++ b/scene/resources/mesh.h @@ -156,7 +156,7 @@ public: virtual Array surface_get_arrays(int p_surface) const; virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const; virtual Dictionary surface_get_lods(int p_surface) const; - virtual uint32_t surface_get_format(int p_idx) const; + virtual BitField<ArrayFormat> surface_get_format(int p_idx) const; virtual PrimitiveType surface_get_primitive_type(int p_idx) const; virtual void surface_set_material(int p_idx, const Ref<Material> &p_material); virtual Ref<Material> surface_get_material(int p_idx) const; @@ -269,9 +269,9 @@ protected: static void _bind_methods(); public: - void add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes = TypedArray<Array>(), const Dictionary &p_lods = Dictionary(), uint32_t p_flags = 0); + void add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes = TypedArray<Array>(), const Dictionary &p_lods = Dictionary(), BitField<ArrayFormat> p_flags = 0); - void add_surface(uint32_t p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data = Vector<uint8_t>(), const Vector<AABB> &p_bone_aabbs = Vector<AABB>(), const Vector<RS::SurfaceData::LOD> &p_lods = Vector<RS::SurfaceData::LOD>()); + void add_surface(BitField<ArrayFormat> p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data = Vector<uint8_t>(), const Vector<AABB> &p_bone_aabbs = Vector<AABB>(), const Vector<RS::SurfaceData::LOD> &p_lods = Vector<RS::SurfaceData::LOD>()); Array surface_get_arrays(int p_surface) const override; TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override; @@ -298,7 +298,7 @@ public: int surface_get_array_len(int p_idx) const override; int surface_get_array_index_len(int p_idx) const override; - uint32_t surface_get_format(int p_idx) const override; + BitField<ArrayFormat> surface_get_format(int p_idx) const override; PrimitiveType surface_get_primitive_type(int p_idx) const override; virtual void surface_set_material(int p_idx, const Ref<Material> &p_material) override; @@ -330,7 +330,7 @@ public: }; VARIANT_ENUM_CAST(Mesh::ArrayType); -VARIANT_ENUM_CAST(Mesh::ArrayFormat); +VARIANT_BITFIELD_CAST(Mesh::ArrayFormat); VARIANT_ENUM_CAST(Mesh::ArrayCustomFormat); VARIANT_ENUM_CAST(Mesh::PrimitiveType); VARIANT_ENUM_CAST(Mesh::BlendShapeMode); @@ -351,7 +351,7 @@ public: virtual Array surface_get_arrays(int p_surface) const override { return Array(); } virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override { return TypedArray<Array>(); } virtual Dictionary surface_get_lods(int p_surface) const override { return Dictionary(); } - virtual uint32_t surface_get_format(int p_idx) const override { return 0; } + virtual BitField<ArrayFormat> surface_get_format(int p_idx) const override { return 0; } virtual PrimitiveType surface_get_primitive_type(int p_idx) const override { return PRIMITIVE_TRIANGLES; } virtual void surface_set_material(int p_idx, const Ref<Material> &p_material) override {} virtual Ref<Material> surface_get_material(int p_idx) const override { return Ref<Material>(); } diff --git a/scene/resources/mesh_library.cpp b/scene/resources/mesh_library.cpp index d45b8a9295..015eb0fa45 100644 --- a/scene/resources/mesh_library.cpp +++ b/scene/resources/mesh_library.cpp @@ -139,7 +139,6 @@ void MeshLibrary::set_item_name(int p_item, const String &p_name) { ERR_FAIL_COND_MSG(!item_map.has(p_item), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'."); item_map[p_item].name = p_name; emit_changed(); - notify_property_list_changed(); } void MeshLibrary::set_item_mesh(int p_item, const Ref<Mesh> &p_mesh) { @@ -155,7 +154,6 @@ void MeshLibrary::set_item_mesh_transform(int p_item, const Transform3D &p_trans item_map[p_item].mesh_transform = p_transform; notify_change_to_owners(); emit_changed(); - notify_property_list_changed(); } void MeshLibrary::set_item_shapes(int p_item, const Vector<ShapeData> &p_shapes) { @@ -190,7 +188,6 @@ void MeshLibrary::set_item_navigation_layers(int p_item, uint32_t p_navigation_l notify_property_list_changed(); notify_change_to_owners(); emit_changed(); - notify_property_list_changed(); } void MeshLibrary::set_item_preview(int p_item, const Ref<Texture2D> &p_preview) { diff --git a/scene/resources/navigation_mesh.cpp b/scene/resources/navigation_mesh.cpp index 287597de32..7e1b42c80b 100644 --- a/scene/resources/navigation_mesh.cpp +++ b/scene/resources/navigation_mesh.cpp @@ -401,7 +401,7 @@ Ref<ArrayMesh> NavigationMesh::get_debug_mesh() { } debug_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, face_mesh_array); - Ref<StandardMaterial3D> debug_geometry_face_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_face_material(); + Ref<StandardMaterial3D> debug_geometry_face_material = NavigationServer3D::get_singleton()->get_debug_navigation_geometry_face_material(); debug_mesh->surface_set_material(0, debug_geometry_face_material); // if enabled build geometry edge line surface @@ -426,7 +426,7 @@ Ref<ArrayMesh> NavigationMesh::get_debug_mesh() { line_mesh_array.resize(Mesh::ARRAY_MAX); line_mesh_array[Mesh::ARRAY_VERTEX] = line_vertex_array; debug_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, line_mesh_array); - Ref<StandardMaterial3D> debug_geometry_edge_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_edge_material(); + Ref<StandardMaterial3D> debug_geometry_edge_material = NavigationServer3D::get_singleton()->get_debug_navigation_geometry_edge_material(); debug_mesh->surface_set_material(1, debug_geometry_edge_material); } diff --git a/scene/resources/packed_scene.cpp b/scene/resources/packed_scene.cpp index 514e7eb260..c24186a109 100644 --- a/scene/resources/packed_scene.cpp +++ b/scene/resources/packed_scene.cpp @@ -402,8 +402,7 @@ Node *SceneState::instantiate(GenEditState p_edit_state) const { } } - for (uint32_t i = 0; i < deferred_node_paths.size(); i++) { - const DeferredNodePathProperties &dnp = deferred_node_paths[i]; + for (const DeferredNodePathProperties &dnp : deferred_node_paths) { Node *other = dnp.base->get_node_or_null(dnp.path); dnp.base->set(dnp.property, other); } diff --git a/scene/resources/particle_process_material.cpp b/scene/resources/particle_process_material.cpp index a7f48b92fe..7ae154ea1d 100644 --- a/scene/resources/particle_process_material.cpp +++ b/scene/resources/particle_process_material.cpp @@ -1756,8 +1756,8 @@ void ParticleProcessMaterial::_bind_methods() { ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_min", PROPERTY_HINT_RANGE, "0,16,0.01,or_less,or_greater"), "set_param_min", "get_param_min", PARAM_ANIM_SPEED); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_max", PROPERTY_HINT_RANGE, "0,16,0.01,or_less,or_greater"), "set_param_max", "get_param_max", PARAM_ANIM_SPEED); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anim_speed_curve", PROPERTY_HINT_RESOURCE_TYPE, "CurveTexture"), "set_param_texture", "get_param_texture", PARAM_ANIM_SPEED); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_min", PROPERTY_HINT_RANGE, "0,16,0.01,or_less,or_greater"), "set_param_min", "get_param_min", PARAM_ANIM_OFFSET); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_max", PROPERTY_HINT_RANGE, "0,16,0.01,or_less,or_greater"), "set_param_max", "get_param_max", PARAM_ANIM_OFFSET); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_min", PROPERTY_HINT_RANGE, "0,1,0.0001"), "set_param_min", "get_param_min", PARAM_ANIM_OFFSET); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_max", PROPERTY_HINT_RANGE, "0,1,0.0001"), "set_param_max", "get_param_max", PARAM_ANIM_OFFSET); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anim_offset_curve", PROPERTY_HINT_RESOURCE_TYPE, "CurveTexture"), "set_param_texture", "get_param_texture", PARAM_ANIM_OFFSET); ADD_GROUP("Sub Emitter", "sub_emitter_"); diff --git a/scene/resources/polygon_path_finder.cpp b/scene/resources/polygon_path_finder.cpp index 85106883f9..3bbd0a0b5e 100644 --- a/scene/resources/polygon_path_finder.cpp +++ b/scene/resources/polygon_path_finder.cpp @@ -325,7 +325,7 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2 &p_from, const Vector } const Point &np = points[least_cost_point]; - //open the neighbours for search + //open the neighbors for search for (const int &E : np.connections) { Point &p = points.write[E]; @@ -339,7 +339,7 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2 &p_from, const Vector p.distance = distance; } } else { - //add to open neighbours + //add to open neighbors p.prev = least_cost_point; p.distance = distance; diff --git a/scene/resources/primitive_meshes.cpp b/scene/resources/primitive_meshes.cpp index b6e953dd56..86ed0001dd 100644 --- a/scene/resources/primitive_meshes.cpp +++ b/scene/resources/primitive_meshes.cpp @@ -180,7 +180,7 @@ TypedArray<Array> PrimitiveMesh::surface_get_blend_shape_arrays(int p_surface) c return TypedArray<Array>(); //not really supported } -uint32_t PrimitiveMesh::surface_get_format(int p_idx) const { +BitField<Mesh::ArrayFormat> PrimitiveMesh::surface_get_format(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, 1, 0); uint32_t mesh_format = RS::ARRAY_FORMAT_VERTEX | RS::ARRAY_FORMAT_NORMAL | RS::ARRAY_FORMAT_TANGENT | RS::ARRAY_FORMAT_TEX_UV | RS::ARRAY_FORMAT_INDEX; @@ -2901,7 +2901,7 @@ void TextMesh::_create_mesh_array(Array &p_arr) const { TS->shaped_text_set_spacing(text_rid, TextServer::SpacingType(i), font->get_spacing(TextServer::SpacingType(i))); } - Array stt; + TypedArray<Vector3i> stt; if (st_parser == TextServer::STRUCTURED_TEXT_CUSTOM) { GDVIRTUAL_CALL(_structured_text_parser, st_args, txt, stt); } else { diff --git a/scene/resources/primitive_meshes.h b/scene/resources/primitive_meshes.h index c1c51b350b..e62f26b17c 100644 --- a/scene/resources/primitive_meshes.h +++ b/scene/resources/primitive_meshes.h @@ -84,7 +84,7 @@ public: virtual Array surface_get_arrays(int p_surface) const override; virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override; virtual Dictionary surface_get_lods(int p_surface) const override; - virtual uint32_t surface_get_format(int p_idx) const override; + virtual BitField<ArrayFormat> surface_get_format(int p_idx) const override; virtual Mesh::PrimitiveType surface_get_primitive_type(int p_idx) const override; virtual void surface_set_material(int p_idx, const Ref<Material> &p_material) override; virtual Ref<Material> surface_get_material(int p_idx) const override; @@ -622,7 +622,7 @@ protected: virtual void _create_mesh_array(Array &p_arr) const override; public: - GDVIRTUAL2RC(Array, _structured_text_parser, Array, String) + GDVIRTUAL2RC(TypedArray<Vector3i>, _structured_text_parser, Array, String) TextMesh(); ~TextMesh(); diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp index ade8875935..0ba177f882 100644 --- a/scene/resources/resource_format_text.cpp +++ b/scene/resources/resource_format_text.cpp @@ -49,10 +49,6 @@ /// -void ResourceLoaderText::set_local_path(const String &p_local_path) { - res_path = p_local_path; -} - Ref<Resource> ResourceLoaderText::get_resource() { return resource; } @@ -449,10 +445,10 @@ Error ResourceLoaderText::load() { #ifdef TOOLS_ENABLED // Silence a warning that can happen during the initial filesystem scan due to cache being regenerated. if (ResourceLoader::get_resource_uid(path) != uid) { - WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UUID: " + uidt + " - using text path instead: " + path).utf8().get_data()); + WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data()); } #else - WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UUID: " + uidt + " - using text path instead: " + path).utf8().get_data()); + WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data()); #endif } } @@ -601,14 +597,14 @@ Error ResourceLoaderText::load() { resource_current++; + if (progress && resources_total > 0) { + *progress = resource_current / float(resources_total); + } + int_resources[id] = res; //always assign int resources - if (do_assign) { - if (cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE) { - res->set_path(path); - } else { - res->set_path(path, cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE); - res->set_scene_unique_id(id); - } + if (do_assign && cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) { + res->set_path(path, cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE); + res->set_scene_unique_id(id); } Dictionary missing_resource_properties; @@ -663,10 +659,6 @@ Error ResourceLoaderText::load() { if (!missing_resource_properties.is_empty()) { res->set_meta(META_MISSING_RESOURCES, missing_resource_properties); } - - if (progress && resources_total > 0) { - *progress = resource_current / float(resources_total); - } } while (true) { @@ -716,8 +708,6 @@ Error ResourceLoaderText::load() { resource = Ref<Resource>(r); } - resource_current++; - Dictionary missing_resource_properties; while (true) { @@ -770,6 +760,12 @@ Error ResourceLoaderText::load() { } } + resource_current++; + + if (progress && resources_total > 0) { + *progress = resource_current / float(resources_total); + } + if (missing_resource) { missing_resource->set_recording_properties(false); } @@ -779,9 +775,6 @@ Error ResourceLoaderText::load() { } error = OK; - if (progress && resources_total > 0) { - *progress = resource_current / float(resources_total); - } return error; } @@ -930,7 +923,11 @@ Error ResourceLoaderText::rename_dependencies(Ref<FileAccess> p_f, const String if (is_scene) { fw->store_line("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n"); } else { - fw->store_line("[gd_resource type=\"" + res_type + "\" load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n"); + String script_res_text; + if (!script_class.is_empty()) { + script_res_text = "script_class=\"" + script_class + "\" "; + } + fw->store_line("[gd_resource type=\"" + res_type + "\" " + script_res_text + "load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n"); } } @@ -1054,6 +1051,10 @@ void ResourceLoaderText::open(Ref<FileAccess> p_f, bool p_skip_first_tag) { return; } + if (tag.fields.has("script_class")) { + script_class = tag.fields["script_class"]; + } + res_type = tag.fields["type"]; } else { @@ -1500,6 +1501,44 @@ Error ResourceLoaderText::get_classes_used(HashSet<StringName> *r_classes) { return OK; } +String ResourceLoaderText::recognize_script_class(Ref<FileAccess> p_f) { + error = OK; + + lines = 1; + f = p_f; + + stream.f = f; + + ignore_resource_parsing = true; + + VariantParser::Tag tag; + Error err = VariantParser::parse_tag(&stream, lines, error_text, tag); + + if (err) { + _printerr(); + return ""; + } + + if (tag.fields.has("format")) { + int fmt = tag.fields["format"]; + if (fmt > FORMAT_VERSION) { + error_text = "Saved with newer format version"; + _printerr(); + return ""; + } + } + + if (tag.name != "gd_resource") { + return ""; + } + + if (tag.fields.has("script_class")) { + return tag.fields["script_class"]; + } + + return ""; +} + String ResourceLoaderText::recognize(Ref<FileAccess> p_f) { error = OK; @@ -1669,6 +1708,25 @@ String ResourceFormatLoaderText::get_resource_type(const String &p_path) const { return ClassDB::get_compatibility_remapped_class(r); } +String ResourceFormatLoaderText::get_resource_script_class(const String &p_path) const { + String ext = p_path.get_extension().to_lower(); + if (ext != "tres") { + return String(); + } + + // ...for anything else must test... + + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { + return ""; //could not read + } + + ResourceLoaderText loader; + loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path); + loader.res_path = loader.local_path; + return loader.recognize_script_class(f); +} + ResourceUID::ID ResourceFormatLoaderText::get_resource_uid(const String &p_path) const { String ext = p_path.get_extension().to_lower(); @@ -1849,6 +1907,9 @@ void ResourceFormatSaverTextInstance::_find_resources(const Variant &p_variant, List<Variant> keys; d.get_key_list(&keys); for (const Variant &E : keys) { + // Of course keys should also be cached, after all we can't prevent users from using resources as keys, right? + // See also ResourceFormatSaverBinaryInstance::_find_resources (when p_variant is of type Variant::DICTIONARY) + _find_resources(E); Variant v = d[E]; _find_resources(v); } @@ -1909,7 +1970,12 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Reso String title = packed_scene.is_valid() ? "[gd_scene " : "[gd_resource "; if (packed_scene.is_null()) { title += "type=\"" + _resource_get_class(p_resource) + "\" "; + Ref<Script> script = p_resource->get_script(); + if (script.is_valid() && script->get_global_name()) { + title += "script_class=\"" + String(script->get_global_name()) + "\" "; + } } + int load_steps = saved_resources.size() + external_resources.size(); if (load_steps > 1) { @@ -2237,6 +2303,40 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Reso return OK; } +Error ResourceLoaderText::set_uid(Ref<FileAccess> p_f, ResourceUID::ID p_uid) { + open(p_f, true); + ERR_FAIL_COND_V(error != OK, error); + ignore_resource_parsing = true; + + Ref<FileAccess> fw; + + fw = FileAccess::open(local_path + ".uidren", FileAccess::WRITE); + if (is_scene) { + fw->store_string("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]"); + } else { + String script_res_text; + if (!script_class.is_empty()) { + script_res_text = "script_class=\"" + script_class + "\" "; + } + + fw->store_string("[gd_resource type=\"" + res_type + "\" " + script_res_text + "load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]"); + } + + uint8_t c = f->get_8(); + while (!f->eof_reached()) { + fw->store_8(c); + c = f->get_8(); + } + + bool all_ok = fw->get_error() == OK; + + if (!all_ok) { + return ERR_CANT_CREATE; + } + + return OK; +} + Error ResourceFormatSaverText::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) { if (p_path.ends_with(".tscn") && !Ref<PackedScene>(p_resource).is_valid()) { return ERR_FILE_UNRECOGNIZED; @@ -2246,6 +2346,35 @@ Error ResourceFormatSaverText::save(const Ref<Resource> &p_resource, const Strin return saver.save(p_path, p_resource, p_flags); } +Error ResourceFormatSaverText::set_uid(const String &p_path, ResourceUID::ID p_uid) { + String lc = p_path.to_lower(); + if (!lc.ends_with(".tscn") && !lc.ends_with(".tres")) { + return ERR_FILE_UNRECOGNIZED; + } + + String local_path = ProjectSettings::get_singleton()->localize_path(p_path); + Error err = OK; + { + Ref<FileAccess> fo = FileAccess::open(p_path, FileAccess::READ); + if (fo.is_null()) { + ERR_FAIL_V(ERR_CANT_OPEN); + } + + ResourceLoaderText loader; + loader.local_path = local_path; + loader.res_path = loader.local_path; + err = loader.set_uid(fo, p_uid); + } + + if (err == OK) { + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + da->remove(local_path); + da->rename(local_path + ".uidren", local_path); + } + + return err; +} + bool ResourceFormatSaverText::recognize(const Ref<Resource> &p_resource) const { return true; // All resources recognized! } diff --git a/scene/resources/resource_format_text.h b/scene/resources/resource_format_text.h index f96511fb74..25001d8023 100644 --- a/scene/resources/resource_format_text.h +++ b/scene/resources/resource_format_text.h @@ -64,6 +64,7 @@ class ResourceLoaderText { int resources_total = 0; int resource_current = 0; String resource_type; + String script_class; VariantParser::Tag next_tag; @@ -106,6 +107,7 @@ class ResourceLoaderText { VariantParser::ResourceParser rp; friend class ResourceFormatLoaderText; + friend class ResourceFormatSaverText; Error error = OK; @@ -114,15 +116,16 @@ class ResourceLoaderText { Ref<PackedScene> _parse_node_tag(VariantParser::ResourceParser &parser); public: - void set_local_path(const String &p_local_path); Ref<Resource> get_resource(); Error load(); + Error set_uid(Ref<FileAccess> p_f, ResourceUID::ID p_uid); int get_stage() const; int get_stage_count() const; void set_translation_remapped(bool p_remapped); void open(Ref<FileAccess> p_f, bool p_skip_first_tag = false); String recognize(Ref<FileAccess> p_f); + String recognize_script_class(Ref<FileAccess> p_f); ResourceUID::ID get_uid(Ref<FileAccess> p_f); void get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types); Error rename_dependencies(Ref<FileAccess> p_f, const String &p_path, const HashMap<String, String> &p_map); @@ -142,6 +145,7 @@ public: virtual void get_classes_used(const String &p_path, HashSet<StringName> *r_classes); virtual String get_resource_type(const String &p_path) const; + virtual String get_resource_script_class(const String &p_path) const; virtual ResourceUID::ID get_resource_uid(const String &p_path) const; virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); virtual Error rename_dependencies(const String &p_path, const HashMap<String, String> &p_map); @@ -195,6 +199,7 @@ class ResourceFormatSaverText : public ResourceFormatSaver { public: static ResourceFormatSaverText *singleton; virtual Error save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags = 0); + virtual Error set_uid(const String &p_path, ResourceUID::ID p_uid); virtual bool recognize(const Ref<Resource> &p_resource) const; virtual void get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const; diff --git a/scene/resources/shader.cpp b/scene/resources/shader.cpp index 9bb2db17ab..b3952e745f 100644 --- a/scene/resources/shader.cpp +++ b/scene/resources/shader.cpp @@ -43,7 +43,6 @@ Shader::Mode Shader::get_mode() const { void Shader::_dependency_changed() { RenderingServer::get_singleton()->shader_set_code(shader, RenderingServer::get_singleton()->shader_get_code(shader)); - params_cache_dirty = true; emit_changed(); } @@ -93,7 +92,6 @@ void Shader::set_code(const String &p_code) { } RenderingServer::get_singleton()->shader_set_code(shader, pp_code); - params_cache_dirty = true; emit_changed(); } @@ -108,8 +106,6 @@ void Shader::get_shader_uniform_list(List<PropertyInfo> *p_params, bool p_get_gr List<PropertyInfo> local; RenderingServer::get_singleton()->get_shader_parameter_list(shader, &local); - params_cache.clear(); - params_cache_dirty = false; for (PropertyInfo &pi : local) { bool is_group = pi.usage == PROPERTY_USAGE_GROUP || pi.usage == PROPERTY_USAGE_SUBGROUP; @@ -120,7 +116,6 @@ void Shader::get_shader_uniform_list(List<PropertyInfo> *p_params, bool p_get_gr if (default_textures.has(pi.name)) { //do not show default textures continue; } - params_cache[pi.name] = pi.name; } if (p_params) { //small little hack @@ -176,11 +171,17 @@ bool Shader::is_text_shader() const { return true; } -bool Shader::has_parameter(const StringName &p_name) const { - return params_cache.has(p_name); +void Shader::_update_shader() const { } -void Shader::_update_shader() const { +Array Shader::_get_shader_uniform_list(bool p_get_groups) { + List<PropertyInfo> uniform_list; + get_shader_uniform_list(&uniform_list, p_get_groups); + Array ret; + for (const PropertyInfo &pi : uniform_list) { + ret.push_back(pi.operator Dictionary()); + } + return ret; } void Shader::_bind_methods() { @@ -192,7 +193,7 @@ void Shader::_bind_methods() { ClassDB::bind_method(D_METHOD("set_default_texture_parameter", "name", "texture", "index"), &Shader::set_default_texture_parameter, DEFVAL(0)); ClassDB::bind_method(D_METHOD("get_default_texture_parameter", "name", "index"), &Shader::get_default_texture_parameter, DEFVAL(0)); - ClassDB::bind_method(D_METHOD("has_parameter", "name"), &Shader::has_parameter); + ClassDB::bind_method(D_METHOD("get_shader_uniform_list", "get_groups"), &Shader::_get_shader_uniform_list, DEFVAL(false)); ADD_PROPERTY(PropertyInfo(Variant::STRING, "code", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_code", "get_code"); diff --git a/scene/resources/shader.h b/scene/resources/shader.h index e579c2fca1..75c490e912 100644 --- a/scene/resources/shader.h +++ b/scene/resources/shader.h @@ -57,15 +57,12 @@ private: HashSet<Ref<ShaderInclude>> include_dependencies; String code; - // hack the name of performance - // shaders keep a list of ShaderMaterial -> RenderingServer name translations, to make - // conversion fast and save memory. - mutable bool params_cache_dirty = true; - mutable HashMap<StringName, StringName> params_cache; //map a shader param to a material param.. HashMap<StringName, HashMap<int, Ref<Texture2D>>> default_textures; void _dependency_changed(); virtual void _update_shader() const; //used for visual shader + Array _get_shader_uniform_list(bool p_get_groups = false); + protected: static void _bind_methods(); @@ -79,7 +76,6 @@ public: String get_code() const; void get_shader_uniform_list(List<PropertyInfo> *p_params, bool p_get_groups = false) const; - bool has_parameter(const StringName &p_name) const; void set_default_texture_parameter(const StringName &p_name, const Ref<Texture2D> &p_texture, int p_index = 0); Ref<Texture2D> get_default_texture_parameter(const StringName &p_name, int p_index = 0) const; @@ -87,47 +83,6 @@ public: virtual bool is_text_shader() const; - // Finds the shader parameter name for the given property name, which should start with "shader_parameter/". - _FORCE_INLINE_ StringName remap_parameter(const StringName &p_property) const { - if (params_cache_dirty) { - get_shader_uniform_list(nullptr); - } - - String n = p_property; - - // Backwards compatibility with old shader parameter names. - // Note: The if statements are important to make sure we are only replacing text exactly at index 0. - if (n.find("param/") == 0) { - n = n.replace_first("param/", "shader_parameter/"); - } - if (n.find("shader_param/") == 0) { - n = n.replace_first("shader_param/", "shader_parameter/"); - } - if (n.find("shader_uniform/") == 0) { - n = n.replace_first("shader_uniform/", "shader_parameter/"); - } - - { - // Additional backwards compatibility for projects between #62972 and #64092 (about a month of v4.0 development). - // These projects did not have any prefix for shader uniforms due to a bug. - // This code should be removed during beta or rc of 4.0. - const HashMap<StringName, StringName>::Iterator E = params_cache.find(n); - if (E) { - return E->value; - } - } - - if (n.begins_with("shader_parameter/")) { - n = n.replace_first("shader_parameter/", ""); - const HashMap<StringName, StringName>::Iterator E = params_cache.find(n); - if (E) { - return E->value; - } - } - - return StringName(); - } - virtual RID get_rid() const override; Shader(); diff --git a/scene/resources/skeleton_modification_3d.cpp b/scene/resources/skeleton_modification_3d.cpp deleted file mode 100644 index 92fb4bfd78..0000000000 --- a/scene/resources/skeleton_modification_3d.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#include "skeleton_modification_3d.h" -#include "scene/3d/skeleton_3d.h" - -void SkeletonModification3D::_execute(real_t p_delta) { - GDVIRTUAL_CALL(_execute, p_delta); - - if (!enabled) { - return; - } -} - -void SkeletonModification3D::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - if (stack) { - is_setup = true; - } else { - WARN_PRINT("Could not setup modification with name " + this->get_name()); - } - - GDVIRTUAL_CALL(_setup_modification, Ref<SkeletonModificationStack3D>(p_stack)); -} - -void SkeletonModification3D::set_enabled(bool p_enabled) { - enabled = p_enabled; -} - -bool SkeletonModification3D::get_enabled() { - return enabled; -} - -// Helper function. Needed for CCDIK. -real_t SkeletonModification3D::clamp_angle(real_t p_angle, real_t p_min_bound, real_t p_max_bound, bool p_invert) { - // Map to the 0 to 360 range (in radians though) instead of the -180 to 180 range. - if (p_angle < 0) { - p_angle = Math_TAU + p_angle; - } - - // Make min and max in the range of 0 to 360 (in radians), and make sure they are in the right order - if (p_min_bound < 0) { - p_min_bound = Math_TAU + p_min_bound; - } - if (p_max_bound < 0) { - p_max_bound = Math_TAU + p_max_bound; - } - if (p_min_bound > p_max_bound) { - SWAP(p_min_bound, p_max_bound); - } - - bool is_beyond_bounds = (p_angle < p_min_bound || p_angle > p_max_bound); - bool is_within_bounds = (p_angle > p_min_bound && p_angle < p_max_bound); - - // Note: May not be the most optimal way to clamp, but it always constraints to the nearest angle. - if ((!p_invert && is_beyond_bounds) || (p_invert && is_within_bounds)) { - Vector2 min_bound_vec = Vector2(Math::cos(p_min_bound), Math::sin(p_min_bound)); - Vector2 max_bound_vec = Vector2(Math::cos(p_max_bound), Math::sin(p_max_bound)); - Vector2 angle_vec = Vector2(Math::cos(p_angle), Math::sin(p_angle)); - - if (angle_vec.distance_squared_to(min_bound_vec) <= angle_vec.distance_squared_to(max_bound_vec)) { - p_angle = p_min_bound; - } else { - p_angle = p_max_bound; - } - } - - return p_angle; -} - -bool SkeletonModification3D::_print_execution_error(bool p_condition, String p_message) { - // If the modification is not setup, don't bother printing the error - if (!is_setup) { - return p_condition; - } - - if (p_condition && !execution_error_found) { - ERR_PRINT(p_message); - execution_error_found = true; - } - return p_condition; -} - -Ref<SkeletonModificationStack3D> SkeletonModification3D::get_modification_stack() { - return stack; -} - -void SkeletonModification3D::set_is_setup(bool p_is_setup) { - is_setup = p_is_setup; -} - -bool SkeletonModification3D::get_is_setup() const { - return is_setup; -} - -void SkeletonModification3D::set_execution_mode(int p_mode) { - execution_mode = p_mode; -} - -int SkeletonModification3D::get_execution_mode() const { - return execution_mode; -} - -void SkeletonModification3D::_bind_methods() { - GDVIRTUAL_BIND(_execute, "delta"); - GDVIRTUAL_BIND(_setup_modification, "modification_stack") - - ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &SkeletonModification3D::set_enabled); - ClassDB::bind_method(D_METHOD("get_enabled"), &SkeletonModification3D::get_enabled); - ClassDB::bind_method(D_METHOD("get_modification_stack"), &SkeletonModification3D::get_modification_stack); - ClassDB::bind_method(D_METHOD("set_is_setup", "is_setup"), &SkeletonModification3D::set_is_setup); - ClassDB::bind_method(D_METHOD("get_is_setup"), &SkeletonModification3D::get_is_setup); - ClassDB::bind_method(D_METHOD("set_execution_mode", "execution_mode"), &SkeletonModification3D::set_execution_mode); - ClassDB::bind_method(D_METHOD("get_execution_mode"), &SkeletonModification3D::get_execution_mode); - ClassDB::bind_method(D_METHOD("clamp_angle", "angle", "min", "max", "invert"), &SkeletonModification3D::clamp_angle); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "get_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "execution_mode", PROPERTY_HINT_ENUM, "process,physics_process"), "set_execution_mode", "get_execution_mode"); -} - -SkeletonModification3D::SkeletonModification3D() { - stack = nullptr; - is_setup = false; -} diff --git a/scene/resources/skeleton_modification_3d.h b/scene/resources/skeleton_modification_3d.h deleted file mode 100644 index 367adbd977..0000000000 --- a/scene/resources/skeleton_modification_3d.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#ifndef SKELETON_MODIFICATION_3D_H -#define SKELETON_MODIFICATION_3D_H - -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_stack_3d.h" - -class SkeletonModificationStack3D; - -class SkeletonModification3D : public Resource { - GDCLASS(SkeletonModification3D, Resource); - friend class Skeleton3D; - friend class SkeletonModificationStack3D; - -protected: - static void _bind_methods(); - - SkeletonModificationStack3D *stack = nullptr; - int execution_mode = 0; // 0 = process - - bool enabled = true; - bool is_setup = false; - bool execution_error_found = false; - - bool _print_execution_error(bool p_condition, String p_message); - - GDVIRTUAL1(_execute, double) - GDVIRTUAL1(_setup_modification, Ref<SkeletonModificationStack3D>) - -public: - virtual void _execute(real_t p_delta); - virtual void _setup_modification(SkeletonModificationStack3D *p_stack); - - real_t clamp_angle(real_t p_angle, real_t p_min_bound, real_t p_max_bound, bool p_invert); - - void set_enabled(bool p_enabled); - bool get_enabled(); - - void set_execution_mode(int p_mode); - int get_execution_mode() const; - - Ref<SkeletonModificationStack3D> get_modification_stack(); - - void set_is_setup(bool p_setup); - bool get_is_setup() const; - - SkeletonModification3D(); -}; - -#endif // SKELETON_MODIFICATION_3D_H diff --git a/scene/resources/skeleton_modification_3d_ccdik.cpp b/scene/resources/skeleton_modification_3d_ccdik.cpp deleted file mode 100644 index b5c930f970..0000000000 --- a/scene/resources/skeleton_modification_3d_ccdik.cpp +++ /dev/null @@ -1,474 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_ccdik.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#include "scene/resources/skeleton_modification_3d_ccdik.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DCCDIK::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path.begins_with("joint_data/")) { - int ccdik_data_size = ccdik_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, ccdik_data_size, false); - - if (what == "bone_name") { - set_ccdik_joint_bone_name(which, p_value); - } else if (what == "bone_index") { - set_ccdik_joint_bone_index(which, p_value); - } else if (what == "ccdik_axis") { - set_ccdik_joint_ccdik_axis(which, p_value); - } else if (what == "enable_joint_constraint") { - set_ccdik_joint_enable_constraint(which, p_value); - } else if (what == "joint_constraint_angle_min") { - set_ccdik_joint_constraint_angle_min(which, Math::deg_to_rad(real_t(p_value))); - } else if (what == "joint_constraint_angle_max") { - set_ccdik_joint_constraint_angle_max(which, Math::deg_to_rad(real_t(p_value))); - } else if (what == "joint_constraint_angles_invert") { - set_ccdik_joint_constraint_invert(which, p_value); - } - return true; - } - return true; -} - -bool SkeletonModification3DCCDIK::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path.begins_with("joint_data/")) { - const int ccdik_data_size = ccdik_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, ccdik_data_size, false); - - if (what == "bone_name") { - r_ret = get_ccdik_joint_bone_name(which); - } else if (what == "bone_index") { - r_ret = get_ccdik_joint_bone_index(which); - } else if (what == "ccdik_axis") { - r_ret = get_ccdik_joint_ccdik_axis(which); - } else if (what == "enable_joint_constraint") { - r_ret = get_ccdik_joint_enable_constraint(which); - } else if (what == "joint_constraint_angle_min") { - r_ret = Math::rad_to_deg(get_ccdik_joint_constraint_angle_min(which)); - } else if (what == "joint_constraint_angle_max") { - r_ret = Math::rad_to_deg(get_ccdik_joint_constraint_angle_max(which)); - } else if (what == "joint_constraint_angles_invert") { - r_ret = get_ccdik_joint_constraint_invert(which); - } - return true; - } - return true; -} - -void SkeletonModification3DCCDIK::_get_property_list(List<PropertyInfo> *p_list) const { - for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) { - String base_string = "joint_data/" + itos(i) + "/"; - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, base_string + "bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - - p_list->push_back(PropertyInfo(Variant::INT, base_string + "ccdik_axis", - PROPERTY_HINT_ENUM, "X Axis,Y Axis,Z Axis", PROPERTY_USAGE_DEFAULT)); - - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "enable_joint_constraint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (ccdik_data_chain[i].enable_constraint) { - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "joint_constraint_angle_min", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "joint_constraint_angle_max", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "joint_constraint_angles_invert", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } - } -} - -void SkeletonModification3DCCDIK::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - if (!enabled) { - return; - } - - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update"); - update_target_cache(); - return; - } - if (tip_node_cache.is_null()) { - _print_execution_error(true, "Tip cache is out of date. Attempting to update"); - update_tip_cache(); - return; - } - - // Reset the local bone overrides for CCDIK affected nodes - for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) { - stack->skeleton->set_bone_local_pose_override(ccdik_data_chain[i].bone_idx, - stack->skeleton->get_bone_local_pose_override(ccdik_data_chain[i].bone_idx), - 0.0, false); - } - - Node3D *node_target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - Node3D *node_tip = Object::cast_to<Node3D>(ObjectDB::get_instance(tip_node_cache)); - - if (_print_execution_error(!node_target || !node_target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) { - return; - } - if (_print_execution_error(!node_tip || !node_tip->is_inside_tree(), "Tip node is not in the scene tree. Cannot execute modification!")) { - return; - } - - if (use_high_quality_solve) { - for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) { - for (uint32_t j = i; j < ccdik_data_chain.size(); j++) { - _execute_ccdik_joint(j, node_target, node_tip); - } - } - } else { - for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) { - _execute_ccdik_joint(i, node_target, node_tip); - } - } - - execution_error_found = false; -} - -void SkeletonModification3DCCDIK::_execute_ccdik_joint(int p_joint_idx, Node3D *p_target, Node3D *p_tip) { - CCDIK_Joint_Data ccdik_data = ccdik_data_chain[p_joint_idx]; - - if (_print_execution_error(ccdik_data.bone_idx < 0 || ccdik_data.bone_idx > stack->skeleton->get_bone_count(), - "CCDIK joint: bone index for joint" + itos(p_joint_idx) + " not found. Cannot execute modification!")) { - return; - } - - Transform3D bone_trans = stack->skeleton->global_pose_to_local_pose(ccdik_data.bone_idx, stack->skeleton->get_bone_global_pose(ccdik_data.bone_idx)); - Transform3D tip_trans = stack->skeleton->global_pose_to_local_pose(ccdik_data.bone_idx, stack->skeleton->world_transform_to_global_pose(p_tip->get_global_transform())); - Transform3D target_trans = stack->skeleton->global_pose_to_local_pose(ccdik_data.bone_idx, stack->skeleton->world_transform_to_global_pose(p_target->get_global_transform())); - - if (tip_trans.origin.distance_to(target_trans.origin) <= 0.01) { - return; - } - - // Inspired (and very loosely based on) by the CCDIK algorithm made by Zalo on GitHub (https://github.com/zalo/MathUtilities) - // Convert the 3D position to a 2D position so we can use Atan2 (via the angle function) - // to know how much rotation we need on the given axis to place the tip at the target. - Vector2 tip_pos_2d; - Vector2 target_pos_2d; - if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_X) { - tip_pos_2d = Vector2(tip_trans.origin.y, tip_trans.origin.z); - target_pos_2d = Vector2(target_trans.origin.y, target_trans.origin.z); - bone_trans.basis.rotate_local(Vector3(1, 0, 0), target_pos_2d.angle() - tip_pos_2d.angle()); - } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Y) { - tip_pos_2d = Vector2(tip_trans.origin.z, tip_trans.origin.x); - target_pos_2d = Vector2(target_trans.origin.z, target_trans.origin.x); - bone_trans.basis.rotate_local(Vector3(0, 1, 0), target_pos_2d.angle() - tip_pos_2d.angle()); - } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Z) { - tip_pos_2d = Vector2(tip_trans.origin.x, tip_trans.origin.y); - target_pos_2d = Vector2(target_trans.origin.x, target_trans.origin.y); - bone_trans.basis.rotate_local(Vector3(0, 0, 1), target_pos_2d.angle() - tip_pos_2d.angle()); - } else { - // Should never happen, but... - ERR_FAIL_MSG("CCDIK joint: Unknown axis vector passed for joint" + itos(p_joint_idx) + ". Cannot execute modification!"); - } - - if (ccdik_data.enable_constraint) { - Vector3 rotation_axis; - real_t rotation_angle; - bone_trans.basis.get_axis_angle(rotation_axis, rotation_angle); - - // Note: When the axis has a negative direction, the angle is OVER 180 degrees and therefore we need to account for this - // when constraining. - if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_X) { - if (rotation_axis.x < 0) { - rotation_angle += Math_PI; - rotation_axis = Vector3(1, 0, 0); - } - } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Y) { - if (rotation_axis.y < 0) { - rotation_angle += Math_PI; - rotation_axis = Vector3(0, 1, 0); - } - } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Z) { - if (rotation_axis.z < 0) { - rotation_angle += Math_PI; - rotation_axis = Vector3(0, 0, 1); - } - } else { - // Should never happen, but... - ERR_FAIL_MSG("CCDIK joint: Unknown axis vector passed for joint" + itos(p_joint_idx) + ". Cannot execute modification!"); - } - rotation_angle = clamp_angle(rotation_angle, ccdik_data.constraint_angle_min, ccdik_data.constraint_angle_max, ccdik_data.constraint_angles_invert); - - bone_trans.basis.set_axis_angle(rotation_axis, rotation_angle); - } - - stack->skeleton->set_bone_local_pose_override(ccdik_data.bone_idx, bone_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(ccdik_data.bone_idx); -} - -void SkeletonModification3DCCDIK::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - if (stack != nullptr) { - is_setup = true; - execution_error_found = false; - update_target_cache(); - update_tip_cache(); - } -} - -void SkeletonModification3DCCDIK::update_target_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: node is not in scene tree!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DCCDIK::update_tip_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update tip cache: modification is not properly setup!"); - return; - } - - tip_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(tip_node)) { - Node *node = stack->skeleton->get_node(tip_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update tip cache: node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update tip cache: node is not in scene tree!"); - tip_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DCCDIK::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_target_cache(); -} - -NodePath SkeletonModification3DCCDIK::get_target_node() const { - return target_node; -} - -void SkeletonModification3DCCDIK::set_tip_node(const NodePath &p_tip_node) { - tip_node = p_tip_node; - update_tip_cache(); -} - -NodePath SkeletonModification3DCCDIK::get_tip_node() const { - return tip_node; -} - -void SkeletonModification3DCCDIK::set_use_high_quality_solve(bool p_high_quality) { - use_high_quality_solve = p_high_quality; -} - -bool SkeletonModification3DCCDIK::get_use_high_quality_solve() const { - return use_high_quality_solve; -} - -// CCDIK joint data functions -String SkeletonModification3DCCDIK::get_ccdik_joint_bone_name(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, String()); - return ccdik_data_chain[p_joint_idx].bone_name; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_bone_name(int p_joint_idx, String p_bone_name) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].bone_name = p_bone_name; - - if (stack) { - if (stack->skeleton) { - ccdik_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(p_bone_name); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DCCDIK::get_ccdik_joint_bone_index(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return ccdik_data_chain[p_joint_idx].bone_idx; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_bone_index(int p_joint_idx, int p_bone_idx) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!"); - ccdik_data_chain[p_joint_idx].bone_idx = p_bone_idx; - - if (stack) { - if (stack->skeleton) { - ccdik_data_chain[p_joint_idx].bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DCCDIK::get_ccdik_joint_ccdik_axis(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return ccdik_data_chain[p_joint_idx].ccdik_axis; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_ccdik_axis(int p_joint_idx, int p_axis) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_axis < 0, "CCDIK axis is out of range: The axis mode is too low!"); - ccdik_data_chain[p_joint_idx].ccdik_axis = p_axis; - notify_property_list_changed(); -} - -bool SkeletonModification3DCCDIK::get_ccdik_joint_enable_constraint(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return ccdik_data_chain[p_joint_idx].enable_constraint; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_enable_constraint(int p_joint_idx, bool p_enable) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].enable_constraint = p_enable; - notify_property_list_changed(); -} - -real_t SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_min(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return ccdik_data_chain[p_joint_idx].constraint_angle_min; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_min(int p_joint_idx, real_t p_angle_min) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].constraint_angle_min = p_angle_min; -} - -real_t SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_max(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return ccdik_data_chain[p_joint_idx].constraint_angle_max; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_max(int p_joint_idx, real_t p_angle_max) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].constraint_angle_max = p_angle_max; -} - -bool SkeletonModification3DCCDIK::get_ccdik_joint_constraint_invert(int p_joint_idx) const { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return ccdik_data_chain[p_joint_idx].constraint_angles_invert; -} - -void SkeletonModification3DCCDIK::set_ccdik_joint_constraint_invert(int p_joint_idx, bool p_invert) { - const int bone_chain_size = ccdik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ccdik_data_chain[p_joint_idx].constraint_angles_invert = p_invert; -} - -int SkeletonModification3DCCDIK::get_ccdik_data_chain_length() { - return ccdik_data_chain.size(); -} -void SkeletonModification3DCCDIK::set_ccdik_data_chain_length(int p_length) { - ERR_FAIL_COND(p_length < 0); - ccdik_data_chain.resize(p_length); - execution_error_found = false; - notify_property_list_changed(); -} - -void SkeletonModification3DCCDIK::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DCCDIK::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DCCDIK::get_target_node); - - ClassDB::bind_method(D_METHOD("set_tip_node", "tip_nodepath"), &SkeletonModification3DCCDIK::set_tip_node); - ClassDB::bind_method(D_METHOD("get_tip_node"), &SkeletonModification3DCCDIK::get_tip_node); - - ClassDB::bind_method(D_METHOD("set_use_high_quality_solve", "high_quality_solve"), &SkeletonModification3DCCDIK::set_use_high_quality_solve); - ClassDB::bind_method(D_METHOD("get_use_high_quality_solve"), &SkeletonModification3DCCDIK::get_use_high_quality_solve); - - // CCDIK joint data functions - ClassDB::bind_method(D_METHOD("get_ccdik_joint_bone_name", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_bone_name); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_bone_name", "joint_idx", "bone_name"), &SkeletonModification3DCCDIK::set_ccdik_joint_bone_name); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_bone_index", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_bone_index); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_bone_index", "joint_idx", "bone_index"), &SkeletonModification3DCCDIK::set_ccdik_joint_bone_index); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_ccdik_axis", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_ccdik_axis); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_ccdik_axis", "joint_idx", "axis"), &SkeletonModification3DCCDIK::set_ccdik_joint_ccdik_axis); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_enable_joint_constraint", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_enable_constraint); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_enable_joint_constraint", "joint_idx", "enable"), &SkeletonModification3DCCDIK::set_ccdik_joint_enable_constraint); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_angle_min", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_min); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_angle_min", "joint_idx", "min_angle"), &SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_min); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_angle_max", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_max); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_angle_max", "joint_idx", "max_angle"), &SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_max); - ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_invert", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_constraint_invert); - ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_invert", "joint_idx", "invert"), &SkeletonModification3DCCDIK::set_ccdik_joint_constraint_invert); - - ClassDB::bind_method(D_METHOD("set_ccdik_data_chain_length", "length"), &SkeletonModification3DCCDIK::set_ccdik_data_chain_length); - ClassDB::bind_method(D_METHOD("get_ccdik_data_chain_length"), &SkeletonModification3DCCDIK::get_ccdik_data_chain_length); - - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "tip_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_tip_node", "get_tip_node"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "high_quality_solve", PROPERTY_HINT_NONE, ""), "set_use_high_quality_solve", "get_use_high_quality_solve"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "ccdik_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_ccdik_data_chain_length", "get_ccdik_data_chain_length"); -} - -SkeletonModification3DCCDIK::SkeletonModification3DCCDIK() { - stack = nullptr; - is_setup = false; - enabled = true; -} - -SkeletonModification3DCCDIK::~SkeletonModification3DCCDIK() { -} diff --git a/scene/resources/skeleton_modification_3d_ccdik.h b/scene/resources/skeleton_modification_3d_ccdik.h deleted file mode 100644 index 30c29bb3aa..0000000000 --- a/scene/resources/skeleton_modification_3d_ccdik.h +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_ccdik.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#ifndef SKELETON_MODIFICATION_3D_CCDIK_H -#define SKELETON_MODIFICATION_3D_CCDIK_H - -#include "core/templates/local_vector.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DCCDIK : public SkeletonModification3D { - GDCLASS(SkeletonModification3DCCDIK, SkeletonModification3D); - -private: - enum CCDIK_Axes { - AXIS_X, - AXIS_Y, - AXIS_Z - }; - - struct CCDIK_Joint_Data { - String bone_name = ""; - int bone_idx = -1; - int ccdik_axis = 0; - - bool enable_constraint = false; - real_t constraint_angle_min = 0; - real_t constraint_angle_max = (2.0 * Math_PI); - bool constraint_angles_invert = false; - }; - - LocalVector<CCDIK_Joint_Data> ccdik_data_chain; - NodePath target_node; - ObjectID target_node_cache; - - NodePath tip_node; - ObjectID tip_node_cache; - - bool use_high_quality_solve = true; - - void update_target_cache(); - void update_tip_cache(); - - void _execute_ccdik_joint(int p_joint_idx, Node3D *p_target, Node3D *p_tip); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - void set_tip_node(const NodePath &p_tip_node); - NodePath get_tip_node() const; - - void set_use_high_quality_solve(bool p_solve); - bool get_use_high_quality_solve() const; - - String get_ccdik_joint_bone_name(int p_joint_idx) const; - void set_ccdik_joint_bone_name(int p_joint_idx, String p_bone_name); - int get_ccdik_joint_bone_index(int p_joint_idx) const; - void set_ccdik_joint_bone_index(int p_joint_idx, int p_bone_idx); - int get_ccdik_joint_ccdik_axis(int p_joint_idx) const; - void set_ccdik_joint_ccdik_axis(int p_joint_idx, int p_axis); - bool get_ccdik_joint_enable_constraint(int p_joint_idx) const; - void set_ccdik_joint_enable_constraint(int p_joint_idx, bool p_enable); - real_t get_ccdik_joint_constraint_angle_min(int p_joint_idx) const; - void set_ccdik_joint_constraint_angle_min(int p_joint_idx, real_t p_angle_min); - real_t get_ccdik_joint_constraint_angle_max(int p_joint_idx) const; - void set_ccdik_joint_constraint_angle_max(int p_joint_idx, real_t p_angle_max); - bool get_ccdik_joint_constraint_invert(int p_joint_idx) const; - void set_ccdik_joint_constraint_invert(int p_joint_idx, bool p_invert); - - int get_ccdik_data_chain_length(); - void set_ccdik_data_chain_length(int p_new_length); - - SkeletonModification3DCCDIK(); - ~SkeletonModification3DCCDIK(); -}; - -#endif // SKELETON_MODIFICATION_3D_CCDIK_H diff --git a/scene/resources/skeleton_modification_3d_fabrik.cpp b/scene/resources/skeleton_modification_3d_fabrik.cpp deleted file mode 100644 index 9fb7ade155..0000000000 --- a/scene/resources/skeleton_modification_3d_fabrik.cpp +++ /dev/null @@ -1,628 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_fabrik.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#include "scene/resources/skeleton_modification_3d_fabrik.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DFABRIK::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path.begins_with("joint_data/")) { - int fabrik_data_size = fabrik_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, fabrik_data_size, false); - - if (what == "bone_name") { - set_fabrik_joint_bone_name(which, p_value); - } else if (what == "bone_index") { - set_fabrik_joint_bone_index(which, p_value); - } else if (what == "length") { - set_fabrik_joint_length(which, p_value); - } else if (what == "magnet_position") { - set_fabrik_joint_magnet(which, p_value); - } else if (what == "auto_calculate_length") { - set_fabrik_joint_auto_calculate_length(which, p_value); - } else if (what == "use_tip_node") { - set_fabrik_joint_use_tip_node(which, p_value); - } else if (what == "tip_node") { - set_fabrik_joint_tip_node(which, p_value); - } else if (what == "use_target_basis") { - set_fabrik_joint_use_target_basis(which, p_value); - } else if (what == "roll") { - set_fabrik_joint_roll(which, Math::deg_to_rad(real_t(p_value))); - } - return true; - } - return true; -} - -bool SkeletonModification3DFABRIK::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path.begins_with("joint_data/")) { - const int fabrik_data_size = fabrik_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, fabrik_data_size, false); - - if (what == "bone_name") { - r_ret = get_fabrik_joint_bone_name(which); - } else if (what == "bone_index") { - r_ret = get_fabrik_joint_bone_index(which); - } else if (what == "length") { - r_ret = get_fabrik_joint_length(which); - } else if (what == "magnet_position") { - r_ret = get_fabrik_joint_magnet(which); - } else if (what == "auto_calculate_length") { - r_ret = get_fabrik_joint_auto_calculate_length(which); - } else if (what == "use_tip_node") { - r_ret = get_fabrik_joint_use_tip_node(which); - } else if (what == "tip_node") { - r_ret = get_fabrik_joint_tip_node(which); - } else if (what == "use_target_basis") { - r_ret = get_fabrik_joint_use_target_basis(which); - } else if (what == "roll") { - r_ret = Math::rad_to_deg(get_fabrik_joint_roll(which)); - } - return true; - } - return true; -} - -void SkeletonModification3DFABRIK::_get_property_list(List<PropertyInfo> *p_list) const { - for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) { - String base_string = "joint_data/" + itos(i) + "/"; - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, base_string + "bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "roll", PROPERTY_HINT_RANGE, "-360,360,0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "auto_calculate_length", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - - if (!fabrik_data_chain[i].auto_calculate_length) { - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "length", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } else { - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_tip_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (fabrik_data_chain[i].use_tip_node) { - p_list->push_back(PropertyInfo(Variant::NODE_PATH, base_string + "tip_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D", PROPERTY_USAGE_DEFAULT)); - } - } - - // Cannot apply magnet to the origin of the chain, as it will not do anything. - if (i > 0) { - p_list->push_back(PropertyInfo(Variant::VECTOR3, base_string + "magnet_position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } - // Only give the override basis option on the last bone in the chain, so only include it for the last bone. - if (i == fabrik_data_chain.size() - 1) { - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_target_basis", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } - } -} - -void SkeletonModification3DFABRIK::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - if (!enabled) { - return; - } - - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update..."); - update_target_cache(); - return; - } - - if (_print_execution_error(fabrik_data_chain.size() <= 1, "FABRIK requires at least two joints to operate. Cannot execute modification!")) { - return; - } - - Node3D *node_target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - if (_print_execution_error(!node_target || !node_target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) { - return; - } - - // Make sure the transform cache is the correct size - if (fabrik_transforms.size() != fabrik_data_chain.size()) { - fabrik_transforms.resize(fabrik_data_chain.size()); - } - - // Verify that all joints have a valid bone ID, and that all bone lengths are zero or more - // Also, while we are here, apply magnet positions. - for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) { - if (_print_execution_error(fabrik_data_chain[i].bone_idx < 0, "FABRIK Joint " + itos(i) + " has an invalid bone ID. Cannot execute!")) { - return; - } - - if (fabrik_data_chain[i].length < 0 && fabrik_data_chain[i].auto_calculate_length) { - fabrik_joint_auto_calculate_length(i); - } - if (_print_execution_error(fabrik_data_chain[i].length < 0, "FABRIK Joint " + itos(i) + " has an invalid joint length. Cannot execute!")) { - return; - } - fabrik_transforms[i] = stack->skeleton->get_bone_global_pose(fabrik_data_chain[i].bone_idx); - - // Apply magnet positions: - if (stack->skeleton->get_bone_parent(fabrik_data_chain[i].bone_idx) >= 0) { - int parent_bone_idx = stack->skeleton->get_bone_parent(fabrik_data_chain[i].bone_idx); - Transform3D conversion_transform = (stack->skeleton->get_bone_global_pose(parent_bone_idx)); - fabrik_transforms[i].origin += conversion_transform.basis.xform_inv(fabrik_data_chain[i].magnet_position); - } else { - fabrik_transforms[i].origin += fabrik_data_chain[i].magnet_position; - } - } - Transform3D origin_global_pose_trans = stack->skeleton->get_bone_global_pose_no_override(fabrik_data_chain[0].bone_idx); - - target_global_pose = stack->skeleton->world_transform_to_global_pose(node_target->get_global_transform()); - origin_global_pose = origin_global_pose_trans; - - final_joint_idx = fabrik_data_chain.size() - 1; - real_t target_distance = fabrik_transforms[final_joint_idx].origin.distance_to(target_global_pose.origin); - chain_iterations = 0; - - while (target_distance > chain_tolerance) { - chain_backwards(); - chain_forwards(); - - // update the target distance - target_distance = fabrik_transforms[final_joint_idx].origin.distance_to(target_global_pose.origin); - - // update chain iterations - chain_iterations += 1; - if (chain_iterations >= chain_max_iterations) { - break; - } - } - chain_apply(); - - execution_error_found = false; -} - -void SkeletonModification3DFABRIK::chain_backwards() { - int final_bone_idx = fabrik_data_chain[final_joint_idx].bone_idx; - Transform3D final_joint_trans = fabrik_transforms[final_joint_idx]; - - // Get the direction the final bone is facing in. - stack->skeleton->update_bone_rest_forward_vector(final_bone_idx); - Transform3D final_bone_direction_trans = final_joint_trans.looking_at(target_global_pose.origin, Vector3(0, 1, 0)); - final_bone_direction_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(final_bone_idx, final_bone_direction_trans.basis); - Vector3 direction = final_bone_direction_trans.basis.xform(stack->skeleton->get_bone_axis_forward_vector(final_bone_idx)).normalized(); - - // If set to override, then use the target's Basis rather than the bone's - if (fabrik_data_chain[final_joint_idx].use_target_basis) { - direction = target_global_pose.basis.xform(stack->skeleton->get_bone_axis_forward_vector(final_bone_idx)).normalized(); - } - - // set the position of the final joint to the target position - final_joint_trans.origin = target_global_pose.origin - (direction * fabrik_data_chain[final_joint_idx].length); - fabrik_transforms[final_joint_idx] = final_joint_trans; - - // for all other joints, move them towards the target - int i = final_joint_idx; - while (i >= 1) { - Transform3D next_bone_trans = fabrik_transforms[i]; - i -= 1; - Transform3D current_trans = fabrik_transforms[i]; - - real_t length = fabrik_data_chain[i].length / (current_trans.origin.distance_to(next_bone_trans.origin)); - current_trans.origin = next_bone_trans.origin.lerp(current_trans.origin, length); - - // Save the result - fabrik_transforms[i] = current_trans; - } -} - -void SkeletonModification3DFABRIK::chain_forwards() { - // Set root at the initial position. - Transform3D root_transform = fabrik_transforms[0]; - - root_transform.origin = origin_global_pose.origin; - fabrik_transforms[0] = origin_global_pose; - - for (uint32_t i = 0; i < fabrik_data_chain.size() - 1; i++) { - Transform3D current_trans = fabrik_transforms[i]; - Transform3D next_bone_trans = fabrik_transforms[i + 1]; - - real_t length = fabrik_data_chain[i].length / (next_bone_trans.origin.distance_to(current_trans.origin)); - next_bone_trans.origin = current_trans.origin.lerp(next_bone_trans.origin, length); - - // Save the result - fabrik_transforms[i + 1] = next_bone_trans; - } -} - -void SkeletonModification3DFABRIK::chain_apply() { - for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) { - int current_bone_idx = fabrik_data_chain[i].bone_idx; - Transform3D current_trans = fabrik_transforms[i]; - - // If this is the last bone in the chain... - if (i == fabrik_data_chain.size() - 1) { - if (fabrik_data_chain[i].use_target_basis == false) { // Point to target... - // Get the forward direction that the basis is facing in right now. - stack->skeleton->update_bone_rest_forward_vector(current_bone_idx); - Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(current_bone_idx); - // Rotate the bone towards the target: - current_trans.basis.rotate_to_align(forward_vector, current_trans.origin.direction_to(target_global_pose.origin)); - current_trans.basis.rotate_local(forward_vector, fabrik_data_chain[i].roll); - } else { // Use the target's Basis... - current_trans.basis = target_global_pose.basis.orthonormalized().scaled(current_trans.basis.get_scale()); - } - } else { // every other bone in the chain... - Transform3D next_trans = fabrik_transforms[i + 1]; - - // Get the forward direction that the basis is facing in right now. - stack->skeleton->update_bone_rest_forward_vector(current_bone_idx); - Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(current_bone_idx); - // Rotate the bone towards the next bone in the chain: - current_trans.basis.rotate_to_align(forward_vector, current_trans.origin.direction_to(next_trans.origin)); - current_trans.basis.rotate_local(forward_vector, fabrik_data_chain[i].roll); - } - stack->skeleton->set_bone_local_pose_override(current_bone_idx, stack->skeleton->global_pose_to_local_pose(current_bone_idx, current_trans), stack->strength, true); - } - - // Update all the bones so the next modification has up-to-date data. - stack->skeleton->force_update_all_bone_transforms(); -} - -void SkeletonModification3DFABRIK::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - if (stack != nullptr) { - is_setup = true; - execution_error_found = false; - update_target_cache(); - - for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) { - update_joint_tip_cache(i); - } - } -} - -void SkeletonModification3DFABRIK::update_target_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree() && target_node.is_empty() == false) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: node is not in the scene tree!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DFABRIK::update_joint_tip_cache(int p_joint_idx) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_MSG(p_joint_idx, bone_chain_size, "FABRIK joint not found"); - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update tip cache: modification is not properly setup!"); - return; - } - fabrik_data_chain[p_joint_idx].tip_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree() && fabrik_data_chain[p_joint_idx].tip_node.is_empty() == false) { - if (stack->skeleton->has_node(fabrik_data_chain[p_joint_idx].tip_node)) { - Node *node = stack->skeleton->get_node(fabrik_data_chain[p_joint_idx].tip_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update tip cache for joint " + itos(p_joint_idx) + ": node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update tip cache for joint " + itos(p_joint_idx) + ": node is not in scene tree!"); - fabrik_data_chain[p_joint_idx].tip_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DFABRIK::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_target_cache(); -} - -NodePath SkeletonModification3DFABRIK::get_target_node() const { - return target_node; -} - -int SkeletonModification3DFABRIK::get_fabrik_data_chain_length() { - return fabrik_data_chain.size(); -} - -void SkeletonModification3DFABRIK::set_fabrik_data_chain_length(int p_length) { - ERR_FAIL_COND(p_length < 0); - fabrik_data_chain.resize(p_length); - fabrik_transforms.resize(p_length); - execution_error_found = false; - notify_property_list_changed(); -} - -real_t SkeletonModification3DFABRIK::get_chain_tolerance() { - return chain_tolerance; -} - -void SkeletonModification3DFABRIK::set_chain_tolerance(real_t p_tolerance) { - ERR_FAIL_COND_MSG(p_tolerance <= 0, "FABRIK chain tolerance must be more than zero!"); - chain_tolerance = p_tolerance; -} - -int SkeletonModification3DFABRIK::get_chain_max_iterations() { - return chain_max_iterations; -} -void SkeletonModification3DFABRIK::set_chain_max_iterations(int p_iterations) { - ERR_FAIL_COND_MSG(p_iterations <= 0, "FABRIK chain iterations must be at least one. Set enabled to false to disable the FABRIK chain."); - chain_max_iterations = p_iterations; -} - -// FABRIK joint data functions -String SkeletonModification3DFABRIK::get_fabrik_joint_bone_name(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, String()); - return fabrik_data_chain[p_joint_idx].bone_name; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_bone_name(int p_joint_idx, String p_bone_name) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].bone_name = p_bone_name; - - if (stack) { - if (stack->skeleton) { - fabrik_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(p_bone_name); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DFABRIK::get_fabrik_joint_bone_index(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return fabrik_data_chain[p_joint_idx].bone_idx; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_bone_index(int p_joint_idx, int p_bone_idx) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!"); - fabrik_data_chain[p_joint_idx].bone_idx = p_bone_idx; - - if (stack) { - if (stack->skeleton) { - fabrik_data_chain[p_joint_idx].bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -real_t SkeletonModification3DFABRIK::get_fabrik_joint_length(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return fabrik_data_chain[p_joint_idx].length; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_length(int p_joint_idx, real_t p_bone_length) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_bone_length < 0, "FABRIK joint length cannot be less than zero!"); - - if (!is_setup) { - fabrik_data_chain[p_joint_idx].length = p_bone_length; - return; - } - - if (fabrik_data_chain[p_joint_idx].auto_calculate_length) { - WARN_PRINT("FABRIK Length not set: auto calculate length is enabled for this joint!"); - fabrik_joint_auto_calculate_length(p_joint_idx); - } else { - fabrik_data_chain[p_joint_idx].length = p_bone_length; - } - - execution_error_found = false; -} - -Vector3 SkeletonModification3DFABRIK::get_fabrik_joint_magnet(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, Vector3()); - return fabrik_data_chain[p_joint_idx].magnet_position; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_magnet(int p_joint_idx, Vector3 p_magnet) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].magnet_position = p_magnet; -} - -bool SkeletonModification3DFABRIK::get_fabrik_joint_auto_calculate_length(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return fabrik_data_chain[p_joint_idx].auto_calculate_length; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_auto_calculate_length(int p_joint_idx, bool p_auto_calculate) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].auto_calculate_length = p_auto_calculate; - fabrik_joint_auto_calculate_length(p_joint_idx); - notify_property_list_changed(); -} - -void SkeletonModification3DFABRIK::fabrik_joint_auto_calculate_length(int p_joint_idx) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - if (!fabrik_data_chain[p_joint_idx].auto_calculate_length) { - return; - } - - if (!stack || !stack->skeleton || !is_setup) { - _print_execution_error(true, "Cannot auto calculate joint length: modification is not properly setup!"); - return; - } - ERR_FAIL_INDEX_MSG(fabrik_data_chain[p_joint_idx].bone_idx, stack->skeleton->get_bone_count(), - "Bone for joint " + itos(p_joint_idx) + " is not set or points to an unknown bone!"); - - if (fabrik_data_chain[p_joint_idx].use_tip_node) { // Use the tip node to update joint length. - - update_joint_tip_cache(p_joint_idx); - - Node3D *tip_node = Object::cast_to<Node3D>(ObjectDB::get_instance(fabrik_data_chain[p_joint_idx].tip_node_cache)); - ERR_FAIL_COND_MSG(!tip_node, "Tip node for joint " + itos(p_joint_idx) + "is not a Node3D-based node. Cannot calculate length..."); - ERR_FAIL_COND_MSG(!tip_node->is_inside_tree(), "Tip node for joint " + itos(p_joint_idx) + "is not in the scene tree. Cannot calculate length..."); - - Transform3D node_trans = tip_node->get_global_transform(); - node_trans = stack->skeleton->world_transform_to_global_pose(node_trans); - //node_trans = stack->skeleton->global_pose_to_local_pose(fabrik_data_chain[p_joint_idx].bone_idx, node_trans); - //fabrik_data_chain[p_joint_idx].length = node_trans.origin.length(); - - fabrik_data_chain[p_joint_idx].length = stack->skeleton->get_bone_global_pose(fabrik_data_chain[p_joint_idx].bone_idx).origin.distance_to(node_trans.origin); - - } else { // Use child bone(s) to update joint length, if possible - Vector<int> bone_children = stack->skeleton->get_bone_children(fabrik_data_chain[p_joint_idx].bone_idx); - if (bone_children.size() <= 0) { - ERR_FAIL_MSG("Cannot calculate length for joint " + itos(p_joint_idx) + "joint uses leaf bone. \nPlease manually set the bone length or use a tip node!"); - return; - } - - Transform3D bone_trans = stack->skeleton->get_bone_global_pose(fabrik_data_chain[p_joint_idx].bone_idx); - - real_t final_length = 0; - for (int i = 0; i < bone_children.size(); i++) { - Transform3D child_transform = stack->skeleton->get_bone_global_pose(bone_children[i]); - final_length += bone_trans.origin.distance_to(child_transform.origin); - //final_length += stack->skeleton->global_pose_to_local_pose(fabrik_data_chain[p_joint_idx].bone_idx, child_transform).origin.length(); - } - fabrik_data_chain[p_joint_idx].length = final_length / bone_children.size(); - } - execution_error_found = false; - notify_property_list_changed(); -} - -bool SkeletonModification3DFABRIK::get_fabrik_joint_use_tip_node(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return fabrik_data_chain[p_joint_idx].use_tip_node; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_use_tip_node(int p_joint_idx, bool p_use_tip_node) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].use_tip_node = p_use_tip_node; - notify_property_list_changed(); -} - -NodePath SkeletonModification3DFABRIK::get_fabrik_joint_tip_node(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, NodePath()); - return fabrik_data_chain[p_joint_idx].tip_node; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_tip_node(int p_joint_idx, NodePath p_tip_node) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].tip_node = p_tip_node; - update_joint_tip_cache(p_joint_idx); -} - -bool SkeletonModification3DFABRIK::get_fabrik_joint_use_target_basis(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return fabrik_data_chain[p_joint_idx].use_target_basis; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_use_target_basis(int p_joint_idx, bool p_use_target_basis) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].use_target_basis = p_use_target_basis; -} - -real_t SkeletonModification3DFABRIK::get_fabrik_joint_roll(int p_joint_idx) const { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, 0.0); - return fabrik_data_chain[p_joint_idx].roll; -} - -void SkeletonModification3DFABRIK::set_fabrik_joint_roll(int p_joint_idx, real_t p_roll) { - const int bone_chain_size = fabrik_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - fabrik_data_chain[p_joint_idx].roll = p_roll; -} - -void SkeletonModification3DFABRIK::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DFABRIK::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DFABRIK::get_target_node); - ClassDB::bind_method(D_METHOD("set_fabrik_data_chain_length", "length"), &SkeletonModification3DFABRIK::set_fabrik_data_chain_length); - ClassDB::bind_method(D_METHOD("get_fabrik_data_chain_length"), &SkeletonModification3DFABRIK::get_fabrik_data_chain_length); - ClassDB::bind_method(D_METHOD("set_chain_tolerance", "tolerance"), &SkeletonModification3DFABRIK::set_chain_tolerance); - ClassDB::bind_method(D_METHOD("get_chain_tolerance"), &SkeletonModification3DFABRIK::get_chain_tolerance); - ClassDB::bind_method(D_METHOD("set_chain_max_iterations", "max_iterations"), &SkeletonModification3DFABRIK::set_chain_max_iterations); - ClassDB::bind_method(D_METHOD("get_chain_max_iterations"), &SkeletonModification3DFABRIK::get_chain_max_iterations); - - // FABRIK joint data functions - ClassDB::bind_method(D_METHOD("get_fabrik_joint_bone_name", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_bone_name); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_bone_name", "joint_idx", "bone_name"), &SkeletonModification3DFABRIK::set_fabrik_joint_bone_name); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_bone_index", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_bone_index); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_bone_index", "joint_idx", "bone_index"), &SkeletonModification3DFABRIK::set_fabrik_joint_bone_index); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_length", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_length); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_length", "joint_idx", "length"), &SkeletonModification3DFABRIK::set_fabrik_joint_length); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_magnet", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_magnet); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_magnet", "joint_idx", "magnet_position"), &SkeletonModification3DFABRIK::set_fabrik_joint_magnet); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_auto_calculate_length", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_auto_calculate_length); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_auto_calculate_length", "joint_idx", "auto_calculate_length"), &SkeletonModification3DFABRIK::set_fabrik_joint_auto_calculate_length); - ClassDB::bind_method(D_METHOD("fabrik_joint_auto_calculate_length", "joint_idx"), &SkeletonModification3DFABRIK::fabrik_joint_auto_calculate_length); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_use_tip_node", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_use_tip_node); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_use_tip_node", "joint_idx", "use_tip_node"), &SkeletonModification3DFABRIK::set_fabrik_joint_use_tip_node); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_tip_node", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_tip_node); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_tip_node", "joint_idx", "tip_node"), &SkeletonModification3DFABRIK::set_fabrik_joint_tip_node); - ClassDB::bind_method(D_METHOD("get_fabrik_joint_use_target_basis", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_use_target_basis); - ClassDB::bind_method(D_METHOD("set_fabrik_joint_use_target_basis", "joint_idx", "use_target_basis"), &SkeletonModification3DFABRIK::set_fabrik_joint_use_target_basis); - - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "fabrik_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_fabrik_data_chain_length", "get_fabrik_data_chain_length"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "chain_tolerance", PROPERTY_HINT_RANGE, "0,100,0.001"), "set_chain_tolerance", "get_chain_tolerance"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "chain_max_iterations", PROPERTY_HINT_RANGE, "1,50,1"), "set_chain_max_iterations", "get_chain_max_iterations"); -} - -SkeletonModification3DFABRIK::SkeletonModification3DFABRIK() { - stack = nullptr; - is_setup = false; - enabled = true; -} - -SkeletonModification3DFABRIK::~SkeletonModification3DFABRIK() { -} diff --git a/scene/resources/skeleton_modification_3d_fabrik.h b/scene/resources/skeleton_modification_3d_fabrik.h deleted file mode 100644 index c834658093..0000000000 --- a/scene/resources/skeleton_modification_3d_fabrik.h +++ /dev/null @@ -1,124 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_fabrik.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#ifndef SKELETON_MODIFICATION_3D_FABRIK_H -#define SKELETON_MODIFICATION_3D_FABRIK_H - -#include "core/templates/local_vector.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DFABRIK : public SkeletonModification3D { - GDCLASS(SkeletonModification3DFABRIK, SkeletonModification3D); - -private: - struct FABRIK_Joint_Data { - String bone_name = ""; - int bone_idx = -1; - real_t length = -1; - Vector3 magnet_position = Vector3(0, 0, 0); - - bool auto_calculate_length = true; - bool use_tip_node = false; - NodePath tip_node; - ObjectID tip_node_cache; - - bool use_target_basis = false; - real_t roll = 0; - }; - - LocalVector<FABRIK_Joint_Data> fabrik_data_chain; - LocalVector<Transform3D> fabrik_transforms; - - NodePath target_node; - ObjectID target_node_cache; - - real_t chain_tolerance = 0.01; - int chain_max_iterations = 10; - int chain_iterations = 0; - - void update_target_cache(); - void update_joint_tip_cache(int p_joint_idx); - - int final_joint_idx = 0; - Transform3D target_global_pose; - Transform3D origin_global_pose; - - void chain_backwards(); - void chain_forwards(); - void chain_apply(); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - int get_fabrik_data_chain_length(); - void set_fabrik_data_chain_length(int p_new_length); - - real_t get_chain_tolerance(); - void set_chain_tolerance(real_t p_tolerance); - - int get_chain_max_iterations(); - void set_chain_max_iterations(int p_iterations); - - String get_fabrik_joint_bone_name(int p_joint_idx) const; - void set_fabrik_joint_bone_name(int p_joint_idx, String p_bone_name); - int get_fabrik_joint_bone_index(int p_joint_idx) const; - void set_fabrik_joint_bone_index(int p_joint_idx, int p_bone_idx); - real_t get_fabrik_joint_length(int p_joint_idx) const; - void set_fabrik_joint_length(int p_joint_idx, real_t p_bone_length); - Vector3 get_fabrik_joint_magnet(int p_joint_idx) const; - void set_fabrik_joint_magnet(int p_joint_idx, Vector3 p_magnet); - bool get_fabrik_joint_auto_calculate_length(int p_joint_idx) const; - void set_fabrik_joint_auto_calculate_length(int p_joint_idx, bool p_auto_calculate); - void fabrik_joint_auto_calculate_length(int p_joint_idx); - bool get_fabrik_joint_use_tip_node(int p_joint_idx) const; - void set_fabrik_joint_use_tip_node(int p_joint_idx, bool p_use_tip_node); - NodePath get_fabrik_joint_tip_node(int p_joint_idx) const; - void set_fabrik_joint_tip_node(int p_joint_idx, NodePath p_tip_node); - bool get_fabrik_joint_use_target_basis(int p_joint_idx) const; - void set_fabrik_joint_use_target_basis(int p_joint_idx, bool p_use_basis); - real_t get_fabrik_joint_roll(int p_joint_idx) const; - void set_fabrik_joint_roll(int p_joint_idx, real_t p_roll); - - SkeletonModification3DFABRIK(); - ~SkeletonModification3DFABRIK(); -}; - -#endif // SKELETON_MODIFICATION_3D_FABRIK_H diff --git a/scene/resources/skeleton_modification_3d_jiggle.cpp b/scene/resources/skeleton_modification_3d_jiggle.cpp deleted file mode 100644 index 2cfc7fb10f..0000000000 --- a/scene/resources/skeleton_modification_3d_jiggle.cpp +++ /dev/null @@ -1,582 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_jiggle.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#include "scene/resources/skeleton_modification_3d_jiggle.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DJiggle::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path.begins_with("joint_data/")) { - const int jiggle_size = jiggle_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, jiggle_size, false); - - if (what == "bone_name") { - set_jiggle_joint_bone_name(which, p_value); - } else if (what == "bone_index") { - set_jiggle_joint_bone_index(which, p_value); - } else if (what == "override_defaults") { - set_jiggle_joint_override(which, p_value); - } else if (what == "stiffness") { - set_jiggle_joint_stiffness(which, p_value); - } else if (what == "mass") { - set_jiggle_joint_mass(which, p_value); - } else if (what == "damping") { - set_jiggle_joint_damping(which, p_value); - } else if (what == "use_gravity") { - set_jiggle_joint_use_gravity(which, p_value); - } else if (what == "gravity") { - set_jiggle_joint_gravity(which, p_value); - } else if (what == "roll") { - set_jiggle_joint_roll(which, Math::deg_to_rad(real_t(p_value))); - } - return true; - } else { - if (path == "use_colliders") { - set_use_colliders(p_value); - } else if (path == "collision_mask") { - set_collision_mask(p_value); - } - return true; - } - return true; -} - -bool SkeletonModification3DJiggle::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path.begins_with("joint_data/")) { - const int jiggle_size = jiggle_data_chain.size(); - int which = path.get_slicec('/', 1).to_int(); - String what = path.get_slicec('/', 2); - ERR_FAIL_INDEX_V(which, jiggle_size, false); - - if (what == "bone_name") { - r_ret = get_jiggle_joint_bone_name(which); - } else if (what == "bone_index") { - r_ret = get_jiggle_joint_bone_index(which); - } else if (what == "override_defaults") { - r_ret = get_jiggle_joint_override(which); - } else if (what == "stiffness") { - r_ret = get_jiggle_joint_stiffness(which); - } else if (what == "mass") { - r_ret = get_jiggle_joint_mass(which); - } else if (what == "damping") { - r_ret = get_jiggle_joint_damping(which); - } else if (what == "use_gravity") { - r_ret = get_jiggle_joint_use_gravity(which); - } else if (what == "gravity") { - r_ret = get_jiggle_joint_gravity(which); - } else if (what == "roll") { - r_ret = Math::rad_to_deg(get_jiggle_joint_roll(which)); - } - return true; - } else { - if (path == "use_colliders") { - r_ret = get_use_colliders(); - } else if (path == "collision_mask") { - r_ret = get_collision_mask(); - } - return true; - } - return true; -} - -void SkeletonModification3DJiggle::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back(PropertyInfo(Variant::BOOL, "use_colliders", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (use_colliders) { - p_list->push_back(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS, "", PROPERTY_USAGE_DEFAULT)); - } - - for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) { - String base_string = "joint_data/" + itos(i) + "/"; - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, base_string + "bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "roll", PROPERTY_HINT_RANGE, "-360,360,0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "override_defaults", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - - if (jiggle_data_chain[i].override_defaults) { - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "stiffness", PROPERTY_HINT_RANGE, "0, 1000, 0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "mass", PROPERTY_HINT_RANGE, "0, 1000, 0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "damping", PROPERTY_HINT_RANGE, "0, 1, 0.01", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_gravity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (jiggle_data_chain[i].use_gravity) { - p_list->push_back(PropertyInfo(Variant::VECTOR3, base_string + "gravity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - } - } - } -} - -void SkeletonModification3DJiggle::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - if (!enabled) { - return; - } - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update..."); - update_cache(); - return; - } - Node3D *target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - _print_execution_error(!target || !target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!"); - - for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) { - _execute_jiggle_joint(i, target, p_delta); - } - - execution_error_found = false; -} - -void SkeletonModification3DJiggle::_execute_jiggle_joint(int p_joint_idx, Node3D *p_target, real_t p_delta) { - // Adopted from: https://wiki.unity3d.com/index.php/JiggleBone - // With modifications by TwistedTwigleg. - - if (jiggle_data_chain[p_joint_idx].bone_idx <= -2) { - jiggle_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(jiggle_data_chain[p_joint_idx].bone_name); - } - if (_print_execution_error( - jiggle_data_chain[p_joint_idx].bone_idx < 0 || jiggle_data_chain[p_joint_idx].bone_idx > stack->skeleton->get_bone_count(), - "Jiggle joint " + itos(p_joint_idx) + " bone index is invalid. Cannot execute modification!")) { - return; - } - - Transform3D bone_local_pos = stack->skeleton->get_bone_local_pose_override(jiggle_data_chain[p_joint_idx].bone_idx); - if (bone_local_pos == Transform3D()) { - bone_local_pos = stack->skeleton->get_bone_pose(jiggle_data_chain[p_joint_idx].bone_idx); - } - - Transform3D new_bone_trans = stack->skeleton->local_pose_to_global_pose(jiggle_data_chain[p_joint_idx].bone_idx, bone_local_pos); - Vector3 target_position = stack->skeleton->world_transform_to_global_pose(p_target->get_global_transform()).origin; - - jiggle_data_chain[p_joint_idx].force = (target_position - jiggle_data_chain[p_joint_idx].dynamic_position) * jiggle_data_chain[p_joint_idx].stiffness * p_delta; - - if (jiggle_data_chain[p_joint_idx].use_gravity) { - Vector3 gravity_to_apply = new_bone_trans.basis.inverse().xform(jiggle_data_chain[p_joint_idx].gravity); - jiggle_data_chain[p_joint_idx].force += gravity_to_apply * p_delta; - } - - jiggle_data_chain[p_joint_idx].acceleration = jiggle_data_chain[p_joint_idx].force / jiggle_data_chain[p_joint_idx].mass; - jiggle_data_chain[p_joint_idx].velocity += jiggle_data_chain[p_joint_idx].acceleration * (1 - jiggle_data_chain[p_joint_idx].damping); - - jiggle_data_chain[p_joint_idx].dynamic_position += jiggle_data_chain[p_joint_idx].velocity + jiggle_data_chain[p_joint_idx].force; - jiggle_data_chain[p_joint_idx].dynamic_position += new_bone_trans.origin - jiggle_data_chain[p_joint_idx].last_position; - jiggle_data_chain[p_joint_idx].last_position = new_bone_trans.origin; - - // Collision detection/response - if (use_colliders) { - if (execution_mode == SkeletonModificationStack3D::EXECUTION_MODE::execution_mode_physics_process) { - Ref<World3D> world_3d = stack->skeleton->get_world_3d(); - ERR_FAIL_COND(world_3d.is_null()); - PhysicsDirectSpaceState3D *space_state = PhysicsServer3D::get_singleton()->space_get_direct_state(world_3d->get_space()); - PhysicsDirectSpaceState3D::RayResult ray_result; - - // Convert to world transforms, which is what the physics server needs - Transform3D new_bone_trans_world = stack->skeleton->global_pose_to_world_transform(new_bone_trans); - Transform3D dynamic_position_world = stack->skeleton->global_pose_to_world_transform(Transform3D(Basis(), jiggle_data_chain[p_joint_idx].dynamic_position)); - - PhysicsDirectSpaceState3D::RayParameters ray_params; - ray_params.from = new_bone_trans_world.origin; - ray_params.to = dynamic_position_world.get_origin(); - ray_params.collision_mask = collision_mask; - - bool ray_hit = space_state->intersect_ray(ray_params, ray_result); - - if (ray_hit) { - jiggle_data_chain[p_joint_idx].dynamic_position = jiggle_data_chain[p_joint_idx].last_noncollision_position; - jiggle_data_chain[p_joint_idx].acceleration = Vector3(0, 0, 0); - jiggle_data_chain[p_joint_idx].velocity = Vector3(0, 0, 0); - } else { - jiggle_data_chain[p_joint_idx].last_noncollision_position = jiggle_data_chain[p_joint_idx].dynamic_position; - } - - } else { - WARN_PRINT_ONCE("Jiggle modifier: You cannot detect colliders without the stack mode being set to _physics_process!"); - } - } - - // Get the forward direction that the basis is facing in right now. - stack->skeleton->update_bone_rest_forward_vector(jiggle_data_chain[p_joint_idx].bone_idx); - Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(jiggle_data_chain[p_joint_idx].bone_idx); - - // Rotate the bone using the dynamic position! - new_bone_trans.basis.rotate_to_align(forward_vector, new_bone_trans.origin.direction_to(jiggle_data_chain[p_joint_idx].dynamic_position)); - - // Roll - new_bone_trans.basis.rotate_local(forward_vector, jiggle_data_chain[p_joint_idx].roll); - - new_bone_trans = stack->skeleton->global_pose_to_local_pose(jiggle_data_chain[p_joint_idx].bone_idx, new_bone_trans); - stack->skeleton->set_bone_local_pose_override(jiggle_data_chain[p_joint_idx].bone_idx, new_bone_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(jiggle_data_chain[p_joint_idx].bone_idx); -} - -void SkeletonModification3DJiggle::_update_jiggle_joint_data() { - for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) { - if (!jiggle_data_chain[i].override_defaults) { - set_jiggle_joint_stiffness(i, stiffness); - set_jiggle_joint_mass(i, mass); - set_jiggle_joint_damping(i, damping); - set_jiggle_joint_use_gravity(i, use_gravity); - set_jiggle_joint_gravity(i, gravity); - } - } -} - -void SkeletonModification3DJiggle::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - - if (stack) { - is_setup = true; - execution_error_found = false; - - if (stack->skeleton) { - for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) { - int bone_idx = jiggle_data_chain[i].bone_idx; - if (bone_idx > 0 && bone_idx < stack->skeleton->get_bone_count()) { - jiggle_data_chain[i].dynamic_position = stack->skeleton->local_pose_to_global_pose(bone_idx, stack->skeleton->get_bone_local_pose_override(bone_idx)).origin; - } - } - } - - update_cache(); - } -} - -void SkeletonModification3DJiggle::update_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: node is not in the scene tree!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DJiggle::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_cache(); -} - -NodePath SkeletonModification3DJiggle::get_target_node() const { - return target_node; -} - -void SkeletonModification3DJiggle::set_stiffness(real_t p_stiffness) { - ERR_FAIL_COND_MSG(p_stiffness < 0, "Stiffness cannot be set to a negative value!"); - stiffness = p_stiffness; - _update_jiggle_joint_data(); -} - -real_t SkeletonModification3DJiggle::get_stiffness() const { - return stiffness; -} - -void SkeletonModification3DJiggle::set_mass(real_t p_mass) { - ERR_FAIL_COND_MSG(p_mass < 0, "Mass cannot be set to a negative value!"); - mass = p_mass; - _update_jiggle_joint_data(); -} - -real_t SkeletonModification3DJiggle::get_mass() const { - return mass; -} - -void SkeletonModification3DJiggle::set_damping(real_t p_damping) { - ERR_FAIL_COND_MSG(p_damping < 0, "Damping cannot be set to a negative value!"); - ERR_FAIL_COND_MSG(p_damping > 1, "Damping cannot be more than one!"); - damping = p_damping; - _update_jiggle_joint_data(); -} - -real_t SkeletonModification3DJiggle::get_damping() const { - return damping; -} - -void SkeletonModification3DJiggle::set_use_gravity(bool p_use_gravity) { - use_gravity = p_use_gravity; - _update_jiggle_joint_data(); -} - -bool SkeletonModification3DJiggle::get_use_gravity() const { - return use_gravity; -} - -void SkeletonModification3DJiggle::set_gravity(Vector3 p_gravity) { - gravity = p_gravity; - _update_jiggle_joint_data(); -} - -Vector3 SkeletonModification3DJiggle::get_gravity() const { - return gravity; -} - -void SkeletonModification3DJiggle::set_use_colliders(bool p_use_collider) { - use_colliders = p_use_collider; - notify_property_list_changed(); -} - -bool SkeletonModification3DJiggle::get_use_colliders() const { - return use_colliders; -} - -void SkeletonModification3DJiggle::set_collision_mask(int p_mask) { - collision_mask = p_mask; -} - -int SkeletonModification3DJiggle::get_collision_mask() const { - return collision_mask; -} - -// Jiggle joint data functions -int SkeletonModification3DJiggle::get_jiggle_data_chain_length() { - return jiggle_data_chain.size(); -} - -void SkeletonModification3DJiggle::set_jiggle_data_chain_length(int p_length) { - ERR_FAIL_COND(p_length < 0); - jiggle_data_chain.resize(p_length); - execution_error_found = false; - notify_property_list_changed(); -} - -void SkeletonModification3DJiggle::set_jiggle_joint_bone_name(int p_joint_idx, String p_name) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - - jiggle_data_chain[p_joint_idx].bone_name = p_name; - if (stack && stack->skeleton) { - jiggle_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(p_name); - } - execution_error_found = false; - notify_property_list_changed(); -} - -String SkeletonModification3DJiggle::get_jiggle_joint_bone_name(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, ""); - return jiggle_data_chain[p_joint_idx].bone_name; -} - -int SkeletonModification3DJiggle::get_jiggle_joint_bone_index(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return jiggle_data_chain[p_joint_idx].bone_idx; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_bone_index(int p_joint_idx, int p_bone_idx) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!"); - jiggle_data_chain[p_joint_idx].bone_idx = p_bone_idx; - - if (stack) { - if (stack->skeleton) { - jiggle_data_chain[p_joint_idx].bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -void SkeletonModification3DJiggle::set_jiggle_joint_override(int p_joint_idx, bool p_override) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].override_defaults = p_override; - _update_jiggle_joint_data(); - notify_property_list_changed(); -} - -bool SkeletonModification3DJiggle::get_jiggle_joint_override(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return jiggle_data_chain[p_joint_idx].override_defaults; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_stiffness(int p_joint_idx, real_t p_stiffness) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_COND_MSG(p_stiffness < 0, "Stiffness cannot be set to a negative value!"); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].stiffness = p_stiffness; -} - -real_t SkeletonModification3DJiggle::get_jiggle_joint_stiffness(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return jiggle_data_chain[p_joint_idx].stiffness; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_mass(int p_joint_idx, real_t p_mass) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_COND_MSG(p_mass < 0, "Mass cannot be set to a negative value!"); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].mass = p_mass; -} - -real_t SkeletonModification3DJiggle::get_jiggle_joint_mass(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return jiggle_data_chain[p_joint_idx].mass; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_damping(int p_joint_idx, real_t p_damping) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_COND_MSG(p_damping < 0, "Damping cannot be set to a negative value!"); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].damping = p_damping; -} - -real_t SkeletonModification3DJiggle::get_jiggle_joint_damping(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1); - return jiggle_data_chain[p_joint_idx].damping; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_use_gravity(int p_joint_idx, bool p_use_gravity) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].use_gravity = p_use_gravity; - notify_property_list_changed(); -} - -bool SkeletonModification3DJiggle::get_jiggle_joint_use_gravity(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false); - return jiggle_data_chain[p_joint_idx].use_gravity; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_gravity(int p_joint_idx, Vector3 p_gravity) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].gravity = p_gravity; -} - -Vector3 SkeletonModification3DJiggle::get_jiggle_joint_gravity(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, Vector3(0, 0, 0)); - return jiggle_data_chain[p_joint_idx].gravity; -} - -void SkeletonModification3DJiggle::set_jiggle_joint_roll(int p_joint_idx, real_t p_roll) { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX(p_joint_idx, bone_chain_size); - jiggle_data_chain[p_joint_idx].roll = p_roll; -} - -real_t SkeletonModification3DJiggle::get_jiggle_joint_roll(int p_joint_idx) const { - const int bone_chain_size = jiggle_data_chain.size(); - ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, 0.0); - return jiggle_data_chain[p_joint_idx].roll; -} - -void SkeletonModification3DJiggle::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DJiggle::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DJiggle::get_target_node); - - ClassDB::bind_method(D_METHOD("set_jiggle_data_chain_length", "length"), &SkeletonModification3DJiggle::set_jiggle_data_chain_length); - ClassDB::bind_method(D_METHOD("get_jiggle_data_chain_length"), &SkeletonModification3DJiggle::get_jiggle_data_chain_length); - - ClassDB::bind_method(D_METHOD("set_stiffness", "stiffness"), &SkeletonModification3DJiggle::set_stiffness); - ClassDB::bind_method(D_METHOD("get_stiffness"), &SkeletonModification3DJiggle::get_stiffness); - ClassDB::bind_method(D_METHOD("set_mass", "mass"), &SkeletonModification3DJiggle::set_mass); - ClassDB::bind_method(D_METHOD("get_mass"), &SkeletonModification3DJiggle::get_mass); - ClassDB::bind_method(D_METHOD("set_damping", "damping"), &SkeletonModification3DJiggle::set_damping); - ClassDB::bind_method(D_METHOD("get_damping"), &SkeletonModification3DJiggle::get_damping); - ClassDB::bind_method(D_METHOD("set_use_gravity", "use_gravity"), &SkeletonModification3DJiggle::set_use_gravity); - ClassDB::bind_method(D_METHOD("get_use_gravity"), &SkeletonModification3DJiggle::get_use_gravity); - ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &SkeletonModification3DJiggle::set_gravity); - ClassDB::bind_method(D_METHOD("get_gravity"), &SkeletonModification3DJiggle::get_gravity); - - ClassDB::bind_method(D_METHOD("set_use_colliders", "use_colliders"), &SkeletonModification3DJiggle::set_use_colliders); - ClassDB::bind_method(D_METHOD("get_use_colliders"), &SkeletonModification3DJiggle::get_use_colliders); - ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &SkeletonModification3DJiggle::set_collision_mask); - ClassDB::bind_method(D_METHOD("get_collision_mask"), &SkeletonModification3DJiggle::get_collision_mask); - - // Jiggle joint data functions - ClassDB::bind_method(D_METHOD("set_jiggle_joint_bone_name", "joint_idx", "name"), &SkeletonModification3DJiggle::set_jiggle_joint_bone_name); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_bone_name", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_bone_name); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_bone_index", "joint_idx", "bone_idx"), &SkeletonModification3DJiggle::set_jiggle_joint_bone_index); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_bone_index", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_bone_index); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_override", "joint_idx", "override"), &SkeletonModification3DJiggle::set_jiggle_joint_override); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_override", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_override); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_stiffness", "joint_idx", "stiffness"), &SkeletonModification3DJiggle::set_jiggle_joint_stiffness); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_stiffness", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_stiffness); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_mass", "joint_idx", "mass"), &SkeletonModification3DJiggle::set_jiggle_joint_mass); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_mass", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_mass); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_damping", "joint_idx", "damping"), &SkeletonModification3DJiggle::set_jiggle_joint_damping); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_damping", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_damping); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_use_gravity", "joint_idx", "use_gravity"), &SkeletonModification3DJiggle::set_jiggle_joint_use_gravity); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_use_gravity", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_use_gravity); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_gravity", "joint_idx", "gravity"), &SkeletonModification3DJiggle::set_jiggle_joint_gravity); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_gravity", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_gravity); - ClassDB::bind_method(D_METHOD("set_jiggle_joint_roll", "joint_idx", "roll"), &SkeletonModification3DJiggle::set_jiggle_joint_roll); - ClassDB::bind_method(D_METHOD("get_jiggle_joint_roll", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_roll); - - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "jiggle_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_jiggle_data_chain_length", "get_jiggle_data_chain_length"); - ADD_GROUP("Default Joint Settings", ""); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "stiffness"), "set_stiffness", "get_stiffness"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mass"), "set_mass", "get_mass"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "damping", PROPERTY_HINT_RANGE, "0, 1, 0.01"), "set_damping", "get_damping"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_gravity"), "set_use_gravity", "get_use_gravity"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity"), "set_gravity", "get_gravity"); - ADD_GROUP("", ""); -} - -SkeletonModification3DJiggle::SkeletonModification3DJiggle() { - stack = nullptr; - is_setup = false; - jiggle_data_chain = Vector<Jiggle_Joint_Data>(); - stiffness = 3; - mass = 0.75; - damping = 0.75; - use_gravity = false; - gravity = Vector3(0, -6.0, 0); - enabled = true; -} - -SkeletonModification3DJiggle::~SkeletonModification3DJiggle() { -} diff --git a/scene/resources/skeleton_modification_3d_jiggle.h b/scene/resources/skeleton_modification_3d_jiggle.h deleted file mode 100644 index cca620a72d..0000000000 --- a/scene/resources/skeleton_modification_3d_jiggle.h +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_jiggle.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#ifndef SKELETON_MODIFICATION_3D_JIGGLE_H -#define SKELETON_MODIFICATION_3D_JIGGLE_H - -#include "core/templates/local_vector.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DJiggle : public SkeletonModification3D { - GDCLASS(SkeletonModification3DJiggle, SkeletonModification3D); - -private: - struct Jiggle_Joint_Data { - String bone_name = ""; - int bone_idx = -1; - - bool override_defaults = false; - real_t stiffness = 3; - real_t mass = 0.75; - real_t damping = 0.75; - bool use_gravity = false; - Vector3 gravity = Vector3(0, -6.0, 0); - real_t roll = 0; - - Vector3 cached_rotation = Vector3(0, 0, 0); - Vector3 force = Vector3(0, 0, 0); - Vector3 acceleration = Vector3(0, 0, 0); - Vector3 velocity = Vector3(0, 0, 0); - Vector3 last_position = Vector3(0, 0, 0); - Vector3 dynamic_position = Vector3(0, 0, 0); - - Vector3 last_noncollision_position = Vector3(0, 0, 0); - }; - - NodePath target_node; - ObjectID target_node_cache; - LocalVector<Jiggle_Joint_Data> jiggle_data_chain; - - real_t stiffness = 3; - real_t mass = 0.75; - real_t damping = 0.75; - bool use_gravity = false; - Vector3 gravity = Vector3(0, -6.0, 0); - - bool use_colliders = false; - uint32_t collision_mask = 1; - - void update_cache(); - void _execute_jiggle_joint(int p_joint_idx, Node3D *p_target, real_t p_delta); - void _update_jiggle_joint_data(); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - void set_stiffness(real_t p_stiffness); - real_t get_stiffness() const; - void set_mass(real_t p_mass); - real_t get_mass() const; - void set_damping(real_t p_damping); - real_t get_damping() const; - - void set_use_gravity(bool p_use_gravity); - bool get_use_gravity() const; - void set_gravity(Vector3 p_gravity); - Vector3 get_gravity() const; - - void set_use_colliders(bool p_use_colliders); - bool get_use_colliders() const; - void set_collision_mask(int p_mask); - int get_collision_mask() const; - - int get_jiggle_data_chain_length(); - void set_jiggle_data_chain_length(int p_new_length); - - void set_jiggle_joint_bone_name(int p_joint_idx, String p_name); - String get_jiggle_joint_bone_name(int p_joint_idx) const; - void set_jiggle_joint_bone_index(int p_joint_idx, int p_idx); - int get_jiggle_joint_bone_index(int p_joint_idx) const; - - void set_jiggle_joint_override(int p_joint_idx, bool p_override); - bool get_jiggle_joint_override(int p_joint_idx) const; - void set_jiggle_joint_stiffness(int p_joint_idx, real_t p_stiffness); - real_t get_jiggle_joint_stiffness(int p_joint_idx) const; - void set_jiggle_joint_mass(int p_joint_idx, real_t p_mass); - real_t get_jiggle_joint_mass(int p_joint_idx) const; - void set_jiggle_joint_damping(int p_joint_idx, real_t p_damping); - real_t get_jiggle_joint_damping(int p_joint_idx) const; - void set_jiggle_joint_use_gravity(int p_joint_idx, bool p_use_gravity); - bool get_jiggle_joint_use_gravity(int p_joint_idx) const; - void set_jiggle_joint_gravity(int p_joint_idx, Vector3 p_gravity); - Vector3 get_jiggle_joint_gravity(int p_joint_idx) const; - void set_jiggle_joint_roll(int p_joint_idx, real_t p_roll); - real_t get_jiggle_joint_roll(int p_joint_idx) const; - - SkeletonModification3DJiggle(); - ~SkeletonModification3DJiggle(); -}; - -#endif // SKELETON_MODIFICATION_3D_JIGGLE_H diff --git a/scene/resources/skeleton_modification_3d_lookat.cpp b/scene/resources/skeleton_modification_3d_lookat.cpp deleted file mode 100644 index 57eedeb64e..0000000000 --- a/scene/resources/skeleton_modification_3d_lookat.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_lookat.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#include "scene/resources/skeleton_modification_3d_lookat.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DLookAt::_set(const StringName &p_path, const Variant &p_value) { - if (p_path == "lock_rotation_to_plane") { - set_lock_rotation_to_plane(p_value); - } else if (p_path == "lock_rotation_plane") { - set_lock_rotation_plane(p_value); - } else if (p_path == "additional_rotation") { - Vector3 tmp = p_value; - tmp.x = Math::deg_to_rad(tmp.x); - tmp.y = Math::deg_to_rad(tmp.y); - tmp.z = Math::deg_to_rad(tmp.z); - set_additional_rotation(tmp); - } - - return true; -} - -bool SkeletonModification3DLookAt::_get(const StringName &p_path, Variant &r_ret) const { - if (p_path == "lock_rotation_to_plane") { - r_ret = get_lock_rotation_to_plane(); - } else if (p_path == "lock_rotation_plane") { - r_ret = get_lock_rotation_plane(); - } else if (p_path == "additional_rotation") { - Vector3 tmp = get_additional_rotation(); - tmp.x = Math::rad_to_deg(tmp.x); - tmp.y = Math::rad_to_deg(tmp.y); - tmp.z = Math::rad_to_deg(tmp.z); - r_ret = tmp; - } - - return true; -} - -void SkeletonModification3DLookAt::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back(PropertyInfo(Variant::BOOL, "lock_rotation_to_plane", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (lock_rotation_to_plane) { - p_list->push_back(PropertyInfo(Variant::INT, "lock_rotation_plane", PROPERTY_HINT_ENUM, "X plane,Y plane,Z plane", PROPERTY_USAGE_DEFAULT)); - } - p_list->push_back(PropertyInfo(Variant::VECTOR3, "additional_rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); -} - -void SkeletonModification3DLookAt::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - if (!enabled) { - return; - } - - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update..."); - update_cache(); - return; - } - - if (bone_idx <= -2) { - bone_idx = stack->skeleton->find_bone(bone_name); - } - - Node3D *target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - if (_print_execution_error(!target || !target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) { - return; - } - if (_print_execution_error(bone_idx <= -1, "Bone index is invalid. Cannot execute modification!")) { - return; - } - Transform3D new_bone_trans = stack->skeleton->get_bone_local_pose_override(bone_idx); - if (new_bone_trans == Transform3D()) { - new_bone_trans = stack->skeleton->get_bone_pose(bone_idx); - } - Vector3 target_pos = stack->skeleton->global_pose_to_local_pose(bone_idx, stack->skeleton->world_transform_to_global_pose(target->get_global_transform())).origin; - - // Lock the rotation to a plane relative to the bone by changing the target position - if (lock_rotation_to_plane) { - if (lock_rotation_plane == ROTATION_PLANE::ROTATION_PLANE_X) { - target_pos.x = new_bone_trans.origin.x; - } else if (lock_rotation_plane == ROTATION_PLANE::ROTATION_PLANE_Y) { - target_pos.y = new_bone_trans.origin.y; - } else if (lock_rotation_plane == ROTATION_PLANE::ROTATION_PLANE_Z) { - target_pos.z = new_bone_trans.origin.z; - } - } - - // Look at the target! - new_bone_trans = new_bone_trans.looking_at(target_pos, Vector3(0, 1, 0)); - // Convert from Z-forward to whatever direction the bone faces. - stack->skeleton->update_bone_rest_forward_vector(bone_idx); - new_bone_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(bone_idx, new_bone_trans.basis); - - // Apply additional rotation - new_bone_trans.basis.rotate_local(Vector3(1, 0, 0), additional_rotation.x); - new_bone_trans.basis.rotate_local(Vector3(0, 1, 0), additional_rotation.y); - new_bone_trans.basis.rotate_local(Vector3(0, 0, 1), additional_rotation.z); - - stack->skeleton->set_bone_local_pose_override(bone_idx, new_bone_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(bone_idx); - - // If we completed it successfully, then we can set execution_error_found to false - execution_error_found = false; -} - -void SkeletonModification3DLookAt::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - - if (stack != nullptr) { - is_setup = true; - execution_error_found = false; - update_cache(); - } -} - -void SkeletonModification3DLookAt::set_bone_name(String p_name) { - bone_name = p_name; - if (stack) { - if (stack->skeleton) { - bone_idx = stack->skeleton->find_bone(bone_name); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -String SkeletonModification3DLookAt::get_bone_name() const { - return bone_name; -} - -int SkeletonModification3DLookAt::get_bone_index() const { - return bone_idx; -} - -void SkeletonModification3DLookAt::set_bone_index(int p_bone_idx) { - ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!"); - bone_idx = p_bone_idx; - - if (stack) { - if (stack->skeleton) { - bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - } - execution_error_found = false; - notify_property_list_changed(); -} - -void SkeletonModification3DLookAt::update_cache() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: Node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: Node is not in the scene tree!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DLookAt::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_cache(); -} - -NodePath SkeletonModification3DLookAt::get_target_node() const { - return target_node; -} - -Vector3 SkeletonModification3DLookAt::get_additional_rotation() const { - return additional_rotation; -} - -void SkeletonModification3DLookAt::set_additional_rotation(Vector3 p_offset) { - additional_rotation = p_offset; -} - -bool SkeletonModification3DLookAt::get_lock_rotation_to_plane() const { - return lock_rotation_plane; -} - -void SkeletonModification3DLookAt::set_lock_rotation_to_plane(bool p_lock_rotation) { - lock_rotation_to_plane = p_lock_rotation; - notify_property_list_changed(); -} - -int SkeletonModification3DLookAt::get_lock_rotation_plane() const { - return lock_rotation_plane; -} - -void SkeletonModification3DLookAt::set_lock_rotation_plane(int p_plane) { - lock_rotation_plane = p_plane; -} - -void SkeletonModification3DLookAt::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_bone_name", "name"), &SkeletonModification3DLookAt::set_bone_name); - ClassDB::bind_method(D_METHOD("get_bone_name"), &SkeletonModification3DLookAt::get_bone_name); - - ClassDB::bind_method(D_METHOD("set_bone_index", "bone_idx"), &SkeletonModification3DLookAt::set_bone_index); - ClassDB::bind_method(D_METHOD("get_bone_index"), &SkeletonModification3DLookAt::get_bone_index); - - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DLookAt::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DLookAt::get_target_node); - - ClassDB::bind_method(D_METHOD("set_additional_rotation", "additional_rotation"), &SkeletonModification3DLookAt::set_additional_rotation); - ClassDB::bind_method(D_METHOD("get_additional_rotation"), &SkeletonModification3DLookAt::get_additional_rotation); - - ClassDB::bind_method(D_METHOD("set_lock_rotation_to_plane", "lock_to_plane"), &SkeletonModification3DLookAt::set_lock_rotation_to_plane); - ClassDB::bind_method(D_METHOD("get_lock_rotation_to_plane"), &SkeletonModification3DLookAt::get_lock_rotation_to_plane); - ClassDB::bind_method(D_METHOD("set_lock_rotation_plane", "plane"), &SkeletonModification3DLookAt::set_lock_rotation_plane); - ClassDB::bind_method(D_METHOD("get_lock_rotation_plane"), &SkeletonModification3DLookAt::get_lock_rotation_plane); - - ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "bone_name"), "set_bone_name", "get_bone_name"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "bone_index"), "set_bone_index", "get_bone_index"); - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); -} - -SkeletonModification3DLookAt::SkeletonModification3DLookAt() { - stack = nullptr; - is_setup = false; - bone_name = ""; - bone_idx = -2; - additional_rotation = Vector3(); - lock_rotation_to_plane = false; - enabled = true; -} - -SkeletonModification3DLookAt::~SkeletonModification3DLookAt() { -} diff --git a/scene/resources/skeleton_modification_3d_lookat.h b/scene/resources/skeleton_modification_3d_lookat.h deleted file mode 100644 index 9a25ac530d..0000000000 --- a/scene/resources/skeleton_modification_3d_lookat.h +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_lookat.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#ifndef SKELETON_MODIFICATION_3D_LOOKAT_H -#define SKELETON_MODIFICATION_3D_LOOKAT_H - -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DLookAt : public SkeletonModification3D { - GDCLASS(SkeletonModification3DLookAt, SkeletonModification3D); - -private: - String bone_name = ""; - int bone_idx = -1; - NodePath target_node; - ObjectID target_node_cache; - - Vector3 additional_rotation = Vector3(1, 0, 0); - bool lock_rotation_to_plane = false; - int lock_rotation_plane = ROTATION_PLANE_X; - - void update_cache(); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - enum ROTATION_PLANE { - ROTATION_PLANE_X, - ROTATION_PLANE_Y, - ROTATION_PLANE_Z - }; - - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_bone_name(String p_name); - String get_bone_name() const; - - void set_bone_index(int p_idx); - int get_bone_index() const; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - void set_additional_rotation(Vector3 p_offset); - Vector3 get_additional_rotation() const; - - void set_lock_rotation_to_plane(bool p_lock_to_plane); - bool get_lock_rotation_to_plane() const; - void set_lock_rotation_plane(int p_plane); - int get_lock_rotation_plane() const; - - SkeletonModification3DLookAt(); - ~SkeletonModification3DLookAt(); -}; - -#endif // SKELETON_MODIFICATION_3D_LOOKAT_H diff --git a/scene/resources/skeleton_modification_3d_stackholder.cpp b/scene/resources/skeleton_modification_3d_stackholder.cpp deleted file mode 100644 index 1598badb30..0000000000 --- a/scene/resources/skeleton_modification_3d_stackholder.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_stackholder.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#include "scene/resources/skeleton_modification_3d_stackholder.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DStackHolder::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path == "held_modification_stack") { - set_held_modification_stack(p_value); - } - return true; -} - -bool SkeletonModification3DStackHolder::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path == "held_modification_stack") { - r_ret = get_held_modification_stack(); - } - return true; -} - -void SkeletonModification3DStackHolder::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back(PropertyInfo(Variant::OBJECT, "held_modification_stack", PROPERTY_HINT_RESOURCE_TYPE, "SkeletonModificationStack3D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE)); -} - -void SkeletonModification3DStackHolder::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - - if (held_modification_stack.is_valid()) { - held_modification_stack->execute(p_delta, execution_mode); - } -} - -void SkeletonModification3DStackHolder::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - - if (stack != nullptr) { - is_setup = true; - - if (held_modification_stack.is_valid()) { - held_modification_stack->set_skeleton(stack->get_skeleton()); - held_modification_stack->setup(); - } - } -} - -void SkeletonModification3DStackHolder::set_held_modification_stack(Ref<SkeletonModificationStack3D> p_held_stack) { - held_modification_stack = p_held_stack; - - if (is_setup && held_modification_stack.is_valid()) { - held_modification_stack->set_skeleton(stack->get_skeleton()); - held_modification_stack->setup(); - } -} - -Ref<SkeletonModificationStack3D> SkeletonModification3DStackHolder::get_held_modification_stack() const { - return held_modification_stack; -} - -void SkeletonModification3DStackHolder::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_held_modification_stack", "held_modification_stack"), &SkeletonModification3DStackHolder::set_held_modification_stack); - ClassDB::bind_method(D_METHOD("get_held_modification_stack"), &SkeletonModification3DStackHolder::get_held_modification_stack); -} - -SkeletonModification3DStackHolder::SkeletonModification3DStackHolder() { - stack = nullptr; - is_setup = false; - enabled = true; -} - -SkeletonModification3DStackHolder::~SkeletonModification3DStackHolder() { -} diff --git a/scene/resources/skeleton_modification_3d_stackholder.h b/scene/resources/skeleton_modification_3d_stackholder.h deleted file mode 100644 index da39044f97..0000000000 --- a/scene/resources/skeleton_modification_3d_stackholder.h +++ /dev/null @@ -1,59 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_stackholder.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#ifndef SKELETON_MODIFICATION_3D_STACKHOLDER_H -#define SKELETON_MODIFICATION_3D_STACKHOLDER_H - -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DStackHolder : public SkeletonModification3D { - GDCLASS(SkeletonModification3DStackHolder, SkeletonModification3D); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - Ref<SkeletonModificationStack3D> held_modification_stack; - - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_held_modification_stack(Ref<SkeletonModificationStack3D> p_held_stack); - Ref<SkeletonModificationStack3D> get_held_modification_stack() const; - - SkeletonModification3DStackHolder(); - ~SkeletonModification3DStackHolder(); -}; - -#endif // SKELETON_MODIFICATION_3D_STACKHOLDER_H diff --git a/scene/resources/skeleton_modification_3d_twoboneik.cpp b/scene/resources/skeleton_modification_3d_twoboneik.cpp deleted file mode 100644 index 7d5b4d2b55..0000000000 --- a/scene/resources/skeleton_modification_3d_twoboneik.cpp +++ /dev/null @@ -1,617 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_twoboneik.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#include "scene/resources/skeleton_modification_3d_twoboneik.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -bool SkeletonModification3DTwoBoneIK::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path == "use_tip_node") { - set_use_tip_node(p_value); - } else if (path == "tip_node") { - set_tip_node(p_value); - } else if (path == "auto_calculate_joint_length") { - set_auto_calculate_joint_length(p_value); - } else if (path == "use_pole_node") { - set_use_pole_node(p_value); - } else if (path == "pole_node") { - set_pole_node(p_value); - } else if (path == "joint_one_length") { - set_joint_one_length(p_value); - } else if (path == "joint_two_length") { - set_joint_two_length(p_value); - } else if (path == "joint_one/bone_name") { - set_joint_one_bone_name(p_value); - } else if (path == "joint_one/bone_idx") { - set_joint_one_bone_idx(p_value); - } else if (path == "joint_one/roll") { - set_joint_one_roll(Math::deg_to_rad(real_t(p_value))); - } else if (path == "joint_two/bone_name") { - set_joint_two_bone_name(p_value); - } else if (path == "joint_two/bone_idx") { - set_joint_two_bone_idx(p_value); - } else if (path == "joint_two/roll") { - set_joint_two_roll(Math::deg_to_rad(real_t(p_value))); - } - - return true; -} - -bool SkeletonModification3DTwoBoneIK::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path == "use_tip_node") { - r_ret = get_use_tip_node(); - } else if (path == "tip_node") { - r_ret = get_tip_node(); - } else if (path == "auto_calculate_joint_length") { - r_ret = get_auto_calculate_joint_length(); - } else if (path == "use_pole_node") { - r_ret = get_use_pole_node(); - } else if (path == "pole_node") { - r_ret = get_pole_node(); - } else if (path == "joint_one_length") { - r_ret = get_joint_one_length(); - } else if (path == "joint_two_length") { - r_ret = get_joint_two_length(); - } else if (path == "joint_one/bone_name") { - r_ret = get_joint_one_bone_name(); - } else if (path == "joint_one/bone_idx") { - r_ret = get_joint_one_bone_idx(); - } else if (path == "joint_one/roll") { - r_ret = Math::rad_to_deg(get_joint_one_roll()); - } else if (path == "joint_two/bone_name") { - r_ret = get_joint_two_bone_name(); - } else if (path == "joint_two/bone_idx") { - r_ret = get_joint_two_bone_idx(); - } else if (path == "joint_two/roll") { - r_ret = Math::rad_to_deg(get_joint_two_roll()); - } - - return true; -} - -void SkeletonModification3DTwoBoneIK::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back(PropertyInfo(Variant::BOOL, "use_tip_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (use_tip_node) { - p_list->push_back(PropertyInfo(Variant::NODE_PATH, "tip_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D", PROPERTY_USAGE_DEFAULT)); - } - - p_list->push_back(PropertyInfo(Variant::BOOL, "auto_calculate_joint_length", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (!auto_calculate_joint_length) { - p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_one_length", PROPERTY_HINT_RANGE, "-1, 10000, 0.001", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_two_length", PROPERTY_HINT_RANGE, "-1, 10000, 0.001", PROPERTY_USAGE_DEFAULT)); - } - - p_list->push_back(PropertyInfo(Variant::BOOL, "use_pole_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - if (use_pole_node) { - p_list->push_back(PropertyInfo(Variant::NODE_PATH, "pole_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D", PROPERTY_USAGE_DEFAULT)); - } - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, "joint_one/bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, "joint_one/bone_idx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_one/roll", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT)); - - p_list->push_back(PropertyInfo(Variant::STRING_NAME, "joint_two/bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::INT, "joint_two/bone_idx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT)); - p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_two/roll", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT)); -} - -void SkeletonModification3DTwoBoneIK::_execute(real_t p_delta) { - ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot execute!"); - - if (!enabled) { - return; - } - - if (_print_execution_error(joint_one_bone_idx < 0 || joint_two_bone_idx < 0, - "One (or more) of the bones in the modification have invalid bone indexes. Cannot execute modification!")) { - return; - } - - if (target_node_cache.is_null()) { - _print_execution_error(true, "Target cache is out of date. Attempting to update..."); - update_cache_target(); - return; - } - - // Update joint lengths (if needed) - if (auto_calculate_joint_length && (joint_one_length < 0 || joint_two_length < 0)) { - calculate_joint_lengths(); - } - - // Adopted from the links below: - // http://theorangeduck.com/page/simple-two-joint - // https://www.alanzucconi.com/2018/05/02/ik-2d-2/ - // With modifications by TwistedTwigleg - Node3D *target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache)); - if (_print_execution_error(!target || !target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) { - return; - } - Transform3D target_trans = stack->skeleton->world_transform_to_global_pose(target->get_global_transform()); - - Transform3D bone_one_trans; - Transform3D bone_two_trans; - - // Make the first joint look at the pole, and the second look at the target. That way, the - // TwoBoneIK solver has to really only handle extension/contraction, which should make it align with the pole. - if (use_pole_node) { - if (pole_node_cache.is_null()) { - _print_execution_error(true, "Pole cache is out of date. Attempting to update..."); - update_cache_pole(); - return; - } - - Node3D *pole = Object::cast_to<Node3D>(ObjectDB::get_instance(pole_node_cache)); - if (_print_execution_error(!pole || !pole->is_inside_tree(), "Pole node is not in the scene tree. Cannot execute modification!")) { - return; - } - Transform3D pole_trans = stack->skeleton->world_transform_to_global_pose(pole->get_global_transform()); - - Transform3D bone_one_local_pos = stack->skeleton->get_bone_local_pose_override(joint_one_bone_idx); - if (bone_one_local_pos == Transform3D()) { - bone_one_local_pos = stack->skeleton->get_bone_pose(joint_one_bone_idx); - } - Transform3D bone_two_local_pos = stack->skeleton->get_bone_local_pose_override(joint_two_bone_idx); - if (bone_two_local_pos == Transform3D()) { - bone_two_local_pos = stack->skeleton->get_bone_pose(joint_two_bone_idx); - } - - bone_one_trans = stack->skeleton->local_pose_to_global_pose(joint_one_bone_idx, bone_one_local_pos); - bone_one_trans = bone_one_trans.looking_at(pole_trans.origin, Vector3(0, 1, 0)); - bone_one_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(joint_one_bone_idx, bone_one_trans.basis); - stack->skeleton->update_bone_rest_forward_vector(joint_one_bone_idx); - bone_one_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_one_bone_idx), joint_one_roll); - stack->skeleton->set_bone_local_pose_override(joint_one_bone_idx, stack->skeleton->global_pose_to_local_pose(joint_one_bone_idx, bone_one_trans), stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_one_bone_idx); - - bone_two_trans = stack->skeleton->local_pose_to_global_pose(joint_two_bone_idx, bone_two_local_pos); - bone_two_trans = bone_two_trans.looking_at(target_trans.origin, Vector3(0, 1, 0)); - bone_two_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(joint_two_bone_idx, bone_two_trans.basis); - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - bone_two_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx), joint_two_roll); - stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, stack->skeleton->global_pose_to_local_pose(joint_two_bone_idx, bone_two_trans), stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_two_bone_idx); - } else { - Transform3D bone_one_local_pos = stack->skeleton->get_bone_local_pose_override(joint_one_bone_idx); - if (bone_one_local_pos == Transform3D()) { - bone_one_local_pos = stack->skeleton->get_bone_pose(joint_one_bone_idx); - } - Transform3D bone_two_local_pos = stack->skeleton->get_bone_local_pose_override(joint_two_bone_idx); - if (bone_two_local_pos == Transform3D()) { - bone_two_local_pos = stack->skeleton->get_bone_pose(joint_two_bone_idx); - } - - bone_one_trans = stack->skeleton->local_pose_to_global_pose(joint_one_bone_idx, bone_one_local_pos); - bone_two_trans = stack->skeleton->local_pose_to_global_pose(joint_two_bone_idx, bone_two_local_pos); - } - - Transform3D bone_two_tip_trans; - if (use_tip_node) { - if (tip_node_cache.is_null()) { - _print_execution_error(true, "Tip cache is out of date. Attempting to update..."); - update_cache_tip(); - return; - } - Node3D *tip = Object::cast_to<Node3D>(ObjectDB::get_instance(tip_node_cache)); - if (_print_execution_error(!tip || !tip->is_inside_tree(), "Tip node is not in the scene tree. Cannot execute modification!")) { - return; - } - bone_two_tip_trans = stack->skeleton->world_transform_to_global_pose(tip->get_global_transform()); - } else { - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - bone_two_tip_trans = bone_two_trans; - bone_two_tip_trans.origin += bone_two_trans.basis.xform(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx)).normalized() * joint_two_length; - } - - real_t joint_one_to_target_length = bone_one_trans.origin.distance_to(target_trans.origin); - if (joint_one_length + joint_two_length < joint_one_to_target_length) { - // Set the target *just* out of reach to straighten the bones - joint_one_to_target_length = joint_one_length + joint_two_length + 0.01; - } else if (joint_one_to_target_length < joint_one_length) { - // Place the target in reach so the solver doesn't do crazy things - joint_one_to_target_length = joint_one_length; - } - - // Get the square lengths for all three sides of the triangle we'll use to calculate the angles - real_t sqr_one_length = joint_one_length * joint_one_length; - real_t sqr_two_length = joint_two_length * joint_two_length; - real_t sqr_three_length = joint_one_to_target_length * joint_one_to_target_length; - - // Calculate the angles for the first joint using the law of cosigns - real_t ac_ab_0 = Math::acos(CLAMP(bone_two_tip_trans.origin.direction_to(bone_one_trans.origin).dot(bone_two_trans.origin.direction_to(bone_one_trans.origin)), -1, 1)); - real_t ac_at_0 = Math::acos(CLAMP(bone_one_trans.origin.direction_to(bone_two_tip_trans.origin).dot(bone_one_trans.origin.direction_to(target_trans.origin)), -1, 1)); - real_t ac_ab_1 = Math::acos(CLAMP((sqr_two_length - sqr_one_length - sqr_three_length) / (-2.0 * joint_one_length * joint_one_to_target_length), -1, 1)); - - // Calculate the angles of rotation. Angle 0 is the extension/contraction axis, while angle 1 is the rotation axis to align the triangle to the target - Vector3 axis_0 = bone_one_trans.origin.direction_to(bone_two_tip_trans.origin).cross(bone_one_trans.origin.direction_to(bone_two_trans.origin)); - Vector3 axis_1 = bone_one_trans.origin.direction_to(bone_two_tip_trans.origin).cross(bone_one_trans.origin.direction_to(target_trans.origin)); - - // Make a quaternion with the delta rotation needed to rotate the first joint into alignment and apply it to the transform. - Quaternion bone_one_quat = bone_one_trans.basis.get_rotation_quaternion(); - Quaternion rot_0 = Quaternion(bone_one_quat.inverse().xform(axis_0).normalized(), (ac_ab_1 - ac_ab_0)); - Quaternion rot_2 = Quaternion(bone_one_quat.inverse().xform(axis_1).normalized(), ac_at_0); - bone_one_trans.basis.set_quaternion(bone_one_quat * (rot_0 * rot_2)); - - stack->skeleton->update_bone_rest_forward_vector(joint_one_bone_idx); - bone_one_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_one_bone_idx), joint_one_roll); - - // Apply the rotation to the first joint - bone_one_trans = stack->skeleton->global_pose_to_local_pose(joint_one_bone_idx, bone_one_trans); - bone_one_trans.origin = Vector3(0, 0, 0); - stack->skeleton->set_bone_local_pose_override(joint_one_bone_idx, bone_one_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_one_bone_idx); - - if (use_pole_node) { - // Update bone_two_trans so its at the latest position, with the rotation of bone_one_trans taken into account, then look at the target. - bone_two_trans = stack->skeleton->local_pose_to_global_pose(joint_two_bone_idx, stack->skeleton->get_bone_local_pose_override(joint_two_bone_idx)); - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx); - bone_two_trans.basis.rotate_to_align(forward_vector, bone_two_trans.origin.direction_to(target_trans.origin)); - - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - bone_two_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx), joint_two_roll); - - bone_two_trans = stack->skeleton->global_pose_to_local_pose(joint_two_bone_idx, bone_two_trans); - stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, bone_two_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_two_bone_idx); - } else { - // Calculate the angles for the second joint using the law of cosigns, make a quaternion with the delta rotation needed to rotate the joint into - // alignment, and then apply it to the second joint. - real_t ba_bc_0 = Math::acos(CLAMP(bone_two_trans.origin.direction_to(bone_one_trans.origin).dot(bone_two_trans.origin.direction_to(bone_two_tip_trans.origin)), -1, 1)); - real_t ba_bc_1 = Math::acos(CLAMP((sqr_three_length - sqr_one_length - sqr_two_length) / (-2.0 * joint_one_length * joint_two_length), -1, 1)); - Quaternion bone_two_quat = bone_two_trans.basis.get_rotation_quaternion(); - Quaternion rot_1 = Quaternion(bone_two_quat.inverse().xform(axis_0).normalized(), (ba_bc_1 - ba_bc_0)); - bone_two_trans.basis.set_quaternion(bone_two_quat * rot_1); - - stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx); - bone_two_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx), joint_two_roll); - - bone_two_trans = stack->skeleton->global_pose_to_local_pose(joint_two_bone_idx, bone_two_trans); - bone_two_trans.origin = Vector3(0, 0, 0); - stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, bone_two_trans, stack->strength, true); - stack->skeleton->force_update_bone_children_transforms(joint_two_bone_idx); - } -} - -void SkeletonModification3DTwoBoneIK::_setup_modification(SkeletonModificationStack3D *p_stack) { - stack = p_stack; - - if (stack != nullptr) { - is_setup = true; - execution_error_found = false; - update_cache_target(); - update_cache_tip(); - } -} - -void SkeletonModification3DTwoBoneIK::update_cache_target() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update target cache: modification is not properly setup!"); - return; - } - - target_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree() && target_node.is_empty() == false) { - if (stack->skeleton->has_node(target_node)) { - Node *node = stack->skeleton->get_node(target_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update target cache: Target node is this modification's skeleton or cannot be found. Cannot execute modification"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update target cache: Target node is not in the scene tree. Cannot execute modification!"); - target_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DTwoBoneIK::update_cache_tip() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update tip cache: modification is not properly setup!"); - return; - } - - tip_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(tip_node)) { - Node *node = stack->skeleton->get_node(tip_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update tip cache: Tip node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update tip cache: Tip node is not in the scene tree. Cannot execute modification!"); - tip_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DTwoBoneIK::update_cache_pole() { - if (!is_setup || !stack) { - _print_execution_error(true, "Cannot update pole cache: modification is not properly setup!"); - return; - } - - pole_node_cache = ObjectID(); - if (stack->skeleton) { - if (stack->skeleton->is_inside_tree()) { - if (stack->skeleton->has_node(pole_node)) { - Node *node = stack->skeleton->get_node(pole_node); - ERR_FAIL_COND_MSG(!node || stack->skeleton == node, - "Cannot update pole cache: Pole node is this modification's skeleton or cannot be found!"); - ERR_FAIL_COND_MSG(!node->is_inside_tree(), - "Cannot update pole cache: Pole node is not in the scene tree. Cannot execute modification!"); - pole_node_cache = node->get_instance_id(); - - execution_error_found = false; - } - } - } -} - -void SkeletonModification3DTwoBoneIK::set_target_node(const NodePath &p_target_node) { - target_node = p_target_node; - update_cache_target(); -} - -NodePath SkeletonModification3DTwoBoneIK::get_target_node() const { - return target_node; -} - -void SkeletonModification3DTwoBoneIK::set_use_tip_node(const bool p_use_tip_node) { - use_tip_node = p_use_tip_node; - notify_property_list_changed(); -} - -bool SkeletonModification3DTwoBoneIK::get_use_tip_node() const { - return use_tip_node; -} - -void SkeletonModification3DTwoBoneIK::set_tip_node(const NodePath &p_tip_node) { - tip_node = p_tip_node; - update_cache_tip(); -} - -NodePath SkeletonModification3DTwoBoneIK::get_tip_node() const { - return tip_node; -} - -void SkeletonModification3DTwoBoneIK::set_use_pole_node(const bool p_use_pole_node) { - use_pole_node = p_use_pole_node; - notify_property_list_changed(); -} - -bool SkeletonModification3DTwoBoneIK::get_use_pole_node() const { - return use_pole_node; -} - -void SkeletonModification3DTwoBoneIK::set_pole_node(const NodePath &p_pole_node) { - pole_node = p_pole_node; - update_cache_pole(); -} - -NodePath SkeletonModification3DTwoBoneIK::get_pole_node() const { - return pole_node; -} - -void SkeletonModification3DTwoBoneIK::set_auto_calculate_joint_length(bool p_calculate) { - auto_calculate_joint_length = p_calculate; - if (p_calculate) { - calculate_joint_lengths(); - } - notify_property_list_changed(); -} - -bool SkeletonModification3DTwoBoneIK::get_auto_calculate_joint_length() const { - return auto_calculate_joint_length; -} - -void SkeletonModification3DTwoBoneIK::calculate_joint_lengths() { - if (!is_setup) { - return; // fail silently, as we likely just loaded the scene. - } - ERR_FAIL_COND_MSG(!stack || stack->skeleton == nullptr, - "Modification is not setup and therefore cannot calculate joint lengths!"); - ERR_FAIL_COND_MSG(joint_one_bone_idx <= -1 || joint_two_bone_idx <= -1, - "One of the bones in the TwoBoneIK modification are not set! Cannot calculate joint lengths!"); - - Transform3D bone_one_rest_trans = stack->skeleton->get_bone_global_pose(joint_one_bone_idx); - Transform3D bone_two_rest_trans = stack->skeleton->get_bone_global_pose(joint_two_bone_idx); - - joint_one_length = bone_one_rest_trans.origin.distance_to(bone_two_rest_trans.origin); - - if (use_tip_node) { - if (tip_node_cache.is_null()) { - update_cache_tip(); - WARN_PRINT("Tip cache is out of date. Updating..."); - } - - Node3D *tip = Object::cast_to<Node3D>(ObjectDB::get_instance(tip_node_cache)); - if (tip) { - Transform3D bone_tip_trans = stack->skeleton->world_transform_to_global_pose(tip->get_global_transform()); - joint_two_length = bone_two_rest_trans.origin.distance_to(bone_tip_trans.origin); - } - } else { - // Attempt to use children bones to get the length - Vector<int> bone_two_children = stack->skeleton->get_bone_children(joint_two_bone_idx); - if (bone_two_children.size() > 0) { - joint_two_length = 0; - for (int i = 0; i < bone_two_children.size(); i++) { - joint_two_length += bone_two_rest_trans.origin.distance_to( - stack->skeleton->get_bone_global_pose(bone_two_children[i]).origin); - } - joint_two_length = joint_two_length / bone_two_children.size(); - } else { - WARN_PRINT("TwoBoneIK modification: Cannot auto calculate length for joint 2! Auto setting the length to 1..."); - joint_two_length = 1.0; - } - } - execution_error_found = false; -} - -void SkeletonModification3DTwoBoneIK::set_joint_one_bone_name(String p_bone_name) { - joint_one_bone_name = p_bone_name; - if (stack && stack->skeleton) { - joint_one_bone_idx = stack->skeleton->find_bone(p_bone_name); - } - execution_error_found = false; - notify_property_list_changed(); -} - -String SkeletonModification3DTwoBoneIK::get_joint_one_bone_name() const { - return joint_one_bone_name; -} - -void SkeletonModification3DTwoBoneIK::set_joint_one_bone_idx(int p_bone_idx) { - joint_one_bone_idx = p_bone_idx; - if (stack && stack->skeleton) { - joint_one_bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DTwoBoneIK::get_joint_one_bone_idx() const { - return joint_one_bone_idx; -} - -void SkeletonModification3DTwoBoneIK::set_joint_one_length(real_t p_length) { - joint_one_length = p_length; -} - -real_t SkeletonModification3DTwoBoneIK::get_joint_one_length() const { - return joint_one_length; -} - -void SkeletonModification3DTwoBoneIK::set_joint_two_bone_name(String p_bone_name) { - joint_two_bone_name = p_bone_name; - if (stack && stack->skeleton) { - joint_two_bone_idx = stack->skeleton->find_bone(p_bone_name); - } - execution_error_found = false; - notify_property_list_changed(); -} - -String SkeletonModification3DTwoBoneIK::get_joint_two_bone_name() const { - return joint_two_bone_name; -} - -void SkeletonModification3DTwoBoneIK::set_joint_two_bone_idx(int p_bone_idx) { - joint_two_bone_idx = p_bone_idx; - if (stack && stack->skeleton) { - joint_two_bone_name = stack->skeleton->get_bone_name(p_bone_idx); - } - execution_error_found = false; - notify_property_list_changed(); -} - -int SkeletonModification3DTwoBoneIK::get_joint_two_bone_idx() const { - return joint_two_bone_idx; -} - -void SkeletonModification3DTwoBoneIK::set_joint_two_length(real_t p_length) { - joint_two_length = p_length; -} - -real_t SkeletonModification3DTwoBoneIK::get_joint_two_length() const { - return joint_two_length; -} - -void SkeletonModification3DTwoBoneIK::set_joint_one_roll(real_t p_roll) { - joint_one_roll = p_roll; -} - -real_t SkeletonModification3DTwoBoneIK::get_joint_one_roll() const { - return joint_one_roll; -} - -void SkeletonModification3DTwoBoneIK::set_joint_two_roll(real_t p_roll) { - joint_two_roll = p_roll; -} - -real_t SkeletonModification3DTwoBoneIK::get_joint_two_roll() const { - return joint_two_roll; -} - -void SkeletonModification3DTwoBoneIK::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DTwoBoneIK::set_target_node); - ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DTwoBoneIK::get_target_node); - - ClassDB::bind_method(D_METHOD("set_use_pole_node", "use_pole_node"), &SkeletonModification3DTwoBoneIK::set_use_pole_node); - ClassDB::bind_method(D_METHOD("get_use_pole_node"), &SkeletonModification3DTwoBoneIK::get_use_pole_node); - ClassDB::bind_method(D_METHOD("set_pole_node", "pole_nodepath"), &SkeletonModification3DTwoBoneIK::set_pole_node); - ClassDB::bind_method(D_METHOD("get_pole_node"), &SkeletonModification3DTwoBoneIK::get_pole_node); - - ClassDB::bind_method(D_METHOD("set_use_tip_node", "use_tip_node"), &SkeletonModification3DTwoBoneIK::set_use_tip_node); - ClassDB::bind_method(D_METHOD("get_use_tip_node"), &SkeletonModification3DTwoBoneIK::get_use_tip_node); - ClassDB::bind_method(D_METHOD("set_tip_node", "tip_nodepath"), &SkeletonModification3DTwoBoneIK::set_tip_node); - ClassDB::bind_method(D_METHOD("get_tip_node"), &SkeletonModification3DTwoBoneIK::get_tip_node); - - ClassDB::bind_method(D_METHOD("set_auto_calculate_joint_length", "auto_calculate_joint_length"), &SkeletonModification3DTwoBoneIK::set_auto_calculate_joint_length); - ClassDB::bind_method(D_METHOD("get_auto_calculate_joint_length"), &SkeletonModification3DTwoBoneIK::get_auto_calculate_joint_length); - - ClassDB::bind_method(D_METHOD("set_joint_one_bone_name", "bone_name"), &SkeletonModification3DTwoBoneIK::set_joint_one_bone_name); - ClassDB::bind_method(D_METHOD("get_joint_one_bone_name"), &SkeletonModification3DTwoBoneIK::get_joint_one_bone_name); - ClassDB::bind_method(D_METHOD("set_joint_one_bone_idx", "bone_idx"), &SkeletonModification3DTwoBoneIK::set_joint_one_bone_idx); - ClassDB::bind_method(D_METHOD("get_joint_one_bone_idx"), &SkeletonModification3DTwoBoneIK::get_joint_one_bone_idx); - ClassDB::bind_method(D_METHOD("set_joint_one_length", "bone_length"), &SkeletonModification3DTwoBoneIK::set_joint_one_length); - ClassDB::bind_method(D_METHOD("get_joint_one_length"), &SkeletonModification3DTwoBoneIK::get_joint_one_length); - - ClassDB::bind_method(D_METHOD("set_joint_two_bone_name", "bone_name"), &SkeletonModification3DTwoBoneIK::set_joint_two_bone_name); - ClassDB::bind_method(D_METHOD("get_joint_two_bone_name"), &SkeletonModification3DTwoBoneIK::get_joint_two_bone_name); - ClassDB::bind_method(D_METHOD("set_joint_two_bone_idx", "bone_idx"), &SkeletonModification3DTwoBoneIK::set_joint_two_bone_idx); - ClassDB::bind_method(D_METHOD("get_joint_two_bone_idx"), &SkeletonModification3DTwoBoneIK::get_joint_two_bone_idx); - ClassDB::bind_method(D_METHOD("set_joint_two_length", "bone_length"), &SkeletonModification3DTwoBoneIK::set_joint_two_length); - ClassDB::bind_method(D_METHOD("get_joint_two_length"), &SkeletonModification3DTwoBoneIK::get_joint_two_length); - - ClassDB::bind_method(D_METHOD("set_joint_one_roll", "roll"), &SkeletonModification3DTwoBoneIK::set_joint_one_roll); - ClassDB::bind_method(D_METHOD("get_joint_one_roll"), &SkeletonModification3DTwoBoneIK::get_joint_one_roll); - ClassDB::bind_method(D_METHOD("set_joint_two_roll", "roll"), &SkeletonModification3DTwoBoneIK::set_joint_two_roll); - ClassDB::bind_method(D_METHOD("get_joint_two_roll"), &SkeletonModification3DTwoBoneIK::get_joint_two_roll); - - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node"); - ADD_GROUP("", ""); -} - -SkeletonModification3DTwoBoneIK::SkeletonModification3DTwoBoneIK() { - stack = nullptr; - is_setup = false; -} - -SkeletonModification3DTwoBoneIK::~SkeletonModification3DTwoBoneIK() { -} diff --git a/scene/resources/skeleton_modification_3d_twoboneik.h b/scene/resources/skeleton_modification_3d_twoboneik.h deleted file mode 100644 index 57481e0181..0000000000 --- a/scene/resources/skeleton_modification_3d_twoboneik.h +++ /dev/null @@ -1,118 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_3d_twoboneik.h */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#ifndef SKELETON_MODIFICATION_3D_TWOBONEIK_H -#define SKELETON_MODIFICATION_3D_TWOBONEIK_H - -#include "scene/3d/skeleton_3d.h" -#include "scene/resources/skeleton_modification_3d.h" - -class SkeletonModification3DTwoBoneIK : public SkeletonModification3D { - GDCLASS(SkeletonModification3DTwoBoneIK, SkeletonModification3D); - -private: - NodePath target_node; - ObjectID target_node_cache; - - bool use_tip_node = false; - NodePath tip_node; - ObjectID tip_node_cache; - - bool use_pole_node = false; - NodePath pole_node; - ObjectID pole_node_cache; - - String joint_one_bone_name = ""; - int joint_one_bone_idx = -1; - String joint_two_bone_name = ""; - int joint_two_bone_idx = -1; - - bool auto_calculate_joint_length = false; - real_t joint_one_length = -1; - real_t joint_two_length = -1; - - real_t joint_one_roll = 0; - real_t joint_two_roll = 0; - - void update_cache_target(); - void update_cache_tip(); - void update_cache_pole(); - -protected: - static void _bind_methods(); - bool _get(const StringName &p_path, Variant &r_ret) const; - bool _set(const StringName &p_path, const Variant &p_value); - void _get_property_list(List<PropertyInfo> *p_list) const; - -public: - virtual void _execute(real_t p_delta) override; - virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override; - - void set_target_node(const NodePath &p_target_node); - NodePath get_target_node() const; - - void set_use_tip_node(const bool p_use_tip_node); - bool get_use_tip_node() const; - void set_tip_node(const NodePath &p_tip_node); - NodePath get_tip_node() const; - - void set_use_pole_node(const bool p_use_pole_node); - bool get_use_pole_node() const; - void set_pole_node(const NodePath &p_pole_node); - NodePath get_pole_node() const; - - void set_auto_calculate_joint_length(bool p_calculate); - bool get_auto_calculate_joint_length() const; - void calculate_joint_lengths(); - - void set_joint_one_bone_name(String p_bone_name); - String get_joint_one_bone_name() const; - void set_joint_one_bone_idx(int p_bone_idx); - int get_joint_one_bone_idx() const; - void set_joint_one_length(real_t p_length); - real_t get_joint_one_length() const; - - void set_joint_two_bone_name(String p_bone_name); - String get_joint_two_bone_name() const; - void set_joint_two_bone_idx(int p_bone_idx); - int get_joint_two_bone_idx() const; - void set_joint_two_length(real_t p_length); - real_t get_joint_two_length() const; - - void set_joint_one_roll(real_t p_roll); - real_t get_joint_one_roll() const; - void set_joint_two_roll(real_t p_roll); - real_t get_joint_two_roll() const; - - SkeletonModification3DTwoBoneIK(); - ~SkeletonModification3DTwoBoneIK(); -}; - -#endif // SKELETON_MODIFICATION_3D_TWOBONEIK_H diff --git a/scene/resources/skeleton_modification_stack_3d.cpp b/scene/resources/skeleton_modification_stack_3d.cpp deleted file mode 100644 index 32708e198a..0000000000 --- a/scene/resources/skeleton_modification_stack_3d.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/**************************************************************************/ -/* skeleton_modification_stack_3d.cpp */ -/**************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/**************************************************************************/ -/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ -/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/**************************************************************************/ - -#include "skeleton_modification_stack_3d.h" -#include "scene/3d/skeleton_3d.h" - -/////////////////////////////////////// -// ModificationStack3D -/////////////////////////////////////// - -void SkeletonModificationStack3D::_get_property_list(List<PropertyInfo> *p_list) const { - for (uint32_t i = 0; i < modifications.size(); i++) { - p_list->push_back( - PropertyInfo(Variant::OBJECT, "modifications/" + itos(i), - PROPERTY_HINT_RESOURCE_TYPE, - "SkeletonModification3D", - PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE)); - } -} - -bool SkeletonModificationStack3D::_set(const StringName &p_path, const Variant &p_value) { - String path = p_path; - - if (path.begins_with("modifications/")) { - int mod_idx = path.get_slicec('/', 1).to_int(); - set_modification(mod_idx, p_value); - return true; - } - return true; -} - -bool SkeletonModificationStack3D::_get(const StringName &p_path, Variant &r_ret) const { - String path = p_path; - - if (path.begins_with("modifications/")) { - int mod_idx = path.get_slicec('/', 1).to_int(); - r_ret = get_modification(mod_idx); - return true; - } - return true; -} - -void SkeletonModificationStack3D::setup() { - if (is_setup) { - return; - } - - if (skeleton != nullptr) { - is_setup = true; - for (uint32_t i = 0; i < modifications.size(); i++) { - if (!modifications[i].is_valid()) { - continue; - } - modifications[i]->_setup_modification(this); - } - } else { - WARN_PRINT("Cannot setup SkeletonModificationStack3D: no skeleton set!"); - } -} - -void SkeletonModificationStack3D::execute(real_t p_delta, int p_execution_mode) { - ERR_FAIL_COND_MSG(!is_setup || skeleton == nullptr || is_queued_for_deletion(), - "Modification stack is not properly setup and therefore cannot execute!"); - - if (!skeleton->is_inside_tree()) { - ERR_PRINT_ONCE("Skeleton is not inside SceneTree! Cannot execute modification!"); - return; - } - - if (!enabled) { - return; - } - - for (uint32_t i = 0; i < modifications.size(); i++) { - if (!modifications[i].is_valid()) { - continue; - } - - if (modifications[i]->get_execution_mode() == p_execution_mode) { - modifications[i]->_execute(p_delta); - } - } -} - -void SkeletonModificationStack3D::enable_all_modifications(bool p_enabled) { - for (uint32_t i = 0; i < modifications.size(); i++) { - if (!modifications[i].is_valid()) { - continue; - } - modifications[i]->set_enabled(p_enabled); - } -} - -Ref<SkeletonModification3D> SkeletonModificationStack3D::get_modification(int p_mod_idx) const { - const int modifications_size = modifications.size(); - ERR_FAIL_INDEX_V(p_mod_idx, modifications_size, nullptr); - return modifications[p_mod_idx]; -} - -void SkeletonModificationStack3D::add_modification(Ref<SkeletonModification3D> p_mod) { - ERR_FAIL_NULL(p_mod); - p_mod->_setup_modification(this); - modifications.push_back(p_mod); -} - -void SkeletonModificationStack3D::delete_modification(int p_mod_idx) { - const int modifications_size = modifications.size(); - ERR_FAIL_INDEX(p_mod_idx, modifications_size); - modifications.remove_at(p_mod_idx); -} - -void SkeletonModificationStack3D::set_modification(int p_mod_idx, Ref<SkeletonModification3D> p_mod) { - const int modifications_size = modifications.size(); - ERR_FAIL_INDEX(p_mod_idx, modifications_size); - - if (p_mod == nullptr) { - modifications.remove_at(p_mod_idx); - } else { - p_mod->_setup_modification(this); - modifications[p_mod_idx] = p_mod; - } -} - -void SkeletonModificationStack3D::set_modification_count(int p_count) { - ERR_FAIL_COND_MSG(p_count < 0, "Modification count cannot be less than zero."); - modifications.resize(p_count); - notify_property_list_changed(); -} - -int SkeletonModificationStack3D::get_modification_count() const { - return modifications.size(); -} - -void SkeletonModificationStack3D::set_skeleton(Skeleton3D *p_skeleton) { - skeleton = p_skeleton; -} - -Skeleton3D *SkeletonModificationStack3D::get_skeleton() const { - return skeleton; -} - -bool SkeletonModificationStack3D::get_is_setup() const { - return is_setup; -} - -void SkeletonModificationStack3D::set_enabled(bool p_enabled) { - enabled = p_enabled; - - if (!enabled && is_setup && skeleton != nullptr) { - skeleton->clear_bones_local_pose_override(); - } -} - -bool SkeletonModificationStack3D::get_enabled() const { - return enabled; -} - -void SkeletonModificationStack3D::set_strength(real_t p_strength) { - ERR_FAIL_COND_MSG(p_strength < 0, "Strength cannot be less than zero!"); - ERR_FAIL_COND_MSG(p_strength > 1, "Strength cannot be more than one!"); - strength = p_strength; -} - -real_t SkeletonModificationStack3D::get_strength() const { - return strength; -} - -void SkeletonModificationStack3D::_bind_methods() { - ClassDB::bind_method(D_METHOD("setup"), &SkeletonModificationStack3D::setup); - ClassDB::bind_method(D_METHOD("execute", "delta", "execution_mode"), &SkeletonModificationStack3D::execute); - - ClassDB::bind_method(D_METHOD("enable_all_modifications", "enabled"), &SkeletonModificationStack3D::enable_all_modifications); - ClassDB::bind_method(D_METHOD("get_modification", "mod_idx"), &SkeletonModificationStack3D::get_modification); - ClassDB::bind_method(D_METHOD("add_modification", "modification"), &SkeletonModificationStack3D::add_modification); - ClassDB::bind_method(D_METHOD("delete_modification", "mod_idx"), &SkeletonModificationStack3D::delete_modification); - ClassDB::bind_method(D_METHOD("set_modification", "mod_idx", "modification"), &SkeletonModificationStack3D::set_modification); - - ClassDB::bind_method(D_METHOD("set_modification_count", "count"), &SkeletonModificationStack3D::set_modification_count); - ClassDB::bind_method(D_METHOD("get_modification_count"), &SkeletonModificationStack3D::get_modification_count); - - ClassDB::bind_method(D_METHOD("get_is_setup"), &SkeletonModificationStack3D::get_is_setup); - - ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &SkeletonModificationStack3D::set_enabled); - ClassDB::bind_method(D_METHOD("get_enabled"), &SkeletonModificationStack3D::get_enabled); - - ClassDB::bind_method(D_METHOD("set_strength", "strength"), &SkeletonModificationStack3D::set_strength); - ClassDB::bind_method(D_METHOD("get_strength"), &SkeletonModificationStack3D::get_strength); - - ClassDB::bind_method(D_METHOD("get_skeleton"), &SkeletonModificationStack3D::get_skeleton); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "get_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "strength", PROPERTY_HINT_RANGE, "0, 1, 0.001"), "set_strength", "get_strength"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "modification_count", PROPERTY_HINT_RANGE, "0, 100, 1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_ARRAY, "Modifications,modifications/"), "set_modification_count", "get_modification_count"); -} - -SkeletonModificationStack3D::SkeletonModificationStack3D() { -} diff --git a/scene/resources/style_box.cpp b/scene/resources/style_box.cpp index 6390850b24..4f16986392 100644 --- a/scene/resources/style_box.cpp +++ b/scene/resources/style_box.cpp @@ -34,76 +34,65 @@ #include <limits.h> -float StyleBox::get_style_margin(Side p_side) const { - float ret = 0; - GDVIRTUAL_REQUIRED_CALL(_get_style_margin, p_side, ret); - return ret; -} +Size2 StyleBox::get_minimum_size() const { + Size2 min_size = Size2(get_margin(SIDE_LEFT) + get_margin(SIDE_RIGHT), get_margin(SIDE_TOP) + get_margin(SIDE_BOTTOM)); + Size2 custom_size; + GDVIRTUAL_CALL(_get_minimum_size, custom_size); -bool StyleBox::test_mask(const Point2 &p_point, const Rect2 &p_rect) const { - bool ret = true; - GDVIRTUAL_CALL(_test_mask, p_point, p_rect, ret); - return ret; -} + if (min_size.x < custom_size.x) { + min_size.x = custom_size.x; + } + if (min_size.y < custom_size.y) { + min_size.y = custom_size.y; + } -void StyleBox::draw(RID p_canvas_item, const Rect2 &p_rect) const { - GDVIRTUAL_REQUIRED_CALL(_draw, p_canvas_item, p_rect); + return min_size; } -void StyleBox::set_default_margin(Side p_side, float p_value) { +void StyleBox::set_content_margin(Side p_side, float p_value) { ERR_FAIL_INDEX((int)p_side, 4); - margin[p_side] = p_value; + content_margin[p_side] = p_value; emit_changed(); } -void StyleBox::set_default_margin_all(float p_value) { +void StyleBox::set_content_margin_all(float p_value) { for (int i = 0; i < 4; i++) { - margin[i] = p_value; + content_margin[i] = p_value; } emit_changed(); } -void StyleBox::set_default_margin_individual(float p_left, float p_top, float p_right, float p_bottom) { - margin[SIDE_LEFT] = p_left; - margin[SIDE_TOP] = p_top; - margin[SIDE_RIGHT] = p_right; - margin[SIDE_BOTTOM] = p_bottom; +void StyleBox::set_content_margin_individual(float p_left, float p_top, float p_right, float p_bottom) { + content_margin[SIDE_LEFT] = p_left; + content_margin[SIDE_TOP] = p_top; + content_margin[SIDE_RIGHT] = p_right; + content_margin[SIDE_BOTTOM] = p_bottom; emit_changed(); } -float StyleBox::get_default_margin(Side p_side) const { +float StyleBox::get_content_margin(Side p_side) const { ERR_FAIL_INDEX_V((int)p_side, 4, 0.0); - return margin[p_side]; + return content_margin[p_side]; } float StyleBox::get_margin(Side p_side) const { ERR_FAIL_INDEX_V((int)p_side, 4, 0.0); - if (margin[p_side] < 0) { + if (content_margin[p_side] < 0) { return get_style_margin(p_side); } else { - return margin[p_side]; + return content_margin[p_side]; } } -CanvasItem *StyleBox::get_current_item_drawn() const { - return CanvasItem::get_current_item_drawn(); -} - -Size2 StyleBox::get_minimum_size() const { - return Size2(get_margin(SIDE_LEFT) + get_margin(SIDE_RIGHT), get_margin(SIDE_TOP) + get_margin(SIDE_BOTTOM)); -} - Point2 StyleBox::get_offset() const { return Point2(get_margin(SIDE_LEFT), get_margin(SIDE_TOP)); } -Size2 StyleBox::get_center_size() const { - Size2 ret; - GDVIRTUAL_CALL(_get_center_size, ret); - return ret; +void StyleBox::draw(RID p_canvas_item, const Rect2 &p_rect) const { + GDVIRTUAL_REQUIRED_CALL(_draw, p_canvas_item, p_rect); } Rect2 StyleBox::get_draw_rect(const Rect2 &p_rect) const { @@ -114,37 +103,46 @@ Rect2 StyleBox::get_draw_rect(const Rect2 &p_rect) const { return p_rect; } +CanvasItem *StyleBox::get_current_item_drawn() const { + return CanvasItem::get_current_item_drawn(); +} + +bool StyleBox::test_mask(const Point2 &p_point, const Rect2 &p_rect) const { + bool ret = true; + GDVIRTUAL_CALL(_test_mask, p_point, p_rect, ret); + return ret; +} + void StyleBox::_bind_methods() { - ClassDB::bind_method(D_METHOD("test_mask", "point", "rect"), &StyleBox::test_mask); + ClassDB::bind_method(D_METHOD("get_minimum_size"), &StyleBox::get_minimum_size); - ClassDB::bind_method(D_METHOD("set_default_margin", "margin", "offset"), &StyleBox::set_default_margin); - ClassDB::bind_method(D_METHOD("set_default_margin_all", "offset"), &StyleBox::set_default_margin_all); - ClassDB::bind_method(D_METHOD("get_default_margin", "margin"), &StyleBox::get_default_margin); + ClassDB::bind_method(D_METHOD("set_content_margin", "margin", "offset"), &StyleBox::set_content_margin); + ClassDB::bind_method(D_METHOD("set_content_margin_all", "offset"), &StyleBox::set_content_margin_all); + ClassDB::bind_method(D_METHOD("get_content_margin", "margin"), &StyleBox::get_content_margin); ClassDB::bind_method(D_METHOD("get_margin", "margin"), &StyleBox::get_margin); - ClassDB::bind_method(D_METHOD("get_minimum_size"), &StyleBox::get_minimum_size); - ClassDB::bind_method(D_METHOD("get_center_size"), &StyleBox::get_center_size); ClassDB::bind_method(D_METHOD("get_offset"), &StyleBox::get_offset); - ClassDB::bind_method(D_METHOD("get_current_item_drawn"), &StyleBox::get_current_item_drawn); ClassDB::bind_method(D_METHOD("draw", "canvas_item", "rect"), &StyleBox::draw); + ClassDB::bind_method(D_METHOD("get_current_item_drawn"), &StyleBox::get_current_item_drawn); + + ClassDB::bind_method(D_METHOD("test_mask", "point", "rect"), &StyleBox::test_mask); ADD_GROUP("Content Margins", "content_margin_"); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_left", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_default_margin", "get_default_margin", SIDE_LEFT); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_top", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_default_margin", "get_default_margin", SIDE_TOP); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_right", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_default_margin", "get_default_margin", SIDE_RIGHT); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_bottom", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_default_margin", "get_default_margin", SIDE_BOTTOM); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_left", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_content_margin", "get_content_margin", SIDE_LEFT); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_top", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_content_margin", "get_content_margin", SIDE_TOP); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_right", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_content_margin", "get_content_margin", SIDE_RIGHT); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_bottom", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_content_margin", "get_content_margin", SIDE_BOTTOM); - GDVIRTUAL_BIND(_get_style_margin, "side") - GDVIRTUAL_BIND(_test_mask, "point", "rect") - GDVIRTUAL_BIND(_get_center_size) - GDVIRTUAL_BIND(_get_draw_rect, "rect") GDVIRTUAL_BIND(_draw, "to_canvas_item", "rect") + GDVIRTUAL_BIND(_get_draw_rect, "rect") + GDVIRTUAL_BIND(_get_minimum_size) + GDVIRTUAL_BIND(_test_mask, "point", "rect") } StyleBox::StyleBox() { for (int i = 0; i < 4; i++) { - margin[i] = -1; + content_margin[i] = -1; } } @@ -165,38 +163,38 @@ Ref<Texture2D> StyleBoxTexture::get_texture() const { return texture; } -void StyleBoxTexture::set_margin_size(Side p_side, float p_size) { +void StyleBoxTexture::set_texture_margin(Side p_side, float p_size) { ERR_FAIL_INDEX((int)p_side, 4); - margin[p_side] = p_size; + texture_margin[p_side] = p_size; emit_changed(); } -void StyleBoxTexture::set_margin_size_all(float p_size) { +void StyleBoxTexture::set_texture_margin_all(float p_size) { for (int i = 0; i < 4; i++) { - margin[i] = p_size; + texture_margin[i] = p_size; } emit_changed(); } -void StyleBoxTexture::set_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom) { - margin[SIDE_LEFT] = p_left; - margin[SIDE_TOP] = p_top; - margin[SIDE_RIGHT] = p_right; - margin[SIDE_BOTTOM] = p_bottom; +void StyleBoxTexture::set_texture_margin_individual(float p_left, float p_top, float p_right, float p_bottom) { + texture_margin[SIDE_LEFT] = p_left; + texture_margin[SIDE_TOP] = p_top; + texture_margin[SIDE_RIGHT] = p_right; + texture_margin[SIDE_BOTTOM] = p_bottom; emit_changed(); } -float StyleBoxTexture::get_margin_size(Side p_side) const { +float StyleBoxTexture::get_texture_margin(Side p_side) const { ERR_FAIL_INDEX_V((int)p_side, 4, 0.0); - return margin[p_side]; + return texture_margin[p_side]; } float StyleBoxTexture::get_style_margin(Side p_side) const { ERR_FAIL_INDEX_V((int)p_side, 4, 0.0); - return margin[p_side]; + return texture_margin[p_side]; } Rect2 StyleBoxTexture::get_draw_rect(const Rect2 &p_rect) const { @@ -218,7 +216,10 @@ void StyleBoxTexture::draw(RID p_canvas_item, const Rect2 &p_rect) const { rect.size.x += expand_margin[SIDE_LEFT] + expand_margin[SIDE_RIGHT]; rect.size.y += expand_margin[SIDE_TOP] + expand_margin[SIDE_BOTTOM]; - RenderingServer::get_singleton()->canvas_item_add_nine_patch(p_canvas_item, rect, src_rect, texture->get_rid(), Vector2(margin[SIDE_LEFT], margin[SIDE_TOP]), Vector2(margin[SIDE_RIGHT], margin[SIDE_BOTTOM]), RS::NinePatchAxisMode(axis_h), RS::NinePatchAxisMode(axis_v), draw_center, modulate); + Vector2 start_offset = Vector2(texture_margin[SIDE_LEFT], texture_margin[SIDE_TOP]); + Vector2 end_offset = Vector2(texture_margin[SIDE_RIGHT], texture_margin[SIDE_BOTTOM]); + + RenderingServer::get_singleton()->canvas_item_add_nine_patch(p_canvas_item, rect, src_rect, texture->get_rid(), start_offset, end_offset, RS::NinePatchAxisMode(axis_h), RS::NinePatchAxisMode(axis_v), draw_center, modulate); } void StyleBoxTexture::set_draw_center(bool p_enabled) { @@ -230,21 +231,29 @@ bool StyleBoxTexture::is_draw_center_enabled() const { return draw_center; } -Size2 StyleBoxTexture::get_center_size() const { - if (texture.is_null()) { - return Size2(); +Size2 StyleBoxTexture::get_minimum_size() const { + Size2 min_size = StyleBox::get_minimum_size(); + + // Make sure that the min size is no smaller than the used texture region. + if (texture.is_valid()) { + if (min_size.x < region_rect.size.x) { + min_size.x = region_rect.size.x; + } + if (min_size.y < region_rect.size.y) { + min_size.y = region_rect.size.y; + } } - return region_rect.size - get_minimum_size(); + return min_size; } -void StyleBoxTexture::set_expand_margin_size(Side p_side, float p_size) { +void StyleBoxTexture::set_expand_margin(Side p_side, float p_size) { ERR_FAIL_INDEX((int)p_side, 4); expand_margin[p_side] = p_size; emit_changed(); } -void StyleBoxTexture::set_expand_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom) { +void StyleBoxTexture::set_expand_margin_individual(float p_left, float p_top, float p_right, float p_bottom) { expand_margin[SIDE_LEFT] = p_left; expand_margin[SIDE_TOP] = p_top; expand_margin[SIDE_RIGHT] = p_right; @@ -252,14 +261,14 @@ void StyleBoxTexture::set_expand_margin_size_individual(float p_left, float p_to emit_changed(); } -void StyleBoxTexture::set_expand_margin_size_all(float p_expand_margin_size) { +void StyleBoxTexture::set_expand_margin_all(float p_expand_margin_size) { for (int i = 0; i < 4; i++) { expand_margin[i] = p_expand_margin_size; } emit_changed(); } -float StyleBoxTexture::get_expand_margin_size(Side p_side) const { +float StyleBoxTexture::get_expand_margin(Side p_side) const { ERR_FAIL_INDEX_V((int)p_side, 4, 0); return expand_margin[p_side]; } @@ -313,13 +322,13 @@ void StyleBoxTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("set_texture", "texture"), &StyleBoxTexture::set_texture); ClassDB::bind_method(D_METHOD("get_texture"), &StyleBoxTexture::get_texture); - ClassDB::bind_method(D_METHOD("set_margin_size", "margin", "size"), &StyleBoxTexture::set_margin_size); - ClassDB::bind_method(D_METHOD("set_margin_size_all", "size"), &StyleBoxTexture::set_margin_size_all); - ClassDB::bind_method(D_METHOD("get_margin_size", "margin"), &StyleBoxTexture::get_margin_size); + ClassDB::bind_method(D_METHOD("set_texture_margin", "margin", "size"), &StyleBoxTexture::set_texture_margin); + ClassDB::bind_method(D_METHOD("set_texture_margin_all", "size"), &StyleBoxTexture::set_texture_margin_all); + ClassDB::bind_method(D_METHOD("get_texture_margin", "margin"), &StyleBoxTexture::get_texture_margin); - ClassDB::bind_method(D_METHOD("set_expand_margin_size", "margin", "size"), &StyleBoxTexture::set_expand_margin_size); - ClassDB::bind_method(D_METHOD("set_expand_margin_all", "size"), &StyleBoxTexture::set_expand_margin_size_all); - ClassDB::bind_method(D_METHOD("get_expand_margin_size", "margin"), &StyleBoxTexture::get_expand_margin_size); + ClassDB::bind_method(D_METHOD("set_expand_margin", "margin", "size"), &StyleBoxTexture::set_expand_margin); + ClassDB::bind_method(D_METHOD("set_expand_margin_all", "size"), &StyleBoxTexture::set_expand_margin_all); + ClassDB::bind_method(D_METHOD("get_expand_margin", "margin"), &StyleBoxTexture::get_expand_margin); ClassDB::bind_method(D_METHOD("set_region_rect", "region"), &StyleBoxTexture::set_region_rect); ClassDB::bind_method(D_METHOD("get_region_rect"), &StyleBoxTexture::get_region_rect); @@ -338,17 +347,17 @@ void StyleBoxTexture::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture"); - ADD_GROUP("Margins", "margin_"); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_left", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_margin_size", "get_margin_size", SIDE_LEFT); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_top", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_margin_size", "get_margin_size", SIDE_TOP); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_right", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_margin_size", "get_margin_size", SIDE_RIGHT); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_margin_size", "get_margin_size", SIDE_BOTTOM); + ADD_GROUP("Texture Margins", "texture_margin_"); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "texture_margin_left", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_texture_margin", "get_texture_margin", SIDE_LEFT); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "texture_margin_top", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_texture_margin", "get_texture_margin", SIDE_TOP); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "texture_margin_right", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_texture_margin", "get_texture_margin", SIDE_RIGHT); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "texture_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_texture_margin", "get_texture_margin", SIDE_BOTTOM); ADD_GROUP("Expand Margins", "expand_margin_"); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin_size", "get_expand_margin_size", SIDE_LEFT); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin_size", "get_expand_margin_size", SIDE_TOP); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin_size", "get_expand_margin_size", SIDE_RIGHT); - ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin_size", "get_expand_margin_size", SIDE_BOTTOM); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin", "get_expand_margin", SIDE_LEFT); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin", "get_expand_margin", SIDE_TOP); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin", "get_expand_margin", SIDE_RIGHT); + ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin", "get_expand_margin", SIDE_BOTTOM); ADD_GROUP("Axis Stretch", "axis_stretch_"); ADD_PROPERTY(PropertyInfo(Variant::INT, "axis_stretch_horizontal", PROPERTY_HINT_ENUM, "Stretch,Tile,Tile Fit"), "set_h_axis_stretch_mode", "get_h_axis_stretch_mode"); @@ -450,13 +459,13 @@ int StyleBoxFlat::get_corner_radius(const Corner p_corner) const { return corner_radius[p_corner]; } -void StyleBoxFlat::set_expand_margin_size(Side p_side, float p_size) { +void StyleBoxFlat::set_expand_margin(Side p_side, float p_size) { ERR_FAIL_INDEX((int)p_side, 4); expand_margin[p_side] = p_size; emit_changed(); } -void StyleBoxFlat::set_expand_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom) { +void StyleBoxFlat::set_expand_margin_individual(float p_left, float p_top, float p_right, float p_bottom) { expand_margin[SIDE_LEFT] = p_left; expand_margin[SIDE_TOP] = p_top; expand_margin[SIDE_RIGHT] = p_right; @@ -464,14 +473,14 @@ void StyleBoxFlat::set_expand_margin_size_individual(float p_left, float p_top, emit_changed(); } -void StyleBoxFlat::set_expand_margin_size_all(float p_expand_margin_size) { +void StyleBoxFlat::set_expand_margin_all(float p_expand_margin_size) { for (int i = 0; i < 4; i++) { expand_margin[i] = p_expand_margin_size; } emit_changed(); } -float StyleBoxFlat::get_expand_margin_size(Side p_side) const { +float StyleBoxFlat::get_expand_margin(Side p_side) const { ERR_FAIL_INDEX_V((int)p_side, 4, 0.0); return expand_margin[p_side]; } @@ -549,10 +558,6 @@ int StyleBoxFlat::get_corner_detail() const { return corner_detail; } -Size2 StyleBoxFlat::get_center_size() const { - return Size2(); -} - inline void set_inner_corner_radius(const Rect2 style_rect, const Rect2 inner_rect, const real_t corner_radius[4], real_t *inner_corner_radius) { real_t border_left = inner_rect.position.x - style_rect.position.x; real_t border_top = inner_rect.position.y - style_rect.position.y; @@ -891,9 +896,9 @@ void StyleBoxFlat::_bind_methods() { ClassDB::bind_method(D_METHOD("set_corner_radius", "corner", "radius"), &StyleBoxFlat::set_corner_radius); ClassDB::bind_method(D_METHOD("get_corner_radius", "corner"), &StyleBoxFlat::get_corner_radius); - ClassDB::bind_method(D_METHOD("set_expand_margin", "margin", "size"), &StyleBoxFlat::set_expand_margin_size); - ClassDB::bind_method(D_METHOD("set_expand_margin_all", "size"), &StyleBoxFlat::set_expand_margin_size_all); - ClassDB::bind_method(D_METHOD("get_expand_margin", "margin"), &StyleBoxFlat::get_expand_margin_size); + ClassDB::bind_method(D_METHOD("set_expand_margin", "margin", "size"), &StyleBoxFlat::set_expand_margin); + ClassDB::bind_method(D_METHOD("set_expand_margin_all", "size"), &StyleBoxFlat::set_expand_margin_all); + ClassDB::bind_method(D_METHOD("get_expand_margin", "margin"), &StyleBoxFlat::get_expand_margin); ClassDB::bind_method(D_METHOD("set_draw_center", "draw_center"), &StyleBoxFlat::set_draw_center); ClassDB::bind_method(D_METHOD("is_draw_center_enabled"), &StyleBoxFlat::is_draw_center_enabled); @@ -1041,10 +1046,6 @@ float StyleBoxLine::get_style_margin(Side p_side) const { return 0; } -Size2 StyleBoxLine::get_center_size() const { - return Size2(); -} - void StyleBoxLine::draw(RID p_canvas_item, const Rect2 &p_rect) const { RenderingServer *vs = RenderingServer::get_singleton(); Rect2i r = p_rect; diff --git a/scene/resources/style_box.h b/scene/resources/style_box.h index 5a80b4d4e2..91033617ab 100644 --- a/scene/resources/style_box.h +++ b/scene/resources/style_box.h @@ -41,36 +41,34 @@ class StyleBox : public Resource { GDCLASS(StyleBox, Resource); RES_BASE_EXTENSION("stylebox"); OBJ_SAVE_TYPE(StyleBox); - float margin[4]; + float content_margin[4]; protected: - virtual float get_style_margin(Side p_side) const; + virtual float get_style_margin(Side p_side) const { return 0; } static void _bind_methods(); - GDVIRTUAL1RC(float, _get_style_margin, Side) - GDVIRTUAL2RC(bool, _test_mask, Point2, Rect2) - GDVIRTUAL0RC(Size2, _get_center_size) - GDVIRTUAL1RC(Rect2, _get_draw_rect, Rect2) GDVIRTUAL2C(_draw, RID, Rect2) + GDVIRTUAL1RC(Rect2, _get_draw_rect, Rect2) + GDVIRTUAL0RC(Size2, _get_minimum_size) + GDVIRTUAL2RC(bool, _test_mask, Point2, Rect2) public: - virtual bool test_mask(const Point2 &p_point, const Rect2 &p_rect) const; + virtual Size2 get_minimum_size() const; - void set_default_margin(Side p_side, float p_value); - void set_default_margin_all(float p_value); - void set_default_margin_individual(float p_left, float p_top, float p_right, float p_bottom); - float get_default_margin(Side p_side) const; + void set_content_margin(Side p_side, float p_value); + void set_content_margin_all(float p_value); + void set_content_margin_individual(float p_left, float p_top, float p_right, float p_bottom); + float get_content_margin(Side p_side) const; float get_margin(Side p_side) const; - virtual Size2 get_center_size() const; + Point2 get_offset() const; - virtual Rect2 get_draw_rect(const Rect2 &p_rect) const; virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const; + virtual Rect2 get_draw_rect(const Rect2 &p_rect) const; CanvasItem *get_current_item_drawn() const; - Size2 get_minimum_size() const; - Point2 get_offset() const; + virtual bool test_mask(const Point2 &p_point, const Rect2 &p_rect) const; StyleBox(); }; @@ -96,7 +94,7 @@ public: private: float expand_margin[4] = {}; - float margin[4] = {}; + float texture_margin[4] = {}; Rect2 region_rect; Ref<Texture2D> texture; bool draw_center = true; @@ -109,15 +107,17 @@ protected: static void _bind_methods(); public: - void set_expand_margin_size(Side p_expand_side, float p_size); - void set_expand_margin_size_all(float p_expand_margin_size); - void set_expand_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom); - float get_expand_margin_size(Side p_expand_side) const; + virtual Size2 get_minimum_size() const override; - void set_margin_size(Side p_side, float p_size); - void set_margin_size_all(float p_size); - void set_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom); - float get_margin_size(Side p_side) const; + void set_expand_margin(Side p_expand_side, float p_size); + void set_expand_margin_all(float p_expand_margin_size); + void set_expand_margin_individual(float p_left, float p_top, float p_right, float p_bottom); + float get_expand_margin(Side p_expand_side) const; + + void set_texture_margin(Side p_side, float p_size); + void set_texture_margin_all(float p_size); + void set_texture_margin_individual(float p_left, float p_top, float p_right, float p_bottom); + float get_texture_margin(Side p_side) const; void set_region_rect(const Rect2 &p_region_rect); Rect2 get_region_rect() const; @@ -127,7 +127,6 @@ public: void set_draw_center(bool p_enabled); bool is_draw_center_enabled() const; - virtual Size2 get_center_size() const override; void set_h_axis_stretch_mode(AxisStretchMode p_mode); AxisStretchMode get_h_axis_stretch_mode() const; @@ -198,10 +197,10 @@ public: void set_corner_detail(const int &p_corner_detail); int get_corner_detail() const; - void set_expand_margin_size(Side p_expand_side, float p_size); - void set_expand_margin_size_all(float p_expand_margin_size); - void set_expand_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom); - float get_expand_margin_size(Side p_expand_side) const; + void set_expand_margin(Side p_expand_side, float p_size); + void set_expand_margin_all(float p_expand_margin_size); + void set_expand_margin_individual(float p_left, float p_top, float p_right, float p_bottom); + float get_expand_margin(Side p_expand_side) const; void set_draw_center(bool p_enabled); bool is_draw_center_enabled() const; @@ -223,8 +222,6 @@ public: void set_aa_size(const real_t p_aa_size); real_t get_aa_size() const; - virtual Size2 get_center_size() const override; - virtual Rect2 get_draw_rect(const Rect2 &p_rect) const override; virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const override; @@ -261,8 +258,6 @@ public: void set_grow_end(float p_grow); float get_grow_end() const; - virtual Size2 get_center_size() const override; - virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const override; StyleBoxLine(); diff --git a/scene/resources/surface_tool.cpp b/scene/resources/surface_tool.cpp index e802e1c2d9..17e92ddfca 100644 --- a/scene/resources/surface_tool.cpp +++ b/scene/resources/surface_tool.cpp @@ -732,13 +732,13 @@ void SurfaceTool::index() { LocalVector<Vertex> old_vertex_array = vertex_array; vertex_array.clear(); - for (uint32_t i = 0; i < old_vertex_array.size(); i++) { - int *idxptr = indices.getptr(old_vertex_array[i]); + for (const Vertex &vertex : old_vertex_array) { + int *idxptr = indices.getptr(vertex); int idx; if (!idxptr) { idx = indices.size(); - vertex_array.push_back(old_vertex_array[i]); - indices[old_vertex_array[i]] = idx; + vertex_array.push_back(vertex); + indices[vertex] = idx; } else { idx = *idxptr; } @@ -756,9 +756,8 @@ void SurfaceTool::deindex() { LocalVector<Vertex> old_vertex_array = vertex_array; vertex_array.clear(); - for (uint32_t i = 0; i < index_array.size(); i++) { - uint32_t index = index_array[i]; - ERR_FAIL_COND(index >= old_vertex_array.size()); + for (const int &index : index_array) { + ERR_FAIL_COND(uint32_t(index) >= old_vertex_array.size()); vertex_array.push_back(old_vertex_array[index]); } format &= ~Mesh::ARRAY_FORMAT_INDEX; @@ -1000,8 +999,7 @@ void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const } int vfrom = vertex_array.size(); - for (uint32_t vi = 0; vi < nvertices.size(); vi++) { - Vertex v = nvertices[vi]; + for (Vertex &v : nvertices) { v.vertex = p_xform.xform(v.vertex); if (nformat & RS::ARRAY_FORMAT_NORMAL) { v.normal = p_xform.basis.xform(v.normal); @@ -1014,8 +1012,8 @@ void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const vertex_array.push_back(v); } - for (uint32_t i = 0; i < nindices.size(); i++) { - int dst_index = nindices[i] + vfrom; + for (const int &index : nindices) { + int dst_index = index + vfrom; index_array.push_back(dst_index); } if (index_array.size() % 3) { @@ -1132,9 +1130,9 @@ void SurfaceTool::generate_tangents() { TangentGenerationContextUserData triangle_data; triangle_data.vertices = &vertex_array; - for (uint32_t i = 0; i < vertex_array.size(); i++) { - vertex_array[i].binormal = Vector3(); - vertex_array[i].tangent = Vector3(); + for (Vertex &vertex : vertex_array) { + vertex.binormal = Vector3(); + vertex.tangent = Vector3(); } triangle_data.indices = &index_array; msc.m_pUserData = &triangle_data; @@ -1176,12 +1174,12 @@ void SurfaceTool::generate_normals(bool p_flip) { } } - for (uint32_t vi = 0; vi < vertex_array.size(); vi++) { - Vector3 *lv = vertex_hash.getptr(vertex_array[vi]); + for (Vertex &vertex : vertex_array) { + Vector3 *lv = vertex_hash.getptr(vertex); if (!lv) { - vertex_array[vi].normal = Vector3(); + vertex.normal = Vector3(); } else { - vertex_array[vi].normal = lv->normalized(); + vertex.normal = lv->normalized(); } } diff --git a/scene/resources/text_paragraph.cpp b/scene/resources/text_paragraph.cpp index 6d66c48b78..dfafc7d2bc 100644 --- a/scene/resources/text_paragraph.cpp +++ b/scene/resources/text_paragraph.cpp @@ -135,8 +135,8 @@ void TextParagraph::_bind_methods() { void TextParagraph::_shape_lines() { if (lines_dirty) { - for (int i = 0; i < (int)lines_rid.size(); i++) { - TS->free_rid(lines_rid[i]); + for (const RID &line_rid : lines_rid) { + TS->free_rid(line_rid); } lines_rid.clear(); @@ -234,14 +234,14 @@ void TextParagraph::_shape_lines() { } else { // Autowrap disabled. - for (int i = 0; i < (int)lines_rid.size(); i++) { + for (const RID &line_rid : lines_rid) { if (alignment == HORIZONTAL_ALIGNMENT_FILL) { - TS->shaped_text_fit_to_width(lines_rid[i], width, jst_flags); + TS->shaped_text_fit_to_width(line_rid, width, jst_flags); overrun_flags.set_flag(TextServer::OVERRUN_JUSTIFICATION_AWARE); - TS->shaped_text_overrun_trim_to_width(lines_rid[i], width, overrun_flags); - TS->shaped_text_fit_to_width(lines_rid[i], width, jst_flags | TextServer::JUSTIFICATION_CONSTRAIN_ELLIPSIS); + TS->shaped_text_overrun_trim_to_width(line_rid, width, overrun_flags); + TS->shaped_text_fit_to_width(line_rid, width, jst_flags | TextServer::JUSTIFICATION_CONSTRAIN_ELLIPSIS); } else { - TS->shaped_text_overrun_trim_to_width(lines_rid[i], width, overrun_flags); + TS->shaped_text_overrun_trim_to_width(line_rid, width, overrun_flags); } } } @@ -268,8 +268,8 @@ RID TextParagraph::get_dropcap_rid() const { void TextParagraph::clear() { _THREAD_SAFE_METHOD_ - for (int i = 0; i < (int)lines_rid.size(); i++) { - TS->free_rid(lines_rid[i]); + for (const RID &line_rid : lines_rid) { + TS->free_rid(line_rid); } lines_rid.clear(); TS->shaped_text_clear(rid); @@ -915,17 +915,17 @@ int TextParagraph::hit_test(const Point2 &p_coords) const { return 0; } } - for (int i = 0; i < (int)lines_rid.size(); i++) { - if (TS->shaped_text_get_orientation(lines_rid[i]) == TextServer::ORIENTATION_HORIZONTAL) { - if ((p_coords.y >= ofs.y) && (p_coords.y <= ofs.y + TS->shaped_text_get_size(lines_rid[i]).y)) { - return TS->shaped_text_hit_test_position(lines_rid[i], p_coords.x); + for (const RID &line_rid : lines_rid) { + if (TS->shaped_text_get_orientation(line_rid) == TextServer::ORIENTATION_HORIZONTAL) { + if ((p_coords.y >= ofs.y) && (p_coords.y <= ofs.y + TS->shaped_text_get_size(line_rid).y)) { + return TS->shaped_text_hit_test_position(line_rid, p_coords.x); } - ofs.y += TS->shaped_text_get_size(lines_rid[i]).y; + ofs.y += TS->shaped_text_get_size(line_rid).y; } else { - if ((p_coords.x >= ofs.x) && (p_coords.x <= ofs.x + TS->shaped_text_get_size(lines_rid[i]).x)) { - return TS->shaped_text_hit_test_position(lines_rid[i], p_coords.y); + if ((p_coords.x >= ofs.x) && (p_coords.x <= ofs.x + TS->shaped_text_get_size(line_rid).x)) { + return TS->shaped_text_hit_test_position(line_rid, p_coords.y); } - ofs.y += TS->shaped_text_get_size(lines_rid[i]).x; + ofs.y += TS->shaped_text_get_size(line_rid).x; } } return TS->shaped_text_get_range(rid).y; @@ -1027,8 +1027,8 @@ TextParagraph::TextParagraph() { } TextParagraph::~TextParagraph() { - for (int i = 0; i < (int)lines_rid.size(); i++) { - TS->free_rid(lines_rid[i]); + for (const RID &line_rid : lines_rid) { + TS->free_rid(line_rid); } lines_rid.clear(); TS->free_rid(rid); diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp index 4043b73b71..b5a68ef14b 100644 --- a/scene/resources/tile_set.cpp +++ b/scene/resources/tile_set.cpp @@ -404,8 +404,8 @@ void TileSet::_update_terrains_cache() { if (terrains_cache_dirty) { // Organizes tiles into structures. per_terrain_pattern_tiles.resize(terrain_sets.size()); - for (int i = 0; i < (int)per_terrain_pattern_tiles.size(); i++) { - per_terrain_pattern_tiles[i].clear(); + for (RBMap<TileSet::TerrainsPattern, RBSet<TileMapCell>> &tiles : per_terrain_pattern_tiles) { + tiles.clear(); } for (const KeyValue<int, Ref<TileSetSource>> &kv : sources) { @@ -473,6 +473,7 @@ void TileSet::_compute_next_source_id() { int TileSet::add_source(Ref<TileSetSource> p_tile_set_source, int p_atlas_source_id_override) { ERR_FAIL_COND_V(!p_tile_set_source.is_valid(), TileSet::INVALID_SOURCE); ERR_FAIL_COND_V_MSG(p_atlas_source_id_override >= 0 && (sources.has(p_atlas_source_id_override)), TileSet::INVALID_SOURCE, vformat("Cannot create TileSet atlas source. Another atlas source exists with id %d.", p_atlas_source_id_override)); + ERR_FAIL_COND_V_MSG(p_atlas_source_id_override < 0 && p_atlas_source_id_override != TileSet::INVALID_SOURCE, TileSet::INVALID_SOURCE, vformat("Provided source ID %d is not valid. Negative source IDs are not allowed.", p_atlas_source_id_override)); int new_source_id = p_atlas_source_id_override >= 0 ? p_atlas_source_id_override : next_source_id; sources[new_source_id] = p_tile_set_source; @@ -1341,8 +1342,8 @@ void TileSet::clear_tile_proxies() { int TileSet::add_pattern(Ref<TileMapPattern> p_pattern, int p_index) { ERR_FAIL_COND_V(!p_pattern.is_valid(), -1); ERR_FAIL_COND_V_MSG(p_pattern->is_empty(), -1, "Cannot add an empty pattern to the TileSet."); - for (unsigned int i = 0; i < patterns.size(); i++) { - ERR_FAIL_COND_V_MSG(patterns[i] == p_pattern, -1, "TileSet has already this pattern."); + for (const Ref<TileMapPattern> &pattern : patterns) { + ERR_FAIL_COND_V_MSG(pattern == p_pattern, -1, "TileSet has already this pattern."); } ERR_FAIL_COND_V(p_index > (int)patterns.size(), -1); if (p_index < 0) { @@ -4189,8 +4190,8 @@ real_t TileSetAtlasSource::get_tile_animation_total_duration(const Vector2i p_at ERR_FAIL_COND_V_MSG(!tiles.has(p_atlas_coords), 1, vformat("TileSetAtlasSource has no tile at %s.", Vector2i(p_atlas_coords))); real_t sum = 0.0; - for (int frame = 0; frame < (int)tiles[p_atlas_coords].animation_frames_durations.size(); frame++) { - sum += tiles[p_atlas_coords].animation_frames_durations[frame]; + for (const real_t &duration : tiles[p_atlas_coords].animation_frames_durations) { + sum += duration; } return sum; } @@ -4572,8 +4573,8 @@ void TileSetAtlasSource::_clear_tiles_outside_texture() { } } - for (unsigned int i = 0; i < to_remove.size(); i++) { - remove_tile(to_remove[i]); + for (const Vector2i &v : to_remove) { + remove_tile(v); } } diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp index d8a963f15b..1cbeaae428 100644 --- a/scene/resources/visual_shader.cpp +++ b/scene/resources/visual_shader.cpp @@ -399,10 +399,10 @@ void VisualShaderNode::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "output_port_for_preview"), "set_output_port_for_preview", "get_output_port_for_preview"); ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "default_input_values", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_default_input_values", "get_default_input_values"); ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "expanded_output_ports", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_output_ports_expanded", "_get_output_ports_expanded"); - ADD_SIGNAL(MethodInfo("editor_refresh_request")); BIND_ENUM_CONSTANT(PORT_TYPE_SCALAR); BIND_ENUM_CONSTANT(PORT_TYPE_SCALAR_INT); + BIND_ENUM_CONSTANT(PORT_TYPE_SCALAR_UINT); BIND_ENUM_CONSTANT(PORT_TYPE_VECTOR_2D); BIND_ENUM_CONSTANT(PORT_TYPE_VECTOR_3D); BIND_ENUM_CONSTANT(PORT_TYPE_VECTOR_4D); @@ -951,7 +951,7 @@ bool VisualShader::can_connect_nodes(Type p_type, int p_from_node, int p_from_po } bool VisualShader::is_port_types_compatible(int p_a, int p_b) const { - return MAX(0, p_a - 5) == (MAX(0, p_b - 5)); + return MAX(0, p_a - (int)VisualShaderNode::PORT_TYPE_BOOLEAN) == (MAX(0, p_b - (int)VisualShaderNode::PORT_TYPE_BOOLEAN)); } void VisualShader::connect_nodes_forced(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) { @@ -1198,6 +1198,9 @@ String VisualShader::generate_preview_shader(Type p_type, int p_node, int p_port case VisualShaderNode::PORT_TYPE_SCALAR_INT: { shader_code += " COLOR.rgb = vec3(float(n_out" + itos(p_node) + "p" + itos(p_port) + "));\n"; } break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: { + shader_code += " COLOR.rgb = vec3(float(n_out" + itos(p_node) + "p" + itos(p_port) + "));\n"; + } break; case VisualShaderNode::PORT_TYPE_BOOLEAN: { shader_code += " COLOR.rgb = vec3(n_out" + itos(p_node) + "p" + itos(p_port) + " ? 1.0 : 0.0);\n"; } break; @@ -1689,6 +1692,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB case VisualShaderNode::PORT_TYPE_SCALAR_INT: { inputs[i] = "float(" + src_var + ")"; } break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: { + inputs[i] = "float(" + src_var + ")"; + } break; case VisualShaderNode::PORT_TYPE_BOOLEAN: { inputs[i] = "(" + src_var + " ? 1.0 : 0.0)"; } break; @@ -1710,17 +1716,44 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB case VisualShaderNode::PORT_TYPE_SCALAR: { inputs[i] = "int(" + src_var + ")"; } break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: { + inputs[i] = "int(" + src_var + ")"; + } break; case VisualShaderNode::PORT_TYPE_BOOLEAN: { inputs[i] = "(" + src_var + " ? 1 : 0)"; } break; case VisualShaderNode::PORT_TYPE_VECTOR_2D: { - inputs[i] = "dot(float(" + src_var + "), vec2(0.5, 0.5))"; + inputs[i] = "int(" + src_var + ".x)"; + } break; + case VisualShaderNode::PORT_TYPE_VECTOR_3D: { + inputs[i] = "int(" + src_var + ".x)"; + } break; + case VisualShaderNode::PORT_TYPE_VECTOR_4D: { + inputs[i] = "int(" + src_var + ".x)"; + } break; + default: + break; + } + } break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: { + switch (out_type) { + case VisualShaderNode::PORT_TYPE_SCALAR: { + inputs[i] = "uint(" + src_var + ")"; + } break; + case VisualShaderNode::PORT_TYPE_SCALAR_INT: { + inputs[i] = "uint(" + src_var + ")"; + } break; + case VisualShaderNode::PORT_TYPE_BOOLEAN: { + inputs[i] = "(" + src_var + " ? 1u : 0u)"; + } break; + case VisualShaderNode::PORT_TYPE_VECTOR_2D: { + inputs[i] = "uint(" + src_var + ".x)"; } break; case VisualShaderNode::PORT_TYPE_VECTOR_3D: { - inputs[i] = "dot(float(" + src_var + "), vec3(0.333333, 0.333333, 0.333333))"; + inputs[i] = "uint(" + src_var + ".x)"; } break; case VisualShaderNode::PORT_TYPE_VECTOR_4D: { - inputs[i] = "dot(float(" + src_var + "), vec4(0.25, 0.25, 0.25, 0.25))"; + inputs[i] = "uint(" + src_var + ".x)"; } break; default: break; @@ -1734,6 +1767,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB case VisualShaderNode::PORT_TYPE_SCALAR_INT: { inputs[i] = src_var + " > 0 ? true : false"; } break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: { + inputs[i] = src_var + " > 0u ? true : false"; + } break; case VisualShaderNode::PORT_TYPE_VECTOR_2D: { inputs[i] = "all(bvec2(" + src_var + "))"; } break; @@ -1755,6 +1791,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB case VisualShaderNode::PORT_TYPE_SCALAR_INT: { inputs[i] = "vec2(float(" + src_var + "))"; } break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: { + inputs[i] = "vec2(float(" + src_var + "))"; + } break; case VisualShaderNode::PORT_TYPE_BOOLEAN: { inputs[i] = "vec2(" + src_var + " ? 1.0 : 0.0)"; } break; @@ -1775,6 +1814,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB case VisualShaderNode::PORT_TYPE_SCALAR_INT: { inputs[i] = "vec3(float(" + src_var + "))"; } break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: { + inputs[i] = "vec3(float(" + src_var + "))"; + } break; case VisualShaderNode::PORT_TYPE_BOOLEAN: { inputs[i] = "vec3(" + src_var + " ? 1.0 : 0.0)"; } break; @@ -1796,6 +1838,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB case VisualShaderNode::PORT_TYPE_SCALAR_INT: { inputs[i] = "vec4(float(" + src_var + "))"; } break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: { + inputs[i] = "vec4(float(" + src_var + "))"; + } break; case VisualShaderNode::PORT_TYPE_BOOLEAN: { inputs[i] = "vec4(" + src_var + " ? 1.0 : 0.0)"; } break; @@ -1826,7 +1871,11 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB } else if (defval.get_type() == Variant::INT) { int val = defval; inputs[i] = "n_in" + itos(p_node) + "p" + itos(i); - node_code += " int " + inputs[i] + " = " + itos(val) + ";\n"; + if (vsnode->get_input_port_type(i) == VisualShaderNode::PORT_TYPE_SCALAR_UINT) { + node_code += " uint " + inputs[i] + " = " + itos(val) + "u;\n"; + } else { + node_code += " int " + inputs[i] + " = " + itos(val) + ";\n"; + } } else if (defval.get_type() == Variant::BOOL) { bool val = defval; inputs[i] = "n_in" + itos(p_node) + "p" + itos(i); @@ -1906,6 +1955,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB case VisualShaderNode::PORT_TYPE_SCALAR_INT: outputs[i] = "int " + var_name; break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: + outputs[i] = "uint " + var_name; + break; case VisualShaderNode::PORT_TYPE_VECTOR_2D: outputs[i] = "vec2 " + var_name; break; @@ -1951,6 +2003,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB case VisualShaderNode::PORT_TYPE_SCALAR_INT: r_code += " int " + outputs[i] + ";\n"; break; + case VisualShaderNode::PORT_TYPE_SCALAR_UINT: + r_code += " uint " + outputs[i] + ";\n"; + break; case VisualShaderNode::PORT_TYPE_VECTOR_2D: r_code += " vec2 " + outputs[i] + ";\n"; break; @@ -2214,6 +2269,12 @@ void VisualShader::_update_shader() const { } global_code += "int "; break; + case VaryingType::VARYING_TYPE_UINT: + if (E.value.mode == VaryingMode::VARYING_MODE_VERTEX_TO_FRAG_LIGHT) { + global_code += "flat "; + } + global_code += "uint "; + break; case VaryingType::VARYING_TYPE_VECTOR_2D: global_code += "vec2 "; break; @@ -2283,6 +2344,9 @@ void VisualShader::_update_shader() const { case VaryingType::VARYING_TYPE_INT: code2 += "0"; break; + case VaryingType::VARYING_TYPE_UINT: + code2 += "0u"; + break; case VaryingType::VARYING_TYPE_VECTOR_2D: code2 += "vec2(0.0)"; break; @@ -2443,14 +2507,6 @@ void VisualShader::_update_shader() const { global_compute_code += " return __rand_from_seed(seed) * (to - from) + from;\n"; global_compute_code += "}\n\n"; - global_compute_code += "vec2 __randv2_range(inout uint seed, vec2 from, vec2 to) {\n"; - global_compute_code += " return vec2(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y));\n"; - global_compute_code += "}\n\n"; - - global_compute_code += "vec3 __randv3_range(inout uint seed, vec3 from, vec3 to) {\n"; - global_compute_code += " return vec3(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z));\n"; - global_compute_code += "}\n\n"; - global_compute_code += "uint __hash(uint x) {\n"; global_compute_code += " x = ((x >> uint(16)) ^ x) * uint(73244475);\n"; global_compute_code += " x = ((x >> uint(16)) ^ x) * uint(73244475);\n"; @@ -2583,6 +2639,7 @@ void VisualShader::_bind_methods() { BIND_ENUM_CONSTANT(VARYING_TYPE_FLOAT); BIND_ENUM_CONSTANT(VARYING_TYPE_INT); + BIND_ENUM_CONSTANT(VARYING_TYPE_UINT); BIND_ENUM_CONSTANT(VARYING_TYPE_VECTOR_2D); BIND_ENUM_CONSTANT(VARYING_TYPE_VECTOR_3D); BIND_ENUM_CONSTANT(VARYING_TYPE_VECTOR_4D); @@ -2648,7 +2705,7 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = { { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "node_position_world", "NODE_POSITION_WORLD" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "camera_position_world", "CAMERA_POSITION_WORLD" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "camera_direction_world", "CAMERA_DIRECTION_WORLD" }, - { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR_INT, "camera_visible_layers", "CAMERA_VISIBLE_LAYERS" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "camera_visible_layers", "CAMERA_VISIBLE_LAYERS" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "node_position_view", "NODE_POSITION_VIEW" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_4D, "custom0", "CUSTOM0" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_4D, "custom1", "CUSTOM1" }, @@ -2676,16 +2733,13 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = { { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_2D, "viewport_size", "VIEWPORT_SIZE" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_BOOLEAN, "output_is_srgb", "OUTPUT_IS_SRGB" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_BOOLEAN, "front_facing", "FRONT_FACING" }, - { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "screen_texture", "SCREEN_TEXTURE" }, - { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "normal_roughness_texture", "NORMAL_ROUGHNESS_TEXTURE" }, - { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "depth_texture", "DEPTH_TEXTURE" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR_INT, "view_index", "VIEW_INDEX" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR_INT, "view_mono_left", "VIEW_MONO_LEFT" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR_INT, "view_right", "VIEW_RIGHT" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_3D, "node_position_world", "NODE_POSITION_WORLD" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_3D, "camera_position_world", "CAMERA_POSITION_WORLD" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_3D, "camera_direction_world", "CAMERA_DIRECTION_WORLD" }, - { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR_INT, "camera_visible_layers", "CAMERA_VISIBLE_LAYERS" }, + { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "camera_visible_layers", "CAMERA_VISIBLE_LAYERS" }, { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_3D, "node_position_view", "NODE_POSITION_VIEW" }, // Node3D, Light @@ -2741,7 +2795,6 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = { { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_BOOLEAN, "at_light_pass", "AT_LIGHT_PASS" }, { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "texture", "TEXTURE" }, { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "normal_texture", "NORMAL_TEXTURE" }, - { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "screen_texture", "SCREEN_TEXTURE" }, { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_4D, "specular_shininess", "SPECULAR_SHININESS" }, { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "specular_shininess_texture", "SPECULAR_SHININESS_TEXTURE" }, { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_2D, "vertex", "VERTEX" }, @@ -2776,7 +2829,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = { { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" }, - { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, @@ -2790,7 +2845,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = { { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" }, - { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, @@ -2804,7 +2861,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = { { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" }, - { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, @@ -2818,7 +2877,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = { { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" }, - { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, @@ -2834,7 +2895,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = { { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" }, - { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" }, + { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" }, { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" }, @@ -3252,6 +3315,8 @@ int VisualShaderNodeParameterRef::get_output_port_count() const { return 1; case PARAMETER_TYPE_INT: return 1; + case PARAMETER_TYPE_UINT: + return 1; case PARAMETER_TYPE_BOOLEAN: return 1; case PARAMETER_TYPE_VECTOR2: @@ -3278,6 +3343,8 @@ VisualShaderNodeParameterRef::PortType VisualShaderNodeParameterRef::get_output_ return PortType::PORT_TYPE_SCALAR; case PARAMETER_TYPE_INT: return PortType::PORT_TYPE_SCALAR_INT; + case PARAMETER_TYPE_UINT: + return PortType::PORT_TYPE_SCALAR_UINT; case PARAMETER_TYPE_BOOLEAN: return PortType::PORT_TYPE_BOOLEAN; case PARAMETER_TYPE_VECTOR2: @@ -3309,6 +3376,8 @@ String VisualShaderNodeParameterRef::get_output_port_name(int p_port) const { return ""; case PARAMETER_TYPE_INT: return ""; + case PARAMETER_TYPE_UINT: + return ""; case PARAMETER_TYPE_BOOLEAN: return ""; case PARAMETER_TYPE_VECTOR2: @@ -3403,6 +3472,8 @@ VisualShaderNodeParameterRef::PortType VisualShaderNodeParameterRef::get_port_ty return PORT_TYPE_SCALAR; case PARAMETER_TYPE_INT: return PORT_TYPE_SCALAR_INT; + case PARAMETER_TYPE_UINT: + return PORT_TYPE_SCALAR_UINT; case UNIFORM_TYPE_SAMPLER: return PORT_TYPE_SAMPLER; case PARAMETER_TYPE_VECTOR2: @@ -4659,6 +4730,8 @@ String VisualShaderNodeVarying::get_type_str() const { return "float"; case VisualShader::VARYING_TYPE_INT: return "int"; + case VisualShader::VARYING_TYPE_UINT: + return "uint"; case VisualShader::VARYING_TYPE_VECTOR_2D: return "vec2"; case VisualShader::VARYING_TYPE_VECTOR_3D: @@ -4679,6 +4752,8 @@ VisualShaderNodeVarying::PortType VisualShaderNodeVarying::get_port_type(VisualS switch (p_type) { case VisualShader::VARYING_TYPE_INT: return PORT_TYPE_SCALAR_INT; + case VisualShader::VARYING_TYPE_UINT: + return PORT_TYPE_SCALAR_UINT; case VisualShader::VARYING_TYPE_VECTOR_2D: return PORT_TYPE_VECTOR_2D; case VisualShader::VARYING_TYPE_VECTOR_3D: @@ -4811,6 +4886,9 @@ String VisualShaderNodeVaryingGetter::generate_code(Shader::Mode p_mode, VisualS case VisualShader::VARYING_TYPE_INT: from = "0"; break; + case VisualShader::VARYING_TYPE_UINT: + from = "0u"; + break; case VisualShader::VARYING_TYPE_VECTOR_2D: from = "vec2(0.0)"; break; diff --git a/scene/resources/visual_shader.h b/scene/resources/visual_shader.h index b8ee693a84..0d53589fa5 100644 --- a/scene/resources/visual_shader.h +++ b/scene/resources/visual_shader.h @@ -80,6 +80,7 @@ public: enum VaryingType { VARYING_TYPE_FLOAT, VARYING_TYPE_INT, + VARYING_TYPE_UINT, VARYING_TYPE_VECTOR_2D, VARYING_TYPE_VECTOR_3D, VARYING_TYPE_VECTOR_4D, @@ -260,6 +261,7 @@ public: enum PortType { PORT_TYPE_SCALAR, PORT_TYPE_SCALAR_INT, + PORT_TYPE_SCALAR_UINT, PORT_TYPE_VECTOR_2D, PORT_TYPE_VECTOR_3D, PORT_TYPE_VECTOR_4D, @@ -550,6 +552,7 @@ public: enum ParameterType { PARAMETER_TYPE_FLOAT, PARAMETER_TYPE_INT, + PARAMETER_TYPE_UINT, PARAMETER_TYPE_BOOLEAN, PARAMETER_TYPE_VECTOR2, PARAMETER_TYPE_VECTOR3, diff --git a/scene/resources/visual_shader_nodes.cpp b/scene/resources/visual_shader_nodes.cpp index df8e836a51..e78d9b924d 100644 --- a/scene/resources/visual_shader_nodes.cpp +++ b/scene/resources/visual_shader_nodes.cpp @@ -223,6 +223,68 @@ void VisualShaderNodeIntConstant::_bind_methods() { VisualShaderNodeIntConstant::VisualShaderNodeIntConstant() { } +////////////// Scalar(UInt) + +String VisualShaderNodeUIntConstant::get_caption() const { + return "UIntConstant"; +} + +int VisualShaderNodeUIntConstant::get_input_port_count() const { + return 0; +} + +VisualShaderNodeUIntConstant::PortType VisualShaderNodeUIntConstant::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR_UINT; +} + +String VisualShaderNodeUIntConstant::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeUIntConstant::get_output_port_count() const { + return 1; +} + +VisualShaderNodeUIntConstant::PortType VisualShaderNodeUIntConstant::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR_UINT; +} + +String VisualShaderNodeUIntConstant::get_output_port_name(int p_port) const { + return ""; // No output port means the editor will be used as port. +} + +String VisualShaderNodeUIntConstant::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { + return " " + p_output_vars[0] + " = " + itos(constant) + "u;\n"; +} + +void VisualShaderNodeUIntConstant::set_constant(int p_constant) { + if (constant == p_constant) { + return; + } + constant = p_constant; + emit_changed(); +} + +int VisualShaderNodeUIntConstant::get_constant() const { + return constant; +} + +Vector<StringName> VisualShaderNodeUIntConstant::get_editable_properties() const { + Vector<StringName> props; + props.push_back("constant"); + return props; +} + +void VisualShaderNodeUIntConstant::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_constant", "constant"), &VisualShaderNodeUIntConstant::set_constant); + ClassDB::bind_method(D_METHOD("get_constant"), &VisualShaderNodeUIntConstant::get_constant); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "constant"), "set_constant", "get_constant"); +} + +VisualShaderNodeUIntConstant::VisualShaderNodeUIntConstant() { +} + ////////////// Boolean String VisualShaderNodeBooleanConstant::get_caption() const { @@ -694,141 +756,157 @@ Vector<VisualShader::DefaultTextureParam> VisualShaderNodeTexture::get_default_t } String VisualShaderNodeTexture::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { - if (source == SOURCE_TEXTURE) { - String u = "uniform sampler2D " + make_unique_id(p_type, p_id, "tex"); - switch (texture_type) { - case TYPE_DATA: - break; - case TYPE_COLOR: - u += " : source_color"; - break; - case TYPE_NORMAL_MAP: - u += " : hint_normal"; - break; - default: - break; - } - return u + ";\n"; + String code; + + switch (source) { + case SOURCE_TEXTURE: { + code += "uniform sampler2D " + make_unique_id(p_type, p_id, "tex"); + switch (texture_type) { + case TYPE_DATA: { + } break; + case TYPE_COLOR: { + code += " : source_color"; + } break; + case TYPE_NORMAL_MAP: { + code += " : hint_normal"; + } break; + default: { + } break; + } + code += ";\n"; + } break; + case SOURCE_SCREEN: { + if ((p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) { + code += "uniform sampler2D " + make_unique_id(p_type, p_id, "screen_tex") + " : hint_screen_texture;\n"; + } + } break; + case SOURCE_DEPTH: + case SOURCE_3D_NORMAL: + case SOURCE_ROUGHNESS: { + if (p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) { + String sampler_name = ""; + String hint = " : "; + if (source == SOURCE_DEPTH) { + sampler_name = "depth_tex"; + hint += "hint_depth_texture;\n"; + } else { + sampler_name = source == SOURCE_ROUGHNESS ? "roughness_tex" : "normal_roughness_tex"; + hint += "hint_normal_roughness_texture;\n"; + } + code += "uniform sampler2D " + make_unique_id(p_type, p_id, sampler_name) + hint; + } + } break; + default: { + } break; } - return String(); + return code; } String VisualShaderNodeTexture::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { String default_uv; if (p_mode == Shader::MODE_CANVAS_ITEM || p_mode == Shader::MODE_SPATIAL) { - default_uv = "UV"; + if (source == SOURCE_SCREEN) { + default_uv = "SCREEN_UV"; + } else { + default_uv = "UV"; + } } else { default_uv = "vec2(0.0)"; } String code; - if (source == SOURCE_TEXTURE) { - String id = make_unique_id(p_type, p_id, "tex"); - if (p_input_vars[0].is_empty()) { // Use UV by default. + String uv = p_input_vars[0].is_empty() ? default_uv : p_input_vars[0]; + + switch (source) { + case SOURCE_PORT: + case SOURCE_TEXTURE: { + String id; + if (source == SOURCE_PORT) { + id = p_input_vars[2]; + if (id.is_empty()) { + break; + } + } else { // SOURCE_TEXTURE + id = make_unique_id(p_type, p_id, "tex"); + } if (p_input_vars[1].is_empty()) { - code += " " + p_output_vars[0] + " = texture(" + id + ", " + default_uv + ");\n"; + code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n"; } else { - code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + default_uv + ", " + p_input_vars[1] + ");\n"; + code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n"; } - } else if (p_input_vars[1].is_empty()) { - //no lod - code += " " + p_output_vars[0] + " = texture(" + id + ", " + p_input_vars[0] + ");\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n"; - } - return code; - } - - if (source == SOURCE_PORT) { - String id = p_input_vars[2]; - if (id.is_empty()) { - code += " " + p_output_vars[0] + " = vec4(0.0);\n"; - } else { - if (p_input_vars[0].is_empty()) { // Use UV by default. + return code; + } break; + case SOURCE_SCREEN: { + if ((p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) { + String id = make_unique_id(p_type, p_id, "screen_tex"); if (p_input_vars[1].is_empty()) { - code += " " + p_output_vars[0] + " = texture(" + id + ", " + default_uv + ");\n"; + code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n"; } else { - code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + default_uv + ", " + p_input_vars[1] + ");\n"; + code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n"; } - } else if (p_input_vars[1].is_empty()) { - //no lod - code += " " + p_output_vars[0] + " = texture(" + id + ", " + p_input_vars[0] + ");\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n"; + return code; } - } - return code; - } - - if (source == SOURCE_SCREEN && (p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) { - if (p_input_vars[0].is_empty() || p_for_preview) { // Use UV by default. - if (p_input_vars[1].is_empty()) { - code += " " + p_output_vars[0] + " = textureLod(SCREEN_TEXTURE, " + default_uv + ", 0.0);\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(SCREEN_TEXTURE, " + default_uv + ", " + p_input_vars[1] + ");\n"; - } - } else if (p_input_vars[1].is_empty()) { - //no lod - code += " " + p_output_vars[0] + " = textureLod(SCREEN_TEXTURE, " + p_input_vars[0] + ", 0.0);\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(SCREEN_TEXTURE, " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n"; - } - return code; - } + } break; + case SOURCE_2D_NORMAL: + case SOURCE_2D_TEXTURE: { + if (p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) { + String id = source == SOURCE_2D_TEXTURE ? "TEXTURE" : "NORMAL_TEXTURE"; - if (source == SOURCE_2D_TEXTURE && p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) { - if (p_input_vars[0].is_empty()) { // Use UV by default. - if (p_input_vars[1].is_empty()) { - code += " " + p_output_vars[0] + " = texture(TEXTURE, " + default_uv + ");\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(TEXTURE, " + default_uv + ", " + p_input_vars[1] + ");\n"; + if (p_input_vars[1].is_empty()) { + code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n"; + } else { + code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n"; + } + return code; } - } else if (p_input_vars[1].is_empty()) { - //no lod - code += " " + p_output_vars[0] + " = texture(TEXTURE, " + p_input_vars[0] + ");\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(TEXTURE, " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n"; - } - return code; - } + } break; + case SOURCE_3D_NORMAL: + case SOURCE_ROUGHNESS: + case SOURCE_DEPTH: { + if (!p_for_preview && p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) { + String var_name = ""; + String sampler_name = ""; + + switch (source) { + case SOURCE_DEPTH: { + var_name = "_depth"; + sampler_name = "depth_tex"; + } break; + case SOURCE_ROUGHNESS: { + var_name = "_roughness"; + sampler_name = "roughness_tex"; + } break; + case SOURCE_3D_NORMAL: { + var_name = "_normal"; + sampler_name = "normal_roughness_tex"; + } break; + default: { + } break; + } - if (source == SOURCE_2D_NORMAL && p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) { - if (p_input_vars[0].is_empty()) { // Use UV by default. - if (p_input_vars[1].is_empty()) { - code += " " + p_output_vars[0] + " = texture(NORMAL_TEXTURE, " + default_uv + ");\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(NORMAL_TEXTURE, " + default_uv + ", " + p_input_vars[1] + ");\n"; - } - } else if (p_input_vars[1].is_empty()) { - //no lod - code += " " + p_output_vars[0] + " = texture(NORMAL_TEXTURE, " + p_input_vars[0] + ".xy);\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(NORMAL_TEXTURE, " + p_input_vars[0] + ".xy, " + p_input_vars[1] + ");\n"; - } - return code; - } + String id = make_unique_id(p_type, p_id, sampler_name); + String type = source == SOURCE_3D_NORMAL ? "vec3" : "float"; + String components = source == SOURCE_3D_NORMAL ? "rgb" : "r"; - if (source == SOURCE_DEPTH) { - if (!p_for_preview && p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) { - code += " {\n"; - if (p_input_vars[0].is_empty()) { // Use UV by default. + code += " {\n"; if (p_input_vars[1].is_empty()) { - code += " float _depth = texture(DEPTH_TEXTURE, " + default_uv + ").r;\n"; + code += " " + type + " " + var_name + " = texture(" + id + ", " + uv + ")." + components + ";\n"; } else { - code += " float _depth = textureLod(DEPTH_TEXTURE, " + default_uv + ", " + p_input_vars[1] + ").r;\n"; + code += " " + type + " " + var_name + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ")." + components + ";\n"; } - } else if (p_input_vars[1].is_empty()) { - //no lod - code += " float _depth = texture(DEPTH_TEXTURE, " + p_input_vars[0] + ".xy).r;\n"; - } else { - code += " float _depth = textureLod(DEPTH_TEXTURE, " + p_input_vars[0] + ".xy, " + p_input_vars[1] + ").r;\n"; - } + if (source == SOURCE_3D_NORMAL) { + code += " " + p_output_vars[0] + " = vec4(" + var_name + ", 1.0);\n"; + } else { + code += " " + p_output_vars[0] + " = vec4(" + var_name + ", " + var_name + ", " + var_name + ", 1.0);\n"; + } + code += " }\n"; - code += " " + p_output_vars[0] + " = vec4(_depth, _depth, _depth, 1.0);\n"; - code += " }\n"; - return code; - } + return code; + } + } break; + default: { + } break; } code += " " + p_output_vars[0] + " = vec4(0.0);\n"; @@ -859,12 +937,17 @@ void VisualShaderNodeTexture::set_source(Source p_source) { case SOURCE_PORT: simple_decl = false; break; + case SOURCE_3D_NORMAL: + simple_decl = false; + break; + case SOURCE_ROUGHNESS: + simple_decl = false; + break; default: break; } source = p_source; emit_changed(); - emit_signal(SNAME("editor_refresh_request")); } VisualShaderNodeTexture::Source VisualShaderNodeTexture::get_source() const { @@ -908,31 +991,34 @@ String VisualShaderNodeTexture::get_warning(Shader::Mode p_mode, VisualShader::T return RTR("The sampler port is connected but not used. Consider changing the source to 'SamplerPort'."); } - if (source == SOURCE_TEXTURE) { - return String(); // all good - } - - if (source == SOURCE_PORT) { - return String(); // all good - } - - if (source == SOURCE_SCREEN && (p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) { - return String(); // all good - } - - if (source == SOURCE_2D_TEXTURE && p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) { - return String(); // all good - } - - if (source == SOURCE_2D_NORMAL && p_mode == Shader::MODE_CANVAS_ITEM) { - return String(); // all good - } - - if (source == SOURCE_DEPTH && p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) { - if (get_output_port_for_preview() == 0) { // DEPTH_TEXTURE is not supported in preview(canvas_item) shader - return RTR("Invalid source for preview."); - } - return String(); // all good + switch (source) { + case SOURCE_TEXTURE: + case SOURCE_PORT: { + return String(); // All good. + } break; + case SOURCE_SCREEN: { + if ((p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) { + return String(); // All good. + } + } break; + case SOURCE_2D_NORMAL: + case SOURCE_2D_TEXTURE: { + if (p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) { + return String(); // All good. + } + } break; + case SOURCE_3D_NORMAL: + case SOURCE_ROUGHNESS: + case SOURCE_DEPTH: { + if (p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) { + if (get_output_port_for_preview() == 0) { // Not supported in preview(canvas_item) shader. + return RTR("Invalid source for preview."); + } + return String(); // All good. + } + } break; + default: { + } break; } return RTR("Invalid source for shader."); @@ -948,7 +1034,7 @@ void VisualShaderNodeTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("set_texture_type", "value"), &VisualShaderNodeTexture::set_texture_type); ClassDB::bind_method(D_METHOD("get_texture_type"), &VisualShaderNodeTexture::get_texture_type); - ADD_PROPERTY(PropertyInfo(Variant::INT, "source", PROPERTY_HINT_ENUM, "Texture,Screen,Texture2D,NormalMap2D,Depth,SamplerPort"), "set_source", "get_source"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "source", PROPERTY_HINT_ENUM, "Texture,Screen,Texture2D,NormalMap2D,Depth,SamplerPort,Normal3D,Roughness"), "set_source", "get_source"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture"); ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_type", PROPERTY_HINT_ENUM, "Data,Color,Normal Map"), "set_texture_type", "get_texture_type"); @@ -958,6 +1044,8 @@ void VisualShaderNodeTexture::_bind_methods() { BIND_ENUM_CONSTANT(SOURCE_2D_NORMAL); BIND_ENUM_CONSTANT(SOURCE_DEPTH); BIND_ENUM_CONSTANT(SOURCE_PORT); + BIND_ENUM_CONSTANT(SOURCE_3D_NORMAL); + BIND_ENUM_CONSTANT(SOURCE_ROUGHNESS); BIND_ENUM_CONSTANT(SOURCE_MAX); BIND_ENUM_CONSTANT(TYPE_DATA); @@ -1198,6 +1286,17 @@ bool VisualShaderNodeSample3D::is_input_port_default(int p_port, Shader::Mode p_ } String VisualShaderNodeSample3D::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { + String code; + String id; + if (source == SOURCE_TEXTURE) { + id = make_unique_id(p_type, p_id, "tex3d"); + } else { // SOURCE_PORT + id = p_input_vars[2]; + if (id.is_empty()) { + code += " " + p_output_vars[0] + " = vec4(0.0);\n"; + return code; + } + } String default_uv; if (p_mode == Shader::MODE_CANVAS_ITEM || p_mode == Shader::MODE_SPATIAL) { default_uv = "vec3(UV, 0.0)"; @@ -1205,33 +1304,12 @@ String VisualShaderNodeSample3D::generate_code(Shader::Mode p_mode, VisualShader default_uv = "vec3(0.0)"; } - String code; - if (source == SOURCE_TEXTURE || source == SOURCE_PORT) { - String id; - if (source == SOURCE_TEXTURE) { - id = make_unique_id(p_type, p_id, "tex3d"); - } else { - id = p_input_vars[2]; - } - if (!id.is_empty()) { - if (p_input_vars[0].is_empty()) { // Use UV by default. - if (p_input_vars[1].is_empty()) { - code += " " + p_output_vars[0] + " = texture(" + id + ", " + default_uv + ");\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + default_uv + ", " + p_input_vars[1] + ");\n"; - } - } else if (p_input_vars[1].is_empty()) { - //no lod - code += " " + p_output_vars[0] + " = texture(" + id + ", " + p_input_vars[0] + ");\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n"; - } - } else { - code += " " + p_output_vars[0] + " = vec4(0.0);\n"; - } - return code; + String uv = p_input_vars[0].is_empty() ? default_uv : p_input_vars[0]; + if (p_input_vars[1].is_empty()) { + code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n"; + } else { + code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n"; } - code += " " + p_output_vars[0] + " = vec4(0.0);\n"; return code; } @@ -1242,7 +1320,6 @@ void VisualShaderNodeSample3D::set_source(Source p_source) { } source = p_source; emit_changed(); - emit_signal(SNAME("editor_refresh_request")); } VisualShaderNodeSample3D::Source VisualShaderNodeSample3D::get_source() const { @@ -1264,14 +1341,7 @@ String VisualShaderNodeSample3D::get_warning(Shader::Mode p_mode, VisualShader:: if (is_input_port_connected(2) && source != SOURCE_PORT) { return RTR("The sampler port is connected but not used. Consider changing the source to 'SamplerPort'."); } - - if (source == SOURCE_TEXTURE) { - return String(); // all good - } - if (source == SOURCE_PORT) { - return String(); // all good - } - return RTR("Invalid source for shader."); + return String(); } VisualShaderNodeSample3D::VisualShaderNodeSample3D() { @@ -1477,42 +1547,33 @@ String VisualShaderNodeCubemap::generate_global(Shader::Mode p_mode, VisualShade } String VisualShaderNodeCubemap::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { - String default_uv; - if (p_mode == Shader::MODE_CANVAS_ITEM || p_mode == Shader::MODE_SPATIAL) { - default_uv = "vec3(UV, 0.0)"; - } else { - default_uv = "vec3(0.0)"; - } - String code; String id; + if (source == SOURCE_TEXTURE) { id = make_unique_id(p_type, p_id, "cube"); - } else if (source == SOURCE_PORT) { + } else { // SOURCE_PORT id = p_input_vars[2]; - } else { - return code; + if (id.is_empty()) { + code += " " + p_output_vars[0] + " = vec4(0.0);\n"; + return code; + } } - if (id.is_empty()) { - code += " " + p_output_vars[0] + " = vec4(0.0);\n"; - return code; + String default_uv; + if (p_mode == Shader::MODE_CANVAS_ITEM || p_mode == Shader::MODE_SPATIAL) { + default_uv = "vec3(UV, 0.0)"; + } else { + default_uv = "vec3(0.0)"; } - if (p_input_vars[0].is_empty()) { // Use UV by default. - - if (p_input_vars[1].is_empty()) { - code += " " + p_output_vars[0] + " = texture(" + id + ", " + default_uv + ");\n"; - } else { - code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + default_uv + ", " + p_input_vars[1] + ");\n"; - } - - } else if (p_input_vars[1].is_empty()) { - //no lod - code += " " + p_output_vars[0] + " = texture(" + id + ", " + p_input_vars[0] + ");\n"; + String uv = p_input_vars[0].is_empty() ? default_uv : p_input_vars[0]; + if (p_input_vars[1].is_empty()) { + code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n"; } else { - code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n"; + code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n"; } + return code; } @@ -1532,7 +1593,6 @@ void VisualShaderNodeCubemap::set_source(Source p_source) { } source = p_source; emit_changed(); - emit_signal(SNAME("editor_refresh_request")); } VisualShaderNodeCubemap::Source VisualShaderNodeCubemap::get_source() const { @@ -1640,11 +1700,15 @@ bool VisualShaderNodeLinearSceneDepth::has_output_port_preview(int p_port) const return false; } +String VisualShaderNodeLinearSceneDepth::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + return "uniform sampler2D " + make_unique_id(p_type, p_id, "depth_tex") + " : hint_depth_texture;\n"; +} + String VisualShaderNodeLinearSceneDepth::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { String code; code += " {\n"; - code += " float __log_depth = textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).x;\n"; + code += " float __log_depth = textureLod(" + make_unique_id(p_type, p_id, "depth_tex") + ", SCREEN_UV, 0.0).x;\n"; code += " vec3 __depth_ndc = vec3(SCREEN_UV * 2.0 - 1.0, __log_depth);\n"; code += " vec4 __depth_view = INV_PROJECTION_MATRIX * vec4(__depth_ndc, 1.0);\n"; code += " __depth_view.xyz /= __depth_view.w;\n"; @@ -1797,7 +1861,7 @@ VisualShaderNodeIntOp::PortType VisualShaderNodeIntOp::get_output_port_type(int } String VisualShaderNodeIntOp::get_output_port_name(int p_port) const { - return "op"; //no output port means the editor will be used as port + return "op"; // No output port means the editor will be used as port. } String VisualShaderNodeIntOp::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { @@ -1891,6 +1955,127 @@ VisualShaderNodeIntOp::VisualShaderNodeIntOp() { set_input_port_default_value(1, 0); } +////////////// Unsigned Integer Op + +String VisualShaderNodeUIntOp::get_caption() const { + return "UIntOp"; +} + +int VisualShaderNodeUIntOp::get_input_port_count() const { + return 2; +} + +VisualShaderNodeUIntOp::PortType VisualShaderNodeUIntOp::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR_UINT; +} + +String VisualShaderNodeUIntOp::get_input_port_name(int p_port) const { + return p_port == 0 ? "a" : "b"; +} + +int VisualShaderNodeUIntOp::get_output_port_count() const { + return 1; +} + +VisualShaderNodeUIntOp::PortType VisualShaderNodeUIntOp::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR_UINT; +} + +String VisualShaderNodeUIntOp::get_output_port_name(int p_port) const { + return "op"; // No output port means the editor will be used as port. +} + +String VisualShaderNodeUIntOp::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { + String code = " " + p_output_vars[0] + " = "; + switch (op) { + case OP_ADD: + code += p_input_vars[0] + " + " + p_input_vars[1] + ";\n"; + break; + case OP_SUB: + code += p_input_vars[0] + " - " + p_input_vars[1] + ";\n"; + break; + case OP_MUL: + code += p_input_vars[0] + " * " + p_input_vars[1] + ";\n"; + break; + case OP_DIV: + code += p_input_vars[0] + " / " + p_input_vars[1] + ";\n"; + break; + case OP_MOD: + code += p_input_vars[0] + " % " + p_input_vars[1] + ";\n"; + break; + case OP_MAX: + code += "max(" + p_input_vars[0] + ", " + p_input_vars[1] + ");\n"; + break; + case OP_MIN: + code += "min(" + p_input_vars[0] + ", " + p_input_vars[1] + ");\n"; + break; + case OP_BITWISE_AND: + code += p_input_vars[0] + " & " + p_input_vars[1] + ";\n"; + break; + case OP_BITWISE_OR: + code += p_input_vars[0] + " | " + p_input_vars[1] + ";\n"; + break; + case OP_BITWISE_XOR: + code += p_input_vars[0] + " ^ " + p_input_vars[1] + ";\n"; + break; + case OP_BITWISE_LEFT_SHIFT: + code += p_input_vars[0] + " << " + p_input_vars[1] + ";\n"; + break; + case OP_BITWISE_RIGHT_SHIFT: + code += p_input_vars[0] + " >> " + p_input_vars[1] + ";\n"; + break; + default: + break; + } + + return code; +} + +void VisualShaderNodeUIntOp::set_operator(Operator p_op) { + ERR_FAIL_INDEX(int(p_op), OP_ENUM_SIZE); + if (op == p_op) { + return; + } + op = p_op; + emit_changed(); +} + +VisualShaderNodeUIntOp::Operator VisualShaderNodeUIntOp::get_operator() const { + return op; +} + +Vector<StringName> VisualShaderNodeUIntOp::get_editable_properties() const { + Vector<StringName> props; + props.push_back("operator"); + return props; +} + +void VisualShaderNodeUIntOp::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualShaderNodeUIntOp::set_operator); + ClassDB::bind_method(D_METHOD("get_operator"), &VisualShaderNodeUIntOp::get_operator); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "operator", PROPERTY_HINT_ENUM, "Add,Subtract,Multiply,Divide,Remainder,Max,Min,Bitwise AND,Bitwise OR,Bitwise XOR,Bitwise Left Shift,Bitwise Right Shift"), "set_operator", "get_operator"); + + BIND_ENUM_CONSTANT(OP_ADD); + BIND_ENUM_CONSTANT(OP_SUB); + BIND_ENUM_CONSTANT(OP_MUL); + BIND_ENUM_CONSTANT(OP_DIV); + BIND_ENUM_CONSTANT(OP_MOD); + BIND_ENUM_CONSTANT(OP_MAX); + BIND_ENUM_CONSTANT(OP_MIN); + BIND_ENUM_CONSTANT(OP_BITWISE_AND); + BIND_ENUM_CONSTANT(OP_BITWISE_OR); + BIND_ENUM_CONSTANT(OP_BITWISE_XOR); + BIND_ENUM_CONSTANT(OP_BITWISE_LEFT_SHIFT); + BIND_ENUM_CONSTANT(OP_BITWISE_RIGHT_SHIFT); + BIND_ENUM_CONSTANT(OP_ENUM_SIZE); +} + +VisualShaderNodeUIntOp::VisualShaderNodeUIntOp() { + set_input_port_default_value(0, 0); + set_input_port_default_value(1, 0); +} + ////////////// Vector Op String VisualShaderNodeVectorOp::get_caption() const { @@ -2626,6 +2811,79 @@ VisualShaderNodeIntFunc::VisualShaderNodeIntFunc() { set_input_port_default_value(0, 0); } +////////////// Unsigned Int Func + +String VisualShaderNodeUIntFunc::get_caption() const { + return "UIntFunc"; +} + +int VisualShaderNodeUIntFunc::get_input_port_count() const { + return 1; +} + +VisualShaderNodeUIntFunc::PortType VisualShaderNodeUIntFunc::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR_UINT; +} + +String VisualShaderNodeUIntFunc::get_input_port_name(int p_port) const { + return ""; +} + +int VisualShaderNodeUIntFunc::get_output_port_count() const { + return 1; +} + +VisualShaderNodeUIntFunc::PortType VisualShaderNodeUIntFunc::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR_UINT; +} + +String VisualShaderNodeUIntFunc::get_output_port_name(int p_port) const { + return ""; // No output port means the editor will be used as port. +} + +String VisualShaderNodeUIntFunc::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { + static const char *functions[FUNC_MAX] = { + "-($)", + "~($)" + }; + + return " " + p_output_vars[0] + " = " + String(functions[func]).replace("$", p_input_vars[0]) + ";\n"; +} + +void VisualShaderNodeUIntFunc::set_function(Function p_func) { + ERR_FAIL_INDEX(int(p_func), int(FUNC_MAX)); + if (func == p_func) { + return; + } + func = p_func; + emit_changed(); +} + +VisualShaderNodeUIntFunc::Function VisualShaderNodeUIntFunc::get_function() const { + return func; +} + +Vector<StringName> VisualShaderNodeUIntFunc::get_editable_properties() const { + Vector<StringName> props; + props.push_back("function"); + return props; +} + +void VisualShaderNodeUIntFunc::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_function", "func"), &VisualShaderNodeUIntFunc::set_function); + ClassDB::bind_method(D_METHOD("get_function"), &VisualShaderNodeUIntFunc::get_function); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, "Negate,Bitwise NOT"), "set_function", "get_function"); + + BIND_ENUM_CONSTANT(FUNC_NEGATE); + BIND_ENUM_CONSTANT(FUNC_BITWISE_NOT); + BIND_ENUM_CONSTANT(FUNC_MAX); +} + +VisualShaderNodeUIntFunc::VisualShaderNodeUIntFunc() { + set_input_port_default_value(0, 0); +} + ////////////// Vector Func String VisualShaderNodeVectorFunc::get_caption() const { @@ -3531,6 +3789,8 @@ VisualShaderNodeClamp::PortType VisualShaderNodeClamp::get_input_port_type(int p switch (op_type) { case OP_TYPE_INT: return PORT_TYPE_SCALAR_INT; + case OP_TYPE_UINT: + return PORT_TYPE_SCALAR_UINT; case OP_TYPE_VECTOR_2D: return PORT_TYPE_VECTOR_2D; case OP_TYPE_VECTOR_3D: @@ -3562,6 +3822,8 @@ VisualShaderNodeClamp::PortType VisualShaderNodeClamp::get_output_port_type(int switch (op_type) { case OP_TYPE_INT: return PORT_TYPE_SCALAR_INT; + case OP_TYPE_UINT: + return PORT_TYPE_SCALAR_UINT; case OP_TYPE_VECTOR_2D: return PORT_TYPE_VECTOR_2D; case OP_TYPE_VECTOR_3D: @@ -3593,6 +3855,7 @@ void VisualShaderNodeClamp::set_op_type(OpType p_op_type) { set_input_port_default_value(1, 0.0, get_input_port_default_value(1)); set_input_port_default_value(2, 0.0, get_input_port_default_value(2)); break; + case OP_TYPE_UINT: case OP_TYPE_INT: set_input_port_default_value(0, 0, get_input_port_default_value(0)); set_input_port_default_value(1, 0, get_input_port_default_value(1)); @@ -3634,10 +3897,11 @@ void VisualShaderNodeClamp::_bind_methods() { ClassDB::bind_method(D_METHOD("set_op_type", "op_type"), &VisualShaderNodeClamp::set_op_type); ClassDB::bind_method(D_METHOD("get_op_type"), &VisualShaderNodeClamp::get_op_type); - ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Float,Int,Vector2,Vector3,Vector4"), "set_op_type", "get_op_type"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Float,Int,UInt,Vector2,Vector3,Vector4"), "set_op_type", "get_op_type"); BIND_ENUM_CONSTANT(OP_TYPE_FLOAT); BIND_ENUM_CONSTANT(OP_TYPE_INT); + BIND_ENUM_CONSTANT(OP_TYPE_UINT); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_2D); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_3D); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_4D); @@ -4914,7 +5178,7 @@ Vector<StringName> VisualShaderNodeFloatParameter::get_editable_properties() con VisualShaderNodeFloatParameter::VisualShaderNodeFloatParameter() { } -////////////// Integer Parametet +////////////// Integer Parameter String VisualShaderNodeIntParameter::get_caption() const { return "IntParameter"; @@ -5105,6 +5369,112 @@ Vector<StringName> VisualShaderNodeIntParameter::get_editable_properties() const VisualShaderNodeIntParameter::VisualShaderNodeIntParameter() { } +////////////// Unsigned Integer Parameter + +String VisualShaderNodeUIntParameter::get_caption() const { + return "UIntParameter"; +} + +int VisualShaderNodeUIntParameter::get_input_port_count() const { + return 0; +} + +VisualShaderNodeUIntParameter::PortType VisualShaderNodeUIntParameter::get_input_port_type(int p_port) const { + return PORT_TYPE_SCALAR_UINT; +} + +String VisualShaderNodeUIntParameter::get_input_port_name(int p_port) const { + return String(); +} + +int VisualShaderNodeUIntParameter::get_output_port_count() const { + return 1; +} + +VisualShaderNodeUIntParameter::PortType VisualShaderNodeUIntParameter::get_output_port_type(int p_port) const { + return PORT_TYPE_SCALAR_UINT; +} + +String VisualShaderNodeUIntParameter::get_output_port_name(int p_port) const { + return ""; // No output port means the editor will be used as port. +} + +String VisualShaderNodeUIntParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + String code = _get_qual_str() + "uniform uint " + get_parameter_name(); + if (default_value_enabled) { + code += " = " + itos(default_value); + } + code += ";\n"; + return code; +} + +String VisualShaderNodeUIntParameter::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { + return " " + p_output_vars[0] + " = " + get_parameter_name() + ";\n"; +} + +bool VisualShaderNodeUIntParameter::is_show_prop_names() const { + return true; +} + +bool VisualShaderNodeUIntParameter::is_use_prop_slots() const { + return true; +} + +void VisualShaderNodeUIntParameter::set_default_value_enabled(bool p_default_value_enabled) { + if (default_value_enabled == p_default_value_enabled) { + return; + } + default_value_enabled = p_default_value_enabled; + emit_changed(); +} + +bool VisualShaderNodeUIntParameter::is_default_value_enabled() const { + return default_value_enabled; +} + +void VisualShaderNodeUIntParameter::set_default_value(int p_default_value) { + if (default_value == p_default_value) { + return; + } + default_value = p_default_value; + emit_changed(); +} + +int VisualShaderNodeUIntParameter::get_default_value() const { + return default_value; +} + +void VisualShaderNodeUIntParameter::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_default_value_enabled", "enabled"), &VisualShaderNodeUIntParameter::set_default_value_enabled); + ClassDB::bind_method(D_METHOD("is_default_value_enabled"), &VisualShaderNodeUIntParameter::is_default_value_enabled); + + ClassDB::bind_method(D_METHOD("set_default_value", "value"), &VisualShaderNodeUIntParameter::set_default_value); + ClassDB::bind_method(D_METHOD("get_default_value"), &VisualShaderNodeUIntParameter::get_default_value); + + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "default_value_enabled"), "set_default_value_enabled", "is_default_value_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "default_value"), "set_default_value", "get_default_value"); +} + +bool VisualShaderNodeUIntParameter::is_qualifier_supported(Qualifier p_qual) const { + return true; // All qualifiers are supported. +} + +bool VisualShaderNodeUIntParameter::is_convertible_to_constant() const { + return true; // Conversion is allowed. +} + +Vector<StringName> VisualShaderNodeUIntParameter::get_editable_properties() const { + Vector<StringName> props = VisualShaderNodeParameter::get_editable_properties(); + props.push_back("default_value_enabled"); + if (default_value_enabled) { + props.push_back("default_value"); + } + return props; +} + +VisualShaderNodeUIntParameter::VisualShaderNodeUIntParameter() { +} + ////////////// Boolean Parameter String VisualShaderNodeBooleanParameter::get_caption() const { @@ -5733,7 +6103,7 @@ VisualShaderNodeTransformParameter::VisualShaderNodeTransformParameter() { ////////////// -String get_sampler_hint(VisualShaderNodeTextureParameter::TextureType p_texture_type, VisualShaderNodeTextureParameter::ColorDefault p_color_default, VisualShaderNodeTextureParameter::TextureFilter p_texture_filter, VisualShaderNodeTextureParameter::TextureRepeat p_texture_repeat) { +String get_sampler_hint(VisualShaderNodeTextureParameter::TextureType p_texture_type, VisualShaderNodeTextureParameter::ColorDefault p_color_default, VisualShaderNodeTextureParameter::TextureFilter p_texture_filter, VisualShaderNodeTextureParameter::TextureRepeat p_texture_repeat, VisualShaderNodeTextureParameter::TextureSource p_texture_source) { String code; bool has_colon = false; @@ -5836,6 +6206,33 @@ String get_sampler_hint(VisualShaderNodeTextureParameter::TextureType p_texture_ } } + { + String source_code; + + switch (p_texture_source) { + case VisualShaderNodeTextureParameter::SOURCE_SCREEN: + source_code = "hint_screen_texture"; + break; + case VisualShaderNodeTextureParameter::SOURCE_DEPTH: + source_code = "hint_depth_texture"; + break; + case VisualShaderNodeTextureParameter::SOURCE_NORMAL_ROUGHNESS: + source_code = "hint_normal_roughness_texture"; + break; + default: + break; + } + + if (!source_code.is_empty()) { + if (!has_colon) { + code += " : "; + } else { + code += ", "; + } + code += source_code; + } + } + return code; } @@ -5922,6 +6319,19 @@ VisualShaderNodeTextureParameter::TextureRepeat VisualShaderNodeTextureParameter return texture_repeat; } +void VisualShaderNodeTextureParameter::set_texture_source(TextureSource p_source) { + ERR_FAIL_INDEX(int(p_source), int(SOURCE_MAX)); + if (texture_source == p_source) { + return; + } + texture_source = p_source; + emit_changed(); +} + +VisualShaderNodeTextureParameter::TextureSource VisualShaderNodeTextureParameter::get_texture_source() const { + return texture_source; +} + Vector<StringName> VisualShaderNodeTextureParameter::get_editable_properties() const { Vector<StringName> props = VisualShaderNodeParameter::get_editable_properties(); props.push_back("texture_type"); @@ -5930,6 +6340,7 @@ Vector<StringName> VisualShaderNodeTextureParameter::get_editable_properties() c } props.push_back("texture_filter"); props.push_back("texture_repeat"); + props.push_back("texture_source"); return props; } @@ -5943,6 +6354,7 @@ HashMap<StringName, String> VisualShaderNodeTextureParameter::get_editable_prope names.insert("color_default", RTR("Default Color")); names.insert("texture_filter", RTR("Filter")); names.insert("texture_repeat", RTR("Repeat")); + names.insert("texture_source", RTR("Source")); return names; } @@ -5950,19 +6362,23 @@ void VisualShaderNodeTextureParameter::_bind_methods() { ClassDB::bind_method(D_METHOD("set_texture_type", "type"), &VisualShaderNodeTextureParameter::set_texture_type); ClassDB::bind_method(D_METHOD("get_texture_type"), &VisualShaderNodeTextureParameter::get_texture_type); - ClassDB::bind_method(D_METHOD("set_color_default", "type"), &VisualShaderNodeTextureParameter::set_color_default); + ClassDB::bind_method(D_METHOD("set_color_default", "color"), &VisualShaderNodeTextureParameter::set_color_default); ClassDB::bind_method(D_METHOD("get_color_default"), &VisualShaderNodeTextureParameter::get_color_default); ClassDB::bind_method(D_METHOD("set_texture_filter", "filter"), &VisualShaderNodeTextureParameter::set_texture_filter); ClassDB::bind_method(D_METHOD("get_texture_filter"), &VisualShaderNodeTextureParameter::get_texture_filter); - ClassDB::bind_method(D_METHOD("set_texture_repeat", "type"), &VisualShaderNodeTextureParameter::set_texture_repeat); + ClassDB::bind_method(D_METHOD("set_texture_repeat", "repeat"), &VisualShaderNodeTextureParameter::set_texture_repeat); ClassDB::bind_method(D_METHOD("get_texture_repeat"), &VisualShaderNodeTextureParameter::get_texture_repeat); + ClassDB::bind_method(D_METHOD("set_texture_source", "source"), &VisualShaderNodeTextureParameter::set_texture_source); + ClassDB::bind_method(D_METHOD("get_texture_source"), &VisualShaderNodeTextureParameter::get_texture_source); + ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_type", PROPERTY_HINT_ENUM, "Data,Color,Normal Map,Anisotropic"), "set_texture_type", "get_texture_type"); ADD_PROPERTY(PropertyInfo(Variant::INT, "color_default", PROPERTY_HINT_ENUM, "White,Black,Transparent"), "set_color_default", "get_color_default"); ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_filter", PROPERTY_HINT_ENUM, "Default,Nearest,Linear,Nearest Mipmap,Linear Mipmap,Nearest Mipmap Anisotropic,Linear Mipmap Anisotropic"), "set_texture_filter", "get_texture_filter"); ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_repeat", PROPERTY_HINT_ENUM, "Default,Enabled,Disabled"), "set_texture_repeat", "get_texture_repeat"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_source", PROPERTY_HINT_ENUM, "None,Screen,Depth,NormalRoughness"), "set_texture_source", "get_texture_source"); BIND_ENUM_CONSTANT(TYPE_DATA); BIND_ENUM_CONSTANT(TYPE_COLOR); @@ -5988,6 +6404,12 @@ void VisualShaderNodeTextureParameter::_bind_methods() { BIND_ENUM_CONSTANT(REPEAT_ENABLED); BIND_ENUM_CONSTANT(REPEAT_DISABLED); BIND_ENUM_CONSTANT(REPEAT_MAX); + + BIND_ENUM_CONSTANT(SOURCE_NONE); + BIND_ENUM_CONSTANT(SOURCE_SCREEN); + BIND_ENUM_CONSTANT(SOURCE_DEPTH); + BIND_ENUM_CONSTANT(SOURCE_NORMAL_ROUGHNESS); + BIND_ENUM_CONSTANT(SOURCE_MAX); } bool VisualShaderNodeTextureParameter::is_qualifier_supported(Qualifier p_qual) const { @@ -6028,7 +6450,7 @@ String VisualShaderNodeTexture2DParameter::get_output_port_name(int p_port) cons String VisualShaderNodeTexture2DParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { String code = _get_qual_str() + "uniform sampler2D " + get_parameter_name(); - code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat); + code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source); code += ";\n"; return code; } @@ -6039,7 +6461,7 @@ VisualShaderNodeTexture2DParameter::VisualShaderNodeTexture2DParameter() { ////////////// Texture Parameter (Triplanar) String VisualShaderNodeTextureParameterTriplanar::get_caption() const { - return "TextureUniformTriplanar"; + return "TextureParameterTriplanar"; } int VisualShaderNodeTextureParameterTriplanar::get_input_port_count() const { @@ -6128,7 +6550,7 @@ String VisualShaderNodeTextureParameterTriplanar::generate_global_per_func(Shade String VisualShaderNodeTextureParameterTriplanar::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { String code = _get_qual_str() + "uniform sampler2D " + get_parameter_name(); - code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat); + code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source); code += ";\n"; return code; } @@ -6174,7 +6596,7 @@ String VisualShaderNodeTexture2DArrayParameter::get_output_port_name(int p_port) String VisualShaderNodeTexture2DArrayParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { String code = _get_qual_str() + "uniform sampler2DArray " + get_parameter_name(); - code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat); + code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source); code += ";\n"; return code; } @@ -6194,7 +6616,7 @@ String VisualShaderNodeTexture3DParameter::get_output_port_name(int p_port) cons String VisualShaderNodeTexture3DParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { String code = _get_qual_str() + "uniform sampler3D " + get_parameter_name(); - code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat); + code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source); code += ";\n"; return code; } @@ -6214,7 +6636,7 @@ String VisualShaderNodeCubemapParameter::get_output_port_name(int p_port) const String VisualShaderNodeCubemapParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { String code = _get_qual_str() + "uniform samplerCube " + get_parameter_name(); - code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat); + code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source); code += ";\n"; return code; } @@ -6315,6 +6737,8 @@ VisualShaderNodeSwitch::PortType VisualShaderNodeSwitch::get_input_port_type(int switch (op_type) { case OP_TYPE_INT: return PORT_TYPE_SCALAR_INT; + case OP_TYPE_UINT: + return PORT_TYPE_SCALAR_UINT; case OP_TYPE_VECTOR_2D: return PORT_TYPE_VECTOR_2D; case OP_TYPE_VECTOR_3D: @@ -6353,6 +6777,8 @@ VisualShaderNodeSwitch::PortType VisualShaderNodeSwitch::get_output_port_type(in switch (op_type) { case OP_TYPE_INT: return PORT_TYPE_SCALAR_INT; + case OP_TYPE_UINT: + return PORT_TYPE_SCALAR_UINT; case OP_TYPE_VECTOR_2D: return PORT_TYPE_VECTOR_2D; case OP_TYPE_VECTOR_3D: @@ -6383,6 +6809,7 @@ void VisualShaderNodeSwitch::set_op_type(OpType p_op_type) { set_input_port_default_value(1, 1.0, get_input_port_default_value(1)); set_input_port_default_value(2, 0.0, get_input_port_default_value(2)); break; + case OP_TYPE_UINT: case OP_TYPE_INT: set_input_port_default_value(1, 1, get_input_port_default_value(1)); set_input_port_default_value(2, 0, get_input_port_default_value(2)); @@ -6428,10 +6855,11 @@ void VisualShaderNodeSwitch::_bind_methods() { // static ClassDB::bind_method(D_METHOD("set_op_type", "type"), &VisualShaderNodeSwitch::set_op_type); ClassDB::bind_method(D_METHOD("get_op_type"), &VisualShaderNodeSwitch::get_op_type); - ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Float,Int,Vector2,Vector3,Vector4,Boolean,Transform"), "set_op_type", "get_op_type"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Float,Int,UInt,Vector2,Vector3,Vector4,Boolean,Transform"), "set_op_type", "get_op_type"); BIND_ENUM_CONSTANT(OP_TYPE_FLOAT); BIND_ENUM_CONSTANT(OP_TYPE_INT); + BIND_ENUM_CONSTANT(OP_TYPE_UINT); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_2D); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_3D); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_4D); @@ -6664,6 +7092,8 @@ VisualShaderNodeCompare::PortType VisualShaderNodeCompare::get_input_port_type(i return PORT_TYPE_SCALAR; case CTYPE_SCALAR_INT: return PORT_TYPE_SCALAR_INT; + case CTYPE_SCALAR_UINT: + return PORT_TYPE_SCALAR_UINT; case CTYPE_VECTOR_2D: return PORT_TYPE_VECTOR_2D; case CTYPE_VECTOR_3D: @@ -6749,6 +7179,7 @@ String VisualShaderNodeCompare::generate_code(Shader::Mode p_mode, VisualShader: code += " " + p_output_vars[0] + " = " + (p_input_vars[0] + " $ " + p_input_vars[1]).replace("$", operators[func]) + ";\n"; } } break; + case CTYPE_SCALAR_UINT: case CTYPE_SCALAR_INT: { code += " " + p_output_vars[0] + " = " + (p_input_vars[0] + " $ " + p_input_vars[1]).replace("$", operators[func]) + ";\n"; } break; @@ -6799,6 +7230,7 @@ void VisualShaderNodeCompare::set_comparison_type(ComparisonType p_comparison_ty set_input_port_default_value(1, 0.0, get_input_port_default_value(1)); simple_decl = true; break; + case CTYPE_SCALAR_UINT: case CTYPE_SCALAR_INT: set_input_port_default_value(0, 0, get_input_port_default_value(0)); set_input_port_default_value(1, 0, get_input_port_default_value(1)); @@ -6886,12 +7318,13 @@ void VisualShaderNodeCompare::_bind_methods() { ClassDB::bind_method(D_METHOD("set_condition", "condition"), &VisualShaderNodeCompare::set_condition); ClassDB::bind_method(D_METHOD("get_condition"), &VisualShaderNodeCompare::get_condition); - ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, "Float,Int,Vector2,Vector3,Vector4,Boolean,Transform"), "set_comparison_type", "get_comparison_type"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, "Float,Int,UInt,Vector2,Vector3,Vector4,Boolean,Transform"), "set_comparison_type", "get_comparison_type"); ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, "a == b,a != b,a > b,a >= b,a < b,a <= b"), "set_function", "get_function"); ADD_PROPERTY(PropertyInfo(Variant::INT, "condition", PROPERTY_HINT_ENUM, "All,Any"), "set_condition", "get_condition"); BIND_ENUM_CONSTANT(CTYPE_SCALAR); BIND_ENUM_CONSTANT(CTYPE_SCALAR_INT); + BIND_ENUM_CONSTANT(CTYPE_SCALAR_UINT); BIND_ENUM_CONSTANT(CTYPE_VECTOR_2D); BIND_ENUM_CONSTANT(CTYPE_VECTOR_3D); BIND_ENUM_CONSTANT(CTYPE_VECTOR_4D); @@ -7261,12 +7694,15 @@ bool VisualShaderNodeProximityFade::has_output_port_preview(int p_port) const { return false; } +String VisualShaderNodeProximityFade::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const { + return "uniform sampler2D " + make_unique_id(p_type, p_id, "depth_tex") + " : hint_depth_texture;\n"; +} + String VisualShaderNodeProximityFade::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { String code; code += " {\n"; - String proximity_fade_distance = vformat("%s", p_input_vars[0]); - code += " float __depth_tex = textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).r;\n"; + code += " float __depth_tex = texture(" + make_unique_id(p_type, p_id, "depth_tex") + ", SCREEN_UV).r;\n"; if (!RenderingServer::get_singleton()->is_low_end()) { code += " vec4 __depth_world_pos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, __depth_tex, 1.0);\n"; } else { diff --git a/scene/resources/visual_shader_nodes.h b/scene/resources/visual_shader_nodes.h index b2d71a35a6..e3b101cf84 100644 --- a/scene/resources/visual_shader_nodes.h +++ b/scene/resources/visual_shader_nodes.h @@ -160,6 +160,36 @@ public: /////////////////////////////////////// +class VisualShaderNodeUIntConstant : public VisualShaderNodeConstant { + GDCLASS(VisualShaderNodeUIntConstant, VisualShaderNodeConstant); + int constant = 0; + +protected: + static void _bind_methods(); + +public: + virtual String get_caption() const override; + + virtual int get_input_port_count() const override; + virtual PortType get_input_port_type(int p_port) const override; + virtual String get_input_port_name(int p_port) const override; + + virtual int get_output_port_count() const override; + virtual PortType get_output_port_type(int p_port) const override; + virtual String get_output_port_name(int p_port) const override; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override; + + void set_constant(int p_constant); + int get_constant() const; + + virtual Vector<StringName> get_editable_properties() const override; + + VisualShaderNodeUIntConstant(); +}; + +/////////////////////////////////////// + class VisualShaderNodeBooleanConstant : public VisualShaderNodeConstant { GDCLASS(VisualShaderNodeBooleanConstant, VisualShaderNodeConstant); bool constant = false; @@ -355,6 +385,8 @@ public: SOURCE_2D_NORMAL, SOURCE_DEPTH, SOURCE_PORT, + SOURCE_3D_NORMAL, + SOURCE_ROUGHNESS, SOURCE_MAX, }; @@ -638,6 +670,7 @@ public: virtual String get_output_port_name(int p_port) const override; virtual bool has_output_port_preview(int p_port) const override; + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override; virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override; VisualShaderNodeLinearSceneDepth(); @@ -741,6 +774,54 @@ public: VARIANT_ENUM_CAST(VisualShaderNodeIntOp::Operator) +class VisualShaderNodeUIntOp : public VisualShaderNode { + GDCLASS(VisualShaderNodeUIntOp, VisualShaderNode); + +public: + enum Operator { + OP_ADD, + OP_SUB, + OP_MUL, + OP_DIV, + OP_MOD, + OP_MAX, + OP_MIN, + OP_BITWISE_AND, + OP_BITWISE_OR, + OP_BITWISE_XOR, + OP_BITWISE_LEFT_SHIFT, + OP_BITWISE_RIGHT_SHIFT, + OP_ENUM_SIZE, + }; + +protected: + Operator op = OP_ADD; + + static void _bind_methods(); + +public: + virtual String get_caption() const override; + + virtual int get_input_port_count() const override; + virtual PortType get_input_port_type(int p_port) const override; + virtual String get_input_port_name(int p_port) const override; + + virtual int get_output_port_count() const override; + virtual PortType get_output_port_type(int p_port) const override; + virtual String get_output_port_name(int p_port) const override; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override; + + void set_operator(Operator p_op); + Operator get_operator() const; + + virtual Vector<StringName> get_editable_properties() const override; + + VisualShaderNodeUIntOp(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeUIntOp::Operator) + class VisualShaderNodeVectorOp : public VisualShaderNodeVectorBase { GDCLASS(VisualShaderNodeVectorOp, VisualShaderNodeVectorBase); @@ -1047,6 +1128,48 @@ public: VARIANT_ENUM_CAST(VisualShaderNodeIntFunc::Function) /////////////////////////////////////// +/// UINT FUNC +/////////////////////////////////////// + +class VisualShaderNodeUIntFunc : public VisualShaderNode { + GDCLASS(VisualShaderNodeUIntFunc, VisualShaderNode); + +public: + enum Function { + FUNC_NEGATE, + FUNC_BITWISE_NOT, + FUNC_MAX, + }; + +protected: + Function func = FUNC_NEGATE; + + static void _bind_methods(); + +public: + virtual String get_caption() const override; + + virtual int get_input_port_count() const override; + virtual PortType get_input_port_type(int p_port) const override; + virtual String get_input_port_name(int p_port) const override; + + virtual int get_output_port_count() const override; + virtual PortType get_output_port_type(int p_port) const override; + virtual String get_output_port_name(int p_port) const override; + + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override; + + void set_function(Function p_func); + Function get_function() const; + + virtual Vector<StringName> get_editable_properties() const override; + + VisualShaderNodeUIntFunc(); +}; + +VARIANT_ENUM_CAST(VisualShaderNodeUIntFunc::Function) + +/////////////////////////////////////// /// VECTOR FUNC /////////////////////////////////////// @@ -1356,6 +1479,7 @@ public: enum OpType { OP_TYPE_FLOAT, OP_TYPE_INT, + OP_TYPE_UINT, OP_TYPE_VECTOR_2D, OP_TYPE_VECTOR_3D, OP_TYPE_VECTOR_4D, @@ -1902,6 +2026,49 @@ VARIANT_ENUM_CAST(VisualShaderNodeIntParameter::Hint) /////////////////////////////////////// +class VisualShaderNodeUIntParameter : public VisualShaderNodeParameter { + GDCLASS(VisualShaderNodeUIntParameter, VisualShaderNodeParameter); + +private: + bool default_value_enabled = false; + int default_value = 0; + +protected: + static void _bind_methods(); + +public: + virtual String get_caption() const override; + + virtual int get_input_port_count() const override; + virtual PortType get_input_port_type(int p_port) const override; + virtual String get_input_port_name(int p_port) const override; + + virtual int get_output_port_count() const override; + virtual PortType get_output_port_type(int p_port) const override; + virtual String get_output_port_name(int p_port) const override; + + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override; + virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override; + + virtual bool is_show_prop_names() const override; + virtual bool is_use_prop_slots() const override; + + void set_default_value_enabled(bool p_enabled); + bool is_default_value_enabled() const; + + void set_default_value(int p_value); + int get_default_value() const; + + bool is_qualifier_supported(Qualifier p_qual) const override; + bool is_convertible_to_constant() const override; + + virtual Vector<StringName> get_editable_properties() const override; + + VisualShaderNodeUIntParameter(); +}; + +/////////////////////////////////////// + class VisualShaderNodeBooleanParameter : public VisualShaderNodeParameter { GDCLASS(VisualShaderNodeBooleanParameter, VisualShaderNodeParameter); @@ -2198,11 +2365,20 @@ public: REPEAT_MAX, }; + enum TextureSource { + SOURCE_NONE, + SOURCE_SCREEN, + SOURCE_DEPTH, + SOURCE_NORMAL_ROUGHNESS, + SOURCE_MAX, + }; + protected: TextureType texture_type = TYPE_DATA; ColorDefault color_default = COLOR_DEFAULT_WHITE; TextureFilter texture_filter = FILTER_DEFAULT; TextureRepeat texture_repeat = REPEAT_DEFAULT; + TextureSource texture_source = SOURCE_NONE; protected: static void _bind_methods(); @@ -2234,6 +2410,9 @@ public: void set_texture_repeat(TextureRepeat p_repeat); TextureRepeat get_texture_repeat() const; + void set_texture_source(TextureSource p_source); + TextureSource get_texture_source() const; + bool is_qualifier_supported(Qualifier p_qual) const override; bool is_convertible_to_constant() const override; @@ -2244,6 +2423,7 @@ VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::TextureType) VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::ColorDefault) VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::TextureFilter) VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::TextureRepeat) +VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::TextureSource) /////////////////////////////////////// @@ -2361,6 +2541,7 @@ public: enum OpType { OP_TYPE_FLOAT, OP_TYPE_INT, + OP_TYPE_UINT, OP_TYPE_VECTOR_2D, OP_TYPE_VECTOR_3D, OP_TYPE_VECTOR_4D, @@ -2476,6 +2657,7 @@ public: enum ComparisonType { CTYPE_SCALAR, CTYPE_SCALAR_INT, + CTYPE_SCALAR_UINT, CTYPE_VECTOR_2D, CTYPE_VECTOR_3D, CTYPE_VECTOR_4D, @@ -2667,6 +2849,7 @@ public: virtual String get_output_port_name(int p_port) const override; virtual bool has_output_port_preview(int p_port) const override; + virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override; virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override; VisualShaderNodeProximityFade(); diff --git a/scene/resources/visual_shader_particle_nodes.cpp b/scene/resources/visual_shader_particle_nodes.cpp index 4ac663f7f2..9cf42b681c 100644 --- a/scene/resources/visual_shader_particle_nodes.cpp +++ b/scene/resources/visual_shader_particle_nodes.cpp @@ -911,11 +911,12 @@ void VisualShaderNodeParticleRandomness::_bind_methods() { ClassDB::bind_method(D_METHOD("set_op_type", "type"), &VisualShaderNodeParticleRandomness::set_op_type); ClassDB::bind_method(D_METHOD("get_op_type"), &VisualShaderNodeParticleRandomness::get_op_type); - ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Scalar,Vector2,Vector3"), "set_op_type", "get_op_type"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Scalar,Vector2,Vector3,Vector4"), "set_op_type", "get_op_type"); BIND_ENUM_CONSTANT(OP_TYPE_SCALAR); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_2D); BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_3D); + BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_4D); BIND_ENUM_CONSTANT(OP_TYPE_MAX); } @@ -939,6 +940,8 @@ VisualShaderNodeParticleRandomness::PortType VisualShaderNodeParticleRandomness: return PORT_TYPE_VECTOR_2D; case OP_TYPE_VECTOR_3D: return PORT_TYPE_VECTOR_3D; + case OP_TYPE_VECTOR_4D: + return PORT_TYPE_VECTOR_4D; default: break; } @@ -950,48 +953,69 @@ String VisualShaderNodeParticleRandomness::get_output_port_name(int p_port) cons } int VisualShaderNodeParticleRandomness::get_input_port_count() const { - return 2; + return 3; } VisualShaderNodeParticleRandomness::PortType VisualShaderNodeParticleRandomness::get_input_port_type(int p_port) const { - switch (op_type) { - case OP_TYPE_VECTOR_2D: - return PORT_TYPE_VECTOR_2D; - case OP_TYPE_VECTOR_3D: - return PORT_TYPE_VECTOR_3D; - default: + switch (p_port) { + case 0: + return PORT_TYPE_SCALAR_UINT; + case 1: + case 2: + switch (op_type) { + case OP_TYPE_VECTOR_2D: + return PORT_TYPE_VECTOR_2D; + case OP_TYPE_VECTOR_3D: + return PORT_TYPE_VECTOR_3D; + case OP_TYPE_VECTOR_4D: + return PORT_TYPE_VECTOR_4D; + default: + break; + } break; } return PORT_TYPE_SCALAR; } String VisualShaderNodeParticleRandomness::get_input_port_name(int p_port) const { - if (p_port == 0) { - return "min"; - } else if (p_port == 1) { - return "max"; + switch (p_port) { + case 0: + return "seed"; + case 1: + return "min"; + case 2: + return "max"; } return String(); } -String VisualShaderNodeParticleRandomness::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { +bool VisualShaderNodeParticleRandomness::is_input_port_default(int p_port, Shader::Mode p_mode) const { + return p_port == 0; // seed +} + +String VisualShaderNodeParticleRandomness::generate_global_per_node(Shader::Mode p_mode, int p_id) const { String code; - switch (op_type) { - case OP_TYPE_SCALAR: { - code += vformat(" %s = __randf_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]); - } break; - case OP_TYPE_VECTOR_2D: { - code += vformat(" %s = __randv2_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]); - } break; - case OP_TYPE_VECTOR_3D: { - code += vformat(" %s = __randv3_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]); - } break; - default: - break; - } + + code += "vec2 __randv2_range(inout uint seed, vec2 from, vec2 to) {\n"; + code += " return vec2(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y));\n"; + code += "}\n\n"; + + code += "vec3 __randv3_range(inout uint seed, vec3 from, vec3 to) {\n"; + code += " return vec3(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z));\n"; + code += "}\n\n"; + + code += "vec4 __randv4_range(inout uint seed, vec4 from, vec4 to) {\n"; + code += " return vec4(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z), __randf_range(seed, from.w, to.w));\n"; + code += "}\n\n"; + return code; } +String VisualShaderNodeParticleRandomness::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const { + static const char *func[(int)OP_TYPE_MAX] = { "__randf_range", "__randv2_range", "__randv3_range", "__randv4_range" }; + return vformat(" %s = %s(%s, %s, %s);\n", p_output_vars[0], func[op_type], p_input_vars[0].is_empty() ? "__seed" : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1], p_input_vars[2].is_empty() ? (String)get_input_port_default_value(2) : p_input_vars[2]); +} + void VisualShaderNodeParticleRandomness::set_op_type(OpType p_op_type) { ERR_FAIL_INDEX(int(p_op_type), int(OP_TYPE_MAX)); if (op_type == p_op_type) { @@ -999,16 +1023,20 @@ void VisualShaderNodeParticleRandomness::set_op_type(OpType p_op_type) { } switch (p_op_type) { case OP_TYPE_SCALAR: { - set_input_port_default_value(0, 0.0, get_input_port_default_value(0)); set_input_port_default_value(1, 0.0, get_input_port_default_value(1)); + set_input_port_default_value(2, 0.0, get_input_port_default_value(2)); } break; case OP_TYPE_VECTOR_2D: { - set_input_port_default_value(0, Vector2(), get_input_port_default_value(0)); set_input_port_default_value(1, Vector2(), get_input_port_default_value(1)); + set_input_port_default_value(2, Vector2(), get_input_port_default_value(2)); } break; case OP_TYPE_VECTOR_3D: { - set_input_port_default_value(0, Vector3(), get_input_port_default_value(0)); set_input_port_default_value(1, Vector3(), get_input_port_default_value(1)); + set_input_port_default_value(2, Vector3(), get_input_port_default_value(2)); + } break; + case OP_TYPE_VECTOR_4D: { + set_input_port_default_value(1, Quaternion(), get_input_port_default_value(1)); + set_input_port_default_value(2, Quaternion(), get_input_port_default_value(2)); } break; default: break; @@ -1026,8 +1054,8 @@ bool VisualShaderNodeParticleRandomness::has_output_port_preview(int p_port) con } VisualShaderNodeParticleRandomness::VisualShaderNodeParticleRandomness() { - set_input_port_default_value(0, -1.0); - set_input_port_default_value(1, 1.0); + set_input_port_default_value(1, -1.0); + set_input_port_default_value(2, 1.0); } // VisualShaderNodeParticleAccelerator diff --git a/scene/resources/visual_shader_particle_nodes.h b/scene/resources/visual_shader_particle_nodes.h index c0ab974693..08fb059534 100644 --- a/scene/resources/visual_shader_particle_nodes.h +++ b/scene/resources/visual_shader_particle_nodes.h @@ -216,6 +216,7 @@ public: OP_TYPE_SCALAR, OP_TYPE_VECTOR_2D, OP_TYPE_VECTOR_3D, + OP_TYPE_VECTOR_4D, OP_TYPE_MAX, }; @@ -232,12 +233,14 @@ public: virtual int get_input_port_count() const override; virtual PortType get_input_port_type(int p_port) const override; virtual String get_input_port_name(int p_port) const override; + virtual bool is_input_port_default(int p_port, Shader::Mode p_mode) const override; virtual int get_output_port_count() const override; virtual PortType get_output_port_type(int p_port) const override; virtual String get_output_port_name(int p_port) const override; virtual bool has_output_port_preview(int p_port) const override; + virtual String generate_global_per_node(Shader::Mode p_mode, int p_id) const override; virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override; void set_op_type(OpType p_type); diff --git a/scene/resources/world_2d.cpp b/scene/resources/world_2d.cpp index f2ec60e084..c35f7360b5 100644 --- a/scene/resources/world_2d.cpp +++ b/scene/resources/world_2d.cpp @@ -75,10 +75,8 @@ World2D::World2D() { PhysicsServer2D::get_singleton()->space_set_active(space, true); PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_GRAVITY, GLOBAL_DEF_BASIC("physics/2d/default_gravity", 980.0)); PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_DEF_BASIC("physics/2d/default_gravity_vector", Vector2(0, 1))); - PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF("physics/2d/default_linear_damp", 0.1)); - ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/default_linear_damp", PropertyInfo(Variant::FLOAT, "physics/2d/default_linear_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater")); - PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF("physics/2d/default_angular_damp", 1.0)); - ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/default_angular_damp", PropertyInfo(Variant::FLOAT, "physics/2d/default_angular_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater")); + PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "physics/2d/default_linear_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"), 0.1)); + PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "physics/2d/default_angular_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"), 1.0)); // Create and configure the navigation_map to be more friendly with pixels than meters. navigation_map = NavigationServer2D::get_singleton()->map_create(); diff --git a/scene/resources/world_3d.cpp b/scene/resources/world_3d.cpp index 272cc5ef78..536edd334b 100644 --- a/scene/resources/world_3d.cpp +++ b/scene/resources/world_3d.cpp @@ -144,10 +144,8 @@ World3D::World3D() { PhysicsServer3D::get_singleton()->space_set_active(space, true); PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_GRAVITY, GLOBAL_DEF_BASIC("physics/3d/default_gravity", 9.8)); PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_DEF_BASIC("physics/3d/default_gravity_vector", Vector3(0, -1, 0))); - PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF("physics/3d/default_linear_damp", 0.1)); - ProjectSettings::get_singleton()->set_custom_property_info("physics/3d/default_linear_damp", PropertyInfo(Variant::FLOAT, "physics/3d/default_linear_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater")); - PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF("physics/3d/default_angular_damp", 0.1)); - ProjectSettings::get_singleton()->set_custom_property_info("physics/3d/default_angular_damp", PropertyInfo(Variant::FLOAT, "physics/3d/default_angular_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater")); + PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "physics/3d/default_linear_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), 0.1)); + PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "physics/3d/default_angular_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), 0.1)); navigation_map = NavigationServer3D::get_singleton()->map_create(); NavigationServer3D::get_singleton()->map_set_active(navigation_map, true); |