diff options
195 files changed, 11596 insertions, 3231 deletions
diff --git a/.editorconfig b/.editorconfig index e51d0d4c60..d4b7fbb471 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,7 +9,7 @@ insert_final_newline = true [*.{cpp,hpp,c,h,mm}] trim_trailing_whitespace = true -[*.py] +[*.{py,cs}] indent_style = space indent_size = 4 diff --git a/CODEOWNERS b/CODEOWNERS index 30d80990a6..27315f2c9d 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -17,7 +17,7 @@ misc/* @akien-mga modules/bullet/* @AndreaCatania modules/enet/* @godotengine/network -modules/gnative/* @karroffel +modules/gdnative/* @karroffel modules/gdscript/* @reduz @vnen @bojidar-bg modules/mbedtls/* @godotengine/network modules/mobile_vr/* @BastiaanOlij diff --git a/SConstruct b/SConstruct index cb1e9fd567..08c5b6d34f 100644 --- a/SConstruct +++ b/SConstruct @@ -145,6 +145,7 @@ opts.Add(EnumVariable('bits', "Target platform bits", 'default', ('default', '32 opts.Add('p', "Platform (alias for 'platform')", '') opts.Add('platform', "Target platform (%s)" % ('|'.join(platform_list), ), '') opts.Add(EnumVariable('target', "Compilation target", 'debug', ('debug', 'release_debug', 'release'))) +opts.Add(EnumVariable('optimize', "Optimization type", 'speed', ('speed', 'size'))) opts.Add(BoolVariable('tools', "Build the tools (a.k.a. the Godot editor)", True)) opts.Add(BoolVariable('use_lto', 'Use link-time optimization', False)) @@ -416,11 +417,19 @@ if selected_platform in platform_list: if env['tools']: env.Append(CPPDEFINES=['TOOLS_ENABLED']) if env['disable_3d']: - env.Append(CPPDEFINES=['_3D_DISABLED']) + if env['tools']: + print("Build option 'disable_3d=yes' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template).") + sys.exit(255) + else: + env.Append(CPPDEFINES=['_3D_DISABLED']) if env['gdscript']: env.Append(CPPDEFINES=['GDSCRIPT_ENABLED']) if env['disable_advanced_gui']: - env.Append(CPPDEFINES=['ADVANCED_GUI_DISABLED']) + if env['tools']: + print("Build option 'disable_advanced_gui=yes' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template).") + sys.exit(255) + else: + env.Append(CPPDEFINES=['ADVANCED_GUI_DISABLED']) if env['minizip']: env.Append(CPPDEFINES=['MINIZIP_ENABLED']) if env['xml']: diff --git a/core/image.cpp b/core/image.cpp index b0bed80a6f..19440d1718 100644 --- a/core/image.cpp +++ b/core/image.cpp @@ -33,6 +33,7 @@ #include "core/io/image_loader.h" #include "core/os/copymem.h" #include "hash_map.h" +#include "math_funcs.h" #include "print_string.h" #include "thirdparty/misc/hq2x.h" @@ -525,7 +526,7 @@ static double _bicubic_interp_kernel(double x) { } template <int CC> -static void _scale_cubic(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { +static void _scale_cubic(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { // get source image size int width = p_src_width; @@ -555,7 +556,7 @@ static void _scale_cubic(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_wi // initial pixel value - uint8_t *dst = p_dst + (y * p_dst_width + x) * CC; + uint8_t *__restrict dst = p_dst + (y * p_dst_width + x) * CC; double color[CC]; for (int i = 0; i < CC; i++) { @@ -583,7 +584,7 @@ static void _scale_cubic(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_wi ox2 = xmax; // get pixel of original image - const uint8_t *p = p_src + (oy2 * p_src_width + ox2) * CC; + const uint8_t *__restrict p = p_src + (oy2 * p_src_width + ox2) * CC; for (int i = 0; i < CC; i++) { @@ -600,7 +601,7 @@ static void _scale_cubic(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_wi } template <int CC> -static void _scale_bilinear(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { +static void _scale_bilinear(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { enum { FRAC_BITS = 8, @@ -655,7 +656,7 @@ static void _scale_bilinear(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src } template <int CC> -static void _scale_nearest(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { +static void _scale_nearest(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) { for (uint32_t i = 0; i < p_dst_height; i++) { @@ -676,6 +677,16 @@ static void _scale_nearest(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_ } } +static void _overlay(const uint8_t *__restrict p_src, uint8_t *__restrict p_dst, float p_alpha, uint32_t p_width, uint32_t p_height, uint32_t p_pixel_size) { + + uint16_t alpha = CLAMP((uint16_t)(p_alpha * 256.0f), 0, 256); + + for (uint32_t i = 0; i < p_width * p_height * p_pixel_size; i++) { + + p_dst[i] = (p_dst[i] * (256 - alpha) + p_src[i] * alpha) >> 8; + } +} + void Image::resize_to_po2(bool p_square) { if (!_can_modify(format)) { @@ -707,6 +718,8 @@ void Image::resize(int p_width, int p_height, Interpolation p_interpolation) { ERR_FAIL(); } + bool mipmap_aware = p_interpolation == INTERPOLATE_TRILINEAR /* || p_interpolation == INTERPOLATE_TRICUBIC */; + ERR_FAIL_COND(p_width <= 0); ERR_FAIL_COND(p_height <= 0); ERR_FAIL_COND(p_width > MAX_WIDTH); @@ -717,6 +730,32 @@ void Image::resize(int p_width, int p_height, Interpolation p_interpolation) { Image dst(p_width, p_height, 0, format); + // Setup mipmap-aware scaling + Image dst2; + int mip1; + int mip2; + float mip1_weight; + if (mipmap_aware) { + float avg_scale = ((float)p_width / width + (float)p_height / height) * 0.5f; + if (avg_scale >= 1.0f) { + mipmap_aware = false; + } else { + float level = Math::log(1.0f / avg_scale) / Math::log(2.0f); + mip1 = CLAMP((int)Math::floor(level), 0, get_mipmap_count()); + mip2 = CLAMP((int)Math::ceil(level), 0, get_mipmap_count()); + mip1_weight = 1.0f - (level - mip1); + } + } + bool interpolate_mipmaps = mipmap_aware && mip1 != mip2; + if (interpolate_mipmaps) { + dst2.create(p_width, p_height, 0, format); + } + bool had_mipmaps = mipmaps; + if (interpolate_mipmaps && !had_mipmaps) { + generate_mipmaps(); + } + // -- + PoolVector<uint8_t>::Read r = data.read(); const unsigned char *r_ptr = r.ptr(); @@ -734,13 +773,57 @@ void Image::resize(int p_width, int p_height, Interpolation p_interpolation) { case 4: _scale_nearest<4>(r_ptr, w_ptr, width, height, p_width, p_height); break; } } break; - case INTERPOLATE_BILINEAR: { + case INTERPOLATE_BILINEAR: + case INTERPOLATE_TRILINEAR: { + + for (int i = 0; i < 2; ++i) { + int src_width; + int src_height; + const unsigned char *src_ptr; + + if (!mipmap_aware) { + if (i == 0) { + // Standard behavior + src_width = width; + src_height = height; + src_ptr = r_ptr; + } else { + // No need for a second iteration + break; + } + } else { + if (i == 0) { + // Read from the first mipmap that will be interpolated + // (if both levels are the same, we will not interpolate, but at least we'll sample from the right level) + int offs; + _get_mipmap_offset_and_size(mip1, offs, src_width, src_height); + src_ptr = r_ptr + offs; + } else if (!interpolate_mipmaps) { + // No need generate a second image + break; + } else { + // Switch to read from the second mipmap that will be interpolated + int offs; + _get_mipmap_offset_and_size(mip2, offs, src_width, src_height); + src_ptr = r_ptr + offs; + // Switch to write to the second destination image + w = dst2.data.write(); + w_ptr = w.ptr(); + } + } - switch (get_format_pixel_size(format)) { - case 1: _scale_bilinear<1>(r_ptr, w_ptr, width, height, p_width, p_height); break; - case 2: _scale_bilinear<2>(r_ptr, w_ptr, width, height, p_width, p_height); break; - case 3: _scale_bilinear<3>(r_ptr, w_ptr, width, height, p_width, p_height); break; - case 4: _scale_bilinear<4>(r_ptr, w_ptr, width, height, p_width, p_height); break; + switch (get_format_pixel_size(format)) { + case 1: _scale_bilinear<1>(src_ptr, w_ptr, src_width, src_height, p_width, p_height); break; + case 2: _scale_bilinear<2>(src_ptr, w_ptr, src_width, src_height, p_width, p_height); break; + case 3: _scale_bilinear<3>(src_ptr, w_ptr, src_width, src_height, p_width, p_height); break; + case 4: _scale_bilinear<4>(src_ptr, w_ptr, src_width, src_height, p_width, p_height); break; + } + } + + if (interpolate_mipmaps) { + // Switch to read again from the first scaled mipmap to overlay it over the second + r = dst.data.read(); + _overlay(r.ptr(), w.ptr(), mip1_weight, p_width, p_height, get_format_pixel_size(format)); } } break; @@ -759,7 +842,11 @@ void Image::resize(int p_width, int p_height, Interpolation p_interpolation) { r = PoolVector<uint8_t>::Read(); w = PoolVector<uint8_t>::Write(); - if (mipmaps > 0) + if (interpolate_mipmaps) { + dst._copy_internals_from(dst2); + } + + if (had_mipmaps) dst.generate_mipmaps(); _copy_internals_from(dst); @@ -1898,8 +1985,9 @@ void Image::fill(const Color &c) { unlock(); } -Ref<Image> (*Image::_png_mem_loader_func)(const uint8_t *, int) = NULL; -Ref<Image> (*Image::_jpg_mem_loader_func)(const uint8_t *, int) = NULL; +ImageMemLoadFunc Image::_png_mem_loader_func = NULL; +ImageMemLoadFunc Image::_jpg_mem_loader_func = NULL; +ImageMemLoadFunc Image::_webp_mem_loader_func = NULL; void (*Image::_image_compress_bc_func)(Image *, Image::CompressSource) = NULL; void (*Image::_image_compress_pvrtc2_func)(Image *) = NULL; @@ -2357,6 +2445,7 @@ void Image::_bind_methods() { ClassDB::bind_method(D_METHOD("load_png_from_buffer", "buffer"), &Image::load_png_from_buffer); ClassDB::bind_method(D_METHOD("load_jpg_from_buffer", "buffer"), &Image::load_jpg_from_buffer); + ClassDB::bind_method(D_METHOD("load_webp_from_buffer", "buffer"), &Image::load_webp_from_buffer); ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "_set_data", "_get_data"); @@ -2402,6 +2491,7 @@ void Image::_bind_methods() { BIND_ENUM_CONSTANT(INTERPOLATE_NEAREST); BIND_ENUM_CONSTANT(INTERPOLATE_BILINEAR); BIND_ENUM_CONSTANT(INTERPOLATE_CUBIC); + BIND_ENUM_CONSTANT(INTERPOLATE_TRILINEAR); BIND_ENUM_CONSTANT(ALPHA_NONE); BIND_ENUM_CONSTANT(ALPHA_BIT); @@ -2649,32 +2739,26 @@ String Image::get_format_name(Format p_format) { } Error Image::load_png_from_buffer(const PoolVector<uint8_t> &p_array) { - - int buffer_size = p_array.size(); - - ERR_FAIL_COND_V(buffer_size == 0, ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(!_png_mem_loader_func, ERR_INVALID_PARAMETER); - - PoolVector<uint8_t>::Read r = p_array.read(); - - Ref<Image> image = _png_mem_loader_func(r.ptr(), buffer_size); - ERR_FAIL_COND_V(!image.is_valid(), ERR_PARSE_ERROR); - - copy_internals_from(image); - - return OK; + return _load_from_buffer(p_array, _png_mem_loader_func); } Error Image::load_jpg_from_buffer(const PoolVector<uint8_t> &p_array) { + return _load_from_buffer(p_array, _jpg_mem_loader_func); +} + +Error Image::load_webp_from_buffer(const PoolVector<uint8_t> &p_array) { + return _load_from_buffer(p_array, _webp_mem_loader_func); +} +Error Image::_load_from_buffer(const PoolVector<uint8_t> &p_array, ImageMemLoadFunc p_loader) { int buffer_size = p_array.size(); ERR_FAIL_COND_V(buffer_size == 0, ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(!_jpg_mem_loader_func, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(!p_loader, ERR_INVALID_PARAMETER); PoolVector<uint8_t>::Read r = p_array.read(); - Ref<Image> image = _jpg_mem_loader_func(r.ptr(), buffer_size); + Ref<Image> image = p_loader(r.ptr(), buffer_size); ERR_FAIL_COND_V(!image.is_valid(), ERR_PARSE_ERROR); copy_internals_from(image); diff --git a/core/image.h b/core/image.h index 43516e2c0b..8c4854e053 100644 --- a/core/image.h +++ b/core/image.h @@ -47,6 +47,7 @@ class Image; typedef Error (*SavePNGFunc)(const String &p_path, const Ref<Image> &p_img); +typedef Ref<Image> (*ImageMemLoadFunc)(const uint8_t *p_png, int p_size); class Image : public Resource { GDCLASS(Image, Resource); @@ -107,6 +108,8 @@ public: INTERPOLATE_NEAREST, INTERPOLATE_BILINEAR, INTERPOLATE_CUBIC, + INTERPOLATE_TRILINEAR, + /* INTERPOLATE_TRICUBIC, */ /* INTERPOLATE GAUSS */ }; @@ -118,8 +121,9 @@ public: //some functions provided by something else - static Ref<Image> (*_png_mem_loader_func)(const uint8_t *p_png, int p_size); - static Ref<Image> (*_jpg_mem_loader_func)(const uint8_t *p_png, int p_size); + static ImageMemLoadFunc _png_mem_loader_func; + static ImageMemLoadFunc _jpg_mem_loader_func; + static ImageMemLoadFunc _webp_mem_loader_func; static void (*_image_compress_bc_func)(Image *, CompressSource p_source); static void (*_image_compress_pvrtc2_func)(Image *); @@ -175,6 +179,8 @@ private: void _set_data(const Dictionary &p_data); Dictionary _get_data() const; + Error _load_from_buffer(const PoolVector<uint8_t> &p_array, ImageMemLoadFunc p_loader); + public: int get_width() const; ///< Get image width int get_height() const; ///< Get image height @@ -302,6 +308,7 @@ public: Error load_png_from_buffer(const PoolVector<uint8_t> &p_array); Error load_jpg_from_buffer(const PoolVector<uint8_t> &p_array); + Error load_webp_from_buffer(const PoolVector<uint8_t> &p_array); Image(const uint8_t *p_mem_png_jpg, int p_len = -1); Image(const char **p_xpm); diff --git a/core/message_queue.cpp b/core/message_queue.cpp index 25ee6eafae..3adaad868a 100644 --- a/core/message_queue.cpp +++ b/core/message_queue.cpp @@ -342,7 +342,7 @@ MessageQueue::MessageQueue() { buffer_end = 0; buffer_max_used = 0; - buffer_size = GLOBAL_DEF("memory/limits/message_queue/max_size_kb", DEFAULT_QUEUE_SIZE_KB); + buffer_size = GLOBAL_DEF_RST("memory/limits/message_queue/max_size_kb", DEFAULT_QUEUE_SIZE_KB); buffer_size *= 1024; buffer = memnew_arr(uint8_t, buffer_size); } diff --git a/core/object.cpp b/core/object.cpp index 1d2aeb7ba5..d86c60a3b8 100644 --- a/core/object.cpp +++ b/core/object.cpp @@ -601,8 +601,12 @@ void Object::get_property_list(List<PropertyInfo> *p_list, bool p_reversed) cons _get_property_listv(p_list, p_reversed); - if (!is_class("Script")) // can still be set, but this is for userfriendlyness + if (!is_class("Script")) { // can still be set, but this is for userfriendlyness +#ifdef TOOLS_ENABLED + p_list->push_back(PropertyInfo(Variant::NIL, "Script", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_GROUP)); +#endif p_list->push_back(PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NONZERO)); + } #ifdef TOOLS_ENABLED if (editor_section_folding.size()) { p_list->push_back(PropertyInfo(Variant::ARRAY, CoreStringNames::get_singleton()->_sections_unfolded, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL)); diff --git a/core/os/os.cpp b/core/os/os.cpp index d0a7bc6fbe..89866e4044 100644 --- a/core/os/os.cpp +++ b/core/os/os.cpp @@ -659,9 +659,23 @@ const char *OS::get_audio_driver_name(int p_driver) const { return AudioDriverManager::get_driver(p_driver)->get_name(); } +void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) { + restart_on_exit = p_restart; + restart_commandline = p_restart_arguments; +} + +bool OS::is_restart_on_exit_set() const { + return restart_on_exit; +} + +List<String> OS::get_restart_on_exit_arguments() const { + return restart_commandline; +} + OS::OS() { void *volatile stack_bottom; + restart_on_exit = false; last_error = NULL; singleton = this; _keep_screen_on = true; // set default value to true, because this had been true before godot 2.0. diff --git a/core/os/os.h b/core/os/os.h index adf01a90e7..4e0cb003fb 100644 --- a/core/os/os.h +++ b/core/os/os.h @@ -74,6 +74,9 @@ class OS { CompositeLogger *_logger; + bool restart_on_exit; + List<String> restart_commandline; + protected: void _set_logger(CompositeLogger *p_logger); @@ -182,7 +185,7 @@ public: virtual int get_video_driver_count() const; virtual const char *get_video_driver_name(int p_driver) const; - + virtual int get_current_video_driver() const = 0; virtual int get_audio_driver_count() const; virtual const char *get_audio_driver_name(int p_driver) const; @@ -496,6 +499,11 @@ public: bool is_layered_allowed() const { return _allow_layered; } bool is_hidpi_allowed() const { return _allow_hidpi; } + + void set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments); + bool is_restart_on_exit_set() const; + List<String> get_restart_on_exit_arguments() const; + OS(); virtual ~OS(); }; diff --git a/core/project_settings.cpp b/core/project_settings.cpp index db1d0a604c..60e8933751 100644 --- a/core/project_settings.cpp +++ b/core/project_settings.cpp @@ -105,6 +105,11 @@ void ProjectSettings::set_initial_value(const String &p_name, const Variant &p_v ERR_FAIL_COND(!props.has(p_name)); props[p_name].initial = p_value; } +void ProjectSettings::set_restart_if_changed(const String &p_name, bool p_restart) { + + ERR_FAIL_COND(!props.has(p_name)); + props[p_name].restart_if_changed = p_restart; +} String ProjectSettings::globalize_path(const String &p_path) const { @@ -225,6 +230,9 @@ void ProjectSettings::_get_property_list(List<PropertyInfo> *p_list) const { else vc.flags = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE; + if (v->restart_if_changed) { + vc.flags |= PROPERTY_USAGE_RESTART_IF_CHANGED; + } vclist.insert(vc); } @@ -817,7 +825,7 @@ Error ProjectSettings::save_custom(const String &p_path, const CustomMap &p_cust return OK; } -Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default) { +Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default, bool p_restart_if_changed) { Variant ret; if (!ProjectSettings::get_singleton()->has_setting(p_var)) { @@ -827,6 +835,7 @@ Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default) { ProjectSettings::get_singleton()->set_initial_value(p_var, p_default); ProjectSettings::get_singleton()->set_builtin_order(p_var); + ProjectSettings::get_singleton()->set_restart_if_changed(p_var, p_restart_if_changed); return ret; } @@ -1080,7 +1089,6 @@ ProjectSettings::ProjectSettings() { custom_prop_info["rendering/threads/thread_model"] = PropertyInfo(Variant::INT, "rendering/threads/thread_model", PROPERTY_HINT_ENUM, "Single-Unsafe,Single-Safe,Multi-Threaded"); custom_prop_info["physics/2d/thread_model"] = PropertyInfo(Variant::INT, "physics/2d/thread_model", PROPERTY_HINT_ENUM, "Single-Unsafe,Single-Safe,Multi-Threaded"); custom_prop_info["rendering/quality/intended_usage/framebuffer_allocation"] = PropertyInfo(Variant::INT, "rendering/quality/intended_usage/framebuffer_allocation", PROPERTY_HINT_ENUM, "2D,2D Without Sampling,3D,3D Without Effects"); - GLOBAL_DEF("rendering/quality/intended_usage/framebuffer_mode", 2); GLOBAL_DEF("debug/settings/profiler/max_functions", 16384); diff --git a/core/project_settings.h b/core/project_settings.h index 045d942b31..75ebc5acc8 100644 --- a/core/project_settings.h +++ b/core/project_settings.h @@ -59,18 +59,21 @@ protected: Variant initial; bool hide_from_editor; bool overridden; + bool restart_if_changed; VariantContainer() : order(0), persist(false), hide_from_editor(false), - overridden(false) { + overridden(false), + restart_if_changed(false) { } VariantContainer(const Variant &p_variant, int p_order, bool p_persist = false) : order(p_order), persist(p_persist), variant(p_variant), hide_from_editor(false), - overridden(false) { + overridden(false), + restart_if_changed(false) { } }; @@ -120,6 +123,7 @@ public: String globalize_path(const String &p_path) const; void set_initial_value(const String &p_name, const Variant &p_value); + void set_restart_if_changed(const String &p_name, bool p_restart); bool property_can_revert(const String &p_name); Variant property_get_revert(const String &p_name); @@ -158,8 +162,9 @@ public: }; //not a macro any longer -Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default); +Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default, bool p_restart_if_changed = false); #define GLOBAL_DEF(m_var, m_value) _GLOBAL_DEF(m_var, m_value) +#define GLOBAL_DEF_RST(m_var, m_value) _GLOBAL_DEF(m_var, m_value, true) #define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get(m_var) #endif diff --git a/core/register_core_types.cpp b/core/register_core_types.cpp index 2a611ccf6a..9bcc2d4530 100644 --- a/core/register_core_types.cpp +++ b/core/register_core_types.cpp @@ -191,7 +191,7 @@ void register_core_types() { void register_core_settings() { //since in register core types, globals may not e present - GLOBAL_DEF("network/limits/packet_peer_stream/max_buffer_po2", (16)); + GLOBAL_DEF_RST("network/limits/packet_peer_stream/max_buffer_po2", (16)); } void register_core_singletons() { diff --git a/core/script_language.h b/core/script_language.h index 2950b35109..4e81b9b626 100644 --- a/core/script_language.h +++ b/core/script_language.h @@ -213,7 +213,7 @@ public: virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const = 0; virtual void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {} virtual bool is_using_templates() { return false; } - virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL) const = 0; + virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL, Set<int> *r_safe_lines = NULL) const = 0; virtual String validate_path(const String &p_path) const { return ""; } virtual Script *create_script() const = 0; virtual bool has_named_classes() const = 0; diff --git a/core/ustring.cpp b/core/ustring.cpp index bee5f5ffdb..bb08dd13c4 100644 --- a/core/ustring.cpp +++ b/core/ustring.cpp @@ -921,8 +921,8 @@ String String::to_upper() const { for (int i = 0; i < upper.size(); i++) { - const char s = upper[i]; - const char t = _find_upper(s); + const CharType s = upper[i]; + const CharType t = _find_upper(s); if (s != t) // avoid copy on write upper[i] = t; } @@ -936,8 +936,8 @@ String String::to_lower() const { for (int i = 0; i < lower.size(); i++) { - const char s = lower[i]; - const char t = _find_lower(s); + const CharType s = lower[i]; + const CharType t = _find_lower(s); if (s != t) // avoid copy on write lower[i] = t; } diff --git a/core/vector.h b/core/vector.h index f586471e27..c026448ddd 100644 --- a/core/vector.h +++ b/core/vector.h @@ -152,6 +152,8 @@ public: Error insert(int p_pos, const T &p_val); + void append_array(const Vector<T> &p_other); + template <class C> void sort_custom() { @@ -408,6 +410,17 @@ Error Vector<T>::insert(int p_pos, const T &p_val) { } template <class T> +void Vector<T>::append_array(const Vector<T> &p_other) { + const int ds = p_other.size(); + if (ds == 0) + return; + const int bs = size(); + resize(bs + ds); + for (int i = 0; i < ds; ++i) + operator[](bs + i) = p_other[i]; +} + +template <class T> Vector<T>::Vector(const Vector &p_from) { _ptr = NULL; diff --git a/doc/classes/Image.xml b/doc/classes/Image.xml index 9fc7672a80..55693bd49c 100644 --- a/doc/classes/Image.xml +++ b/doc/classes/Image.xml @@ -350,6 +350,15 @@ Loads an image from the binary contents of a PNG file. </description> </method> + <method name="load_webp_from_buffer"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="buffer" type="PoolByteArray"> + </argument> + <description> + Loads an image from the binary contents of a WebP file. + </description> + </method> <method name="lock"> <return type="void"> </return> @@ -584,6 +593,12 @@ </constant> <constant name="INTERPOLATE_CUBIC" value="2" enum="Interpolation"> </constant> + <constant name="INTERPOLATE_TRILINEAR" value="3" enum="Interpolation"> + Performs bilinear separately on the two most suited mipmap levels, then linearly interpolates between them. + It's slower than [code]INTERPOLATE_BILINEAR[/code], but produces higher quality results, with much less aliasing artifacts. + If the image does not have mipmaps, they will be generated and used internally, but no mipmaps will be generated on the resulting image. (Note that if you intend to scale multiple copies of the original image, it's better to call [code]generate_mipmaps[/code] on it in advance, to avoid wasting processing power in generating them again and again.) + On the other hand, if the image already has mipmaps, they will be used, and a new set will be generated for the resulting image. + </constant> <constant name="ALPHA_NONE" value="0" enum="AlphaMode"> </constant> <constant name="ALPHA_BIT" value="1" enum="AlphaMode"> diff --git a/doc/classes/TileMap.xml b/doc/classes/TileMap.xml index 656063771d..3486b721ca 100644 --- a/doc/classes/TileMap.xml +++ b/doc/classes/TileMap.xml @@ -153,6 +153,8 @@ Sets the tile index for the cell given by a Vector2. An index of [code]-1[/code] clears the cell. Optionally, the tile can also be flipped, transposed, or given autotile coordinates. + Note that data such as navigation polygons and collision shapes are not immediately updated for performance reasons. + If you need these to be immediately updated, you can call [method update_dirty_quadrants]. </description> </method> <method name="set_cellv"> @@ -172,6 +174,8 @@ Sets the tile index for the given cell. An index of [code]-1[/code] clears the cell. Optionally, the tile can also be flipped or transposed. + Note that data such as navigation polygons and collision shapes are not immediately updated for performance reasons. + If you need these to be immediately updated, you can call [method update_dirty_quadrants]. </description> </method> <method name="set_collision_layer_bit"> @@ -217,6 +221,13 @@ Calling with invalid (or missing) parameters applies autotiling rules for the entire tilemap. </description> </method> + <method name="update_dirty_quadrants"> + <return type="void"> + </return> + <description> + Updates the tile map's quadrants, allowing things such as navigation and collision shapes to be immediately used if modified. + </description> + </method> <method name="world_to_map" qualifiers="const"> <return type="Vector2"> </return> diff --git a/drivers/alsa/audio_driver_alsa.cpp b/drivers/alsa/audio_driver_alsa.cpp index ae85ee50d1..08005efa9d 100644 --- a/drivers/alsa/audio_driver_alsa.cpp +++ b/drivers/alsa/audio_driver_alsa.cpp @@ -58,7 +58,10 @@ Error AudioDriverALSA::init_device() { #define CHECK_FAIL(m_cond) \ if (m_cond) { \ fprintf(stderr, "ALSA ERR: %s\n", snd_strerror(status)); \ - snd_pcm_close(pcm_handle); \ + if (pcm_handle) { \ + snd_pcm_close(pcm_handle); \ + pcm_handle = NULL; \ + } \ ERR_FAIL_COND_V(m_cond, ERR_CANT_OPEN); \ } @@ -150,7 +153,6 @@ Error AudioDriverALSA::init() { active = false; thread_exited = false; exit_thread = false; - pcm_open = false; Error err = init_device(); if (err == OK) { @@ -313,9 +315,9 @@ void AudioDriverALSA::unlock() { void AudioDriverALSA::finish_device() { - if (pcm_open) { + if (pcm_handle) { snd_pcm_close(pcm_handle); - pcm_open = NULL; + pcm_handle = NULL; } } diff --git a/drivers/alsa/audio_driver_alsa.h b/drivers/alsa/audio_driver_alsa.h index 2878e100a2..e2a2325cf3 100644 --- a/drivers/alsa/audio_driver_alsa.h +++ b/drivers/alsa/audio_driver_alsa.h @@ -66,7 +66,6 @@ class AudioDriverALSA : public AudioDriver { bool active; bool thread_exited; mutable bool exit_thread; - bool pcm_open; public: const char *get_name() const { diff --git a/drivers/coreaudio/audio_driver_coreaudio.cpp b/drivers/coreaudio/audio_driver_coreaudio.cpp index 63af4506f3..ac21de91e4 100644 --- a/drivers/coreaudio/audio_driver_coreaudio.cpp +++ b/drivers/coreaudio/audio_driver_coreaudio.cpp @@ -102,7 +102,7 @@ Error AudioDriverCoreAudio::init() { break; } - mix_rate = GLOBAL_DEF("audio/mix_rate", DEFAULT_MIX_RATE); + mix_rate = GLOBAL_DEF_RST("audio/mix_rate", DEFAULT_MIX_RATE); zeromem(&strdesc, sizeof(strdesc)); strdesc.mFormatID = kAudioFormatLinearPCM; @@ -117,7 +117,7 @@ Error AudioDriverCoreAudio::init() { result = AudioUnitSetProperty(audio_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, kOutputBus, &strdesc, sizeof(strdesc)); ERR_FAIL_COND_V(result != noErr, FAILED); - int latency = GLOBAL_DEF("audio/output_latency", DEFAULT_OUTPUT_LATENCY); + int latency = GLOBAL_DEF_RST("audio/output_latency", DEFAULT_OUTPUT_LATENCY); // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels) buffer_frames = closest_power_of_2(latency * mix_rate / 1000); diff --git a/drivers/gles2/rasterizer_canvas_gles2.cpp b/drivers/gles2/rasterizer_canvas_gles2.cpp index daa421d45c..fb150d6820 100644 --- a/drivers/gles2/rasterizer_canvas_gles2.cpp +++ b/drivers/gles2/rasterizer_canvas_gles2.cpp @@ -409,8 +409,6 @@ void RasterizerCanvasGLES2::_canvas_item_render_commands(Item *p_item, Item *cur Rect2 dst_rect = Rect2(r->rect.position, r->rect.size); - state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, texpixel_size); - if (dst_rect.size.width < 0) { dst_rect.position.x += dst_rect.size.width; dst_rect.size.width *= -1; @@ -663,6 +661,8 @@ void RasterizerCanvasGLES2::_canvas_item_render_commands(Item *p_item, Item *cur if (state.canvas_shader.bind()) _set_uniforms(); + _bind_canvas_texture(RID(), RID()); + if (pline->triangles.size()) { _draw_generic(GL_TRIANGLE_STRIP, pline->triangles.size(), pline->triangles.ptr(), NULL, pline->triangle_colors.ptr(), pline->triangle_colors.size() == 1); } else { diff --git a/drivers/gles2/rasterizer_storage_gles2.cpp b/drivers/gles2/rasterizer_storage_gles2.cpp index 2da496d4b7..0dc506d991 100644 --- a/drivers/gles2/rasterizer_storage_gles2.cpp +++ b/drivers/gles2/rasterizer_storage_gles2.cpp @@ -2005,6 +2005,8 @@ void RasterizerStorageGLES2::initialize() { } } + config.shrink_textures_x2 = false; + frame.count = 0; frame.prev_tick = 0; frame.delta = 0; diff --git a/drivers/gles2/shader_compiler_gles2.cpp b/drivers/gles2/shader_compiler_gles2.cpp index aa55e72083..549d91a5a0 100644 --- a/drivers/gles2/shader_compiler_gles2.cpp +++ b/drivers/gles2/shader_compiler_gles2.cpp @@ -721,8 +721,6 @@ ShaderCompilerGLES2::ShaderCompilerGLES2() { actions[VS::SHADER_CANVAS_ITEM].renames["NORMAL"] = "normal"; actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP"] = "normal_map"; actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP_DEPTH"] = "normal_depth"; - actions[VS::SHADER_CANVAS_ITEM].renames["UV"] = "uv_interp"; - actions[VS::SHADER_CANVAS_ITEM].renames["COLOR"] = "color"; actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE"] = "color_texture"; actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE_PIXEL_SIZE"] = "color_texpixel_size"; actions[VS::SHADER_CANVAS_ITEM].renames["NORMAL_TEXTURE"] = "normal_texture"; @@ -736,7 +734,6 @@ ShaderCompilerGLES2::ShaderCompilerGLES2() { actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_HEIGHT"] = "light_height"; actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_COLOR"] = "light_color"; actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_UV"] = "light_uv"; - //actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_SHADOW_COLOR"]="light_shadow_color"; actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT"] = "light"; actions[VS::SHADER_CANVAS_ITEM].renames["SHADOW_COLOR"] = "shadow_color"; @@ -768,7 +765,8 @@ ShaderCompilerGLES2::ShaderCompilerGLES2() { actions[VS::SHADER_SPATIAL].renames["UV2"] = "uv2_interp"; actions[VS::SHADER_SPATIAL].renames["COLOR"] = "color_interp"; actions[VS::SHADER_SPATIAL].renames["POINT_SIZE"] = "gl_PointSize"; - //actions[VS::SHADER_SPATIAL].renames["INSTANCE_ID"]=ShaderLanguage::TYPE_INT; + // gl_InstanceID is not available in OpenGL ES 2.0 + actions[VS::SHADER_SPATIAL].renames["INSTANCE_ID"] = "0"; //builtins @@ -790,13 +788,11 @@ ShaderCompilerGLES2::ShaderCompilerGLES2() { actions[VS::SHADER_SPATIAL].renames["CLEARCOAT_GLOSS"] = "clearcoat_gloss"; actions[VS::SHADER_SPATIAL].renames["ANISOTROPY"] = "anisotropy"; actions[VS::SHADER_SPATIAL].renames["ANISOTROPY_FLOW"] = "anisotropy_flow"; - //actions[VS::SHADER_SPATIAL].renames["SSS_SPREAD"] = "sss_spread"; actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"] = "sss_strength"; actions[VS::SHADER_SPATIAL].renames["TRANSMISSION"] = "transmission"; actions[VS::SHADER_SPATIAL].renames["AO"] = "ao"; actions[VS::SHADER_SPATIAL].renames["AO_LIGHT_AFFECT"] = "ao_light_affect"; actions[VS::SHADER_SPATIAL].renames["EMISSION"] = "emission"; - //actions[VS::SHADER_SPATIAL].renames["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2; actions[VS::SHADER_SPATIAL].renames["POINT_COORD"] = "gl_PointCoord"; actions[VS::SHADER_SPATIAL].renames["INSTANCE_CUSTOM"] = "instance_custom"; actions[VS::SHADER_SPATIAL].renames["SCREEN_UV"] = "screen_uv"; @@ -838,8 +834,6 @@ ShaderCompilerGLES2::ShaderCompilerGLES2() { actions[VS::SHADER_SPATIAL].usage_defines["DIFFUSE_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n"; actions[VS::SHADER_SPATIAL].usage_defines["SPECULAR_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n"; - actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"] = "sss_strength"; - actions[VS::SHADER_SPATIAL].render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n"; actions[VS::SHADER_SPATIAL].render_mode_defines["world_vertex_coords"] = "#define VERTEX_WORLD_COORDS_USED\n"; diff --git a/drivers/gles3/rasterizer_canvas_gles3.cpp b/drivers/gles3/rasterizer_canvas_gles3.cpp index f859e49b5b..5e13bed198 100644 --- a/drivers/gles3/rasterizer_canvas_gles3.cpp +++ b/drivers/gles3/rasterizer_canvas_gles3.cpp @@ -1895,7 +1895,7 @@ void RasterizerCanvasGLES3::initialize() { } { - uint32_t poly_size = GLOBAL_DEF("rendering/limits/buffers/canvas_polygon_buffer_size_kb", 128); + uint32_t poly_size = GLOBAL_DEF_RST("rendering/limits/buffers/canvas_polygon_buffer_size_kb", 128); poly_size *= 1024; //kb poly_size = MAX(poly_size, (2 + 2 + 4) * 4 * sizeof(float)); glGenBuffers(1, &data.polygon_buffer); @@ -1942,7 +1942,7 @@ void RasterizerCanvasGLES3::initialize() { glGenVertexArrays(1, &data.polygon_buffer_pointer_array); - uint32_t index_size = GLOBAL_DEF("rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", 128); + uint32_t index_size = GLOBAL_DEF_RST("rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", 128); index_size *= 1024; //kb glGenBuffers(1, &data.polygon_index_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.polygon_index_buffer); diff --git a/drivers/gles3/rasterizer_scene_gles3.cpp b/drivers/gles3/rasterizer_scene_gles3.cpp index 9d0fb462f4..2b7cea8508 100644 --- a/drivers/gles3/rasterizer_scene_gles3.cpp +++ b/drivers/gles3/rasterizer_scene_gles3.cpp @@ -4086,6 +4086,7 @@ void RasterizerSceneGLES3::render_scene(const Transform &p_cam_transform, const state.ubo_data.z_slope_scale = 0; state.ubo_data.shadow_dual_paraboloid_render_side = 0; state.ubo_data.shadow_dual_paraboloid_render_zfar = 0; + state.ubo_data.opaque_prepass_threshold = 0.99; p_cam_projection.get_viewport_size(state.ubo_data.viewport_size[0], state.ubo_data.viewport_size[1]); @@ -4698,6 +4699,7 @@ void RasterizerSceneGLES3::render_shadow(RID p_light, RID p_shadow_atlas, int p_ state.ubo_data.z_slope_scale = normal_bias; state.ubo_data.shadow_dual_paraboloid_render_side = dp_direction; state.ubo_data.shadow_dual_paraboloid_render_zfar = zfar; + state.ubo_data.opaque_prepass_threshold = 0.1; _setup_environment(NULL, light_projection, light_transform); @@ -4866,7 +4868,7 @@ void RasterizerSceneGLES3::initialize() { glBufferData(GL_UNIFORM_BUFFER, sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_ubo, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); - render_list.max_elements = GLOBAL_DEF("rendering/limits/rendering/max_renderable_elements", (int)RenderList::DEFAULT_MAX_ELEMENTS); + render_list.max_elements = GLOBAL_DEF_RST("rendering/limits/rendering/max_renderable_elements", (int)RenderList::DEFAULT_MAX_ELEMENTS); if (render_list.max_elements > 1000000) render_list.max_elements = 1000000; if (render_list.max_elements < 1024) diff --git a/drivers/gles3/rasterizer_scene_gles3.h b/drivers/gles3/rasterizer_scene_gles3.h index 524212b9c1..cf387a69bc 100644 --- a/drivers/gles3/rasterizer_scene_gles3.h +++ b/drivers/gles3/rasterizer_scene_gles3.h @@ -141,6 +141,7 @@ public: float subsurface_scatter_width; float ambient_occlusion_affect_light; float ambient_occlusion_affect_ssao; + float opaque_prepass_threshold; uint32_t fog_depth_enabled; float fog_depth_begin; @@ -152,7 +153,7 @@ public: float fog_height_max; float fog_height_curve; // make sure this struct is padded to be a multiple of 16 bytes for webgl - float pad[3]; + float pad[2]; } ubo_data; diff --git a/drivers/gles3/rasterizer_storage_gles3.cpp b/drivers/gles3/rasterizer_storage_gles3.cpp index eb25d6c7a1..9e389a353e 100644 --- a/drivers/gles3/rasterizer_storage_gles3.cpp +++ b/drivers/gles3/rasterizer_storage_gles3.cpp @@ -3240,7 +3240,7 @@ void RasterizerStorageGLES3::mesh_surface_update_region(RID p_mesh, int p_surfac PoolVector<uint8_t>::Read r = p_data.read(); - glBindBuffer(GL_ARRAY_BUFFER, mesh->surfaces[p_surface]->array_id); + glBindBuffer(GL_ARRAY_BUFFER, mesh->surfaces[p_surface]->vertex_id); glBufferSubData(GL_ARRAY_BUFFER, p_offset, total_size, r.ptr()); glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind } @@ -3404,6 +3404,7 @@ Vector<PoolVector<uint8_t> > RasterizerStorageGLES3::mesh_surface_get_blend_shap return bsarr; } + Vector<AABB> RasterizerStorageGLES3::mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const { const Mesh *mesh = mesh_owner.getornull(p_mesh); @@ -3455,6 +3456,7 @@ void RasterizerStorageGLES3::mesh_remove_surface(RID p_mesh, int p_surface) { mesh->instance_change_notify(); } + int RasterizerStorageGLES3::mesh_get_surface_count(RID p_mesh) const { const Mesh *mesh = mesh_owner.getornull(p_mesh); @@ -3468,6 +3470,7 @@ void RasterizerStorageGLES3::mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb ERR_FAIL_COND(!mesh); mesh->custom_aabb = p_aabb; + mesh->instance_change_notify(); } AABB RasterizerStorageGLES3::mesh_get_custom_aabb(RID p_mesh) const { @@ -7463,7 +7466,7 @@ void RasterizerStorageGLES3::initialize() { { //transform feedback buffers - uint32_t xf_feedback_size = GLOBAL_DEF("rendering/limits/buffers/blend_shape_max_buffer_size_kb", 4096); + uint32_t xf_feedback_size = GLOBAL_DEF_RST("rendering/limits/buffers/blend_shape_max_buffer_size_kb", 4096); for (int i = 0; i < 2; i++) { glGenBuffers(1, &resources.transform_feedback_buffers[i]); diff --git a/drivers/gles3/rasterizer_storage_gles3.h b/drivers/gles3/rasterizer_storage_gles3.h index 80df21941b..1db577f23c 100644 --- a/drivers/gles3/rasterizer_storage_gles3.h +++ b/drivers/gles3/rasterizer_storage_gles3.h @@ -693,7 +693,6 @@ public: AABB custom_aabb; mutable uint64_t last_pass; SelfList<MultiMesh>::List multimeshes; - _FORCE_INLINE_ void update_multimeshes() { SelfList<MultiMesh> *mm = multimeshes.first(); diff --git a/drivers/gles3/shader_compiler_gles3.cpp b/drivers/gles3/shader_compiler_gles3.cpp index 3f6fe3ec61..f3ba7aa408 100644 --- a/drivers/gles3/shader_compiler_gles3.cpp +++ b/drivers/gles3/shader_compiler_gles3.cpp @@ -780,8 +780,6 @@ ShaderCompilerGLES3::ShaderCompilerGLES3() { actions[VS::SHADER_CANVAS_ITEM].renames["NORMAL"] = "normal"; actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP"] = "normal_map"; actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP_DEPTH"] = "normal_depth"; - actions[VS::SHADER_CANVAS_ITEM].renames["UV"] = "uv_interp"; - actions[VS::SHADER_CANVAS_ITEM].renames["COLOR"] = "color"; actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE"] = "color_texture"; actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE_PIXEL_SIZE"] = "color_texpixel_size"; actions[VS::SHADER_CANVAS_ITEM].renames["NORMAL_TEXTURE"] = "normal_texture"; @@ -824,7 +822,7 @@ ShaderCompilerGLES3::ShaderCompilerGLES3() { actions[VS::SHADER_SPATIAL].renames["UV2"] = "uv2_interp"; actions[VS::SHADER_SPATIAL].renames["COLOR"] = "color_interp"; actions[VS::SHADER_SPATIAL].renames["POINT_SIZE"] = "gl_PointSize"; - //actions[VS::SHADER_SPATIAL].renames["INSTANCE_ID"]=ShaderLanguage::TYPE_INT; + actions[VS::SHADER_SPATIAL].renames["INSTANCE_ID"] = "gl_InstanceID"; //builtins @@ -846,13 +844,11 @@ ShaderCompilerGLES3::ShaderCompilerGLES3() { actions[VS::SHADER_SPATIAL].renames["CLEARCOAT_GLOSS"] = "clearcoat_gloss"; actions[VS::SHADER_SPATIAL].renames["ANISOTROPY"] = "anisotropy"; actions[VS::SHADER_SPATIAL].renames["ANISOTROPY_FLOW"] = "anisotropy_flow"; - //actions[VS::SHADER_SPATIAL].renames["SSS_SPREAD"] = "sss_spread"; actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"] = "sss_strength"; actions[VS::SHADER_SPATIAL].renames["TRANSMISSION"] = "transmission"; actions[VS::SHADER_SPATIAL].renames["AO"] = "ao"; actions[VS::SHADER_SPATIAL].renames["AO_LIGHT_AFFECT"] = "ao_light_affect"; actions[VS::SHADER_SPATIAL].renames["EMISSION"] = "emission"; - //actions[VS::SHADER_SPATIAL].renames["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2; actions[VS::SHADER_SPATIAL].renames["POINT_COORD"] = "gl_PointCoord"; actions[VS::SHADER_SPATIAL].renames["INSTANCE_CUSTOM"] = "instance_custom"; actions[VS::SHADER_SPATIAL].renames["SCREEN_UV"] = "screen_uv"; @@ -894,8 +890,6 @@ ShaderCompilerGLES3::ShaderCompilerGLES3() { actions[VS::SHADER_SPATIAL].usage_defines["DIFFUSE_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n"; actions[VS::SHADER_SPATIAL].usage_defines["SPECULAR_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n"; - actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"] = "sss_strength"; - actions[VS::SHADER_SPATIAL].render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n"; actions[VS::SHADER_SPATIAL].render_mode_defines["world_vertex_coords"] = "#define VERTEX_WORLD_COORDS_USED\n"; actions[VS::SHADER_SPATIAL].render_mode_defines["ensure_correct_normals"] = "#define ENSURE_CORRECT_NORMALS\n"; diff --git a/drivers/gles3/shaders/scene.glsl b/drivers/gles3/shaders/scene.glsl index abb236138f..6fd85cc1dd 100644 --- a/drivers/gles3/shaders/scene.glsl +++ b/drivers/gles3/shaders/scene.glsl @@ -91,6 +91,7 @@ layout(std140) uniform SceneData { //ubo:0 mediump float subsurface_scatter_width; mediump float ambient_occlusion_affect_light; mediump float ambient_occlusion_affect_ao_channel; + mediump float opaque_prepass_threshold; bool fog_depth_enabled; highp float fog_depth_begin; @@ -679,6 +680,7 @@ layout(std140) uniform SceneData { mediump float subsurface_scatter_width; mediump float ambient_occlusion_affect_light; mediump float ambient_occlusion_affect_ao_channel; + mediump float opaque_prepass_threshold; bool fog_depth_enabled; highp float fog_depth_begin; @@ -1026,12 +1028,11 @@ LIGHT_SHADER_CODE diffuse_brdf_NL = cNdotL * (1.0 / M_PI); #endif -#if defined(TRANSMISSION_USED) - diffuse_light += light_color * diffuse_color * mix(vec3(diffuse_brdf_NL), vec3(M_PI), transmission) * attenuation; -#else diffuse_light += light_color * diffuse_color * diffuse_brdf_NL * attenuation; -#endif +#if defined(TRANSMISSION_USED) + diffuse_light += light_color * diffuse_color * (vec3(1.0 / M_PI) - diffuse_brdf_NL) * transmission * attenuation; +#endif #if defined(LIGHT_USE_RIM) @@ -1628,7 +1629,7 @@ void main() { float alpha = 1.0; #if defined(DO_SIDE_CHECK) - float side=float(gl_FrontFacing)*2.0-1.0; + float side=gl_FrontFacing ? 1.0 : -1.0; #else float side=1.0; #endif @@ -1690,9 +1691,10 @@ FRAGMENT_SHADER_CODE #ifdef USE_OPAQUE_PREPASS - if (alpha<0.99) { + if (alpha<opaque_prepass_threshold) { discard; } + #endif #if defined(ENABLE_NORMALMAP) @@ -2138,6 +2140,8 @@ FRAGMENT_SHADER_CODE #else + + //approximate ambient scale for SSAO, since we will lack full ambient float max_emission=max(emission.r,max(emission.g,emission.b)); float max_ambient=max(ambient_light.r,max(ambient_light.g,ambient_light.b)); @@ -2169,7 +2173,6 @@ FRAGMENT_SHADER_CODE frag_color=vec4(emission+ambient_light+diffuse_light+specular_light,alpha); #endif //SHADELESS - #endif //USE_MULTIPLE_RENDER_TARGETS diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.cpp b/drivers/pulseaudio/audio_driver_pulseaudio.cpp index ed6af04b9d..3622e48ecd 100644 --- a/drivers/pulseaudio/audio_driver_pulseaudio.cpp +++ b/drivers/pulseaudio/audio_driver_pulseaudio.cpp @@ -155,7 +155,7 @@ Error AudioDriverPulseAudio::init_device() { break; } - int latency = GLOBAL_DEF("audio/output_latency", DEFAULT_OUTPUT_LATENCY); + int latency = GLOBAL_DEF_RST("audio/output_latency", DEFAULT_OUTPUT_LATENCY); buffer_frames = closest_power_of_2(latency * mix_rate / 1000); pa_buffer_size = buffer_frames * pa_map.channels; @@ -204,7 +204,7 @@ Error AudioDriverPulseAudio::init() { thread_exited = false; exit_thread = false; - mix_rate = GLOBAL_DEF("audio/mix_rate", DEFAULT_MIX_RATE); + mix_rate = GLOBAL_DEF_RST("audio/mix_rate", DEFAULT_MIX_RATE); pa_ml = pa_mainloop_new(); ERR_FAIL_COND_V(pa_ml == NULL, ERR_CANT_OPEN); diff --git a/drivers/rtaudio/audio_driver_rtaudio.cpp b/drivers/rtaudio/audio_driver_rtaudio.cpp index 457486797f..365788e192 100644 --- a/drivers/rtaudio/audio_driver_rtaudio.cpp +++ b/drivers/rtaudio/audio_driver_rtaudio.cpp @@ -88,7 +88,7 @@ Error AudioDriverRtAudio::init() { // FIXME: Adapt to the OutputFormat -> SpeakerMode change /* - String channels = GLOBAL_DEF("audio/output","stereo"); + String channels = GLOBAL_DEF_RST("audio/output","stereo"); if (channels=="5.1") output_format=OUTPUT_5_1; @@ -108,7 +108,7 @@ Error AudioDriverRtAudio::init() { options.numberOfBuffers = 4; parameters.firstChannel = 0; - mix_rate = GLOBAL_DEF("audio/mix_rate", DEFAULT_MIX_RATE); + mix_rate = GLOBAL_DEF_RST("audio/mix_rate", DEFAULT_MIX_RATE); int latency = GLOBAL_DEF("audio/output_latency", DEFAULT_OUTPUT_LATENCY); unsigned int buffer_frames = closest_power_of_2(latency * mix_rate / 1000); diff --git a/drivers/wasapi/audio_driver_wasapi.cpp b/drivers/wasapi/audio_driver_wasapi.cpp index 3c54c429d9..1d96f9ee7d 100644 --- a/drivers/wasapi/audio_driver_wasapi.cpp +++ b/drivers/wasapi/audio_driver_wasapi.cpp @@ -318,7 +318,7 @@ Error AudioDriverWASAPI::finish_device() { Error AudioDriverWASAPI::init() { - mix_rate = GLOBAL_DEF("audio/mix_rate", DEFAULT_MIX_RATE); + mix_rate = GLOBAL_DEF_RST("audio/mix_rate", DEFAULT_MIX_RATE); Error err = init_device(); if (err != OK) { diff --git a/drivers/xaudio2/audio_driver_xaudio2.cpp b/drivers/xaudio2/audio_driver_xaudio2.cpp index 6675459313..db108f9c6b 100644 --- a/drivers/xaudio2/audio_driver_xaudio2.cpp +++ b/drivers/xaudio2/audio_driver_xaudio2.cpp @@ -50,7 +50,7 @@ Error AudioDriverXAudio2::init() { speaker_mode = SPEAKER_MODE_STEREO; channels = 2; - int latency = GLOBAL_DEF("audio/output_latency", 25); + int latency = GLOBAL_DEF_RST("audio/output_latency", 25); buffer_size = closest_power_of_2(latency * mix_rate / 1000); samples_in = memnew_arr(int32_t, buffer_size * channels); diff --git a/editor/connections_dialog.cpp b/editor/connections_dialog.cpp index 8933fd7fe8..c4f4e28fec 100644 --- a/editor/connections_dialog.cpp +++ b/editor/connections_dialog.cpp @@ -820,7 +820,9 @@ void ConnectionsDock::update_tree() { if (i > 0) signaldesc += ", "; String tname = "var"; - if (pi.type != Variant::NIL) { + if (pi.type == Variant::OBJECT && pi.class_name != StringName()) { + tname = pi.class_name.operator String(); + } else if (pi.type != Variant::NIL) { tname = Variant::get_type_name(pi.type); } signaldesc += tname + " " + (pi.name == "" ? String("arg " + itos(i)) : pi.name); diff --git a/editor/editor_help.cpp b/editor/editor_help.cpp index 65e50560bc..727383b960 100644 --- a/editor/editor_help.cpp +++ b/editor/editor_help.cpp @@ -1900,6 +1900,7 @@ void EditorHelpBit::_meta_clicked(String p_select) { void EditorHelpBit::_bind_methods() { ClassDB::bind_method("_meta_clicked", &EditorHelpBit::_meta_clicked); + ClassDB::bind_method(D_METHOD("set_text", "text"), &EditorHelpBit::set_text); ADD_SIGNAL(MethodInfo("request_hide")); } @@ -1925,7 +1926,7 @@ EditorHelpBit::EditorHelpBit() { rich_text = memnew(RichTextLabel); add_child(rich_text); - rich_text->set_anchors_and_margins_preset(Control::PRESET_WIDE); + //rich_text->set_anchors_and_margins_preset(Control::PRESET_WIDE); rich_text->connect("meta_clicked", this, "_meta_clicked"); rich_text->add_color_override("selection_color", get_color("text_editor/theme/selection_color", "Editor")); rich_text->set_override_selected_font_color(false); diff --git a/editor/editor_help.h b/editor/editor_help.h index 514169dc19..dbea97e98b 100644 --- a/editor/editor_help.h +++ b/editor/editor_help.h @@ -272,9 +272,9 @@ public: ~EditorHelp(); }; -class EditorHelpBit : public Panel { +class EditorHelpBit : public PanelContainer { - GDCLASS(EditorHelpBit, Panel); + GDCLASS(EditorHelpBit, PanelContainer); RichTextLabel *rich_text; void _go_to_help(String p_what); @@ -285,6 +285,7 @@ protected: void _notification(int p_what); public: + RichTextLabel *get_rich_text() { return rich_text; } void set_text(const String &p_text); EditorHelpBit(); }; diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp index c4789f3b63..488980db07 100644 --- a/editor/editor_inspector.cpp +++ b/editor/editor_inspector.cpp @@ -91,6 +91,9 @@ void EditorProperty::_notification(int p_what) { Rect2 rect; Rect2 bottom_rect; + right_child_rect = Rect2(); + bottom_child_rect = Rect2(); + { int child_room = size.width * (1.0 - split_ratio); Ref<Font> font = get_font("font", "Tree"); @@ -118,7 +121,8 @@ void EditorProperty::_notification(int p_what) { if (bottom_editor) { - int m = get_constant("item_margin", "Tree"); + int m = 0; //get_constant("item_margin", "Tree"); + bottom_rect = Rect2(m, rect.size.height + get_constant("vseparation", "Tree"), size.width - m, bottom_editor->get_combined_minimum_size().height); } } @@ -147,10 +151,12 @@ void EditorProperty::_notification(int p_what) { continue; fit_child_in_rect(c, rect); + right_child_rect = rect; } if (bottom_editor) { fit_child_in_rect(bottom_editor, bottom_rect); + bottom_child_rect = bottom_rect; } update(); //need to redraw text @@ -158,6 +164,7 @@ void EditorProperty::_notification(int p_what) { if (p_what == NOTIFICATION_DRAW) { Ref<Font> font = get_font("font", "Tree"); + Color dark_color = get_color("dark_color_2", "Editor"); Size2 size = get_size(); if (bottom_editor) { @@ -171,6 +178,13 @@ void EditorProperty::_notification(int p_what) { draw_style_box(sb, Rect2(Vector2(), size)); } + if (right_child_rect != Rect2()) { + draw_rect(right_child_rect, dark_color); + } + if (bottom_child_rect != Rect2()) { + draw_rect(bottom_child_rect, dark_color); + } + Color color; if (draw_red) { color = get_color("error_color", "Editor"); @@ -251,7 +265,7 @@ void EditorProperty::_notification(int p_what) { //int vs = get_constant("vseparation", "Tree"); Color guide_color = get_color("guide_color", "Tree"); int vs_height = get_size().height; // vs / 2; - draw_line(Point2(0, vs_height), Point2(get_size().width, vs_height), guide_color); + // draw_line(Point2(0, vs_height), Point2(get_size().width, vs_height), guide_color); } } @@ -705,6 +719,24 @@ void EditorProperty::set_object_and_property(Object *p_object, const StringName property = p_property; } +Control *EditorProperty::make_custom_tooltip(const String &p_text) const { + + tooltip_text = p_text; + EditorHelpBit *help_bit = memnew(EditorHelpBit); + help_bit->add_style_override("panel", get_stylebox("panel", "TooltipPanel")); + help_bit->get_rich_text()->set_fixed_size_to_width(300); + + String text = TTR("Property: ") + "[u][b]" + p_text.get_slice("::", 0) + "[/b][/u]\n"; + text += p_text.get_slice("::", 1).strip_edges(); + help_bit->set_text(text); + help_bit->call_deferred("set_text", text); //hack so it uses proper theme once inside scene + return help_bit; +} + +String EditorProperty::get_tooltip_text() const { + return tooltip_text; +} + void EditorProperty::_bind_methods() { ClassDB::bind_method(D_METHOD("set_label", "text"), &EditorProperty::set_label); @@ -731,6 +763,8 @@ void EditorProperty::_bind_methods() { ClassDB::bind_method(D_METHOD("_gui_input"), &EditorProperty::_gui_input); ClassDB::bind_method(D_METHOD("_focusable_focused"), &EditorProperty::_focusable_focused); + ClassDB::bind_method(D_METHOD("get_tooltip_text"), &EditorProperty::get_tooltip_text); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "label"), "set_label", "get_label"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "read_only"), "set_read_only", "is_read_only"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "checkable"), "set_checkable", "is_checkable"); @@ -905,6 +939,20 @@ void EditorInspectorCategory::_notification(int p_what) { } } +Control *EditorInspectorCategory::make_custom_tooltip(const String &p_text) const { + + tooltip_text = p_text; + EditorHelpBit *help_bit = memnew(EditorHelpBit); + help_bit->add_style_override("panel", get_stylebox("panel", "TooltipPanel")); + help_bit->get_rich_text()->set_fixed_size_to_width(300); + + String text = "[u][b]" + p_text.get_slice("::", 0) + "[/b][/u]\n"; + text += p_text.get_slice("::", 1).strip_edges(); + help_bit->set_text(text); + help_bit->call_deferred("set_text", text); //hack so it uses proper theme once inside scene + return help_bit; +} + Size2 EditorInspectorCategory::get_minimum_size() const { Ref<Font> font = get_font("font", "Tree"); @@ -920,12 +968,29 @@ Size2 EditorInspectorCategory::get_minimum_size() const { return ms; } +void EditorInspectorCategory::_bind_methods() { + ClassDB::bind_method(D_METHOD("get_tooltip_text"), &EditorInspectorCategory::get_tooltip_text); +} + +String EditorInspectorCategory::get_tooltip_text() const { + + return tooltip_text; +} + EditorInspectorCategory::EditorInspectorCategory() { } //////////////////////////////////////////////// //////////////////////////////////////////////// +void EditorInspectorSection::_test_unfold() { + + if (!vbox_added) { + add_child(vbox); + vbox_added = true; + } +} + void EditorInspectorSection::_notification(int p_what) { if (p_what == NOTIFICATION_SORT_CHILDREN) { @@ -936,9 +1001,9 @@ void EditorInspectorSection::_notification(int p_what) { #ifdef TOOLS_ENABLED if (foldable) { if (object->editor_is_section_unfolded(section)) { - arrow = get_icon("arrow", "Tree"); + arrow = get_icon("arrow_up", "Tree"); } else { - arrow = get_icon("arrow_collapsed", "Tree"); + arrow = get_icon("arrow", "Tree"); } } #endif @@ -951,7 +1016,7 @@ void EditorInspectorSection::_notification(int p_what) { } offset.y += get_constant("vseparation", "Tree"); - offset.x += get_constant("item_margin", "Tree"); + offset.x += get_constant("inspector_margin", "Editor"); Rect2 rect(offset, size - offset); @@ -979,9 +1044,9 @@ void EditorInspectorSection::_notification(int p_what) { #ifdef TOOLS_ENABLED if (foldable) { if (object->editor_is_section_unfolded(section)) { - arrow = get_icon("arrow", "Tree"); + arrow = get_icon("arrow_up", "Tree"); } else { - arrow = get_icon("arrow_collapsed", "Tree"); + arrow = get_icon("arrow", "Tree"); } } #endif @@ -998,14 +1063,14 @@ void EditorInspectorSection::_notification(int p_what) { int hs = get_constant("hseparation", "Tree"); + Color color = get_color("font_color", "Tree"); + draw_string(font, Point2(hs, font->get_ascent() + (h - font->get_height()) / 2).floor(), label, color, get_size().width); + int ofs = 0; if (arrow.is_valid()) { - draw_texture(arrow, Point2(ofs, (h - arrow->get_height()) / 2).floor()); + draw_texture(arrow, Point2(get_size().width - arrow->get_width(), (h - arrow->get_height()) / 2).floor()); ofs += hs + arrow->get_width(); } - - Color color = get_color("font_color", "Tree"); - draw_string(font, Point2(ofs, font->get_ascent() + (h - font->get_height()) / 2).floor(), label, color, get_size().width); } } @@ -1027,8 +1092,8 @@ Size2 EditorInspectorSection::get_minimum_size() const { } Ref<Font> font = get_font("font", "Tree"); - ms.height += font->get_ascent() + get_constant("vseparation", "Tree"); - ms.width += get_constant("item_margin", "Tree"); + ms.height += font->get_height() + get_constant("vseparation", "Tree"); + ms.width += get_constant("inspector_margin", "Editor"); return ms; } @@ -1041,8 +1106,14 @@ void EditorInspectorSection::setup(const String &p_section, const String &p_labe bg_color = p_bg_color; foldable = p_foldable; + if (!foldable && !vbox_added) { + add_child(vbox); + vbox_added = true; + } + #ifdef TOOLS_ENABLED if (foldable) { + _test_unfold(); if (object->editor_is_section_unfolded(section)) { vbox->show(); } else { @@ -1061,6 +1132,9 @@ void EditorInspectorSection::_gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { + + _test_unfold(); + bool unfold = !object->editor_is_section_unfolded(section); object->editor_set_section_unfold(section, unfold); if (unfold) { @@ -1080,6 +1154,9 @@ void EditorInspectorSection::unfold() { if (!foldable) return; + + _test_unfold(); + #ifdef TOOLS_ENABLED object->editor_set_section_unfold(section, true); @@ -1092,6 +1169,8 @@ void EditorInspectorSection::fold() { if (!foldable) return; + if (!vbox_added) + return; //kinda pointless #ifdef TOOLS_ENABLED object->editor_set_section_unfold(section, false); @@ -1113,7 +1192,14 @@ EditorInspectorSection::EditorInspectorSection() { object = NULL; foldable = false; vbox = memnew(VBoxContainer); - add_child(vbox); + vbox_added = false; + //add_child(vbox); +} + +EditorInspectorSection::~EditorInspectorSection() { + if (!vbox_added) { + memdelete(vbox); + } } //////////////////////////////////////////////// @@ -1274,8 +1360,10 @@ void EditorInspector::update_tree() { String filter = search_box ? search_box->get_text() : ""; String group; String group_base; + VBoxContainer *category_vbox = NULL; - List<PropertyInfo> plist; + List<PropertyInfo> + plist; object->get_property_list(&plist, true); HashMap<String, VBoxContainer *> item_path; @@ -1327,6 +1415,7 @@ void EditorInspector::update_tree() { EditorInspectorCategory *category = memnew(EditorInspectorCategory); main_vbox->add_child(category); + category_vbox = NULL; //reset String type = p.name; if (has_icon(type, "EditorIcons")) @@ -1349,7 +1438,7 @@ void EditorInspector::update_tree() { class_descr_cache[type] = descr.word_wrap(80); } - category->set_tooltip(TTR("Class:") + " " + p.name + (class_descr_cache[type] == "" ? "" : "\n\n" + class_descr_cache[type])); + category->set_tooltip(p.name + "::" + (class_descr_cache[type] == "" ? "" : class_descr_cache[type])); } for (List<Ref<EditorInspectorPlugin> >::Element *E = valid_plugins.front(); E; E = E->next()) { @@ -1412,6 +1501,11 @@ void EditorInspector::update_tree() { continue; } + if (category_vbox == NULL) { + category_vbox = memnew(VBoxContainer); + main_vbox->add_child(category_vbox); + } + VBoxContainer *current_vbox = main_vbox; { @@ -1439,6 +1533,14 @@ void EditorInspector::update_tree() { current_vbox = item_path[acc_path]; level = (MIN(level + 1, 4)); } + + if (current_vbox == main_vbox) { + //do not add directly to the main vbox, given it has no spacing + if (category_vbox == NULL) { + category_vbox = memnew(VBoxContainer); + } + current_vbox = category_vbox; + } } bool checkable = false; @@ -1448,12 +1550,19 @@ void EditorInspector::update_tree() { checked = p.usage & PROPERTY_USAGE_CHECKED; } + if (p.usage & PROPERTY_USAGE_RESTART_IF_CHANGED) { + restart_request_props.insert(p.name); + } + String doc_hint; if (use_doc_hints) { StringName classname = object->get_class_name(); - StringName propname = p.name; + if (object_class != String()) { + classname = object_class; + } + StringName propname = property_prefix + p.name; String descr; bool found = false; @@ -1521,9 +1630,9 @@ void EditorInspector::update_tree() { ep->connect("resource_selected", this, "_resource_selected", varray(), CONNECT_DEFERRED); ep->connect("object_id_selected", this, "_object_id_selected", varray(), CONNECT_DEFERRED); if (doc_hint != String()) { - ep->set_tooltip(TTR("Property: ") + p.name + "\n\n" + doc_hint); + ep->set_tooltip(property_prefix + p.name + "::" + doc_hint); } else { - ep->set_tooltip(TTR("Property: ") + p.name); + ep->set_tooltip(property_prefix + p.name); } ep->set_draw_red(draw_red); ep->set_use_folding(use_folding); @@ -1600,6 +1709,7 @@ void EditorInspector::_clear() { editor_property_map.clear(); sections.clear(); pending.clear(); + restart_request_props.clear(); } void EditorInspector::refresh() { @@ -1625,6 +1735,10 @@ void EditorInspector::edit(Object *p_object) { object = p_object; if (object) { + update_scroll_request = 0; //reset + if (scroll_cache.has(object->get_instance_id())) { //if exists, set something else + update_scroll_request = scroll_cache[object->get_instance_id()]; //done this way because wait until full size is accomodated + } object->add_change_receptor(this); update_tree(); } @@ -1730,6 +1844,19 @@ int EditorInspector::get_scroll_offset() const { return get_v_scroll(); } +void EditorInspector::set_use_sub_inspector_bg(bool p_enable) { + + use_sub_inspector_bg = p_enable; + if (!is_inside_tree()) + return; + + if (use_sub_inspector_bg) { + add_style_override("bg", get_stylebox("sub_inspector_bg", "Editor")); + } else { + add_style_override("bg", get_stylebox("bg", "Tree")); + } +} + void EditorInspector::_edit_request_change(Object *p_object, const String &p_property) { if (object != p_object) //may be undoing/redoing for a non edited object, so ignore @@ -1826,6 +1953,10 @@ void EditorInspector::_property_changed(const String &p_path, const Variant &p_v if (changing) this->changing--; + + if (restart_request_props.has(p_path)) { + emit_signal("restart_requested"); + } } void EditorInspector::_property_changed_update_all(const String &p_path, const Variant &p_value) { @@ -1845,6 +1976,9 @@ void EditorInspector::_multiple_properties_changed(Vector<String> p_paths, Array undo_redo->create_action(TTR("Set Multiple:") + " " + names, UndoRedo::MERGE_ENDS); for (int i = 0; i < p_paths.size(); i++) { _edit_set(p_paths[i], p_values[i], false, ""); + if (restart_request_props.has(p_paths[i])) { + emit_signal("restart_requested"); + } } changing++; undo_redo->commit_action(); @@ -1917,6 +2051,8 @@ void EditorInspector::_property_selected(const String &p_path, int p_focusable) E->get()->deselect(); } } + + emit_signal("property_selected", p_path); } void EditorInspector::_object_id_selected(const String &p_path, ObjectID p_id) { @@ -1940,7 +2076,11 @@ void EditorInspector::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE) { get_tree()->connect("node_removed", this, "_node_removed"); - add_style_override("bg", get_stylebox("bg", "Tree")); + if (use_sub_inspector_bg) { + add_style_override("bg", get_stylebox("sub_inspector_bg", "Editor")); + } else if (is_inside_tree()) { + add_style_override("bg", get_stylebox("bg", "Tree")); + } } if (p_what == NOTIFICATION_EXIT_TREE) { @@ -1950,6 +2090,10 @@ void EditorInspector::_notification(int p_what) { if (p_what == NOTIFICATION_PROCESS) { + if (update_scroll_request >= 0) { + get_v_scrollbar()->call_deferred("set_value", update_scroll_request); + update_scroll_request = -1; + } if (refresh_countdown > 0) { refresh_countdown -= get_process_delta_time(); if (refresh_countdown <= 0) { @@ -1997,6 +2141,32 @@ void EditorInspector::_changed_callback(Object *p_changed, const char *p_prop) { _edit_request_change(p_changed, p_prop); } +void EditorInspector::_vscroll_changed(double p_offset) { + + if (update_scroll_request >= 0) //waiting, do nothing + return; + + if (object) { + scroll_cache[object->get_instance_id()] = p_offset; + } +} + +void EditorInspector::set_property_prefix(const String &p_prefix) { + property_prefix = p_prefix; +} + +String EditorInspector::get_property_prefix() const { + return property_prefix; +} + +void EditorInspector::set_object_class(const String &p_class) { + object_class = p_class; +} + +String EditorInspector::get_object_class() const { + return object_class; +} + void EditorInspector::_bind_methods() { ClassDB::bind_method("_property_changed", &EditorInspector::_property_changed, DEFVAL(false)); @@ -2012,11 +2182,16 @@ void EditorInspector::_bind_methods() { ClassDB::bind_method("_property_selected", &EditorInspector::_property_selected); ClassDB::bind_method("_resource_selected", &EditorInspector::_resource_selected); ClassDB::bind_method("_object_id_selected", &EditorInspector::_object_id_selected); + ClassDB::bind_method("_vscroll_changed", &EditorInspector::_vscroll_changed); + ClassDB::bind_method("refresh", &EditorInspector::refresh); + ADD_SIGNAL(MethodInfo("property_selected", PropertyInfo(Variant::STRING, "property"))); ADD_SIGNAL(MethodInfo("property_keyed", PropertyInfo(Variant::STRING, "property"))); ADD_SIGNAL(MethodInfo("resource_selected", PropertyInfo(Variant::OBJECT, "res"), PropertyInfo(Variant::STRING, "prop"))); ADD_SIGNAL(MethodInfo("object_id_selected", PropertyInfo(Variant::INT, "id"))); + ADD_SIGNAL(MethodInfo("property_edited", PropertyInfo(Variant::STRING, "property"))); + ADD_SIGNAL(MethodInfo("restart_requested")); } EditorInspector::EditorInspector() { @@ -2024,6 +2199,7 @@ EditorInspector::EditorInspector() { undo_redo = NULL; main_vbox = memnew(VBoxContainer); main_vbox->set_h_size_flags(SIZE_EXPAND_FILL); + main_vbox->add_constant_override("separation", 0); add_child(main_vbox); set_enable_h_scroll(false); set_enable_v_scroll(true); @@ -2045,4 +2221,8 @@ EditorInspector::EditorInspector() { _prop_edited = "property_edited"; set_process(true); property_focusable = -1; + use_sub_inspector_bg = false; + + get_v_scrollbar()->connect("value_changed", this, "_vscroll_changed"); + update_scroll_request = -1; } diff --git a/editor/editor_inspector.h b/editor/editor_inspector.h index b7a492f114..454622d662 100644 --- a/editor/editor_inspector.h +++ b/editor/editor_inspector.h @@ -55,6 +55,9 @@ private: bool draw_red; bool keying; + Rect2 right_child_rect; + Rect2 bottom_child_rect; + Rect2 keying_rect; bool keying_hover; Rect2 revert_rect; @@ -82,6 +85,8 @@ private: Control *label_reference; Control *bottom_editor; + mutable String tooltip_text; + protected: void _notification(int p_what); static void _bind_methods(); @@ -140,6 +145,10 @@ public: float get_name_split_ratio() const; void set_object_and_property(Object *p_object, const StringName &p_property); + virtual Control *make_custom_tooltip(const String &p_text) const; + + String get_tooltip_text() const; + EditorProperty(); }; @@ -177,12 +186,17 @@ class EditorInspectorCategory : public Control { Ref<Texture> icon; String label; Color bg_color; + mutable String tooltip_text; protected: void _notification(int p_what); + static void _bind_methods(); public: virtual Size2 get_minimum_size() const; + virtual Control *make_custom_tooltip(const String &p_text) const; + + String get_tooltip_text() const; EditorInspectorCategory(); }; @@ -194,9 +208,12 @@ class EditorInspectorSection : public Container { String section; Object *object; VBoxContainer *vbox; + bool vbox_added; //optimization Color bg_color; bool foldable; + void _test_unfold(); + protected: void _notification(int p_what); static void _bind_methods(); @@ -213,6 +230,7 @@ public: Object *get_edited_object(); EditorInspectorSection(); + ~EditorInspectorSection(); }; class EditorInspector : public ScrollContainer { @@ -249,15 +267,23 @@ class EditorInspector : public ScrollContainer { bool update_all_pending; bool read_only; bool keying; + bool use_sub_inspector_bg; float refresh_countdown; bool update_tree_pending; StringName _prop_edited; StringName property_selected; int property_focusable; + int update_scroll_request; Map<StringName, Map<StringName, String> > descr_cache; Map<StringName, String> class_descr_cache; + Set<StringName> restart_request_props; + + Map<ObjectID, int> scroll_cache; + + String property_prefix; //used for sectioned inspector + String object_class; void _edit_set(const String &p_name, const Variant &p_value, bool p_refresh_all, const String &p_changed_field); @@ -281,6 +307,8 @@ class EditorInspector : public ScrollContainer { void _filter_changed(const String &p_text); void _parse_added_editors(VBoxContainer *current_vbox, Ref<EditorInspectorPlugin> ped); + void _vscroll_changed(double); + protected: static void _bind_methods(); void _notification(int p_what); @@ -330,6 +358,14 @@ public: void set_scroll_offset(int p_offset); int get_scroll_offset() const; + void set_property_prefix(const String &p_prefix); + String get_property_prefix() const; + + void set_object_class(const String &p_class); + String get_object_class() const; + + void set_use_sub_inspector_bg(bool p_enable); + EditorInspector(); }; diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index 4696bdd5a9..ff97878e71 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -1068,6 +1068,32 @@ void EditorNode::_save_scene(String p_file, int idx) { } } +void EditorNode::save_all_scenes_and_restart() { + + _menu_option_confirm(RUN_STOP, true); + exiting = true; + + _save_all_scenes(); + + String to_reopen; + if (get_tree()->get_edited_scene_root()) { + to_reopen = get_tree()->get_edited_scene_root()->get_filename(); + } + + get_tree()->quit(); + String exec = OS::get_singleton()->get_executable_path(); + + List<String> args; + args.push_back("--path"); + args.push_back(ProjectSettings::get_singleton()->get_resource_path()); + args.push_back("-e"); + if (to_reopen != String()) { + args.push_back(to_reopen); + } + + OS::get_singleton()->set_restart_on_exit(true, args); +} + void EditorNode::_save_all_scenes() { for (int i = 0; i < editor_data.get_edited_scene_count(); i++) { @@ -2204,6 +2230,13 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) { about->popup_centered_minsize(Size2(780, 500) * EDSCALE); } break; + case SET_VIDEO_DRIVER_SAVE_AND_RESTART: { + + ProjectSettings::get_singleton()->set("rendering/quality/driver/driver_name", video_driver_request); + ProjectSettings::get_singleton()->save(); + + save_all_scenes_and_restart(); + } break; default: { if (p_option >= IMPORT_PLUGIN_BASE) { } @@ -4390,6 +4423,21 @@ void EditorNode::_bottom_panel_raise_toggled(bool p_pressed) { } } +void EditorNode::_video_driver_selected(int p_which) { + + String driver = video_driver->get_item_metadata(p_which); + + String current = OS::get_singleton()->get_video_driver_name(OS::get_singleton()->get_current_video_driver()); + + if (driver == current) { + return; + } + + video_driver_request = driver; + video_restart_dialog->popup_centered_minsize(); + video_driver->select(video_driver_current); +} + void EditorNode::_bind_methods() { ClassDB::bind_method("_menu_option", &EditorNode::_menu_option); @@ -4460,6 +4508,8 @@ void EditorNode::_bind_methods() { ClassDB::bind_method(D_METHOD("_resources_reimported"), &EditorNode::_resources_reimported); ClassDB::bind_method(D_METHOD("_bottom_panel_raise_toggled"), &EditorNode::_bottom_panel_raise_toggled); + ClassDB::bind_method(D_METHOD("_video_driver_selected"), &EditorNode::_video_driver_selected); + ADD_SIGNAL(MethodInfo("play_pressed")); ADD_SIGNAL(MethodInfo("pause_pressed")); ADD_SIGNAL(MethodInfo("stop_pressed")); @@ -4656,21 +4706,21 @@ EditorNode::EditorNode() { ClassDB::set_class_enabled("RootMotionView", true); //defs here, use EDITOR_GET in logic - EDITOR_DEF("interface/scene_tabs/always_show_close_button", false); - EDITOR_DEF("interface/scene_tabs/resize_if_many_tabs", true); - EDITOR_DEF("interface/scene_tabs/minimum_width", 50); + EDITOR_DEF_RST("interface/scene_tabs/always_show_close_button", false); + EDITOR_DEF_RST("interface/scene_tabs/resize_if_many_tabs", true); + EDITOR_DEF_RST("interface/scene_tabs/minimum_width", 50); EDITOR_DEF("run/output/always_clear_output_on_play", true); EDITOR_DEF("run/output/always_open_output_on_play", true); EDITOR_DEF("run/output/always_close_output_on_stop", true); EDITOR_DEF("run/auto_save/save_before_running", true); - EDITOR_DEF("interface/editor/save_each_scene_on_quit", true); + EDITOR_DEF_RST("interface/editor/save_each_scene_on_quit", true); EDITOR_DEF("interface/editor/quit_confirmation", true); - EDITOR_DEF("interface/scene_tabs/restore_scenes_on_load", false); - EDITOR_DEF("interface/scene_tabs/show_thumbnail_on_hover", true); - EDITOR_DEF("interface/inspector/capitalize_properties", true); - EDITOR_DEF("interface/inspector/disable_folding", false); + EDITOR_DEF_RST("interface/scene_tabs/restore_scenes_on_load", false); + EDITOR_DEF_RST("interface/scene_tabs/show_thumbnail_on_hover", true); + EDITOR_DEF_RST("interface/inspector/capitalize_properties", true); + EDITOR_DEF_RST("interface/inspector/disable_folding", false); EDITOR_DEF("interface/inspector/open_resources_in_current_inspector", true); - EDITOR_DEF("interface/inspector/resources_types_to_open_in_new_inspector", "Material,Mesh"); + EDITOR_DEF("interface/inspector/resources_types_to_open_in_new_inspector", "SpatialMaterial"); EDITOR_DEF("run/auto_save/save_before_running", true); theme_base = memnew(Control); @@ -5191,6 +5241,37 @@ EditorNode::EditorNode() { play_custom_scene_button->set_shortcut(ED_SHORTCUT("editor/play_custom_scene", TTR("Play Custom Scene"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_F5)); #endif + video_driver = memnew(OptionButton); + video_driver->set_flat(true); + video_driver->set_focus_mode(Control::FOCUS_NONE); + video_driver->set_v_size_flags(Control::SIZE_SHRINK_CENTER); + String video_drivers = ProjectSettings::get_singleton()->get_custom_property_info()["rendering/quality/driver/driver_name"].hint_string; + String current_video_driver = OS::get_singleton()->get_video_driver_name(OS::get_singleton()->get_current_video_driver()); + menu_hb->add_child(video_driver); + video_driver_current = 0; + for (int i = 0; i < video_drivers.get_slice_count(","); i++) { + String driver = video_drivers.get_slice(",", i); + if (gui_base->has_icon(driver, "EditorIcons")) { + video_driver->add_icon_item(gui_base->get_icon(driver, "EditorIcons"), ""); + } else { + video_driver->add_item(driver); + } + + video_driver->set_item_metadata(i, driver); + + if (current_video_driver == driver) { + video_driver->select(i); + video_driver_current = i; + } + } + + video_driver->connect("item_selected", this, "_video_driver_selected"); + video_restart_dialog = memnew(ConfirmationDialog); + video_restart_dialog->set_text(TTR("Changing the video driver requires restarting the editor.")); + video_restart_dialog->get_ok()->set_text(TTR("Save & Restart")); + video_restart_dialog->connect("confirmed", this, "_menu_option", varray(SET_VIDEO_DRIVER_SAVE_AND_RESTART)); + gui_base->add_child(video_restart_dialog); + progress_hb = memnew(BackgroundProgress); HBoxContainer *right_menu_hb = memnew(HBoxContainer); @@ -5208,8 +5289,8 @@ EditorNode::EditorNode() { update_menu->set_icon(gui_base->get_icon("Progress1", "EditorIcons")); update_menu->get_popup()->connect("id_pressed", this, "_menu_option"); p = update_menu->get_popup(); - p->add_check_item(TTR("Update Always"), SETTINGS_UPDATE_ALWAYS); - p->add_check_item(TTR("Update Changes"), SETTINGS_UPDATE_CHANGES); + p->add_radio_check_item(TTR("Update Always"), SETTINGS_UPDATE_ALWAYS); + p->add_radio_check_item(TTR("Update Changes"), SETTINGS_UPDATE_CHANGES); p->add_separator(); p->add_check_item(TTR("Disable Update Spinner"), SETTINGS_UPDATE_SPINNER_HIDE); int update_always = EditorSettings::get_singleton()->get_project_metadata("editor_options", "update_always", false); diff --git a/editor/editor_node.h b/editor/editor_node.h index 88fe008b34..38e68b2e09 100644 --- a/editor/editor_node.h +++ b/editor/editor_node.h @@ -182,6 +182,8 @@ private: HELP_COMMUNITY, HELP_ABOUT, + SET_VIDEO_DRIVER_SAVE_AND_RESTART, + IMPORT_PLUGIN_BASE = 100, TOOL_MENU_BASE = 1000 @@ -194,6 +196,13 @@ private: Control *gui_base; VBoxContainer *main_vbox; PanelContainer *play_button_panel; + OptionButton *video_driver; + + ConfirmationDialog *video_restart_dialog; + + int video_driver_current; + String video_driver_request; + void _video_driver_selected(int); //split @@ -745,6 +754,8 @@ public: void add_tool_submenu_item(const String &p_name, PopupMenu *p_submenu); void remove_tool_menu_item(const String &p_name); + void save_all_scenes_and_restart(); + void dim_editor(bool p_dimming); void edit_current() { _edit_current(); }; diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp index ca51f6e635..0b49b5a801 100644 --- a/editor/editor_properties.cpp +++ b/editor/editor_properties.cpp @@ -178,6 +178,8 @@ void EditorPropertyTextEnum::_bind_methods() { EditorPropertyTextEnum::EditorPropertyTextEnum() { options = memnew(OptionButton); options->set_clip_text(true); + options->set_flat(true); + add_child(options); add_focusable(options); options->connect("item_selected", this, "_option_selected"); @@ -390,13 +392,37 @@ EditorPropertyCheck::EditorPropertyCheck() { void EditorPropertyEnum::_option_selected(int p_which) { - emit_signal("property_changed", get_edited_property(), p_which); + String text = options->get_item_text(p_which); + Vector<String> text_split = text.split(":"); + if (text_split.size() == 1) { + emit_signal("property_changed", get_edited_property(), p_which); + return; + } + String name = text_split[1]; + emit_signal("property_changed", get_edited_property(), name.to_int()); } void EditorPropertyEnum::update_property() { int which = get_edited_object()->get(get_edited_property()); - options->select(which); + if (which == 0) { + options->select(which); + return; + } + + for (int i = 0; i < options->get_item_count(); i++) { + String text = options->get_item_text(i); + Vector<String> text_split = text.split(":"); + if (text_split.size() == 1) { + options->select(which); + return; + } + String name = text_split[1]; + if (itos(which) == name) { + options->select(i); + return; + } + } } void EditorPropertyEnum::setup(const Vector<String> &p_options) { @@ -417,6 +443,7 @@ void EditorPropertyEnum::_bind_methods() { EditorPropertyEnum::EditorPropertyEnum() { options = memnew(OptionButton); options->set_clip_text(true); + options->set_flat(true); add_child(options); add_focusable(options); options->connect("item_selected", this, "_option_selected"); @@ -711,6 +738,7 @@ void EditorPropertyInteger::setup(int p_min, int p_max, bool p_allow_greater, bo EditorPropertyInteger::EditorPropertyInteger() { spin = memnew(EditorSpinSlider); + spin->set_flat(true); add_child(spin); add_focusable(spin); spin->connect("value_changed", this, "_value_changed"); @@ -797,6 +825,7 @@ void EditorPropertyFloat::setup(double p_min, double p_max, double p_step, bool EditorPropertyFloat::EditorPropertyFloat() { spin = memnew(EditorSpinSlider); + spin->set_flat(true); add_child(spin); add_focusable(spin); spin->connect("value_changed", this, "_value_changed"); @@ -807,6 +836,12 @@ EditorPropertyFloat::EditorPropertyFloat() { void EditorPropertyEasing::_drag_easing(const Ref<InputEvent> &p_ev) { + Ref<InputEventMouseButton> mb = p_ev; + if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_RIGHT) { + preset->set_global_position(easing_draw->get_global_transform().xform(mb->get_position())); + preset->popup(); + } + Ref<InputEventMouseMotion> mm = p_ev; if (mm.is_valid() && mm->get_button_mask() & BUTTON_MASK_LEFT) { @@ -844,7 +879,7 @@ void EditorPropertyEasing::_draw_easing() { Size2 s = easing_draw->get_size(); Rect2 r(Point2(), s); r = r.grow(3); - get_stylebox("normal", "LineEdit")->draw(ci, r); + //get_stylebox("normal", "LineEdit")->draw(ci, r); int points = 48; @@ -854,6 +889,7 @@ void EditorPropertyEasing::_draw_easing() { Ref<Font> f = get_font("font", "Label"); Color color = get_color("font_color", "Label"); + Vector<Point2> lines; for (int i = 1; i <= points; i++) { float ifl = i / float(points); @@ -866,10 +902,12 @@ void EditorPropertyEasing::_draw_easing() { iflp = 1.0 - iflp; } - VisualServer::get_singleton()->canvas_item_add_line(ci, Point2(iflp * s.width, prev * s.height), Point2(ifl * s.width, h * s.height), color); + lines.push_back(Point2(ifl * s.width, h * s.height)); + lines.push_back(Point2(iflp * s.width, prev * s.height)); prev = h; } + easing_draw->draw_multiline(lines, color, 1.0, true); f->draw(ci, Point2(10, 10 + f->get_ascent()), String::num(exp, 2), color); } @@ -877,29 +915,17 @@ void EditorPropertyEasing::update_property() { easing_draw->update(); } -void EditorPropertyEasing::_set_preset(float p_val) { - emit_signal("property_changed", get_edited_property(), p_val); +void EditorPropertyEasing::_set_preset(int p_preset) { + static const float preset_value[EASING_MAX] = { 0.0, 1.0, 2.0, 0.5, -2.0, -0.5 }; + + emit_signal("property_changed", get_edited_property(), preset_value[p_preset]); easing_draw->update(); } void EditorPropertyEasing::setup(bool p_full, bool p_flip) { flip = p_flip; - if (p_full) { - HBoxContainer *hb2 = memnew(HBoxContainer); - vb->add_child(hb2); - button_out_in = memnew(ToolButton); - button_out_in->set_tooltip(TTR("Out-In")); - button_out_in->set_h_size_flags(SIZE_EXPAND_FILL); - button_out_in->connect("pressed", this, "_set_preset", varray(-0.5)); - hb2->add_child(button_out_in); - - button_in_out = memnew(ToolButton); - button_in_out->set_tooltip(TTR("In")); - button_in_out->set_h_size_flags(SIZE_EXPAND_FILL); - button_in_out->connect("pressed", this, "_set_preset", varray(-2)); - hb2->add_child(button_in_out); - } + full = p_full; } void EditorPropertyEasing::_notification(int p_what) { @@ -907,15 +933,19 @@ void EditorPropertyEasing::_notification(int p_what) { switch (p_what) { case NOTIFICATION_THEME_CHANGED: case NOTIFICATION_ENTER_TREE: { + preset->clear(); + preset->add_icon_item(get_icon("CurveConstant", "EditorIcons"), "Zero", EASING_ZERO); + preset->add_icon_item(get_icon("CurveLinear", "EditorIcons"), "Linear", EASING_LINEAR); + preset->add_icon_item(get_icon("CurveIn", "EditorIcons"), "In", EASING_IN); + preset->add_icon_item(get_icon("CurveOut", "EditorIcons"), "Out", EASING_OUT); + if (full) { + preset->add_icon_item(get_icon("CurveInOut", "EditorIcons"), "In-Out", EASING_IN_OUT); + preset->add_icon_item(get_icon("CurveOutIn", "EditorIcons"), "Out-In", EASING_OUT_IN); + } easing_draw->set_custom_minimum_size(Size2(0, get_font("font", "Label")->get_height() * 2)); - button_linear->set_icon(get_icon("CurveLinear", "EditorIcons")); - button_out->set_icon(get_icon("CurveOut", "EditorIcons")); - button_in->set_icon(get_icon("CurveIn", "EditorIcons")); - button_constant->set_icon(get_icon("CurveConstant", "EditorIcons")); - if (button_out_in) - button_out_in->set_icon(get_icon("CurveOutIn", "EditorIcons")); - if (button_in_out) - button_in_out->set_icon(get_icon("CurveInOut", "EditorIcons")); + } break; + case NOTIFICATION_RESIZED: { + } break; } } @@ -929,47 +959,18 @@ void EditorPropertyEasing::_bind_methods() { EditorPropertyEasing::EditorPropertyEasing() { - vb = memnew(VBoxContainer); - add_child(vb); - HBoxContainer *hb = memnew(HBoxContainer); - set_label_reference(hb); - - vb->add_child(hb); - - button_linear = memnew(ToolButton); - button_linear->set_tooltip(TTR("Linear")); - button_linear->set_h_size_flags(SIZE_EXPAND_FILL); - button_linear->connect("pressed", this, "_set_preset", varray(1)); - hb->add_child(button_linear); - - button_constant = memnew(ToolButton); - button_constant->set_tooltip(TTR("Linear")); - button_constant->set_h_size_flags(SIZE_EXPAND_FILL); - button_constant->connect("pressed", this, "_set_preset", varray(0)); - hb->add_child(button_constant); - - button_out = memnew(ToolButton); - button_out->set_tooltip(TTR("Out")); - button_out->set_h_size_flags(SIZE_EXPAND_FILL); - button_out->connect("pressed", this, "_set_preset", varray(0.5)); - hb->add_child(button_out); - - button_in = memnew(ToolButton); - button_in->set_tooltip(TTR("In")); - button_in->set_h_size_flags(SIZE_EXPAND_FILL); - button_in->connect("pressed", this, "_set_preset", varray(2)); - hb->add_child(button_in); - - button_in_out = NULL; - button_out_in = NULL; - easing_draw = memnew(Control); easing_draw->connect("draw", this, "_draw_easing"); easing_draw->connect("gui_input", this, "_drag_easing"); easing_draw->set_default_cursor_shape(Control::CURSOR_MOVE); - vb->add_child(easing_draw); + add_child(easing_draw); + + preset = memnew(PopupMenu); + add_child(preset); + preset->connect("id_pressed", this, "_set_preset"); flip = false; + full = false; } ///////////////////// VECTOR2 ///////////////////////// @@ -992,6 +993,18 @@ void EditorPropertyVector2::update_property() { setting = false; } +void EditorPropertyVector2::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_color("accent_color", "Editor"); + for (int i = 0; i < 2; i++) { + + Color c = base; + c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v()); + spin[i]->set_custom_label_color(true, c); + } + } +} + void EditorPropertyVector2::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_changed"), &EditorPropertyVector2::_value_changed); @@ -1012,6 +1025,7 @@ EditorPropertyVector2::EditorPropertyVector2() { static const char *desc[2] = { "x", "y" }; for (int i = 0; i < 2; i++) { spin[i] = memnew(EditorSpinSlider); + spin[i]->set_flat(true); spin[i]->set_label(desc[i]); vb->add_child(spin[i]); add_focusable(spin[i]); @@ -1044,7 +1058,17 @@ void EditorPropertyRect2::update_property() { spin[3]->set_value(val.size.y); setting = false; } +void EditorPropertyRect2::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_color("accent_color", "Editor"); + for (int i = 0; i < 4; i++) { + Color c = base; + c.set_hsv(float(i % 2) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v()); + spin[i]->set_custom_label_color(true, c); + } + } +} void EditorPropertyRect2::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_changed"), &EditorPropertyRect2::_value_changed); @@ -1066,6 +1090,8 @@ EditorPropertyRect2::EditorPropertyRect2() { for (int i = 0; i < 4; i++) { spin[i] = memnew(EditorSpinSlider); spin[i]->set_label(desc[i]); + spin[i]->set_flat(true); + vb->add_child(spin[i]); add_focusable(spin[i]); spin[i]->connect("value_changed", this, "_value_changed"); @@ -1094,7 +1120,17 @@ void EditorPropertyVector3::update_property() { spin[2]->set_value(val.z); setting = false; } +void EditorPropertyVector3::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_color("accent_color", "Editor"); + for (int i = 0; i < 3; i++) { + Color c = base; + c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v()); + spin[i]->set_custom_label_color(true, c); + } + } +} void EditorPropertyVector3::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_changed"), &EditorPropertyVector3::_value_changed); @@ -1116,6 +1152,8 @@ EditorPropertyVector3::EditorPropertyVector3() { for (int i = 0; i < 3; i++) { spin[i] = memnew(EditorSpinSlider); spin[i]->set_label(desc[i]); + spin[i]->set_flat(true); + vb->add_child(spin[i]); add_focusable(spin[i]); spin[i]->connect("value_changed", this, "_value_changed"); @@ -1146,7 +1184,17 @@ void EditorPropertyPlane::update_property() { spin[3]->set_value(val.d); setting = false; } +void EditorPropertyPlane::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_color("accent_color", "Editor"); + for (int i = 0; i < 3; i++) { + Color c = base; + c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v()); + spin[i]->set_custom_label_color(true, c); + } + } +} void EditorPropertyPlane::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_changed"), &EditorPropertyPlane::_value_changed); @@ -1168,6 +1216,7 @@ EditorPropertyPlane::EditorPropertyPlane() { for (int i = 0; i < 4; i++) { spin[i] = memnew(EditorSpinSlider); spin[i]->set_label(desc[i]); + spin[i]->set_flat(true); vb->add_child(spin[i]); add_focusable(spin[i]); spin[i]->connect("value_changed", this, "_value_changed"); @@ -1199,7 +1248,17 @@ void EditorPropertyQuat::update_property() { spin[3]->set_value(val.w); setting = false; } +void EditorPropertyQuat::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_color("accent_color", "Editor"); + for (int i = 0; i < 3; i++) { + Color c = base; + c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v()); + spin[i]->set_custom_label_color(true, c); + } + } +} void EditorPropertyQuat::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_changed"), &EditorPropertyQuat::_value_changed); @@ -1221,6 +1280,8 @@ EditorPropertyQuat::EditorPropertyQuat() { for (int i = 0; i < 4; i++) { spin[i] = memnew(EditorSpinSlider); spin[i]->set_label(desc[i]); + spin[i]->set_flat(true); + vb->add_child(spin[i]); add_focusable(spin[i]); spin[i]->connect("value_changed", this, "_value_changed"); @@ -1258,7 +1319,17 @@ void EditorPropertyAABB::update_property() { setting = false; } +void EditorPropertyAABB::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_color("accent_color", "Editor"); + for (int i = 0; i < 6; i++) { + Color c = base; + c.set_hsv(float(i % 3) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v()); + spin[i]->set_custom_label_color(true, c); + } + } +} void EditorPropertyAABB::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_changed"), &EditorPropertyAABB::_value_changed); @@ -1282,6 +1353,8 @@ EditorPropertyAABB::EditorPropertyAABB() { for (int i = 0; i < 6; i++) { spin[i] = memnew(EditorSpinSlider); spin[i]->set_label(desc[i]); + spin[i]->set_flat(true); + g->add_child(spin[i]); spin[i]->set_h_size_flags(SIZE_EXPAND_FILL); add_focusable(spin[i]); @@ -1320,7 +1393,17 @@ void EditorPropertyTransform2D::update_property() { setting = false; } +void EditorPropertyTransform2D::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_color("accent_color", "Editor"); + for (int i = 0; i < 6; i++) { + Color c = base; + c.set_hsv(float(i % 2) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v()); + spin[i]->set_custom_label_color(true, c); + } + } +} void EditorPropertyTransform2D::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_changed"), &EditorPropertyTransform2D::_value_changed); @@ -1340,10 +1423,11 @@ EditorPropertyTransform2D::EditorPropertyTransform2D() { g->set_columns(2); add_child(g); - static const char *desc[6] = { "xx", "xy", "yx", "yy", "ox", "oy" }; + static const char *desc[6] = { "x", "y", "x", "y", "x", "y" }; for (int i = 0; i < 6; i++) { spin[i] = memnew(EditorSpinSlider); spin[i]->set_label(desc[i]); + spin[i]->set_flat(true); g->add_child(spin[i]); spin[i]->set_h_size_flags(SIZE_EXPAND_FILL); add_focusable(spin[i]); @@ -1388,7 +1472,17 @@ void EditorPropertyBasis::update_property() { setting = false; } +void EditorPropertyBasis::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_color("accent_color", "Editor"); + for (int i = 0; i < 9; i++) { + Color c = base; + c.set_hsv(float(i % 3) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v()); + spin[i]->set_custom_label_color(true, c); + } + } +} void EditorPropertyBasis::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_changed"), &EditorPropertyBasis::_value_changed); @@ -1408,10 +1502,11 @@ EditorPropertyBasis::EditorPropertyBasis() { g->set_columns(3); add_child(g); - static const char *desc[9] = { "xx", "xy", "xz", "yx", "yy", "yz", "zx", "zy", "zz" }; + static const char *desc[9] = { "x", "y", "z", "x", "y", "z", "x", "y", "z" }; for (int i = 0; i < 9; i++) { spin[i] = memnew(EditorSpinSlider); spin[i]->set_label(desc[i]); + spin[i]->set_flat(true); g->add_child(spin[i]); spin[i]->set_h_size_flags(SIZE_EXPAND_FILL); add_focusable(spin[i]); @@ -1462,7 +1557,17 @@ void EditorPropertyTransform::update_property() { setting = false; } +void EditorPropertyTransform::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_color("accent_color", "Editor"); + for (int i = 0; i < 12; i++) { + Color c = base; + c.set_hsv(float(i % 3) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v()); + spin[i]->set_custom_label_color(true, c); + } + } +} void EditorPropertyTransform::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_changed"), &EditorPropertyTransform::_value_changed); @@ -1482,10 +1587,11 @@ EditorPropertyTransform::EditorPropertyTransform() { g->set_columns(3); add_child(g); - static const char *desc[12] = { "xx", "xy", "xz", "yx", "yy", "yz", "zx", "zy", "zz", "ox", "oy", "oz" }; + static const char *desc[12] = { "x", "y", "z", "x", "y", "z", "x", "y", "z", "x", "y", "z" }; for (int i = 0; i < 12; i++) { spin[i] = memnew(EditorSpinSlider); spin[i]->set_label(desc[i]); + spin[i]->set_flat(true); g->add_child(spin[i]); spin[i]->set_h_size_flags(SIZE_EXPAND_FILL); add_focusable(spin[i]); @@ -1844,6 +1950,7 @@ void EditorPropertyResource::_resource_preview(const String &p_path, const Ref<T assign->set_custom_minimum_size(Size2(1, thumbnail_size)); } preview->set_texture(p_preview); + assign->set_text(""); } } } @@ -2037,6 +2144,9 @@ void EditorPropertyResource::update_property() { sub_inspector = memnew(EditorInspector); sub_inspector->set_enable_v_scroll(false); + sub_inspector->set_use_sub_inspector_bg(true); + sub_inspector->set_enable_capitalize_paths(true); + sub_inspector->connect("property_keyed", this, "_sub_inspector_property_keyed"); sub_inspector->connect("resource_selected", this, "_sub_inspector_resource_selected"); sub_inspector->connect("object_id_selected", this, "_sub_inspector_object_id_selected"); diff --git a/editor/editor_properties.h b/editor/editor_properties.h index b53d3ef40f..0afb1bf955 100644 --- a/editor/editor_properties.h +++ b/editor/editor_properties.h @@ -278,16 +278,26 @@ public: class EditorPropertyEasing : public EditorProperty { GDCLASS(EditorPropertyEasing, EditorProperty) Control *easing_draw; - ToolButton *button_out, *button_in, *button_linear, *button_constant; - ToolButton *button_in_out, *button_out_in; - VBoxContainer *vb; + PopupMenu *preset; + bool full; + + enum { + EASING_ZERO, + EASING_LINEAR, + EASING_IN, + EASING_OUT, + EASING_IN_OUT, + EASING_OUT_IN, + EASING_MAX + + }; bool flip; void _drag_easing(const Ref<InputEvent> &p_ev); void _draw_easing(); void _notification(int p_what); - void _set_preset(float p_val); + void _set_preset(int); protected: static void _bind_methods(); @@ -305,6 +315,7 @@ class EditorPropertyVector2 : public EditorProperty { void _value_changed(double p_val); protected: + void _notification(int p_what); static void _bind_methods(); public: @@ -320,6 +331,7 @@ class EditorPropertyRect2 : public EditorProperty { void _value_changed(double p_val); protected: + void _notification(int p_what); static void _bind_methods(); public: @@ -335,6 +347,7 @@ class EditorPropertyVector3 : public EditorProperty { void _value_changed(double p_val); protected: + void _notification(int p_what); static void _bind_methods(); public: @@ -350,6 +363,7 @@ class EditorPropertyPlane : public EditorProperty { void _value_changed(double p_val); protected: + void _notification(int p_what); static void _bind_methods(); public: @@ -365,6 +379,7 @@ class EditorPropertyQuat : public EditorProperty { void _value_changed(double p_val); protected: + void _notification(int p_what); static void _bind_methods(); public: @@ -380,6 +395,7 @@ class EditorPropertyAABB : public EditorProperty { void _value_changed(double p_val); protected: + void _notification(int p_what); static void _bind_methods(); public: @@ -395,6 +411,7 @@ class EditorPropertyTransform2D : public EditorProperty { void _value_changed(double p_val); protected: + void _notification(int p_what); static void _bind_methods(); public: @@ -410,6 +427,7 @@ class EditorPropertyBasis : public EditorProperty { void _value_changed(double p_val); protected: + void _notification(int p_what); static void _bind_methods(); public: @@ -425,6 +443,7 @@ class EditorPropertyTransform : public EditorProperty { void _value_changed(double p_val); protected: + void _notification(int p_what); static void _bind_methods(); public: diff --git a/editor/editor_sectioned_inspector.cpp b/editor/editor_sectioned_inspector.cpp new file mode 100644 index 0000000000..72050cd79b --- /dev/null +++ b/editor/editor_sectioned_inspector.cpp @@ -0,0 +1,306 @@ +#include "editor_sectioned_inspector.h" +#include "editor_scale.h" +class SectionedInspectorFilter : public Object { + + GDCLASS(SectionedInspectorFilter, Object); + + Object *edited; + String section; + bool allow_sub; + + bool _set(const StringName &p_name, const Variant &p_value) { + + if (!edited) + return false; + + String name = p_name; + if (section != "") { + name = section + "/" + name; + } + + bool valid; + edited->set(name, p_value, &valid); + return valid; + } + + bool _get(const StringName &p_name, Variant &r_ret) const { + + if (!edited) + return false; + + String name = p_name; + if (section != "") { + name = section + "/" + name; + } + + bool valid = false; + + r_ret = edited->get(name, &valid); + return valid; + } + void _get_property_list(List<PropertyInfo> *p_list) const { + + if (!edited) + return; + + List<PropertyInfo> pinfo; + edited->get_property_list(&pinfo); + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + + PropertyInfo pi = E->get(); + int sp = pi.name.find("/"); + + if (pi.name == "resource_path" || pi.name == "resource_name" || pi.name == "resource_local_to_scene" || pi.name.begins_with("script/")) //skip resource stuff + continue; + + if (sp == -1) { + pi.name = "global/" + pi.name; + } + + if (pi.name.begins_with(section + "/")) { + pi.name = pi.name.replace_first(section + "/", ""); + if (!allow_sub && pi.name.find("/") != -1) + continue; + p_list->push_back(pi); + } + } + } + + bool property_can_revert(const String &p_name) { + + return edited->call("property_can_revert", section + "/" + p_name); + } + + Variant property_get_revert(const String &p_name) { + + return edited->call("property_get_revert", section + "/" + p_name); + } + +protected: + static void _bind_methods() { + + ClassDB::bind_method("property_can_revert", &SectionedInspectorFilter::property_can_revert); + ClassDB::bind_method("property_get_revert", &SectionedInspectorFilter::property_get_revert); + } + +public: + void set_section(const String &p_section, bool p_allow_sub) { + + section = p_section; + allow_sub = p_allow_sub; + _change_notify(); + } + + void set_edited(Object *p_edited) { + edited = p_edited; + _change_notify(); + } + + SectionedInspectorFilter() { + edited = NULL; + } +}; + +void SectionedInspector::_bind_methods() { + + ClassDB::bind_method("_section_selected", &SectionedInspector::_section_selected); + ClassDB::bind_method("_search_changed", &SectionedInspector::_search_changed); + + ClassDB::bind_method("update_category_list", &SectionedInspector::update_category_list); +} + +void SectionedInspector::_section_selected() { + + if (!sections->get_selected()) + return; + + filter->set_section(sections->get_selected()->get_metadata(0), sections->get_selected()->get_children() == NULL); + inspector->set_property_prefix(String(sections->get_selected()->get_metadata(0)) + "/"); +} + +void SectionedInspector::set_current_section(const String &p_section) { + + if (section_map.has(p_section)) { + section_map[p_section]->select(0); + } +} + +String SectionedInspector::get_current_section() const { + + if (sections->get_selected()) + return sections->get_selected()->get_metadata(0); + else + return ""; +} + +String SectionedInspector::get_full_item_path(const String &p_item) { + + String base = get_current_section(); + + if (base != "") + return base + "/" + p_item; + else + return p_item; +} + +void SectionedInspector::edit(Object *p_object) { + + if (!p_object) { + obj = -1; + sections->clear(); + + filter->set_edited(NULL); + inspector->edit(NULL); + + return; + } + + ObjectID id = p_object->get_instance_id(); + + inspector->set_object_class(p_object->get_class()); + + if (obj != id) { + + obj = id; + update_category_list(); + + filter->set_edited(p_object); + inspector->edit(filter); + + if (sections->get_root()->get_children()) { + sections->get_root()->get_children()->select(0); + } + } else { + + update_category_list(); + } +} + +void SectionedInspector::update_category_list() { + + String selected_category = get_current_section(); + sections->clear(); + + Object *o = ObjectDB::get_instance(obj); + + if (!o) + return; + + List<PropertyInfo> pinfo; + o->get_property_list(&pinfo); + + section_map.clear(); + + TreeItem *root = sections->create_item(); + section_map[""] = root; + + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + + PropertyInfo pi = E->get(); + + if (pi.usage & PROPERTY_USAGE_CATEGORY) + continue; + else if (!(pi.usage & PROPERTY_USAGE_EDITOR)) + continue; + + if (pi.name.find(":") != -1 || pi.name == "script" || pi.name == "resource_name" || pi.name == "resource_path" || pi.name == "resource_local_to_scene") + continue; + + if (search_box && search_box->get_text() != String() && pi.name.findn(search_box->get_text()) == -1) + continue; + + int sp = pi.name.find("/"); + if (sp == -1) + pi.name = "Global/" + pi.name; + + Vector<String> sectionarr = pi.name.split("/"); + String metasection; + + int sc = MIN(2, sectionarr.size() - 1); + + for (int i = 0; i < sc; i++) { + + TreeItem *parent = section_map[metasection]; + parent->set_custom_bg_color(0, get_color("prop_subsection", "Editor")); + + if (i > 0) { + metasection += "/" + sectionarr[i]; + } else { + metasection = sectionarr[i]; + } + + if (!section_map.has(metasection)) { + TreeItem *ms = sections->create_item(parent); + section_map[metasection] = ms; + ms->set_text(0, sectionarr[i].capitalize()); + ms->set_metadata(0, metasection); + ms->set_selectable(0, false); + } + + if (i == sc - 1) { + //if it has children, make selectable + section_map[metasection]->set_selectable(0, true); + } + } + } + + if (section_map.has(selected_category)) { + section_map[selected_category]->select(0); + } + + inspector->update_tree(); +} + +void SectionedInspector::register_search_box(LineEdit *p_box) { + + search_box = p_box; + inspector->register_text_enter(p_box); + search_box->connect("text_changed", this, "_search_changed"); +} + +void SectionedInspector::_search_changed(const String &p_what) { + + update_category_list(); +} + +EditorInspector *SectionedInspector::get_inspector() { + + return inspector; +} + +SectionedInspector::SectionedInspector() { + + obj = -1; + + search_box = NULL; + + add_constant_override("autohide", 1); // Fixes the dragger always showing up + + VBoxContainer *left_vb = memnew(VBoxContainer); + left_vb->set_custom_minimum_size(Size2(170, 0) * EDSCALE); + add_child(left_vb); + + sections = memnew(Tree); + sections->set_v_size_flags(SIZE_EXPAND_FILL); + sections->set_hide_root(true); + + left_vb->add_child(sections, true); + + VBoxContainer *right_vb = memnew(VBoxContainer); + right_vb->set_custom_minimum_size(Size2(300, 0) * EDSCALE); + right_vb->set_h_size_flags(SIZE_EXPAND_FILL); + add_child(right_vb); + + filter = memnew(SectionedInspectorFilter); + inspector = memnew(EditorInspector); + inspector->set_v_size_flags(SIZE_EXPAND_FILL); + right_vb->add_child(inspector, true); + inspector->set_use_doc_hints(true); + + sections->connect("cell_selected", this, "_section_selected"); +} + +SectionedInspector::~SectionedInspector() { + + memdelete(filter); +} diff --git a/editor/editor_sectioned_inspector.h b/editor/editor_sectioned_inspector.h new file mode 100644 index 0000000000..75b51a1581 --- /dev/null +++ b/editor/editor_sectioned_inspector.h @@ -0,0 +1,42 @@ +#ifndef EDITOR_SECTIONED_INSPECTOR_H +#define EDITOR_SECTIONED_INSPECTOR_H + +#include "editor/editor_inspector.h" +#include "scene/gui/split_container.h" +#include "scene/gui/tree.h" + +class SectionedInspectorFilter; + +class SectionedInspector : public HSplitContainer { + + GDCLASS(SectionedInspector, HSplitContainer); + + ObjectID obj; + + Tree *sections; + SectionedInspectorFilter *filter; + + Map<String, TreeItem *> section_map; + EditorInspector *inspector; + LineEdit *search_box; + + static void _bind_methods(); + void _section_selected(); + + void _search_changed(const String &p_what); + +public: + void register_search_box(LineEdit *p_box); + EditorInspector *get_inspector(); + void edit(Object *p_object); + String get_full_item_path(const String &p_item); + + void set_current_section(const String &p_section); + String get_current_section() const; + + void update_category_list(); + + SectionedInspector(); + ~SectionedInspector(); +}; +#endif // EDITOR_SECTIONED_INSPECTOR_H diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp index 4045d6c3d3..466b12157d 100644 --- a/editor/editor_settings.cpp +++ b/editor/editor_settings.cpp @@ -165,6 +165,7 @@ struct _EVCSort { Variant::Type type; int order; bool save; + bool restart_if_changed; bool operator<(const _EVCSort &p_vcs) const { return order < p_vcs.order; } }; @@ -188,6 +189,7 @@ void EditorSettings::_get_property_list(List<PropertyInfo> *p_list) const { vc.order = v->order; vc.type = v->variant.get_type(); vc.save = v->save; + vc.restart_if_changed = v->restart_if_changed; vclist.insert(vc); } @@ -210,6 +212,10 @@ void EditorSettings::_get_property_list(List<PropertyInfo> *p_list) const { if (hints.has(E->get().name)) pi = hints[E->get().name]; + if (E->get().restart_if_changed) { + pi.usage |= PROPERTY_USAGE_RESTART_IF_CHANGED; + } + p_list->push_back(pi); } @@ -280,6 +286,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { } _initial_set("interface/editor/editor_language", best); + set_restart_if_changed("interface/editor/editor_language", true); hints["interface/editor/editor_language"] = PropertyInfo(Variant::STRING, "interface/editor/editor_language", PROPERTY_HINT_ENUM, lang_hint, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED); } @@ -357,6 +364,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { _initial_set("text_editor/highlighting/highlight_all_occurrences", true); _initial_set("text_editor/highlighting/highlight_current_line", true); + _initial_set("text_editor/highlighting/highlight_type_safe_lines", true); _initial_set("text_editor/cursor/scroll_past_end_of_file", false); _initial_set("text_editor/indent/type", 0); @@ -397,6 +405,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { _initial_set("text_editor/completion/callhint_tooltip_offset", Vector2()); _initial_set("text_editor/files/restore_scripts_on_load", true); _initial_set("text_editor/completion/complete_file_paths", true); + _initial_set("text_editor/completion/add_type_hints", false); _initial_set("docks/scene_tree/start_create_dialog_fully_expanded", false); _initial_set("docks/scene_tree/draw_relationship_lines", false); @@ -585,6 +594,7 @@ void EditorSettings::_load_default_text_editor_theme() { _initial_set("text_editor/highlighting/completion_font_color", Color::html("aaaaaa")); _initial_set("text_editor/highlighting/text_color", Color::html("aaaaaa")); _initial_set("text_editor/highlighting/line_number_color", Color::html("66aaaaaa")); + _initial_set("text_editor/highlighting/safe_line_number_color", Color::html("99aac8aa")); _initial_set("text_editor/highlighting/caret_color", Color::html("aaaaaa")); _initial_set("text_editor/highlighting/caret_background_color", Color::html("000000")); _initial_set("text_editor/highlighting/text_selected_color", Color::html("000000")); @@ -1017,6 +1027,14 @@ void EditorSettings::raise_order(const String &p_setting) { props[p_setting].order = ++last_order; } +void EditorSettings::set_restart_if_changed(const StringName &p_setting, bool p_restart) { + _THREAD_SAFE_METHOD_ + + if (!props.has(p_setting)) + return; + props[p_setting].restart_if_changed = p_restart; +} + void EditorSettings::set_initial_value(const StringName &p_setting, const Variant &p_value, bool p_update_current) { _THREAD_SAFE_METHOD_ @@ -1030,16 +1048,19 @@ void EditorSettings::set_initial_value(const StringName &p_setting, const Varian } } -Variant _EDITOR_DEF(const String &p_setting, const Variant &p_default) { +Variant _EDITOR_DEF(const String &p_setting, const Variant &p_default, bool p_restart_if_changed) { Variant ret = p_default; - if (EditorSettings::get_singleton()->has_setting(p_setting)) + if (EditorSettings::get_singleton()->has_setting(p_setting)) { ret = EditorSettings::get_singleton()->get(p_setting); - else + } else { EditorSettings::get_singleton()->set_manually(p_setting, p_default); + EditorSettings::get_singleton()->set_restart_if_changed(p_setting, p_restart_if_changed); + } - if (!EditorSettings::get_singleton()->has_default_value(p_setting)) + if (!EditorSettings::get_singleton()->has_default_value(p_setting)) { EditorSettings::get_singleton()->set_initial_value(p_setting, p_default); + } return ret; } diff --git a/editor/editor_settings.h b/editor/editor_settings.h index 420e067cad..e5b61abf54 100644 --- a/editor/editor_settings.h +++ b/editor/editor_settings.h @@ -70,6 +70,7 @@ private: bool has_default_value; bool hide_from_editor; bool save; + bool restart_if_changed; VariantContainer() { variant = Variant(); initial = Variant(); @@ -77,6 +78,7 @@ private: hide_from_editor = false; has_default_value = false; save = false; + restart_if_changed = false; } VariantContainer(const Variant &p_variant, int p_order) { variant = p_variant; @@ -85,6 +87,7 @@ private: hide_from_editor = false; has_default_value = false; save = false; + restart_if_changed = false; } }; @@ -145,6 +148,7 @@ public: void erase(const String &p_setting); void raise_order(const String &p_setting); void set_initial_value(const StringName &p_setting, const Variant &p_value, bool p_update_current = false); + void set_restart_if_changed(const StringName &p_setting, bool p_restart); void set_manually(const StringName &p_setting, const Variant &p_value, bool p_emit_signal = false) { if (p_emit_signal) _set(p_setting, p_value); @@ -200,7 +204,8 @@ public: //not a macro any longer #define EDITOR_DEF(m_var, m_val) _EDITOR_DEF(m_var, Variant(m_val)) -Variant _EDITOR_DEF(const String &p_setting, const Variant &p_default); +#define EDITOR_DEF_RST(m_var, m_val) _EDITOR_DEF(m_var, Variant(m_val), true) +Variant _EDITOR_DEF(const String &p_setting, const Variant &p_default, bool p_restart_if_changed = false); #define EDITOR_GET(m_var) _EDITOR_GET(m_var) Variant _EDITOR_GET(const String &p_setting); diff --git a/editor/editor_spin_slider.cpp b/editor/editor_spin_slider.cpp index 33f7d3c5c4..0e6d81d13b 100644 --- a/editor/editor_spin_slider.cpp +++ b/editor/editor_spin_slider.cpp @@ -161,20 +161,20 @@ void EditorSpinSlider::_notification(int p_what) { updown_offset = -1; Ref<StyleBox> sb = get_stylebox("normal", "LineEdit"); - draw_style_box(sb, Rect2(Vector2(), get_size())); + if (!flat) { + draw_style_box(sb, Rect2(Vector2(), get_size())); + } Ref<Font> font = get_font("font", "LineEdit"); + int sep_base = 4 * EDSCALE; + int sep = sep_base + sb->get_offset().x; //make it have the same margin on both sides, looks better + + int string_width = font->get_string_size(label).width; + int number_width = get_size().width - sb->get_minimum_size().width - string_width - sep; - int avail_width = get_size().width - sb->get_minimum_size().width; - avail_width -= font->get_string_size(label).width; Ref<Texture> updown = get_icon("updown", "SpinBox"); if (get_step() == 1) { - avail_width -= updown->get_width(); - } - - if (has_focus()) { - Ref<StyleBox> focus = get_stylebox("focus", "LineEdit"); - draw_style_box(focus, Rect2(Vector2(), get_size())); + number_width -= updown->get_width(); } String numstr = get_text_value(); @@ -182,10 +182,26 @@ void EditorSpinSlider::_notification(int p_what) { int vofs = (get_size().height - font->get_height()) / 2 + font->get_ascent(); Color fc = get_color("font_color", "LineEdit"); + Color lc; + if (use_custom_label_color) { + lc = custom_label_color; + } else { + lc = fc; + } + + if (flat && label != String()) { + Color label_bg_color = get_color("dark_color_3", "Editor"); + draw_rect(Rect2(Vector2(), Vector2(sb->get_offset().x * 2 + string_width, get_size().height)), label_bg_color); + } + + if (has_focus()) { + Ref<StyleBox> focus = get_stylebox("focus", "LineEdit"); + draw_style_box(focus, Rect2(Vector2(), get_size())); + } - int label_ofs = sb->get_offset().x + avail_width; - draw_string(font, Vector2(label_ofs, vofs), label, fc * Color(1, 1, 1, 0.5)); - draw_string(font, Vector2(sb->get_offset().x, vofs), numstr, fc, avail_width); + draw_string(font, Vector2(sb->get_offset().x, vofs), label, lc * Color(1, 1, 1, 0.5)); + + draw_string(font, Vector2(sb->get_offset().x + string_width + sep, vofs), numstr, fc, number_width); if (get_step() == 1) { Ref<Texture> updown = get_icon("updown", "SpinBox"); @@ -252,9 +268,12 @@ void EditorSpinSlider::_notification(int p_what) { update(); } if (p_what == NOTIFICATION_FOCUS_ENTER) { - if (!Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT) && !value_input_just_closed) { + /* Sorry, I dont like this, it makes navigating the different fields with arrows more difficult. + * Just press enter to edit. + * if (!Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT) && !value_input_just_closed) { _focus_entered(); - } + }*/ + value_input_just_closed = false; } } @@ -336,6 +355,21 @@ bool EditorSpinSlider::is_read_only() const { return read_only; } +void EditorSpinSlider::set_flat(bool p_enable) { + + flat = p_enable; + update(); +} + +bool EditorSpinSlider::is_flat() const { + return flat; +} + +void EditorSpinSlider::set_custom_label_color(bool p_use_custom_label_color, Color p_custom_label_color) { + use_custom_label_color = p_use_custom_label_color; + custom_label_color = p_custom_label_color; +} + void EditorSpinSlider::_focus_entered() { Rect2 gr = get_global_rect(); value_input->set_text(get_text_value()); @@ -355,6 +389,9 @@ void EditorSpinSlider::_bind_methods() { ClassDB::bind_method(D_METHOD("set_read_only", "read_only"), &EditorSpinSlider::set_read_only); ClassDB::bind_method(D_METHOD("is_read_only"), &EditorSpinSlider::is_read_only); + ClassDB::bind_method(D_METHOD("set_flat", "flat"), &EditorSpinSlider::set_flat); + ClassDB::bind_method(D_METHOD("is_flat"), &EditorSpinSlider::is_flat); + ClassDB::bind_method(D_METHOD("_gui_input"), &EditorSpinSlider::_gui_input); ClassDB::bind_method(D_METHOD("_grabber_mouse_entered"), &EditorSpinSlider::_grabber_mouse_entered); ClassDB::bind_method(D_METHOD("_grabber_mouse_exited"), &EditorSpinSlider::_grabber_mouse_exited); @@ -365,10 +402,12 @@ void EditorSpinSlider::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::STRING, "label"), "set_label", "get_label"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "read_only"), "set_read_only", "is_read_only"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat"); } EditorSpinSlider::EditorSpinSlider() { + flat = false; grabbing_spinner_attempt = false; grabbing_spinner = false; grabbing_spinner_dist_cache = 0; @@ -397,4 +436,5 @@ EditorSpinSlider::EditorSpinSlider() { value_input_just_closed = false; hide_slider = false; read_only = false; + use_custom_label_color = false; } diff --git a/editor/editor_spin_slider.h b/editor/editor_spin_slider.h index 5316c0264a..fb32534ef4 100644 --- a/editor/editor_spin_slider.h +++ b/editor/editor_spin_slider.h @@ -68,6 +68,10 @@ class EditorSpinSlider : public Range { void _value_input_entered(const String &); void _value_focus_exited(); bool hide_slider; + bool flat; + + bool use_custom_label_color; + Color custom_label_color; protected: void _notification(int p_what); @@ -88,6 +92,11 @@ public: void set_read_only(bool p_enable); bool is_read_only() const; + void set_flat(bool p_enable); + bool is_flat() const; + + void set_custom_label_color(bool p_use_custom_label_color, Color p_custom_label_color); + virtual Size2 get_minimum_size() const; EditorSpinSlider(); }; diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp index 0534a398f4..ea9f6db61a 100644 --- a/editor/editor_themes.cpp +++ b/editor/editor_themes.cpp @@ -656,6 +656,14 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { theme->set_icon("visibility_xray", "PopupMenu", theme->get_icon("GuiVisibilityXray", "EditorIcons")); theme->set_constant("vseparation", "PopupMenu", (extra_spacing + default_margin_size) * EDSCALE); + Ref<StyleBoxFlat> sub_inspector_bg = make_flat_stylebox(dark_color_1, 2, 0, 0, 0); + sub_inspector_bg->set_border_width(MARGIN_LEFT, 2); + sub_inspector_bg->set_border_color(MARGIN_LEFT, accent_color * Color(1, 1, 1, 0.3)); + sub_inspector_bg->set_draw_center(true); + + theme->set_stylebox("sub_inspector_bg", "Editor", sub_inspector_bg); + theme->set_constant("inspector_margin", "Editor", 8 * EDSCALE); + // Tree & ItemList background Ref<StyleBoxFlat> style_tree_bg = style_default->duplicate(); style_tree_bg->set_bg_color(dark_color_1); @@ -666,6 +674,7 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { // Tree theme->set_icon("checked", "Tree", theme->get_icon("GuiChecked", "EditorIcons")); theme->set_icon("unchecked", "Tree", theme->get_icon("GuiUnchecked", "EditorIcons")); + theme->set_icon("arrow_up", "Tree", theme->get_icon("GuiTreeArrowUp", "EditorIcons")); theme->set_icon("arrow", "Tree", theme->get_icon("GuiTreeArrowDown", "EditorIcons")); theme->set_icon("arrow_collapsed", "Tree", theme->get_icon("GuiTreeArrowRight", "EditorIcons")); theme->set_icon("updown", "Tree", theme->get_icon("GuiTreeUpdown", "EditorIcons")); @@ -1080,6 +1089,7 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { const Color completion_font_color = font_color; const Color text_color = font_color; const Color line_number_color = dim_color; + const Color safe_line_number_color = dim_color * Color(1, 1.2, 1, 1.5); const Color caret_color = mono_color; const Color caret_background_color = mono_color.inverted(); const Color text_selected_color = dark_color_3; @@ -1114,6 +1124,7 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { setting->set_initial_value("text_editor/highlighting/completion_font_color", completion_font_color, true); setting->set_initial_value("text_editor/highlighting/text_color", text_color, true); setting->set_initial_value("text_editor/highlighting/line_number_color", line_number_color, true); + setting->set_initial_value("text_editor/highlighting/safe_line_number_color", safe_line_number_color, true); setting->set_initial_value("text_editor/highlighting/caret_color", caret_color, true); setting->set_initial_value("text_editor/highlighting/caret_background_color", caret_background_color, true); setting->set_initial_value("text_editor/highlighting/text_selected_color", text_selected_color, true); diff --git a/editor/icons/icon_GUI_tree_arrow_up.svg b/editor/icons/icon_GUI_tree_arrow_up.svg new file mode 100644 index 0000000000..4e6e8e9e29 --- /dev/null +++ b/editor/icons/icon_GUI_tree_arrow_up.svg @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="12" + height="12" + version="1.1" + viewBox="0 0 12 12" + id="svg6" + sodipodi:docname="icon_GUI_tree_arrow_up.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1673" + inkscape:window-height="594" + id="namedview8" + showgrid="false" + inkscape:zoom="19.666667" + inkscape:cx="-4.3220338" + inkscape:cy="6.0000001" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <g + transform="rotate(180,6,526.08476)" + id="g4"> + <path + d="m 3,1045.4 3,3 3,-3" + id="path2" + inkscape:connector-curvature="0" + style="fill:none;stroke:#ffffff;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;stroke-opacity:0.39216003" /> + </g> +</svg> diff --git a/editor/icons/icon_g_l_e_s_2.svg b/editor/icons/icon_g_l_e_s_2.svg new file mode 100644 index 0000000000..efc4f01e4f --- /dev/null +++ b/editor/icons/icon_g_l_e_s_2.svg @@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> + +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + version="1.1" + id="svg2" + width="48" + height="16" + viewBox="0 0 47.999999 16" + sodipodi:docname="icon_g_l_e_s_2.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata8"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs6" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1484" + inkscape:window-height="697" + id="namedview4" + showgrid="false" + inkscape:zoom="13.520979" + inkscape:cx="20.549976" + inkscape:cy="7.9399684" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg2" /> + <path + inkscape:connector-curvature="0" + id="path835" + d="m 19.839879,15.499154 c -0.0652,-0.0268 -0.141743,-0.1098 -0.170113,-0.184417 -0.03304,-0.08688 -0.05158,-0.95731 -0.05158,-5.912028 V 3.1830459 l 0.108486,-0.1379162 c 0.150269,-0.1910365 0.41814,-0.1907342 0.568677,6.436e-4 l 0.10899,0.1385579 -0.01358,6.2990785 c -0.01194,6.8660953 -0.0921,5.3381383 -0.0921,5.9327083 -0.106573,0.104434 -0.315006,0.142158 -0.458762,0.08303 z M 5.3808767,14.575188 C 4.5309456,14.518738 3.6260357,14.196602 2.9750499,13.718734 2.5767564,13.42636 2.0035795,12.787236 1.747789,12.350269 1.2385669,11.480363 1.0170768,10.580508 1.0213778,9.399057 1.0293972,7.2009406 1.9726797,5.5285643 3.6891526,4.6693537 4.7813316,4.1226444 6.2246017,4.0371807 7.4330177,4.4476602 8.1309525,4.6847376 8.4685433,4.8972607 9.0207129,5.4471587 9.4063328,5.8311907 9.5338898,6.0004852 9.7108978,6.3631718 9.8335428,6.6144683 9.9681328,6.9987435 10.020175,7.2461971 10.145759,7.8433551 10.170431,7.8289765 9.0218356,7.828057 8.5307356,7.8276009 8.0769363,7.8134035 8.0133918,7.7963663 7.9392662,7.7764919 7.8757344,7.6970176 7.8361313,7.5746239 7.5012661,6.5397183 6.6297764,6.0267536 5.4889128,6.193037 4.244092,6.3744711 3.4980921,7.3344965 3.343357,8.9541432 3.2260083,10.182472 3.5434132,11.329338 4.1781352,11.97041 c 0.46237,0.466997 0.9869175,0.673904 1.7084683,0.673904 1.2025378,0 1.9439704,-0.533034 2.1862936,-1.57178 0.055989,-0.240028 0.059178,-0.324448 0.012859,-0.341503 -0.033838,-0.01246 -0.5090516,-0.02871 -1.0560342,-0.03612 L 6.0352096,10.681458 V 9.8178001 8.9541431 l 1.9890278,-0.014575 c 1.0939663,-0.00802 2.0422396,-0.00163 2.1072756,0.014201 l 0.118246,0.028779 -0.01356,2.6814549 -0.01356,2.681455 -0.7170922,0.01455 c -0.8295927,0.01682 -0.7753286,0.05076 -0.8815155,-0.55106 -0.036825,-0.208719 -0.077853,-0.379487 -0.091164,-0.379487 -0.013311,0 -0.16916,0.135437 -0.3463303,0.300972 -0.3894417,0.363866 -0.8188673,0.600316 -1.3418506,0.738852 -0.4725114,0.125166 -0.8081647,0.149449 -1.4638111,0.10591 z M 32.49721,14.469781 c -0.928547,-0.194854 -1.630354,-0.56605 -2.174913,-1.150343 -0.515384,-0.552992 -0.832054,-1.344249 -0.800629,-2.000518 l 0.01549,-0.323408 1.060826,-0.01418 1.060825,-0.01418 0.05146,0.135352 c 0.0283,0.07444 0.0517,0.198593 0.05197,0.275887 8.54e-4,0.230559 0.229434,0.649361 0.479979,0.879354 0.347226,0.318744 0.735307,0.44853 1.431019,0.478576 1.267096,0.05472 2.007349,-0.393206 1.947849,-1.178652 -0.0456,-0.601928 -0.471503,-0.860841 -2.12876,-1.294103 C 32.881626,10.103917 32.242852,9.9264243 32.07283,9.8691486 30.95902,9.4939337 30.283515,8.9537559 29.97948,8.195172 29.836139,7.8375288 29.784025,7.0484225 29.874852,6.6109088 30.100606,5.5234588 31.071976,4.6456053 32.416011,4.314394 33.01697,4.1662997 34.128873,4.156633 34.77144,4.293917 c 1.67335,0.3575071 2.584333,1.270761 2.774448,2.7813655 0.0543,0.4314615 0.0347,0.4394334 -1.080484,0.4394334 -0.521251,0 -0.9851,-0.023133 -1.038665,-0.051802 C 35.367672,7.4313026 35.307808,7.3078793 35.273143,7.1462409 35.195527,6.7843357 35.099156,6.6147944 34.849667,6.4012402 34.543832,6.1394568 34.14764,6.029069 33.515213,6.0294329 c -0.428465,2.111e-4 -0.570793,0.021517 -0.784491,0.1172346 -0.47592,0.2131691 -0.654939,0.4628549 -0.654939,0.9134748 0,0.5904894 0.225799,0.7059322 2.58195,1.3200619 1.350552,0.3520209 1.903346,0.598685 2.415601,1.0778741 0.591219,0.5530567 0.852295,1.2543747 0.796412,2.1393787 -0.07929,1.255762 -0.891416,2.255747 -2.192274,2.699402 -0.885807,0.302103 -2.21918,0.374602 -3.180262,0.172924 z M 11.476954,14.306572 c -0.0138,-0.03619 -0.019,-2.268126 -0.01158,-4.9598581 l 0.0135,-4.8940567 1.066335,-0.01419 c 0.742348,-0.00988 1.088249,0.00399 1.138458,0.045665 0.06009,0.049873 0.07211,0.7135739 0.07211,3.9791612 v 3.9193056 h 2.293081 c 1.756352,0 2.314103,0.01538 2.382892,0.06567 0.07993,0.05845 0.08822,0.166396 0.07543,0.981428 l -0.01437,0.915757 -3.495384,0.01345 c -2.768549,0.0107 -3.500605,-1.69e-4 -3.520473,-0.05234 z m 10.193414,0.0026 c -0.04842,-0.04842 -0.06297,-1.193838 -0.06236,-4.9074882 4.61e-4,-2.6643823 0.01959,-4.8739347 0.04256,-4.9101166 0.03301,-0.05201 0.813774,-0.062971 3.728627,-0.052342 l 3.686862,0.013441 V 5.3948518 6.337024 l -2.5648,0.026171 -2.5648,0.026172 v 0.9421438 0.9421716 l 2.313597,0.026171 c 1.548367,0.017515 2.332217,0.044804 2.36989,0.082507 0.03673,0.036745 0.05127,0.3461819 0.04183,0.889829 l -0.01446,0.8334926 -2.355428,0.02617 -2.355429,0.02617 v 1.0992 1.099199 l 2.617143,0.0274 c 1.439428,0.01507 2.623562,0.03274 2.63141,0.03926 0.0078,0.0065 0.0078,0.441727 0,0.967118 l -0.01427,0.955257 -3.718613,0.01343 c -2.848812,0.01027 -3.733388,-0.0013 -3.781773,-0.04973 z m 17.753791,-0.378679 c -0.04061,-0.105824 0.0759,-0.828141 0.198829,-1.232689 0.288088,-0.948035 0.88431,-1.590368 2.319422,-2.498804 1.100465,-0.6965999 1.86374,-1.2293374 2.17747,-1.5198007 0.515251,-0.477031 0.731074,-1.0868265 0.620161,-1.7522036 -0.126353,-0.7579473 -0.607483,-1.1395723 -1.436711,-1.1395723 -0.930964,0 -1.401324,0.4507271 -1.481617,1.4197789 l -0.03634,0.4383927 h -1.099202 -1.099196 l -0.01524,-0.3725124 c -0.03408,-0.8332648 0.288934,-1.6827799 0.855164,-2.2490093 0.399774,-0.3997734 1.09283,-0.7574546 1.70958,-0.8822975 0.580047,-0.1174131 1.71432,-0.1077309 2.332892,0.019914 1.258364,0.2596698 2.203978,1.0560413 2.520675,2.1228587 0.104477,0.3519131 0.117355,0.4871812 0.09657,1.0144101 -0.01959,0.4962935 -0.04847,0.667451 -0.157022,0.9292002 -0.313508,0.7560998 -0.900391,1.3802206 -1.888823,2.0086882 -1.507571,0.958543 -1.915442,1.243322 -2.230808,1.557578 -0.26352,0.262604 -0.32016,0.345357 -0.261709,0.382352 0.04123,0.0261 1.061246,0.04757 2.280484,0.04802 1.96272,7.11e-4 2.209393,0.0099 2.237659,0.0836 0.01749,0.04554 0.03178,0.408703 0.03178,0.807033 0,0.398331 -0.0143,0.761495 -0.03178,0.807033 -0.0286,0.07445 -0.414152,0.0828 -3.822672,0.0828 -3.236429,0 -3.795092,-0.01093 -3.819578,-0.07475 z" + style="fill:#5586a4;fill-opacity:1;stroke-width:0.05234285" + sodipodi:nodetypes="ccscccccccccsscsscccccscccsccsccccccccccssscccccccccccccccscsccsccccsssscscccccccscscscccccccscccccccscccccccscccccccccccscccccsssccccccccscscc" /> + <path + style="fill:#000000;stroke-width:1.06666672" + d="" + id="path819" + inkscape:connector-curvature="0" /> + <path + style="fill:#000000;stroke-width:1.06666672" + d="" + id="path817" + inkscape:connector-curvature="0" /> +</svg> diff --git a/editor/icons/icon_g_l_e_s_3.svg b/editor/icons/icon_g_l_e_s_3.svg new file mode 100644 index 0000000000..dfa3c26b38 --- /dev/null +++ b/editor/icons/icon_g_l_e_s_3.svg @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> + +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + version="1.1" + id="svg2" + width="48" + height="16" + viewBox="0 0 47.999999 16" + sodipodi:docname="icon_g_l_e_s_3.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata8"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs6" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1484" + inkscape:window-height="697" + id="namedview4" + showgrid="false" + inkscape:zoom="13.520979" + inkscape:cx="20.549976" + inkscape:cy="7.9399684" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg2" /> + <path + style="fill:#6aa455;fill-opacity:1;stroke-width:0.05234285" + d="M 20.011719 2.9023438 C 19.90715 2.9022255 19.801697 2.9494036 19.726562 3.0449219 L 19.619141 3.1835938 L 19.619141 9.4023438 C 19.619141 14.357062 19.636882 15.227573 19.669922 15.314453 C 19.698292 15.38907 19.774644 15.4732 19.839844 15.5 C 19.9836 15.559128 20.192255 15.52045 20.298828 15.416016 C 20.298828 14.821446 20.378685 16.35047 20.390625 9.484375 L 20.404297 3.1835938 L 20.294922 3.0449219 C 20.219653 2.949233 20.116287 2.902462 20.011719 2.9023438 z M 33.578125 4.1972656 C 33.144709 4.2010336 32.716495 4.240406 32.416016 4.3144531 C 31.071981 4.6456644 30.100754 5.5238781 29.875 6.6113281 C 29.784173 7.0488418 29.835175 7.8376693 29.978516 8.1953125 C 30.282551 8.9538964 30.958456 9.4939257 32.072266 9.8691406 C 32.242288 9.9264163 32.881487 10.104023 33.492188 10.263672 C 35.149445 10.696934 35.575494 10.956666 35.621094 11.558594 C 35.680594 12.34404 34.940924 12.791048 33.673828 12.736328 C 32.978116 12.706282 32.589413 12.576557 32.242188 12.257812 C 31.991643 12.02782 31.762573 11.609465 31.761719 11.378906 C 31.761449 11.301612 31.739238 11.176002 31.710938 11.101562 L 31.658203 10.966797 L 30.597656 10.980469 L 29.537109 10.996094 L 29.521484 11.318359 C 29.490059 11.974628 29.806882 12.767321 30.322266 13.320312 C 30.866825 13.904606 31.5695 14.275849 32.498047 14.470703 C 33.459129 14.672381 34.791927 14.598978 35.677734 14.296875 C 36.978592 13.85322 37.789851 12.853418 37.869141 11.597656 C 37.925024 10.712652 37.665438 10.012041 37.074219 9.4589844 C 36.561964 8.9797953 36.008755 8.7328803 34.658203 8.3808594 C 32.302052 7.7667297 32.076172 7.6510363 32.076172 7.0605469 C 32.076172 6.609927 32.254549 6.3596535 32.730469 6.1464844 C 32.944167 6.0507668 33.08716 6.029508 33.515625 6.0292969 C 34.148052 6.028933 34.543774 6.1386072 34.849609 6.4003906 C 35.099098 6.6139448 35.195822 6.7845792 35.273438 7.1464844 C 35.308103 7.3081228 35.366714 7.4312793 35.425781 7.4628906 C 35.479346 7.4915596 35.943593 7.515625 36.464844 7.515625 C 37.580028 7.515625 37.599222 7.5076334 37.544922 7.0761719 C 37.354807 5.5655674 36.444834 4.6504759 34.771484 4.2929688 C 34.450201 4.2243268 34.011541 4.1934977 33.578125 4.1972656 z M 5.5175781 4.1992188 C 4.8691862 4.2376134 4.2355426 4.3965672 3.6894531 4.6699219 C 1.9729802 5.5291325 1.0295038 7.2003211 1.0214844 9.3984375 C 1.0171834 10.579889 1.2388248 11.479703 1.7480469 12.349609 C 2.0038374 12.786576 2.5763159 13.426376 2.9746094 13.71875 C 3.6255952 14.196618 4.5309283 14.517769 5.3808594 14.574219 C 6.0365058 14.617758 6.3712386 14.593916 6.84375 14.46875 C 7.3667333 14.330214 7.7980583 14.094335 8.1875 13.730469 C 8.3646703 13.564934 8.5198921 13.429688 8.5332031 13.429688 C 8.5465141 13.429688 8.588175 13.599875 8.625 13.808594 C 8.7311869 14.410414 8.6762667 14.376195 9.5058594 14.359375 L 10.222656 14.345703 L 10.236328 11.664062 L 10.25 8.9824219 L 10.130859 8.953125 C 10.065823 8.937294 9.1174038 8.9314331 8.0234375 8.9394531 L 6.0351562 8.9550781 L 6.0351562 9.8183594 L 6.0351562 10.681641 L 7.0292969 10.695312 C 7.5762795 10.702722 8.0520995 10.718009 8.0859375 10.730469 C 8.1322565 10.747524 8.1282546 10.832238 8.0722656 11.072266 C 7.8299424 12.111012 7.0892565 12.644531 5.8867188 12.644531 C 5.1651679 12.644531 4.6401044 12.4377 4.1777344 11.970703 C 3.5430124 11.329631 3.2264013 10.183407 3.34375 8.9550781 C 3.4984851 7.3354314 4.2434605 6.3747935 5.4882812 6.1933594 C 6.6291449 6.027076 7.5010723 6.5393131 7.8359375 7.5742188 C 7.8755406 7.6966124 7.9395463 7.7770006 8.0136719 7.796875 C 8.0772164 7.8139122 8.5303844 7.8276689 9.0214844 7.828125 C 10.17008 7.8290445 10.145115 7.8432518 10.019531 7.2460938 C 9.967489 6.9986401 9.8335825 6.6145778 9.7109375 6.3632812 C 9.5339295 6.0005947 9.4071043 5.8312976 9.0214844 5.4472656 C 8.4693148 4.8973676 8.1315285 4.684343 7.4335938 4.4472656 C 6.8293858 4.2420259 6.16597 4.1608241 5.5175781 4.1992188 z M 42.03125 4.2617188 L 41.537109 4.4335938 C 40.933232 4.6433398 40.657695 4.8014669 40.300781 5.1386719 C 39.969225 5.4519119 39.761404 5.8046136 39.621094 6.2910156 C 39.502474 6.7023596 39.433137 7.3494687 39.498047 7.4492188 C 39.531044 7.4999487 39.783863 7.5127831 40.576172 7.5019531 L 41.611328 7.4863281 L 41.691406 7.0703125 C 41.808812 6.4678105 41.927622 6.2685471 42.265625 6.0957031 C 42.510424 5.9705181 42.604184 5.953125 43.019531 5.953125 C 43.426321 5.953125 43.533311 5.9721266 43.765625 6.0878906 C 44.253715 6.3311276 44.455638 6.904517 44.273438 7.53125 C 44.105442 8.109131 43.697334 8.363965 42.791016 8.453125 C 42.521874 8.479605 42.288464 8.51424 42.271484 8.53125 C 42.225224 8.577174 42.232777 9.7874244 42.279297 9.8339844 C 42.301291 9.8559744 42.598053 9.8907794 42.939453 9.9121094 C 43.836652 9.9681724 44.239534 10.166191 44.525391 10.691406 C 44.916028 11.409137 44.561069 12.318315 43.787109 12.582031 C 43.476088 12.688024 42.767292 12.688624 42.470703 12.583984 C 42.00204 12.418633 41.795632 12.174325 41.642578 11.597656 L 41.560547 11.285156 L 40.46875 11.285156 L 39.376953 11.285156 L 39.361328 11.527344 C 39.352678 11.660649 39.384791 11.918152 39.431641 12.099609 C 39.739925 13.294376 40.783209 14.156157 42.212891 14.396484 C 42.284425 14.408514 42.682741 14.422181 43.097656 14.425781 C 44.074936 14.434074 44.653306 14.320796 45.308594 13.996094 C 46.07786 13.61492 46.610204 13.058412 46.847656 12.382812 C 47.087412 11.700564 47.08166 10.999125 46.833984 10.333984 C 46.695621 9.962377 46.130198 9.3782416 45.6875 9.1503906 C 45.523031 9.0657476 45.386773 8.9810006 45.386719 8.9628906 C 45.386654 8.9447846 45.539488 8.8195027 45.724609 8.6835938 C 46.129744 8.3861558 46.390215 8.064434 46.53125 7.6875 C 46.963216 6.532963 46.370297 5.2063894 45.166016 4.6308594 C 44.482944 4.3044164 44.23589 4.2611938 43.072266 4.2617188 L 42.03125 4.2617188 z M 12.544922 4.4375 L 11.478516 4.453125 L 11.464844 9.3476562 C 11.457424 12.039388 11.462763 14.270451 11.476562 14.306641 C 11.49643 14.358812 12.229498 14.370075 14.998047 14.359375 L 18.492188 14.345703 L 18.507812 13.429688 C 18.520602 12.614656 18.511571 12.507669 18.431641 12.449219 C 18.362852 12.398929 17.80518 12.382812 16.048828 12.382812 L 13.755859 12.382812 L 13.755859 8.4628906 C 13.755859 5.1973033 13.743684 4.534248 13.683594 4.484375 C 13.633385 4.4427 13.28727 4.42762 12.544922 4.4375 z M 25.378906 4.4394531 C 22.464053 4.4288241 21.683401 4.4401775 21.650391 4.4921875 C 21.627421 4.5283694 21.607883 6.7379615 21.607422 9.4023438 C 21.606812 13.115994 21.621502 14.260174 21.669922 14.308594 C 21.718307 14.357024 22.60236 14.369645 25.451172 14.359375 L 29.169922 14.345703 L 29.185547 13.390625 C 29.193347 12.865234 29.193347 12.430328 29.185547 12.423828 C 29.177699 12.417308 27.992162 12.399836 26.552734 12.384766 L 23.935547 12.355469 L 23.935547 11.257812 L 23.935547 10.158203 L 26.291016 10.132812 L 28.646484 10.105469 L 28.662109 9.2714844 C 28.671549 8.7278373 28.655871 8.4195575 28.619141 8.3828125 C 28.581468 8.3451095 27.798367 8.3182962 26.25 8.3007812 L 23.935547 8.2734375 L 23.935547 7.3320312 L 23.935547 6.3886719 L 26.501953 6.3632812 L 29.066406 6.3378906 L 29.066406 5.3945312 L 29.066406 4.453125 L 25.378906 4.4394531 z " + id="path3424" /> + <path + style="fill:#000000;stroke-width:1.06666672" + d="" + id="path819" + inkscape:connector-curvature="0" /> + <path + style="fill:#000000;stroke-width:1.06666672" + d="" + id="path817" + inkscape:connector-curvature="0" /> +</svg> diff --git a/editor/icons/icon_soft_body.svg b/editor/icons/icon_soft_body.svg new file mode 100644 index 0000000000..9930026b61 --- /dev/null +++ b/editor/icons/icon_soft_body.svg @@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg2" + inkscape:version="0.91 r13725" + sodipodi:docname="icon_soft_body.svg"> + <metadata + id="metadata14"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs12" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1920" + inkscape:window-height="1027" + id="namedview10" + showgrid="false" + inkscape:zoom="18.792233" + inkscape:cx="2.8961304" + inkscape:cy="4.3816933" + inkscape:window-x="-8" + inkscape:window-y="-8" + inkscape:window-maximized="1" + inkscape:current-layer="svg2" /> + <path + style="opacity:1;fill:#fc9c9c;fill-opacity:0.99607843;fill-rule:nonzero;stroke:none;stroke-width:1.42799997;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" + d="m 2.3447105,1.6091897 c -0.011911,1.9816766 -1.4168958,3.9344766 0,5.9495986 1.4168957,2.0151221 0,6.6693597 0,6.6693597 l 10.9510055,0 c 0,0 1.780829,-4.4523824 0,-6.489075 -1.780829,-2.0366925 -0.183458,-4.119112 0,-6.1298833 z m 1.8894067,0.7549031 7.4390658,0 c -0.431995,1.5996085 -1.62289,4.0426807 0,5.3749802 1.622888,1.3322996 0,5.887932 0,5.887932 l -7.4390658,0 c 0,0 1.3903413,-4.3680495 0,-5.9780743 -1.3903412,-1.6100247 -0.3951213,-3.7149271 0,-5.2848379 z" + id="rect4142" + inkscape:connector-curvature="0" + sodipodi:nodetypes="czcczcccczcczc" /> +</svg> diff --git a/editor/icons/icon_vulkan.svg b/editor/icons/icon_vulkan.svg new file mode 100644 index 0000000000..1d5fed0305 --- /dev/null +++ b/editor/icons/icon_vulkan.svg @@ -0,0 +1,127 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> + +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + version="1.1" + id="svg2" + width="48" + height="16" + viewBox="0 0 47.999999 16" + sodipodi:docname="icon_vulkan.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata8"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs6" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1853" + inkscape:window-height="1016" + id="namedview4" + showgrid="false" + inkscape:zoom="10.24" + inkscape:cx="9.4970674" + inkscape:cy="11.192118" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="1" + inkscape:current-layer="g8" /> + <path + style="fill:#000000;stroke-width:1.06666672" + d="" + id="path819" + inkscape:connector-curvature="0" /> + <path + style="fill:#000000;stroke-width:1.06666672" + d="" + id="path817" + inkscape:connector-curvature="0" /> + <g + transform="matrix(0.04333868,0,0,0.04333868,-4.0493236,-3.7704963)" + id="g8"> + <path + inkscape:connector-curvature="0" + d="m 724.1,432.41989 h -40.6 c 0,0 0,-99 0,-129.7 13,7.2 30.1,20.5 40.6,33.3 z" + id="path10" + style="fill:#e6555a;fill-opacity:1" /> + <g + id="g12" + style="fill:#e6555a;fill-opacity:1" + transform="translate(0,47.319882)"> + <path + inkscape:connector-curvature="0" + d="m 381.8,385.1 h -50.6 l -66,-204 h 46 l 45.4,143.5 h 0.6 l 46,-143.5 h 46.3 z" + id="path14" + style="fill:#e6555a;fill-opacity:1" /> + <path + inkscape:connector-curvature="0" + d="M 585.5,385.1 H 546.9 V 364.5 H 546 c -5.1,8.6 -11.8,14.8 -20,18.6 -8.2,3.8 -16.6,5.7 -25.1,5.7 -10.9,0 -19.8,-1.4 -26.7,-4.3 -7,-2.9 -12.4,-6.9 -16.4,-12.1 -4,-5.2 -6.8,-11.6 -8.4,-19.1 -1.6,-7.5 -2.4,-15.9 -2.4,-25 v -90.9 h 40.6 v 83.4 c 0,12.2 1.9,21.3 5.7,27.3 3.8,6 10.6,9 20.3,9 11,0 19.1,-3.3 24,-9.9 5,-6.6 7.4,-17.4 7.4,-32.4 v -77.4 h 40.6 v 147.7 z" + id="path16" + style="fill:#e6555a;fill-opacity:1" /> + </g> + <polygon + points="730.8,296.2 730.7,290.5 781.9,237.3 829.9,237.3 774.2,291.6 836.2,385.1 787,385.1 " + id="polygon18" + style="fill:#e6555a;fill-opacity:1" + transform="translate(0,47.319882)" /> + <path + inkscape:connector-curvature="0" + d="m 843.6,330.11989 c 0.6,-9.5 3,-17.4 7.2,-23.7 4.2,-6.3 9.5,-11.3 16,-15.1 6.5,-3.8 13.8,-6.5 21.9,-8.1 8.1,-1.6 16.2,-2.4 24.4,-2.4 7.4,0 15,0.5 22.6,1.6 7.6,1.1 14.6,3.1 20.9,6.1 6.3,3.1 11.4,7.3 15.4,12.7 4,5.4 6,12.6 6,21.6 v 76.9 c 0,6.7 0.4,13.1 1.1,19.1 0.8,6.1 2.1,10.7 4,13.7 h -41.2 c -0.8,-2.3 -1.4,-4.6 -1.9,-7 -0.5,-2.4 -0.8,-4.8 -1,-7.3 -6.5,6.7 -14.1,11.3 -22.9,14 -8.8,2.7 -17.7,4 -26.9,4 -7,0 -13.6,-0.9 -19.7,-2.6 -6.1,-1.7 -11.4,-4.4 -16,-8 -4.6,-3.6 -8.2,-8.2 -10.7,-13.7 -2.6,-5.5 -3.9,-12.1 -3.9,-19.7 0,-8.4 1.5,-15.3 4.4,-20.7 3,-5.4 6.8,-9.8 11.4,-13 4.7,-3.2 10,-5.7 16,-7.3 6,-1.6 12,-2.9 18.1,-3.9 6.1,-0.9 12.1,-1.7 18,-2.3 5.9,-0.6 11.1,-1.4 15.7,-2.6 4.6,-1.1 8.2,-2.8 10.9,-5 2.7,-2.2 3.9,-5.4 3.7,-9.6 0,-4.4 -0.7,-7.9 -2.2,-10.4 -1.4,-2.6 -3.3,-4.6 -5.7,-6 -2.4,-1.4 -5.1,-2.4 -8.3,-2.9 -3.1,-0.5 -6.5,-0.7 -10.1,-0.7 -8,0 -14.3,1.7 -18.9,5.1 -4.6,3.4 -7.2,9.1 -8,17.1 h -40.3 z m 93.8,30 c -1.7,1.5 -3.9,2.7 -6.4,3.6 -2.6,0.9 -5.3,1.6 -8.3,2.2 -2.9,0.6 -6,1 -9.3,1.4 -3.2,0.4 -6.5,0.9 -9.7,1.4 -3,0.6 -6,1.3 -9,2.3 -3,1 -5.5,2.2 -7.7,3.9 -2.2,1.6 -4,3.7 -5.3,6.1 -1.3,2.5 -2,5.6 -2,9.4 0,3.6 0.7,6.7 2,9.1 1.3,2.5 3.1,4.4 5.4,5.9 2.3,1.4 5,2.4 8,3 3.1,0.6 6.2,0.9 9.4,0.9 8,0 14.2,-1.3 18.6,-4 4.4,-2.7 7.6,-5.9 9.7,-9.6 2.1,-3.7 3.4,-7.5 3.9,-11.3 0.5,-3.8 0.7,-6.9 0.7,-9.1 z" + id="path20" + style="fill:#e6555a;fill-opacity:1" /> + <path + inkscape:connector-curvature="0" + d="m 1004.2,284.61989 h 38.6 v 20.6 h 0.9 c 5.1,-8.6 11.8,-14.8 20,-18.7 8.2,-3.9 16.6,-5.9 25.1,-5.9 10.9,0 19.8,1.5 26.7,4.4 7,3 12.4,7.1 16.4,12.3 4,5.2 6.8,11.6 8.4,19.1 1.6,7.5 2.4,15.9 2.4,25 v 90.9 h -40.6 v -83.4 c 0,-12.2 -1.9,-21.3 -5.7,-27.3 -3.8,-6 -10.6,-9 -20.3,-9 -11,0 -19,3.3 -24,9.9 -5,6.6 -7.4,17.4 -7.4,32.4 v 77.4 h -40.6 v -147.7 z" + id="path22" + style="fill:#e6555a;fill-opacity:1" /> + <g + id="g24" + style="fill:#e6555a;fill-opacity:1" + transform="translate(0,47.319882)"> + <path + inkscape:connector-curvature="0" + d="M 612.4,211.8 V 385 H 653 V 234.2 c -13.1,-8 -26.6,-15.5 -40.6,-22.4 z" + id="path26" + style="fill:#e6555a;fill-opacity:1" /> + </g> + <path + inkscape:connector-curvature="0" + d="m 198.4,266.51989 c 23.5,-68.9 164.2,-94.2 314.1,-56.4 90,22.6 163.5,66.5 211.5,109.9 -21.7,-57.6 -127.3,-139.6 -272.8,-167.7 -164.5,-31.8 -326.7,-3.9 -346.8,69.1 -14.5,52.7 49.2,114.5 147.7,156.7 -44.3,-35.8 -65.8,-76 -53.7,-111.6 z" + id="path28" + style="fill:#e6555a;fill-opacity:1" /> + <g + id="g30" + style="fill:#e6555a;fill-opacity:1" + transform="translate(0,47.319882)"> + <path + inkscape:connector-curvature="0" + d="M 724.2,247.6 V 181 h -40.6 v 20.2 c 17.3,15.5 31,31.2 40.6,46.4 z" + id="path32" + style="fill:#e6555a;fill-opacity:1" /> + </g> + </g> +</svg> diff --git a/editor/plugins/particles_editor_plugin.cpp b/editor/plugins/particles_editor_plugin.cpp index e0325702a8..1f5a4a8a36 100644 --- a/editor/plugins/particles_editor_plugin.cpp +++ b/editor/plugins/particles_editor_plugin.cpp @@ -40,7 +40,6 @@ bool ParticlesEditorBase::_generate(PoolVector<Vector3> &points, PoolVector<Vect float area_accum = 0; Map<float, int> triangle_area_map; - print_line("geometry size: " + itos(geometry.size())); for (int i = 0; i < geometry.size(); i++) { @@ -300,6 +299,10 @@ void ParticlesEditor::_menu_option(int p_option) { CPUParticles *cpu_particles = memnew(CPUParticles); cpu_particles->convert_from_particles(node); + cpu_particles->set_name(node->get_name()); + cpu_particles->set_transform(node->get_transform()); + cpu_particles->set_visible(node->is_visible()); + cpu_particles->set_pause_mode(node->get_pause_mode()); undo_redo->create_action("Replace Particles by CPUParticles"); undo_redo->add_do_method(node, "replace_by", cpu_particles); diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp index ffc2203475..2263d782d9 100644 --- a/editor/plugins/script_text_editor.cpp +++ b/editor/plugins/script_text_editor.cpp @@ -116,6 +116,7 @@ void ScriptTextEditor::_load_theme_settings() { Color completion_font_color = EDITOR_GET("text_editor/highlighting/completion_font_color"); Color text_color = EDITOR_GET("text_editor/highlighting/text_color"); Color line_number_color = EDITOR_GET("text_editor/highlighting/line_number_color"); + Color safe_line_number_color = EDITOR_GET("text_editor/highlighting/safe_line_number_color"); Color caret_color = EDITOR_GET("text_editor/highlighting/caret_color"); Color caret_background_color = EDITOR_GET("text_editor/highlighting/caret_background_color"); Color text_selected_color = EDITOR_GET("text_editor/highlighting/text_selected_color"); @@ -147,6 +148,7 @@ void ScriptTextEditor::_load_theme_settings() { text_edit->add_color_override("completion_font_color", completion_font_color); text_edit->add_color_override("font_color", text_color); text_edit->add_color_override("line_number_color", line_number_color); + text_edit->add_color_override("safe_line_number_color", safe_line_number_color); text_edit->add_color_override("caret_color", caret_color); text_edit->add_color_override("caret_background_color", caret_background_color); text_edit->add_color_override("font_selected_color", text_selected_color); @@ -589,6 +591,7 @@ void ScriptTextEditor::set_edited_script(const Ref<Script> &p_script) { emit_signal("name_changed"); code_editor->update_line_and_column(); + call_deferred("_validate_script"); } void ScriptTextEditor::_validate_script() { @@ -599,8 +602,9 @@ void ScriptTextEditor::_validate_script() { String text = te->get_text(); List<String> fnc; + Set<int> safe_lines; - if (!script->get_language()->validate(text, line, col, errortxt, script->get_path(), &fnc)) { + if (!script->get_language()->validate(text, line, col, errortxt, script->get_path(), &fnc, &safe_lines)) { String error_text = "error(" + itos(line) + "," + itos(col) + "): " + errortxt; code_editor->set_error(error_text); } else { @@ -621,8 +625,23 @@ void ScriptTextEditor::_validate_script() { } line--; + bool highlight_safe = EDITOR_DEF("text_editor/highlighting/highlight_type_safe_lines", true); + bool last_is_safe = false; for (int i = 0; i < te->get_line_count(); i++) { te->set_line_as_marked(i, line == i); + if (highlight_safe) { + if (safe_lines.has(i + 1)) { + te->set_line_as_safe(i, true); + last_is_safe = true; + } else if (last_is_safe && (te->is_line_comment(i) || te->get_line(i).strip_edges().empty())) { + te->set_line_as_safe(i, true); + } else { + te->set_line_as_safe(i, false); + last_is_safe = false; + } + } else { + te->set_line_as_safe(i, false); + } } emit_signal("name_changed"); diff --git a/editor/plugins/spatial_editor_plugin.h b/editor/plugins/spatial_editor_plugin.h index 637926a913..af882f6e05 100644 --- a/editor/plugins/spatial_editor_plugin.h +++ b/editor/plugins/spatial_editor_plugin.h @@ -60,6 +60,7 @@ public: virtual Variant get_handle_value(int p_idx) const; virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point); virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false); + virtual bool is_gizmo_handle_highlighted(int idx) const { return false; } virtual bool intersect_frustum(const Camera *p_camera, const Vector<Plane> &p_frustum); virtual bool intersect_ray(Camera *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle = NULL, bool p_sec_first = false); diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp index 682ca744ff..b9b8b07a2e 100644 --- a/editor/plugins/visual_shader_editor_plugin.cpp +++ b/editor/plugins/visual_shader_editor_plugin.cpp @@ -735,7 +735,7 @@ VisualShaderEditor::VisualShaderEditor() { graph->connect("duplicate_nodes_request", this, "_duplicate_nodes"); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_VECTOR); - //graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_SCALAR); + graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_SCALAR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_VECTOR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShaderNode::PORT_TYPE_TRANSFORM); diff --git a/editor/project_settings_editor.cpp b/editor/project_settings_editor.cpp index 7e4e589bb4..e6ae2d64e7 100644 --- a/editor/project_settings_editor.cpp +++ b/editor/project_settings_editor.cpp @@ -106,6 +106,12 @@ void ProjectSettingsEditor::_notification(int p_what) { translation_res_file_open->add_filter("*." + E->get()); translation_res_option_file_open->add_filter("*." + E->get()); } + + restart_close_button->set_icon(get_icon("Close", "EditorIcons")); + restart_container->add_style_override("panel", get_stylebox("bg", "Tree")); + restart_icon->set_texture(get_icon("StatusWarning", "EditorIcons")); + restart_label->add_color_override("font_color", get_color("error_color", "Editor")); + } break; case NOTIFICATION_POPUP_HIDE: { EditorSettings::get_singleton()->set("interface/dialogs/project_settings_bounds", get_rect()); @@ -800,15 +806,13 @@ void ProjectSettingsEditor::popup_project_settings() { plugin_settings->update_plugins(); } -void ProjectSettingsEditor::_item_selected() { +void ProjectSettingsEditor::_item_selected(const String &p_path) { - TreeItem *ti = globals_editor->get_property_editor()->get_property_tree()->get_selected(); - if (!ti) - return; - if (!ti->get_parent()) + String selected_path = p_path; + if (selected_path == String()) return; category->set_text(globals_editor->get_current_section()); - property->set_text(ti->get_text(0)); + property->set_text(selected_path); popup_copy_to_feature->set_disabled(false); } @@ -865,7 +869,7 @@ void ProjectSettingsEditor::_item_add() { void ProjectSettingsEditor::_item_del() { - String path = globals_editor->get_property_editor()->get_selected_path(); + String path = globals_editor->get_inspector()->get_selected_path(); if (path == String()) { EditorNode::get_singleton()->show_warning(TTR("Select a setting item first!")); return; @@ -1043,7 +1047,7 @@ void ProjectSettingsEditor::_copy_to_platform_about_to_show() { void ProjectSettingsEditor::_copy_to_platform(int p_which) { - String path = globals_editor->get_property_editor()->get_selected_path(); + String path = globals_editor->get_inspector()->get_selected_path(); if (path == String()) { EditorNode::get_singleton()->show_warning(TTR("Select a setting item first!")); return; @@ -1572,7 +1576,7 @@ void ProjectSettingsEditor::_update_translations() { void ProjectSettingsEditor::_toggle_search_bar(bool p_pressed) { - globals_editor->get_property_editor()->set_use_filter(p_pressed); + globals_editor->get_inspector()->set_use_filter(p_pressed); if (p_pressed) { @@ -1593,7 +1597,7 @@ void ProjectSettingsEditor::_clear_search_box() { return; search_box->clear(); - globals_editor->get_property_editor()->update_tree(); + globals_editor->get_inspector()->update_tree(); } void ProjectSettingsEditor::set_plugins_page() { @@ -1606,6 +1610,18 @@ TabContainer *ProjectSettingsEditor::get_tabs() { return tab_container; } +void ProjectSettingsEditor::_editor_restart() { + EditorNode::get_singleton()->save_all_scenes_and_restart(); +} + +void ProjectSettingsEditor::_editor_restart_request() { + restart_container->show(); +} + +void ProjectSettingsEditor::_editor_restart_close() { + restart_container->hide(); +} + void ProjectSettingsEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_item_selected"), &ProjectSettingsEditor::_item_selected); @@ -1651,6 +1667,10 @@ void ProjectSettingsEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_copy_to_platform_about_to_show"), &ProjectSettingsEditor::_copy_to_platform_about_to_show); + ClassDB::bind_method(D_METHOD("_editor_restart_request"), &ProjectSettingsEditor::_editor_restart_request); + ClassDB::bind_method(D_METHOD("_editor_restart"), &ProjectSettingsEditor::_editor_restart); + ClassDB::bind_method(D_METHOD("_editor_restart_close"), &ProjectSettingsEditor::_editor_restart_close); + ClassDB::bind_method(D_METHOD("get_tabs"), &ProjectSettingsEditor::get_tabs); } @@ -1737,16 +1757,17 @@ ProjectSettingsEditor::ProjectSettingsEditor(EditorData *p_data) { search_bar->add_child(clear_button); clear_button->connect("pressed", this, "_clear_search_box"); - globals_editor = memnew(SectionedPropertyEditor); + globals_editor = memnew(SectionedInspector); props_base->add_child(globals_editor); - globals_editor->get_property_editor()->set_undo_redo(EditorNode::get_singleton()->get_undo_redo()); - globals_editor->get_property_editor()->set_property_selectable(true); + globals_editor->get_inspector()->set_undo_redo(EditorNode::get_singleton()->get_undo_redo()); + globals_editor->get_inspector()->set_property_selectable(true); //globals_editor->hide_top_label(); globals_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); globals_editor->register_search_box(search_box); - globals_editor->get_property_editor()->get_property_tree()->connect("cell_selected", this, "_item_selected"); - globals_editor->get_property_editor()->connect("property_toggled", this, "_item_checked", varray(), CONNECT_DEFERRED); - globals_editor->get_property_editor()->connect("property_edited", this, "_settings_prop_edited"); + globals_editor->get_inspector()->connect("property_selected", this, "_item_selected"); + //globals_editor->get_inspector()->connect("property_toggled", this, "_item_checked", varray(), CONNECT_DEFERRED); + globals_editor->get_inspector()->connect("property_edited", this, "_settings_prop_edited"); + globals_editor->get_inspector()->connect("restart_requested", this, "_editor_restart_request"); Button *del = memnew(Button); hbc->add_child(del); @@ -1766,6 +1787,26 @@ ProjectSettingsEditor::ProjectSettingsEditor(EditorData *p_data) { get_ok()->set_text(TTR("Close")); set_hide_on_ok(true); + restart_container = memnew(PanelContainer); + props_base->add_child(restart_container); + HBoxContainer *restart_hb = memnew(HBoxContainer); + restart_container->add_child(restart_hb); + restart_icon = memnew(TextureRect); + restart_icon->set_v_size_flags(SIZE_SHRINK_CENTER); + restart_hb->add_child(restart_icon); + restart_label = memnew(Label); + restart_label->set_text(TTR("Editor must be restarted for changes to take effect")); + restart_hb->add_child(restart_label); + restart_hb->add_spacer(); + Button *restart_button = memnew(Button); + restart_button->connect("pressed", this, "_editor_restart"); + restart_hb->add_child(restart_button); + restart_button->set_text(TTR("Save & Restart")); + restart_close_button = memnew(ToolButton); + restart_close_button->connect("pressed", this, "_editor_restart_close"); + restart_hb->add_child(restart_close_button); + restart_container->hide(); + message = memnew(AcceptDialog); add_child(message); diff --git a/editor/project_settings_editor.h b/editor/project_settings_editor.h index 0ced88d7f6..3b74ae1909 100644 --- a/editor/project_settings_editor.h +++ b/editor/project_settings_editor.h @@ -35,7 +35,7 @@ #include "editor/editor_autoload_settings.h" #include "editor/editor_data.h" #include "editor/editor_plugin_settings.h" -#include "editor/property_editor.h" +#include "editor/editor_sectioned_inspector.h" #include "scene/gui/dialogs.h" #include "scene/gui/tab_container.h" @@ -64,7 +64,7 @@ class ProjectSettingsEditor : public AcceptDialog { EditorData *data; UndoRedo *undo_redo; - SectionedPropertyEditor *globals_editor; + SectionedInspector *globals_editor; HBoxContainer *search_bar; Button *search_button; @@ -112,7 +112,7 @@ class ProjectSettingsEditor : public AcceptDialog { EditorPluginSettings *plugin_settings; - void _item_selected(); + void _item_selected(const String &); void _item_adds(String); void _item_add(); void _item_del(); @@ -166,6 +166,15 @@ class ProjectSettingsEditor : public AcceptDialog { static ProjectSettingsEditor *singleton; + Label *restart_label; + TextureRect *restart_icon; + PanelContainer *restart_container; + ToolButton *restart_close_button; + + void _editor_restart_request(); + void _editor_restart(); + void _editor_restart_close(); + protected: void _notification(int p_what); static void _bind_methods(); diff --git a/editor/script_editor_debugger.cpp b/editor/script_editor_debugger.cpp index 62848a6035..9ce0e973f7 100644 --- a/editor/script_editor_debugger.cpp +++ b/editor/script_editor_debugger.cpp @@ -1249,6 +1249,9 @@ void ScriptEditorDebugger::stop() { EditorNode::get_singleton()->get_scene_tree_dock()->hide_remote_tree(); EditorNode::get_singleton()->get_scene_tree_dock()->hide_tab_buttons(); + Node *node = editor->get_scene_tree_dock()->get_tree_editor()->get_selected(); + editor->push_item(node); + if (hide_on_stop) { if (is_visible_in_tree()) EditorNode::get_singleton()->hide_bottom_panel(); diff --git a/editor/settings_config_dialog.cpp b/editor/settings_config_dialog.cpp index ae88b3a035..fe379703e5 100644 --- a/editor/settings_config_dialog.cpp +++ b/editor/settings_config_dialog.cpp @@ -54,12 +54,12 @@ void EditorSettingsDialog::_settings_changed() { void EditorSettingsDialog::_settings_property_edited(const String &p_name) { - String full_name = property_editor->get_full_item_path(p_name); + String full_name = inspector->get_full_item_path(p_name); // Small usability workaround to update the text color settings when the // color theme is changed if (full_name == "text_editor/theme/color_theme") { - property_editor->get_property_editor()->update_tree(); + inspector->get_inspector()->update_tree(); } else if (full_name == "interface/theme/accent_color" || full_name == "interface/theme/base_color" || full_name == "interface/theme/contrast") { EditorSettings::get_singleton()->set_manually("interface/theme/preset", "Custom"); // set preset to Custom } else if (full_name.begins_with("text_editor/highlighting")) { @@ -88,8 +88,8 @@ void EditorSettingsDialog::popup_edit_settings() { EditorSettings::get_singleton()->list_text_editor_themes(); // make sure we have an up to date list of themes - property_editor->edit(EditorSettings::get_singleton()); - property_editor->get_property_editor()->update_tree(); + inspector->edit(EditorSettings::get_singleton()); + inspector->get_inspector()->update_tree(); search_box->select_all(); search_box->grab_focus(); @@ -120,7 +120,7 @@ void EditorSettingsDialog::_clear_search_box() { return; search_box->clear(); - property_editor->get_property_editor()->update_tree(); + inspector->get_inspector()->update_tree(); } void EditorSettingsDialog::_clear_shortcut_search_box() { @@ -158,7 +158,7 @@ void EditorSettingsDialog::_notification(int p_what) { case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { _update_icons(); // Update theme colors. - property_editor->update_category_list(); + inspector->update_category_list(); _update_shortcuts(); } break; } @@ -202,6 +202,11 @@ void EditorSettingsDialog::_update_icons() { shortcut_search_box->add_icon_override("right_icon", get_icon("Search", "EditorIcons")); clear_button->set_icon(get_icon("Close", "EditorIcons")); shortcut_clear_button->set_icon(get_icon("Close", "EditorIcons")); + + restart_close_button->set_icon(get_icon("Close", "EditorIcons")); + restart_container->add_style_override("panel", get_stylebox("bg", "Tree")); + restart_icon->set_texture(get_icon("StatusWarning", "EditorIcons")); + restart_label->add_color_override("font_color", get_color("error_color", "Editor")); } void EditorSettingsDialog::_update_shortcuts() { @@ -388,6 +393,18 @@ void EditorSettingsDialog::_focus_current_search_box() { } } +void EditorSettingsDialog::_editor_restart() { + EditorNode::get_singleton()->save_all_scenes_and_restart(); +} + +void EditorSettingsDialog::_editor_restart_request() { + restart_container->show(); +} + +void EditorSettingsDialog::_editor_restart_close() { + restart_container->hide(); +} + void EditorSettingsDialog::_bind_methods() { ClassDB::bind_method(D_METHOD("_unhandled_input"), &EditorSettingsDialog::_unhandled_input); @@ -402,6 +419,10 @@ void EditorSettingsDialog::_bind_methods() { ClassDB::bind_method(D_METHOD("_press_a_key_confirm"), &EditorSettingsDialog::_press_a_key_confirm); ClassDB::bind_method(D_METHOD("_wait_for_key"), &EditorSettingsDialog::_wait_for_key); ClassDB::bind_method(D_METHOD("_tabs_tab_changed"), &EditorSettingsDialog::_tabs_tab_changed); + + ClassDB::bind_method(D_METHOD("_editor_restart_request"), &EditorSettingsDialog::_editor_restart_request); + ClassDB::bind_method(D_METHOD("_editor_restart"), &EditorSettingsDialog::_editor_restart); + ClassDB::bind_method(D_METHOD("_editor_restart_close"), &EditorSettingsDialog::_editor_restart_close); } EditorSettingsDialog::EditorSettingsDialog() { @@ -434,14 +455,35 @@ EditorSettingsDialog::EditorSettingsDialog() { hbc->add_child(clear_button); clear_button->connect("pressed", this, "_clear_search_box"); - property_editor = memnew(SectionedPropertyEditor); - //property_editor->hide_top_label(); - property_editor->get_property_editor()->set_use_filter(true); - property_editor->register_search_box(search_box); - property_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); - property_editor->get_property_editor()->set_undo_redo(undo_redo); - tab_general->add_child(property_editor); - property_editor->get_property_editor()->connect("property_edited", this, "_settings_property_edited"); + inspector = memnew(SectionedInspector); + //inspector->hide_top_label(); + inspector->get_inspector()->set_use_filter(true); + inspector->register_search_box(search_box); + inspector->set_v_size_flags(Control::SIZE_EXPAND_FILL); + inspector->get_inspector()->set_undo_redo(undo_redo); + tab_general->add_child(inspector); + inspector->get_inspector()->connect("property_edited", this, "_settings_property_edited"); + inspector->get_inspector()->connect("restart_requested", this, "_editor_restart_request"); + + restart_container = memnew(PanelContainer); + tab_general->add_child(restart_container); + HBoxContainer *restart_hb = memnew(HBoxContainer); + restart_container->add_child(restart_hb); + restart_icon = memnew(TextureRect); + restart_icon->set_v_size_flags(SIZE_SHRINK_CENTER); + restart_hb->add_child(restart_icon); + restart_label = memnew(Label); + restart_label->set_text(TTR("Editor must be restarted for changes to take effect")); + restart_hb->add_child(restart_label); + restart_hb->add_spacer(); + Button *restart_button = memnew(Button); + restart_button->connect("pressed", this, "_editor_restart"); + restart_hb->add_child(restart_button); + restart_button->set_text(TTR("Save & Restart")); + restart_close_button = memnew(ToolButton); + restart_close_button->connect("pressed", this, "_editor_restart_close"); + restart_hb->add_child(restart_close_button); + restart_container->hide(); // Shortcuts Tab diff --git a/editor/settings_config_dialog.h b/editor/settings_config_dialog.h index 6676e870d0..6cf2eb6bdf 100644 --- a/editor/settings_config_dialog.h +++ b/editor/settings_config_dialog.h @@ -31,9 +31,14 @@ #ifndef SETTINGS_CONFIG_DIALOG_H #define SETTINGS_CONFIG_DIALOG_H -#include "property_editor.h" +#include "editor/editor_sectioned_inspector.h" +#include "editor_inspector.h" +#include "scene/gui/dialogs.h" +#include "scene/gui/panel_container.h" #include "scene/gui/rich_text_label.h" #include "scene/gui/tab_container.h" +#include "scene/gui/texture_rect.h" +#include "scene/gui/tool_button.h" class EditorSettingsDialog : public AcceptDialog { @@ -49,7 +54,7 @@ class EditorSettingsDialog : public AcceptDialog { LineEdit *shortcut_search_box; ToolButton *clear_button; ToolButton *shortcut_clear_button; - SectionedPropertyEditor *property_editor; + SectionedInspector *inspector; Timer *timer; @@ -89,6 +94,15 @@ class EditorSettingsDialog : public AcceptDialog { static void _undo_redo_callback(void *p_self, const String &p_name); + Label *restart_label; + TextureRect *restart_icon; + PanelContainer *restart_container; + ToolButton *restart_close_button; + + void _editor_restart_request(); + void _editor_restart(); + void _editor_restart_close(); + protected: static void _bind_methods(); diff --git a/editor/spatial_editor_gizmos.cpp b/editor/spatial_editor_gizmos.cpp index c45dea0df7..35544f711b 100644 --- a/editor/spatial_editor_gizmos.cpp +++ b/editor/spatial_editor_gizmos.cpp @@ -33,6 +33,7 @@ #include "geometry.h" #include "quick_hull.h" #include "scene/3d/camera.h" +#include "scene/3d/soft_body.h" #include "scene/resources/box_shape.h" #include "scene/resources/capsule_shape.h" #include "scene/resources/convex_polygon_shape.h" @@ -256,8 +257,12 @@ void EditorSpatialGizmo::add_handles(const Vector<Vector3> &p_handles, bool p_bi for (int i = 0; i < p_handles.size(); i++) { Color col(1, 1, 1, 1); + if (is_gizmo_handle_highlighted(i)) + col = Color(0, 0, 1, 0.9); + if (SpatialEditor::get_singleton()->get_over_gizmo_handle() != i) - col = Color(0.9, 0.9, 0.9, 0.9); + col.a = 0.8; + w[i] = col; } } @@ -1914,6 +1919,100 @@ VehicleWheelSpatialGizmo::VehicleWheelSpatialGizmo(VehicleWheel *p_car_wheel) { /////////// +void SoftBodySpatialGizmo::redraw() { + clear(); + + if (!soft_body || soft_body->get_mesh().is_null()) { + return; + } + + // find mesh + + Vector<Vector3> lines; + + soft_body->get_mesh()->generate_debug_mesh_lines(lines); + + if (!lines.size()) { + return; + } + + Vector<Vector3> points; + soft_body->get_mesh()->generate_debug_mesh_indices(points); + + soft_body->get_mesh()->clear_cache(); + + Color gizmo_color = EDITOR_GET("editors/3d_gizmos/gizmo_colors/shape"); + Ref<Material> material = create_material("shape_material", gizmo_color); + + add_lines(lines, material); + add_collision_segments(lines); + add_handles(points); +} + +bool SoftBodySpatialGizmo::intersect_ray(Camera *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle, bool p_sec_first) { + return EditorSpatialGizmo::intersect_ray(p_camera, p_point, r_pos, r_normal, r_gizmo_handle, p_sec_first); + + /* Perform a shape cast but doesn't work with softbody + PhysicsDirectSpaceState *space_state = PhysicsServer::get_singleton()->space_get_direct_state(SceneTree::get_singleton()->get_root()->get_world()->get_space()); + if (!physics_sphere_shape.is_valid()) { + physics_sphere_shape = PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_SPHERE); + real_t radius = 0.02; + PhysicsServer::get_singleton()->shape_set_data(physics_sphere_shape, radius); + } + + Vector3 sphere_motion(p_camera->project_ray_normal(p_point)); + real_t closest_safe; + real_t closest_unsafe; + PhysicsDirectSpaceState::ShapeRestInfo result; + bool collided = space_state->cast_motion( + physics_sphere_shape, + p_camera->get_transform(), + sphere_motion * Vector3(1000, 1000, 1000), + 0.f, + closest_safe, + closest_unsafe, + Set<RID>(), + 0xFFFFFFFF, + 0xFFFFFFFF, + &result); + + if (collided) { + + if (result.collider_id == soft_body->get_instance_id()) { + print_line("Collided"); + } else { + print_line("Collided but with wrong object: " + itos(result.collider_id)); + } + } else { + print_line("Not collided, motion: x: " + rtos(sphere_motion[0]) + " y: " + rtos(sphere_motion[1]) + " z: " + rtos(sphere_motion[2])); + } + return false; + */ +} + +void SoftBodySpatialGizmo::commit_handle(int p_idx, const Variant &p_restore, bool p_cancel) { + soft_body->pin_point_toggle(p_idx); + redraw(); +} + +bool SoftBodySpatialGizmo::is_gizmo_handle_highlighted(int idx) const { + return soft_body->is_point_pinned(idx); +} + +SoftBodySpatialGizmo::SoftBodySpatialGizmo(SoftBody *p_soft_physics_body) : + EditorSpatialGizmo(), + soft_body(p_soft_physics_body) { + set_spatial_node(p_soft_physics_body); +} + +SoftBodySpatialGizmo::~SoftBodySpatialGizmo() { + //if (!physics_sphere_shape.is_valid()) { + // PhysicsServer::get_singleton()->free(physics_sphere_shape); + //} +} + +/////////// + String CollisionShapeSpatialGizmo::get_handle_name(int p_idx) const { Ref<Shape> s = cs->get_shape(); @@ -4051,6 +4150,12 @@ Ref<SpatialEditorGizmo> SpatialEditorGizmos::get_gizmo(Spatial *p_spatial) { return lsg; } + if (Object::cast_to<SoftBody>(p_spatial)) { + + Ref<SoftBodySpatialGizmo> misg = memnew(SoftBodySpatialGizmo(Object::cast_to<SoftBody>(p_spatial))); + return misg; + } + if (Object::cast_to<MeshInstance>(p_spatial)) { Ref<MeshInstanceSpatialGizmo> misg = memnew(MeshInstanceSpatialGizmo(Object::cast_to<MeshInstance>(p_spatial))); @@ -4081,6 +4186,7 @@ Ref<SpatialEditorGizmo> SpatialEditorGizmos::get_gizmo(Spatial *p_spatial) { return misg; } */ + if (Object::cast_to<CollisionShape>(p_spatial)) { Ref<CollisionShapeSpatialGizmo> misg = memnew(CollisionShapeSpatialGizmo(Object::cast_to<CollisionShape>(p_spatial))); diff --git a/editor/spatial_editor_gizmos.h b/editor/spatial_editor_gizmos.h index 924f82dc16..198d028516 100644 --- a/editor/spatial_editor_gizmos.h +++ b/editor/spatial_editor_gizmos.h @@ -331,6 +331,23 @@ public: BakedIndirectLightGizmo(BakedLightmap *p_baker = NULL); }; +class SoftBodySpatialGizmo : public EditorSpatialGizmo { + GDCLASS(SoftBodySpatialGizmo, EditorSpatialGizmo); + + class SoftBody *soft_body; + //RID physics_sphere_shape; // Used for raycast that doesn't work, in this moment, with softbody + +public: + void redraw(); + virtual bool intersect_ray(Camera *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle = NULL, bool p_sec_first = false); + virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel); + + virtual bool is_gizmo_handle_highlighted(int idx) const; + + SoftBodySpatialGizmo(SoftBody *p_soft_physics_body = NULL); + ~SoftBodySpatialGizmo(); +}; + class CollisionShapeSpatialGizmo : public EditorSpatialGizmo { GDCLASS(CollisionShapeSpatialGizmo, EditorSpatialGizmo); diff --git a/main/main.cpp b/main/main.cpp index 23f2776737..56dd5f73e7 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -825,7 +825,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph OS::get_singleton()->set_cmdline(execpath, main_args); GLOBAL_DEF("rendering/quality/driver/driver_name", "GLES3"); - ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/driver/driver_name", PropertyInfo(Variant::STRING, "rendering/quality/driver/driver_name", PROPERTY_HINT_ENUM, "GLES3,GLES2")); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/driver/driver_name", PropertyInfo(Variant::STRING, "rendering/quality/driver/driver_name", PROPERTY_HINT_ENUM, "GLES2,GLES3")); if (video_driver == "") { video_driver = GLOBAL_GET("rendering/quality/driver/driver_name"); } @@ -914,7 +914,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph } if (audio_driver == "") { // specified in project.godot - audio_driver = GLOBAL_DEF("audio/driver", OS::get_singleton()->get_audio_driver_name(0)); + audio_driver = GLOBAL_DEF_RST("audio/driver", OS::get_singleton()->get_audio_driver_name(0)); } for (int i = 0; i < OS::get_singleton()->get_audio_driver_count(); i++) { @@ -1957,6 +1957,15 @@ void Main::cleanup() { if (engine) memdelete(engine); + if (OS::get_singleton()->is_restart_on_exit_set()) { + //attempt to restart with arguments + String exec = OS::get_singleton()->get_executable_path(); + List<String> args = OS::get_singleton()->get_restart_on_exit_arguments(); + OS::ProcessID pid = 0; + OS::get_singleton()->execute(exec, args, false, &pid); + OS::get_singleton()->set_restart_on_exit(false, List<String>()); //clear list (uses memory) + } + unregister_core_driver_types(); unregister_core_types(); diff --git a/main/tests/test_gdscript.cpp b/main/tests/test_gdscript.cpp index 5c7633a0cf..5f3a2c1dc8 100644 --- a/main/tests/test_gdscript.cpp +++ b/main/tests/test_gdscript.cpp @@ -193,14 +193,6 @@ static String _parser_expr(const GDScriptParser::Node *p_expr) { case GDScriptParser::OperatorNode::OP_BIT_INVERT: { txt = "~" + _parser_expr(c_node->arguments[0]); } break; - case GDScriptParser::OperatorNode::OP_PREINC: { - } break; - case GDScriptParser::OperatorNode::OP_PREDEC: { - } break; - case GDScriptParser::OperatorNode::OP_INC: { - } break; - case GDScriptParser::OperatorNode::OP_DEC: { - } break; case GDScriptParser::OperatorNode::OP_IN: { txt = _parser_expr(c_node->arguments[0]) + " in " + _parser_expr(c_node->arguments[1]); } break; @@ -455,10 +447,9 @@ static void _parser_show_class(const GDScriptParser::ClassNode *p_class, int p_i print_line("\n"); } - for (int i = 0; i < p_class->constant_expressions.size(); i++) { - - const GDScriptParser::ClassNode::Constant &constant = p_class->constant_expressions[i]; - _print_indent(p_indent, "const " + String(constant.identifier) + "=" + _parser_expr(constant.expression)); + for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) { + const GDScriptParser::ClassNode::Constant &constant = E->get(); + _print_indent(p_indent, "const " + String(E->key()) + "=" + _parser_expr(constant.expression)); } for (int i = 0; i < p_class->variables.size(); i++) { diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp index 54431f93f1..2390c71b0a 100644 --- a/modules/bullet/bullet_physics_server.cpp +++ b/modules/bullet/bullet_physics_server.cpp @@ -169,7 +169,7 @@ real_t BulletPhysicsServer::shape_get_custom_solver_bias(RID p_shape) const { } RID BulletPhysicsServer::space_create() { - SpaceBullet *space = bulletnew(SpaceBullet(false)); + SpaceBullet *space = bulletnew(SpaceBullet); CreateThenReturnRID(space_owner, space); } @@ -567,9 +567,6 @@ void BulletPhysicsServer::body_clear_shapes(RID p_body) { void BulletPhysicsServer::body_attach_object_instance_id(RID p_body, uint32_t p_ID) { CollisionObjectBullet *body = get_collisin_object(p_body); - if (!body) { - body = soft_body_owner.get(p_body); - } ERR_FAIL_COND(!body); body->set_instance_id(p_ID); @@ -647,6 +644,20 @@ float BulletPhysicsServer::body_get_param(RID p_body, BodyParameter p_param) con return body->get_param(p_param); } +void BulletPhysicsServer::body_set_combine_mode(RID p_body, BodyParameter p_param, CombineMode p_mode) { + RigidBodyBullet *body = rigid_body_owner.get(p_body); + ERR_FAIL_COND(!body); + + body->set_combine_mode(p_param, p_mode); +} + +PhysicsServer::CombineMode BulletPhysicsServer::body_get_combine_mode(RID p_body, BodyParameter p_param) const { + RigidBodyBullet *body = rigid_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, COMBINE_MODE_INHERIT); + + return body->get_combine_mode(p_param); +} + void BulletPhysicsServer::body_set_kinematic_safe_margin(RID p_body, real_t p_margin) { RigidBodyBullet *body = rigid_body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -853,6 +864,13 @@ RID BulletPhysicsServer::soft_body_create(bool p_init_sleeping) { CreateThenReturnRID(soft_body_owner, body); } +void BulletPhysicsServer::soft_body_update_visual_server(RID p_body, class SoftBodyVisualServerHandler *p_visual_server_handler) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + + body->update_visual_server(p_visual_server_handler); +} + void BulletPhysicsServer::soft_body_set_space(RID p_body, RID p_space) { SoftBodyBullet *body = soft_body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -879,11 +897,11 @@ RID BulletPhysicsServer::soft_body_get_space(RID p_body) const { return space->get_self(); } -void BulletPhysicsServer::soft_body_set_trimesh_body_shape(RID p_body, PoolVector<int> p_indices, PoolVector<Vector3> p_vertices, int p_triangles_num) { +void BulletPhysicsServer::soft_body_set_mesh(RID p_body, const REF &p_mesh) { SoftBodyBullet *body = soft_body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_trimesh_body_shape(p_indices, p_vertices, p_triangles_num); + body->set_soft_mesh(p_mesh); } void BulletPhysicsServer::soft_body_set_collision_layer(RID p_body, uint32_t p_layer) { @@ -961,14 +979,16 @@ void BulletPhysicsServer::soft_body_set_transform(RID p_body, const Transform &p SoftBodyBullet *body = soft_body_owner.get(p_body); ERR_FAIL_COND(!body); - body->set_transform(p_transform); + body->set_soft_transform(p_transform); } -Transform BulletPhysicsServer::soft_body_get_transform(RID p_body) const { +Vector3 BulletPhysicsServer::soft_body_get_vertex_position(RID p_body, int vertex_index) const { const SoftBodyBullet *body = soft_body_owner.get(p_body); - ERR_FAIL_COND_V(!body, Transform()); + Vector3 pos; + ERR_FAIL_COND_V(!body, pos); - return body->get_transform(); + body->get_node_position(vertex_index, pos); + return pos; } void BulletPhysicsServer::soft_body_set_ray_pickable(RID p_body, bool p_enable) { @@ -983,6 +1003,154 @@ bool BulletPhysicsServer::soft_body_is_ray_pickable(RID p_body) const { return body->is_ray_pickable(); } +void BulletPhysicsServer::soft_body_set_simulation_precision(RID p_body, int p_simulation_precision) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_simulation_precision(p_simulation_precision); +} + +int BulletPhysicsServer::soft_body_get_simulation_precision(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_simulation_precision(); +} + +void BulletPhysicsServer::soft_body_set_total_mass(RID p_body, real_t p_total_mass) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_total_mass(p_total_mass); +} + +real_t BulletPhysicsServer::soft_body_get_total_mass(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_total_mass(); +} + +void BulletPhysicsServer::soft_body_set_linear_stiffness(RID p_body, real_t p_stiffness) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_linear_stiffness(p_stiffness); +} + +real_t BulletPhysicsServer::soft_body_get_linear_stiffness(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_linear_stiffness(); +} + +void BulletPhysicsServer::soft_body_set_areaAngular_stiffness(RID p_body, real_t p_stiffness) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_areaAngular_stiffness(p_stiffness); +} + +real_t BulletPhysicsServer::soft_body_get_areaAngular_stiffness(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_areaAngular_stiffness(); +} + +void BulletPhysicsServer::soft_body_set_volume_stiffness(RID p_body, real_t p_stiffness) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_volume_stiffness(p_stiffness); +} + +real_t BulletPhysicsServer::soft_body_get_volume_stiffness(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_volume_stiffness(); +} + +void BulletPhysicsServer::soft_body_set_pressure_coefficient(RID p_body, real_t p_pressure_coefficient) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_pressure_coefficient(p_pressure_coefficient); +} + +real_t BulletPhysicsServer::soft_body_get_pressure_coefficient(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_pressure_coefficient(); +} + +void BulletPhysicsServer::soft_body_set_pose_matching_coefficient(RID p_body, real_t p_pose_matching_coefficient) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + return body->set_pose_matching_coefficient(p_pose_matching_coefficient); +} + +real_t BulletPhysicsServer::soft_body_get_pose_matching_coefficient(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_pose_matching_coefficient(); +} + +void BulletPhysicsServer::soft_body_set_damping_coefficient(RID p_body, real_t p_damping_coefficient) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_damping_coefficient(p_damping_coefficient); +} + +real_t BulletPhysicsServer::soft_body_get_damping_coefficient(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_damping_coefficient(); +} + +void BulletPhysicsServer::soft_body_set_drag_coefficient(RID p_body, real_t p_drag_coefficient) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_drag_coefficient(p_drag_coefficient); +} + +real_t BulletPhysicsServer::soft_body_get_drag_coefficient(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_drag_coefficient(); +} + +void BulletPhysicsServer::soft_body_move_point(RID p_body, int p_point_index, const Vector3 &p_global_position) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_node_position(p_point_index, p_global_position); +} + +Vector3 BulletPhysicsServer::soft_body_get_point_global_position(RID p_body, int p_point_index) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, Vector3(0., 0., 0.)); + Vector3 pos; + body->get_node_position(p_point_index, pos); + return pos; +} + +Vector3 BulletPhysicsServer::soft_body_get_point_offset(RID p_body, int p_point_index) const { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, Vector3()); + Vector3 res; + body->get_node_offset(p_point_index, res); + return res; +} + +void BulletPhysicsServer::soft_body_remove_all_pinned_points(RID p_body) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->reset_all_node_mass(); +} + +void BulletPhysicsServer::soft_body_pin_point(RID p_body, int p_point_index, bool p_pin) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND(!body); + body->set_node_mass(p_point_index, p_pin ? 0 : 1); +} + +bool BulletPhysicsServer::soft_body_is_point_pinned(RID p_body, int p_point_index) { + SoftBodyBullet *body = soft_body_owner.get(p_body); + ERR_FAIL_COND_V(!body, 0.f); + return body->get_node_mass(p_point_index); +} + PhysicsServer::JointType BulletPhysicsServer::joint_get_type(RID p_joint) const { JointBullet *joint = joint_owner.get(p_joint); ERR_FAIL_COND_V(!joint, JOINT_PIN); diff --git a/modules/bullet/bullet_physics_server.h b/modules/bullet/bullet_physics_server.h index e931915bba..2165845529 100644 --- a/modules/bullet/bullet_physics_server.h +++ b/modules/bullet/bullet_physics_server.h @@ -213,6 +213,9 @@ public: virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value); virtual float body_get_param(RID p_body, BodyParameter p_param) const; + virtual void body_set_combine_mode(RID p_body, BodyParameter p_param, CombineMode p_mode); + virtual CombineMode body_get_combine_mode(RID p_body, BodyParameter p_param) const; + virtual void body_set_kinematic_safe_margin(RID p_body, real_t p_margin); virtual real_t body_get_kinematic_safe_margin(RID p_body) const; @@ -259,10 +262,12 @@ public: virtual RID soft_body_create(bool p_init_sleeping = false); + virtual void soft_body_update_visual_server(RID p_body, class SoftBodyVisualServerHandler *p_visual_server_handler); + virtual void soft_body_set_space(RID p_body, RID p_space); virtual RID soft_body_get_space(RID p_body) const; - virtual void soft_body_set_trimesh_body_shape(RID p_body, PoolVector<int> p_indices, PoolVector<Vector3> p_vertices, int p_triangles_num); + virtual void soft_body_set_mesh(RID p_body, const REF &p_mesh); virtual void soft_body_set_collision_layer(RID p_body, uint32_t p_layer); virtual uint32_t soft_body_get_collision_layer(RID p_body) const; @@ -277,12 +282,49 @@ public: virtual void soft_body_set_state(RID p_body, BodyState p_state, const Variant &p_variant); virtual Variant soft_body_get_state(RID p_body, BodyState p_state) const; + /// Special function. This function has bad performance virtual void soft_body_set_transform(RID p_body, const Transform &p_transform); - virtual Transform soft_body_get_transform(RID p_body) const; + virtual Vector3 soft_body_get_vertex_position(RID p_body, int vertex_index) const; virtual void soft_body_set_ray_pickable(RID p_body, bool p_enable); virtual bool soft_body_is_ray_pickable(RID p_body) const; + virtual void soft_body_set_simulation_precision(RID p_body, int p_simulation_precision); + virtual int soft_body_get_simulation_precision(RID p_body); + + virtual void soft_body_set_total_mass(RID p_body, real_t p_total_mass); + virtual real_t soft_body_get_total_mass(RID p_body); + + virtual void soft_body_set_linear_stiffness(RID p_body, real_t p_stiffness); + virtual real_t soft_body_get_linear_stiffness(RID p_body); + + virtual void soft_body_set_areaAngular_stiffness(RID p_body, real_t p_stiffness); + virtual real_t soft_body_get_areaAngular_stiffness(RID p_body); + + virtual void soft_body_set_volume_stiffness(RID p_body, real_t p_stiffness); + virtual real_t soft_body_get_volume_stiffness(RID p_body); + + virtual void soft_body_set_pressure_coefficient(RID p_body, real_t p_pressure_coefficient); + virtual real_t soft_body_get_pressure_coefficient(RID p_body); + + virtual void soft_body_set_pose_matching_coefficient(RID p_body, real_t p_pose_matching_coefficient); + virtual real_t soft_body_get_pose_matching_coefficient(RID p_body); + + virtual void soft_body_set_damping_coefficient(RID p_body, real_t p_damping_coefficient); + virtual real_t soft_body_get_damping_coefficient(RID p_body); + + virtual void soft_body_set_drag_coefficient(RID p_body, real_t p_drag_coefficient); + virtual real_t soft_body_get_drag_coefficient(RID p_body); + + virtual void soft_body_move_point(RID p_body, int p_point_index, const Vector3 &p_global_position); + virtual Vector3 soft_body_get_point_global_position(RID p_body, int p_point_index); + + virtual Vector3 soft_body_get_point_offset(RID p_body, int p_point_index) const; + + virtual void soft_body_remove_all_pinned_points(RID p_body); + virtual void soft_body_pin_point(RID p_body, int p_point_index, bool p_pin); + virtual bool soft_body_is_point_pinned(RID p_body, int p_point_index); + /* JOINT API */ virtual JointType joint_get_type(RID p_joint) const; diff --git a/modules/bullet/collision_object_bullet.cpp b/modules/bullet/collision_object_bullet.cpp index 57e4db708e..1d63318fd7 100644 --- a/modules/bullet/collision_object_bullet.cpp +++ b/modules/bullet/collision_object_bullet.cpp @@ -111,6 +111,8 @@ void CollisionObjectBullet::setupBulletCollisionObject(btCollisionObject *p_coll void CollisionObjectBullet::add_collision_exception(const CollisionObjectBullet *p_ignoreCollisionObject) { exceptions.insert(p_ignoreCollisionObject->get_self()); + if (!bt_collision_object) + return; bt_collision_object->setIgnoreCollisionCheck(p_ignoreCollisionObject->bt_collision_object, true); if (space) space->get_broadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bt_collision_object->getBroadphaseHandle(), space->get_dispatcher()); diff --git a/modules/bullet/register_types.cpp b/modules/bullet/register_types.cpp index b119b7720f..a76b0438b4 100644 --- a/modules/bullet/register_types.cpp +++ b/modules/bullet/register_types.cpp @@ -32,19 +32,26 @@ #include "bullet_physics_server.h" #include "class_db.h" +#include "project_settings.h" /** @author AndreaCatania */ +#ifndef _3D_DISABLED PhysicsServer *_createBulletPhysicsCallback() { return memnew(BulletPhysicsServer); } +#endif void register_bullet_types() { - +#ifndef _3D_DISABLED PhysicsServerManager::register_server("Bullet", &_createBulletPhysicsCallback); PhysicsServerManager::set_default_server("Bullet", 1); + + GLOBAL_DEF("physics/3d/active_soft_world", true); + ProjectSettings::get_singleton()->set_custom_property_info("physics/3d/active_soft_world", PropertyInfo(Variant::BOOL, "physics/3d/active_soft_world")); +#endif } void unregister_bullet_types() { diff --git a/modules/bullet/rigid_body_bullet.cpp b/modules/bullet/rigid_body_bullet.cpp index 2fc96a77b5..19fad283af 100644 --- a/modules/bullet/rigid_body_bullet.cpp +++ b/modules/bullet/rigid_body_bullet.cpp @@ -257,6 +257,8 @@ RigidBodyBullet::RigidBodyBullet() : angularDamp(0), can_sleep(true), omit_forces_integration(false), + restitution_combine_mode(PhysicsServer::COMBINE_MODE_INHERIT), + friction_combine_mode(PhysicsServer::COMBINE_MODE_INHERIT), force_integration_callback(NULL), isTransformChanged(false), previousActiveState(true), @@ -750,6 +752,22 @@ Vector3 RigidBodyBullet::get_angular_velocity() const { return gVec; } +void RigidBodyBullet::set_combine_mode(const PhysicsServer::BodyParameter p_param, const PhysicsServer::CombineMode p_mode) { + if (p_param == PhysicsServer::BODY_PARAM_BOUNCE) { + restitution_combine_mode = p_mode; + } else { + friction_combine_mode = p_mode; + } +} + +PhysicsServer::CombineMode RigidBodyBullet::get_combine_mode(PhysicsServer::BodyParameter p_param) const { + if (p_param == PhysicsServer::BODY_PARAM_BOUNCE) { + return restitution_combine_mode; + } else { + return friction_combine_mode; + } +} + void RigidBodyBullet::set_transform__bullet(const btTransform &p_global_transform) { if (mode == PhysicsServer::BODY_MODE_KINEMATIC) { // The kinematic use MotionState class diff --git a/modules/bullet/rigid_body_bullet.h b/modules/bullet/rigid_body_bullet.h index b9511243c7..911e93bfef 100644 --- a/modules/bullet/rigid_body_bullet.h +++ b/modules/bullet/rigid_body_bullet.h @@ -200,6 +200,9 @@ private: bool can_sleep; bool omit_forces_integration; + PhysicsServer::CombineMode restitution_combine_mode; + PhysicsServer::CombineMode friction_combine_mode; + Vector<CollisionData> collisions; // these parameters are used to avoid vector resize int maxCollisionsDetection; @@ -295,6 +298,12 @@ public: void set_angular_velocity(const Vector3 &p_velocity); Vector3 get_angular_velocity() const; + void set_combine_mode(const PhysicsServer::BodyParameter p_param, const PhysicsServer::CombineMode p_mode); + PhysicsServer::CombineMode get_combine_mode(PhysicsServer::BodyParameter p_param) const; + + _FORCE_INLINE_ PhysicsServer::CombineMode get_restitution_combine_mode() const { return restitution_combine_mode; } + _FORCE_INLINE_ PhysicsServer::CombineMode get_friction_combine_mode() const { return friction_combine_mode; } + virtual void set_transform__bullet(const btTransform &p_global_transform); virtual const btTransform &get_transform__bullet() const; diff --git a/modules/bullet/soft_body_bullet.cpp b/modules/bullet/soft_body_bullet.cpp index 5c20eb73f1..b3680d58db 100644 --- a/modules/bullet/soft_body_bullet.cpp +++ b/modules/bullet/soft_body_bullet.cpp @@ -32,42 +32,24 @@ #include "bullet_types_converter.h" #include "bullet_utilities.h" -#include "scene/3d/immediate_geometry.h" +#include "scene/3d/soft_body.h" #include "space_bullet.h" -/** - @author AndreaCatania -*/ - SoftBodyBullet::SoftBodyBullet() : CollisionObjectBullet(CollisionObjectBullet::TYPE_SOFT_BODY), - mass(1), + total_mass(1), simulation_precision(5), - stiffness(0.5f), - pressure_coefficient(50), - damping_coefficient(0.005), - drag_coefficient(0.005), + linear_stiffness(0.5), + areaAngular_stiffness(0.5), + volume_stiffness(0.5), + pressure_coefficient(0.), + pose_matching_coefficient(0.), + damping_coefficient(0.01), + drag_coefficient(0.), bt_soft_body(NULL), - soft_shape_type(SOFT_SHAPETYPE_NONE), - isScratched(false), - soft_body_shape_data(NULL) { - - test_geometry = memnew(ImmediateGeometry); - - red_mat = Ref<SpatialMaterial>(memnew(SpatialMaterial)); - red_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); - red_mat->set_line_width(20.0); - red_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); - red_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); - red_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); - red_mat->set_albedo(Color(1, 0, 0, 1)); - test_geometry->set_material_override(red_mat); - - test_is_in_scene = false; -} + isScratched(false) {} SoftBodyBullet::~SoftBodyBullet() { - bulletdelete(soft_body_shape_data); } void SoftBodyBullet::reload_body() { @@ -80,8 +62,6 @@ void SoftBodyBullet::reload_body() { void SoftBodyBullet::set_space(SpaceBullet *p_space) { if (space) { isScratched = false; - - // Remove this object from the physics world space->remove_soft_body(this); } @@ -90,86 +70,181 @@ void SoftBodyBullet::set_space(SpaceBullet *p_space) { if (space) { space->add_soft_body(this); } - - reload_soft_body(); } -void SoftBodyBullet::dispatch_callbacks() { - if (!bt_soft_body) { +void SoftBodyBullet::dispatch_callbacks() {} + +void SoftBodyBullet::on_collision_filters_change() {} + +void SoftBodyBullet::on_collision_checker_start() {} + +void SoftBodyBullet::on_enter_area(AreaBullet *p_area) {} + +void SoftBodyBullet::on_exit_area(AreaBullet *p_area) {} + +void SoftBodyBullet::update_visual_server(SoftBodyVisualServerHandler *p_visual_server_handler) { + if (!bt_soft_body) return; + + /// Update visual server vertices + const btSoftBody::tNodeArray &nodes(bt_soft_body->m_nodes); + const int nodes_count = nodes.size(); + + Vector<int> *vs_indices; + const void *vertex_position; + const void *vertex_normal; + + for (int vertex_index = 0; vertex_index < nodes_count; ++vertex_index) { + vertex_position = reinterpret_cast<const void *>(&nodes[vertex_index].m_x); + vertex_normal = reinterpret_cast<const void *>(&nodes[vertex_index].m_n); + + vs_indices = &indices_table[vertex_index]; + + const int vs_indices_size(vs_indices->size()); + for (int x = 0; x < vs_indices_size; ++x) { + p_visual_server_handler->set_vertex((*vs_indices)[x], vertex_position); + p_visual_server_handler->set_normal((*vs_indices)[x], vertex_normal); + } } - if (!test_is_in_scene) { - test_is_in_scene = true; - SceneTree::get_singleton()->get_current_scene()->add_child(test_geometry); + /// Generate AABB + btVector3 aabb_min; + btVector3 aabb_max; + bt_soft_body->getAabb(aabb_min, aabb_max); + + btVector3 size(aabb_max - aabb_min); + + AABB aabb; + B_TO_G(aabb_min, aabb.position); + B_TO_G(size, aabb.size); + + p_visual_server_handler->set_aabb(aabb); +} + +void SoftBodyBullet::set_soft_mesh(const Ref<Mesh> &p_mesh) { + + if (p_mesh.is_null() || !p_mesh->surface_is_softbody_friendly(0)) + soft_mesh.unref(); + else + soft_mesh = p_mesh; + + if (soft_mesh.is_null()) { + + destroy_soft_body(); + return; } - test_geometry->clear(); - test_geometry->begin(Mesh::PRIMITIVE_LINES, NULL); - bool first = true; - Vector3 pos; - for (int i = 0; i < bt_soft_body->m_nodes.size(); ++i) { - const btSoftBody::Node &n = bt_soft_body->m_nodes[i]; - B_TO_G(n.m_x, pos); - test_geometry->add_vertex(pos); - if (!first) { - test_geometry->add_vertex(pos); - } else { - first = false; - } + Array arrays = soft_mesh->surface_get_arrays(0); + ERR_FAIL_COND(!(soft_mesh->surface_get_format(0) & VS::ARRAY_FORMAT_INDEX)); + set_trimesh_body_shape(arrays[VS::ARRAY_INDEX], arrays[VS::ARRAY_VERTEX]); +} + +void SoftBodyBullet::destroy_soft_body() { + + if (!bt_soft_body) + return; + + if (space) { + /// Remove from world before deletion + space->remove_soft_body(this); } - test_geometry->end(); + + destroyBulletCollisionObject(); + bt_soft_body = NULL; +} + +void SoftBodyBullet::set_soft_transform(const Transform &p_transform) { + reset_all_node_positions(); + move_all_nodes(p_transform); } -void SoftBodyBullet::on_collision_filters_change() { +void SoftBodyBullet::move_all_nodes(const Transform &p_transform) { + if (!bt_soft_body) + return; + btTransform bt_transf; + G_TO_B(p_transform, bt_transf); + bt_soft_body->transform(bt_transf); } -void SoftBodyBullet::on_collision_checker_start() { +void SoftBodyBullet::set_node_position(int p_node_index, const Vector3 &p_global_position) { + btVector3 bt_pos; + G_TO_B(p_global_position, bt_pos); + set_node_position(p_node_index, bt_pos); } -void SoftBodyBullet::on_enter_area(AreaBullet *p_area) { +void SoftBodyBullet::set_node_position(int p_node_index, const btVector3 &p_global_position) { + if (bt_soft_body) { + bt_soft_body->m_nodes[p_node_index].m_x = p_global_position; + } } -void SoftBodyBullet::on_exit_area(AreaBullet *p_area) { +void SoftBodyBullet::get_node_position(int p_node_index, Vector3 &r_position) const { + if (bt_soft_body) { + B_TO_G(bt_soft_body->m_nodes[p_node_index].m_x, r_position); + } } -void SoftBodyBullet::set_trimesh_body_shape(PoolVector<int> p_indices, PoolVector<Vector3> p_vertices, int p_triangles_num) { +void SoftBodyBullet::get_node_offset(int p_node_index, Vector3 &r_offset) const { + if (soft_mesh.is_null()) + return; + + Array arrays = soft_mesh->surface_get_arrays(0); + PoolVector<Vector3> vertices(arrays[VS::ARRAY_VERTEX]); - TrimeshSoftShapeData *shape_data = bulletnew(TrimeshSoftShapeData); - shape_data->m_triangles_indices = p_indices; - shape_data->m_vertices = p_vertices; - shape_data->m_triangles_num = p_triangles_num; + if (0 <= p_node_index && vertices.size() > p_node_index) { + r_offset = vertices[p_node_index]; + } +} - set_body_shape_data(shape_data, SOFT_SHAPE_TYPE_TRIMESH); - reload_soft_body(); +void SoftBodyBullet::get_node_offset(int p_node_index, btVector3 &r_offset) const { + Vector3 off; + get_node_offset(p_node_index, off); + G_TO_B(off, r_offset); } -void SoftBodyBullet::set_body_shape_data(SoftShapeData *p_soft_shape_data, SoftShapeType p_type) { - bulletdelete(soft_body_shape_data); - soft_body_shape_data = p_soft_shape_data; - soft_shape_type = p_type; +void SoftBodyBullet::set_node_mass(int node_index, btScalar p_mass) { + if (0 >= p_mass) { + pin_node(node_index); + } else { + unpin_node(node_index); + } + if (bt_soft_body) { + bt_soft_body->setMass(node_index, p_mass); + } } -void SoftBodyBullet::set_transform(const Transform &p_transform) { - transform = p_transform; +btScalar SoftBodyBullet::get_node_mass(int node_index) const { if (bt_soft_body) { - // TODO the softbody set new transform considering the current transform as center of world - // like if it's local transform, so I must fix this by setting nwe transform considering the old - btTransform bt_trans; - G_TO_B(transform, bt_trans); - //bt_soft_body->transform(bt_trans); + return bt_soft_body->getMass(node_index); + } else { + return -1 == search_node_pinned(node_index) ? 1 : 0; } } -const Transform &SoftBodyBullet::get_transform() const { - return transform; +void SoftBodyBullet::reset_all_node_mass() { + if (bt_soft_body) { + for (int i = pinned_nodes.size() - 1; 0 <= i; --i) { + bt_soft_body->setMass(pinned_nodes[i], 1); + } + } + pinned_nodes.resize(0); } -void SoftBodyBullet::get_first_node_origin(btVector3 &p_out_origin) const { - if (bt_soft_body && bt_soft_body->m_nodes.size()) { - p_out_origin = bt_soft_body->m_nodes[0].m_x; - } else { - p_out_origin.setZero(); +void SoftBodyBullet::reset_all_node_positions() { + if (soft_mesh.is_null()) + return; + + Array arrays = soft_mesh->surface_get_arrays(0); + PoolVector<Vector3> vs_vertices(arrays[VS::ARRAY_VERTEX]); + PoolVector<Vector3>::Read vs_vertices_read = vs_vertices.read(); + + for (int vertex_index = bt_soft_body->m_nodes.size() - 1; 0 <= vertex_index; --vertex_index) { + + G_TO_B(vs_vertices_read[indices_table[vertex_index][0]], bt_soft_body->m_nodes[vertex_index].m_x); + + bt_soft_body->m_nodes[vertex_index].m_q = bt_soft_body->m_nodes[vertex_index].m_x; + bt_soft_body->m_nodes[vertex_index].m_v = btVector3(0, 0, 0); + bt_soft_body->m_nodes[vertex_index].m_f = btVector3(0, 0, 0); } } @@ -181,22 +256,34 @@ void SoftBodyBullet::set_activation_state(bool p_active) { } } -void SoftBodyBullet::set_mass(real_t p_val) { +void SoftBodyBullet::set_total_mass(real_t p_val) { if (0 >= p_val) { p_val = 1; } - mass = p_val; + total_mass = p_val; if (bt_soft_body) { - bt_soft_body->setTotalMass(mass); + bt_soft_body->setTotalMass(total_mass); } } -void SoftBodyBullet::set_stiffness(real_t p_val) { - stiffness = p_val; +void SoftBodyBullet::set_linear_stiffness(real_t p_val) { + linear_stiffness = p_val; if (bt_soft_body) { - mat0->m_kAST = stiffness; - mat0->m_kLST = stiffness; - mat0->m_kVST = stiffness; + mat0->m_kLST = linear_stiffness; + } +} + +void SoftBodyBullet::set_areaAngular_stiffness(real_t p_val) { + areaAngular_stiffness = p_val; + if (bt_soft_body) { + mat0->m_kAST = areaAngular_stiffness; + } +} + +void SoftBodyBullet::set_volume_stiffness(real_t p_val) { + volume_stiffness = p_val; + if (bt_soft_body) { + mat0->m_kVST = volume_stiffness; } } @@ -204,6 +291,9 @@ void SoftBodyBullet::set_simulation_precision(int p_val) { simulation_precision = p_val; if (bt_soft_body) { bt_soft_body->m_cfg.piterations = simulation_precision; + bt_soft_body->m_cfg.viterations = simulation_precision; + bt_soft_body->m_cfg.diterations = simulation_precision; + bt_soft_body->m_cfg.citerations = simulation_precision; } } @@ -214,6 +304,13 @@ void SoftBodyBullet::set_pressure_coefficient(real_t p_val) { } } +void SoftBodyBullet::set_pose_matching_coefficient(real_t p_val) { + pose_matching_coefficient = p_val; + if (bt_soft_body) { + bt_soft_body->m_cfg.kMT = pose_matching_coefficient; + } +} + void SoftBodyBullet::set_damping_coefficient(real_t p_val) { damping_coefficient = p_val; if (bt_soft_body) { @@ -228,89 +325,156 @@ void SoftBodyBullet::set_drag_coefficient(real_t p_val) { } } -void SoftBodyBullet::reload_soft_body() { - +void SoftBodyBullet::set_trimesh_body_shape(PoolVector<int> p_indices, PoolVector<Vector3> p_vertices) { + /// Assert the current soft body is destroyed destroy_soft_body(); - create_soft_body(); - if (bt_soft_body) { + /// Parse visual server indices to physical indices. + /// Merge all overlapping vertices and create a map of physical vertices to visual server - // TODO the softbody set new transform considering the current transform as center of world - // like if it's local transform, so I must fix this by setting nwe transform considering the old - btTransform bt_trans; - G_TO_B(transform, bt_trans); - bt_soft_body->transform(bt_trans); + { + /// This is the map of visual server indices to physics indices (So it's the inverse of idices_map), Thanks to it I don't need make a heavy search in the indices_map + Vector<int> vs_indices_to_physics_table; - bt_soft_body->generateBendingConstraints(2, mat0); - mat0->m_kAST = stiffness; - mat0->m_kLST = stiffness; - mat0->m_kVST = stiffness; + { // Map vertices + indices_table.resize(0); - bt_soft_body->m_cfg.piterations = simulation_precision; - bt_soft_body->m_cfg.kDP = damping_coefficient; - bt_soft_body->m_cfg.kDG = drag_coefficient; - bt_soft_body->m_cfg.kPR = pressure_coefficient; - bt_soft_body->setTotalMass(mass); - } - if (space) { - // TODO remove this please - space->add_soft_body(this); - } -} + int index = 0; + Map<Vector3, int> unique_vertices; -void SoftBodyBullet::create_soft_body() { - if (!space || !soft_body_shape_data) { - return; - } - ERR_FAIL_COND(!space->is_using_soft_world()); - switch (soft_shape_type) { - case SOFT_SHAPE_TYPE_TRIMESH: { - TrimeshSoftShapeData *trimesh_data = static_cast<TrimeshSoftShapeData *>(soft_body_shape_data); - - Vector<int> indices; - Vector<btScalar> vertices; - - int i; - const int indices_size = trimesh_data->m_triangles_indices.size(); - const int vertices_size = trimesh_data->m_vertices.size(); - indices.resize(indices_size); - vertices.resize(vertices_size * 3); - - PoolVector<int>::Read i_r = trimesh_data->m_triangles_indices.read(); - for (i = 0; i < indices_size; ++i) { - indices[i] = i_r[i]; + const int vs_vertices_size(p_vertices.size()); + + PoolVector<Vector3>::Read p_vertices_read = p_vertices.read(); + + for (int vs_vertex_index = 0; vs_vertex_index < vs_vertices_size; ++vs_vertex_index) { + + Map<Vector3, int>::Element *e = unique_vertices.find(p_vertices_read[vs_vertex_index]); + int vertex_id; + if (e) { + // Already rxisting + vertex_id = e->value(); + } else { + // Create new one + unique_vertices[p_vertices_read[vs_vertex_index]] = vertex_id = index++; + indices_table.push_back(Vector<int>()); + } + + indices_table[vertex_id].push_back(vs_vertex_index); + vs_indices_to_physics_table.push_back(vertex_id); + } + } + + const int indices_map_size(indices_table.size()); + + Vector<btScalar> bt_vertices; + + { // Parse vertices to bullet + + bt_vertices.resize(indices_map_size * 3); + PoolVector<Vector3>::Read p_vertices_read = p_vertices.read(); + + for (int i = 0; i < indices_map_size; ++i) { + bt_vertices[3 * i + 0] = p_vertices_read[indices_table[i][0]].x; + bt_vertices[3 * i + 1] = p_vertices_read[indices_table[i][0]].y; + bt_vertices[3 * i + 2] = p_vertices_read[indices_table[i][0]].z; } - i_r = PoolVector<int>::Read(); + } + + Vector<int> bt_triangles; + const int triangles_size(p_indices.size() / 3); + + { // Parse indices + + bt_triangles.resize(triangles_size * 3); + + PoolVector<int>::Read p_indices_read = p_indices.read(); - PoolVector<Vector3>::Read f_r = trimesh_data->m_vertices.read(); - for (int j = i = 0; i < vertices_size; ++i, j += 3) { - vertices[j + 0] = f_r[i][0]; - vertices[j + 1] = f_r[i][1]; - vertices[j + 2] = f_r[i][2]; + for (int i = 0; i < triangles_size; ++i) { + bt_triangles[3 * i + 0] = vs_indices_to_physics_table[p_indices_read[3 * i + 2]]; + bt_triangles[3 * i + 1] = vs_indices_to_physics_table[p_indices_read[3 * i + 1]]; + bt_triangles[3 * i + 2] = vs_indices_to_physics_table[p_indices_read[3 * i + 0]]; } - f_r = PoolVector<Vector3>::Read(); + } - bt_soft_body = btSoftBodyHelpers::CreateFromTriMesh(*space->get_soft_body_world_info(), vertices.ptr(), indices.ptr(), trimesh_data->m_triangles_num); - } break; - default: - ERR_PRINT("Shape type not supported"); - return; + btSoftBodyWorldInfo fake_world_info; + bt_soft_body = btSoftBodyHelpers::CreateFromTriMesh(fake_world_info, &bt_vertices[0], &bt_triangles[0], triangles_size, false); + setup_soft_body(); } +} + +void SoftBodyBullet::setup_soft_body() { + + if (!bt_soft_body) + return; + // Soft body setup setupBulletCollisionObject(bt_soft_body); - bt_soft_body->getCollisionShape()->setMargin(0.001f); + bt_soft_body->m_worldInfo = NULL; // Remove fake world info + bt_soft_body->getCollisionShape()->setMargin(0.01); bt_soft_body->setCollisionFlags(bt_soft_body->getCollisionFlags() & (~(btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_STATIC_OBJECT))); + + // Space setup + if (space) { + space->add_soft_body(this); + } + mat0 = bt_soft_body->appendMaterial(); + + // Assign soft body data + bt_soft_body->generateBendingConstraints(2, mat0); + + mat0->m_kLST = linear_stiffness; + mat0->m_kAST = areaAngular_stiffness; + mat0->m_kVST = volume_stiffness; + + // Clusters allow to have Soft vs Soft collision but doesn't work well right now + + //bt_soft_body->m_cfg.kSRHR_CL = 1;// Soft vs rigid hardness [0,1] (cluster only) + //bt_soft_body->m_cfg.kSKHR_CL = 1;// Soft vs kinematic hardness [0,1] (cluster only) + //bt_soft_body->m_cfg.kSSHR_CL = 1;// Soft vs soft hardness [0,1] (cluster only) + //bt_soft_body->m_cfg.kSR_SPLT_CL = 1; // Soft vs rigid impulse split [0,1] (cluster only) + //bt_soft_body->m_cfg.kSK_SPLT_CL = 1; // Soft vs kinematic impulse split [0,1] (cluster only) + //bt_soft_body->m_cfg.kSS_SPLT_CL = 1; // Soft vs Soft impulse split [0,1] (cluster only) + //bt_soft_body->m_cfg.collisions = btSoftBody::fCollision::CL_SS + btSoftBody::fCollision::CL_RS + btSoftBody::fCollision::VF_SS; + //bt_soft_body->generateClusters(64); + + bt_soft_body->m_cfg.piterations = simulation_precision; + bt_soft_body->m_cfg.viterations = simulation_precision; + bt_soft_body->m_cfg.diterations = simulation_precision; + bt_soft_body->m_cfg.citerations = simulation_precision; + bt_soft_body->m_cfg.kDP = damping_coefficient; + bt_soft_body->m_cfg.kDG = drag_coefficient; + bt_soft_body->m_cfg.kPR = pressure_coefficient; + bt_soft_body->m_cfg.kMT = pose_matching_coefficient; + bt_soft_body->setTotalMass(total_mass); + + btSoftBodyHelpers::ReoptimizeLinkOrder(bt_soft_body); + bt_soft_body->updateBounds(); + + // Set pinned nodes + for (int i = pinned_nodes.size() - 1; 0 <= i; --i) { + bt_soft_body->setMass(pinned_nodes[i], 0); + } } -void SoftBodyBullet::destroy_soft_body() { - if (space) { - /// This step is required to assert that the body is not into the world during deletion - /// This step is required since to change the body shape the body must be re-created. - /// Here is handled the case when the body is assigned into a world and the body - /// shape is changed. - space->remove_soft_body(this); +void SoftBodyBullet::pin_node(int p_node_index) { + if (-1 == search_node_pinned(p_node_index)) { + pinned_nodes.push_back(p_node_index); } - destroyBulletCollisionObject(); - bt_soft_body = NULL; +} + +void SoftBodyBullet::unpin_node(int p_node_index) { + const int id = search_node_pinned(p_node_index); + if (-1 != id) { + pinned_nodes.remove(id); + } +} + +int SoftBodyBullet::search_node_pinned(int p_node_index) const { + for (int i = pinned_nodes.size() - 1; 0 <= i; --i) { + if (p_node_index == pinned_nodes[i]) { + return i; + } + } + return -1; } diff --git a/modules/bullet/soft_body_bullet.h b/modules/bullet/soft_body_bullet.h index 9895643b84..c775193584 100644 --- a/modules/bullet/soft_body_bullet.h +++ b/modules/bullet/soft_body_bullet.h @@ -40,7 +40,10 @@ #define x11_None 0L #endif -#include <BulletSoftBody/btSoftBodyHelpers.h> +#include "BulletSoftBody/btSoftBodyHelpers.h" +#include "collision_object_bullet.h" +#include "scene/resources/mesh.h" +#include "servers/physics_server.h" #ifdef x11_None /// This is required to re add the macro None defined by x11 compiler @@ -52,39 +55,34 @@ @author AndreaCatania */ -struct SoftShapeData {}; -struct TrimeshSoftShapeData : public SoftShapeData { - PoolVector<int> m_triangles_indices; - PoolVector<Vector3> m_vertices; - int m_triangles_num; -}; - class SoftBodyBullet : public CollisionObjectBullet { -public: - enum SoftShapeType { - SOFT_SHAPETYPE_NONE = 0, - SOFT_SHAPE_TYPE_TRIMESH - }; private: btSoftBody *bt_soft_body; + Vector<Vector<int> > indices_table; btSoftBody::Material *mat0; // This is just a copy of pointer managed by btSoftBody - SoftShapeType soft_shape_type; bool isScratched; - SoftShapeData *soft_body_shape_data; + Ref<Mesh> soft_mesh; - Transform transform; int simulation_precision; - real_t mass; - real_t stiffness; // [0,1] + real_t total_mass; + real_t linear_stiffness; // [0,1] + real_t areaAngular_stiffness; // [0,1] + real_t volume_stiffness; // [0,1] real_t pressure_coefficient; // [-inf,+inf] + real_t pose_matching_coefficient; // [0,1] real_t damping_coefficient; // [0,1] real_t drag_coefficient; // [0,1] + Vector<int> pinned_nodes; - class ImmediateGeometry *test_geometry; // TODO remove this please - Ref<SpatialMaterial> red_mat; // TODO remove this please - bool test_is_in_scene; // TODO remove this please + // Other property to add + //btScalar kVC; // Volume conversation coefficient [0,+inf] + //btScalar kDF; // Dynamic friction coefficient [0,1] + //btScalar kMT; // Pose matching coefficient [0,1] + //btScalar kCHR; // Rigid contacts hardness [0,1] + //btScalar kKHR; // Kinetic contacts hardness [0,1] + //btScalar kSHR; // Soft contacts hardness [0,1] public: SoftBodyBullet(); @@ -101,39 +99,64 @@ public: _FORCE_INLINE_ btSoftBody *get_bt_soft_body() const { return bt_soft_body; } - void set_trimesh_body_shape(PoolVector<int> p_indices, PoolVector<Vector3> p_vertices, int p_triangles_num); - void set_body_shape_data(SoftShapeData *p_soft_shape_data, SoftShapeType p_type); + void update_visual_server(class SoftBodyVisualServerHandler *p_visual_server_handler); - void set_transform(const Transform &p_transform); - /// This function doesn't return the exact COM transform. - /// It returns the origin only of first node (vertice) of current soft body - /// --- - /// The soft body doesn't have a fixed center of mass, but is a group of nodes (vertices) - /// that each has its own position in the world. - /// For this reason return the correct COM is not so simple and must be calculate - /// Check this to improve this function http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=8803 - const Transform &get_transform() const; - void get_first_node_origin(btVector3 &p_out_origin) const; + void set_soft_mesh(const Ref<Mesh> &p_mesh); + void destroy_soft_body(); + + // Special function. This function has bad performance + void set_soft_transform(const Transform &p_transform); + + void move_all_nodes(const Transform &p_transform); + void set_node_position(int node_index, const Vector3 &p_global_position); + void set_node_position(int node_index, const btVector3 &p_global_position); + void get_node_position(int node_index, Vector3 &r_position) const; + // Heavy function, Please cache this info + void get_node_offset(int node_index, Vector3 &r_offset) const; + // Heavy function, Please cache this info + void get_node_offset(int node_index, btVector3 &r_offset) const; + + void set_node_mass(int node_index, btScalar p_mass); + btScalar get_node_mass(int node_index) const; + void reset_all_node_mass(); + void reset_all_node_positions(); void set_activation_state(bool p_active); - void set_mass(real_t p_val); - _FORCE_INLINE_ real_t get_mass() const { return mass; } - void set_stiffness(real_t p_val); - _FORCE_INLINE_ real_t get_stiffness() const { return stiffness; } + void set_total_mass(real_t p_val); + _FORCE_INLINE_ real_t get_total_mass() const { return total_mass; } + + void set_linear_stiffness(real_t p_val); + _FORCE_INLINE_ real_t get_linear_stiffness() const { return linear_stiffness; } + + void set_areaAngular_stiffness(real_t p_val); + _FORCE_INLINE_ real_t get_areaAngular_stiffness() const { return areaAngular_stiffness; } + + void set_volume_stiffness(real_t p_val); + _FORCE_INLINE_ real_t get_volume_stiffness() const { return volume_stiffness; } + void set_simulation_precision(int p_val); _FORCE_INLINE_ int get_simulation_precision() const { return simulation_precision; } + void set_pressure_coefficient(real_t p_val); _FORCE_INLINE_ real_t get_pressure_coefficient() const { return pressure_coefficient; } + + void set_pose_matching_coefficient(real_t p_val); + _FORCE_INLINE_ real_t get_pose_matching_coefficient() const { return pose_matching_coefficient; } + void set_damping_coefficient(real_t p_val); _FORCE_INLINE_ real_t get_damping_coefficient() const { return damping_coefficient; } + void set_drag_coefficient(real_t p_val); _FORCE_INLINE_ real_t get_drag_coefficient() const { return drag_coefficient; } private: - void reload_soft_body(); - void create_soft_body(); - void destroy_soft_body(); + void set_trimesh_body_shape(PoolVector<int> p_indices, PoolVector<Vector3> p_vertices); + void setup_soft_body(); + + void pin_node(int p_node_index); + void unpin_node(int p_node_index); + int search_node_pinned(int p_node_index) const; }; #endif // SOFT_BODY_BULLET_H diff --git a/modules/bullet/space_bullet.cpp b/modules/bullet/space_bullet.cpp index 971fd39509..132c3739d6 100644 --- a/modules/bullet/space_bullet.cpp +++ b/modules/bullet/space_bullet.cpp @@ -36,6 +36,7 @@ #include "constraint_bullet.h" #include "godot_collision_configuration.h" #include "godot_collision_dispatcher.h" +#include "project_settings.h" #include "rigid_body_bullet.h" #include "servers/physics_server.h" #include "soft_body_bullet.h" @@ -325,7 +326,7 @@ Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_ } } -SpaceBullet::SpaceBullet(bool p_create_soft_world) : +SpaceBullet::SpaceBullet() : broadphase(NULL), dispatcher(NULL), solver(NULL), @@ -338,7 +339,7 @@ SpaceBullet::SpaceBullet(bool p_create_soft_world) : gravityMagnitude(10), contactDebugCount(0) { - create_empty_world(p_create_soft_world); + create_empty_world(GLOBAL_DEF("physics/3d/active_soft_world", true)); direct_access = memnew(BulletPhysicsDirectSpaceState(this)); } @@ -355,6 +356,7 @@ void SpaceBullet::flush_queries() { } void SpaceBullet::step(real_t p_delta_time) { + delta_time = p_delta_time; dynamicsWorld->stepSimulation(p_delta_time, 0, 0); } @@ -483,6 +485,7 @@ void SpaceBullet::reload_collision_filters(RigidBodyBullet *p_body) { void SpaceBullet::add_soft_body(SoftBodyBullet *p_body) { if (is_using_soft_world()) { if (p_body->get_bt_soft_body()) { + p_body->get_bt_soft_body()->m_worldInfo = get_soft_body_world_info(); static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->addSoftBody(p_body->get_bt_soft_body(), p_body->get_collision_layer(), p_body->get_collision_mask()); } } else { @@ -494,6 +497,7 @@ void SpaceBullet::remove_soft_body(SoftBodyBullet *p_body) { if (is_using_soft_world()) { if (p_body->get_bt_soft_body()) { static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->removeSoftBody(p_body->get_bt_soft_body()); + p_body->get_bt_soft_body()->m_worldInfo = NULL; } } } @@ -549,7 +553,43 @@ BulletPhysicsDirectSpaceState *SpaceBullet::get_direct_state() { } btScalar calculateGodotCombinedRestitution(const btCollisionObject *body0, const btCollisionObject *body1) { - return MAX(body0->getRestitution(), body1->getRestitution()); + + const PhysicsServer::CombineMode cm = static_cast<RigidBodyBullet *>(body0->getUserPointer())->get_restitution_combine_mode(); + + switch (cm) { + case PhysicsServer::COMBINE_MODE_INHERIT: + if (static_cast<RigidBodyBullet *>(body1->getUserPointer())->get_restitution_combine_mode() != PhysicsServer::COMBINE_MODE_INHERIT) + return calculateGodotCombinedRestitution(body1, body0); + // else use MAX [This is used when the two bodies doesn't use physical material] + case PhysicsServer::COMBINE_MODE_MAX: + return MAX(body0->getRestitution(), body1->getRestitution()); + case PhysicsServer::COMBINE_MODE_MIN: + return MIN(body0->getRestitution(), body1->getRestitution()); + case PhysicsServer::COMBINE_MODE_MULTIPLY: + return body0->getRestitution() * body1->getRestitution(); + default: // Is always PhysicsServer::COMBINE_MODE_AVERAGE: + return (body0->getRestitution() + body1->getRestitution()) / 2; + } +} + +btScalar calculateGodotCombinedFriction(const btCollisionObject *body0, const btCollisionObject *body1) { + + const PhysicsServer::CombineMode cm = static_cast<RigidBodyBullet *>(body0->getUserPointer())->get_friction_combine_mode(); + + switch (cm) { + case PhysicsServer::COMBINE_MODE_INHERIT: + if (static_cast<RigidBodyBullet *>(body1->getUserPointer())->get_friction_combine_mode() != PhysicsServer::COMBINE_MODE_INHERIT) + return calculateGodotCombinedFriction(body1, body0); + // else use MULTIPLY [This is used when the two bodies doesn't use physical material] + case PhysicsServer::COMBINE_MODE_MULTIPLY: + return body0->getFriction() * body1->getFriction(); + case PhysicsServer::COMBINE_MODE_MAX: + return MAX(body0->getFriction(), body1->getFriction()); + case PhysicsServer::COMBINE_MODE_MIN: + return MIN(body0->getFriction(), body1->getFriction()); + default: // Is always PhysicsServer::COMBINE_MODE_AVERAGE: + return (body0->getFriction() * body1->getFriction()) / 2; + } } void SpaceBullet::create_empty_world(bool p_create_soft_world) { @@ -585,6 +625,7 @@ void SpaceBullet::create_empty_world(bool p_create_soft_world) { ghostPairCallback = bulletnew(btGhostPairCallback); godotFilterCallback = bulletnew(GodotFilterCallback); gCalculateCombinedRestitutionCallback = &calculateGodotCombinedRestitution; + gCalculateCombinedFrictionCallback = &calculateGodotCombinedFriction; dynamicsWorld->setWorldUserInfo(this); diff --git a/modules/bullet/space_bullet.h b/modules/bullet/space_bullet.h index a6c2786878..006c6462cf 100644 --- a/modules/bullet/space_bullet.h +++ b/modules/bullet/space_bullet.h @@ -84,7 +84,7 @@ public: }; class SpaceBullet : public RIDBullet { -private: + friend class AreaBullet; friend void onBulletTickCallback(btDynamicsWorld *world, btScalar timeStep); friend class BulletPhysicsDirectSpaceState; @@ -109,12 +109,14 @@ private: Vector<Vector3> contactDebug; int contactDebugCount; + real_t delta_time; public: - SpaceBullet(bool p_create_soft_world); + SpaceBullet(); virtual ~SpaceBullet(); void flush_queries(); + real_t get_delta_time() { return delta_time; } void step(real_t p_delta_time); _FORCE_INLINE_ btBroadphaseInterface *get_broadphase() { return broadphase; } diff --git a/modules/csg/doc_classes/CSGBox.xml b/modules/csg/doc_classes/CSGBox.xml index 80455fda80..5ec7b5089d 100644 --- a/modules/csg/doc_classes/CSGBox.xml +++ b/modules/csg/doc_classes/CSGBox.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="CSGBox" inherits="CSGPrimitive" category="Core" version="3.1"> <brief_description> + A CSG Box shape. </brief_description> <description> + This node allows you to create a box for use with the CSG system. </description> <tutorials> </tutorials> @@ -12,12 +14,16 @@ </methods> <members> <member name="depth" type="float" setter="set_depth" getter="get_depth"> + Depth of the box measured from the center of the box. </member> <member name="height" type="float" setter="set_height" getter="get_height"> + Height of the box measured from the center of the box. </member> <member name="material" type="Material" setter="set_material" getter="get_material"> + The material used to render the box. </member> <member name="width" type="float" setter="set_width" getter="get_width"> + Width of the box measured from the center of the box. </member> </members> <constants> diff --git a/modules/csg/doc_classes/CSGCombiner.xml b/modules/csg/doc_classes/CSGCombiner.xml index b2265d7703..1cfaa74b7d 100644 --- a/modules/csg/doc_classes/CSGCombiner.xml +++ b/modules/csg/doc_classes/CSGCombiner.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="CSGCombiner" inherits="CSGShape" category="Core" version="3.1"> <brief_description> + A CSG node that allows you to combine other CSG modifiers. </brief_description> <description> + For complex arrangements of shapes it is sometimes needed to add structure to your CSG nodes. The CSGCombiner node allows you to create this structure. The node encapsulates the result of the CSG operations of its children. In this way it is possible to do operations on one set of shapes that are children of one CSGCombiner node, and a set of separate operations on a second set of shapes that are children of a second CSGCombiner node, and then do an operation that takes the two end results as their input to create the final shape. </description> <tutorials> </tutorials> diff --git a/modules/csg/doc_classes/CSGCylinder.xml b/modules/csg/doc_classes/CSGCylinder.xml index 0cab26ad3d..92b170ed1f 100644 --- a/modules/csg/doc_classes/CSGCylinder.xml +++ b/modules/csg/doc_classes/CSGCylinder.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="CSGCylinder" inherits="CSGPrimitive" category="Core" version="3.1"> <brief_description> + A CSG Cylinder shape. </brief_description> <description> + This node allows you to create a cylinder (or cone) for use with the CSG system. </description> <tutorials> </tutorials> @@ -12,16 +14,22 @@ </methods> <members> <member name="cone" type="bool" setter="set_cone" getter="is_cone"> + If true a cone is created, the [member radius] will only apply to one side. </member> <member name="height" type="float" setter="set_height" getter="get_height"> + The height of the cylinder. </member> <member name="material" type="Material" setter="set_material" getter="get_material"> + The material used to render the cylinder. </member> <member name="radius" type="float" setter="set_radius" getter="get_radius"> + The radius of the cylinder. </member> <member name="sides" type="int" setter="set_sides" getter="get_sides"> + The number of sides of the cylinder, the higher this number the more detail there will be in the cylinder. </member> <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces"> + If true the normals of the cylinder are set to give a smooth effect making the cylinder seem rounded. When false the cylinder will have a flat shaded look. </member> </members> <constants> diff --git a/modules/csg/doc_classes/CSGMesh.xml b/modules/csg/doc_classes/CSGMesh.xml index e5c3e5ccf3..419214b7e6 100644 --- a/modules/csg/doc_classes/CSGMesh.xml +++ b/modules/csg/doc_classes/CSGMesh.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="CSGMesh" inherits="CSGPrimitive" category="Core" version="3.1"> <brief_description> + A CSG Mesh shape that uses a mesh resource. </brief_description> <description> + This CSG node allows you to use any mesh resource as a CSG shape provided it is closed, does not self-intersect, does not contain internal faces and has no edges that connect to more then two faces. </description> <tutorials> </tutorials> @@ -12,6 +14,7 @@ </methods> <members> <member name="mesh" type="Mesh" setter="set_mesh" getter="get_mesh"> + The mesh resource to use as a CSG shape. </member> </members> <constants> diff --git a/modules/csg/doc_classes/CSGPolygon.xml b/modules/csg/doc_classes/CSGPolygon.xml index 1e6dec8085..a33e5557cb 100644 --- a/modules/csg/doc_classes/CSGPolygon.xml +++ b/modules/csg/doc_classes/CSGPolygon.xml @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="CSGPolygon" inherits="CSGPrimitive" category="Core" version="3.1"> <brief_description> - Extrudes a 2D polygon shape to create a 3D mesh + Extrudes a 2D polygon shape to create a 3D mesh. </brief_description> <description> This node takes a 2D polygon shape and extrudes it to create a 3D mesh. @@ -14,63 +14,63 @@ </methods> <members> <member name="depth" type="float" setter="set_depth" getter="get_depth"> - Extrusion depth when [member mode] is [constant MODE_DEPTH] + Extrusion depth when [member mode] is [constant MODE_DEPTH]. </member> <member name="material" type="Material" setter="set_material" getter="get_material"> - Material to use for the resulting mesh + Material to use for the resulting mesh. </member> <member name="mode" type="int" setter="set_mode" getter="get_mode" enum="CSGPolygon.Mode"> - Extrusion mode + Extrusion mode. </member> - <member name="path_interval" type="float" setter="set_path_interval" getter="get_path_interval"> - Interval at which a new extrusion slice is added along the path when [member mode] is [constant MODE_PATH] + <member name="path_continuous_u" type="bool" setter="set_path_continuous_u" getter="is_path_continuous_u"> + If true the u component of our uv will continuously increase in unison with the distance traveled along our path when [member mode] is [constant MODE_PATH]. </member> - <member name="path_node" type="NodePath" setter="set_path_node" getter="get_path_node"> - The [Shape] object containing the path along which we extrude when [member mode] is [constant MODE_PATH] + <member name="path_interval" type="float" setter="set_path_interval" getter="get_path_interval"> + Interval at which a new extrusion slice is added along the path when [member mode] is [constant MODE_PATH]. </member> - <member name="path_rotation" type="int" setter="set_path_rotation" getter="get_path_rotation" enum="CSGPolygon.PathRotation"> - The method by which each slice is rotated along the path when [member mode] is [constant MODE_PATH] + <member name="path_joined" type="bool" setter="set_path_joined" getter="is_path_joined"> + If true the start and end of our path are joined together ensuring there is no seam when [member mode] is [constant MODE_PATH]. </member> <member name="path_local" type="bool" setter="set_path_local" getter="is_path_local"> - If false we extrude centered on our path, if true we extrude in relation to the position of our CSGPolygon when [member mode] is [constant MODE_PATH] + If false we extrude centered on our path, if true we extrude in relation to the position of our CSGPolygon when [member mode] is [constant MODE_PATH]. </member> - <member name="path_continuous_u" type="bool" setter="set_path_continuous_u" getter="is_path_continuous_u"> - If true the u component of our uv will continuously increase in unison with the distance traveled along our path when [member mode] is [constant MODE_PATH] + <member name="path_node" type="NodePath" setter="set_path_node" getter="get_path_node"> + The [Shape] object containing the path along which we extrude when [member mode] is [constant MODE_PATH]. </member> - <member name="path_joined" type="bool" setter="set_path_joined" getter="is_path_joined"> - If true the start and end of our path are joined together ensuring there is no seam when [member mode] is [constant MODE_PATH] + <member name="path_rotation" type="int" setter="set_path_rotation" getter="get_path_rotation" enum="CSGPolygon.PathRotation"> + The method by which each slice is rotated along the path when [member mode] is [constant MODE_PATH]. </member> <member name="polygon" type="PoolVector2Array" setter="set_polygon" getter="get_polygon"> - Point array that defines the shape that we'll extrude + Point array that defines the shape that we'll extrude. </member> <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces"> - Generates smooth normals so smooth shading is applied to our mesh + Generates smooth normals so smooth shading is applied to our mesh. </member> <member name="spin_degrees" type="float" setter="set_spin_degrees" getter="get_spin_degrees"> - Degrees to rotate our extrusion for each slice when [member mode] is [constant MODE_SPIN] + Degrees to rotate our extrusion for each slice when [member mode] is [constant MODE_SPIN]. </member> <member name="spin_sides" type="int" setter="set_spin_sides" getter="get_spin_sides"> - Number of extrusion when [member mode] is [constant MODE_SPIN] + Number of extrusion when [member mode] is [constant MODE_SPIN]. </member> </members> <constants> <constant name="MODE_DEPTH" value="0" enum="Mode"> - Shape is extruded to [member depth] + Shape is extruded to [member depth]. </constant> <constant name="MODE_SPIN" value="1" enum="Mode"> - Shape is extruded by rotating it around an axis + Shape is extruded by rotating it around an axis. </constant> <constant name="MODE_PATH" value="2" enum="Mode"> - Shape is extruded along a path set by a [Shape] set in [member path_node] + Shape is extruded along a path set by a [Shape] set in [member path_node]. </constant> <constant name="PATH_ROTATION_POLYGON" value="0" enum="PathRotation"> - Slice is not rotated + Slice is not rotated. </constant> <constant name="PATH_ROTATION_PATH" value="1" enum="PathRotation"> - Slice is rotated around the up vector of the path + Slice is rotated around the up vector of the path. </constant> <constant name="PATH_ROTATION_PATH_FOLLOW" value="2" enum="PathRotation"> - Slice is rotate to match the path exactly + Slice is rotate to match the path exactly. </constant> </constants> </class> diff --git a/modules/csg/doc_classes/CSGPrimitive.xml b/modules/csg/doc_classes/CSGPrimitive.xml index bf41c40f22..2591bab7e3 100644 --- a/modules/csg/doc_classes/CSGPrimitive.xml +++ b/modules/csg/doc_classes/CSGPrimitive.xml @@ -1,6 +1,7 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="CSGPrimitive" inherits="CSGShape" category="Core" version="3.1"> <brief_description> + Base class for CSG primitives. </brief_description> <description> </description> @@ -12,6 +13,7 @@ </methods> <members> <member name="invert_faces" type="bool" setter="set_invert_faces" getter="is_inverting_faces"> + Invert the faces of the mesh. </member> </members> <constants> diff --git a/modules/csg/doc_classes/CSGShape.xml b/modules/csg/doc_classes/CSGShape.xml index cf236a4207..90621b94f4 100644 --- a/modules/csg/doc_classes/CSGShape.xml +++ b/modules/csg/doc_classes/CSGShape.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="CSGShape" inherits="VisualInstance" category="Core" version="3.1"> <brief_description> + The CSG base class. </brief_description> <description> + This is the CSG base class that provides CSG operation support to the various CSG nodes in Godot. </description> <tutorials> </tutorials> @@ -13,23 +15,29 @@ <return type="bool"> </return> <description> + Returns true if this is a root shape and is thus the object that is rendered. </description> </method> </methods> <members> <member name="operation" type="int" setter="set_operation" getter="get_operation" enum="CSGShape.Operation"> + The operation that is performed on this shape. This is ignored for the first CSG child node as the operation is between this node and the previous child of this nodes parent. </member> <member name="snap" type="float" setter="set_snap" getter="get_snap"> </member> <member name="use_collision" type="bool" setter="set_use_collision" getter="is_using_collision"> + Adds a collision shape to the physics engine for our CSG shape. This will always act like a static body. Note that the collision shape is still active even if the CSG shape itself is hidden. </member> </members> <constants> <constant name="OPERATION_UNION" value="0" enum="Operation"> + Geometry of both primitives is merged, intersecting geometry is removed. </constant> <constant name="OPERATION_INTERSECTION" value="1" enum="Operation"> + Only intersecting geometry remains, the rest is removed. </constant> <constant name="OPERATION_SUBTRACTION" value="2" enum="Operation"> + The second shape is susbtracted from the first, leaving a dent with it's shape. </constant> </constants> </class> diff --git a/modules/csg/doc_classes/CSGSphere.xml b/modules/csg/doc_classes/CSGSphere.xml index 520368506e..a0069879cb 100644 --- a/modules/csg/doc_classes/CSGSphere.xml +++ b/modules/csg/doc_classes/CSGSphere.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="CSGSphere" inherits="CSGPrimitive" category="Core" version="3.1"> <brief_description> + A CSG Sphere shape. </brief_description> <description> + This node allows you to create a sphere for use with the CSG system. </description> <tutorials> </tutorials> @@ -12,14 +14,19 @@ </methods> <members> <member name="material" type="Material" setter="set_material" getter="get_material"> + The material used to render the sphere. </member> <member name="radial_segments" type="int" setter="set_radial_segments" getter="get_radial_segments"> + Number of vertical slices for the sphere. </member> <member name="radius" type="float" setter="set_radius" getter="get_radius"> + Radius of the sphere. </member> <member name="rings" type="int" setter="set_rings" getter="get_rings"> + Number of horizontal slices for the sphere. </member> <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces"> + If true the normals of the sphere are set to give a smooth effect making the sphere seem rounded. When false the sphere will have a flat shaded look. </member> </members> <constants> diff --git a/modules/csg/doc_classes/CSGTorus.xml b/modules/csg/doc_classes/CSGTorus.xml index 58bbef2600..187d71a2fa 100644 --- a/modules/csg/doc_classes/CSGTorus.xml +++ b/modules/csg/doc_classes/CSGTorus.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="CSGTorus" inherits="CSGPrimitive" category="Core" version="3.1"> <brief_description> + A CSG Torus shape. </brief_description> <description> + This node allows you to create a torus for use with the CSG system. </description> <tutorials> </tutorials> @@ -12,16 +14,22 @@ </methods> <members> <member name="inner_radius" type="float" setter="set_inner_radius" getter="get_inner_radius"> + The inner radius of the torus. </member> <member name="material" type="Material" setter="set_material" getter="get_material"> + The material used to render the torus. </member> <member name="outer_radius" type="float" setter="set_outer_radius" getter="get_outer_radius"> + The outer radius of the torus. </member> <member name="ring_sides" type="int" setter="set_ring_sides" getter="get_ring_sides"> + The number of edges each ring of the torus is constructed of. </member> <member name="sides" type="int" setter="set_sides" getter="get_sides"> + The number of slices the torus is constructed of. </member> <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces"> + If true the normals of the torus are set to give a smooth effect making the torus seem rounded. When false the torus will have a flat shaded look. </member> </members> <constants> diff --git a/modules/gdnative/nativescript/nativescript.cpp b/modules/gdnative/nativescript/nativescript.cpp index 7bab718b81..5e093109d5 100644 --- a/modules/gdnative/nativescript/nativescript.cpp +++ b/modules/gdnative/nativescript/nativescript.cpp @@ -1053,7 +1053,7 @@ Ref<Script> NativeScriptLanguage::get_template(const String &p_class_name, const s->set_class_name(p_class_name); return Ref<NativeScript>(s); } -bool NativeScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const { +bool NativeScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, Set<int> *r_safe_lines) const { return true; } diff --git a/modules/gdnative/nativescript/nativescript.h b/modules/gdnative/nativescript/nativescript.h index be093dde4b..1b39b63ad9 100644 --- a/modules/gdnative/nativescript/nativescript.h +++ b/modules/gdnative/nativescript/nativescript.h @@ -295,7 +295,7 @@ public: virtual void get_comment_delimiters(List<String> *p_delimiters) const; virtual void get_string_delimiters(List<String> *p_delimiters) const; virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; - virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const; + virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, Set<int> *r_safe_lines = NULL) const; virtual Script *create_script() const; virtual bool has_named_classes() const; virtual bool supports_builtin_mode() const; diff --git a/modules/gdnative/pluginscript/pluginscript_language.cpp b/modules/gdnative/pluginscript/pluginscript_language.cpp index 8018178bd5..816b0f0cab 100644 --- a/modules/gdnative/pluginscript/pluginscript_language.cpp +++ b/modules/gdnative/pluginscript/pluginscript_language.cpp @@ -108,7 +108,7 @@ Ref<Script> PluginScriptLanguage::get_template(const String &p_class_name, const return script; } -bool PluginScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const { +bool PluginScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, Set<int> *r_safe_lines) const { PoolStringArray functions; if (_desc.validate) { bool ret = _desc.validate( diff --git a/modules/gdnative/pluginscript/pluginscript_language.h b/modules/gdnative/pluginscript/pluginscript_language.h index 709345885b..2443e31361 100644 --- a/modules/gdnative/pluginscript/pluginscript_language.h +++ b/modules/gdnative/pluginscript/pluginscript_language.h @@ -74,7 +74,7 @@ public: virtual void get_comment_delimiters(List<String> *p_delimiters) const; virtual void get_string_delimiters(List<String> *p_delimiters) const; virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; - virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL) const; + virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL, Set<int> *r_safe_lines = NULL) const; virtual Script *create_script() const; virtual bool has_named_classes() const; virtual bool supports_builtin_mode() const; diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp index fedc510f01..f2a1a5b50c 100644 --- a/modules/gdscript/editor/gdscript_highlighter.cpp +++ b/modules/gdscript/editor/gdscript_highlighter.cpp @@ -75,9 +75,11 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_ bool in_keyword = false; bool in_word = false; bool in_function_name = false; + bool in_variable_declaration = false; bool in_member_variable = false; bool in_node_path = false; bool is_hex_notation = false; + bool expect_type = false; Color keyword_color; Color color; @@ -205,6 +207,8 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_ if (str[k] == '(') { in_function_name = true; + } else if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_VAR)) { + in_variable_declaration = true; } } @@ -222,6 +226,28 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_ if (is_symbol) { in_function_name = false; in_member_variable = false; + + if (expect_type && str[j] != ' ' && str[j] != '\t' && str[j] != ':') { + expect_type = false; + } + if (j > 0 && str[j] == '>' && str[j - 1] == '-') { + expect_type = true; + } + + if (in_variable_declaration || previous_text == "(" || previous_text == ",") { + int k = j; + // Skip space + while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) { + k++; + } + + if (str[k] == ':') { + // has type hint + expect_type = true; + } + } + + in_variable_declaration = false; } if (!in_node_path && in_region == -1 && str[j] == '$') { @@ -256,6 +282,9 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_ } else if (is_number) { next_type = NUMBER; color = number_color; + } else if (expect_type) { + next_type = TYPE; + color = type_color; } else { next_type = IDENTIFIER; } @@ -330,6 +359,7 @@ void GDScriptSyntaxHighlighter::_update_cache() { function_definition_color = EDITOR_GET("text_editor/highlighting/gdscript/function_definition_color"); node_path_color = EDITOR_GET("text_editor/highlighting/gdscript/node_path_color"); + type_color = EDITOR_GET("text_editor/highlighting/base_type_color"); } SyntaxHighlighter *GDScriptSyntaxHighlighter::create() { diff --git a/modules/gdscript/editor/gdscript_highlighter.h b/modules/gdscript/editor/gdscript_highlighter.h index 0296ab7652..b8cb4a65e9 100644 --- a/modules/gdscript/editor/gdscript_highlighter.h +++ b/modules/gdscript/editor/gdscript_highlighter.h @@ -44,7 +44,8 @@ private: FUNCTION, KEYWORD, MEMBER, - IDENTIFIER + IDENTIFIER, + TYPE, }; // colours @@ -56,6 +57,7 @@ private: Color number_color; Color member_color; Color node_path_color; + Color type_color; public: static SyntaxHighlighter *create(); diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index b3ebd4fe4b..8bd29ffc55 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -220,16 +220,14 @@ void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) { void GDScript::get_script_method_list(List<MethodInfo> *p_list) const { for (const Map<StringName, GDScriptFunction *>::Element *E = member_functions.front(); E; E = E->next()) { + GDScriptFunction *func = E->get(); MethodInfo mi; mi.name = E->key(); - for (int i = 0; i < E->get()->get_argument_count(); i++) { - PropertyInfo arg; - arg.type = Variant::NIL; //variant - arg.name = E->get()->get_argument_name(i); - mi.arguments.push_back(arg); + for (int i = 0; i < func->get_argument_count(); i++) { + mi.arguments.push_back(func->get_argument_type(i)); } - mi.return_val.name = "Variant"; + mi.return_val = func->get_return_type(); p_list->push_back(mi); } } @@ -277,16 +275,14 @@ MethodInfo GDScript::get_method_info(const StringName &p_method) const { if (!E) return MethodInfo(); + GDScriptFunction *func = E->get(); MethodInfo mi; mi.name = E->key(); - for (int i = 0; i < E->get()->get_argument_count(); i++) { - PropertyInfo arg; - arg.type = Variant::NIL; //variant - arg.name = E->get()->get_argument_name(i); - mi.arguments.push_back(arg); + for (int i = 0; i < func->get_argument_count(); i++) { + mi.arguments.push_back(func->get_argument_type(i)); } - mi.return_val.name = "Variant"; + mi.return_val = func->get_return_type(); return mi; } @@ -941,8 +937,12 @@ bool GDScriptInstance::set(const StringName &p_name, const Variant &p_value) { if (err.error == Variant::CallError::CALL_OK) { return true; //function exists, call was successful } - } else + } else { + if (!E->get().data_type.is_type(p_value)) { + return false; // Type mismatch + } members[E->get().index] = p_value; + } return true; } } @@ -1735,7 +1735,9 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { "NAN", "self", "true", + "void", // functions + "as", "assert", "breakpoint", "class", @@ -1824,8 +1826,40 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b if (parser.get_parse_tree() && parser.get_parse_tree()->type == GDScriptParser::Node::TYPE_CLASS) { const GDScriptParser::ClassNode *c = static_cast<const GDScriptParser::ClassNode *>(parser.get_parse_tree()); - if (r_base_type && c->extends_used && c->extends_class.size() == 1) { - *r_base_type = c->extends_class[0]; //todo, should work much better + if (r_base_type) { + GDScriptParser::DataType base_type; + if (c->base_type.has_type) { + base_type = c->base_type; + while (base_type.has_type && base_type.kind != GDScriptParser::DataType::NATIVE) { + switch (base_type.kind) { + case GDScriptParser::DataType::CLASS: { + base_type = base_type.class_type->base_type; + } break; + case GDScriptParser::DataType::GDSCRIPT: { + Ref<GDScript> gds = base_type.script_type; + if (gds.is_valid()) { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = gds->get_instance_base_type(); + } else { + base_type = GDScriptParser::DataType(); + } + } break; + default: { + base_type = GDScriptParser::DataType(); + } break; + } + } + } + if (base_type.has_type) { + *r_base_type = base_type.native_type; + } else { + // Fallback + if (c->extends_used && c->extends_class.size() == 1) { + *r_base_type = c->extends_class[0]; + } else if (!c->extends_used) { + *r_base_type = "Reference"; + } + } } return c->name; } diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h index d1c57a0330..d5fe7a000b 100644 --- a/modules/gdscript/gdscript.h +++ b/modules/gdscript/gdscript.h @@ -64,6 +64,7 @@ class GDScript : public Script { StringName setter; StringName getter; MultiplayerAPI::RPCMode rpc_mode; + GDScriptDataType data_type; }; friend class GDScriptInstance; @@ -145,8 +146,13 @@ public: const Map<StringName, Ref<GDScript> > &get_subclasses() const { return subclasses; } const Map<StringName, Variant> &get_constants() const { return constants; } const Set<StringName> &get_members() const { return members; } + const GDScriptDataType &get_member_type(const StringName &p_member) const { + ERR_FAIL_COND_V(!member_indices.has(p_member), GDScriptDataType()); + return member_indices[p_member].data_type; + } const Map<StringName, GDScriptFunction *> &get_member_functions() const { return member_functions; } const Ref<GDScriptNativeClass> &get_native() const { return native; } + const String &get_script_class_name() const { return name; } virtual bool has_script_signal(const StringName &p_signal) const; virtual void get_script_signal_list(List<MethodInfo> *r_signals) const; @@ -391,7 +397,7 @@ public: virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; virtual bool is_using_templates(); virtual void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script); - virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL) const; + virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL, Set<int> *r_safe_lines = NULL) const; virtual Script *create_script() const; virtual bool has_named_classes() const; virtual bool supports_builtin_mode() const; diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index 70f3d704ae..a428ccd306 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -111,23 +111,50 @@ bool GDScriptCompiler::_create_binary_operator(CodeGen &codegen, const GDScriptP return true; } -/* -int GDScriptCompiler::_parse_subexpression(CodeGen& codegen,const GDScriptParser::Node *p_expression) { - +GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::DataType &p_datatype) const { + if (!p_datatype.has_type) { + return GDScriptDataType(); + } - int ret = _parse_expression(codegen,p_expression); - if (ret<0) - return ret; + GDScriptDataType result; + result.has_type = true; - if (ret&(GDScriptFunction::ADDR_TYPE_STACK<<GDScriptFunction::ADDR_BITS)) { - codegen.stack_level++; - codegen.check_max_stack_level(); - //stack was used, keep value + switch (p_datatype.kind) { + case GDScriptParser::DataType::BUILTIN: { + result.kind = GDScriptDataType::BUILTIN; + result.builtin_type = p_datatype.builtin_type; + } break; + case GDScriptParser::DataType::NATIVE: { + result.kind = GDScriptDataType::NATIVE; + result.native_type = p_datatype.native_type; + } break; + case GDScriptParser::DataType::SCRIPT: { + result.kind = GDScriptDataType::SCRIPT; + result.script_type = p_datatype.script_type; + result.native_type = result.script_type->get_instance_base_type(); + } + case GDScriptParser::DataType::GDSCRIPT: { + result.kind = GDScriptDataType::GDSCRIPT; + result.script_type = p_datatype.script_type; + result.native_type = result.script_type->get_instance_base_type(); + } break; + case GDScriptParser::DataType::CLASS: { + result.kind = GDScriptDataType::GDSCRIPT; + if (p_datatype.class_type->name == StringName()) { + result.script_type = Ref<GDScript>(main_script); + } else { + result.script_type = class_map[p_datatype.class_type->name]; + } + result.native_type = result.script_type->get_instance_base_type(); + } break; + default: { + ERR_PRINT("Parser bug: converting unresolved type."); + result.has_type = false; + } } - return ret; + return result; } -*/ int GDScriptCompiler::_parse_assign_right_expression(CodeGen &codegen, const GDScriptParser::OperatorNode *p_expression, int p_stack_level) { @@ -263,15 +290,6 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: owner = owner->_owner; } - /* - handled in constants now - if (codegen.script->subclasses.has(identifier)) { - //same with a subclass, make it a local constant. - int idx = codegen.get_constant_pos(codegen.script->subclasses[identifier]); - return idx|(GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT<<GDScriptFunction::ADDR_BITS); //make it a local constant (faster access) - - }*/ - if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) { int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier]; @@ -430,6 +448,83 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: return dst_addr; } break; + case GDScriptParser::Node::TYPE_CAST: { + const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression); + + int slevel = p_stack_level; + int src_addr = _parse_expression(codegen, cn->source_node, slevel); + if (src_addr < 0) + return src_addr; + if (src_addr & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) { + slevel++; + codegen.alloc_stack(slevel); + } + + switch (cn->cast_type.kind) { + case GDScriptParser::DataType::BUILTIN: { + codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_BUILTIN); + codegen.opcodes.push_back(cn->cast_type.builtin_type); + } break; + case GDScriptParser::DataType::NATIVE: { + int class_idx; + if (GDScriptLanguage::get_singleton()->get_global_map().has(cn->cast_type.native_type)) { + + class_idx = GDScriptLanguage::get_singleton()->get_global_map()[cn->cast_type.native_type]; + class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root) + } else { + _set_error("Invalid native class type '" + String(cn->cast_type.native_type) + "'.", cn); + return -1; + } + codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_NATIVE); // perform operator + codegen.opcodes.push_back(class_idx); // variable type + } break; + case GDScriptParser::DataType::CLASS: { + + Variant script; + int idx = -1; + if (cn->cast_type.class_type->name == StringName()) { + script = codegen.script; + } else { + StringName name = cn->cast_type.class_type->name; + if (class_map[name] == codegen.script->subclasses[name]) { + idx = codegen.get_name_map_pos(name); + idx |= GDScriptFunction::ADDR_TYPE_CLASS_CONSTANT << GDScriptFunction::ADDR_BITS; + } else { + script = class_map[name]; + } + } + + if (idx < 0) { + idx = codegen.get_constant_pos(script); + idx |= GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS; //make it a local constant (faster access) + } + + codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_SCRIPT); // perform operator + codegen.opcodes.push_back(idx); // variable type + } break; + case GDScriptParser::DataType::SCRIPT: + case GDScriptParser::DataType::GDSCRIPT: { + + Variant script = cn->cast_type.script_type; + int idx = codegen.get_constant_pos(script); + idx |= GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS; //make it a local constant (faster access) + + codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_SCRIPT); // perform operator + codegen.opcodes.push_back(idx); // variable type + } break; + default: { + _set_error("Parser bug: unresolved data type.", cn); + return -1; + } + } + + codegen.opcodes.push_back(src_addr); // source adddress + int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS); + codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode + codegen.alloc_stack(p_stack_level); + return dst_addr; + + } break; case GDScriptParser::Node::TYPE_OPERATOR: { //hell breaks loose @@ -782,14 +877,6 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: case GDScriptParser::OperatorNode::OP_BIT_INVERT: { if (!_create_unary_operator(codegen, on, Variant::OP_BIT_NEGATE, p_stack_level)) return -1; } break; - case GDScriptParser::OperatorNode::OP_PREINC: { - } break; //? - case GDScriptParser::OperatorNode::OP_PREDEC: { - } break; - case GDScriptParser::OperatorNode::OP_INC: { - } break; - case GDScriptParser::OperatorNode::OP_DEC: { - } break; //binary operators (in precedence order) case GDScriptParser::OperatorNode::OP_IN: { if (!_create_binary_operator(codegen, on, Variant::OP_IN, p_stack_level)) return -1; @@ -1064,12 +1151,87 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: if (src_address_b < 0) return -1; - codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN); // perform operator - codegen.opcodes.push_back(dst_address_a); // argument 1 - codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter) + GDScriptParser::DataType assign_type = on->arguments[0]->get_datatype(); + + if (assign_type.has_type && !on->arguments[1]->get_datatype().has_type) { + // Typed assignment + switch (assign_type.kind) { + case GDScriptParser::DataType::BUILTIN: { + codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN); // perform operator + codegen.opcodes.push_back(assign_type.builtin_type); // variable type + codegen.opcodes.push_back(dst_address_a); // argument 1 + codegen.opcodes.push_back(src_address_b); // argument 2 + } break; + case GDScriptParser::DataType::NATIVE: { + int class_idx; + if (GDScriptLanguage::get_singleton()->get_global_map().has(assign_type.native_type)) { + + class_idx = GDScriptLanguage::get_singleton()->get_global_map()[assign_type.native_type]; + class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root) + } else { + _set_error("Invalid native class type '" + String(assign_type.native_type) + "'.", on->arguments[0]); + return -1; + } + codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_NATIVE); // perform operator + codegen.opcodes.push_back(class_idx); // variable type + codegen.opcodes.push_back(dst_address_a); // argument 1 + codegen.opcodes.push_back(src_address_b); // argument 2 + } break; + case GDScriptParser::DataType::CLASS: { + + Variant script; + int idx = -1; + if (assign_type.class_type->name == StringName()) { + script = codegen.script; + } else { + StringName name = assign_type.class_type->name; + if (class_map[name] == codegen.script->subclasses[name]) { + idx = codegen.get_name_map_pos(name); + idx |= GDScriptFunction::ADDR_TYPE_CLASS_CONSTANT << GDScriptFunction::ADDR_BITS; + } else { + script = class_map[name]; + } + } + + if (idx < 0) { + idx = codegen.get_constant_pos(script); + idx |= GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS; //make it a local constant (faster access) + } + + codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_SCRIPT); // perform operator + codegen.opcodes.push_back(idx); // variable type + codegen.opcodes.push_back(dst_address_a); // argument 1 + codegen.opcodes.push_back(src_address_b); // argument 2 + } break; + case GDScriptParser::DataType::SCRIPT: + case GDScriptParser::DataType::GDSCRIPT: { + + Variant script = assign_type.script_type; + int idx = codegen.get_constant_pos(script); + idx |= GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS; //make it a local constant (faster access) + + codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_SCRIPT); // perform operator + codegen.opcodes.push_back(idx); // variable type + codegen.opcodes.push_back(dst_address_a); // argument 1 + codegen.opcodes.push_back(src_address_b); // argument 2 + } break; + default: { + ERR_PRINT("Compiler bug: unresolved assign."); + + // Shouldn't get here, but fail-safe to a regular assignment + codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN); // perform operator + codegen.opcodes.push_back(dst_address_a); // argument 1 + codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter) + } + } + } else { + // Either untyped assignment or already type-checked by the parser + codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN); // perform operator + codegen.opcodes.push_back(dst_address_a); // argument 1 + codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter) + } return dst_address_a; //if anything, returns wathever was assigned or correct stack position } - } break; case GDScriptParser::OperatorNode::OP_IS: { @@ -1525,6 +1687,18 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser if (p_func) { gdfunc->_static = p_func->_static; gdfunc->rpc_mode = p_func->rpc_mode; + gdfunc->argument_types.resize(p_func->argument_types.size()); + for (int i = 0; i < p_func->argument_types.size(); i++) { + gdfunc->argument_types[i] = _gdtype_from_datatype(p_func->argument_types[i]); + } + gdfunc->return_type = _gdtype_from_datatype(p_func->return_type); + } else { + gdfunc->_static = false; + gdfunc->rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; + gdfunc->return_type = GDScriptDataType(); + gdfunc->return_type.has_type = true; + gdfunc->return_type.kind = GDScriptDataType::BUILTIN; + gdfunc->return_type.builtin_type = Variant::NIL; } #ifdef TOOLS_ENABLED @@ -1653,12 +1827,23 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser return OK; } -Error GDScriptCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { - - Map<StringName, Ref<GDScript> > old_subclasses; +Error GDScriptCompiler::_parse_class_level(GDScript *p_script, GDScript *p_owner, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { - if (p_keep_state) { - old_subclasses = p_script->subclasses; + if (p_class->owner && p_class->owner->owner) { + // Owner is not root + StringName owner_name = p_class->owner->name; + if (!parsed_classes.has(owner_name)) { + if (parsing_classes.has(owner_name)) { + _set_error("Cyclic class reference for '" + String(owner_name) + "'.", p_class); + return ERR_PARSE_ERROR; + } + parsing_classes.insert(owner_name); + Error err = _parse_class_level(class_map[owner_name].ptr(), class_map[owner_name]->_owner, p_class->owner, p_keep_state); + if (err) { + return err; + } + parsing_classes.erase(owner_name); + } } p_script->native = Ref<GDScriptNativeClass>(); @@ -1682,236 +1867,100 @@ Error GDScriptCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, cons Ref<GDScriptNativeClass> native; - if (p_class->extends_used) { - //do inheritance - String path = p_class->extends_file; - - Ref<GDScript> script; - - if (path != "") { - //path (and optionally subclasses) - - if (path.is_rel_path()) { - - String base; - - if (p_owner) { - GDScript *current_class = p_owner; - while (current_class != NULL) { - base = current_class->get_path(); - if (base == "") - current_class = current_class->_owner; - else - break; - } - } else { - base = p_script->get_path(); - } - - if (base == "" || base.is_rel_path()) { - _set_error("Could not resolve relative path for parent class: " + path, p_class); - return ERR_FILE_NOT_FOUND; - } - path = base.get_base_dir().plus_file(path).simplify_path(); - } - script = ResourceLoader::load(path); - if (script.is_null()) { - _set_error("Could not load base class: " + path, p_class); - return ERR_FILE_NOT_FOUND; - } - if (!script->valid) { - - _set_error("Script not fully loaded (cyclic preload?): " + path, p_class); - return ERR_BUSY; - } - //print_line("EXTENDS PATH: "+path+" script is "+itos(script.is_valid())+" indices is "+itos(script->member_indices.size())+" valid? "+itos(script->valid)); - - if (p_class->extends_class.size()) { - - for (int i = 0; i < p_class->extends_class.size(); i++) { - - String sub = p_class->extends_class[i]; - if (script->subclasses.has(sub)) { - - Ref<Script> subclass = script->subclasses[sub]; //avoid reference from disappearing - script = subclass; - } else { - - _set_error("Could not find subclass: " + sub, p_class); - return ERR_FILE_NOT_FOUND; - } - } - } - - } else { - - ERR_FAIL_COND_V(p_class->extends_class.size() == 0, ERR_BUG); - //look around for the subclasses - - String base = p_class->extends_class[0]; - GDScript *p = p_owner; - Ref<GDScript> base_class; - - while (p) { - - if (p->subclasses.has(base)) { - - base_class = p->subclasses[base]; - break; - } - - if (p->constants.has(base)) { - - base_class = p->constants[base]; - if (base_class.is_null()) { - _set_error("Constant is not a class: " + base, p_class); - return ERR_SCRIPT_FAILED; - } - break; - } - - p = p->_owner; - } - - if (base_class.is_valid()) { - - String ident = base; - - for (int i = 1; i < p_class->extends_class.size(); i++) { - - String subclass = p_class->extends_class[i]; - - ident += ("." + subclass); - - if (base_class->subclasses.has(subclass)) { - - base_class = base_class->subclasses[subclass]; - } else if (base_class->constants.has(subclass)) { - - Ref<GDScript> new_base_class = base_class->constants[subclass]; - if (new_base_class.is_null()) { - _set_error("Constant is not a class: " + ident, p_class); - return ERR_SCRIPT_FAILED; - } - base_class = new_base_class; - } else { - - _set_error("Could not find subclass: " + ident, p_class); - return ERR_FILE_NOT_FOUND; - } - } - - script = base_class; - - } else { - - if (p_class->extends_class.size() > 1) { - - _set_error("Invalid inheritance (unknown class+subclasses)", p_class); - return ERR_FILE_NOT_FOUND; + // Inheritance + switch (p_class->base_type.kind) { + case GDScriptParser::DataType::CLASS: { + StringName base_name = p_class->base_type.class_type->name; + // Make sure dependency is parsed first + if (!parsed_classes.has(base_name)) { + if (parsing_classes.has(base_name)) { + _set_error("Cyclic class reference for '" + String(base_name) + "'.", p_class); + return ERR_PARSE_ERROR; } - //if not found, try engine classes - if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) { - - _set_error("Unknown class: '" + base + "'", p_class); - return ERR_FILE_NOT_FOUND; - } - - int base_idx = GDScriptLanguage::get_singleton()->get_global_map()[base]; - native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx]; - if (!native.is_valid()) { - - _set_error("Global not a class: '" + base + "'", p_class); - - return ERR_FILE_NOT_FOUND; + parsing_classes.insert(base_name); + Error err = _parse_class_level(class_map[base_name].ptr(), class_map[base_name]->_owner, p_class->base_type.class_type, p_keep_state); + if (err) { + return err; } + parsing_classes.erase(base_name); } - } - - if (script.is_valid()) { - - p_script->base = script; + Ref<GDScript> base = class_map[base_name]; + p_script->base = base; p_script->_base = p_script->base.ptr(); - p_script->member_indices = script->member_indices; - - } else if (native.is_valid()) { - + p_script->member_indices = base->member_indices; + } break; + case GDScriptParser::DataType::GDSCRIPT: { + Ref<GDScript> base = p_class->base_type.script_type; + p_script->base = base; + p_script->_base = p_script->base.ptr(); + p_script->member_indices = base->member_indices; + } break; + case GDScriptParser::DataType::NATIVE: { + int native_idx = GDScriptLanguage::get_singleton()->get_global_map()[p_class->base_type.native_type]; + native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx]; + ERR_FAIL_COND_V(native.is_null(), ERR_BUG); p_script->native = native; - } else { - - _set_error("Could not determine inheritance", p_class); - return ERR_FILE_NOT_FOUND; - } - - } else { - // without extends, implicitly extend Reference - int native_idx = GDScriptLanguage::get_singleton()->get_global_map()["Reference"]; - native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx]; - ERR_FAIL_COND_V(native.is_null(), ERR_BUG); - p_script->native = native; + } break; + default: { + _set_error("Parser bug: invalid inheritance.", p_class); + return ERR_BUG; + } break; } - //print_line("Script: "+p_script->get_path()+" indices: "+itos(p_script->member_indices.size())); - for (int i = 0; i < p_class->variables.size(); i++) { StringName name = p_class->variables[i].identifier; - if (p_script->member_indices.has(name)) { - _set_error("Member '" + name + "' already exists (in current or parent class)", p_class); - return ERR_ALREADY_EXISTS; - } - if (_is_class_member_property(p_script, name)) { - _set_error("Member '" + name + "' already exists as a class property.", p_class); - return ERR_ALREADY_EXISTS; - } - if (p_class->variables[i]._export.type != Variant::NIL) { + GDScript::MemberInfo minfo; + minfo.index = p_script->member_indices.size(); + minfo.setter = p_class->variables[i].setter; + minfo.getter = p_class->variables[i].getter; + minfo.rpc_mode = p_class->variables[i].rpc_mode; + minfo.data_type = _gdtype_from_datatype(p_class->variables[i].data_type); - p_script->member_info[name] = p_class->variables[i]._export; + PropertyInfo prop_info = minfo.data_type; + prop_info.name = name; + PropertyInfo export_info = p_class->variables[i]._export; + + if (export_info.type != Variant::NIL) { + + if (!minfo.data_type.has_type) { + prop_info.type = export_info.type; + prop_info.class_name = export_info.class_name; + } + prop_info.hint = export_info.hint; + prop_info.hint_string = export_info.hint_string; + prop_info.usage = export_info.usage; #ifdef TOOLS_ENABLED if (p_class->variables[i].default_value.get_type() != Variant::NIL) { - p_script->member_default_values[name] = p_class->variables[i].default_value; } #endif } else { - - p_script->member_info[name] = PropertyInfo(Variant::NIL, name, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE); + prop_info.usage = PROPERTY_USAGE_SCRIPT_VARIABLE; } - //int new_idx = p_script->member_indices.size(); - GDScript::MemberInfo minfo; - minfo.index = p_script->member_indices.size(); - minfo.setter = p_class->variables[i].setter; - minfo.getter = p_class->variables[i].getter; - minfo.rpc_mode = p_class->variables[i].rpc_mode; - + p_script->member_info[name] = prop_info; p_script->member_indices[name] = minfo; p_script->members.insert(name); #ifdef TOOLS_ENABLED - p_script->member_lines[name] = p_class->variables[i].line; #endif } - for (int i = 0; i < p_class->constant_expressions.size(); i++) { + for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) { - StringName name = p_class->constant_expressions[i].identifier; - ERR_CONTINUE(p_class->constant_expressions[i].expression->type != GDScriptParser::Node::TYPE_CONSTANT); + StringName name = E->key(); - if (_is_class_member_property(p_script, name)) { - _set_error("Member '" + name + "' already exists as a class property.", p_class); - return ERR_ALREADY_EXISTS; - } + ERR_CONTINUE(E->get().expression->type != GDScriptParser::Node::TYPE_CONSTANT); - GDScriptParser::ConstantNode *constant = static_cast<GDScriptParser::ConstantNode *>(p_class->constant_expressions[i].expression); + GDScriptParser::ConstantNode *constant = static_cast<GDScriptParser::ConstantNode *>(E->get().expression); p_script->constants.insert(name, constant->value); -//p_script->constants[constant->value].make_const(); #ifdef TOOLS_ENABLED - p_script->member_lines[name] = p_class->constant_expressions[i].expression->line; + p_script->member_lines[name] = E->get().expression->line; #endif } @@ -1944,23 +1993,27 @@ Error GDScriptCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, cons p_script->_signals[name] = p_class->_signals[i].arguments; } + + if (p_class->name != StringName()) { + parsed_classes.insert(p_class->name); + } + //parse sub-classes for (int i = 0; i < p_class->subclasses.size(); i++) { StringName name = p_class->subclasses[i]->name; - Ref<GDScript> subclass; + Ref<GDScript> subclass = class_map[name]; - if (old_subclasses.has(name)) { - subclass = old_subclasses[name]; - } else { - subclass.instance(); + // Subclass might still be parsing, just skip it + if (!parsed_classes.has(name) && !parsing_classes.has(name)) { + parsing_classes.insert(name); + Error err = _parse_class_level(subclass.ptr(), p_script, p_class->subclasses[i], p_keep_state); + if (err) + return err; + parsing_classes.erase(name); } - Error err = _parse_class(subclass.ptr(), p_script, p_class->subclasses[i], p_keep_state); - if (err) - return err; - #ifdef TOOLS_ENABLED p_script->member_lines[name] = p_class->subclasses[i]->line; @@ -1970,6 +2023,10 @@ Error GDScriptCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, cons p_script->subclasses.insert(name, subclass); } + return OK; +} + +Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { //parse methods bool has_initializer = false; @@ -2010,44 +2067,6 @@ Error GDScriptCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, cons } #ifdef DEBUG_ENABLED - //validate setters/getters if debug is enabled - for (int i = 0; i < p_class->variables.size(); i++) { - - if (p_class->variables[i].setter) { - const Map<StringName, GDScriptFunction *>::Element *E = p_script->get_member_functions().find(p_class->variables[i].setter); - if (!E) { - _set_error("Setter function '" + String(p_class->variables[i].setter) + "' not found in class.", NULL); - err_line = p_class->variables[i].line; - err_column = 0; - return ERR_PARSE_ERROR; - } - - if (E->get()->is_static()) { - - _set_error("Setter function '" + String(p_class->variables[i].setter) + "' is static.", NULL); - err_line = p_class->variables[i].line; - err_column = 0; - return ERR_PARSE_ERROR; - } - } - if (p_class->variables[i].getter) { - const Map<StringName, GDScriptFunction *>::Element *E = p_script->get_member_functions().find(p_class->variables[i].getter); - if (!E) { - _set_error("Getter function '" + String(p_class->variables[i].getter) + "' not found in class.", NULL); - err_line = p_class->variables[i].line; - err_column = 0; - return ERR_PARSE_ERROR; - } - - if (E->get()->is_static()) { - - _set_error("Getter function '" + String(p_class->variables[i].getter) + "' is static.", NULL); - err_line = p_class->variables[i].line; - err_column = 0; - return ERR_PARSE_ERROR; - } - } - } //validate instances if keeping state @@ -2100,22 +2119,67 @@ Error GDScriptCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, cons } #endif + for (int i = 0; i < p_class->subclasses.size(); i++) { + StringName name = p_class->subclasses[i]->name; + Ref<GDScript> subclass = class_map[name]; + + Error err = _parse_class_blocks(subclass.ptr(), p_class->subclasses[i], p_keep_state); + if (err) { + return err; + } + } + p_script->valid = true; return OK; } +void GDScriptCompiler::_make_scripts(const GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { + + Map<StringName, Ref<GDScript> > old_subclasses; + + if (p_keep_state) { + old_subclasses = p_script->subclasses; + } + + for (int i = 0; i < p_class->subclasses.size(); i++) { + StringName name = p_class->subclasses[i]->name; + + Ref<GDScript> subclass; + + if (old_subclasses.has(name)) { + subclass = old_subclasses[name]; + } else { + subclass.instance(); + } + + subclass->_owner = const_cast<GDScript *>(p_script); + class_map.insert(name, subclass); + + _make_scripts(subclass.ptr(), p_class->subclasses[i], p_keep_state); + } +} + Error GDScriptCompiler::compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state) { err_line = -1; err_column = -1; error = ""; parser = p_parser; + main_script = p_script; const GDScriptParser::Node *root = parser->get_parse_tree(); ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, ERR_INVALID_DATA); source = p_script->get_path(); - Error err = _parse_class(p_script, NULL, static_cast<const GDScriptParser::ClassNode *>(root), p_keep_state); + // Create scripts for subclasses beforehand so they can be referenced + _make_scripts(p_script, static_cast<const GDScriptParser::ClassNode *>(root), p_keep_state); + + Error err = _parse_class_level(p_script, NULL, static_cast<const GDScriptParser::ClassNode *>(root), p_keep_state); + + if (err) + return err; + + err = _parse_class_blocks(p_script, static_cast<const GDScriptParser::ClassNode *>(root), p_keep_state); if (err) return err; diff --git a/modules/gdscript/gdscript_compiler.h b/modules/gdscript/gdscript_compiler.h index 237b0de9e7..55f5e2b48e 100644 --- a/modules/gdscript/gdscript_compiler.h +++ b/modules/gdscript/gdscript_compiler.h @@ -31,12 +31,17 @@ #ifndef GDSCRIPT_COMPILER_H #define GDSCRIPT_COMPILER_H +#include "core/set.h" #include "gdscript.h" #include "gdscript_parser.h" class GDScriptCompiler { const GDScriptParser *parser; + Map<StringName, Ref<GDScript> > class_map; + Set<StringName> parsed_classes; + Set<StringName> parsing_classes; + GDScript *main_script; struct CodeGen { GDScript *script; @@ -138,11 +143,15 @@ class GDScriptCompiler { bool _create_unary_operator(CodeGen &codegen, const GDScriptParser::OperatorNode *on, Variant::Operator op, int p_stack_level); bool _create_binary_operator(CodeGen &codegen, const GDScriptParser::OperatorNode *on, Variant::Operator op, int p_stack_level, bool p_initializer = false); + GDScriptDataType _gdtype_from_datatype(const GDScriptParser::DataType &p_datatype) const; + int _parse_assign_right_expression(CodeGen &codegen, const GDScriptParser::OperatorNode *p_expression, int p_stack_level); int _parse_expression(CodeGen &codegen, const GDScriptParser::Node *p_expression, int p_stack_level, bool p_root = false, bool p_initializer = false); Error _parse_block(CodeGen &codegen, const GDScriptParser::BlockNode *p_block, int p_stack_level = 0, int p_break_addr = -1, int p_continue_addr = -1); Error _parse_function(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready = false); - Error _parse_class(GDScript *p_script, GDScript *p_owner, const GDScriptParser::ClassNode *p_class, bool p_keep_state); + Error _parse_class_level(GDScript *p_script, GDScript *p_owner, const GDScriptParser::ClassNode *p_class, bool p_keep_state); + Error _parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); + void _make_scripts(const GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state); int err_line; int err_column; StringName source; diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp index c8d2d2e3e8..2e4a4c40dd 100644 --- a/modules/gdscript/gdscript_editor.cpp +++ b/modules/gdscript/gdscript_editor.cpp @@ -37,6 +37,7 @@ #include "os/file_access.h" #ifdef TOOLS_ENABLED +#include "core/reference.h" #include "editor/editor_file_system.h" #include "editor/editor_settings.h" #include "engine.h" @@ -53,21 +54,45 @@ void GDScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const { p_delimiters->push_back("' '"); } Ref<Script> GDScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const { +#ifdef TOOLS_ENABLED + bool th = EDITOR_DEF("text_editor/completion/add_type_hints", false); +#else + bool th = false; +#endif String _template = "extends %BASE%\n" "\n" "# Declare member variables here. Examples:\n" - "# var a = 2\n" - "# var b = \"text\"\n" + "# var a %INT_TYPE%= 2\n" + "# var b %STRING_TYPE%= \"text\"\n" "\n" "# Called when the node enters the scene tree for the first time.\n" - "func _ready():\n" + "func _ready()%VOID_RETURN%:\n" "%TS%pass # Replace with function body.\n" "\n" "# Called every frame. 'delta' is the elapsed time since the previous frame.\n" - "#func _process(delta):\n" + "#func _process(delta%FLOAT_TYPE%)%VOID_RETURN%:\n" "#%TS%pass\n"; +#ifdef TOOLS_ENABLED + if (EDITOR_DEF("text_editor/completion/add_type_hints", false)) { + _template = _template.replace("%INT_TYPE%", ": int "); + _template = _template.replace("%STRING_TYPE%", ": String "); + _template = _template.replace("%FLOAT_TYPE%", " : float"); + _template = _template.replace("%VOID_RETURN%", " -> void"); + } else { + _template = _template.replace("%INT_TYPE%", ""); + _template = _template.replace("%STRING_TYPE%", ""); + _template = _template.replace("%FLOAT_TYPE%", ""); + _template = _template.replace("%VOID_RETURN%", ""); + } +#else + _template = _template.replace("%INT_TYPE%", ""); + _template = _template.replace("%STRING_TYPE%", ""); + _template = _template.replace("%FLOAT_TYPE%", ""); + _template = _template.replace("%VOID_RETURN%", ""); +#endif + _template = _template.replace("%BASE%", p_base_class_name); _template = _template.replace("%TS%", _get_indentation()); @@ -91,11 +116,11 @@ void GDScriptLanguage::make_template(const String &p_class_name, const String &p p_script->set_source_code(src); } -bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const { +bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, Set<int> *r_safe_lines) const { GDScriptParser parser; - Error err = parser.parse(p_script, p_path.get_base_dir(), true, p_path); + Error err = parser.parse(p_script, p_path.get_base_dir(), true, p_path, false, r_safe_lines); if (err) { r_line_error = parser.get_error_line(); r_col_error = parser.get_error_column(); @@ -415,63 +440,34 @@ void GDScriptLanguage::get_public_constants(List<Pair<String, Variant> > *p_cons String GDScriptLanguage::make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const { +#ifdef TOOLS_ENABLED + bool th = EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints"); +#else + bool th = false; +#endif + String s = "func " + p_name + "("; if (p_args.size()) { for (int i = 0; i < p_args.size(); i++) { if (i > 0) s += ", "; s += p_args[i].get_slice(":", 0); + if (th) { + String type = p_args[i].get_slice(":", 1); + if (!type.empty() && type != "var") { + s += " : " + type; + } + } } } - s += "):\n" + _get_indentation() + "pass # Replace with function body.\n"; + s += String(")") + (th ? " -> void" : "") + ":\n" + _get_indentation() + "pass # Replace with function body.\n"; return s; } -#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) - -struct GDScriptCompletionIdentifier { - - String enumeration; - StringName obj_type; - Ref<GDScript> script; - Variant::Type type; - Variant value; //im case there is a value, also return it +//////// COMPLETION ////////// - GDScriptCompletionIdentifier() : - type(Variant::NIL) {} -}; - -static GDScriptCompletionIdentifier _get_type_from_variant(const Variant &p_variant, bool p_allow_gdnative_class = false) { - - GDScriptCompletionIdentifier t; - t.type = p_variant.get_type(); - t.value = p_variant; - if (p_variant.get_type() == Variant::OBJECT) { - Object *obj = p_variant; - if (obj) { - - if (p_allow_gdnative_class && Object::cast_to<GDScriptNativeClass>(obj)) { - t.obj_type = Object::cast_to<GDScriptNativeClass>(obj)->get_name(); - t.value = Variant(); - } else { - - t.obj_type = obj->get_class(); - } - } - } - return t; -} - -static GDScriptCompletionIdentifier _get_type_from_pinfo(const PropertyInfo &p_info) { - - GDScriptCompletionIdentifier t; - t.type = p_info.type; - if (p_info.hint == PROPERTY_HINT_RESOURCE_TYPE) { - t.obj_type = p_info.hint_string; - } - return t; -} +#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) struct GDScriptCompletionContext { @@ -480,1043 +476,1612 @@ struct GDScriptCompletionContext { const GDScriptParser::BlockNode *block; Object *base; String base_path; -}; - -static Ref<Reference> _get_parent_class(GDScriptCompletionContext &context) { - - if (context._class->extends_used) { - //do inheritance - String path = context._class->extends_file; - - Ref<GDScript> script; - Ref<GDScriptNativeClass> native; + int line; - if (path != "") { - //path (and optionally subclasses) - - if (path.is_rel_path()) { - - path = context.base_path.plus_file(path); - } - - if (ScriptCodeCompletionCache::get_singleton()) - script = ScriptCodeCompletionCache::get_singleton()->get_cached_resource(path); - else - script = ResourceLoader::load(path); + GDScriptCompletionContext() : + _class(NULL), + function(NULL), + block(NULL), + base(NULL) {} +}; - if (script.is_null()) { - return REF(); - } - if (!script->is_valid()) { +struct GDScriptCompletionIdentifier { + GDScriptParser::DataType type; + String enumeration; + Variant value; + const GDScriptParser::Node *assigned_expression; - return REF(); - } - //print_line("EXTENDS PATH: "+path+" script is "+itos(script.is_valid())+" indices is "+itos(script->member_indices.size())+" valid? "+itos(script->valid)); + GDScriptCompletionIdentifier() : + assigned_expression(NULL) {} +}; - if (context._class->extends_class.size()) { +static void _get_directory_contents(EditorFileSystemDirectory *p_dir, Set<String> &r_list) { - for (int i = 0; i < context._class->extends_class.size(); i++) { + for (int i = 0; i < p_dir->get_file_count(); i++) { + r_list.insert("\"" + p_dir->get_file_path(i) + "\""); + } - String sub = context._class->extends_class[i]; - if (script->get_subclasses().has(sub)) { + for (int i = 0; i < p_dir->get_subdir_count(); i++) { + _get_directory_contents(p_dir->get_subdir(i), r_list); + } +} - script = script->get_subclasses()[sub]; - } else { +static String _get_visual_datatype(const PropertyInfo &p_info, bool p_isarg = true) { - return REF(); - } - } - } + if (p_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) { + String enum_name = p_info.class_name; + if (enum_name.find(".") == -1) { + return enum_name; + } + return enum_name.get_slice(".", 1); + } - if (script.is_valid()) - return script; + String n = p_info.name; + int idx = n.find(":"); + if (idx != -1) { + return n.substr(idx + 1, n.length()); + } + if (p_info.type == Variant::OBJECT) { + if (p_info.hint == PROPERTY_HINT_RESOURCE_TYPE) { + return p_info.hint_string; } else { + return p_info.class_name.operator String(); + } + } + if (p_info.type == Variant::NIL) { + if (p_isarg || (p_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) { + return "var"; + } else { + return "void"; + } + } - if (context._class->extends_class.size() == 0) { - ERR_PRINT("BUG"); - return REF(); - } - - String base = context._class->extends_class[0]; - - if (context._class->extends_class.size() > 1) { - - return REF(); - } - //if not found, try engine classes - if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) { + return Variant::get_type_name(p_info.type); +} - return REF(); +static GDScriptCompletionIdentifier _type_from_variant(const Variant &p_value) { + GDScriptCompletionIdentifier ci; + ci.value = p_value; + ci.type.is_constant = true; + ci.type.has_type = true; + ci.type.kind = GDScriptParser::DataType::BUILTIN; + ci.type.builtin_type = p_value.get_type(); + + if (ci.type.builtin_type == Variant::OBJECT) { + Object *obj = p_value.operator Object *(); + if (!obj) { + return ci; + } + ci.type.native_type = obj->get_class_name(); + Ref<Script> scr = p_value; + if (scr.is_valid()) { + ci.type.is_meta_type = true; + } else { + ci.type.is_meta_type = false; + scr = obj->get_script(); + } + if (scr.is_valid()) { + ci.type.script_type = scr; + Ref<GDScript> gds = scr; + if (gds.is_valid()) { + ci.type.kind = GDScriptParser::DataType::GDSCRIPT; + } else { + ci.type.kind = GDScriptParser::DataType::SCRIPT; } - - int base_idx = GDScriptLanguage::get_singleton()->get_global_map()[base]; - native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx]; - return native; + ci.type.native_type = scr->get_instance_base_type(); + } else { + ci.type.kind = GDScriptParser::DataType::NATIVE; } } - return Ref<Reference>(); + return ci; } -static GDScriptCompletionIdentifier _get_native_class(GDScriptCompletionContext &context) { +static GDScriptCompletionIdentifier _type_from_property(const PropertyInfo &p_property) { + GDScriptCompletionIdentifier ci; - GDScriptCompletionIdentifier id; - - REF pc = _get_parent_class(context); - if (!pc.is_valid()) { - return id; + if (p_property.type == Variant::NIL) { + // Variant + return ci; } - Ref<GDScriptNativeClass> nc = pc; - Ref<GDScript> s = pc; - if (s.is_null() && nc.is_null()) { - return id; - } - while (!s.is_null()) { - nc = s->get_native(); - s = s->get_base(); - } - if (nc.is_null()) { - return id; + if (p_property.usage & PROPERTY_USAGE_CLASS_IS_ENUM) { + ci.enumeration = p_property.class_name; } - id.type = Variant::OBJECT; - if (context.base) - id.value = context.base; - id.obj_type = nc->get_name(); - return id; + ci.type.has_type = true; + ci.type.builtin_type = p_property.type; + if (p_property.type == Variant::OBJECT) { + ci.type.kind = GDScriptParser::DataType::NATIVE; + ci.type.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name; + } else { + ci.type.kind = GDScriptParser::DataType::BUILTIN; + } + return ci; } -static bool _guess_identifier_type(GDScriptCompletionContext &context, int p_line, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type, bool p_for_indexing); - -static bool _guess_expression_type(GDScriptCompletionContext &context, const GDScriptParser::Node *p_node, int p_line, GDScriptCompletionIdentifier &r_type, bool p_for_indexing = false) { - - if (p_node->type == GDScriptParser::Node::TYPE_CONSTANT) { - - const GDScriptParser::ConstantNode *cn = static_cast<const GDScriptParser::ConstantNode *>(p_node); +static GDScriptCompletionIdentifier _type_from_gdtype(const GDScriptDataType &p_gdtype) { + GDScriptCompletionIdentifier ci; + if (!p_gdtype.has_type) { + return ci; + } - r_type = _get_type_from_variant(cn->value); + ci.type.has_type = true; + ci.type.builtin_type = p_gdtype.builtin_type; + ci.type.native_type = p_gdtype.native_type; + ci.type.script_type = p_gdtype.script_type; - return true; - } else if (p_node->type == GDScriptParser::Node::TYPE_DICTIONARY) { - - r_type.type = Variant::DICTIONARY; + switch (p_gdtype.kind) { + case GDScriptDataType::BUILTIN: { + ci.type.kind = GDScriptParser::DataType::BUILTIN; + } break; + case GDScriptDataType::NATIVE: { + ci.type.kind = GDScriptParser::DataType::NATIVE; + } break; + case GDScriptDataType::GDSCRIPT: { + ci.type.kind = GDScriptParser::DataType::GDSCRIPT; + } break; + case GDScriptDataType::SCRIPT: { + ci.type.kind = GDScriptParser::DataType::SCRIPT; + } break; + } + return ci; +} - //what the heck, fill it anyway - const GDScriptParser::DictionaryNode *an = static_cast<const GDScriptParser::DictionaryNode *>(p_node); - Dictionary d; - for (int i = 0; i < an->elements.size(); i++) { - GDScriptCompletionIdentifier k; - if (_guess_expression_type(context, an->elements[i].key, p_line, k) && k.value.get_type() != Variant::NIL) { - GDScriptCompletionIdentifier v; - if (_guess_expression_type(context, an->elements[i].value, p_line, v)) { - d[k.value] = v.value; +static bool _guess_identifier_type(const GDScriptCompletionContext &p_context, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type); +static bool _guess_identifier_type_from_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type); +static bool _guess_method_return_type_from_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, GDScriptCompletionIdentifier &r_type); + +static bool _guess_expression_type(const GDScriptCompletionContext &p_context, const GDScriptParser::Node *p_expression, GDScriptCompletionIdentifier &r_type) { + bool found = false; + switch (p_expression->type) { + case GDScriptParser::Node::TYPE_CONSTANT: { + const GDScriptParser::ConstantNode *cn = static_cast<const GDScriptParser::ConstantNode *>(p_expression); + r_type = _type_from_variant(cn->value); + found = true; + } break; + case GDScriptParser::Node::TYPE_SELF: { + if (p_context._class) { + r_type.type.has_type = true; + r_type.type.kind = GDScriptParser::DataType::CLASS; + r_type.type.class_type = const_cast<GDScriptParser::ClassNode *>(p_context._class); + r_type.type.is_constant = true; + r_type.value = p_context.base; + found = true; + } + } break; + case GDScriptParser::Node::TYPE_IDENTIFIER: { + const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(p_expression); + found = _guess_identifier_type(p_context, id->name, r_type); + } break; + case GDScriptParser::Node::TYPE_DICTIONARY: { + // Try to recreate the dictionary + const GDScriptParser::DictionaryNode *dn = static_cast<const GDScriptParser::DictionaryNode *>(p_expression); + Dictionary d; + bool full = true; + for (int i = 0; i < dn->elements.size(); i++) { + GDScriptCompletionIdentifier key; + if (_guess_expression_type(p_context, dn->elements[i].key, key)) { + GDScriptCompletionIdentifier value; + if (_guess_expression_type(p_context, dn->elements[i].value, value)) { + if (!value.type.is_constant) { + full = false; + break; + } + d[key.value] = value.value; + } else { + full = false; + break; + } + } else { + full = false; + break; } } - } - r_type.value = d; - return true; - } else if (p_node->type == GDScriptParser::Node::TYPE_ARRAY) { - - r_type.type = Variant::ARRAY; - //what the heck, fill it anyway - const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(p_node); - Array arr; - arr.resize(an->elements.size()); - for (int i = 0; i < an->elements.size(); i++) { - GDScriptCompletionIdentifier ci; - if (_guess_expression_type(context, an->elements[i], p_line, ci)) { - arr[i] = ci.value; + if (full) { + // If not fully constant, setting this value is detrimental to the inference + r_type.value = d; + r_type.type.is_constant = true; } - } - r_type.value = arr; - return true; - - } else if (p_node->type == GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION) { - - MethodInfo mi = GDScriptFunctions::get_info(static_cast<const GDScriptParser::BuiltInFunctionNode *>(p_node)->function); - r_type = _get_type_from_pinfo(mi.return_val); - - return true; - } else if (p_node->type == GDScriptParser::Node::TYPE_IDENTIFIER) { - - return _guess_identifier_type(context, p_line - 1, static_cast<const GDScriptParser::IdentifierNode *>(p_node)->name, r_type, p_for_indexing); - } else if (p_node->type == GDScriptParser::Node::TYPE_SELF) { - //eeh... - - r_type = _get_native_class(context); - return r_type.type != Variant::NIL; - - } else if (p_node->type == GDScriptParser::Node::TYPE_OPERATOR) { - - const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(p_node); - if (op->op == GDScriptParser::OperatorNode::OP_CALL) { - - if (op->arguments[0]->type == GDScriptParser::Node::TYPE_TYPE) { - - const GDScriptParser::TypeNode *tn = static_cast<const GDScriptParser::TypeNode *>(op->arguments[0]); - r_type.type = tn->vtype; - return true; - } else if (op->arguments[0]->type == GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION) { - - const GDScriptParser::BuiltInFunctionNode *bin = static_cast<const GDScriptParser::BuiltInFunctionNode *>(op->arguments[0]); - return _guess_expression_type(context, bin, p_line, r_type); - - } else if (op->arguments.size() > 1 && op->arguments[1]->type == GDScriptParser::Node::TYPE_IDENTIFIER) { - - StringName id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1])->name; - - if (op->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER && String(id) == "new") { - - //shortcut - StringName identifier = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0])->name; - - if (ClassDB::class_exists(identifier)) { - r_type.type = Variant::OBJECT; - r_type.value = Variant(); - r_type.obj_type = identifier; - return true; - } + r_type.type.has_type = true; + r_type.type.kind = GDScriptParser::DataType::BUILTIN; + r_type.type.builtin_type = Variant::DICTIONARY; + } break; + case GDScriptParser::Node::TYPE_ARRAY: { + // Try to recreate the array + const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(p_expression); + Array a; + bool full = true; + a.resize(an->elements.size()); + for (int i = 0; i < an->elements.size(); i++) { + GDScriptCompletionIdentifier value; + if (_guess_expression_type(p_context, an->elements[i], value)) { + a[i] = value.value; + } else { + full = false; + break; } - - GDScriptCompletionIdentifier base; - if (!_guess_expression_type(context, op->arguments[0], p_line, base)) - return false; - - if (base.type == Variant::OBJECT) { - - if (id.operator String() == "new" && base.value.get_type() == Variant::OBJECT) { - - Object *obj = base.value; - if (obj && Object::cast_to<GDScriptNativeClass>(obj)) { - GDScriptNativeClass *gdnc = Object::cast_to<GDScriptNativeClass>(obj); - r_type.type = Variant::OBJECT; - r_type.value = Variant(); - r_type.obj_type = gdnc->get_name(); - return true; - } else { - - if (base.obj_type != StringName()) { - - r_type.type = Variant::OBJECT; - r_type.value = Variant(); - r_type.obj_type = base.obj_type; - return true; - } + } + if (full) { + // If not fully constant, setting this value is detrimental to the inference + r_type.value = a; + } + r_type.type.has_type = true; + r_type.type.kind = GDScriptParser::DataType::BUILTIN; + r_type.type.builtin_type = Variant::ARRAY; + } break; + case GDScriptParser::Node::TYPE_OPERATOR: { + const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(p_expression); + switch (op->op) { + case GDScriptParser::OperatorNode::OP_CALL: { + if (op->arguments[0]->type == GDScriptParser::Node::TYPE_TYPE) { + const GDScriptParser::TypeNode *tn = static_cast<const GDScriptParser::TypeNode *>(op->arguments[0]); + r_type.type.has_type = true; + r_type.type.kind = GDScriptParser::DataType::BUILTIN; + r_type.type.builtin_type = tn->vtype; + found = true; + break; + } else if (op->arguments[0]->type == GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION) { + const GDScriptParser::BuiltInFunctionNode *bin = static_cast<const GDScriptParser::BuiltInFunctionNode *>(op->arguments[0]); + MethodInfo mi = GDScriptFunctions::get_info(bin->function); + r_type = _type_from_property(mi.return_val); + found = true; + break; + } else if (op->arguments.size() >= 2 && op->arguments[1]->type == GDScriptParser::Node::TYPE_IDENTIFIER) { + StringName id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1])->name; + + GDScriptCompletionContext c = p_context; + c.line = op->line; + + GDScriptCompletionIdentifier base; + if (!_guess_expression_type(c, op->arguments[0], base)) { + found = false; + break; } - } - if (ClassDB::has_method(base.obj_type, id)) { - -#ifdef TOOLS_ENABLED - MethodBind *mb = ClassDB::get_method(base.obj_type, id); - PropertyInfo pi = mb->get_return_info(); + // Try call if constant methods with constant arguments + if (base.type.is_constant && base.value.get_type() == Variant::OBJECT) { + GDScriptParser::DataType native_type = base.type; - //try calling the function if constant and all args are constant, should not crash.. - Object *baseptr = base.value; - - if (mb->is_const() && pi.type == Variant::OBJECT) { - - bool all_valid = true; - Vector<Variant> args; - for (int i = 2; i < op->arguments.size(); i++) { - GDScriptCompletionIdentifier arg; + while (native_type.kind == GDScriptParser::DataType::CLASS) { + native_type = native_type.class_type->base_type; + } - if (_guess_expression_type(context, op->arguments[i], p_line, arg)) { - if (arg.value.get_type() != Variant::NIL && arg.value.get_type() != Variant::OBJECT) { // calling with object seems dangerous, i don' t know - args.push_back(arg.value); + while (native_type.kind == GDScriptParser::DataType::GDSCRIPT || native_type.kind == GDScriptParser::DataType::SCRIPT) { + if (native_type.script_type.is_valid()) { + Ref<Script> parent = native_type.script_type->get_base_script(); + if (parent.is_valid()) { + native_type.script_type = parent; } else { - all_valid = false; - break; + native_type.kind = GDScriptParser::DataType::NATIVE; + native_type.native_type = native_type.script_type->get_instance_base_type(); + if (!ClassDB::class_exists(native_type.native_type)) { + native_type.native_type = String("_") + native_type.native_type; + if (!ClassDB::class_exists(native_type.native_type)) { + native_type.has_type = false; + } + } } - } else { - all_valid = false; } } - if (all_valid && String(id) == "get_node" && ClassDB::is_parent_class(base.obj_type, "Node") && args.size()) { - - String arg1 = args[0]; - if (arg1.begins_with("/root/")) { - String which = arg1.get_slice("/", 2); - if (which != "") { - List<PropertyInfo> props; - ProjectSettings::get_singleton()->get_property_list(&props); - //print_line("find singleton"); - - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - - String s = E->get().name; - if (!s.begins_with("autoload/")) - continue; - //print_line("found "+s); - String name = s.get_slice("/", 1); - //print_line("name: "+name+", which: "+which); - if (name == which) { - String script = ProjectSettings::get_singleton()->get(s); - - if (!script.begins_with("res://")) { - script = "res://" + script; - } - - if (!script.ends_with(".gd")) { - //not a script, try find the script anyway, - //may have some success - script = script.get_basename() + ".gd"; - } - - if (FileAccess::exists(script)) { - - //print_line("is a script"); - - Ref<Script> scr; - if (ScriptCodeCompletionCache::get_singleton()) - scr = ScriptCodeCompletionCache::get_singleton()->get_cached_resource(script); - else - scr = ResourceLoader::load(script); - - r_type.obj_type = "Node"; - r_type.type = Variant::OBJECT; - r_type.script = scr; - r_type.value = Variant(); - - return true; - } + if (native_type.has_type && native_type.kind == GDScriptParser::DataType::NATIVE) { + MethodBind *mb = ClassDB::get_method(native_type.native_type, id); + if (mb && mb->is_const()) { + bool all_is_const = true; + Vector<Variant> args; + GDScriptCompletionContext c = p_context; + c.line = op->line; + for (int i = 2; all_is_const && i < op->arguments.size(); i++) { + GDScriptCompletionIdentifier arg; + + if (_guess_expression_type(c, op->arguments[i], arg)) { + if (arg.type.has_type && arg.type.is_constant && arg.value.get_type() != Variant::OBJECT) { + args.push_back(arg.value); + } else { + all_is_const = false; } + } else { + all_is_const = false; } } - } - } - if (baseptr) { - - if (all_valid) { - Vector<const Variant *> argptr; - for (int i = 0; i < args.size(); i++) { - argptr.push_back(&args[i]); + Object *baseptr = base.value; + + if (all_is_const && String(id) == "get_node" && ClassDB::is_parent_class(native_type.native_type, "Node") && args.size()) { + + String arg1 = args[0]; + if (arg1.begins_with("/root/")) { + String which = arg1.get_slice("/", 2); + if (which != "") { + // Try singletons first + if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(which)) { + r_type = _type_from_variant(GDScriptLanguage::get_singleton()->get_named_globals_map()[which]); + found = true; + } else { + List<PropertyInfo> props; + ProjectSettings::get_singleton()->get_property_list(&props); + + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + + String s = E->get().name; + if (!s.begins_with("autoload/")) { + continue; + } + String name = s.get_slice("/", 1); + if (name == which) { + String script = ProjectSettings::get_singleton()->get(s); + + if (script.begins_with("*")) { + script = script.right(1); + } + + if (!script.begins_with("res://")) { + script = "res://" + script; + } + + if (!script.ends_with(".gd")) { + //not a script, try find the script anyway, + //may have some success + script = script.get_basename() + ".gd"; + } + + if (FileAccess::exists(script)) { + Ref<Script> scr; + if (ScriptCodeCompletionCache::get_singleton()) { + scr = ScriptCodeCompletionCache::get_singleton()->get_cached_resource(script); + } else { + scr = ResourceLoader::load(script); + } + if (scr.is_valid()) { + r_type.type.has_type = true; + r_type.type.script_type = scr; + r_type.type.is_constant = false; + Ref<GDScript> gds = scr; + if (gds.is_valid()) { + r_type.type.kind = GDScriptParser::DataType::GDSCRIPT; + } else { + r_type.type.kind = GDScriptParser::DataType::SCRIPT; + } + r_type.value = Variant(); + found = true; + } + } + break; + } + } + } + } + } } - Variant::CallError ce; - Variant ret = mb->call(baseptr, (const Variant **)argptr.ptr(), argptr.size(), ce); - - if (ce.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) { + if (!found && all_is_const && baseptr) { + Vector<const Variant *> argptr; + for (int i = 0; i < args.size(); i++) { + argptr.push_back(&args[i]); + } - if (ret.get_type() != Variant::OBJECT || ret.operator Object *() != NULL) { + Variant::CallError ce; + Variant ret = mb->call(baseptr, (const Variant **)argptr.ptr(), argptr.size(), ce); - r_type = _get_type_from_variant(ret); - return true; + if (ce.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) { + if (ret.get_type() != Variant::OBJECT || ret.operator Object *() != NULL) { + r_type = _type_from_variant(ret); + found = true; + } } } } } } - r_type.type = pi.type; - if (pi.hint == PROPERTY_HINT_RESOURCE_TYPE) { - r_type.obj_type = pi.hint_string; + if (!found) { + found = _guess_method_return_type_from_base(c, base, id, r_type); } - - return true; -#else - return false; -#endif - } else { - return false; } - } else { - //method for some variant.. - Variant::CallError ce; - Variant v = Variant::construct(base.type, NULL, 0, ce); - List<MethodInfo> mi; - v.get_method_list(&mi); - for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { - - if (!E->get().name.begins_with("_") && E->get().name == id.operator String()) { - - MethodInfo mi = E->get(); - r_type.type = mi.return_val.type; - if (mi.return_val.hint == PROPERTY_HINT_RESOURCE_TYPE) { - r_type.obj_type = mi.return_val.hint_string; - } - return true; - } + } break; + case GDScriptParser::OperatorNode::OP_PARENT_CALL: { + if (!p_context._class || !op->arguments.size() || op->arguments[0]->type != GDScriptParser::Node::TYPE_IDENTIFIER) { + break; } - } - } - } else if (op->op == GDScriptParser::OperatorNode::OP_INDEX || op->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED) { - GDScriptCompletionIdentifier p1; - GDScriptCompletionIdentifier p2; + StringName id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0])->name; - if (op->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED) { + GDScriptCompletionIdentifier base; + base.value = p_context.base; + base.type = p_context._class->base_type; - if (op->arguments[1]->type == GDScriptParser::Node::TYPE_IDENTIFIER) { - String id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1])->name; - p2.type = Variant::STRING; - p2.value = id; - } + GDScriptCompletionContext c = p_context; + c.line = op->line; - } else { - if (op->arguments[1]) { - if (!_guess_expression_type(context, op->arguments[1], p_line, p2)) { - - return false; + found = _guess_method_return_type_from_base(c, base, id, r_type); + } break; + case GDScriptParser::OperatorNode::OP_INDEX_NAMED: { + if (op->arguments.size() < 2 || op->arguments[1]->type != GDScriptParser::Node::TYPE_IDENTIFIER) { + found = false; + break; } - } - } - - if (op->arguments[0]->type == GDScriptParser::Node::TYPE_ARRAY) { - - const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(op->arguments[0]); - if (p2.value.is_num()) { - int index = p2.value; - if (index < 0 || index >= an->elements.size()) - return false; - return _guess_expression_type(context, an->elements[index], p_line, r_type); - } - - } else if (op->arguments[0]->type == GDScriptParser::Node::TYPE_DICTIONARY) { - - const GDScriptParser::DictionaryNode *dn = static_cast<const GDScriptParser::DictionaryNode *>(op->arguments[0]); + const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1]); - if (p2.value.get_type() == Variant::NIL) - return false; - - for (int i = 0; i < dn->elements.size(); i++) { - - GDScriptCompletionIdentifier k; + GDScriptCompletionContext c = p_context; + c.line = op->line; - if (!_guess_expression_type(context, dn->elements[i].key, p_line, k)) { - - return false; + GDScriptCompletionIdentifier base; + if (!_guess_expression_type(c, op->arguments[0], base)) { + found = false; + break; } - if (k.value.get_type() == Variant::NIL) - return false; + if (base.value.get_type() == Variant::DICTIONARY && base.value.operator Dictionary().has(String(id->name))) { + Variant value = base.value.operator Dictionary()[String(id->name)]; + r_type = _type_from_variant(value); + found = true; + break; + } - if (k.value == p2.value) { + const GDScriptParser::DictionaryNode *dn = NULL; + if (op->arguments[0]->type == GDScriptParser::Node::TYPE_DICTIONARY) { + dn = static_cast<const GDScriptParser::DictionaryNode *>(op->arguments[0]); + } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::TYPE_DICTIONARY) { + dn = static_cast<const GDScriptParser::DictionaryNode *>(base.assigned_expression); + } - return _guess_expression_type(context, dn->elements[i].value, p_line, r_type); + if (dn) { + for (int i = 0; i < dn->elements.size(); i++) { + GDScriptCompletionIdentifier key; + if (!_guess_expression_type(c, dn->elements[i].key, key)) { + continue; + } + if (key.value == String(id->name)) { + r_type.assigned_expression = dn->elements[i].value; + found = _guess_expression_type(c, dn->elements[i].value, r_type); + break; + } + } } - } - } else { + if (!found) { + found = _guess_identifier_type_from_base(c, base, id->name, r_type); + } + } break; + case GDScriptParser::OperatorNode::OP_INDEX: { + if (op->arguments.size() < 2) { + found = false; + break; + } - if (op->arguments[0]) { - if (!_guess_expression_type(context, op->arguments[0], p_line, p1)) { + GDScriptCompletionContext c = p_context; + c.line = op->line; - return false; + GDScriptCompletionIdentifier base; + if (!_guess_expression_type(c, op->arguments[0], base)) { + found = false; + break; } - } - if (p1.value.get_type() == Variant::OBJECT) { - //?? - - if (p1.obj_type != StringName() && p2.type == Variant::STRING) { + GDScriptCompletionIdentifier index; + if (!_guess_expression_type(c, op->arguments[1], index)) { + found = false; + break; + } - StringName base_type = p1.obj_type; + if (base.value.in(index.value)) { + Variant value = base.value.get(index.value); + r_type = _type_from_variant(value); + found = true; + break; + } - if (p1.obj_type == "GDScriptNativeClass") { - //native enum - Ref<GDScriptNativeClass> gdn = p1.value; - if (gdn.is_valid()) { + // Look if it is a dictionary node + const GDScriptParser::DictionaryNode *dn = NULL; + if (op->arguments[0]->type == GDScriptParser::Node::TYPE_DICTIONARY) { + dn = static_cast<const GDScriptParser::DictionaryNode *>(op->arguments[0]); + } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::TYPE_DICTIONARY) { + dn = static_cast<const GDScriptParser::DictionaryNode *>(base.assigned_expression); + } - base_type = gdn->get_name(); + if (dn) { + for (int i = 0; i < dn->elements.size(); i++) { + GDScriptCompletionIdentifier key; + if (!_guess_expression_type(c, dn->elements[i].key, key)) { + continue; } - } - StringName index = p2.value; - bool valid; - Variant::Type t = ClassDB::get_property_type(base_type, index, &valid); - if (t != Variant::NIL && valid) { - r_type.type = t; - if (t == Variant::INT || t == Variant::OBJECT) { -//check for enum! -#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) - - StringName getter = ClassDB::get_property_getter(base_type, index); - if (getter != StringName()) { - MethodBind *mb = ClassDB::get_method(base_type, getter); - if (mb) { - PropertyInfo rt = mb->get_return_info(); - if ((rt.usage & PROPERTY_USAGE_CLASS_IS_ENUM) && t == Variant::INT) { - r_type.enumeration = rt.class_name; - } else if (t == Variant::OBJECT) { - - r_type.obj_type = rt.class_name; - } - } - } -#endif + if (key.value == index.value) { + r_type.assigned_expression = dn->elements[i].value; + found = _guess_expression_type(p_context, dn->elements[i].value, r_type); + break; } - - return true; } } - } else if (p1.value.get_type() != Variant::NIL) { - bool valid; - Variant ret = p1.value.get(p2.value, &valid); - if (valid) { - r_type = _get_type_from_variant(ret); - return true; + // Look if it is an array node + if (!found && index.value.is_num()) { + int idx = index.value; + const GDScriptParser::ArrayNode *an = NULL; + if (op->arguments[0]->type == GDScriptParser::Node::TYPE_ARRAY) { + an = static_cast<const GDScriptParser::ArrayNode *>(op->arguments[0]); + } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::TYPE_ARRAY) { + an = static_cast<const GDScriptParser::ArrayNode *>(base.assigned_expression); + } + + if (an && idx >= 0 && an->elements.size() > idx) { + r_type.assigned_expression = an->elements[idx]; + found = _guess_expression_type(c, an->elements[idx], r_type); + break; + } } - } else { - if (p1.type != Variant::NIL) { - Variant::CallError ce; - Variant base = Variant::construct(p1.type, NULL, 0, ce); - bool valid; - Variant ret = base.get(p2.value, &valid); + // Look for valid indexing in other types + if (!found && (index.value.get_type() == Variant::STRING || index.value.get_type() == Variant::NODE_PATH)) { + StringName id = index.value; + found = _guess_identifier_type_from_base(c, base, id, r_type); + } else if (!found && index.type.kind == GDScriptParser::DataType::BUILTIN) { + Variant::CallError err; + Variant base_val = Variant::construct(base.type.builtin_type, NULL, 0, err); + bool valid = false; + Variant res = base_val.get(index.value, &valid); if (valid) { - r_type = _get_type_from_variant(ret); - return true; + r_type = _type_from_variant(res); + r_type.value = Variant(); + r_type.type.is_constant = false; + found = true; } } - } - } + } break; + default: { + if (op->arguments.size() < 2) { + found = false; + break; + } - } else { + Variant::Operator vop = Variant::OP_MAX; + switch (op->op) { + case GDScriptParser::OperatorNode::OP_ADD: vop = Variant::OP_ADD; break; + case GDScriptParser::OperatorNode::OP_SUB: vop = Variant::OP_SUBTRACT; break; + case GDScriptParser::OperatorNode::OP_MUL: vop = Variant::OP_MULTIPLY; break; + case GDScriptParser::OperatorNode::OP_DIV: vop = Variant::OP_DIVIDE; break; + case GDScriptParser::OperatorNode::OP_MOD: vop = Variant::OP_MODULE; break; + case GDScriptParser::OperatorNode::OP_SHIFT_LEFT: vop = Variant::OP_SHIFT_LEFT; break; + case GDScriptParser::OperatorNode::OP_SHIFT_RIGHT: vop = Variant::OP_SHIFT_RIGHT; break; + case GDScriptParser::OperatorNode::OP_BIT_AND: vop = Variant::OP_BIT_AND; break; + case GDScriptParser::OperatorNode::OP_BIT_OR: vop = Variant::OP_BIT_OR; break; + case GDScriptParser::OperatorNode::OP_BIT_XOR: vop = Variant::OP_BIT_XOR; break; + default: {} + } - Variant::Operator vop = Variant::OP_MAX; - switch (op->op) { - case GDScriptParser::OperatorNode::OP_ADD: vop = Variant::OP_ADD; break; - case GDScriptParser::OperatorNode::OP_SUB: vop = Variant::OP_SUBTRACT; break; - case GDScriptParser::OperatorNode::OP_MUL: vop = Variant::OP_MULTIPLY; break; - case GDScriptParser::OperatorNode::OP_DIV: vop = Variant::OP_DIVIDE; break; - case GDScriptParser::OperatorNode::OP_MOD: vop = Variant::OP_MODULE; break; - case GDScriptParser::OperatorNode::OP_SHIFT_LEFT: vop = Variant::OP_SHIFT_LEFT; break; - case GDScriptParser::OperatorNode::OP_SHIFT_RIGHT: vop = Variant::OP_SHIFT_RIGHT; break; - case GDScriptParser::OperatorNode::OP_BIT_AND: vop = Variant::OP_BIT_AND; break; - case GDScriptParser::OperatorNode::OP_BIT_OR: vop = Variant::OP_BIT_OR; break; - case GDScriptParser::OperatorNode::OP_BIT_XOR: vop = Variant::OP_BIT_XOR; break; - default: {} - } - - if (vop == Variant::OP_MAX) - return false; + if (vop == Variant::OP_MAX) { + break; + } - GDScriptCompletionIdentifier p1; - GDScriptCompletionIdentifier p2; + GDScriptCompletionContext context = p_context; + context.line = op->line; - if (op->arguments[0]) { - if (!_guess_expression_type(context, op->arguments[0], p_line, p1)) { + GDScriptCompletionIdentifier p1; + GDScriptCompletionIdentifier p2; - return false; - } - } + if (!_guess_expression_type(context, op->arguments[0], p1)) { + found = false; + break; + } - if (op->arguments.size() > 1) { - if (!_guess_expression_type(context, op->arguments[1], p_line, p2)) { + if (!_guess_expression_type(context, op->arguments[1], p2)) { + found = false; + break; + } - return false; - } - } + Variant::CallError ce; + bool v1_use_value = p1.value.get_type() != Variant::NIL && p1.value.get_type() != Variant::OBJECT; + Variant v1 = (v1_use_value) ? p1.value : Variant::construct(p1.type.builtin_type, NULL, 0, ce); + bool v2_use_value = p2.value.get_type() != Variant::NIL && p2.value.get_type() != Variant::OBJECT; + Variant v2 = (v2_use_value) ? p2.value : Variant::construct(p2.type.builtin_type, NULL, 0, ce); + // avoid potential invalid ops + if ((vop == Variant::OP_DIVIDE || vop == Variant::OP_MODULE) && v2.get_type() == Variant::INT) { + v2 = 1; + v2_use_value = false; + } + if (vop == Variant::OP_DIVIDE && v2.get_type() == Variant::REAL) { + v2 = 1.0; + v2_use_value = false; + } - Variant::CallError ce; - bool v1_use_value = p1.value.get_type() != Variant::NIL && p1.value.get_type() != Variant::OBJECT; - Variant v1 = (v1_use_value) ? p1.value : Variant::construct(p1.type, NULL, 0, ce); - bool v2_use_value = p2.value.get_type() != Variant::NIL && p2.value.get_type() != Variant::OBJECT; - Variant v2 = (v2_use_value) ? p2.value : Variant::construct(p2.type, NULL, 0, ce); - // avoid potential invalid ops - if ((vop == Variant::OP_DIVIDE || vop == Variant::OP_MODULE) && v2.get_type() == Variant::INT) { - v2 = 1; - v2_use_value = false; - } - if (vop == Variant::OP_DIVIDE && v2.get_type() == Variant::REAL) { - v2 = 1.0; - v2_use_value = false; + Variant res; + bool valid; + Variant::evaluate(vop, v1, v2, res, valid); + if (!valid) { + found = false; + break; + } + r_type = _type_from_variant(res); + if (!v1_use_value || !v2_use_value) { + r_type.value = Variant(); + r_type.type.is_constant = false; + } + + found = true; + } break; } + } break; + } - Variant r; - bool valid; - Variant::evaluate(vop, v1, v2, r, valid); - if (!valid) - return false; - r_type.type = r.get_type(); - if (v1_use_value && v2_use_value) - r_type.value = r; + // It may have found a null, but that's never useful + if (found && r_type.type.has_type && r_type.type.kind == GDScriptParser::DataType::BUILTIN && r_type.type.builtin_type == Variant::NIL) { + found = false; + } - return true; + // Check type hint last. For collections we want chance to get the actual value first + // This way we can detect types from the content of dictionaries and arrays + if (!found && p_expression->get_datatype().has_type) { + r_type.type = p_expression->get_datatype(); + if (!r_type.assigned_expression) { + r_type.assigned_expression = p_expression; } + found = true; } - return false; + return found; } -static bool _guess_identifier_type_in_block(GDScriptCompletionContext &context, int p_line, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type) { +static bool _guess_identifier_type(const GDScriptCompletionContext &p_context, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type) { - if (context.block->if_condition && context.block->if_condition->type == GDScriptParser::Node::TYPE_OPERATOR && static_cast<const GDScriptParser::OperatorNode *>(context.block->if_condition)->op == GDScriptParser::OperatorNode::OP_IS) { - //is used, check if identifier is in there! this helps resolve in blocks that are (if (identifier is value)): which are very common.. - //super dirty hack, but very useful - //credit: Zylann - //TODO: this could be hacked to detect ANDed conditions too.. - const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(context.block->if_condition); - if (op->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER && static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0])->name == p_identifier) { - //bingo - if (_guess_expression_type(context, op->arguments[1], op->line, r_type)) { - return true; + // Look in blocks first + const GDScriptParser::BlockNode *blk = p_context.block; + int last_assign_line = -1; + const GDScriptParser::Node *last_assigned_expression = NULL; + GDScriptParser::DataType var_type; + while (blk) { + if (blk->variables.has(p_identifier)) { + if (blk->variables[p_identifier]->line > p_context.line) { + return false; } - } - } - GDScriptCompletionIdentifier gdi = _get_native_class(context); - if (gdi.obj_type != StringName()) { - bool valid; - Variant::Type t = ClassDB::get_property_type(gdi.obj_type, p_identifier, &valid); - if (t != Variant::NIL && valid) { - r_type.type = t; - if (t == Variant::INT) { -//check for enum! -#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) + var_type = blk->variables[p_identifier]->datatype; - StringName getter = ClassDB::get_property_getter(gdi.obj_type, p_identifier); - if (getter != StringName()) { - MethodBind *mb = ClassDB::get_method(gdi.obj_type, getter); - if (mb) { - PropertyInfo rt = mb->get_return_info(); - if (rt.usage & PROPERTY_USAGE_CLASS_IS_ENUM) { - r_type.enumeration = rt.class_name; - } - } + if (!last_assigned_expression && blk->variables[p_identifier]->assign && blk->variables[p_identifier]->assign->type == GDScriptParser::Node::TYPE_OPERATOR) { + const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(blk->variables[p_identifier]->assign); + if (op->op == GDScriptParser::OperatorNode::OP_ASSIGN && op->arguments.size() >= 2) { + last_assign_line = op->line; + last_assigned_expression = op->arguments[1]; } -#endif } - return true; } - } - - const GDScriptParser::Node *last_assign = NULL; - int last_assign_line = -1; - - for (int i = 0; i < context.block->statements.size(); i++) { - - if (context.block->statements[i]->line > p_line) - continue; - - if (context.block->statements[i]->type == GDScriptParser::BlockNode::TYPE_LOCAL_VAR) { - const GDScriptParser::LocalVarNode *lv = static_cast<const GDScriptParser::LocalVarNode *>(context.block->statements[i]); + for (const List<GDScriptParser::Node *>::Element *E = blk->statements.front(); E; E = E->next()) { + const GDScriptParser::Node *expr = E->get(); + if (expr->line > p_context.line || expr->type != GDScriptParser::Node::TYPE_OPERATOR) { + continue; + } - if (lv->assign && lv->name == p_identifier) { + const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(expr); + if (op->op != GDScriptParser::OperatorNode::OP_ASSIGN || op->line < last_assign_line) { + continue; + } - last_assign = lv->assign; - last_assign_line = context.block->statements[i]->line; + if (op->arguments.size() >= 2 && op->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER) { + const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0]); + if (id->name == p_identifier) { + last_assign_line = op->line; + last_assigned_expression = op->arguments[1]; + } } } - if (context.block->statements[i]->type == GDScriptParser::BlockNode::TYPE_OPERATOR) { - const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(context.block->statements[i]); - if (op->op == GDScriptParser::OperatorNode::OP_ASSIGN) { - - if (op->arguments.size() && op->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER) { - - const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0]); - - if (id->name == p_identifier) { - - last_assign = op->arguments[1]; - last_assign_line = context.block->statements[i]->line; - } + if (blk->if_condition && blk->if_condition->type == GDScriptParser::Node::TYPE_OPERATOR && static_cast<const GDScriptParser::OperatorNode *>(blk->if_condition)->op == GDScriptParser::OperatorNode::OP_IS) { + //is used, check if identifier is in there! this helps resolve in blocks that are (if (identifier is value)): which are very common.. + //super dirty hack, but very useful + //credit: Zylann + //TODO: this could be hacked to detect ANDed conditions too.. + const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(blk->if_condition); + if (op->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER && static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0])->name == p_identifier) { + //bingo + GDScriptCompletionContext c = p_context; + c.line = op->line; + c.block = blk; + if (_guess_expression_type(p_context, op->arguments[1], r_type)) { + return true; } } } - } - - //use the last assignment, (then backwards?) - if (last_assign && last_assign_line != p_line) { - return _guess_expression_type(context, last_assign, last_assign_line, r_type); + blk = blk->parent_block; } - return false; -} - -static bool _guess_identifier_from_assignment_in_function(GDScriptCompletionContext &context, int p_src_line, const StringName &p_identifier, const StringName &p_function, GDScriptCompletionIdentifier &r_type) { - - const GDScriptParser::FunctionNode *func = NULL; - for (int i = 0; i < context._class->functions.size(); i++) { - if (context._class->functions[i]->name == p_function) { - func = context._class->functions[i]; - break; + if (last_assigned_expression && last_assign_line != p_context.line) { + GDScriptCompletionContext c = p_context; + c.line = last_assign_line; + r_type.assigned_expression = last_assigned_expression; + if (_guess_expression_type(c, last_assigned_expression, r_type)) { + return true; } } - if (!func) - return false; + if (var_type.has_type) { + r_type.type = var_type; + return true; + } - for (int i = 0; i < func->body->statements.size(); i++) { + if (p_context.function) { + for (int i = 0; i < p_context.function->arguments.size(); i++) { + if (p_context.function->arguments[i] == p_identifier) { + if (p_context.function->argument_types[i].has_type) { + r_type.type = p_context.function->argument_types[i]; + return true; + } - if (func->body->statements[i]->line == p_src_line) { - break; + int def_from = p_context.function->arguments.size() - p_context.function->default_values.size(); + if (i >= def_from) { + int def_idx = def_from - i; + if (p_context.function->default_values[def_idx]->type == GDScriptParser::Node::TYPE_OPERATOR) { + const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(p_context.function->default_values[def_idx]); + if (op->arguments.size() < 2) { + return false; + } + GDScriptCompletionContext c = p_context; + c.function = NULL; + c.block = NULL; + return _guess_expression_type(c, op->arguments[1], r_type); + } + } + break; + } } - if (func->body->statements[i]->type == GDScriptParser::BlockNode::TYPE_OPERATOR) { - const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(func->body->statements[i]); - if (op->op == GDScriptParser::OperatorNode::OP_ASSIGN) { - - if (op->arguments.size() && op->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER) { - - const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0]); - - if (id->name == p_identifier) { - - return _guess_expression_type(context, op->arguments[1], func->body->statements[i]->line, r_type); + GDScriptParser::DataType base_type = p_context._class->base_type; + while (base_type.has_type) { + switch (base_type.kind) { + case GDScriptParser::DataType::GDSCRIPT: { + Ref<GDScript> gds = base_type.script_type; + if (gds.is_valid() && gds->has_method(p_context.function->name)) { + GDScriptFunction *func = gds->get_member_functions()[p_context.function->name]; + if (func) { + for (int i = 0; i < func->get_argument_count(); i++) { + if (func->get_argument_name(i) == p_identifier) { + r_type = _type_from_gdtype(func->get_argument_type(i)); + return true; + } + } + } + Ref<GDScript> base_gds = gds->get_base_script(); + if (base_gds.is_valid()) { + base_type.kind = GDScriptParser::DataType::GDSCRIPT; + base_type.script_type = base_gds; + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = gds->get_instance_base_type(); + } + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = gds->get_instance_base_type(); } - } + } break; + case GDScriptParser::DataType::NATIVE: { + List<MethodInfo> methods; + ClassDB::get_method_list(base_type.native_type, &methods); + ClassDB::get_virtual_methods(base_type.native_type, &methods); + + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + if (E->get().name == p_context.function->name) { + MethodInfo &mi = E->get(); + for (List<PropertyInfo>::Element *E = mi.arguments.front(); E; E = E->next()) { + if (E->get().name == p_identifier) { + r_type = _type_from_property(E->get()); + return true; + } + } + } + } + base_type.has_type = false; + } break; + default: { + base_type.has_type = false; + } break; } } } - return false; -} - -static bool _guess_identifier_type(GDScriptCompletionContext &context, int p_line, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type, bool p_for_indexing) { - - //go to block first + // Check current class (including inheritance) + if (p_context._class) { + GDScriptCompletionIdentifier context_base; + context_base.value = p_context.base; + context_base.type.has_type = true; + context_base.type.kind = GDScriptParser::DataType::CLASS; + context_base.type.class_type = const_cast<GDScriptParser::ClassNode *>(p_context._class); + context_base.type.is_meta_type = p_context.function && p_context.function->_static; - const GDScriptParser::BlockNode *block = context.block; - - while (block) { - - GDScriptCompletionContext c = context; - c.block = block; - - if (_guess_identifier_type_in_block(c, p_line, p_identifier, r_type)) { + if (_guess_identifier_type_from_base(p_context, context_base, p_identifier, r_type)) { return true; } - - block = block->parent_block; } - //guess from argument if virtual - if (context.function && context.function->name != StringName()) { - - int argindex = -1; + // Check named scripts + if (ScriptServer::is_global_class(p_identifier)) { + Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_identifier)); + if (scr.is_valid()) { + r_type = _type_from_variant(scr); + r_type.type.is_meta_type = true; + return true; + } + return false; + } - for (int i = 0; i < context.function->arguments.size(); i++) { + // Check ClassDB + if (ClassDB::class_exists(p_identifier)) { + r_type.type.has_type = true; + r_type.type.kind = GDScriptParser::DataType::NATIVE; + r_type.type.native_type = p_identifier; + if (Engine::get_singleton()->has_singleton(p_identifier)) { + r_type.type.is_meta_type = false; + r_type.value = Engine::get_singleton()->get_singleton_object(p_identifier); + } else { + r_type.type.is_meta_type = true; + int idx = GDScriptLanguage::get_singleton()->get_global_map()[p_identifier]; + r_type.value = GDScriptLanguage::get_singleton()->get_global_array()[idx]; + } + return true; + } - if (context.function->arguments[i] == p_identifier) { - argindex = i; - break; - } + // ClassDB again for underscore-prefixed classes + StringName under_id = String("_") + p_identifier; + if (ClassDB::class_exists(under_id)) { + r_type.type.has_type = true; + r_type.type.kind = GDScriptParser::DataType::NATIVE; + r_type.type.native_type = p_identifier; + if (Engine::get_singleton()->has_singleton(p_identifier)) { + r_type.type.is_meta_type = false; + r_type.value = Engine::get_singleton()->get_singleton_object(p_identifier); + } else { + r_type.type.is_meta_type = true; + int idx = GDScriptLanguage::get_singleton()->get_global_map()[p_identifier]; + r_type.value = GDScriptLanguage::get_singleton()->get_global_array()[idx]; } + return true; + } - if (argindex != -1) { - GDScriptCompletionIdentifier id = _get_native_class(context); - if (id.type == Variant::OBJECT && id.obj_type != StringName()) { - //this kinda sucks but meh + // Check autoload singletons + if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(p_identifier)) { + r_type = _type_from_variant(GDScriptLanguage::get_singleton()->get_named_globals_map()[p_identifier]); + return true; + } - List<MethodInfo> vmethods; - ClassDB::get_virtual_methods(id.obj_type, &vmethods); - for (List<MethodInfo>::Element *E = vmethods.front(); E; E = E->next()) { + return false; +} - if (E->get().name == context.function->name && argindex < E->get().arguments.size()) { +static bool _guess_identifier_type_from_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type) { + GDScriptParser::DataType base_type = p_base.type; + bool _static = base_type.is_meta_type; + while (base_type.has_type) { + switch (base_type.kind) { + case GDScriptParser::DataType::CLASS: { + if (base_type.class_type->constant_expressions.has(p_identifier)) { + GDScriptParser::ClassNode::Constant c = base_type.class_type->constant_expressions[p_identifier]; + r_type.type = c.type; + if (c.expression->type == GDScriptParser::Node::TYPE_CONSTANT) { + r_type.value = static_cast<const GDScriptParser::ConstantNode *>(c.expression)->value; + } + return true; + } - PropertyInfo arg = E->get().arguments[argindex]; + if (!_static) { + for (int i = 0; i < base_type.class_type->variables.size(); i++) { + GDScriptParser::ClassNode::Member m = base_type.class_type->variables[i]; + if (m.identifier == p_identifier) { + if (m.data_type.has_type) { + r_type.type = m.data_type; + return true; + } + if (m.expression) { + if (_guess_expression_type(p_context, m.expression, r_type)) { + return true; + } + if (m.expression->get_datatype().has_type) { + r_type.type = m.expression->get_datatype(); + return true; + } + } + return false; + } + } + } + base_type = base_type.class_type->base_type; + } break; + case GDScriptParser::DataType::GDSCRIPT: { + Ref<GDScript> gds = base_type.script_type; + if (gds.is_valid()) { + if (gds->get_constants().has(p_identifier)) { + r_type = _type_from_variant(gds->get_constants()[p_identifier]); + return true; + } + if (!_static) { + const Set<StringName>::Element *m = gds->get_members().find(p_identifier); + if (m) { + r_type = _type_from_gdtype(gds->get_member_type(p_identifier)); + return true; + } + } + Ref<GDScript> parent = gds->get_base_script(); + if (parent.is_valid()) { + base_type.script_type = parent; + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = gds->get_instance_base_type(); + } + } else { + return false; + } + } break; + case GDScriptParser::DataType::SCRIPT: { + Ref<Script> scr = base_type.script_type; + if (scr.is_valid()) { + Map<StringName, Variant> constants; + scr->get_constants(&constants); + if (constants.has(p_identifier)) { + r_type = _type_from_variant(constants[p_identifier]); + return true; + } - int scp = String(arg.name).find(":"); - if (scp != -1) { + if (!_static) { + List<PropertyInfo> members; + scr->get_script_property_list(&members); + for (const List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) { + const PropertyInfo &prop = E->get(); + if (prop.name == p_identifier) { + r_type = _type_from_property(prop); + return true; + } + } + } + Ref<Script> parent = scr->get_base_script(); + if (parent.is_valid()) { + base_type.script_type = parent; + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = scr->get_instance_base_type(); + } + } else { + return false; + } + } break; + case GDScriptParser::DataType::NATIVE: { + StringName class_name = base_type.native_type; + if (!ClassDB::class_exists(class_name)) { + class_name = String("_") + class_name; + if (!ClassDB::class_exists(class_name)) { + return false; + } + } - r_type.type = Variant::OBJECT; - r_type.obj_type = String(arg.name).substr(scp + 1, String(arg.name).length()); - return true; + // Skip constants since they're all integers. Type does not matter because int has no members + List<PropertyInfo> props; + ClassDB::get_property_list(class_name, &props); + for (const List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + const PropertyInfo &prop = E->get(); + if (prop.name == p_identifier) { + StringName getter = ClassDB::get_property_getter(class_name, p_identifier); + if (getter != StringName()) { + MethodBind *g = ClassDB::get_method(class_name, getter); + if (g) { + r_type = _type_from_property(g->get_return_info()); + return true; + } } else { - - r_type.type = arg.type; - if (arg.hint == PROPERTY_HINT_RESOURCE_TYPE) - r_type.obj_type = arg.hint_string; + r_type = _type_from_property(prop); return true; } + break; } } - } + return false; + } break; + case GDScriptParser::DataType::BUILTIN: { + Variant::CallError err; + Variant tmp = Variant::construct(base_type.builtin_type, NULL, 0, err); + + if (err.error != Variant::CallError::CALL_OK) { + return false; + } + bool valid = false; + Variant res = tmp.get(p_identifier, &valid); + if (valid) { + r_type = _type_from_variant(res); + r_type.value = Variant(); + r_type.type.is_constant = false; + return true; + } + return false; + } break; + default: { + return false; + } break; } } - //guess type in constant + return false; +} - for (int i = 0; i < context._class->constant_expressions.size(); i++) { +static bool _find_last_return_in_block(const GDScriptCompletionContext &p_context, int &r_last_return_line, const GDScriptParser::Node **r_last_returned_value) { + if (!p_context.block) { + return false; + } - if (context._class->constant_expressions[i].identifier == p_identifier) { + for (int i = 0; i < p_context.block->statements.size(); i++) { + if (p_context.block->statements[i]->line < r_last_return_line) { + continue; + } + if (p_context.block->statements[i]->type != GDScriptParser::Node::TYPE_CONTROL_FLOW) { + continue; + } - ERR_FAIL_COND_V(context._class->constant_expressions[i].expression->type != GDScriptParser::Node::TYPE_CONSTANT, false); - r_type = _get_type_from_variant(static_cast<const GDScriptParser::ConstantNode *>(context._class->constant_expressions[i].expression)->value); - return true; + const GDScriptParser::ControlFlowNode *cf = static_cast<const GDScriptParser::ControlFlowNode *>(p_context.block->statements[i]); + if (cf->cf_type == GDScriptParser::ControlFlowNode::CF_RETURN && cf->arguments.size() > 0) { + if (cf->line > r_last_return_line) { + r_last_return_line = cf->line; + *r_last_returned_value = cf->arguments[0]; + } } } - if (!(context.function && context.function->_static)) { + // Recurse into subblocks + for (int i = 0; i < p_context.block->sub_blocks.size(); i++) { + GDScriptCompletionContext c = p_context; + c.block = p_context.block->sub_blocks[i]; + _find_last_return_in_block(c, r_last_return_line, r_last_returned_value); + } - for (int i = 0; i < context._class->variables.size(); i++) { + return false; +} - if (context._class->variables[i].identifier == p_identifier) { +static bool _guess_method_return_type_from_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, GDScriptCompletionIdentifier &r_type) { + GDScriptParser::DataType base_type = p_base.type; + bool _static = base_type.is_meta_type; - if (context._class->variables[i]._export.type != Variant::NIL) { + if (_static && p_method == "new") { + r_type.type = base_type; + r_type.type.is_meta_type = false; + r_type.type.is_constant = false; + return true; + } - r_type = _get_type_from_pinfo(context._class->variables[i]._export); - return true; - } else if (context._class->variables[i].expression) { - if (p_line <= context._class->variables[i].line) - return false; + while (base_type.has_type) { + switch (base_type.kind) { + case GDScriptParser::DataType::CLASS: { + if (!base_type.class_type) { + base_type.has_type = false; + break; + } - bool rtype = _guess_expression_type(context, context._class->variables[i].expression, context._class->variables[i].line, r_type); - if (rtype && r_type.type != Variant::NIL) - return true; - //return _guess_expression_type(context,context._class->variables[i].expression,context._class->variables[i].line,r_type); + for (int i = 0; i < base_type.class_type->static_functions.size(); i++) { + if (base_type.class_type->static_functions[i]->name == p_method) { + int last_return_line = -1; + const GDScriptParser::Node *last_returned_value = NULL; + GDScriptCompletionContext c = p_context; + c._class = base_type.class_type; + c.function = base_type.class_type->static_functions[i]; + c.block = c.function->body; + + _find_last_return_in_block(c, last_return_line, &last_returned_value); + if (last_returned_value) { + c.line = c.block->end_line; + return _guess_expression_type(c, last_returned_value, r_type); + } + } + } + if (!_static) { + for (int i = 0; i < base_type.class_type->functions.size(); i++) { + if (base_type.class_type->functions[i]->name == p_method) { + int last_return_line = -1; + const GDScriptParser::Node *last_returned_value = NULL; + GDScriptCompletionContext c = p_context; + c._class = base_type.class_type; + c.function = base_type.class_type->functions[i]; + c.block = c.function->body; + + _find_last_return_in_block(c, last_return_line, &last_returned_value); + if (last_returned_value) { + c.line = c.block->end_line; + return _guess_expression_type(c, last_returned_value, r_type); + } + } + } } - //try to guess from assignment in constructor or _ready - if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_ready", r_type)) - return true; - if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_enter_tree", r_type)) - return true; - if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_init", r_type)) + base_type = base_type.class_type->base_type; + } break; + case GDScriptParser::DataType::GDSCRIPT: { + Ref<GDScript> gds = base_type.script_type; + if (gds.is_valid()) { + if (gds->get_member_functions().has(p_method)) { + r_type = _type_from_gdtype(gds->get_member_functions()[p_method]->get_return_type()); + return true; + } + Ref<GDScript> base_script = gds->get_base_script(); + if (base_script.is_valid()) { + base_type.script_type = base_script; + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = gds->get_instance_base_type(); + } + } else { + return false; + } + } break; + case GDScriptParser::DataType::SCRIPT: { + Ref<Script> scr = base_type.script_type; + if (scr.is_valid()) { + List<MethodInfo> methods; + scr->get_script_method_list(&methods); + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + MethodInfo &mi = E->get(); + if (mi.name == p_method) { + r_type = _type_from_property(mi.return_val); + return true; + } + } + Ref<Script> base_script = scr->get_base_script(); + if (base_script.is_valid()) { + base_type.script_type = base_script; + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = scr->get_instance_base_type(); + } + } else { + return false; + } + } break; + case GDScriptParser::DataType::NATIVE: { + StringName native = base_type.native_type; + if (!ClassDB::class_exists(native)) { + native = String("_") + native; + if (!ClassDB::class_exists(native)) { + return false; + } + } + MethodBind *mb = ClassDB::get_method(native, p_method); + if (mb) { + r_type = _type_from_property(mb->get_return_info()); return true; + } + return false; + } break; + case GDScriptParser::DataType::BUILTIN: { + Variant::CallError err; + Variant tmp = Variant::construct(base_type.builtin_type, NULL, 0, err); + if (err.error != Variant::CallError::CALL_OK) { + return false; + } + + List<MethodInfo> methods; + tmp.get_method_list(&methods); + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + MethodInfo &mi = E->get(); + if (mi.name == p_method) { + r_type = _type_from_property(mi.return_val); + return true; + } + } + return false; + } break; + default: { return false; } } } + return false; +} - //autoloads as singletons - List<PropertyInfo> props; - ProjectSettings::get_singleton()->get_property_list(&props); - - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - - String s = E->get().name; - if (!s.begins_with("autoload/")) - continue; - String name = s.get_slice("/", 1); - if (name == String(p_identifier)) { +static String _make_arguments_hint(const MethodInfo &p_info, int p_arg_idx) { - String path = ProjectSettings::get_singleton()->get(s); - if (path.begins_with("*")) { - String script = path.substr(1, path.length()); + String arghint = _get_visual_datatype(p_info.return_val, false) + " " + p_info.name + "("; - if (!script.ends_with(".gd")) { - //not a script, try find the script anyway, - //may have some success - script = script.get_basename() + ".gd"; - } + int def_args = p_info.arguments.size() - p_info.default_arguments.size(); + int i = 0; + for (const List<PropertyInfo>::Element *E = p_info.arguments.front(); E; E = E->next()) { + if (i > 0) { + arghint += ", "; + } else { + arghint += " "; + } - if (FileAccess::exists(script)) { + if (i == p_arg_idx) { + arghint += String::chr(0xFFFF); + } + arghint += _get_visual_datatype(E->get(), true) + " " + E->get().name; - //print_line("is a script"); + if (i - def_args >= 0) { + arghint += String(" = ") + p_info.default_arguments[i - def_args].get_construct_string(); + } - Ref<Script> scr; - if (ScriptCodeCompletionCache::get_singleton()) - scr = ScriptCodeCompletionCache::get_singleton()->get_cached_resource(script); - else - scr = ResourceLoader::load(script); + if (i == p_arg_idx) { + arghint += String::chr(0xFFFF); + } - r_type.obj_type = "Node"; - r_type.type = Variant::OBJECT; - r_type.script = scr; - r_type.value = Variant(); + i++; + } - return true; - } - } + if (p_info.flags & METHOD_FLAG_VARARG) { + if (p_info.arguments.size() > 0) { + arghint += ", "; + } else { + arghint += " "; } + if (p_arg_idx >= p_info.arguments.size()) { + arghint += String::chr(0xFFFF); + } + arghint += "..."; + if (p_arg_idx >= p_info.arguments.size()) { + arghint += String::chr(0xFFFF); + } + } + if (p_info.arguments.size() > 0 || (p_info.flags & METHOD_FLAG_VARARG)) { + arghint += " "; } - //global - for (Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) { - if (E->key() == p_identifier) { + arghint += ")"; - r_type = _get_type_from_variant(GDScriptLanguage::get_singleton()->get_global_array()[E->get()], !p_for_indexing); - return true; - } - } - return false; + return arghint; } -static void _find_identifiers_in_block(GDScriptCompletionContext &context, int p_line, bool p_only_functions, Set<String> &result) { +static String _make_arguments_hint(const GDScriptParser::FunctionNode *p_function, int p_arg_idx) { - if (p_only_functions) - return; + String arghint = p_function->return_type.to_string() + " " + p_function->name.operator String() + "("; - for (int i = 0; i < context.block->statements.size(); i++) { + int def_args = p_function->arguments.size() - p_function->default_values.size(); + for (int i = 0; i < p_function->arguments.size(); i++) { + if (i > 0) { + arghint += ", "; + } else { + arghint += " "; + } - GDScriptParser::Node *statement = context.block->statements[i]; - if (statement->line > p_line) - continue; + if (i == p_arg_idx) { + arghint += String::chr(0xFFFF); + } + arghint += p_function->argument_types[i].to_string() + " " + p_function->arguments[i].operator String(); + + if (i - def_args >= 0) { + String def_val = "<unknown>"; + if (p_function->default_values[i - def_args] && p_function->default_values[i - def_args]->type == GDScriptParser::Node::TYPE_OPERATOR) { + const GDScriptParser::OperatorNode *assign = static_cast<const GDScriptParser::OperatorNode *>(p_function->default_values[i - def_args]); + + if (assign->arguments.size() >= 2) { + if (assign->arguments[1]->type == GDScriptParser::Node::TYPE_CONSTANT) { + const GDScriptParser::ConstantNode *cn = static_cast<const GDScriptParser::ConstantNode *>(assign->arguments[1]); + def_val = cn->value.get_construct_string(); + } else if (assign->arguments[1]->type == GDScriptParser::Node::TYPE_IDENTIFIER) { + const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(assign->arguments[1]); + def_val = id->name.operator String(); + } + } + } + arghint += " = " + def_val; + } + if (i == p_arg_idx) { + arghint += String::chr(0xFFFF); + } + } - GDScriptParser::BlockNode::Type statementType = statement->type; - if (statementType == GDScriptParser::BlockNode::TYPE_LOCAL_VAR) { + if (p_function->arguments.size() > 0) { + arghint += " "; + } + arghint += ")"; - const GDScriptParser::LocalVarNode *lv = static_cast<const GDScriptParser::LocalVarNode *>(statement); - result.insert(lv->name.operator String()); - } else if (statementType == GDScriptParser::BlockNode::TYPE_CONTROL_FLOW) { + return arghint; +} - const GDScriptParser::ControlFlowNode *cf = static_cast<const GDScriptParser::ControlFlowNode *>(statement); - if (cf->cf_type == GDScriptParser::ControlFlowNode::CF_FOR) { +static void _find_enumeration_candidates(const String p_enum_hint, Set<String> &r_result) { - const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(cf->arguments[0]); - result.insert(id->name.operator String()); + if (p_enum_hint.find(".") == -1) { + // Global constant + StringName current_enum = p_enum_hint; + for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) { + if (GlobalConstants::get_global_constant_enum(i) == current_enum) { + r_result.insert(GlobalConstants::get_global_constant_name(i)); } } - } -} - -static void _find_identifiers_in_class(GDScriptCompletionContext &context, bool p_static, bool p_only_functions, Set<String> &result) { + } else { + String class_name = p_enum_hint.get_slice(".", 0); + String enum_name = p_enum_hint.get_slice(".", 1); - if (!p_static && !p_only_functions) { + if (!ClassDB::class_exists(class_name)) { + return; + } - for (int i = 0; i < context._class->variables.size(); i++) { - result.insert(context._class->variables[i].identifier); + List<StringName> enum_constants; + ClassDB::get_enum_constants(class_name, enum_name, &enum_constants); + for (List<StringName>::Element *E = enum_constants.front(); E; E = E->next()) { + String candidate = class_name + "." + E->get(); + r_result.insert(candidate); } } - if (!p_only_functions) { +} - for (int i = 0; i < context._class->constant_expressions.size(); i++) { - result.insert(context._class->constant_expressions[i].identifier); +static void _find_identifiers_in_block(const GDScriptCompletionContext &p_context, Set<String> &r_result) { + for (Map<StringName, GDScriptParser::LocalVarNode *>::Element *E = p_context.block->variables.front(); E; E = E->next()) { + if (E->get()->line < p_context.line) { + r_result.insert(E->key().operator String()); } + } + if (p_context.block->parent_block) { + GDScriptCompletionContext c = p_context; + c.block = p_context.block->parent_block; + _find_identifiers_in_block(c, r_result); + } +} + +static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Set<String> &r_result); - for (int i = 0; i < context._class->subclasses.size(); i++) { - result.insert(context._class->subclasses[i]->name); +static void _find_identifiers_in_class(const GDScriptCompletionContext &p_context, bool p_static, bool p_only_functions, bool p_parent_only, Set<String> &r_result) { + if (!p_parent_only) { + if (!p_static && !p_only_functions) { + for (int i = 0; i < p_context._class->variables.size(); i++) { + r_result.insert(p_context._class->variables[i].identifier); + } } - } - for (int i = 0; i < context._class->static_functions.size(); i++) { - if (context._class->static_functions[i]->arguments.size()) - result.insert(context._class->static_functions[i]->name.operator String() + "("); - else - result.insert(context._class->static_functions[i]->name.operator String() + "()"); - } + if (!p_only_functions) { + for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_context._class->constant_expressions.front(); E; E = E->next()) { + r_result.insert(E->key()); + } + for (int i = 0; i < p_context._class->subclasses.size(); i++) { + r_result.insert(p_context._class->subclasses[i]->name); + } + } - if (!p_static) { + for (int i = 0; i < p_context._class->static_functions.size(); i++) { + if (p_context._class->static_functions[i]->arguments.size()) { + r_result.insert(p_context._class->static_functions[i]->name.operator String() + "("); + } else { + r_result.insert(p_context._class->static_functions[i]->name.operator String() + "()"); + } + } - for (int i = 0; i < context._class->functions.size(); i++) { - if (context._class->functions[i]->arguments.size()) - result.insert(context._class->functions[i]->name.operator String() + "("); - else - result.insert(context._class->functions[i]->name.operator String() + "()"); + if (!p_static) { + for (int i = 0; i < p_context._class->functions.size(); i++) { + if (p_context._class->functions[i]->arguments.size()) { + r_result.insert(p_context._class->functions[i]->name.operator String() + "("); + } else { + r_result.insert(p_context._class->functions[i]->name.operator String() + "()"); + } + } } } - //globals - - Ref<Reference> base = _get_parent_class(context); + // Parents + GDScriptCompletionIdentifier base_type; + base_type.type = p_context._class->base_type; + base_type.type.is_meta_type = p_static; + base_type.value = p_context.base; - while (true) { + GDScriptCompletionContext c = p_context; + c.block = NULL; + c.function = NULL; - Ref<GDScript> script = base; - Ref<GDScriptNativeClass> nc = base; - if (script.is_valid()) { + _find_identifiers_in_base(c, base_type, p_only_functions, r_result); +} - if (!p_static && !p_only_functions) { - for (const Set<StringName>::Element *E = script->get_members().front(); E; E = E->next()) { - result.insert(E->get().operator String()); +static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Set<String> &r_result) { + GDScriptParser::DataType base_type = p_base.type; + bool _static = base_type.is_meta_type; + + if (_static && base_type.kind != GDScriptParser::DataType::BUILTIN) { + r_result.insert("new("); + } + + while (base_type.has_type) { + switch (base_type.kind) { + case GDScriptParser::DataType::CLASS: { + GDScriptCompletionContext c = p_context; + c._class = base_type.class_type; + c.block = NULL; + c.function = NULL; + _find_identifiers_in_class(c, _static, p_only_functions, false, r_result); + base_type = base_type.class_type->base_type; + } break; + case GDScriptParser::DataType::GDSCRIPT: { + Ref<GDScript> script = base_type.script_type; + if (script.is_valid()) { + if (!_static && !p_only_functions) { + for (const Set<StringName>::Element *E = script->get_members().front(); E; E = E->next()) { + r_result.insert(E->get().operator String()); + } + } + if (!p_only_functions) { + for (const Map<StringName, Variant>::Element *E = script->get_constants().front(); E; E = E->next()) { + r_result.insert(E->key().operator String()); + } + } + for (const Map<StringName, GDScriptFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) { + if (!_static || E->get()->is_static()) { + if (E->get()->get_argument_count()) { + r_result.insert(E->key().operator String() + "("); + } else { + r_result.insert(E->key().operator String() + "()"); + } + } + } + if (!p_only_functions) { + for (const Map<StringName, Ref<GDScript> >::Element *E = script->get_subclasses().front(); E; E = E->next()) { + r_result.insert(E->key().operator String()); + } + } + base_type = GDScriptParser::DataType(); + if (script->get_base().is_valid()) { + base_type.has_type = true; + base_type.kind = GDScriptParser::DataType::GDSCRIPT; + base_type.script_type = script->get_base(); + } else { + base_type.has_type = script->get_instance_base_type() != StringName(); + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.script_type = script->get_instance_base_type(); + } + } else { + return; } - } + } break; + case GDScriptParser::DataType::SCRIPT: { + Ref<Script> scr = base_type.script_type; + if (scr.is_valid()) { + if (!_static && !p_only_functions) { + List<PropertyInfo> members; + scr->get_script_property_list(&members); + for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) { + r_result.insert(E->get().name); + } + } + if (!p_only_functions) { + Map<StringName, Variant> constants; + scr->get_constants(&constants); + for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) { + r_result.insert(E->key().operator String()); + } + } - if (!p_only_functions) { - for (const Map<StringName, Variant>::Element *E = script->get_constants().front(); E; E = E->next()) { - result.insert(E->key().operator String()); - } - } + List<MethodInfo> methods; + scr->get_script_method_list(&methods); + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + if (E->get().arguments.size()) { + r_result.insert(E->get().name + "("); + } else { + r_result.insert(E->get().name + "()"); + } + } - for (const Map<StringName, GDScriptFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) { - if (!p_static || E->get()->is_static()) { - if (E->get()->get_argument_count()) - result.insert(E->key().operator String() + "("); - else - result.insert(E->key().operator String() + "()"); + Ref<Script> base_script = scr->get_base_script(); + if (base_script.is_valid()) { + base_type.script_type = base_script; + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = scr->get_instance_base_type(); + } + } else { + return; } - } - - if (!p_only_functions) { - for (const Map<StringName, Ref<GDScript> >::Element *E = script->get_subclasses().front(); E; E = E->next()) { - result.insert(E->key().operator String()); + } break; + case GDScriptParser::DataType::NATIVE: { + StringName type = base_type.native_type; + if (!ClassDB::class_exists(type)) { + type = String("_") + type; + if (!ClassDB::class_exists(type)) { + return; + } } - } - base = script->get_base(); - if (base.is_null()) - base = script->get_native(); - } else if (nc.is_valid()) { + if (!p_only_functions) { + List<String> constants; + ClassDB::get_integer_constant_list(type, &constants); + for (List<String>::Element *E = constants.front(); E; E = E->next()) { + r_result.insert(E->get()); + } - StringName type = nc->get_name(); + if (!_static) { + List<PropertyInfo> pinfo; + ClassDB::get_property_list(type, &pinfo); + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) { + continue; + } + if (E->get().name.find("/") != -1) { + continue; + } + r_result.insert(E->get().name); + } + } + } - if (!p_only_functions) { + if (!_static) { + List<MethodInfo> methods; + ClassDB::get_method_list(type, &methods, false, true); + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + if (E->get().name.begins_with("_")) { + continue; + } + if (E->get().arguments.size()) { + r_result.insert(E->get().name + "("); + } else { + r_result.insert(E->get().name + "()"); + } + } + } - List<String> constants; - ClassDB::get_integer_constant_list(type, &constants); - for (List<String>::Element *E = constants.front(); E; E = E->next()) { - result.insert(E->get()); + return; + } break; + case GDScriptParser::DataType::BUILTIN: { + Variant::CallError err; + Variant tmp = Variant::construct(base_type.builtin_type, NULL, 0, err); + if (err.error != Variant::CallError::CALL_OK) { + return; } - List<PropertyInfo> pinfo; + if (!p_only_functions) { + List<PropertyInfo> members; + tmp.get_property_list(&members); - ClassDB::get_property_list(type, &pinfo); + for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) { + if (String(E->get().name).find("/") == -1) { + r_result.insert(E->get().name); + } + } + } - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) - continue; - if (String(E->get().name).find("/") != -1) - continue; - result.insert(E->get().name); + List<MethodInfo> methods; + tmp.get_method_list(&methods); + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + if (E->get().arguments.size()) { + r_result.insert(E->get().name + "("); + } else { + r_result.insert(E->get().name + "()"); + } } - } - List<MethodInfo> methods; - ClassDB::get_method_list(type, &methods, false, true); - for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - if (E->get().name.begins_with("_")) - continue; - if (E->get().arguments.size()) - result.insert(E->get().name + "("); - else - result.insert(E->get().name + "()"); - } - break; - } else - break; + return; + } break; + default: { + return; + } break; + } } } -static void _find_identifiers(GDScriptCompletionContext &context, int p_line, bool p_only_functions, Set<String> &result) { +static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p_only_functions, Set<String> &r_result) { - const GDScriptParser::BlockNode *block = context.block; + const GDScriptParser::BlockNode *block = p_context.block; - if (context.function) { + if (p_context.function) { - const GDScriptParser::FunctionNode *f = context.function; + const GDScriptParser::FunctionNode *f = p_context.function; for (int i = 0; i < f->arguments.size(); i++) { - result.insert(f->arguments[i].operator String()); + r_result.insert(f->arguments[i].operator String()); } } - while (block) { - - GDScriptCompletionContext c = context; + if (!p_only_functions && block) { + GDScriptCompletionContext c = p_context; c.block = block; - - _find_identifiers_in_block(c, p_line, p_only_functions, result); - block = block->parent_block; + _find_identifiers_in_block(c, r_result); } - const GDScriptParser::ClassNode *clss = context._class; - - bool _static = context.function && context.function->_static; + const GDScriptParser::ClassNode *clss = p_context._class; + bool _static = !p_context.function || p_context.function->_static; while (clss) { - GDScriptCompletionContext c = context; + GDScriptCompletionContext c = p_context; c._class = clss; c.block = NULL; c.function = NULL; - _find_identifiers_in_class(c, _static, p_only_functions, result); + _find_identifiers_in_class(c, _static, p_only_functions, false, r_result); + _static = true; clss = clss->owner; } for (int i = 0; i < GDScriptFunctions::FUNC_MAX; i++) { - - result.insert(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))); + MethodInfo mi = GDScriptFunctions::get_info(GDScriptFunctions::Function(i)); + if (mi.arguments.size() || (mi.flags & METHOD_FLAG_VARARG)) { + r_result.insert(String(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))) + "("); + } else { + r_result.insert(String(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))) + "()"); + } } static const char *_type_names[Variant::VARIANT_MAX] = { @@ -1526,667 +2091,372 @@ static void _find_identifiers(GDScriptCompletionContext &context, int p_line, bo }; for (int i = 0; i < Variant::VARIANT_MAX; i++) { - result.insert(_type_names[i]); + r_result.insert(_type_names[i]); } - List<String> reserved_words; - GDScriptLanguage::get_singleton()->get_reserved_words(&reserved_words); + static const char *_keywords[] = { + "and", "in", "not", "or", "false", "PI", "TAU", "INF", "NAN", "self", "true", "as", "assert", + "breakpoint", "class", "extends", "is", "func", "preload", "setget", "signal", "tool", "yield", + "const", "enum", "export", "onready", "static", "var", "break", "continue", "if", "elif", + "else", "for", "pass", "return", "match", "while", "remote", "sync", "master", "slave", + "remotesync", "mastersync", "slavesync", + 0 + }; - for (List<String>::Element *E = reserved_words.front(); E; E = E->next()) { - result.insert(E->get()); + const char **kw = _keywords; + while (*kw) { + r_result.insert(*kw); + kw++; } - //autoload singletons + // Autoload singletons List<PropertyInfo> props; ProjectSettings::get_singleton()->get_property_list(&props); - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - String s = E->get().name; - if (!s.begins_with("autoload/")) + if (!s.begins_with("autoload/")) { continue; - String name = s.get_slice("/", 1); + } String path = ProjectSettings::get_singleton()->get(s); if (path.begins_with("*")) { - result.insert(name); + r_result.insert(s.get_slice("/", 1)); } } - for (const Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) { - result.insert(E->key().operator String()); - } -} - -static String _get_visual_datatype(const PropertyInfo &p_info, bool p_isarg = true) { - - String n = p_info.name; - int idx = n.find(":"); - if (idx != -1) { - return n.substr(idx + 1, n.length()); + // Named scripts + List<StringName> named_scripts; + ScriptServer::get_global_class_list(&named_scripts); + for (List<StringName>::Element *E = named_scripts.front(); E; E = E->next()) { + r_result.insert(E->get().operator String()); } - if (p_info.type == Variant::OBJECT && p_info.hint == PROPERTY_HINT_RESOURCE_TYPE) - return p_info.hint_string; - if (p_info.type == Variant::NIL) { - if (p_isarg) - return "var"; - else - return "void"; + // Native classes + for (const Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) { + r_result.insert(E->key().operator String()); } - - return Variant::get_type_name(p_info.type); } -static void _make_function_hint(const GDScriptParser::FunctionNode *p_func, int p_argidx, String &arghint) { - - arghint = "func " + p_func->name + "("; - for (int i = 0; i < p_func->arguments.size(); i++) { - if (i > 0) - arghint += ", "; - else - arghint += " "; - - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - arghint += p_func->arguments[i].operator String(); - int deffrom = p_func->arguments.size() - p_func->default_values.size(); - - if (i >= deffrom) { - int defidx = deffrom - i; - - if (defidx >= 0 && defidx < p_func->default_values.size()) { - - if (p_func->default_values[defidx]->type == GDScriptParser::Node::TYPE_OPERATOR) { - - const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(p_func->default_values[defidx]); - if (op->op == GDScriptParser::OperatorNode::OP_ASSIGN) { - const GDScriptParser::ConstantNode *cn = static_cast<const GDScriptParser::ConstantNode *>(op->arguments[1]); - arghint += "=" + cn->value.get_construct_string(); +static void _find_call_arguments(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, int p_argidx, bool p_static, Set<String> &r_result, String &r_arghint) { + Variant base = p_base.value; + GDScriptParser::DataType base_type = p_base.type; + bool _static = false; + + while (base_type.has_type) { + switch (base_type.kind) { + case GDScriptParser::DataType::CLASS: { + for (int i = 0; i < base_type.class_type->static_functions.size(); i++) { + if (base_type.class_type->static_functions[i]->name == p_method) { + r_arghint = _make_arguments_hint(base_type.class_type->static_functions[i], p_argidx); + return; + } + } + if (!_static) { + for (int i = 0; i < base_type.class_type->functions.size(); i++) { + if (base_type.class_type->functions[i]->name == p_method) { + r_arghint = _make_arguments_hint(base_type.class_type->functions[i], p_argidx); + return; + } } - } else { } - } - } - - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - } - if (p_func->arguments.size() > 0) - arghint += " "; - arghint += ")"; -} - -void get_directory_contents(EditorFileSystemDirectory *p_dir, Set<String> &r_list) { - - for (int i = 0; i < p_dir->get_subdir_count(); i++) { - get_directory_contents(p_dir->get_subdir(i), r_list); - } - - for (int i = 0; i < p_dir->get_file_count(); i++) { - r_list.insert("\"" + p_dir->get_file_path(i) + "\""); - } -} - -static void _find_type_arguments(GDScriptCompletionContext &context, const GDScriptParser::Node *p_node, int p_line, const StringName &p_method, const GDScriptCompletionIdentifier &id, int p_argidx, Set<String> &result, bool &r_forced, String &arghint) { - - //print_line("find type arguments?"); - if (id.type == Variant::OBJECT && id.obj_type != StringName()) { - - MethodBind *m = ClassDB::get_method(id.obj_type, p_method); - if (!m) { - //not in static method, see script - - //print_line("not in static: "+String(p_method)); - Ref<GDScript> on_script; - - if (id.value.get_type()) { - Object *obj = id.value; - GDScript *scr = Object::cast_to<GDScript>(obj); - if (scr) { - while (scr) { + if ((p_method == "connect" || p_method == "emit_signal") && p_argidx == 0) { + for (int i = 0; i < base_type.class_type->_signals.size(); i++) { + r_result.insert("\"" + base_type.class_type->_signals[i].name.operator String() + "\""); + } + } - for (const Map<StringName, GDScriptFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { - if (E->get()->is_static() && p_method == E->get()->get_name()) { - arghint = "static func " + String(p_method) + "("; - for (int i = 0; i < E->get()->get_argument_count(); i++) { - if (i > 0) - arghint += ", "; - else - arghint += " "; - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - arghint += "var " + E->get()->get_argument_name(i); - int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count(); - if (i >= deffrom) { - int defidx = deffrom - i; - if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) { - arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string(); - } - } - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - } - arghint += ")"; - return; //found - } + base_type = base_type.class_type->base_type; + } break; + case GDScriptParser::DataType::GDSCRIPT: { + Ref<GDScript> gds = base_type.script_type; + if (gds.is_valid()) { + if ((p_method == "connect" || p_method == "emit_signal") && p_argidx == 0) { + List<MethodInfo> signals; + gds->get_script_signal_list(&signals); + for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { + r_result.insert("\"" + E->get().name + "\""); } - - if (scr->get_base().is_valid()) - scr = scr->get_base().ptr(); - else - scr = NULL; + } + Ref<GDScript> base_script = gds->get_base_script(); + if (base_script.is_valid()) { + base_type.script_type = base_script; + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = gds->get_instance_base_type(); } } else { - if (obj) { - on_script = obj->get_script(); + return; + } + } break; + case GDScriptParser::DataType::NATIVE: { + StringName class_name = base_type.native_type; + if (!ClassDB::class_exists(class_name)) { + class_name = String("_") + class_name; + if (!ClassDB::class_exists(class_name)) { + base_type.has_type = false; + break; } } - } - - //print_line("but it has a script?"); - if (!on_script.is_valid() && id.script.is_valid()) { - //print_line("yes"); - on_script = id.script; - } - - if (on_script.is_valid()) { - - GDScript *scr = on_script.ptr(); - if (scr) { - while (scr) { - - String code = scr->get_source_code(); - //print_line("has source code!"); - - if (code != "") { - //if there is code, parse it. This way is slower but updates in real-time - GDScriptParser p; - //Error parse(const String& p_code, const String& p_base_path="", bool p_just_validate=false,const String& p_self_path="",bool p_for_completion=false); - - Error err = p.parse(scr->get_source_code(), scr->get_path().get_base_dir(), true, "", false); - - if (err == OK) { - //print_line("checking the functions..."); - //only if ok, otherwise use what is cached on the script - //GDScriptParser::ClassNode *base = p. - const GDScriptParser::Node *root = p.get_parse_tree(); - ERR_FAIL_COND(root->type != GDScriptParser::Node::TYPE_CLASS); - - const GDScriptParser::ClassNode *cl = static_cast<const GDScriptParser::ClassNode *>(root); - - const GDScriptParser::FunctionNode *func = NULL; - bool st = false; - - for (int i = 0; i < cl->functions.size(); i++) { - //print_line(String(cl->functions[i]->name)+" vs "+String(p_method)); - if (cl->functions[i]->name == p_method) { - func = cl->functions[i]; - } - } - - for (int i = 0; i < cl->static_functions.size(); i++) { - - //print_line(String(cl->static_functions[i]->name)+" vs "+String(p_method)); - if (cl->static_functions[i]->name == p_method) { - func = cl->static_functions[i]; - st = true; - } - } - - if (func) { - - arghint = "func " + String(p_method) + "("; - if (st) - arghint = "static " + arghint; - for (int i = 0; i < func->arguments.size(); i++) { - if (i > 0) - arghint += ", "; - else - arghint += " "; - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - arghint += "var " + String(func->arguments[i]); - int deffrom = func->arguments.size() - func->default_values.size(); - if (i >= deffrom) { - int defidx = deffrom - i; + List<MethodInfo> methods; + ClassDB::get_method_list(class_name, &methods); + ClassDB::get_virtual_methods(class_name, &methods); + int method_args = 0; - if (defidx >= 0 && defidx < func->default_values.size() && func->default_values[defidx]->type == GDScriptParser::Node::TYPE_OPERATOR) { - const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(func->default_values[defidx]); - if (op->op == GDScriptParser::OperatorNode::OP_ASSIGN) { - const GDScriptParser::ConstantNode *cn = static_cast<const GDScriptParser::ConstantNode *>(op->arguments[1]); - arghint += "=" + cn->value.get_construct_string(); - } - } - } - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - } - - arghint += " )"; - return; + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + if (E->get().name == p_method) { + method_args = E->get().arguments.size(); + if (base.get_type() == Variant::OBJECT) { + Object *obj = base.operator Object *(); + if (obj) { + List<String> options; + obj->get_argument_options(p_method, p_argidx, &options); + for (List<String>::Element *E = options.front(); E; E = E->next()) { + r_result.insert(E->get()); } - } else { - //print_line("failed parsing?"); - code = ""; } } - if (code == "") { - - for (const Map<StringName, GDScriptFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { - if (p_method == E->get()->get_name()) { - arghint = "func " + String(p_method) + "("; - for (int i = 0; i < E->get()->get_argument_count(); i++) { - if (i > 0) - arghint += ", "; - else - arghint += " "; - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - arghint += "var " + E->get()->get_argument_name(i); - int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count(); - if (i >= deffrom) { - int defidx = deffrom - i; - if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) { - arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string(); - } - } - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - } - arghint += ")"; - return; //found - } + if (p_argidx < method_args) { + PropertyInfo arg_info = E->get().arguments[p_argidx]; + if (arg_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) { + _find_enumeration_candidates(arg_info.class_name, r_result); } } - if (scr->get_base().is_valid()) - scr = scr->get_base().ptr(); - else - scr = NULL; + r_arghint = _make_arguments_hint(E->get(), p_argidx); + break; } } - } - - } else { - - //regular method -#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) - if (p_argidx < m->get_argument_count()) { - PropertyInfo pi = m->get_argument_info(p_argidx); - - if (pi.usage & PROPERTY_USAGE_CLASS_IS_ENUM) { - String enumeration = pi.class_name; - if (enumeration.find(".") != -1) { - //class constant - List<StringName> constants; - String cls = enumeration.get_slice(".", 0); - String enm = enumeration.get_slice(".", 1); - - ClassDB::get_enum_constants(cls, enm, &constants); - //constants.sort_custom<StringName::AlphCompare>(); - for (List<StringName>::Element *E = constants.front(); E; E = E->next()) { - String add = cls + "." + E->get(); - result.insert(add); - r_forced = true; - } - } else { - //global constant - StringName current_enum = enumeration; - - for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) { - if (GlobalConstants::get_global_constant_enum(i) == current_enum) { - result.insert(GlobalConstants::get_global_constant_name(i)); - r_forced = true; - } - } - //global + if ((p_method == "connect" || p_method == "emit_signal") && p_argidx == 0) { + List<MethodInfo> signals; + ClassDB::get_signal_list(class_name, &signals); + for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { + r_result.insert("\"" + E->get().name + "\""); } } - } -#endif - if (p_method.operator String() == "connect" || (p_method.operator String() == "emit_signal" && p_argidx == 0)) { - - if (p_argidx == 0) { - List<MethodInfo> sigs; - ClassDB::get_signal_list(id.obj_type, &sigs); - - if (id.script.is_valid()) { - id.script->get_script_signal_list(&sigs); - } else if (id.value.get_type() == Variant::OBJECT) { - Object *obj = id.value; - if (obj && !obj->get_script().is_null()) { - Ref<Script> scr = obj->get_script(); - if (scr.is_valid()) { - scr->get_script_signal_list(&sigs); - } - } - } - - for (List<MethodInfo>::Element *E = sigs.front(); E; E = E->next()) { - result.insert("\"" + E->get().name + "\""); - r_forced = true; - } - } else if (p_argidx == 2) { + if (ClassDB::is_parent_class(class_name, "Node") && (p_method == "get_node" || p_method == "has_node") && p_argidx == 0) { + // Get autoloads + List<PropertyInfo> props; + ProjectSettings::get_singleton()->get_property_list(&props); - if (context._class) { - for (int i = 0; i < context._class->functions.size(); i++) { - result.insert("\"" + context._class->functions[i]->name + "\""); - r_forced = true; + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + String s = E->get().name; + if (!s.begins_with("autoload/")) { + continue; } + String name = s.get_slice("/", 1); + r_result.insert("\"/root/" + name + "\""); } } - /*if (p_argidx==2) { - - ERR_FAIL_COND(p_node->type!=GDScriptParser::Node::TYPE_OPERATOR); - const GDScriptParser::OperatorNode *op=static_cast<const GDScriptParser::OperatorNode *>(p_node); - if (op->arguments.size()>) - - }*/ - } else { - - if (p_argidx == 0 && (String(p_method) == "get_node" || String(p_method) == "has_node") && ClassDB::is_parent_class(id.obj_type, "Node")) { + if (p_argidx == 0 && method_args > 0 && ClassDB::is_parent_class(class_name, "InputEvent") && p_method.operator String().find("action") != -1) { + // Get input actions List<PropertyInfo> props; ProjectSettings::get_singleton()->get_property_list(&props); - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - String s = E->get().name; - if (!s.begins_with("autoload/")) + if (!s.begins_with("input/")) { continue; - //print_line("found "+s); + } String name = s.get_slice("/", 1); - result.insert("\"/root/" + name + "\""); - r_forced = true; + r_result.insert("\"" + name + "\""); } } - Object *obj = id.value; - if (obj) { - List<String> options; - obj->get_argument_options(p_method, p_argidx, &options); - - for (List<String>::Element *E = options.front(); E; E = E->next()) { - - result.insert(E->get()); - r_forced = true; + base_type.has_type = false; + } break; + case GDScriptParser::DataType::BUILTIN: { + if (base.get_type() == Variant::NIL) { + Variant::CallError err; + base = Variant::construct(base_type.builtin_type, NULL, 0, err); + if (err.error != Variant::CallError::CALL_OK) { + return; } } - } - - arghint = _get_visual_datatype(m->get_return_info(), false) + " " + p_method.operator String() + String("("); - - for (int i = 0; i < m->get_argument_count(); i++) { - if (i > 0) - arghint += ", "; - else - arghint += " "; - - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - String n = m->get_argument_info(i).name; - int dp = n.find(":"); - if (dp != -1) - n = n.substr(0, dp); - arghint += _get_visual_datatype(m->get_argument_info(i)) + " " + n; - int deffrom = m->get_argument_count() - m->get_default_argument_count(); - - if (i >= deffrom) { - int defidx = i - deffrom; - if (defidx >= 0 && defidx < m->get_default_argument_count()) { - Variant v = m->get_default_argument(i); - arghint += "=" + v.get_construct_string(); + List<MethodInfo> methods; + base.get_method_list(&methods); + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + if (E->get().name == p_method) { + r_arghint = _make_arguments_hint(E->get(), p_argidx); + return; } } - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - } - if (m->get_argument_count() > 0) - arghint += " "; - - arghint += ")"; + base_type.has_type = false; + } break; + default: { + base_type.has_type = false; + } break; } } } -static void _find_call_arguments(GDScriptCompletionContext &context, const GDScriptParser::Node *p_node, int p_line, int p_argidx, Set<String> &result, bool &r_forced, String &arghint) { +static void _find_call_arguments(const GDScriptCompletionContext &p_context, const GDScriptParser::Node *p_node, int p_argidx, Set<String> &r_result, bool &r_forced, String &r_arghint) { if (!p_node || p_node->type != GDScriptParser::Node::TYPE_OPERATOR) { - return; } + Variant base; + GDScriptParser::DataType base_type; + StringName function; + bool _static = false; const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(p_node); - if (op->op != GDScriptParser::OperatorNode::OP_CALL) { + GDScriptCompletionIdentifier connect_base; + if (op->op != GDScriptParser::OperatorNode::OP_CALL && op->op != GDScriptParser::OperatorNode::OP_PARENT_CALL) { return; } - if (op->arguments[0]->type == GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION) { - //complete built-in function - const GDScriptParser::BuiltInFunctionNode *fn = static_cast<const GDScriptParser::BuiltInFunctionNode *>(op->arguments[0]); - MethodInfo mi = GDScriptFunctions::get_info(fn->function); + if (!op->arguments.size()) { + return; + } - if (mi.name == "load" && bool(EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths"))) { - get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), result); - } + if (op->op == GDScriptParser::OperatorNode::OP_CALL) { + if (op->arguments[0]->type == GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION) { + // Complete built-in function + const GDScriptParser::BuiltInFunctionNode *fn = static_cast<const GDScriptParser::BuiltInFunctionNode *>(op->arguments[0]); + MethodInfo mi = GDScriptFunctions::get_info(fn->function); - arghint = _get_visual_datatype(mi.return_val, false) + " " + GDScriptFunctions::get_func_name(fn->function) + String("("); - for (int i = 0; i < mi.arguments.size(); i++) { - if (i > 0) - arghint += ", "; - else - arghint += " "; - if (i == p_argidx || ((mi.flags & METHOD_FLAG_VARARG) && i > p_argidx)) { - arghint += String::chr(0xFFFF); - } - arghint += _get_visual_datatype(mi.arguments[i]) + " " + mi.arguments[i].name; - if (i == p_argidx || ((mi.flags & METHOD_FLAG_VARARG) && i > p_argidx)) { - arghint += String::chr(0xFFFF); + if ((mi.name == "load" || mi.name == "preload") && bool(EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths"))) { + _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), r_result); } - } - if (mi.arguments.size() > 0) - arghint += " "; - arghint += ")"; - } else if (op->arguments[0]->type == GDScriptParser::Node::TYPE_TYPE) { - //complete constructor - const GDScriptParser::TypeNode *tn = static_cast<const GDScriptParser::TypeNode *>(op->arguments[0]); + r_arghint = _make_arguments_hint(mi, p_argidx); + return; - List<MethodInfo> mil; - Variant::get_constructor_list(tn->vtype, &mil); + } else if (op->arguments[0]->type == GDScriptParser::Node::TYPE_TYPE) { + // Complete constructor + const GDScriptParser::TypeNode *tn = static_cast<const GDScriptParser::TypeNode *>(op->arguments[0]); - for (List<MethodInfo>::Element *E = mil.front(); E; E = E->next()) { + List<MethodInfo> constructors; + Variant::get_constructor_list(tn->vtype, &constructors); - MethodInfo mi = E->get(); - if (mi.arguments.size() == 0) - continue; - if (E->prev()) - arghint += "\n"; - arghint += Variant::get_type_name(tn->vtype) + " " + Variant::get_type_name(tn->vtype) + String("("); - for (int i = 0; i < mi.arguments.size(); i++) { - if (i > 0) - arghint += ", "; - else - arghint += " "; - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - arghint += _get_visual_datatype(mi.arguments[i]) + " " + mi.arguments[i].name; - if (i == p_argidx) { - arghint += String::chr(0xFFFF); + int i = 0; + for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) { + if (p_argidx >= E->get().arguments.size()) { + continue; } - } - if (mi.arguments.size() > 0) - arghint += " "; - arghint += ")"; - } - - } else if (op->arguments.size() >= 2 && op->arguments[1]->type == GDScriptParser::Node::TYPE_IDENTIFIER) { - //make sure identifier exists... - - const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1]); - if (op->arguments[0]->type == GDScriptParser::Node::TYPE_SELF) { - //self, look up - - for (int i = 0; i < context._class->static_functions.size(); i++) { - if (context._class->static_functions[i]->name == id->name) { - _make_function_hint(context._class->static_functions[i], p_argidx, arghint); - return; + if (i > 0) { + r_arghint += "\n"; } + r_arghint += _make_arguments_hint(E->get(), p_argidx); + i++; } + return; + } else if (op->arguments[0]->type == GDScriptParser::Node::TYPE_SELF) { - if (context.function && !context.function->_static) { - - for (int i = 0; i < context._class->functions.size(); i++) { - if (context._class->functions[i]->name == id->name) { - _make_function_hint(context._class->functions[i], p_argidx, arghint); - return; - } - } + if (op->arguments.size() < 2 || op->arguments[1]->type != GDScriptParser::Node::TYPE_IDENTIFIER) { + return; } - Ref<Reference> base = _get_parent_class(context); - - while (true) { - - Ref<GDScript> script = base; - Ref<GDScriptNativeClass> nc = base; - if (script.is_valid()) { - - for (const Map<StringName, GDScriptFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) { + base = p_context.base; - if (E->key() == id->name) { + const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1]); + function = id->name; + base_type.has_type = true; + base_type.kind = GDScriptParser::DataType::CLASS; + base_type.class_type = const_cast<GDScriptParser::ClassNode *>(p_context._class); + _static = p_context.function && p_context.function->_static; - if (context.function && context.function->_static && !E->get()->is_static()) - continue; + if (function == "connect" && op->arguments.size() >= 4) { + _guess_expression_type(p_context, op->arguments[3], connect_base); + } - arghint = "func " + id->name.operator String() + String("("); - for (int i = 0; i < E->get()->get_argument_count(); i++) { - if (i > 0) - arghint += ", "; - else - arghint += " "; - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - arghint += E->get()->get_argument_name(i); - int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count(); - if (i >= deffrom) { - int defidx = deffrom - i; - if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) { - arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string(); - } - } - if (i == p_argidx) { - arghint += String::chr(0xFFFF); - } - } - if (E->get()->get_argument_count() > 0) - arghint += " "; - arghint += ")"; - return; - } - } + } else { + if (op->arguments.size() < 2 || op->arguments[1]->type != GDScriptParser::Node::TYPE_IDENTIFIER) { + return; + } + const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1]); + function = id->name; - base = script->get_base(); - if (base.is_null()) - base = script->get_native(); - } else if (nc.is_valid()) { + GDScriptCompletionIdentifier ci; + if (_guess_expression_type(p_context, op->arguments[0], ci)) { + base_type = ci.type; + base = ci.value; + } else { + return; + } + _static = ci.type.is_meta_type; - if (!(context.function && context.function->_static)) { + if (function == "connect" && op->arguments.size() >= 4) { + _guess_expression_type(p_context, op->arguments[3], connect_base); + } + } + } else { + if (!p_context._class || op->arguments.size() < 1 || op->arguments[0]->type != GDScriptParser::Node::TYPE_IDENTIFIER) { + return; + } + base_type.has_type = true; + base_type.kind = GDScriptParser::DataType::CLASS; + base_type.class_type = const_cast<GDScriptParser::ClassNode *>(p_context._class); + base_type.is_meta_type = p_context.function && p_context.function->_static; + base = p_context.base; - GDScriptCompletionIdentifier ci; - ci.type = Variant::OBJECT; - ci.obj_type = nc->get_name(); - if (!context._class->owner) - ci.value = context.base; + function = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0])->name; - _find_type_arguments(context, p_node, p_line, id->name, ci, p_argidx, result, r_forced, arghint); - //guess type.. - /* - List<MethodInfo> methods; - ClassDB::get_method_list(type,&methods); - for(List<MethodInfo>::Element *E=methods.front();E;E=E->next()) { - if (E->get().arguments.size()) - result.insert(E->get().name+"("); - else - result.insert(E->get().name+"()"); - }*/ - } - break; - } else - break; - } - } else { - //indexed lookup + if (function == "connect" && op->arguments.size() >= 4) { + _guess_expression_type(p_context, op->arguments[3], connect_base); + } + } - GDScriptCompletionIdentifier ci; - if (_guess_expression_type(context, op->arguments[0], p_line, ci)) { + GDScriptCompletionIdentifier ci; + ci.type = base_type; + ci.value = base; + _find_call_arguments(p_context, ci, function, p_argidx, _static, r_result, r_arghint); - _find_type_arguments(context, p_node, p_line, id->name, ci, p_argidx, result, r_forced, arghint); - return; - } + if (function == "connect" && p_argidx == 2) { + Set<String> methods; + _find_identifiers_in_base(p_context, connect_base, true, methods); + for (Set<String>::Element *E = methods.front(); E; E = E->next()) { + r_result.insert("\"" + E->get().replace("(", "").replace(")", "") + "\""); } } + + r_forced = r_result.size() > 0; } Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_forced, String &r_call_hint) { - GDScriptParser p; + GDScriptParser parser; - p.parse(p_code, p_base_path, false, "", true); - bool isfunction = false; - Set<String> options; + parser.parse(p_code, p_base_path, false, "", true); r_forced = false; + Set<String> options; GDScriptCompletionContext context; - context._class = p.get_completion_class(); - context.block = p.get_completion_block(); - context.function = p.get_completion_function(); + context._class = parser.get_completion_class(); + context.block = parser.get_completion_block(); + context.function = parser.get_completion_function(); context.base = p_owner; context.base_path = p_base_path; + context.line = parser.get_completion_line(); + bool is_function = false; - switch (p.get_completion_type()) { - + switch (parser.get_completion_type()) { case GDScriptParser::COMPLETION_NONE: { } break; case GDScriptParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: { List<StringName> constants; - Variant::get_numeric_constants_for_type(p.get_completion_built_in_constant(), &constants); + Variant::get_numeric_constants_for_type(parser.get_completion_built_in_constant(), &constants); for (List<StringName>::Element *E = constants.front(); E; E = E->next()) { options.insert(E->get().operator String()); } - - } break; - case GDScriptParser::COMPLETION_FUNCTION: - isfunction = true; - case GDScriptParser::COMPLETION_IDENTIFIER: { - - _find_identifiers(context, p.get_completion_line(), isfunction, options); } break; case GDScriptParser::COMPLETION_PARENT_FUNCTION: { - + _find_identifiers_in_class(context, !context.function || context.function->_static, true, true, options); + } break; + case GDScriptParser::COMPLETION_FUNCTION: { + is_function = true; + } // fallthrough + case GDScriptParser::COMPLETION_IDENTIFIER: { + _find_identifiers(context, is_function, options); } break; case GDScriptParser::COMPLETION_GET_NODE: { - if (p_owner) { List<String> opts; p_owner->get_argument_options("get_node", 0, &opts); @@ -2204,315 +2474,358 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base } } } + + // Get autoloads + List<PropertyInfo> props; + ProjectSettings::get_singleton()->get_property_list(&props); + + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + String s = E->get().name; + if (!s.begins_with("autoload/")) { + continue; + } + String name = s.get_slice("/", 1); + options.insert("\"/root/" + name + "\""); + } } } break; - case GDScriptParser::COMPLETION_METHOD: - isfunction = true; + case GDScriptParser::COMPLETION_METHOD: { + is_function = true; + } // fallthrough case GDScriptParser::COMPLETION_INDEX: { - - const GDScriptParser::Node *node = p.get_completion_node(); - if (node->type != GDScriptParser::Node::TYPE_OPERATOR) + const GDScriptParser::Node *node = parser.get_completion_node(); + if (node->type != GDScriptParser::Node::TYPE_OPERATOR) { break; + } + const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(node); + if (op->arguments.size() < 1) { + break; + } - GDScriptCompletionIdentifier t; - if (_guess_expression_type(context, static_cast<const GDScriptParser::OperatorNode *>(node)->arguments[0], p.get_completion_line(), t, true)) { - - if (t.type == Variant::OBJECT && t.obj_type == "GDScriptNativeClass") { - //native enum - Ref<GDScriptNativeClass> gdn = t.value; - if (gdn.is_valid()) { - StringName cn = gdn->get_name(); - List<String> cnames; - ClassDB::get_integer_constant_list(cn, &cnames); - for (List<String>::Element *E = cnames.front(); E; E = E->next()) { - options.insert(E->get()); - } - - List<PropertyInfo> pinfo; - ClassDB::get_property_list(cn, &pinfo); - - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) - continue; - if (String(E->get().name).find("/") != -1) - continue; - options.insert(E->get().name); - } - } - } else if (t.type == Variant::OBJECT && t.obj_type != StringName()) { - - Ref<GDScript> on_script; - - if (t.value.get_type()) { - Object *obj = t.value; - - GDScript *scr = Object::cast_to<GDScript>(obj); - if (scr) { - while (scr) { + GDScriptCompletionIdentifier base; + if (!_guess_expression_type(context, op->arguments[0], base)) { + break; + } - if (!isfunction) { - for (const Map<StringName, Variant>::Element *E = scr->get_constants().front(); E; E = E->next()) { - options.insert(E->key()); - } - } - for (const Map<StringName, GDScriptFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { - if (E->get()->is_static()) - options.insert(E->key()); - } + GDScriptCompletionContext c = context; + c.function = NULL; + c.block = NULL; + c.base = base.value.get_type() == Variant::OBJECT ? base.value.operator Object *() : NULL; + if (base.type.kind == GDScriptParser::DataType::CLASS) { + c._class = base.type.class_type; + } else { + c._class = NULL; + } - if (scr->get_base().is_valid()) - scr = scr->get_base().ptr(); - else - scr = NULL; + _find_identifiers_in_base(c, base, is_function, options); + } break; + case GDScriptParser::COMPLETION_CALL_ARGUMENTS: { + _find_call_arguments(context, parser.get_completion_node(), parser.get_completion_argument_index(), options, r_forced, r_call_hint); + } break; + case GDScriptParser::COMPLETION_VIRTUAL_FUNC: { + GDScriptParser::DataType native_type = context._class->base_type; + while (native_type.has_type && native_type.kind != GDScriptParser::DataType::NATIVE) { + switch (native_type.kind) { + case GDScriptParser::DataType::CLASS: { + native_type = native_type.class_type->base_type; + } break; + case GDScriptParser::DataType::GDSCRIPT: { + Ref<GDScript> gds = native_type.script_type; + if (gds.is_valid()) { + Ref<GDScript> base = gds->get_base_script(); + if (base.is_valid()) { + native_type.script_type = base; + } else { + native_type.native_type = gds->get_instance_base_type(); + native_type.kind = GDScriptParser::DataType::NATIVE; } } else { - if (obj) { - on_script = obj->get_script(); - } + native_type.has_type = false; } - } - - if (!on_script.is_valid() && t.script.is_valid()) { - on_script = t.script; - } - - if (on_script.is_valid()) { - - GDScript *scr = on_script.ptr(); - if (scr) { - while (scr) { - - String code = scr->get_source_code(); - - if (code != "") { - //if there is code, parse it. This way is slower but updates in real-time - GDScriptParser p; - - Error err = p.parse(scr->get_source_code(), scr->get_path().get_base_dir(), true, "", false); - - if (err == OK) { - //only if ok, otherwise use what is cached on the script - //GDScriptParser::ClassNode *base = p. - const GDScriptParser::Node *root = p.get_parse_tree(); - ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, ERR_PARSE_ERROR); - - const GDScriptParser::ClassNode *cl = static_cast<const GDScriptParser::ClassNode *>(root); - - for (int i = 0; i < cl->functions.size(); i++) { - - if (cl->functions[i]->arguments.size()) - options.insert(String(cl->functions[i]->name) + "("); - else - options.insert(String(cl->functions[i]->name) + "()"); - } - - for (int i = 0; i < cl->static_functions.size(); i++) { - - if (cl->static_functions[i]->arguments.size()) - options.insert(String(cl->static_functions[i]->name) + "("); - else - options.insert(String(cl->static_functions[i]->name) + "()"); - } + } break; + default: { + native_type.has_type = false; + } break; + } + } - if (!isfunction) { - for (int i = 0; i < cl->variables.size(); i++) { + if (!native_type.has_type) { + break; + } - options.insert(String(cl->variables[i].identifier)); - } + StringName class_name = native_type.native_type; + if (!ClassDB::class_exists(class_name)) { + class_name = String("_") + class_name; + if (!ClassDB::class_exists(class_name)) { + break; + } + } - for (int i = 0; i < cl->constant_expressions.size(); i++) { + bool use_type_hint = EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints").operator bool(); - options.insert(String(cl->constant_expressions[i].identifier)); - } - } + List<MethodInfo> virtual_methods; + ClassDB::get_virtual_methods(class_name, &virtual_methods); + for (List<MethodInfo>::Element *E = virtual_methods.front(); E; E = E->next()) { - } else { - code = ""; //well, then no code - } - } - - if (code == "") { - //use class directly, no code was found - if (!isfunction) { - for (const Map<StringName, Variant>::Element *E = scr->get_constants().front(); E; E = E->next()) { - options.insert(E->key()); - } - } - for (const Map<StringName, GDScriptFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { - if (E->get()->get_argument_count()) - options.insert(String(E->key()) + "()"); - else - options.insert(String(E->key()) + "("); - } - - for (const Set<StringName>::Element *E = scr->get_members().front(); E; E = E->next()) { - options.insert(E->get()); - } - } + MethodInfo &mi = E->get(); + String method_hint = mi.name; + if (method_hint.find(":") != -1) { + method_hint = method_hint.get_slice(":", 0); + } + method_hint += "("; - if (scr->get_base().is_valid()) - scr = scr->get_base().ptr(); - else - scr = NULL; + if (mi.arguments.size()) { + for (int i = 0; i < mi.arguments.size(); i++) { + if (i > 0) { + method_hint += ", "; + } + String arg = mi.arguments[i].name; + if (arg.find(":") != -1) { + arg = arg.substr(0, arg.find(":")); + } + method_hint += arg; + if (use_type_hint && mi.arguments[i].type != Variant::NIL) { + method_hint += " : "; + if (mi.arguments[i].type == Variant::OBJECT && mi.arguments[i].class_name != StringName()) { + method_hint += mi.arguments[i].class_name.operator String(); + } else { + method_hint += Variant::get_type_name(mi.arguments[i].type); } } } - - if (!isfunction) { - ClassDB::get_integer_constant_list(t.obj_type, r_options); - - List<PropertyInfo> pinfo; - ClassDB::get_property_list(t.obj_type, &pinfo); - - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) - continue; - if (String(E->get().name).find("/") != -1) - continue; - r_options->push_back(E->get().name); - } + } + method_hint += ")"; + if (use_type_hint && (mi.return_val.type != Variant::NIL || !(mi.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) { + method_hint += " -> "; + if (mi.return_val.type == Variant::NIL) { + method_hint += "void"; + } else if (mi.return_val.type == Variant::OBJECT && mi.return_val.class_name != StringName()) { + method_hint += mi.return_val.class_name.operator String(); + } else { + method_hint += Variant::get_type_name(mi.return_val.type); } + } + method_hint += ":"; - List<MethodInfo> mi; - ClassDB::get_method_list(t.obj_type, &mi, false, true); - for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { - - if (E->get().name.begins_with("_")) - continue; + options.insert(method_hint); + } + } break; + case GDScriptParser::COMPLETION_YIELD: { + const GDScriptParser::Node *node = parser.get_completion_node(); - if (E->get().arguments.size()) - options.insert(E->get().name + "("); - else - options.insert(E->get().name + "()"); - } - } else { + GDScriptCompletionContext c = context; + c.line = node->line; + GDScriptCompletionIdentifier type; + if (!_guess_expression_type(c, node, type)) { + break; + } - //check InputEvent hint - { - if (t.value.get_type() == Variant::NIL) { - Variant::CallError ce; - t.value = Variant::construct(t.type, NULL, 0, ce); + GDScriptParser::DataType base_type = type.type; + while (base_type.has_type) { + switch (base_type.kind) { + case GDScriptParser::DataType::CLASS: { + for (int i = 0; i < base_type.class_type->_signals.size(); i++) { + options.insert("\"" + base_type.class_type->_signals[i].name.operator String() + "\""); } - - if (!isfunction) { - List<PropertyInfo> pl; - t.value.get_property_list(&pl); - for (List<PropertyInfo>::Element *E = pl.front(); E; E = E->next()) { - - if (String(E->get().name).find("/") == -1) - options.insert(E->get().name); + base_type = base_type.class_type->base_type; + } break; + case GDScriptParser::DataType::SCRIPT: + case GDScriptParser::DataType::GDSCRIPT: { + Ref<Script> scr = base_type.script_type; + if (scr.is_valid()) { + List<MethodInfo> signals; + scr->get_script_signal_list(&signals); + for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { + options.insert("\"" + E->get().name + "\""); + } + Ref<Script> base_script = scr->get_base_script(); + if (base_script.is_valid()) { + base_type.script_type = base_script; + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = scr->get_instance_base_type(); + } + } else { + base_type.has_type = false; + } + } break; + case GDScriptParser::DataType::NATIVE: { + base_type.has_type = false; + + StringName class_name = base_type.native_type; + if (!ClassDB::class_exists(class_name)) { + class_name = String("_") + class_name; + if (!ClassDB::class_exists(class_name)) { + break; } } - List<MethodInfo> mi; - t.value.get_method_list(&mi); - for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { - if (E->get().arguments.size()) - options.insert(E->get().name + "("); - else - options.insert(E->get().name + "()"); + List<MethodInfo> signals; + ClassDB::get_signal_list(class_name, &signals); + for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { + options.insert("\"" + E->get().name + "\""); } + } break; + default: { + base_type.has_type = false; } } } - } break; - case GDScriptParser::COMPLETION_CALL_ARGUMENTS: { - - _find_call_arguments(context, p.get_completion_node(), p.get_completion_line(), p.get_completion_argument_index(), options, r_forced, r_call_hint); + case GDScriptParser::COMPLETION_RESOURCE_PATH: { + if (EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths")) { + _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), options); + r_forced = true; + } } break; - case GDScriptParser::COMPLETION_VIRTUAL_FUNC: { - - GDScriptCompletionIdentifier cid = _get_native_class(context); - - if (cid.obj_type != StringName()) { - List<MethodInfo> vm; - ClassDB::get_virtual_methods(cid.obj_type, &vm); - for (List<MethodInfo>::Element *E = vm.front(); E; E = E->next()) { + case GDScriptParser::COMPLETION_ASSIGN: { + GDScriptCompletionIdentifier type; + if (!_guess_expression_type(context, parser.get_completion_node(), type)) { + break; + } - MethodInfo &mi = E->get(); - String m = mi.name; - if (m.find(":") != -1) - m = m.substr(0, m.find(":")); - m += "("; - - if (mi.arguments.size()) { - for (int i = 0; i < mi.arguments.size(); i++) { - if (i > 0) - m += ", "; - String n = mi.arguments[i].name; - if (n.find(":") != -1) - n = n.substr(0, n.find(":")); - m += n; + if (!type.enumeration.empty()) { + _find_enumeration_candidates(type.enumeration, options); + r_forced = options.size() > 0; + } + } break; + case GDScriptParser::COMPLETION_TYPE_HINT: { + const GDScriptParser::ClassNode *clss = context._class; + while (clss) { + for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = clss->constant_expressions.front(); E; E = E->next()) { + GDScriptCompletionIdentifier constant; + GDScriptCompletionContext c = context; + c.function = NULL; + c.block = NULL; + c.line = E->value().expression->line; + if (_guess_expression_type(c, E->value().expression, constant)) { + if (constant.type.has_type && constant.type.is_meta_type) { + options.insert(E->key().operator String()); } } - m += "):"; + } + for (int i = 0; i < clss->subclasses.size(); i++) { + if (clss->subclasses[i]->name != StringName()) { + options.insert(clss->subclasses[i]->name.operator String()); + } + } + clss = clss->owner; + for (int i = 0; i < Variant::VARIANT_MAX; i++) { + options.insert(Variant::get_type_name((Variant::Type)i)); + } + } - options.insert(m); + List<StringName> native_classes; + ClassDB::get_class_list(&native_classes); + for (List<StringName>::Element *E = native_classes.front(); E; E = E->next()) { + String class_name = E->get().operator String(); + if (class_name.begins_with("_")) { + class_name = class_name.right(1); + } + if (Engine::get_singleton()->has_singleton(class_name)) { + continue; } + options.insert(class_name); } - } break; - case GDScriptParser::COMPLETION_YIELD: { - const GDScriptParser::Node *node = p.get_completion_node(); + // Named scripts + List<StringName> named_scripts; + ScriptServer::get_global_class_list(&named_scripts); + for (List<StringName>::Element *E = named_scripts.front(); E; E = E->next()) { + options.insert(E->get().operator String()); + } - GDScriptCompletionIdentifier t; - if (!_guess_expression_type(context, node, p.get_completion_line(), t)) + if (parser.get_completion_identifier_is_function()) { + options.insert("void"); + } + r_forced = true; + } break; + case GDScriptParser::COMPLETION_TYPE_HINT_INDEX: { + GDScriptCompletionIdentifier base; + String index = parser.get_completion_cursor().operator String(); + if (!_guess_identifier_type(context, index.get_slice(".", 0), base)) { break; + } - if (t.type == Variant::OBJECT && t.obj_type != StringName()) { + GDScriptCompletionContext c = context; + c._class = NULL; + c.function = NULL; + c.block = NULL; + bool finding = true; + index = index.right(index.find(".") + 1); + while (index.find(".") != -1) { + String id = index.get_slice(".", 0); - List<MethodInfo> sigs; - ClassDB::get_signal_list(t.obj_type, &sigs); - for (List<MethodInfo>::Element *E = sigs.front(); E; E = E->next()) { - options.insert("\"" + E->get().name + "\""); - r_forced = true; + GDScriptCompletionIdentifier sub_base; + if (!_guess_identifier_type_from_base(c, base, id, sub_base)) { + finding = false; + break; } + index = index.right(index.find(".") + 1); + base = sub_base; } - } break; - case GDScriptParser::COMPLETION_RESOURCE_PATH: { - - if (EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths")) { - get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), options); - r_forced = true; + if (!finding) { + break; } - } break; - case GDScriptParser::COMPLETION_ASSIGN: { -#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) - GDScriptCompletionIdentifier ci; - if (_guess_expression_type(context, p.get_completion_node(), p.get_completion_line(), ci)) { - - String enumeration = ci.enumeration; - if (enumeration.find(".") != -1) { - //class constant - List<StringName> constants; - String cls = enumeration.get_slice(".", 0); - String enm = enumeration.get_slice(".", 1); - - ClassDB::get_enum_constants(cls, enm, &constants); - //constants.sort_custom<StringName::AlphCompare>(); - for (List<StringName>::Element *E = constants.front(); E; E = E->next()) { - String add = cls + "." + E->get(); - r_options->push_back(add); - r_forced = true; - } - } else { - - //global constant - StringName current_enum = enumeration; + GDScriptParser::DataType base_type = base.type; + while (base_type.has_type) { + switch (base_type.kind) { + case GDScriptParser::DataType::CLASS: { + if (base_type.class_type) { + for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = base_type.class_type->constant_expressions.front(); E; E = E->next()) { + GDScriptCompletionIdentifier constant; + GDScriptCompletionContext c = context; + c._class = base_type.class_type; + c.function = NULL; + c.block = NULL; + c.line = E->value().expression->line; + if (_guess_expression_type(c, E->value().expression, constant)) { + if (constant.type.has_type && constant.type.is_meta_type) { + options.insert(E->key().operator String()); + } + } + } + for (int i = 0; i < base_type.class_type->subclasses.size(); i++) { + if (base_type.class_type->subclasses[i]->name != StringName()) { + options.insert(base_type.class_type->subclasses[i]->name.operator String()); + } + } - for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) { - if (GlobalConstants::get_global_constant_enum(i) == current_enum) { - r_options->push_back(GlobalConstants::get_global_constant_name(i)); - r_forced = true; + base_type = base_type.class_type->base_type; + } else { + base_type.has_type = false; } - } - //global + } break; + case GDScriptParser::DataType::SCRIPT: + case GDScriptParser::DataType::GDSCRIPT: { + Ref<Script> scr = base_type.script_type; + if (scr.is_valid()) { + Map<StringName, Variant> constants; + scr->get_constants(&constants); + for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) { + Ref<Script> const_scr = E->value(); + if (const_scr.is_valid()) { + options.insert(E->key().operator String()); + } + } + Ref<Script> base_script = scr->get_base_script(); + if (base_script.is_valid()) { + base_type.script_type = base_script; + } else { + base_type.has_type = false; + } + } else { + base_type.has_type = false; + } + } break; + default: { + base_type.has_type = false; + } break; } } -#endif + r_forced = options.size() > 0; } break; } @@ -2531,6 +2844,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base #endif +//////// END COMPLETION ////////// + String GDScriptLanguage::_get_indentation() const { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { @@ -2616,6 +2931,185 @@ void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_t #ifdef TOOLS_ENABLED +static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, const String &p_symbol, bool p_is_function, GDScriptLanguage::LookupResult &r_result) { + GDScriptParser::DataType base_type = p_base; + + while (base_type.has_type) { + switch (base_type.kind) { + case GDScriptParser::DataType::CLASS: { + if (base_type.class_type) { + if (p_is_function) { + for (int i = 0; i < base_type.class_type->functions.size(); i++) { + if (base_type.class_type->functions[i]->name == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = base_type.class_type->functions[i]->line; + return OK; + } + } + for (int i = 0; i < base_type.class_type->static_functions.size(); i++) { + if (base_type.class_type->static_functions[i]->name == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = base_type.class_type->static_functions[i]->line; + return OK; + } + } + } else { + if (base_type.class_type->constant_expressions.has(p_symbol)) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = base_type.class_type->constant_expressions[p_symbol].expression->line; + return OK; + } + + for (int i = 0; i < base_type.class_type->variables.size(); i++) { + if (base_type.class_type->variables[i].identifier == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = base_type.class_type->variables[i].line; + return OK; + } + } + } + } + base_type = base_type.class_type->base_type; + } break; + case GDScriptParser::DataType::SCRIPT: + case GDScriptParser::DataType::GDSCRIPT: { + Ref<Script> scr = base_type.script_type; + if (scr.is_valid()) { + int line = scr->get_member_line(p_symbol); + if (line >= 0) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = line; + r_result.script = scr; + return OK; + } + Ref<Script> base_script = scr->get_base_script(); + if (base_script.is_valid()) { + base_type.script_type = base_script; + } else { + base_type.kind = GDScriptParser::DataType::NATIVE; + base_type.native_type = scr->get_instance_base_type(); + } + } else { + base_type.has_type = false; + } + } break; + case GDScriptParser::DataType::NATIVE: { + StringName class_name = base_type.native_type; + if (!ClassDB::class_exists(class_name)) { + class_name = String("_") + class_name; + if (!ClassDB::class_exists(class_name)) { + base_type.has_type = false; + break; + } + } + + if (ClassDB::has_method(class_name, p_symbol, true)) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; + r_result.class_name = base_type.native_type; + r_result.class_member = p_symbol; + return OK; + } + + List<MethodInfo> virtual_methods; + ClassDB::get_virtual_methods(class_name, &virtual_methods, true); + for (List<MethodInfo>::Element *E = virtual_methods.front(); E; E = E->next()) { + if (E->get().name == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; + r_result.class_name = base_type.native_type; + r_result.class_member = p_symbol; + return OK; + } + } + + StringName enum_name = ClassDB::get_integer_constant_enum(class_name, p_symbol, true); + if (enum_name != StringName()) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_ENUM; + r_result.class_name = base_type.native_type; + r_result.class_member = enum_name; + return OK; + } + + List<String> constants; + ClassDB::get_integer_constant_list(class_name, &constants, true); + for (List<String>::Element *E = constants.front(); E; E = E->next()) { + if (E->get() == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; + r_result.class_name = base_type.native_type; + r_result.class_member = p_symbol; + return OK; + } + } + + List<PropertyInfo> properties; + ClassDB::get_property_list(class_name, &properties, true); + for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { + if (E->get().name == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; + r_result.class_name = base_type.native_type; + r_result.class_member = p_symbol; + return OK; + } + } + + StringName parent = ClassDB::get_parent_class(class_name); + if (parent != StringName()) { + if (String(parent).begins_with("_")) { + base_type.native_type = String(parent).right(1); + } else { + base_type.native_type = parent; + } + } else { + base_type.has_type = false; + } + } break; + case GDScriptParser::DataType::BUILTIN: { + base_type.has_type = false; + + if (Variant::has_numeric_constant(base_type.builtin_type, p_symbol)) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; + r_result.class_name = Variant::get_type_name(base_type.builtin_type); + r_result.class_member = p_symbol; + return OK; + } + + Variant v; + REF v_ref; + if (base_type.builtin_type == Variant::OBJECT) { + v_ref.instance(); + v = v_ref; + } else { + Variant::CallError err; + v = Variant::construct(base_type.builtin_type, NULL, 0, err); + if (err.error != Variant::CallError::CALL_OK) { + break; + } + } + + if (v.has_method(p_symbol)) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; + r_result.class_name = Variant::get_type_name(base_type.builtin_type); + r_result.class_member = p_symbol; + return OK; + } + + bool valid = false; + v.get(p_symbol, &valid); + if (valid) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; + r_result.class_name = Variant::get_type_name(base_type.builtin_type); + r_result.class_member = p_symbol; + return OK; + } + } break; + default: { + base_type.has_type = false; + } break; + } + } + + return ERR_CANT_RESOLVE; +} + Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result) { //before parsing, try the usual stuff @@ -2623,6 +3117,13 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS; r_result.class_name = p_symbol; return OK; + } else { + String under_prefix = "_" + p_symbol; + if (ClassDB::class_exists(under_prefix)) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS; + r_result.class_name = p_symbol; + return OK; + } } for (int i = 0; i < Variant::VARIANT_MAX; i++) { @@ -2650,17 +3151,18 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol return OK; } - GDScriptParser p; - p.parse(p_code, p_base_path, false, "", true); + GDScriptParser parser; + parser.parse(p_code, p_base_path, false, "", true); - if (p.get_completion_type() == GDScriptParser::COMPLETION_NONE) + if (parser.get_completion_type() == GDScriptParser::COMPLETION_NONE) { return ERR_CANT_RESOLVE; + } GDScriptCompletionContext context; - - context._class = p.get_completion_class(); - context.block = p.get_completion_block(); - context.function = p.get_completion_function(); + context._class = parser.get_completion_class(); + context.function = parser.get_completion_function(); + context.block = parser.get_completion_block(); + context.line = parser.get_completion_line(); context.base = p_owner; context.base_path = p_base_path; @@ -2675,171 +3177,68 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol } } - bool isfunction = false; + bool is_function = false; - switch (p.get_completion_type()) { - - case GDScriptParser::COMPLETION_GET_NODE: - case GDScriptParser::COMPLETION_NONE: { - } break; + switch (parser.get_completion_type()) { case GDScriptParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: { - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; - r_result.class_name = Variant::get_type_name(p.get_completion_built_in_constant()); + r_result.class_name = Variant::get_type_name(parser.get_completion_built_in_constant()); r_result.class_member = p_symbol; return OK; - } break; + case GDScriptParser::COMPLETION_PARENT_FUNCTION: case GDScriptParser::COMPLETION_FUNCTION: { - - if (context._class && context._class->functions.size()) { - for (int i = 0; i < context._class->functions.size(); i++) { - if (context._class->functions[i]->name == p_symbol) { - r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location = context._class->functions[i]->line; - return OK; - } - } - } - - Ref<GDScript> parent = _get_parent_class(context); - while (parent.is_valid()) { - int line = parent->get_member_line(p_symbol); - if (line >= 0) { - r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location = line; - r_result.script = parent; - return OK; - } - - parent = parent->get_base(); - } - - GDScriptCompletionIdentifier identifier = _get_native_class(context); - print_line("identifier: " + String(identifier.obj_type)); - - if (ClassDB::has_method(identifier.obj_type, p_symbol)) { - - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name = identifier.obj_type; - r_result.class_member = p_symbol; - return OK; - } - - } break; + is_function = true; + } // fallthrough case GDScriptParser::COMPLETION_IDENTIFIER: { - //check if a function - if (p.get_completion_identifier_is_function()) { - if (context._class && context._class->functions.size()) { - for (int i = 0; i < context._class->functions.size(); i++) { - if (context._class->functions[i]->name == p_symbol) { - r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location = context._class->functions[i]->line; - return OK; - } - } - } - - Ref<GDScript> parent = _get_parent_class(context); - while (parent.is_valid()) { - int line = parent->get_member_line(p_symbol); - if (line >= 0) { - r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location = line; - r_result.script = parent; - return OK; - } - - parent = parent->get_base(); - } - - GDScriptCompletionIdentifier identifier = _get_native_class(context); - - if (ClassDB::has_method(identifier.obj_type, p_symbol)) { + if (!is_function) { + is_function = parser.get_completion_identifier_is_function(); + } - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name = identifier.obj_type; - r_result.class_member = p_symbol; - return OK; + GDScriptParser::DataType base_type; + if (context._class) { + if (parser.get_completion_type() != GDScriptParser::COMPLETION_PARENT_FUNCTION) { + base_type.has_type = true; + base_type.kind = GDScriptParser::DataType::CLASS; + base_type.class_type = const_cast<GDScriptParser::ClassNode *>(context._class); + } else { + base_type = context._class->base_type; } } else { + break; + } - GDScriptCompletionIdentifier gdi = _get_native_class(context); - if (gdi.obj_type != StringName()) { - bool valid; - Variant::Type t = ClassDB::get_property_type(gdi.obj_type, p_symbol, &valid); - if (t != Variant::NIL && valid) { - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; - r_result.class_name = gdi.obj_type; - r_result.class_member = p_symbol; - return OK; - } - } - + if (!is_function && context.block) { + // Lookup local variables const GDScriptParser::BlockNode *block = context.block; - //search in blocks going up (local var?) while (block) { - - for (int i = 0; i < block->statements.size(); i++) { - - if (block->statements[i]->line > p.get_completion_line()) - continue; - - if (block->statements[i]->type == GDScriptParser::BlockNode::TYPE_LOCAL_VAR) { - - const GDScriptParser::LocalVarNode *lv = static_cast<const GDScriptParser::LocalVarNode *>(block->statements[i]); - - if (lv->assign && lv->name == p_symbol) { - - r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location = block->statements[i]->line; - return OK; - } - } + if (block->variables.has(p_symbol)) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = block->variables[p_symbol]->line; + return OK; } block = block->parent_block; } + } - //guess from function arguments - if (context.function && context.function->name != StringName()) { - - for (int i = 0; i < context.function->arguments.size(); i++) { - - if (context.function->arguments[i] == p_symbol) { - r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location = context.function->line; - return OK; - } - } - } - - //guess in class constants - - for (int i = 0; i < context._class->constant_expressions.size(); i++) { - - if (context._class->constant_expressions[i].identifier == p_symbol) { + if (context.function && context.function->name != StringName()) { + // Lookup function arguments + for (int i = 0; i < context.function->arguments.size(); i++) { + if (context.function->arguments[i] == p_symbol) { r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location = context._class->constant_expressions[i].expression->line; + r_result.location = context.function->line; return OK; } } + } - //guess in class variables - if (!(context.function && context.function->_static)) { - - for (int i = 0; i < context._class->variables.size(); i++) { - - if (context._class->variables[i].identifier == p_symbol) { - - r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location = context._class->variables[i].line; - return OK; - } - } - } + if (_lookup_symbol_from_base(base_type, p_symbol, is_function, r_result) == OK) { + return OK; + } - //guess in autoloads as singletons + if (!is_function) { + // Guess in autoloads as singletons List<PropertyInfo> props; ProjectSettings::get_singleton()->get_property_list(&props); @@ -2856,8 +3255,8 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol String script = path.substr(1, path.length()); if (!script.ends_with(".gd")) { - //not a script, try find the script anyway, - //may have some success + // Not a script, try find the script anyway, + // may have some success script = script.get_basename() + ".gd"; } @@ -2872,7 +3271,7 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol } } - //global + // Global Map<StringName, int> classes = GDScriptLanguage::get_singleton()->get_global_map(); if (classes.has(p_symbol)) { Variant value = GDScriptLanguage::get_singleton()->get_global_array()[classes[p_symbol]]; @@ -2918,152 +3317,31 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol } } } - - } break; - case GDScriptParser::COMPLETION_PARENT_FUNCTION: { - } break; - case GDScriptParser::COMPLETION_METHOD: - isfunction = true; + case GDScriptParser::COMPLETION_METHOD: { + is_function = true; + } // fallthrough case GDScriptParser::COMPLETION_INDEX: { - - const GDScriptParser::Node *node = p.get_completion_node(); - if (node->type != GDScriptParser::Node::TYPE_OPERATOR) + const GDScriptParser::Node *node = parser.get_completion_node(); + if (node->type != GDScriptParser::Node::TYPE_OPERATOR) { + break; + } + GDScriptCompletionIdentifier base; + if (!_guess_expression_type(context, static_cast<const GDScriptParser::OperatorNode *>(node)->arguments[0], base)) { break; - - GDScriptCompletionIdentifier t; - if (_guess_expression_type(context, static_cast<const GDScriptParser::OperatorNode *>(node)->arguments[0], p.get_completion_line(), t)) { - - if (t.type == Variant::OBJECT && t.obj_type == "GDScriptNativeClass") { - //native enum - Ref<GDScriptNativeClass> gdn = t.value; - if (gdn.is_valid()) { - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; - r_result.class_name = gdn->get_name(); - r_result.class_member = p_symbol; - return OK; - } - } else if (t.type == Variant::OBJECT && t.obj_type != StringName()) { - - Ref<GDScript> on_script; - - if (t.value.get_type()) { - Object *obj = t.value; - - if (obj) { - - on_script = obj->get_script(); - - if (on_script.is_valid()) { - int loc = on_script->get_member_line(p_symbol); - if (loc >= 0) { - r_result.script = on_script; - r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location = loc; - return OK; - } - } - } - } - - if (ClassDB::has_method(t.obj_type, p_symbol)) { - - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name = t.obj_type; - r_result.class_member = p_symbol; - return OK; - } - - StringName enumName = ClassDB::get_integer_constant_enum(t.obj_type, p_symbol, true); - if (enumName != StringName()) { - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_ENUM; - r_result.class_name = t.obj_type; - r_result.class_member = enumName; - return OK; - } - - bool success; - ClassDB::get_integer_constant(t.obj_type, p_symbol, &success); - if (success) { - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; - r_result.class_name = t.obj_type; - r_result.class_member = p_symbol; - return OK; - } - - ClassDB::get_property_type(t.obj_type, p_symbol, &success); - - if (success) { - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; - r_result.class_name = t.obj_type; - r_result.class_member = p_symbol; - return OK; - } - - } else { - - Variant::CallError ce; - Variant v = Variant::construct(t.type, NULL, 0, ce); - - bool valid; - v.get_numeric_constant_value(t.type, p_symbol, &valid); - if (valid) { - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; - r_result.class_name = Variant::get_type_name(t.type); - r_result.class_member = p_symbol; - return OK; - } - - //todo check all inputevent types for property - - v.get(p_symbol, &valid); - - if (valid) { - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; - r_result.class_name = Variant::get_type_name(t.type); - r_result.class_member = p_symbol; - return OK; - } - - if (v.has_method(p_symbol)) { - - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name = Variant::get_type_name(t.type); - r_result.class_member = p_symbol; - return OK; - } - } } - } break; - case GDScriptParser::COMPLETION_CALL_ARGUMENTS: { - - return ERR_CANT_RESOLVE; + if (_lookup_symbol_from_base(base.type, p_symbol, is_function, r_result) == OK) { + return OK; + } } break; case GDScriptParser::COMPLETION_VIRTUAL_FUNC: { + GDScriptParser::DataType base_type = context._class->base_type; - GDScriptCompletionIdentifier cid = _get_native_class(context); - - if (cid.obj_type != StringName()) { - List<MethodInfo> vm; - ClassDB::get_virtual_methods(cid.obj_type, &vm); - for (List<MethodInfo>::Element *E = vm.front(); E; E = E->next()) { - - if (p_symbol == E->get().name) { - - r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name = cid.obj_type; - r_result.class_member = p_symbol; - return OK; - } - } + if (_lookup_symbol_from_base(base_type, p_symbol, true, r_result) == OK) { + return OK; } } break; - case GDScriptParser::COMPLETION_YIELD: { - - return ERR_CANT_RESOLVE; - - } break; } return ERR_CANT_RESOLVE; diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp index 10599f0c38..6a08d86904 100644 --- a/modules/gdscript/gdscript_function.cpp +++ b/modules/gdscript/gdscript_function.cpp @@ -200,6 +200,12 @@ static String _get_var_type(const Variant *p_type) { &&OPCODE_ASSIGN, \ &&OPCODE_ASSIGN_TRUE, \ &&OPCODE_ASSIGN_FALSE, \ + &&OPCODE_ASSIGN_TYPED_BUILTIN, \ + &&OPCODE_ASSIGN_TYPED_NATIVE, \ + &&OPCODE_ASSIGN_TYPED_SCRIPT, \ + &&OPCODE_CAST_TO_BUILTIN, \ + &&OPCODE_CAST_TO_NATIVE, \ + &&OPCODE_CAST_TO_SCRIPT, \ &&OPCODE_CONSTRUCT, \ &&OPCODE_CONSTRUCT_ARRAY, \ &&OPCODE_CONSTRUCT_DICTIONARY, \ @@ -318,10 +324,28 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a if (_stack_size) { stack = (Variant *)aptr; - for (int i = 0; i < p_argcount; i++) - memnew_placement(&stack[i], Variant(*p_args[i])); - for (int i = p_argcount; i < _stack_size; i++) + for (int i = 0; i < p_argcount; i++) { + if (!argument_types[i].has_type) { + memnew_placement(&stack[i], Variant(*p_args[i])); + continue; + } + + if (!argument_types[i].is_type(*p_args[i], true)) { + r_err.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_err.argument = i; + r_err.expected = argument_types[i].kind == GDScriptDataType::BUILTIN ? argument_types[i].builtin_type : Variant::OBJECT; + return Variant(); + } + if (argument_types[i].kind == GDScriptDataType::BUILTIN) { + Variant arg = Variant::construct(argument_types[i].builtin_type, &p_args[i], 1, r_err); + memnew_placement(&stack[i], Variant(arg)); + } else { + memnew_placement(&stack[i], Variant(*p_args[i])); + } + } + for (int i = p_argcount; i < _stack_size; i++) { memnew_placement(&stack[i], Variant); + } } else { stack = NULL; } @@ -709,6 +733,199 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a } DISPATCH_OPCODE; + OPCODE(OPCODE_ASSIGN_TYPED_BUILTIN) { + + CHECK_SPACE(4); + Variant::Type var_type = (Variant::Type)_code_ptr[ip + 1]; + GET_VARIANT_PTR(dst, 2); + GET_VARIANT_PTR(src, 3); + + GD_ERR_BREAK(var_type < 0 || var_type >= Variant::VARIANT_MAX); + + if (src->get_type() != var_type) { + err_text = "Trying to assign value of type '" + Variant::get_type_name(src->get_type()) + + "' to a variable of type '" + Variant::get_type_name(var_type) + "'."; + OPCODE_BREAK; + } + + *dst = *src; + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ASSIGN_TYPED_NATIVE) { + + CHECK_SPACE(4); + GET_VARIANT_PTR(type, 1); + GET_VARIANT_PTR(dst, 2); + GET_VARIANT_PTR(src, 3); + + GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(type->operator Object *()); + GD_ERR_BREAK(!nc); + Object *src_obj = src->operator Object *(); + GD_ERR_BREAK(!src_obj); + + if (!ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) { + err_text = "Trying to assign value of type '" + src_obj->get_class_name() + + "' to a variable of type '" + nc->get_name() + "'."; + OPCODE_BREAK; + } + + *dst = *src; + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_ASSIGN_TYPED_SCRIPT) { + + CHECK_SPACE(4); + GET_VARIANT_PTR(type, 1); + GET_VARIANT_PTR(dst, 2); + GET_VARIANT_PTR(src, 3); + + Script *base_type = Object::cast_to<Script>(type->operator Object *()); + + GD_ERR_BREAK(!base_type); + + if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { + err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'."; + OPCODE_BREAK; + } + + if (src->get_type() != Variant::NIL && src->operator Object *() != NULL) { + + ScriptInstance *scr_inst = src->operator Object *()->get_script_instance(); + if (!scr_inst) { + err_text = "Trying to assign value of type '" + src->operator Object *()->get_class_name() + + "' to a variable of type '" + base_type->get_path().get_file() + "'."; + OPCODE_BREAK; + } + + Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr(); + bool valid = false; + + while (src_type) { + if (src_type == base_type) { + valid = true; + break; + } + src_type = src_type->get_base_script().ptr(); + } + + if (!valid) { + err_text = "Trying to assign value of type '" + src->operator Object *()->get_script_instance()->get_script()->get_path().get_file() + + "' to a variable of type '" + base_type->get_path().get_file() + "'."; + OPCODE_BREAK; + } + } + + *dst = *src; + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CAST_TO_BUILTIN) { + + CHECK_SPACE(4); + Variant::Type to_type = (Variant::Type)_code_ptr[ip + 1]; + GET_VARIANT_PTR(src, 2); + GET_VARIANT_PTR(dst, 3); + + GD_ERR_BREAK(to_type < 0 || to_type >= Variant::VARIANT_MAX); + + Variant::CallError err; + *dst = Variant::construct(to_type, (const Variant **)&src, 1, err); + +#ifdef DEBUG_ENABLED + if (err.error != Variant::CallError::CALL_OK) { + err_text = "Invalid cast: could not convert value to '" + Variant::get_type_name(to_type) + "'."; + OPCODE_BREAK; + } +#endif + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CAST_TO_NATIVE) { + + CHECK_SPACE(4); + GET_VARIANT_PTR(to_type, 1); + GET_VARIANT_PTR(src, 2); + GET_VARIANT_PTR(dst, 3); + + GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(to_type->operator Object *()); + GD_ERR_BREAK(!nc); + +#ifdef DEBUG_ENABLED + if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { + err_text = "Invalid cast: can't convert a non-object value to an object type."; + OPCODE_BREAK; + } +#endif + Object *src_obj = src->operator Object *(); + + if (src_obj && !ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) { + *dst = Variant(); // invalid cast, assign NULL + } else { + *dst = *src; + } + + ip += 4; + } + DISPATCH_OPCODE; + + OPCODE(OPCODE_CAST_TO_SCRIPT) { + + CHECK_SPACE(4); + GET_VARIANT_PTR(to_type, 1); + GET_VARIANT_PTR(src, 2); + GET_VARIANT_PTR(dst, 3); + + Script *base_type = Object::cast_to<Script>(to_type->operator Object *()); + + GD_ERR_BREAK(!base_type); + +#ifdef DEBUG_ENABLED + if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) { + err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'."; + OPCODE_BREAK; + } +#endif + + bool valid = false; + + if (src->get_type() != Variant::NIL && src->operator Object *() != NULL) { + + ScriptInstance *scr_inst = src->operator Object *()->get_script_instance(); + + if (scr_inst) { + + Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr(); + + while (src_type) { + if (src_type == base_type) { + valid = true; + break; + } + src_type = src_type->get_base_script().ptr(); + } + } + } + + if (valid) { + *dst = *src; // Valid cast, copy the source object + } else { + *dst = Variant(); // invalid cast, assign NULL + } + + ip += 4; + } + DISPATCH_OPCODE; + OPCODE(OPCODE_CONSTRUCT) { CHECK_SPACE(2); @@ -1370,6 +1587,15 @@ int GDScriptFunction::get_default_argument_addr(int p_idx) const { return default_arguments[p_idx]; } +GDScriptDataType GDScriptFunction::get_return_type() const { + return return_type; +} + +GDScriptDataType GDScriptFunction::get_argument_type(int p_idx) const { + ERR_FAIL_INDEX_V(p_idx, argument_types.size(), GDScriptDataType()); + return argument_types[p_idx]; +} + StringName GDScriptFunction::get_name() const { return name; diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h index 770d5c8733..3ce84290fd 100644 --- a/modules/gdscript/gdscript_function.h +++ b/modules/gdscript/gdscript_function.h @@ -42,6 +42,95 @@ class GDScriptInstance; class GDScript; +struct GDScriptDataType { + bool has_type; + enum { + BUILTIN, + NATIVE, + SCRIPT, + GDSCRIPT + } kind; + Variant::Type builtin_type; + StringName native_type; + Ref<Script> script_type; + + bool is_type(const Variant &p_variant, bool p_allow_implicit_conversion = false) const { + if (!has_type) return true; // Can't type check + + switch (kind) { + case BUILTIN: { + Variant::Type var_type = p_variant.get_type(); + bool valid = builtin_type == var_type; + if (!valid && p_allow_implicit_conversion) { + valid = Variant::can_convert_strict(var_type, builtin_type); + } + return valid; + } break; + case NATIVE: { + if (p_variant.get_type() == Variant::NIL) { + return true; + } + if (p_variant.get_type() != Variant::OBJECT) { + return false; + } + Object *obj = p_variant.operator Object *(); + if (obj && !ClassDB::is_parent_class(obj->get_class_name(), native_type)) { + return false; + } + return true; + } break; + case SCRIPT: + case GDSCRIPT: { + if (p_variant.get_type() == Variant::NIL) { + return true; + } + if (p_variant.get_type() != Variant::OBJECT) { + return false; + } + Object *obj = p_variant.operator Object *(); + Ref<Script> base = obj && obj->get_script_instance() ? obj->get_script_instance()->get_script() : NULL; + bool valid = false; + while (base.is_valid()) { + if (base == script_type) { + valid = true; + break; + } + base = base->get_base_script(); + } + return valid; + } break; + } + return false; + } + + operator PropertyInfo() const { + PropertyInfo info; + if (has_type) { + switch (kind) { + case BUILTIN: { + info.type = builtin_type; + } break; + case NATIVE: { + info.type = Variant::OBJECT; + info.class_name = native_type; + } break; + case SCRIPT: + case GDSCRIPT: { + info.type = Variant::OBJECT; + info.class_name = script_type->get_instance_base_type(); + } break; + } + } else { + info.type = Variant::NIL; + info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; + } + return info; + } + + GDScriptDataType() : + has_type(false) {} +}; + class GDScriptFunction { public: enum Opcode { @@ -56,6 +145,12 @@ public: OPCODE_ASSIGN, OPCODE_ASSIGN_TRUE, OPCODE_ASSIGN_FALSE, + OPCODE_ASSIGN_TYPED_BUILTIN, + OPCODE_ASSIGN_TYPED_NATIVE, + OPCODE_ASSIGN_TYPED_SCRIPT, + OPCODE_CAST_TO_BUILTIN, + OPCODE_CAST_TO_NATIVE, + OPCODE_CAST_TO_SCRIPT, OPCODE_CONSTRUCT, //only for basic types!! OPCODE_CONSTRUCT_ARRAY, OPCODE_CONSTRUCT_DICTIONARY, @@ -139,6 +234,8 @@ private: #endif Vector<int> default_arguments; Vector<int> code; + Vector<GDScriptDataType> argument_types; + GDScriptDataType return_type; #ifdef TOOLS_ENABLED Vector<StringName> arg_names; @@ -199,6 +296,8 @@ public: int get_max_stack_size() const; int get_default_argument_count() const; int get_default_argument_addr(int p_idx) const; + GDScriptDataType get_return_type() const; + GDScriptDataType get_argument_type(int p_idx) const; GDScript *get_script() const { return _script; } StringName get_source() const { return source; } diff --git a/modules/gdscript/gdscript_functions.cpp b/modules/gdscript/gdscript_functions.cpp index ce91e7dff3..7e98b6ced9 100644 --- a/modules/gdscript/gdscript_functions.cpp +++ b/modules/gdscript/gdscript_functions.cpp @@ -1663,7 +1663,7 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { MethodInfo mi("weakref", PropertyInfo(Variant::OBJECT, "obj")); mi.return_val.type = Variant::OBJECT; - mi.return_val.name = "WeakRef"; + mi.return_val.class_name = "WeakRef"; return mi; @@ -1672,19 +1672,20 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { MethodInfo mi("funcref", PropertyInfo(Variant::OBJECT, "instance"), PropertyInfo(Variant::STRING, "funcname")); mi.return_val.type = Variant::OBJECT; - mi.return_val.name = "FuncRef"; + mi.return_val.class_name = "FuncRef"; return mi; } break; case TYPE_CONVERT: { - MethodInfo mi("convert", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::INT, "type")); - mi.return_val.type = Variant::OBJECT; + MethodInfo mi("convert", PropertyInfo(Variant::NIL, "what", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT), PropertyInfo(Variant::INT, "type")); + mi.return_val.type = Variant::NIL; + mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; return mi; } break; case TYPE_OF: { - MethodInfo mi("typeof", PropertyInfo(Variant::NIL, "what")); + MethodInfo mi("typeof", PropertyInfo(Variant::NIL, "what", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT)); mi.return_val.type = Variant::INT; return mi; @@ -1760,7 +1761,7 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { } break; case VAR_TO_STR: { - MethodInfo mi("var2str", PropertyInfo(Variant::NIL, "var")); + MethodInfo mi("var2str", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT)); mi.return_val.type = Variant::STRING; return mi; @@ -1773,7 +1774,7 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { return mi; } break; case VAR_TO_BYTES: { - MethodInfo mi("var2bytes", PropertyInfo(Variant::NIL, "var")); + MethodInfo mi("var2bytes", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT)); mi.return_val.type = Variant::POOL_BYTE_ARRAY; return mi; @@ -1796,7 +1797,7 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { MethodInfo mi("load", PropertyInfo(Variant::STRING, "path")); mi.return_val.type = Variant::OBJECT; - mi.return_val.name = "Resource"; + mi.return_val.class_name = "Resource"; return mi; } break; case INST2DICT: { @@ -1826,13 +1827,13 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { } break; case TO_JSON: { - MethodInfo mi("to_json", PropertyInfo(Variant::NIL, "var")); + MethodInfo mi("to_json", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT)); mi.return_val.type = Variant::STRING; return mi; } break; case HASH: { - MethodInfo mi("hash", PropertyInfo(Variant::NIL, "var")); + MethodInfo mi("hash", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT)); mi.return_val.type = Variant::INT; return mi; } break; @@ -1868,7 +1869,7 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { return mi; } break; case LEN: { - MethodInfo mi("len", PropertyInfo(Variant::NIL, "var")); + MethodInfo mi("len", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT)); mi.return_val.type = Variant::INT; return mi; } break; diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index d62112d3f1..ac53f33e9e 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -30,6 +30,10 @@ #include "gdscript_parser.h" +#include "core/core_string_names.h" +#include "core/engine.h" +#include "core/project_settings.h" +#include "core/reference.h" #include "gdscript.h" #include "io/resource_loader.h" #include "os/file_access.h" @@ -138,8 +142,9 @@ bool GDScriptParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bo } Node *arg = _parse_expression(p_parent, p_static); - if (!arg) + if (!arg) { return false; + } p_args.push_back(arg); @@ -263,6 +268,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s bool need_identifier = true; bool done = false; + int line = tokenizer->get_token_line(); while (!done) { @@ -330,16 +336,19 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_CALL; - + op->line = line; op->arguments.push_back(alloc_node<SelfNode>()); + op->arguments[0]->line = line; IdentifierNode *funcname = alloc_node<IdentifierNode>(); funcname->name = "get_node"; - + funcname->line = line; op->arguments.push_back(funcname); ConstantNode *nodepath = alloc_node<ConstantNode>(); nodepath->value = NodePath(StringName(path)); + nodepath->datatype = _type_from_variant(nodepath->value); + nodepath->line = line; op->arguments.push_back(nodepath); expr = op; @@ -353,6 +362,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = tokenizer->get_token_constant(); + constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_PI) { @@ -360,6 +370,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_PI; + constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_TAU) { @@ -367,6 +378,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_TAU; + constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_INF) { @@ -374,6 +386,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_INF; + constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_NAN) { @@ -381,6 +394,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_NAN; + constant->datatype = _type_from_variant(constant->value); tokenizer->advance(); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_PRELOAD) { @@ -419,15 +433,13 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s } if (subexpr->type == Node::TYPE_IDENTIFIER) { IdentifierNode *in = static_cast<IdentifierNode *>(subexpr); - Vector<ClassNode::Constant> ce = current_class->constant_expressions; // Try to find the constant expression by the identifier - for (int i = 0; i < ce.size(); ++i) { - if (ce[i].identifier == in->name) { - if (ce[i].expression->type == Node::TYPE_CONSTANT) { - cn = static_cast<ConstantNode *>(ce[i].expression); - found_constant = true; - } + if (current_class->constant_expressions.has(in->name)) { + Node *cn_exp = current_class->constant_expressions[in->name].expression; + if (cn_exp->type == Node::TYPE_CONSTANT) { + cn = static_cast<ConstantNode *>(cn_exp); + found_constant = true; } } } @@ -480,15 +492,28 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s _set_error("Expected ')' after 'preload' path"); return NULL; } + + Ref<GDScript> gds = res; + if (gds.is_valid() && !gds->is_valid()) { + _set_error("Could not fully preload the script, possible cyclic reference or compilation error."); + return NULL; + } + tokenizer->advance(); ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = res; + constant->datatype = _type_from_variant(constant->value); expr = constant; } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_YIELD) { - //constant defined by tokenizer + if (!current_function) { + _set_error("yield() can only be used inside function blocks."); + return NULL; + } + + current_function->has_yield = true; tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { @@ -618,6 +643,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = Variant::get_numeric_constant_value(bi_type, identifier); + cn->datatype = _type_from_variant(cn->value); expr = cn; } @@ -695,24 +721,56 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s const ClassNode *cln = current_class; bool bfn = false; StringName identifier; + int id_line = tokenizer->get_token_line(); if (_get_completable_identifier(COMPLETION_IDENTIFIER, identifier)) { } - if (p_parsing_constant) { - for (int i = 0; i < cln->constant_expressions.size(); ++i) { - - if (cln->constant_expressions[i].identifier == identifier) { + BlockNode *b = current_block; + while (b) { + if (b->variables.has(identifier)) { + IdentifierNode *id = alloc_node<IdentifierNode>(); + LocalVarNode *lv = b->variables[identifier]; + id->name = identifier; + id->declared_block = b; + id->line = id_line; + expr = id; + bfn = true; - expr = cln->constant_expressions[i].expression; - bfn = true; - break; + switch (tokenizer->get_token()) { + case GDScriptTokenizer::TK_OP_ASSIGN_ADD: + case GDScriptTokenizer::TK_OP_ASSIGN_BIT_AND: + case GDScriptTokenizer::TK_OP_ASSIGN_BIT_OR: + case GDScriptTokenizer::TK_OP_ASSIGN_BIT_XOR: + case GDScriptTokenizer::TK_OP_ASSIGN_DIV: + case GDScriptTokenizer::TK_OP_ASSIGN_MOD: + case GDScriptTokenizer::TK_OP_ASSIGN_MUL: + case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: + case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: + case GDScriptTokenizer::TK_OP_ASSIGN_SUB: { + if (lv->assignments == 0 && !lv->datatype.has_type) { + _set_error("Using assignment with operation on a variable that was never assigned."); + return NULL; + } + } // fallthrough + case GDScriptTokenizer::TK_OP_ASSIGN: { + lv->assignments += 1; + } } + break; } + b = b->parent_block; + } - if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) { + if (!bfn && p_parsing_constant) { + if (cln->constant_expressions.has(identifier)) { + expr = cln->constant_expressions[identifier].expression; + bfn = true; + } else if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) { //check from constants ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = GDScriptLanguage::get_singleton()->get_global_array()[GDScriptLanguage::get_singleton()->get_global_map()[identifier]]; + constant->datatype = _type_from_variant(constant->value); + constant->line = id_line; expr = constant; bfn = true; } @@ -729,6 +787,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s if (!bfn) { IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; + id->line = id_line; expr = id; } @@ -902,6 +961,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s //lua style identifier, easier to write ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = tokenizer->get_token_literal(); + cn->datatype = _type_from_variant(cn->value); key = cn; tokenizer->advance(2); expecting = DICT_EXPECT_VALUE; @@ -941,7 +1001,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s expr = dict; - } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD && (tokenizer->is_token_literal(1) || tokenizer->get_token(1) == GDScriptTokenizer::TK_CURSOR) && tokenizer->get_token(2) == GDScriptTokenizer::TK_PARENTHESIS_OPEN) { + } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD && (tokenizer->is_token_literal(1) || tokenizer->get_token(1) == GDScriptTokenizer::TK_CURSOR)) { // We check with is_token_literal, as this allows us to use match/sync/etc. as a name // parent call @@ -953,17 +1013,23 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s op->arguments.push_back(self); forbidden for now */ StringName identifier; - if (_get_completable_identifier(COMPLETION_PARENT_FUNCTION, identifier)) { - //indexing stuff - } + bool is_completion = _get_completable_identifier(COMPLETION_PARENT_FUNCTION, identifier) && for_completion; IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; op->arguments.push_back(id); - tokenizer->advance(1); - if (!_parse_arguments(op, op->arguments, p_static)) - return NULL; + if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { + if (!is_completion) { + _set_error("Expected '(' for parent function call."); + return NULL; + } + } else { + tokenizer->advance(); + if (!_parse_arguments(op, op->arguments, p_static)) { + return NULL; + } + } expr = op; @@ -1087,6 +1153,26 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s break; } + /*****************/ + /* Parse Casting */ + /*****************/ + + bool has_casting = expr->type == Node::TYPE_CAST; + if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_AS) { + if (has_casting) { + _set_error("Unexpected 'as'."); + return NULL; + } + CastNode *cn = alloc_node<CastNode>(); + if (!_parse_type(cn->cast_type)) { + _set_error("Expected type after 'as'."); + return NULL; + } + has_casting = true; + cn->source_node = expr; + expr = cn; + } + /******************/ /* Parse Operator */ /******************/ @@ -1110,7 +1196,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s //assign, if allowed is only allowed on the first operator #define _VALIDATE_ASSIGN \ - if (!p_allow_assign) { \ + if (!p_allow_assign || has_casting) { \ _set_error("Unexpected assign."); \ return NULL; \ } \ @@ -1338,11 +1424,11 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s if (next_op >= (expression.size() - 2) || expression[next_op + 2].op != OperatorNode::OP_TERNARY_ELSE) { _set_error("Expected else after ternary if."); - ERR_FAIL_V(NULL); + return NULL; } if (next_op >= (expression.size() - 3)) { _set_error("Expected value after ternary else."); - ERR_FAIL_V(NULL); + return NULL; } OperatorNode *op = alloc_node<OperatorNode>(); @@ -1450,13 +1536,13 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to ConstantNode *cn = alloc_node<ConstantNode>(); Array arr; - //print_line("mk array "+itos(!p_to_const)); arr.resize(an->elements.size()); for (int i = 0; i < an->elements.size(); i++) { ConstantNode *acn = static_cast<ConstantNode *>(an->elements[i]); arr[i] = acn->value; } cn->value = arr; + cn->datatype = _type_from_variant(cn->value); return cn; } @@ -1490,6 +1576,7 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to dict[key_c->value] = value_c->value; } cn->value = dict; + cn->datatype = _type_from_variant(cn->value); return cn; } @@ -1591,6 +1678,7 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = v; + cn->datatype = _type_from_variant(v); return cn; } else if (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && last_not_constant == 0) { @@ -1620,24 +1708,9 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = v; + cn->datatype = _type_from_variant(v); return cn; - - } /*else if (op->arguments[0]->type==Node::TYPE_CONSTANT && op->arguments[1]->type==Node::TYPE_IDENTIFIER) { - - ConstantNode *ca = static_cast<ConstantNode*>(op->arguments[0]); - IdentifierNode *ib = static_cast<IdentifierNode*>(op->arguments[1]); - - bool valid; - Variant v = ca->value.get_named(ib->name,&valid); - if (!valid) { - _set_error("invalid index '"+String(ib->name)+"' in constant expression"); - return op; - } - - ConstantNode *cn = alloc_node<ConstantNode>(); - cn->value=v; - return cn; - }*/ + } return op; @@ -1658,13 +1731,14 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = v; + cn->datatype = _type_from_variant(v); return cn; } return op; } - //validate assignment (don't assign to cosntant expression + //validate assignment (don't assign to constant expression switch (op->op) { case OperatorNode::OP_ASSIGN: @@ -1711,6 +1785,7 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to } \ ConstantNode *cn = alloc_node<ConstantNode>(); \ cn->value = res; \ + cn->datatype = _type_from_variant(res); \ return cn; #define _REDUCE_BINARY(m_vop) \ @@ -1724,6 +1799,7 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to } \ ConstantNode *cn = alloc_node<ConstantNode>(); \ cn->value = res; \ + cn->datatype = _type_from_variant(res); \ return cn; switch (op->op) { @@ -1799,6 +1875,13 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to case OperatorNode::OP_BIT_XOR: { _REDUCE_BINARY(Variant::OP_BIT_XOR); } break; + case OperatorNode::OP_TERNARY_IF: { + if (static_cast<ConstantNode *>(op->arguments[0])->value.booleanize()) { + return op->arguments[1]; + } else { + return op->arguments[2]; + } + } break; default: { ERR_FAIL_V(op); } } @@ -1905,6 +1988,15 @@ GDScriptParser::PatternNode *GDScriptParser::_parse_pattern(bool p_static) { tokenizer->advance(); pattern->pt_type = GDScriptParser::PatternNode::PT_BIND; pattern->bind = tokenizer->get_token_identifier(); + // Check if binding is already used + if (current_block->variables.has(pattern->bind)) { + _set_error("Binding name of '" + pattern->bind.operator String() + "' was already used in the pattern."); + return NULL; + } + // Create local variable for proper identifier detection later + LocalVarNode *lv = alloc_node<LocalVarNode>(); + lv->name = pattern->bind; + current_block->variables.insert(lv->name, lv); tokenizer->advance(); } break; // dictionary @@ -2038,18 +2130,34 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran } PatternBranchNode *branch = alloc_node<PatternBranchNode>(); + branch->body = alloc_node<BlockNode>(); + branch->body->parent_block = p_block; + p_block->sub_blocks.push_back(branch->body); + current_block = branch->body; branch->patterns.push_back(_parse_pattern(p_static)); if (!branch->patterns[0]) { return; } + bool has_binding = branch->patterns[0]->pt_type == PatternNode::PT_BIND; + bool catch_all = has_binding || branch->patterns[0]->pt_type == PatternNode::PT_WILDCARD; + while (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); branch->patterns.push_back(_parse_pattern(p_static)); if (!branch->patterns[branch->patterns.size() - 1]) { return; } + + PatternNode::PatternType pt = branch->patterns[branch->patterns.size() - 1]->pt_type; + + if (pt == PatternNode::PT_BIND) { + _set_error("Cannot use bindings with multipattern."); + return; + } + + catch_all = catch_all || pt == PatternNode::PT_WILDCARD; } if (!_enter_indent_block()) { @@ -2057,54 +2165,76 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran return; } - branch->body = alloc_node<BlockNode>(); - branch->body->parent_block = p_block; - p_block->sub_blocks.push_back(branch->body); - current_block = branch->body; - _parse_block(branch->body, p_static); current_block = p_block; + if (catch_all && branch->body->has_return) { + p_block->has_return = true; + } + p_branches.push_back(branch); } } void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings) { + + const DataType &to_match_type = p_node_to_match->get_datatype(); + switch (p_pattern->pt_type) { case PatternNode::PT_CONSTANT: { - // typecheck - BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); - typeof_node->function = GDScriptFunctions::TYPE_OF; + DataType pattern_type = _reduce_node_type(p_pattern->constant); + if (error_set) { + return; + } + + OperatorNode *type_comp = NULL; + + // static type check if possible + if (pattern_type.has_type && to_match_type.has_type) { + if (!_is_type_compatible(to_match_type, pattern_type) && !_is_type_compatible(pattern_type, to_match_type)) { + _set_error("Pattern type (" + pattern_type.to_string() + ") is not compatible with the type of the value to match (" + to_match_type.to_string() + ").", + p_pattern->line); + return; + } + } else { + // runtime typecheck + BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); + typeof_node->function = GDScriptFunctions::TYPE_OF; - OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); - typeof_match_value->op = OperatorNode::OP_CALL; - typeof_match_value->arguments.push_back(typeof_node); - typeof_match_value->arguments.push_back(p_node_to_match); + OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); + typeof_match_value->op = OperatorNode::OP_CALL; + typeof_match_value->arguments.push_back(typeof_node); + typeof_match_value->arguments.push_back(p_node_to_match); - OperatorNode *typeof_pattern_value = alloc_node<OperatorNode>(); - typeof_pattern_value->op = OperatorNode::OP_CALL; - typeof_pattern_value->arguments.push_back(typeof_node); - typeof_pattern_value->arguments.push_back(p_pattern->constant); + OperatorNode *typeof_pattern_value = alloc_node<OperatorNode>(); + typeof_pattern_value->op = OperatorNode::OP_CALL; + typeof_pattern_value->arguments.push_back(typeof_node); + typeof_pattern_value->arguments.push_back(p_pattern->constant); - OperatorNode *type_comp = alloc_node<OperatorNode>(); - type_comp->op = OperatorNode::OP_EQUAL; - type_comp->arguments.push_back(typeof_match_value); - type_comp->arguments.push_back(typeof_pattern_value); + type_comp = alloc_node<OperatorNode>(); + type_comp->op = OperatorNode::OP_EQUAL; + type_comp->arguments.push_back(typeof_match_value); + type_comp->arguments.push_back(typeof_pattern_value); + } - // comare the actual values + // compare the actual values OperatorNode *value_comp = alloc_node<OperatorNode>(); value_comp->op = OperatorNode::OP_EQUAL; value_comp->arguments.push_back(p_pattern->constant); value_comp->arguments.push_back(p_node_to_match); - OperatorNode *comparison = alloc_node<OperatorNode>(); - comparison->op = OperatorNode::OP_AND; - comparison->arguments.push_back(type_comp); - comparison->arguments.push_back(value_comp); + if (type_comp) { + OperatorNode *full_comparison = alloc_node<OperatorNode>(); + full_comparison->op = OperatorNode::OP_AND; + full_comparison->arguments.push_back(type_comp); + full_comparison->arguments.push_back(value_comp); - p_resulting_node = comparison; + p_resulting_node = full_comparison; + } else { + p_resulting_node = value_comp; + } } break; case PatternNode::PT_BIND: { @@ -2129,22 +2259,32 @@ void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_m // typeof(value_to_match) == TYPE_ARRAY && value_to_match.size() == length { - // typecheck - BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); - typeof_node->function = GDScriptFunctions::TYPE_OF; - - OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); - typeof_match_value->op = OperatorNode::OP_CALL; - typeof_match_value->arguments.push_back(typeof_node); - typeof_match_value->arguments.push_back(p_node_to_match); - - IdentifierNode *typeof_array = alloc_node<IdentifierNode>(); - typeof_array->name = "TYPE_ARRAY"; - - OperatorNode *type_comp = alloc_node<OperatorNode>(); - type_comp->op = OperatorNode::OP_EQUAL; - type_comp->arguments.push_back(typeof_match_value); - type_comp->arguments.push_back(typeof_array); + OperatorNode *type_comp = NULL; + // static type check if possible + if (to_match_type.has_type) { + // must be an array + if (to_match_type.kind != DataType::BUILTIN || to_match_type.builtin_type != Variant::ARRAY) { + _set_error("Cannot match an array pattern with a non-array expression.", p_pattern->line); + return; + } + } else { + // runtime typecheck + BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); + typeof_node->function = GDScriptFunctions::TYPE_OF; + + OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); + typeof_match_value->op = OperatorNode::OP_CALL; + typeof_match_value->arguments.push_back(typeof_node); + typeof_match_value->arguments.push_back(p_node_to_match); + + IdentifierNode *typeof_array = alloc_node<IdentifierNode>(); + typeof_array->name = "TYPE_ARRAY"; + + type_comp = alloc_node<OperatorNode>(); + type_comp->op = OperatorNode::OP_EQUAL; + type_comp->arguments.push_back(typeof_match_value); + type_comp->arguments.push_back(typeof_array); + } // size ConstantNode *length = alloc_node<ConstantNode>(); @@ -2163,12 +2303,16 @@ void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_m length_comparison->arguments.push_back(call); length_comparison->arguments.push_back(length); - OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>(); - type_and_length_comparison->op = OperatorNode::OP_AND; - type_and_length_comparison->arguments.push_back(type_comp); - type_and_length_comparison->arguments.push_back(length_comparison); + if (type_comp) { + OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>(); + type_and_length_comparison->op = OperatorNode::OP_AND; + type_and_length_comparison->arguments.push_back(type_comp); + type_and_length_comparison->arguments.push_back(length_comparison); - p_resulting_node = type_and_length_comparison; + p_resulting_node = type_and_length_comparison; + } else { + p_resulting_node = length_comparison; + } } for (int i = 0; i < p_pattern->array.size(); i++) { @@ -2208,22 +2352,32 @@ void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_m // typeof(value_to_match) == TYPE_DICTIONARY && value_to_match.size() == length { - // typecheck - BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); - typeof_node->function = GDScriptFunctions::TYPE_OF; - - OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); - typeof_match_value->op = OperatorNode::OP_CALL; - typeof_match_value->arguments.push_back(typeof_node); - typeof_match_value->arguments.push_back(p_node_to_match); - - IdentifierNode *typeof_dictionary = alloc_node<IdentifierNode>(); - typeof_dictionary->name = "TYPE_DICTIONARY"; - - OperatorNode *type_comp = alloc_node<OperatorNode>(); - type_comp->op = OperatorNode::OP_EQUAL; - type_comp->arguments.push_back(typeof_match_value); - type_comp->arguments.push_back(typeof_dictionary); + OperatorNode *type_comp = NULL; + // static type check if possible + if (to_match_type.has_type) { + // must be an dictionary + if (to_match_type.kind != DataType::BUILTIN || to_match_type.builtin_type != Variant::DICTIONARY) { + _set_error("Cannot match an dictionary pattern with a non-dictionary expression.", p_pattern->line); + return; + } + } else { + // runtime typecheck + BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); + typeof_node->function = GDScriptFunctions::TYPE_OF; + + OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); + typeof_match_value->op = OperatorNode::OP_CALL; + typeof_match_value->arguments.push_back(typeof_node); + typeof_match_value->arguments.push_back(p_node_to_match); + + IdentifierNode *typeof_dictionary = alloc_node<IdentifierNode>(); + typeof_dictionary->name = "TYPE_DICTIONARY"; + + type_comp = alloc_node<OperatorNode>(); + type_comp->op = OperatorNode::OP_EQUAL; + type_comp->arguments.push_back(typeof_match_value); + type_comp->arguments.push_back(typeof_dictionary); + } // size ConstantNode *length = alloc_node<ConstantNode>(); @@ -2242,12 +2396,16 @@ void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_m length_comparison->arguments.push_back(call); length_comparison->arguments.push_back(length); - OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>(); - type_and_length_comparison->op = OperatorNode::OP_AND; - type_and_length_comparison->arguments.push_back(type_comp); - type_and_length_comparison->arguments.push_back(length_comparison); + if (type_comp) { + OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>(); + type_and_length_comparison->op = OperatorNode::OP_AND; + type_and_length_comparison->arguments.push_back(type_comp); + type_and_length_comparison->arguments.push_back(length_comparison); - p_resulting_node = type_and_length_comparison; + p_resulting_node = type_and_length_comparison; + } else { + p_resulting_node = length_comparison; + } } for (Map<ConstantNode *, PatternNode *>::Element *e = p_pattern->dictionary.front(); e; e = e->next()) { @@ -2308,9 +2466,20 @@ void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_m } } -void GDScriptParser::_transform_match_statment(BlockNode *p_block, MatchNode *p_match_statement) { +void GDScriptParser::_transform_match_statment(MatchNode *p_match_statement) { IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = "#match_value"; + id->line = p_match_statement->line; + id->datatype = _reduce_node_type(p_match_statement->val_to_match); + if (id->datatype.has_type) { + _mark_line_as_safe(id->line); + } else { + _mark_line_as_unsafe(id->line); + } + + if (error_set) { + return; + } for (int i = 0; i < p_match_statement->branches.size(); i++) { @@ -2323,11 +2492,16 @@ void GDScriptParser::_transform_match_statment(BlockNode *p_block, MatchNode *p_ for (int j = 0; j < branch->patterns.size(); j++) { PatternNode *pattern = branch->patterns[j]; + _mark_line_as_safe(pattern->line); Map<StringName, Node *> bindings; - Node *resulting_node; + Node *resulting_node = NULL; _generate_pattern(pattern, id, resulting_node, bindings); + if (!resulting_node) { + return; + } + if (!binding.empty() && !bindings.empty()) { _set_error("Multipatterns can't contain bindings"); return; @@ -2335,6 +2509,14 @@ void GDScriptParser::_transform_match_statment(BlockNode *p_block, MatchNode *p_ binding = bindings; } + // Result is always a boolean + DataType resulting_node_type; + resulting_node_type.has_type = true; + resulting_node_type.is_constant = true; + resulting_node_type.kind = DataType::BUILTIN; + resulting_node_type.builtin_type = Variant::BOOL; + resulting_node->set_datatype(resulting_node_type); + if (compiled_branch.compiled_pattern) { OperatorNode *or_node = alloc_node<OperatorNode>(); or_node->op = OperatorNode::OP_OR; @@ -2350,12 +2532,19 @@ void GDScriptParser::_transform_match_statment(BlockNode *p_block, MatchNode *p_ // prepare the body ...hehe for (Map<StringName, Node *>::Element *e = binding.front(); e; e = e->next()) { - LocalVarNode *local_var = alloc_node<LocalVarNode>(); - local_var->name = e->key(); + if (!branch->body->variables.has(e->key())) { + _set_error("Parser bug: missing pattern bind variable.", branch->line); + ERR_FAIL(); + } + + LocalVarNode *local_var = branch->body->variables[e->key()]; local_var->assign = e->value(); + local_var->set_datatype(local_var->assign->get_datatype()); IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = local_var->name; + id->declared_block = branch->body; + id->set_datatype(local_var->assign->get_datatype()); OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_ASSIGN; @@ -2413,7 +2602,21 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { } switch (token) { - + case GDScriptTokenizer::TK_EOF: + case GDScriptTokenizer::TK_ERROR: + case GDScriptTokenizer::TK_NEWLINE: + case GDScriptTokenizer::TK_CF_PASS: { + // will check later + } break; + default: { + // TODO: Make this a warning + /*if (p_block->has_return) { + _set_error("Unreacheable code."); + return; + }*/ + } break; + } + switch (token) { case GDScriptTokenizer::TK_EOF: p_block->end_line = tokenizer->get_token_line(); case GDScriptTokenizer::TK_ERROR: { @@ -2443,6 +2646,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { _set_error("Expected ';' or <NewLine>."); return; } + _mark_line_as_safe(tokenizer->get_token_line()); tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON) { // Ignore semicolon after 'pass' @@ -2453,6 +2657,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { //variale declaration and (eventual) initialization tokenizer->advance(); + int var_line = tokenizer->get_token_line(); if (!tokenizer->is_token_literal(0, true)) { _set_error("Expected identifier for local variable name."); @@ -2470,24 +2675,34 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { } BlockNode *check_block = p_block; while (check_block) { - for (int i = 0; i < check_block->variables.size(); i++) { - if (n == check_block->variables[i]) { - _set_error("Variable '" + String(n) + "' already defined in the scope (at line: " + itos(check_block->variable_lines[i]) + ")."); - return; - } + if (check_block->variables.has(n)) { + _set_error("Variable '" + String(n) + "' already defined in the scope (at line: " + itos(check_block->variables[n]->line) + ")."); + return; } check_block = check_block->parent_block; } - int var_line = tokenizer->get_token_line(); - //must know when the local variable is declared LocalVarNode *lv = alloc_node<LocalVarNode>(); lv->name = n; + lv->line = var_line; p_block->statements.push_back(lv); Node *assigned = NULL; + if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { + if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { + lv->datatype = DataType(); +#ifdef DEBUG_ENABLED + lv->datatype.infer_type = true; +#endif + tokenizer->advance(); + } else if (!_parse_type(lv->datatype)) { + _set_error("Expected type for variable."); + return; + } + } + if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) { tokenizer->advance(); @@ -2499,26 +2714,36 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { return; } - lv->assign = subexpr; + lv->assignments++; assigned = subexpr; } else { ConstantNode *c = alloc_node<ConstantNode>(); - c->value = Variant(); + if (lv->datatype.has_type && lv->datatype.kind == DataType::BUILTIN) { + Variant::CallError err; + c->value = Variant::construct(lv->datatype.builtin_type, NULL, 0, err); + } else { + c->value = Variant(); + } + c->line = var_line; assigned = c; } //must be added later, to avoid self-referencing. - p_block->variables.push_back(n); //line? - p_block->variable_lines.push_back(var_line); + p_block->variables.insert(n, lv); IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = n; + id->declared_block = p_block; + id->line = var_line; OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(assigned); + op->line = var_line; p_block->statements.push_back(op); + lv->assign_op = op; + lv->assign = assigned; if (!_end_statement()) { _set_error("Expected end of statement (var)"); @@ -2563,6 +2788,9 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { return; p_block->statements.push_back(cf_if); + bool all_have_return = cf_if->body->has_return; + bool have_else = false; + while (true) { while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE && _parse_newline()) @@ -2619,6 +2847,8 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { if (error_set) return; + all_have_return = all_have_return && cf_else->body->has_return; + } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CF_ELSE) { if (tab_level.back()->get() > indent_level) { @@ -2642,12 +2872,19 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { if (error_set) return; + all_have_return = all_have_return && cf_if->body_else->has_return; + have_else = true; + break; //after else, exit } else break; } + cf_if->body->has_return = all_have_return; + // If there's no else block, path out of the if might not have a return + p_block->has_return = all_have_return && have_else; + } break; case GDScriptTokenizer::TK_CF_WHILE: { @@ -2680,6 +2917,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { current_block = p_block; if (error_set) return; + p_block->has_return = cf_while->body->has_return; p_block->statements.push_back(cf_while); } break; case GDScriptTokenizer::TK_CF_FOR: { @@ -2711,6 +2949,9 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { return; } + DataType iter_type; + iter_type.is_constant = true; + if (container->type == Node::TYPE_OPERATOR) { OperatorNode *op = static_cast<OperatorNode *>(container); @@ -2745,6 +2986,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { case 2: cn->value = Vector2(constants[0], constants[1]); break; case 3: cn->value = Vector3(constants[0], constants[1], constants[2]); break; } + cn->datatype = _type_from_variant(cn->value); container = cn; } else { OperatorNode *on = alloc_node<OperatorNode>(); @@ -2766,6 +3008,10 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { container = on; } } + + iter_type.has_type = true; + iter_type.kind = DataType::BUILTIN; + iter_type.builtin_type = Variant::INT; } } @@ -2789,15 +3035,20 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { // this is for checking variable for redefining // inside this _parse_block - cf_for->body->variables.push_back(id->name); - cf_for->body->variable_lines.push_back(id->line); + LocalVarNode *lv = alloc_node<LocalVarNode>(); + lv->name = id->name; + lv->line = id->line; + lv->assignments++; + id->declared_block = cf_for->body; + lv->set_datatype(iter_type); + id->set_datatype(iter_type); + cf_for->body->variables.insert(id->name, lv); _parse_block(cf_for->body, p_static); - cf_for->body->variables.remove(0); - cf_for->body->variable_lines.remove(0); current_block = p_block; if (error_set) return; + p_block->has_return = cf_for->body->has_return; p_block->statements.push_back(cf_for); } break; case GDScriptTokenizer::TK_CF_CONTINUE: { @@ -2827,6 +3078,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { tokenizer->advance(); ControlFlowNode *cf_return = alloc_node<ControlFlowNode>(); cf_return->cf_type = ControlFlowNode::CF_RETURN; + cf_return->line = tokenizer->get_token_line(-1); if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON || tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE || tokenizer->get_token() == GDScriptTokenizer::TK_EOF) { //expect end of statement @@ -2850,6 +3102,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { return; } } + p_block->has_return = true; } break; case GDScriptTokenizer::TK_CF_MATCH: { @@ -2882,12 +3135,14 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { _parse_pattern_block(compiled_branches, match_node->branches, p_static); - _transform_match_statment(compiled_branches, match_node); + if (error_set) return; ControlFlowNode *match_cf_node = alloc_node<ControlFlowNode>(); match_cf_node->cf_type = ControlFlowNode::CF_MATCH; match_cf_node->match = match_node; + match_cf_node->body = compiled_branches; + p_block->has_return = p_block->has_return || compiled_branches->has_return; p_block->statements.push_back(match_cf_node); _end_statement(); @@ -2938,16 +3193,6 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { } } break; - /* - case GDScriptTokenizer::TK_CF_LOCAL: { - - if (tokenizer->get_token(1)!=GDScriptTokenizer::TK_SEMICOLON && tokenizer->get_token(1)!=GDScriptTokenizer::TK_NEWLINE ) { - - _set_error("Expected ';' or <NewLine>."); - } - tokenizer->advance(); - } break; - */ } } } @@ -3103,6 +3348,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } break; case GDScriptTokenizer::TK_PR_EXTENDS: { + _mark_line_as_safe(tokenizer->get_token_line()); _parse_extends(p_class); if (error_set) return; @@ -3131,6 +3377,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { return; } + if (ClassDB::class_exists(p_class->name)) { + _set_error("Class '" + p_class->name + "' shadows a native class."); + return; + } + tokenizer->advance(2); } break; @@ -3150,7 +3401,6 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { //class inside class :D StringName name; - StringName extends; if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) { @@ -3160,10 +3410,30 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { name = tokenizer->get_token_identifier(1); tokenizer->advance(2); + // Check if name is shadowing something else + if (ClassDB::class_exists(name) || ClassDB::class_exists("_" + name.operator String())) { + _set_error("Class '" + String(name) + "' shadows a native class."); + return; + } if (ScriptServer::is_global_class(name)) { _set_error("Can't override name of unique global class '" + name + "' already exists at path: " + ScriptServer::get_global_class_path(p_class->name)); return; } + ClassNode *outer_class = p_class; + while (outer_class) { + for (int i = 0; i < outer_class->subclasses.size(); i++) { + if (outer_class->subclasses[i]->name == name) { + _set_error("Another class named '" + String(name) + "' already exists in this scope (at line " + itos(outer_class->subclasses[i]->line) + ")."); + return; + } + } + if (outer_class->constant_expressions.has(name)) { + _set_error("A constant named '" + String(name) + "' already exists in the outer class scope (at line" + itos(outer_class->constant_expressions[name].expression->line) + ")."); + return; + } + + outer_class = outer_class->owner; + } ClassNode *newclass = alloc_node<ClassNode>(); newclass->initializer = alloc_node<BlockNode>(); @@ -3249,6 +3519,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); Vector<StringName> arguments; + Vector<DataType> argument_types; Vector<Node *> default_values; int fnline = tokenizer->get_token_line(); @@ -3279,6 +3550,15 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); + DataType argtype; + if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { + if (!_parse_type(argtype)) { + _set_error("Expected type for argument."); + return; + } + } + argument_types.push_back(argtype); + if (defaulting && tokenizer->get_token() != GDScriptTokenizer::TK_OP_ASSIGN) { _set_error("Default parameter expected."); @@ -3296,9 +3576,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { OperatorNode *on = alloc_node<OperatorNode>(); on->op = OperatorNode::OP_ASSIGN; + on->line = fnline; IdentifierNode *in = alloc_node<IdentifierNode>(); in->name = argname; + in->line = fnline; on->arguments.push_back(in); on->arguments.push_back(defval); @@ -3335,6 +3617,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (name == "_init") { + if (_static) { + _set_error("Constructor cannot be static."); + return; + } + if (p_class->extends_used) { OperatorNode *cparent = alloc_node<OperatorNode>(); @@ -3349,6 +3636,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { _set_error("expected '(' for parent constructor arguments."); + return; } tokenizer->advance(); @@ -3386,6 +3674,15 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } } + DataType return_type; + if (tokenizer->get_token() == GDScriptTokenizer::TK_FORWARD_ARROW) { + + if (!_parse_type(return_type, true)) { + _set_error("Expected return type for function."); + return; + } + } + if (!_enter_indent_block(block)) { _set_error("Indented block expected."); @@ -3394,7 +3691,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { FunctionNode *function = alloc_node<FunctionNode>(); function->name = name; + function->return_type = return_type; function->arguments = arguments; + function->argument_types = argument_types; function->default_values = default_values; function->_static = _static; function->line = fnline; @@ -4109,10 +4408,37 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { member.line = tokenizer->get_token_line(); member.rpc_mode = rpc_mode; + if (current_class->constant_expressions.has(member.identifier)) { + _set_error("A constant named '" + String(member.identifier) + "' alread exists in this class (at line: " + + itos(current_class->constant_expressions[member.identifier].expression->line) + ")."); + return; + } + + for (int i = 0; i < current_class->variables.size(); i++) { + if (current_class->variables[i].identifier == member.identifier) { + _set_error("Variable '" + String(member.identifier) + "' alread exists in this class (at line: " + + itos(current_class->variables[i].line) + ")."); + return; + } + } + tokenizer->advance(); rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; + if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { + if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { + member.data_type = DataType(); +#ifdef DEBUG_ENABLED + member.data_type.infer_type = true; +#endif + tokenizer->advance(); + } else if (!_parse_type(member.data_type)) { + _set_error("Expected type for class variable."); + return; + } + } + if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) { #ifdef DEBUG_ENABLED @@ -4144,42 +4470,31 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { member.expression = subexpr; - if (autoexport) { - if (1) /*(subexpr->type==Node::TYPE_ARRAY) { - - member._export.type=Variant::ARRAY; - - } else if (subexpr->type==Node::TYPE_DICTIONARY) { - - member._export.type=Variant::DICTIONARY; - - } else*/ - { + if (autoexport && !member.data_type.has_type) { - if (subexpr->type != Node::TYPE_CONSTANT) { + if (subexpr->type != Node::TYPE_CONSTANT) { - _set_error("Type-less export needs a constant expression assigned to infer type."); - return; - } + _set_error("Type-less export needs a constant expression assigned to infer type."); + return; + } - ConstantNode *cn = static_cast<ConstantNode *>(subexpr); - if (cn->value.get_type() == Variant::NIL) { + ConstantNode *cn = static_cast<ConstantNode *>(subexpr); + if (cn->value.get_type() == Variant::NIL) { - _set_error("Can't accept a null constant expression for inferring export type."); + _set_error("Can't accept a null constant expression for inferring export type."); + return; + } + member._export.type = cn->value.get_type(); + member._export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; + if (cn->value.get_type() == Variant::OBJECT) { + Object *obj = cn->value; + Resource *res = Object::cast_to<Resource>(obj); + if (res == NULL) { + _set_error("Exported constant not a type or resource."); return; } - member._export.type = cn->value.get_type(); - member._export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; - if (cn->value.get_type() == Variant::OBJECT) { - Object *obj = cn->value; - Resource *res = Object::cast_to<Resource>(obj); - if (res == NULL) { - _set_error("Exported constant not a type or resource."); - return; - } - member._export.hint = PROPERTY_HINT_RESOURCE_TYPE; - member._export.hint_string = res->get_class(); - } + member._export.hint = PROPERTY_HINT_RESOURCE_TYPE; + member._export.hint_string = res->get_class(); } } #ifdef TOOLS_ENABLED @@ -4213,15 +4528,36 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { else p_class->initializer->statements.push_back(op); - } else { + member.initial_assignment = op; - if (autoexport) { + } else { + if (autoexport && !member.data_type.has_type) { _set_error("Type-less export needs a constant expression assigned to infer type."); return; } } + if (autoexport && member.data_type.has_type) { + if (member.data_type.kind == DataType::BUILTIN) { + member._export.type = member.data_type.builtin_type; + } else if (member.data_type.kind == DataType::NATIVE) { + if (ClassDB::is_parent_class(member.data_type.native_type, "Resource")) { + member._export.type = Variant::OBJECT; + member._export.hint = PROPERTY_HINT_RESOURCE_TYPE; + member._export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; + member._export.class_name = member.data_type.native_type; + } else { + _set_error("Invalid export type. Only built-in and native resource types can be exported.", member.line); + return; + } + + } else { + _set_error("Invalid export type. Only built-in and native resource types can be exported.", member.line); + return; + } + } + if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_SETGET) { tokenizer->advance(); @@ -4258,7 +4594,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } } break; case GDScriptTokenizer::TK_PR_CONST: { - //variale declaration and (eventual) initialization + // constant declaration and initialization ClassNode::Constant constant; @@ -4269,9 +4605,38 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { return; } - constant.identifier = tokenizer->get_token_literal(); + StringName const_id = tokenizer->get_token_literal(); + int line = tokenizer->get_token_line(); + + if (current_class->constant_expressions.has(const_id)) { + _set_error("Constant '" + String(const_id) + "' alread exists in this class (at line: " + + itos(current_class->constant_expressions[const_id].expression->line) + ")."); + return; + } + + for (int i = 0; i < current_class->variables.size(); i++) { + if (current_class->variables[i].identifier == const_id) { + _set_error("A variable named '" + String(const_id) + "' alread exists in this class (at line: " + + itos(current_class->variables[i].line) + ")."); + return; + } + } + tokenizer->advance(); + if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { + if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { + constant.type = DataType(); +#ifdef DEBUG_ENABLED + constant.type.infer_type = true; +#endif + tokenizer->advance(); + } else if (!_parse_type(constant.type)) { + _set_error("Expected type for class constant."); + return; + } + } + if (tokenizer->get_token() != GDScriptTokenizer::TK_OP_ASSIGN) { _set_error("Constant expects assignment."); return; @@ -4288,14 +4653,16 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } if (subexpr->type != Node::TYPE_CONSTANT) { - _set_error("Expected constant expression"); + _set_error("Expected constant expression", line); + return; } + subexpr->line = line; constant.expression = subexpr; - p_class->constant_expressions.push_back(constant); + p_class->constant_expressions.insert(const_id, constant); if (!_end_statement()) { - _set_error("Expected end of statement (constant)"); + _set_error("Expected end of statement (constant)", line); return; } @@ -4338,7 +4705,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } else { // tokenizer->is_token_literal(0, true) ClassNode::Constant constant; - constant.identifier = tokenizer->get_token_literal(); + StringName const_id = tokenizer->get_token_literal(); tokenizer->advance(); @@ -4355,22 +4722,25 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (subexpr->type != Node::TYPE_CONSTANT) { _set_error("Expected constant expression"); + return; } - const ConstantNode *subexpr_const = static_cast<const ConstantNode *>(subexpr); + ConstantNode *subexpr_const = static_cast<ConstantNode *>(subexpr); if (subexpr_const->value.get_type() != Variant::INT) { _set_error("Expected an int value for enum"); + return; } last_assign = subexpr_const->value; - constant.expression = subexpr; + constant.expression = subexpr_const; } else { last_assign = last_assign + 1; ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = last_assign; + cn->datatype = _type_from_variant(cn->value); constant.expression = cn; } @@ -4380,20 +4750,25 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (enum_name != "") { const ConstantNode *cn = static_cast<const ConstantNode *>(constant.expression); - enum_dict[constant.identifier] = cn->value; + enum_dict[const_id] = cn->value; } - p_class->constant_expressions.push_back(constant); + constant.type.has_type = true; + constant.type.kind = DataType::BUILTIN; + constant.type.builtin_type = Variant::INT; + p_class->constant_expressions.insert(const_id, constant); } } if (enum_name != "") { ClassNode::Constant enum_constant; - enum_constant.identifier = enum_name; ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = enum_dict; + cn->datatype = _type_from_variant(cn->value); + enum_constant.expression = cn; - p_class->constant_expressions.push_back(enum_constant); + enum_constant.type = cn->datatype; + p_class->constant_expressions.insert(enum_name, enum_constant); } if (!_end_statement()) { @@ -4423,6 +4798,2711 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } } +void GDScriptParser::_determine_inheritance(ClassNode *p_class) { + + if (p_class->extends_used) { + //do inheritance + String path = p_class->extends_file; + + Ref<GDScript> script; + StringName native; + ClassNode *base_class = NULL; + + if (path != "") { + //path (and optionally subclasses) + + if (path.is_rel_path()) { + + String base = base_path; + + if (base == "" || base.is_rel_path()) { + _set_error("Could not resolve relative path for parent class: " + path, p_class->line); + return; + } + path = base.plus_file(path).simplify_path(); + } + script = ResourceLoader::load(path); + if (script.is_null()) { + _set_error("Could not load base class: " + path, p_class->line); + return; + } + if (!script->is_valid()) { + + _set_error("Script not fully loaded (cyclic preload?): " + path, p_class->line); + return; + } + + if (p_class->extends_class.size()) { + + for (int i = 0; i < p_class->extends_class.size(); i++) { + + String sub = p_class->extends_class[i]; + if (script->get_subclasses().has(sub)) { + + Ref<Script> subclass = script->get_subclasses()[sub]; //avoid reference from disappearing + script = subclass; + } else { + + _set_error("Could not find subclass: " + sub, p_class->line); + return; + } + } + } + + } else { + + if (p_class->extends_class.size() == 0) { + _set_error("Parser bug: undecidable inheritance.", p_class->line); + ERR_FAIL(); + } + //look around for the subclasses + + int extend_iter = 1; + String base = p_class->extends_class[0]; + ClassNode *p = p_class->owner; + Ref<GDScript> base_script; + + if (ScriptServer::is_global_class(base)) { + base_script = ResourceLoader::load(ScriptServer::get_global_class_path(base)); + if (!base_script.is_valid()) { + _set_error("Class '" + base + "' could not be fully loaded (script error or cyclic inheritance).", p_class->line); + return; + } + p = NULL; + } + + while (p) { + + bool found = false; + + for (int i = 0; i < p->subclasses.size(); i++) { + if (p->subclasses[i]->name == base) { + ClassNode *test = p->subclasses[i]; + while (test) { + if (test == p_class) { + _set_error("Cyclic inheritance.", test->line); + return; + } + if (test->base_type.kind == DataType::CLASS) { + test = test->base_type.class_type; + } else { + break; + } + } + found = true; + if (extend_iter < p_class->extends_class.size()) { + // Keep looking at current classes if possible + base = p_class->extends_class[extend_iter++]; + p = p->subclasses[i]; + } else { + base_class = p->subclasses[i]; + } + break; + } + } + + if (base_class) break; + if (found) continue; + + if (p->constant_expressions.has(base)) { + if (!p->constant_expressions[base].expression->type == Node::TYPE_CONSTANT) { + _set_error("Could not resolve constant '" + base + "'.", p_class->line); + return; + } + const ConstantNode *cn = static_cast<const ConstantNode *>(p->constant_expressions[base].expression); + base_script = cn->value; + if (base_script.is_null()) { + _set_error("Constant is not a class: " + base, p_class->line); + return; + } + break; + } + + p = p->owner; + } + + if (base_script.is_valid()) { + + String ident = base; + + for (int i = extend_iter; i < p_class->extends_class.size(); i++) { + + String subclass = p_class->extends_class[i]; + + ident += ("." + subclass); + + if (base_script->get_subclasses().has(subclass)) { + + base_script = base_script->get_subclasses()[subclass]; + } else if (base_script->get_constants().has(subclass)) { + + Ref<GDScript> new_base_class = base_script->get_constants()[subclass]; + if (new_base_class.is_null()) { + _set_error("Constant is not a class: " + ident, p_class->line); + return; + } + base_script = new_base_class; + } else { + + _set_error("Could not find subclass: " + ident, p_class->line); + return; + } + } + + script = base_script; + + } else if (!base_class) { + + if (p_class->extends_class.size() > 1) { + + _set_error("Invalid inheritance (unknown class + subclasses)", p_class->line); + return; + } + //if not found, try engine classes + if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) { + + _set_error("Unknown class: '" + base + "'", p_class->line); + return; + } + + native = base; + } + } + + if (base_class) { + p_class->base_type.has_type = true; + p_class->base_type.kind = DataType::CLASS; + p_class->base_type.class_type = base_class; + } else if (script.is_valid()) { + p_class->base_type.has_type = true; + p_class->base_type.kind = DataType::GDSCRIPT; + p_class->base_type.script_type = script; + p_class->base_type.native_type = script->get_instance_base_type(); + } else if (native != StringName()) { + p_class->base_type.has_type = true; + p_class->base_type.kind = DataType::NATIVE; + p_class->base_type.native_type = native; + } else { + _set_error("Could not determine inheritance", p_class->line); + return; + } + + } else { + // without extends, implicitly extend Reference + p_class->base_type.has_type = true; + p_class->base_type.kind = DataType::NATIVE; + p_class->base_type.native_type = "Reference"; + } + + // Recursively determine subclasses + for (int i = 0; i < p_class->subclasses.size(); i++) { + _determine_inheritance(p_class->subclasses[i]); + } +} + +String GDScriptParser::DataType::to_string() const { + if (!has_type) return "var"; + switch (kind) { + case BUILTIN: { + if (builtin_type == Variant::NIL) return "null"; + return Variant::get_type_name(builtin_type); + } break; + case NATIVE: { + if (is_meta_type) { + return "GDScriptNativeClass"; + } + return native_type.operator String(); + } break; + + case GDSCRIPT: { + Ref<GDScript> gds = script_type; + const String &gds_class = gds->get_script_class_name(); + if (!gds_class.empty()) { + return gds_class; + } + } // fallthrough + case SCRIPT: { + if (is_meta_type) { + return script_type->get_class_name().operator String(); + } + String name = script_type->get_name(); + if (name != String()) { + return name; + } + name = script_type->get_path().get_file(); + if (name != String()) { + return name; + } + return native_type.operator String(); + } break; + case CLASS: { + ERR_FAIL_COND_V(!class_type, String()); + if (is_meta_type) { + return "GDScript"; + } + if (class_type->name == StringName()) { + return "self"; + } + return class_type->name.operator String(); + } break; + } + + return "Unresolved"; +} + +bool GDScriptParser::_parse_type(DataType &r_type, bool p_can_be_void) { + tokenizer->advance(); + r_type.has_type = true; + + bool finished = false; + bool can_index = false; + String full_name; + + if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { + completion_cursor = StringName(); + completion_type = COMPLETION_TYPE_HINT; + completion_class = current_class; + completion_function = current_function; + completion_line = tokenizer->get_token_line(); + completion_argument = 0; + completion_block = current_block; + completion_found = true; + completion_ident_is_call = p_can_be_void; + tokenizer->advance(); + } + + switch (tokenizer->get_token()) { + case GDScriptTokenizer::TK_PR_VOID: { + if (!p_can_be_void) { + return false; + } + r_type.kind = DataType::BUILTIN; + r_type.builtin_type = Variant::NIL; + } break; + case GDScriptTokenizer::TK_BUILT_IN_TYPE: { + r_type.builtin_type = tokenizer->get_token_type(); + if (tokenizer->get_token_type() == Variant::OBJECT) { + r_type.kind = DataType::NATIVE; + r_type.native_type = "Object"; + } else { + r_type.kind = DataType::BUILTIN; + } + } break; + case GDScriptTokenizer::TK_IDENTIFIER: { + r_type.native_type = tokenizer->get_token_identifier(); + if (ClassDB::class_exists(r_type.native_type) || ClassDB::class_exists("_" + r_type.native_type.operator String())) { + r_type.kind = DataType::NATIVE; + } else { + r_type.kind = DataType::UNRESOLVED; + can_index = true; + full_name = r_type.native_type; + } + } break; + default: { + return false; + } + } + + tokenizer->advance(); + + if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) { + completion_cursor = r_type.native_type; + completion_type = COMPLETION_TYPE_HINT; + completion_class = current_class; + completion_function = current_function; + completion_line = tokenizer->get_token_line(); + completion_argument = 0; + completion_block = current_block; + completion_found = true; + completion_ident_is_call = p_can_be_void; + tokenizer->advance(); + } + + if (can_index) { + while (!finished) { + switch (tokenizer->get_token()) { + case GDScriptTokenizer::TK_PERIOD: { + if (!can_index) { + _set_error("Unexpected '.'."); + return false; + } + can_index = false; + tokenizer->advance(); + } break; + case GDScriptTokenizer::TK_IDENTIFIER: { + if (can_index) { + _set_error("Unexpected identifier."); + return false; + } + + StringName id; + bool has_completion = _get_completable_identifier(COMPLETION_TYPE_HINT_INDEX, id); + if (id == StringName()) { + id = "@temp"; + } + + full_name += "." + id.operator String(); + can_index = true; + if (has_completion) { + completion_cursor = full_name; + } + } break; + default: { + finished = true; + } break; + } + } + + if (tokenizer->get_token(-1) == GDScriptTokenizer::TK_PERIOD) { + _set_error("Expected subclass identifier."); + return false; + } + + r_type.native_type = full_name; + } + + return true; +} + +GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source, int p_line) { + if (!p_source.has_type) return p_source; + if (p_source.kind != DataType::UNRESOLVED) return p_source; + + Vector<String> full_name = p_source.native_type.operator String().split(".", false); + int name_part = 0; + + DataType result; + result.has_type = true; + + while (name_part < full_name.size()) { + + bool found = false; + StringName id = full_name[name_part]; + DataType base_type = result; + + ClassNode *p = NULL; + if (name_part == 0) { + if (ScriptServer::is_global_class(id)) { + String script_path = ScriptServer::get_global_class_path(id); + if (script_path == self_path) { + result.kind = DataType::CLASS; + result.class_type = current_class; + } else { + Ref<Script> script = ResourceLoader::load(script_path); + Ref<GDScript> gds = script; + if (gds.is_valid()) { + if (!gds->is_valid()) { + _set_error("Class '" + id + "' could not be fully loaded (script error or cyclic inheritance).", p_line); + return DataType(); + } + result.kind = DataType::GDSCRIPT; + result.script_type = gds; + } else if (script.is_valid()) { + result.kind = DataType::SCRIPT; + result.script_type = script; + } else { + _set_error("Class '" + id + "' was found in global scope but its script could not be loaded.", p_line); + return DataType(); + } + } + name_part++; + continue; + } else { + p = current_class; + } + } else if (base_type.kind == DataType::CLASS) { + p = base_type.class_type; + } + while (p) { + if (p->constant_expressions.has(id)) { + if (p->constant_expressions[id].expression->type != Node::TYPE_CONSTANT) { + _set_error("Parser bug: unresolved constant.", p_line); + ERR_FAIL_V(result); + } + const ConstantNode *cn = static_cast<const ConstantNode *>(p->constant_expressions[id].expression); + Ref<GDScript> gds = cn->value; + if (gds.is_valid()) { + result.kind = DataType::GDSCRIPT; + result.script_type = gds; + found = true; + } else { + Ref<Script> scr = cn->value; + if (scr.is_valid()) { + result.kind = DataType::SCRIPT; + result.script_type = scr; + found = true; + } + } + break; + } + + // Inner classes + ClassNode *outer_class = p; + while (outer_class) { + for (int i = 0; i < outer_class->subclasses.size(); i++) { + if (outer_class->subclasses[i] == p) { + continue; + } + if (outer_class->subclasses[i]->name == id) { + found = true; + result.kind = DataType::CLASS; + result.class_type = outer_class->subclasses[i]; + break; + } + } + if (found) { + break; + } + outer_class = outer_class->owner; + } + + if (!found && p->base_type.kind == DataType::CLASS) { + p = p->base_type.class_type; + } else { + base_type = p->base_type; + break; + } + } + + // Still look for class constants in parent script + if (!found && (base_type.kind == DataType::GDSCRIPT || base_type.kind == DataType::SCRIPT)) { + Ref<Script> scr = base_type.script_type; + ERR_FAIL_COND_V(scr.is_null(), result); + Map<StringName, Variant> constants; + scr->get_constants(&constants); + + if (constants.has(id)) { + Ref<GDScript> gds = constants[id]; + + if (gds.is_valid()) { + result.kind = DataType::GDSCRIPT; + result.script_type = gds; + found = true; + } else { + Ref<Script> scr = constants[id]; + if (scr.is_valid()) { + result.kind = DataType::SCRIPT; + result.script_type = scr; + found = true; + } + } + } + } + + if (!found && !for_completion) { + String base; + if (name_part == 0) { + base = "self"; + } else { + base = result.to_string(); + } + _set_error("Identifier '" + String(id) + "' is not a valid type (not a script or class), or could not be found on base '" + + base + "'.", + p_line); + return DataType(); + } + + name_part++; + } + + return result; +} + +GDScriptParser::DataType GDScriptParser::_type_from_variant(const Variant &p_value) const { + DataType result; + result.has_type = true; + result.is_constant = true; + result.kind = DataType::BUILTIN; + result.builtin_type = p_value.get_type(); + + if (result.builtin_type == Variant::OBJECT) { + Object *obj = p_value.operator Object *(); + if (!obj) { + return DataType(); + } + result.native_type = obj->get_class_name(); + Ref<Script> scr = p_value; + if (scr.is_valid()) { + result.is_meta_type = true; + } else { + result.is_meta_type = false; + scr = obj->get_script(); + } + if (scr.is_valid()) { + result.script_type = scr; + Ref<GDScript> gds = scr; + if (gds.is_valid()) { + result.kind = DataType::GDSCRIPT; + } else { + result.kind = DataType::SCRIPT; + } + result.native_type = scr->get_instance_base_type(); + } else { + result.kind = DataType::NATIVE; + } + } + + return result; +} + +GDScriptParser::DataType GDScriptParser::_type_from_property(const PropertyInfo &p_property, bool p_nil_is_variant) const { + DataType ret; + if (p_property.type == Variant::NIL && (p_nil_is_variant || (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) { + // Variant + return ret; + } + ret.has_type = true; + ret.builtin_type = p_property.type; + if (p_property.type == Variant::OBJECT) { + ret.kind = DataType::NATIVE; + ret.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name; + } else { + ret.kind = DataType::BUILTIN; + } + return ret; +} + +GDScriptParser::DataType GDScriptParser::_type_from_gdtype(const GDScriptDataType &p_gdtype) const { + DataType result; + if (!p_gdtype.has_type) { + return result; + } + + result.has_type = true; + result.builtin_type = p_gdtype.builtin_type; + result.native_type = p_gdtype.native_type; + result.script_type = p_gdtype.script_type; + + switch (p_gdtype.kind) { + case GDScriptDataType::BUILTIN: { + result.kind = DataType::BUILTIN; + } break; + case GDScriptDataType::NATIVE: { + result.kind = DataType::NATIVE; + } break; + case GDScriptDataType::GDSCRIPT: { + result.kind = DataType::GDSCRIPT; + } break; + case GDScriptDataType::SCRIPT: { + result.kind = DataType::SCRIPT; + } break; + } + return result; +} + +GDScriptParser::DataType GDScriptParser::_get_operation_type(const Variant::Operator p_op, const DataType &p_a, const DataType &p_b, bool &r_valid) const { + if (!p_a.has_type || !p_b.has_type) { + r_valid = true; + return DataType(); + } + + Variant::Type a_type = p_a.kind == DataType::BUILTIN ? p_a.builtin_type : Variant::OBJECT; + Variant::Type b_type = p_b.kind == DataType::BUILTIN ? p_b.builtin_type : Variant::OBJECT; + + Variant a; + REF a_ref; + if (a_type == Variant::OBJECT) { + a_ref.instance(); + a = a_ref; + } else { + Variant::CallError err; + a = Variant::construct(a_type, NULL, 0, err); + if (err.error != Variant::CallError::CALL_OK) { + r_valid = false; + return DataType(); + } + } + Variant b; + REF b_ref; + if (b_type == Variant::OBJECT) { + b_ref.instance(); + b = b_ref; + } else { + Variant::CallError err; + b = Variant::construct(b_type, NULL, 0, err); + if (err.error != Variant::CallError::CALL_OK) { + r_valid = false; + return DataType(); + } + } + + // Avoid division by zero + if (a_type == Variant::INT || a_type == Variant::REAL) { + Variant::evaluate(Variant::OP_ADD, a, 1, a, r_valid); + } + if (b_type == Variant::INT || b_type == Variant::REAL) { + Variant::evaluate(Variant::OP_ADD, b, 1, b, r_valid); + } + + Variant ret; + Variant::evaluate(p_op, a, b, ret, r_valid); + + if (r_valid) { + return _type_from_variant(ret); + } + + return DataType(); +} + +Variant::Operator GDScriptParser::_get_variant_operation(const OperatorNode::Operator &p_op) const { + switch (p_op) { + case OperatorNode::OP_NEG: { + return Variant::OP_NEGATE; + } break; + case OperatorNode::OP_POS: { + return Variant::OP_POSITIVE; + } break; + case OperatorNode::OP_NOT: { + return Variant::OP_NOT; + } break; + case OperatorNode::OP_BIT_INVERT: { + return Variant::OP_BIT_NEGATE; + } break; + case OperatorNode::OP_IN: { + return Variant::OP_IN; + } break; + case OperatorNode::OP_EQUAL: { + return Variant::OP_EQUAL; + } break; + case OperatorNode::OP_NOT_EQUAL: { + return Variant::OP_NOT_EQUAL; + } break; + case OperatorNode::OP_LESS: { + return Variant::OP_LESS; + } break; + case OperatorNode::OP_LESS_EQUAL: { + return Variant::OP_LESS_EQUAL; + } break; + case OperatorNode::OP_GREATER: { + return Variant::OP_GREATER; + } break; + case OperatorNode::OP_GREATER_EQUAL: { + return Variant::OP_GREATER_EQUAL; + } break; + case OperatorNode::OP_AND: { + return Variant::OP_AND; + } break; + case OperatorNode::OP_OR: { + return Variant::OP_OR; + } break; + case OperatorNode::OP_ASSIGN_ADD: + case OperatorNode::OP_ADD: { + return Variant::OP_ADD; + } break; + case OperatorNode::OP_ASSIGN_SUB: + case OperatorNode::OP_SUB: { + return Variant::OP_SUBTRACT; + } break; + case OperatorNode::OP_ASSIGN_MUL: + case OperatorNode::OP_MUL: { + return Variant::OP_MULTIPLY; + } break; + case OperatorNode::OP_ASSIGN_DIV: + case OperatorNode::OP_DIV: { + return Variant::OP_DIVIDE; + } break; + case OperatorNode::OP_ASSIGN_MOD: + case OperatorNode::OP_MOD: { + return Variant::OP_MODULE; + } break; + case OperatorNode::OP_ASSIGN_BIT_AND: + case OperatorNode::OP_BIT_AND: { + return Variant::OP_BIT_AND; + } break; + case OperatorNode::OP_ASSIGN_BIT_OR: + case OperatorNode::OP_BIT_OR: { + return Variant::OP_BIT_OR; + } break; + case OperatorNode::OP_ASSIGN_BIT_XOR: + case OperatorNode::OP_BIT_XOR: { + return Variant::OP_BIT_XOR; + } break; + case OperatorNode::OP_ASSIGN_SHIFT_LEFT: + case OperatorNode::OP_SHIFT_LEFT: { + return Variant::OP_SHIFT_LEFT; + } + case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: + case OperatorNode::OP_SHIFT_RIGHT: { + return Variant::OP_SHIFT_RIGHT; + } + default: { + return Variant::OP_MAX; + } break; + } +} + +bool GDScriptParser::_is_type_compatible(const DataType &p_container, const DataType &p_expression, bool p_allow_implicit_conversion) const { + // Ignore for completion + if (!check_types || for_completion) { + return true; + } + // Can't test if not all have type + if (!p_container.has_type || !p_expression.has_type) { + return true; + } + + // Should never get here unresolved + ERR_FAIL_COND_V(p_container.kind == DataType::UNRESOLVED, false); + ERR_FAIL_COND_V(p_expression.kind == DataType::UNRESOLVED, false); + + if (p_container.kind == DataType::BUILTIN && p_expression.kind == DataType::BUILTIN) { + bool valid = p_container.builtin_type == p_expression.builtin_type; + if (p_allow_implicit_conversion) { + valid = valid || (p_container.builtin_type == Variant::INT && p_expression.builtin_type == Variant::REAL); + valid = valid || (p_container.builtin_type == Variant::REAL && p_expression.builtin_type == Variant::INT); + valid = valid || (p_container.builtin_type == Variant::STRING && p_expression.builtin_type == Variant::NODE_PATH); + valid = valid || (p_container.builtin_type == Variant::NODE_PATH && p_expression.builtin_type == Variant::STRING); + valid = valid || (p_container.builtin_type == Variant::BOOL && p_expression.builtin_type == Variant::REAL); + valid = valid || (p_container.builtin_type == Variant::BOOL && p_expression.builtin_type == Variant::INT); + valid = valid || (p_container.builtin_type == Variant::INT && p_expression.builtin_type == Variant::BOOL); + valid = valid || (p_container.builtin_type == Variant::REAL && p_expression.builtin_type == Variant::BOOL); + } + return valid; + } + + if (p_container.kind == DataType::BUILTIN || (p_expression.kind == DataType::BUILTIN && p_expression.builtin_type != Variant::NIL)) { + // Can't mix built-ins with objects + return false; + } + + // From now on everything is objects, check polymorphism + // The container must be the same class or a superclass of the expression + + if (p_expression.kind == DataType::BUILTIN && p_expression.builtin_type == Variant::NIL) { + // Null can be assigned to object types + return true; + } + + StringName expr_native; + Ref<Script> expr_script; + ClassNode *expr_class = NULL; + + switch (p_expression.kind) { + case DataType::NATIVE: { + if (p_container.kind != DataType::NATIVE) { + // Non-native type can't be a superclass of a native type + return false; + } + if (p_expression.is_meta_type) { + expr_native = GDScriptNativeClass::get_class_static(); + } else { + expr_native = p_expression.native_type; + } + } break; + case DataType::SCRIPT: + case DataType::GDSCRIPT: { + if (p_container.kind == DataType::CLASS) { + // This cannot be resolved without cyclic dependencies, so just bail out + return false; + } + if (p_expression.is_meta_type) { + expr_native = p_expression.script_type->get_class_name(); + } else { + expr_script = p_expression.script_type; + expr_native = expr_script->get_instance_base_type(); + } + } break; + case DataType::CLASS: { + if (p_expression.is_meta_type) { + expr_native = GDScript::get_class_static(); + } else { + expr_class = p_expression.class_type; + ClassNode *base = expr_class; + while (base->base_type.kind == DataType::CLASS) { + base = base->base_type.class_type; + } + expr_native = base->base_type.native_type; + expr_script = base->base_type.script_type; + } + } + } + + switch (p_container.kind) { + case DataType::NATIVE: { + if (p_container.is_meta_type) { + return ClassDB::is_parent_class(expr_native, GDScriptNativeClass::get_class_static()); + } else { + return ClassDB::is_parent_class(expr_native, p_container.native_type); + } + } break; + case DataType::SCRIPT: + case DataType::GDSCRIPT: { + if (p_container.is_meta_type) { + return ClassDB::is_parent_class(expr_native, GDScript::get_class_static()); + } + if (expr_class == head && p_container.script_type->get_path() == self_path) { + // Special case: container is self script and expression is self + return true; + } + while (expr_script.is_valid()) { + if (expr_script == p_container.script_type) { + return true; + } + expr_script = expr_script->get_base_script(); + } + return false; + } break; + case DataType::CLASS: { + if (p_container.is_meta_type) { + return ClassDB::is_parent_class(expr_native, GDScript::get_class_static()); + } + if (p_container.class_type == head && expr_script.is_valid() && expr_script->get_path() == self_path) { + // Special case: container is self and expression is self script + return true; + } + while (expr_class) { + if (expr_class == p_container.class_type) { + return true; + } + expr_class = expr_class->base_type.class_type; + } + return false; + } + } + + return false; +} + +GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { + if (p_node->get_datatype().has_type) { + return p_node->get_datatype(); + } + + DataType node_type; + + switch (p_node->type) { + case Node::TYPE_CONSTANT: { + node_type = _type_from_variant(static_cast<ConstantNode *>(p_node)->value); + } break; + case Node::TYPE_ARRAY: { + node_type.has_type = true; + node_type.kind = DataType::BUILTIN; + node_type.builtin_type = Variant::ARRAY; + } break; + case Node::TYPE_DICTIONARY: { + node_type.has_type = true; + node_type.kind = DataType::BUILTIN; + node_type.builtin_type = Variant::DICTIONARY; + } break; + case Node::TYPE_SELF: { + node_type.has_type = true; + node_type.kind = DataType::CLASS; + node_type.class_type = current_class; + } break; + case Node::TYPE_IDENTIFIER: { + IdentifierNode *id = static_cast<IdentifierNode *>(p_node); + if (id->declared_block) { + node_type = id->declared_block->variables[id->name]->get_datatype(); + } else if (id->name == "#match_value") { + // It's a special id just for the match statetement, ignore + break; + } else if (current_function && current_function->arguments.find(id->name) >= 0) { + int idx = current_function->arguments.find(id->name); + node_type = current_function->argument_types[idx]; + } else { + node_type = _reduce_identifier_type(NULL, id->name, id->line); + } + } break; + case Node::TYPE_CAST: { + CastNode *cn = static_cast<CastNode *>(p_node); + + DataType source_type = _reduce_node_type(cn->source_node); + cn->cast_type = _resolve_type(cn->cast_type, cn->line); + if (source_type.has_type) { + + bool valid = false; + if (check_types) { + if (cn->cast_type.kind == DataType::BUILTIN && source_type.kind == DataType::BUILTIN) { + valid = Variant::can_convert(source_type.builtin_type, cn->cast_type.builtin_type); + } + if (cn->cast_type.kind != DataType::BUILTIN && source_type.kind != DataType::BUILTIN) { + valid = _is_type_compatible(cn->cast_type, source_type) || _is_type_compatible(source_type, cn->cast_type); + } + + if (!valid) { + _set_error("Invalid cast. Cannot convert from '" + source_type.to_string() + + "' to '" + cn->cast_type.to_string() + "'.", + cn->line); + return DataType(); + } + } + } else { + _mark_line_as_unsafe(cn->line); + } + + node_type = cn->cast_type; + + } break; + case Node::TYPE_OPERATOR: { + OperatorNode *op = static_cast<OperatorNode *>(p_node); + + switch (op->op) { + case OperatorNode::OP_CALL: + case OperatorNode::OP_PARENT_CALL: { + node_type = _reduce_function_call_type(op); + } break; + case OperatorNode::OP_YIELD: { + if (op->arguments.size() == 2) { + DataType base_type = _reduce_node_type(op->arguments[0]); + DataType signal_type = _reduce_node_type(op->arguments[1]); + // TODO: Check if signal exists when it's a constant + if (base_type.has_type && base_type.kind == DataType::BUILTIN && base_type.builtin_type != Variant::NIL && base_type.builtin_type != Variant::OBJECT) { + _set_error("First argument of 'yield()' must be an object.", op->line); + return DataType(); + } + if (signal_type.has_type && (signal_type.kind != DataType::BUILTIN || signal_type.builtin_type != Variant::STRING)) { + _set_error("Second argument of 'yield()' must be a string.", op->line); + return DataType(); + } + } + // yield can return anything + node_type.has_type = false; + } break; + case OperatorNode::OP_IS: { + + if (op->arguments.size() != 2) { + _set_error("Parser bug: binary operation without 2 arguments.", op->line); + ERR_FAIL_V(DataType()); + } + + DataType value_type = _reduce_node_type(op->arguments[0]); + DataType type_type = _reduce_node_type(op->arguments[1]); + + if (check_types && type_type.has_type) { + if (!type_type.is_meta_type && (type_type.kind != DataType::NATIVE || !ClassDB::is_parent_class(type_type.native_type, "Script"))) { + _set_error("Invalid 'is' test: right operand is not a type (not a native type nor a script).", op->line); + return DataType(); + } + type_type.is_meta_type = false; // Test the actual type + if (!_is_type_compatible(type_type, value_type) && !_is_type_compatible(value_type, type_type)) { + // TODO: Make this a warning? + _set_error("A value of type '" + value_type.to_string() + "' will never be an instance of '" + type_type.to_string() + "'.", op->line); + return DataType(); + } + } + + node_type.has_type = true; + node_type.is_constant = true; + node_type.is_meta_type = false; + node_type.kind = DataType::BUILTIN; + node_type.builtin_type = Variant::BOOL; + } break; + // Unary operators + case OperatorNode::OP_NEG: + case OperatorNode::OP_POS: + case OperatorNode::OP_NOT: + case OperatorNode::OP_BIT_INVERT: { + + DataType argument_type = _reduce_node_type(op->arguments[0]); + if (!argument_type.has_type) { + break; + } + + Variant::Operator var_op = _get_variant_operation(op->op); + bool valid = false; + node_type = _get_operation_type(var_op, argument_type, argument_type, valid); + + if (check_types && !valid) { + _set_error("Invalid operand type ('" + argument_type.to_string() + + "') to unary operator '" + Variant::get_operator_name(var_op) + "'.", + op->line, op->column); + return DataType(); + } + + } break; + // Binary operators + case OperatorNode::OP_IN: + case OperatorNode::OP_EQUAL: + case OperatorNode::OP_NOT_EQUAL: + case OperatorNode::OP_LESS: + case OperatorNode::OP_LESS_EQUAL: + case OperatorNode::OP_GREATER: + case OperatorNode::OP_GREATER_EQUAL: + case OperatorNode::OP_AND: + case OperatorNode::OP_OR: + case OperatorNode::OP_ADD: + case OperatorNode::OP_SUB: + case OperatorNode::OP_MUL: + case OperatorNode::OP_DIV: + case OperatorNode::OP_MOD: + case OperatorNode::OP_SHIFT_LEFT: + case OperatorNode::OP_SHIFT_RIGHT: + case OperatorNode::OP_BIT_AND: + case OperatorNode::OP_BIT_OR: + case OperatorNode::OP_BIT_XOR: { + + if (op->arguments.size() != 2) { + _set_error("Parser bug: binary operation without 2 arguments.", op->line); + ERR_FAIL_V(DataType()); + } + + DataType argument_a_type = _reduce_node_type(op->arguments[0]); + DataType argument_b_type = _reduce_node_type(op->arguments[1]); + if (!argument_a_type.has_type || !argument_b_type.has_type) { + _mark_line_as_unsafe(op->line); + break; + } + + Variant::Operator var_op = _get_variant_operation(op->op); + bool valid = false; + node_type = _get_operation_type(var_op, argument_a_type, argument_b_type, valid); + + if (check_types && !valid) { + _set_error("Invalid operand types ('" + argument_a_type.to_string() + "' and '" + + argument_b_type.to_string() + "') to operator '" + Variant::get_operator_name(var_op) + "'.", + op->line, op->column); + return DataType(); + } + + } break; + // Ternary operators + case OperatorNode::OP_TERNARY_IF: { + if (op->arguments.size() != 3) { + _set_error("Parser bug: ternary operation without 3 arguments"); + ERR_FAIL_V(DataType()); + } + + DataType true_type = _reduce_node_type(op->arguments[1]); + DataType false_type = _reduce_node_type(op->arguments[2]); + + // If types are equal, then the expression is of the same type + // If they are compatible, return the broader type + if (true_type == false_type || _is_type_compatible(true_type, false_type)) { + node_type = true_type; + } else if (_is_type_compatible(false_type, true_type)) { + node_type = false_type; + } + + // TODO: Warn if types aren't compatible + + } break; + // Assignment should never happen within an expression + case OperatorNode::OP_ASSIGN: + case OperatorNode::OP_ASSIGN_ADD: + case OperatorNode::OP_ASSIGN_SUB: + case OperatorNode::OP_ASSIGN_MUL: + case OperatorNode::OP_ASSIGN_DIV: + case OperatorNode::OP_ASSIGN_MOD: + case OperatorNode::OP_ASSIGN_SHIFT_LEFT: + case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: + case OperatorNode::OP_ASSIGN_BIT_AND: + case OperatorNode::OP_ASSIGN_BIT_OR: + case OperatorNode::OP_ASSIGN_BIT_XOR: + case OperatorNode::OP_INIT_ASSIGN: { + + _set_error("Assignment inside expression is not allowed (parser bug?).", op->line); + return DataType(); + + } break; + case OperatorNode::OP_INDEX_NAMED: { + if (op->arguments.size() != 2) { + _set_error("Parser bug: named index with invalid arguments.", op->line); + ERR_FAIL_V(DataType()); + } + if (op->arguments[1]->type != Node::TYPE_IDENTIFIER) { + _set_error("Parser bug: named index without identifier argument.", op->line); + ERR_FAIL_V(DataType()); + } + + DataType base_type = _reduce_node_type(op->arguments[0]); + IdentifierNode *member_id = static_cast<IdentifierNode *>(op->arguments[1]); + + if (base_type.has_type) { + if (check_types && base_type.kind == DataType::BUILTIN) { + // Variant type, just test if it's possible + DataType result; + switch (base_type.builtin_type) { + case Variant::NIL: + case Variant::DICTIONARY: { + result.has_type = false; + } break; + default: { + Variant::CallError err; + Variant temp = Variant::construct(base_type.builtin_type, NULL, 0, err); + + bool valid = false; + Variant res = temp.get(member_id->name.operator String(), &valid); + + if (valid) { + result = _type_from_variant(res); + } else if (check_types) { + _set_error("Can't get index '" + String(member_id->name.operator String()) + "' on base '" + + base_type.to_string() + "'.", + op->line); + return DataType(); + } + } break; + } + result.is_constant = false; + node_type = result; + } else { + node_type = _reduce_identifier_type(&base_type, member_id->name, op->line); + } + } else { + _mark_line_as_unsafe(op->line); + } + if (error_set) { + return DataType(); + } + } break; + case OperatorNode::OP_INDEX: { + + if (op->arguments[1]->type == Node::TYPE_CONSTANT) { + ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[1]); + if (cn->value.get_type() == Variant::STRING) { + // Treat this as named indexing + + IdentifierNode *id = alloc_node<IdentifierNode>(); + id->name = cn->value.operator StringName(); + + op->op = OperatorNode::OP_INDEX_NAMED; + op->arguments[1] = id; + + return _reduce_node_type(op); + } + } + + DataType base_type = _reduce_node_type(op->arguments[0]); + DataType index_type = _reduce_node_type(op->arguments[1]); + + if (!base_type.has_type) { + _mark_line_as_unsafe(op->line); + break; + } + + if (check_types && index_type.has_type) { + if (base_type.kind == DataType::BUILTIN) { + // Check if indexing is valid + bool error = index_type.kind != DataType::BUILTIN; + if (!error) { + switch (base_type.builtin_type) { + // Expect int or real as index + case Variant::POOL_BYTE_ARRAY: + case Variant::POOL_COLOR_ARRAY: + case Variant::POOL_INT_ARRAY: + case Variant::POOL_REAL_ARRAY: + case Variant::POOL_STRING_ARRAY: + case Variant::POOL_VECTOR2_ARRAY: + case Variant::POOL_VECTOR3_ARRAY: + case Variant::ARRAY: + case Variant::STRING: { + error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::REAL; + } break; + // Expect String only + case Variant::RECT2: + case Variant::PLANE: + case Variant::QUAT: + case Variant::AABB: + case Variant::OBJECT: { + error = index_type.builtin_type != Variant::STRING; + } break; + // Expect String or number + case Variant::VECTOR2: + case Variant::VECTOR3: + case Variant::TRANSFORM2D: + case Variant::BASIS: + case Variant::TRANSFORM: { + error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::REAL && + index_type.builtin_type != Variant::STRING; + } break; + // Expect String or int + case Variant::COLOR: { + error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING; + } break; + } + } + if (error) { + _set_error("Invalid index type (" + index_type.to_string() + ") for base '" + base_type.to_string() + "'.", + op->line); + return DataType(); + } + + if (op->arguments[1]->type == GDScriptParser::Node::TYPE_CONSTANT) { + ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[1]); + // Index is a constant, just try it if possible + switch (base_type.builtin_type) { + // Arrays/string have variable indexing, can't test directly + case Variant::STRING: + case Variant::ARRAY: + case Variant::DICTIONARY: + case Variant::POOL_BYTE_ARRAY: + case Variant::POOL_COLOR_ARRAY: + case Variant::POOL_INT_ARRAY: + case Variant::POOL_REAL_ARRAY: + case Variant::POOL_STRING_ARRAY: + case Variant::POOL_VECTOR2_ARRAY: + case Variant::POOL_VECTOR3_ARRAY: { + break; + } + default: { + Variant::CallError err; + Variant temp = Variant::construct(base_type.builtin_type, NULL, 0, err); + + bool valid = false; + Variant res = temp.get(cn->value, &valid); + + if (valid) { + node_type = _type_from_variant(res); + node_type.is_constant = false; + } else if (check_types) { + _set_error("Can't get index '" + String(cn->value) + "' on base '" + + base_type.to_string() + "'.", + op->line); + return DataType(); + } + } break; + } + } else { + _mark_line_as_unsafe(op->line); + } + } else if (!for_completion && (index_type.kind != DataType::BUILTIN || index_type.builtin_type != Variant::STRING)) { + _set_error("Only strings can be used as index in the base type '" + base_type.to_string() + "'.", op->line); + return DataType(); + } + } + if (check_types && !node_type.has_type) { + // Can infer indexing type for some variant types + DataType result; + result.has_type = true; + result.kind = DataType::BUILTIN; + switch (base_type.builtin_type) { + // Can't index at all + case Variant::NIL: + case Variant::BOOL: + case Variant::INT: + case Variant::REAL: + case Variant::NODE_PATH: + case Variant::_RID: { + _set_error("Can't index on a value of type '" + base_type.to_string() + "'.", op->line); + return DataType(); + } break; + // Return int + case Variant::POOL_BYTE_ARRAY: + case Variant::POOL_INT_ARRAY: { + result.builtin_type = Variant::INT; + } break; + // Return real + case Variant::POOL_REAL_ARRAY: + case Variant::VECTOR2: + case Variant::VECTOR3: + case Variant::QUAT: { + result.builtin_type = Variant::REAL; + } break; + // Return color + case Variant::POOL_COLOR_ARRAY: { + result.builtin_type = Variant::COLOR; + } break; + // Return string + case Variant::POOL_STRING_ARRAY: + case Variant::STRING: { + result.builtin_type = Variant::STRING; + } break; + // Return Vector2 + case Variant::POOL_VECTOR2_ARRAY: + case Variant::TRANSFORM2D: + case Variant::RECT2: { + result.builtin_type = Variant::VECTOR2; + } break; + // Return Vector3 + case Variant::POOL_VECTOR3_ARRAY: + case Variant::AABB: + case Variant::BASIS: { + result.builtin_type = Variant::VECTOR3; + } break; + // Depends on the index + case Variant::TRANSFORM: + case Variant::PLANE: + case Variant::COLOR: + default: { + result.has_type = false; + } break; + } + node_type = result; + } + } break; + default: { + _set_error("Parser bug: unhandled operation.", op->line); + ERR_FAIL_V(DataType()); + } + } + } break; + } + + p_node->set_datatype(_resolve_type(node_type, p_node->line)); + return node_type; +} + +bool GDScriptParser::_get_function_signature(DataType &p_base_type, const StringName &p_function, DataType &r_return_type, List<DataType> &r_arg_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) const { + + r_static = false; + r_default_arg_count = 0; + + DataType original_type = p_base_type; + ClassNode *base = NULL; + FunctionNode *callee = NULL; + + if (p_base_type.kind == DataType::CLASS) { + base = p_base_type.class_type; + } + + // Look up the current file (parse tree) + while (!callee && base) { + for (int i = 0; i < base->static_functions.size(); i++) { + FunctionNode *func = base->static_functions[i]; + if (p_function == func->name) { + r_static = true; + callee = func; + break; + } + } + if (!callee && !p_base_type.is_meta_type) { + for (int i = 0; i < base->functions.size(); i++) { + FunctionNode *func = base->functions[i]; + if (p_function == func->name) { + callee = func; + break; + } + } + } + p_base_type = base->base_type; + if (p_base_type.kind == DataType::CLASS) { + base = p_base_type.class_type; + } else { + break; + } + } + + if (callee) { + r_return_type = callee->get_datatype(); + for (int i = 0; i < callee->argument_types.size(); i++) { + r_arg_types.push_back(callee->argument_types[i]); + } + r_default_arg_count = callee->default_values.size(); + return true; + } + + // Nothing in current file, check parent script + Ref<GDScript> base_gdscript; + Ref<Script> base_script; + StringName native; + if (p_base_type.kind == DataType::GDSCRIPT) { + base_gdscript = p_base_type.script_type; + } else if (p_base_type.kind == DataType::SCRIPT) { + base_script = p_base_type.script_type; + } else if (p_base_type.kind == DataType::NATIVE) { + native = p_base_type.native_type; + } + + while (base_gdscript.is_valid()) { + native = base_gdscript->get_instance_base_type(); + + Map<StringName, GDScriptFunction *> funcs = base_gdscript->get_member_functions(); + + if (funcs.has(p_function)) { + GDScriptFunction *f = funcs[p_function]; + r_static = f->is_static(); + r_default_arg_count = f->get_default_argument_count(); + r_return_type = _type_from_gdtype(f->get_return_type()); + for (int i = 0; i < f->get_argument_count(); i++) { + r_arg_types.push_back(_type_from_gdtype(f->get_argument_type(i))); + } + return true; + } + + base_gdscript = base_gdscript->get_base_script(); + } + + while (base_script.is_valid()) { + native = base_script->get_instance_base_type(); + MethodInfo mi = base_script->get_method_info(p_function); + + if (!(mi == MethodInfo())) { + r_return_type = _type_from_property(mi.return_val, false); + r_default_arg_count = mi.default_arguments.size(); + for (List<PropertyInfo>::Element *E = mi.arguments.front(); E; E = E->next()) { + r_arg_types.push_back(_type_from_property(E->get())); + } + return true; + } + base_script = base_script->get_base_script(); + } + +#ifdef DEBUG_METHODS_ENABLED + + // Only native remains + if (!ClassDB::class_exists(native)) { + native = "_" + native.operator String(); + } + if (!ClassDB::class_exists(native)) { + if (!check_types) return false; + ERR_EXPLAIN("Parser bug: Class '" + String(native) + "' not found."); + ERR_FAIL_V(false); + } + + MethodBind *method = ClassDB::get_method(native, p_function); + + if (!method) { + // Try virtual methods + List<MethodInfo> virtuals; + ClassDB::get_virtual_methods(native, &virtuals); + + for (const List<MethodInfo>::Element *E = virtuals.front(); E; E = E->next()) { + const MethodInfo &mi = E->get(); + if (mi.name == p_function) { + r_default_arg_count = mi.default_arguments.size(); + for (const List<PropertyInfo>::Element *pi = mi.arguments.front(); pi; pi = pi->next()) { + r_arg_types.push_back(_type_from_property(pi->get())); + } + r_return_type = _type_from_property(mi.return_val, false); + r_vararg = mi.flags & METHOD_FLAG_VARARG; + return true; + } + } + + // If the base is a script, it might be trying to access members of the Script class itself + if (original_type.is_meta_type && !(p_function == "new") && (original_type.kind == DataType::SCRIPT || original_type.kind == DataType::GDSCRIPT)) { + method = ClassDB::get_method(original_type.script_type->get_class_name(), p_function); + + if (method) { + r_static = true; + } else { + // Try virtual methods of the script type + virtuals.clear(); + ClassDB::get_virtual_methods(original_type.script_type->get_class_name(), &virtuals); + for (const List<MethodInfo>::Element *E = virtuals.front(); E; E = E->next()) { + const MethodInfo &mi = E->get(); + if (mi.name == p_function) { + r_default_arg_count = mi.default_arguments.size(); + for (const List<PropertyInfo>::Element *pi = mi.arguments.front(); pi; pi = pi->next()) { + r_arg_types.push_back(_type_from_property(pi->get())); + } + r_return_type = _type_from_property(mi.return_val, false); + r_static = true; + r_vararg = mi.flags & METHOD_FLAG_VARARG; + return true; + } + } + return false; + } + } else { + return false; + } + } + + r_default_arg_count = method->get_default_argument_count(); + r_return_type = _type_from_property(method->get_return_info(), false); + r_vararg = method->is_vararg(); + + for (int i = 0; i < method->get_argument_count(); i++) { + r_arg_types.push_back(_type_from_property(method->get_argument_info(i))); + } + return true; +#else + return false; +#endif +} + +GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const OperatorNode *p_call) { + if (p_call->arguments.size() < 1) { + _set_error("Parser bug: function call without enough arguments.", p_call->line); + ERR_FAIL_V(DataType()); + } + + DataType return_type; + List<DataType> arg_types; + int default_args_count = 0; + int arg_count = p_call->arguments.size(); + String callee_name; + bool is_vararg = false; + + switch (p_call->arguments[0]->type) { + case GDScriptParser::Node::TYPE_TYPE: { + // Built-in constructor, special case + TypeNode *tn = static_cast<TypeNode *>(p_call->arguments[0]); + + Vector<DataType> par_types; + par_types.resize(p_call->arguments.size() - 1); + for (int i = 1; i < p_call->arguments.size(); i++) { + par_types[i - 1] = _reduce_node_type(p_call->arguments[i]); + } + + if (error_set) return DataType(); + + bool match = false; + List<MethodInfo> constructors; + Variant::get_constructor_list(tn->vtype, &constructors); + PropertyInfo return_type; + + for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) { + MethodInfo &mi = E->get(); + + if (p_call->arguments.size() - 1 < mi.arguments.size() - mi.default_arguments.size()) { + continue; + } + if (p_call->arguments.size() - 1 > mi.arguments.size()) { + continue; + } + + bool types_match = true; + for (int i = 0; i < par_types.size(); i++) { + DataType arg_type; + if (mi.arguments[i].type != Variant::NIL) { + arg_type.has_type = true; + arg_type.kind = mi.arguments[i].type == Variant::OBJECT ? DataType::NATIVE : DataType::BUILTIN; + arg_type.builtin_type = mi.arguments[i].type; + arg_type.native_type = mi.arguments[i].class_name; + } + + if (!_is_type_compatible(arg_type, par_types[i], true)) { + types_match = false; + break; + } + } + + if (types_match) { + match = true; + return_type = mi.return_val; + break; + } + } + + if (match) { + return _type_from_property(return_type, false); + } else if (check_types) { + String err = "No constructor of '"; + err += Variant::get_type_name(tn->vtype); + err += "' matches the signature '"; + err += Variant::get_type_name(tn->vtype) + "("; + for (int i = 0; i < par_types.size(); i++) { + if (i > 0) err += ", "; + err += par_types[i].to_string(); + } + err += ")'."; + _set_error(err, p_call->line, p_call->column); + return DataType(); + } + return DataType(); + } break; + case GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION: { + BuiltInFunctionNode *func = static_cast<BuiltInFunctionNode *>(p_call->arguments[0]); + MethodInfo mi = GDScriptFunctions::get_info(func->function); + + return_type = _type_from_property(mi.return_val, false); + + // Check arguments + + is_vararg = mi.flags & METHOD_FLAG_VARARG; + + default_args_count = mi.default_arguments.size(); + callee_name = mi.name; + arg_count -= 1; + + // Check each argument type + for (List<PropertyInfo>::Element *E = mi.arguments.front(); E; E = E->next()) { + arg_types.push_back(_type_from_property(E->get())); + } + } break; + default: { + if (p_call->op == OperatorNode::OP_CALL && p_call->arguments.size() < 2) { + _set_error("Parser bug: self method call without enough arguments.", p_call->line); + ERR_FAIL_V(DataType()); + } + + int arg_id = p_call->op == OperatorNode::OP_CALL ? 1 : 0; + + if (p_call->arguments[arg_id]->type != Node::TYPE_IDENTIFIER) { + _set_error("Parser bug: invalid function call argument.", p_call->line); + ERR_FAIL_V(DataType()); + } + + IdentifierNode *func_id = static_cast<IdentifierNode *>(p_call->arguments[arg_id]); + callee_name = func_id->name; + arg_count -= 1 + arg_id; + + DataType base_type; + if (p_call->op == OperatorNode::OP_PARENT_CALL) { + base_type = current_class->base_type; + } else { + base_type = _reduce_node_type(p_call->arguments[0]); + } + + if (!base_type.has_type || (base_type.kind == DataType::BUILTIN && base_type.builtin_type == Variant::NIL)) { + _mark_line_as_unsafe(p_call->line); + return DataType(); + } + + if (base_type.kind == DataType::BUILTIN) { + Variant::CallError err; + Variant tmp = Variant::construct(base_type.builtin_type, NULL, 0, err); + + if (check_types) { + if (!tmp.has_method(callee_name)) { + _set_error("Method '" + callee_name + "' is not declared on base '" + base_type.to_string() + "'.", p_call->line); + return DataType(); + } + + default_args_count = Variant::get_method_default_arguments(base_type.builtin_type, callee_name).size(); + const Vector<Variant::Type> &var_arg_types = Variant::get_method_argument_types(base_type.builtin_type, callee_name); + + for (int i = 0; i < var_arg_types.size(); i++) { + DataType argtype; + if (var_arg_types[i] != Variant::NIL) { + argtype.has_type = true; + argtype.kind = DataType::BUILTIN; + argtype.builtin_type = var_arg_types[i]; + } + arg_types.push_back(argtype); + } + } + + return_type.has_type = true; + return_type.kind = DataType::BUILTIN; + return_type.builtin_type = Variant::get_method_return_type(base_type.builtin_type, callee_name); + break; + } + + DataType original_type = base_type; + bool is_initializer = callee_name == "new"; + bool is_static = false; + bool valid = false; + + if (is_initializer && original_type.is_meta_type) { + // Try to check it as initializer + base_type = original_type; + callee_name = "_init"; + base_type.is_meta_type = false; + + valid = _get_function_signature(base_type, callee_name, return_type, arg_types, + default_args_count, is_static, is_vararg); + + if (valid) { + return_type = original_type; + return_type.is_meta_type = false; + } + } + + if (!valid) { + base_type = original_type; + return_type = DataType(); + valid = _get_function_signature(base_type, callee_name, return_type, arg_types, + default_args_count, is_static, is_vararg); + } + + if (!valid) { +#ifdef DEBUG_ENABLED + if (p_call->arguments[0]->type == Node::TYPE_SELF) { + _set_error("Method '" + callee_name + "' is not declared in the current class.", p_call->line); + return DataType(); + } + _mark_line_as_unsafe(p_call->line); +#endif + return DataType(); + } + +#ifdef DEBUG_ENABLED + if (current_function && !for_completion && !is_static && p_call->arguments[0]->type == Node::TYPE_SELF && current_function->_static) { + if (current_function && current_function->_static && p_call->arguments[0]->type == Node::TYPE_SELF) { + _set_error("Can't call non-static function from a static function.", p_call->line); + return DataType(); + } + } + + if (check_types && !is_static && !is_initializer && base_type.is_meta_type) { + _set_error("Non-static function '" + String(callee_name) + "' can only be called from an instance.", p_call->line); + return DataType(); + } +#endif + } break; + } + + if (!check_types) { + return return_type; + } + + if (arg_count < arg_types.size() - default_args_count) { + _set_error("Too few arguments for '" + callee_name + "()' call. Expected at least " + itos(arg_types.size() - default_args_count) + ".", p_call->line); + return return_type; + } + if (!is_vararg && arg_count > arg_types.size()) { + _set_error("Too many arguments for '" + callee_name + "()' call. Expected at most " + itos(arg_types.size()) + ".", p_call->line); + return return_type; + } + + int arg_diff = p_call->arguments.size() - arg_count; + for (int i = arg_diff; i < p_call->arguments.size(); i++) { + DataType par_type = _reduce_node_type(p_call->arguments[i]); + + if ((i - arg_diff) >= arg_types.size()) { + continue; + } + + if (!par_type.has_type) { + _mark_line_as_unsafe(p_call->line); + } else if (!_is_type_compatible(arg_types[i - arg_diff], par_type, true)) { + // Supertypes are acceptable for dynamic compliance + if (!_is_type_compatible(par_type, arg_types[i - arg_diff])) { + _set_error("At '" + callee_name + "()' call, argument " + itos(i - arg_diff + 1) + ". Assigned type (" + + par_type.to_string() + ") doesn't match the function argument's type (" + + arg_types[i - arg_diff].to_string() + ").", + p_call->line); + return DataType(); + } else { + _mark_line_as_unsafe(p_call->line); + } + } + } + + return return_type; +} + +bool GDScriptParser::_get_member_type(const DataType &p_base_type, const StringName &p_member, DataType &r_member_type) const { + DataType base_type = p_base_type; + + // Check classes in current file + ClassNode *base = NULL; + if (base_type.kind == DataType::CLASS) { + base = base_type.class_type; + } + + while (base) { + if (base->constant_expressions.has(p_member)) { + r_member_type = base->constant_expressions[p_member].expression->get_datatype(); + return true; + } + + if (!base_type.is_meta_type) { + for (int i = 0; i < base->variables.size(); i++) { + ClassNode::Member m = base->variables[i]; + if (m.identifier == p_member) { + r_member_type = m.data_type; + return true; + } + } + } else { + for (int i = 0; i < base->subclasses.size(); i++) { + ClassNode *c = base->subclasses[i]; + if (c->name == p_member) { + DataType class_type; + class_type.has_type = true; + class_type.is_constant = true; + class_type.is_meta_type = true; + class_type.kind = DataType::CLASS; + class_type.class_type = c; + r_member_type = class_type; + return true; + } + } + } + + base_type = base->base_type; + if (base_type.kind == DataType::CLASS) { + base = base_type.class_type; + } else { + break; + } + } + + Ref<GDScript> gds; + if (base_type.kind == DataType::GDSCRIPT) { + gds = base_type.script_type; + } + + Ref<Script> scr; + if (base_type.kind == DataType::SCRIPT) { + scr = base_type.script_type; + } + + StringName native; + if (base_type.kind == DataType::NATIVE) { + native = base_type.native_type; + } + + // Check GDScripts + while (gds.is_valid()) { + if (gds->get_constants().has(p_member)) { + Variant c = gds->get_constants()[p_member]; + r_member_type = _type_from_variant(c); + return true; + } + + if (!base_type.is_meta_type) { + if (gds->get_members().has(p_member)) { + r_member_type = _type_from_gdtype(gds->get_member_type(p_member)); + return true; + } + } + + native = gds->get_instance_base_type(); + if (gds->get_base_script().is_valid()) { + gds = gds->get_base_script(); + scr = gds->get_base_script(); + bool is_meta = base_type.is_meta_type; + base_type = _type_from_variant(scr.operator Variant()); + base_type.is_meta_type = is_meta; + } else { + break; + } + } + + // Check other script types + while (scr.is_valid()) { + Map<StringName, Variant> constants; + scr->get_constants(&constants); + if (constants.has(p_member)) { + r_member_type = _type_from_variant(constants[p_member]); + return true; + } + + List<PropertyInfo> properties; + scr->get_script_property_list(&properties); + for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { + if (E->get().name == p_member) { + r_member_type = _type_from_property(E->get()); + return true; + } + } + + base_type = _type_from_variant(scr.operator Variant()); + native = scr->get_instance_base_type(); + scr = scr->get_base_script(); + } + + // Check ClassDB + if (!ClassDB::class_exists(native)) { + native = "_" + native.operator String(); + } + if (!ClassDB::class_exists(native)) { + if (!check_types) return false; + ERR_EXPLAIN("Parser bug: Class '" + String(native) + "' not found."); + ERR_FAIL_V(false); + } + + bool valid = false; + ClassDB::get_integer_constant(native, p_member, &valid); + if (valid) { + DataType ct; + ct.has_type = true; + ct.is_constant = true; + ct.kind = DataType::BUILTIN; + ct.builtin_type = Variant::INT; + r_member_type = ct; + return true; + } + + if (!base_type.is_meta_type) { + List<PropertyInfo> properties; + ClassDB::get_property_list(native, &properties); + for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { + if (E->get().name == p_member) { + // Check if a getter exists + StringName getter_name = ClassDB::get_property_getter(native, p_member); + if (getter_name != StringName()) { + // Use the getter return type +#ifdef DEBUG_METHODS_ENABLED + MethodBind *getter_method = ClassDB::get_method(native, getter_name); + if (getter_method) { + r_member_type = _type_from_property(getter_method->get_return_info()); + } else { + r_member_type = DataType(); + } +#else + r_member_type = DataType(); +#endif + } else { + r_member_type = _type_from_property(E->get()); + } + return true; + } + } + } + + // If the base is a script, it might be trying to access members of the Script class itself + if (p_base_type.is_meta_type && (p_base_type.kind == DataType::SCRIPT || p_base_type.kind == DataType::GDSCRIPT)) { + native = p_base_type.script_type->get_class_name(); + ClassDB::get_integer_constant(native, p_member, &valid); + if (valid) { + DataType ct; + ct.has_type = true; + ct.is_constant = true; + ct.kind = DataType::BUILTIN; + ct.builtin_type = Variant::INT; + r_member_type = ct; + return true; + } + + List<PropertyInfo> properties; + ClassDB::get_property_list(native, &properties); + for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { + if (E->get().name == p_member) { + // Check if a getter exists + StringName getter_name = ClassDB::get_property_getter(native, p_member); + if (getter_name != StringName()) { + // Use the getter return type +#ifdef DEBUG_METHODS_ENABLED + MethodBind *getter_method = ClassDB::get_method(native, getter_name); + if (getter_method) { + r_member_type = _type_from_property(getter_method->get_return_info()); + } else { + r_member_type = DataType(); + } +#else + r_member_type = DataType(); +#endif + } else { + r_member_type = _type_from_property(E->get()); + } + return true; + } + } + } + + return false; +} + +GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType *p_base_type, const StringName &p_identifier, int p_line) { + + if (p_base_type && !p_base_type->has_type) { + return DataType(); + } + + DataType base_type; + + // Check classes in current file + ClassNode *base = NULL; + if (!p_base_type) { + // Possibly this is a global, check first + + if (ClassDB::class_exists(p_identifier) || ClassDB::class_exists("_" + p_identifier.operator String())) { + DataType result; + result.has_type = true; + result.is_constant = true; + result.is_meta_type = true; + if (Engine::get_singleton()->has_singleton(p_identifier) || Engine::get_singleton()->has_singleton("_" + p_identifier.operator String())) { + result.is_meta_type = false; + } + result.kind = DataType::NATIVE; + result.native_type = p_identifier; + return result; + } + + ClassNode *outer_class = current_class; + while (outer_class) { + if (outer_class->name == p_identifier) { + DataType result; + result.has_type = true; + result.is_constant = true; + result.is_meta_type = true; + result.kind = DataType::CLASS; + result.class_type = outer_class; + return result; + } + for (int i = 0; i < outer_class->subclasses.size(); i++) { + if (outer_class->subclasses[i] == current_class) { + continue; + } + if (outer_class->subclasses[i]->name == p_identifier) { + DataType result; + result.has_type = true; + result.is_constant = true; + result.is_meta_type = true; + result.kind = DataType::CLASS; + result.class_type = outer_class->subclasses[i]; + return result; + } + } + outer_class = outer_class->owner; + } + + if (ScriptServer::is_global_class(p_identifier)) { + Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_identifier)); + if (scr.is_valid()) { + DataType result; + result.has_type = true; + result.script_type = scr; + result.is_meta_type = true; + Ref<GDScript> gds = scr; + if (gds.is_valid()) { + if (!gds->is_valid()) { + _set_error("Class '" + p_identifier + "' could not be fully loaded (script error or cyclic inheritance)."); + return DataType(); + } + result.kind = DataType::GDSCRIPT; + } else { + result.kind = DataType::SCRIPT; + } + return result; + } + _set_error("Class '" + p_identifier + "' was found in global scope but its script could not be loaded."); + return DataType(); + } + + if (GDScriptLanguage::get_singleton()->get_global_map().has(p_identifier)) { + int idx = GDScriptLanguage::get_singleton()->get_global_map()[p_identifier]; + Variant g = GDScriptLanguage::get_singleton()->get_global_array()[idx]; + return _type_from_variant(g); + } + + if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(p_identifier)) { + Variant g = GDScriptLanguage::get_singleton()->get_named_globals_map()[p_identifier]; + return _type_from_variant(g); + } + + // Non-tool singletons aren't loaded, check project settings + List<PropertyInfo> props; + ProjectSettings::get_singleton()->get_property_list(&props); + + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + String s = E->get().name; + if (!s.begins_with("autoload/")) { + continue; + } + String name = s.get_slice("/", 1); + if (name == p_identifier) { + String script = ProjectSettings::get_singleton()->get(s); + if (script.begins_with("*")) { + script = script.right(1); + } + if (!script.begins_with("res://")) { + script = "res://" + script; + } + Ref<Script> singleton = ResourceLoader::load(script); + if (singleton.is_valid()) { + DataType result; + result.has_type = true; + result.script_type = singleton; + + Ref<GDScript> gds = singleton; + if (gds.is_valid()) { + if (!gds->is_valid()) { + _set_error("Couldn't fully load singleton script '" + p_identifier + "' (possible cyclic reference or parse error).", p_line); + return DataType(); + } + result.kind = DataType::GDSCRIPT; + } else { + result.kind = DataType::SCRIPT; + } + } + } + } + + // Nothing found, keep looking in local scope + + base = current_class; + base_type.has_type = true; + base_type.is_constant = true; + base_type.kind = DataType::CLASS; + base_type.class_type = base; + } else { + base_type = *p_base_type; + if (base_type.kind == DataType::CLASS) { + base = base_type.class_type; + } + } + + DataType member_type; + + if (_get_member_type(base_type, p_identifier, member_type)) { + return member_type; + } + + if (!p_base_type) { + // This means looking in the current class, which type is always known + _set_error("Identifier '" + p_identifier.operator String() + "' is not declared in the current scope.", p_line); + } + + _mark_line_as_unsafe(p_line); + return DataType(); +} + +void GDScriptParser::_check_class_level_types(ClassNode *p_class) { + + _mark_line_as_safe(p_class->line); + + // Constants + for (Map<StringName, ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) { + ClassNode::Constant &c = E->get(); + _mark_line_as_safe(c.expression->line); + DataType cont = _resolve_type(c.type, c.expression->line); + DataType expr = _resolve_type(c.expression->get_datatype(), c.expression->line); + + if (!_is_type_compatible(cont, expr)) { + _set_error("Constant value type (" + expr.to_string() + ") is not compatible with declared type (" + cont.to_string() + ").", + c.expression->line); + return; + } + + expr.is_constant = true; + c.type = expr; + c.expression->set_datatype(expr); + } + + // Function declarations + for (int i = 0; i < p_class->static_functions.size(); i++) { + _check_function_types(p_class->static_functions[i]); + if (error_set) return; + } + + for (int i = 0; i < p_class->functions.size(); i++) { + _check_function_types(p_class->functions[i]); + if (error_set) return; + } + + // Class variables + for (int i = 0; i < p_class->variables.size(); i++) { + ClassNode::Member &v = p_class->variables[i]; + + DataType tmp; + if (_get_member_type(p_class->base_type, v.identifier, tmp)) { + _set_error("Member '" + String(v.identifier) + "' already exists in parent class.", v.line); + return; + } + + _mark_line_as_safe(v.line); + v.data_type = _resolve_type(v.data_type, v.line); + + if (v.expression) { + DataType expr_type = _reduce_node_type(v.expression); + + if (!_is_type_compatible(v.data_type, expr_type)) { + // Try supertype test + if (_is_type_compatible(expr_type, v.data_type)) { + _mark_line_as_unsafe(v.line); + } else { + // Try with implicit conversion + if (v.data_type.kind != DataType::BUILTIN || !_is_type_compatible(v.data_type, expr_type, true)) { + _set_error("Assigned expression type (" + expr_type.to_string() + ") doesn't match the variable's type (" + + v.data_type.to_string() + ").", + v.line); + return; + } + + // Replace assigment with implict conversion + BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>(); + convert->line = v.line; + convert->function = GDScriptFunctions::TYPE_CONVERT; + + ConstantNode *tgt_type = alloc_node<ConstantNode>(); + tgt_type->line = v.line; + tgt_type->value = (int)v.data_type.builtin_type; + + OperatorNode *convert_call = alloc_node<OperatorNode>(); + convert_call->line = v.line; + convert_call->op = OperatorNode::OP_CALL; + convert_call->arguments.push_back(convert); + convert_call->arguments.push_back(v.expression); + convert_call->arguments.push_back(tgt_type); + + v.expression = convert_call; + v.initial_assignment->arguments[1] = convert_call; + } + } + + if (v.data_type.infer_type) { + if (!expr_type.has_type) { + _set_error("Assigned value does not have a set type, variable type cannot be inferred.", v.line); + return; + } + v.data_type = expr_type; + v.data_type.is_constant = false; + } + } else if (v.data_type.has_type && v.data_type.kind == DataType::BUILTIN) { + // Create default value based on the type + IdentifierNode *id = alloc_node<IdentifierNode>(); + id->line = v.line; + id->name = v.identifier; + + ConstantNode *init = alloc_node<ConstantNode>(); + init->line = v.line; + Variant::CallError err; + init->value = Variant::construct(v.data_type.builtin_type, NULL, 0, err); + + OperatorNode *op = alloc_node<OperatorNode>(); + op->line = v.line; + op->op = OperatorNode::OP_INIT_ASSIGN; + op->arguments.push_back(id); + op->arguments.push_back(init); + + p_class->initializer->statements.push_front(op); + v.initial_assignment = op; +#ifdef DEBUG_ENABLED + NewLineNode *nl = alloc_node<NewLineNode>(); + nl->line = v.line - 1; + p_class->initializer->statements.push_front(nl); +#endif + } + + // Check export hint + if (v.data_type.has_type && v._export.type != Variant::NIL) { + DataType export_type = _type_from_property(v._export); + if (!_is_type_compatible(v.data_type, export_type, true)) { + _set_error("Export hint type (" + export_type.to_string() + ") doesn't match the variable's type (" + + v.data_type.to_string() + ").", + v.line); + return; + } + } + + // Setter and getter + if (v.setter == StringName() && v.getter == StringName()) continue; + + bool found_getter = false; + bool found_setter = false; + for (int j = 0; j < p_class->functions.size(); j++) { + if (v.setter == p_class->functions[j]->name) { + found_setter = true; + FunctionNode *setter = p_class->functions[j]; + + if (setter->arguments.size() != 1) { + _set_error("Setter function needs to receive exactly 1 argument. See '" + setter->name + + "()' definition at line " + itos(setter->line) + ".", + v.line); + return; + } + if (!_is_type_compatible(v.data_type, setter->argument_types[0])) { + _set_error("Setter argument type (" + setter->argument_types[0].to_string() + + ") doesn't match the variable's type (" + v.data_type.to_string() + "). See '" + + setter->name + "()' definition at line " + itos(setter->line) + ".", + v.line); + return; + } + continue; + } + if (v.getter == p_class->functions[j]->name) { + found_getter = true; + FunctionNode *getter = p_class->functions[j]; + + if (getter->arguments.size() != 0) { + _set_error("Getter function can't receive arguments. See '" + getter->name + + "()' definition at line " + itos(getter->line) + ".", + v.line); + return; + } + if (!_is_type_compatible(v.data_type, getter->get_datatype())) { + _set_error("Getter return type (" + getter->get_datatype().to_string() + + ") doesn't match the variable's type (" + v.data_type.to_string() + + "). See '" + getter->name + "()' definition at line " + itos(getter->line) + ".", + v.line); + return; + } + } + if (found_getter && found_setter) break; + } + + if ((found_getter || v.getter == StringName()) && (found_setter || v.setter == StringName())) continue; + + // Check for static functions + for (int j = 0; j < p_class->static_functions.size(); j++) { + if (v.setter == p_class->static_functions[j]->name) { + FunctionNode *setter = p_class->static_functions[j]; + _set_error("Setter can't be a static function. See '" + setter->name + "()' definition at line " + itos(setter->line) + ".", v.line); + return; + } + if (v.getter == p_class->static_functions[j]->name) { + FunctionNode *getter = p_class->static_functions[j]; + _set_error("Getter can't be a static function. See '" + getter->name + "()' definition at line " + itos(getter->line) + ".", v.line); + return; + } + } + + if (!found_setter && v.setter != StringName()) { + _set_error("Setter function is not defined.", v.line); + return; + } + + if (!found_getter && v.getter != StringName()) { + _set_error("Getter function is not defined.", v.line); + return; + } + } + + // Inner classes + for (int i = 0; i < p_class->subclasses.size(); i++) { + current_class = p_class->subclasses[i]; + _check_class_level_types(current_class); + if (error_set) return; + current_class = p_class; + } +} + +void GDScriptParser::_check_function_types(FunctionNode *p_function) { + + p_function->return_type = _resolve_type(p_function->return_type, p_function->line); + + // Arguments + int defaults_ofs = p_function->arguments.size() - p_function->default_values.size(); + for (int i = 0; i < p_function->arguments.size(); i++) { + + // Resolve types + p_function->argument_types[i] = _resolve_type(p_function->argument_types[i], p_function->line); + + if (i >= defaults_ofs) { + if (p_function->default_values[i - defaults_ofs]->type != Node::TYPE_OPERATOR) { + _set_error("Parser bug: invalid argument default value.", p_function->line, p_function->column); + return; + } + + OperatorNode *op = static_cast<OperatorNode *>(p_function->default_values[i - defaults_ofs]); + + if (op->op != OperatorNode::OP_ASSIGN || op->arguments.size() != 2) { + _set_error("Parser bug: invalid argument default value operation.", p_function->line); + return; + } + + DataType def_type = _reduce_node_type(op->arguments[1]); + + if (!_is_type_compatible(p_function->argument_types[i], def_type, true)) { + String arg_name = p_function->arguments[i]; + _set_error("Value type (" + def_type.to_string() + ") doesn't match the type of argument '" + + arg_name + "' (" + p_function->arguments[i] + ")", + p_function->line); + } + } + } + + if (!(p_function->name == "_init")) { + // Signature for the initializer may vary + DataType return_type; + List<DataType> arg_types; + int default_arg_count = 0; + bool _static = false; + bool vararg = false; + + DataType base_type = current_class->base_type; + if (_get_function_signature(base_type, p_function->name, return_type, arg_types, default_arg_count, _static, vararg)) { + bool valid = _static == p_function->_static; + valid = valid && return_type == p_function->return_type; + valid = valid && p_function->default_values.size() >= default_arg_count; + valid = valid && arg_types.size() == p_function->arguments.size(); + int i = 0; + for (List<DataType>::Element *E = arg_types.front(); valid && E; E = E->next()) { + valid = valid && E->get() == p_function->argument_types[i++]; + } + + if (!valid) { + _set_error("Function signature doesn't match the parent.", p_function->line); + return; + } + } + } else { + if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) { + _set_error("Constructor cannot return a value.", p_function->line); + return; + } + } + + if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) { + if (!p_function->body->has_return) { + _set_error("Non-void function must return a value in all possible paths.", p_function->line); + return; + } + } + + if (p_function->has_yield) { + // yield() will make the function return a GDScriptFunctionState, so the type is ambiguous + p_function->return_type.has_type = false; + } +} + +void GDScriptParser::_check_class_blocks_types(ClassNode *p_class) { + + // Function blocks + for (int i = 0; i < p_class->static_functions.size(); i++) { + current_function = p_class->static_functions[i]; + current_block = current_function->body; + _mark_line_as_safe(current_function->line); + _check_block_types(current_block); + current_block = NULL; + current_function = NULL; + if (error_set) return; + } + + for (int i = 0; i < p_class->functions.size(); i++) { + current_function = p_class->functions[i]; + current_block = current_function->body; + _mark_line_as_safe(current_function->line); + _check_block_types(current_block); + current_block = NULL; + current_function = NULL; + if (error_set) return; + } + + // Inner classes + for (int i = 0; i < p_class->subclasses.size(); i++) { + current_class = p_class->subclasses[i]; + _check_class_blocks_types(current_class); + if (error_set) return; + current_class = p_class; + } +} + +void GDScriptParser::_check_block_types(BlockNode *p_block) { + + Node *last_var_assign = NULL; + + // Check each statement + for (List<Node *>::Element *E = p_block->statements.front(); E; E = E->next()) { + Node *statement = E->get(); + switch (statement->type) { + case Node::TYPE_NEWLINE: + case Node::TYPE_BREAKPOINT: + case Node::TYPE_ASSERT: { + // Nothing to do + } break; + case Node::TYPE_LOCAL_VAR: { + LocalVarNode *lv = static_cast<LocalVarNode *>(statement); + lv->datatype = _resolve_type(lv->datatype, lv->line); + _mark_line_as_safe(lv->line); + + if (lv->assign) { + DataType assign_type = _reduce_node_type(lv->assign); + if (!_is_type_compatible(lv->datatype, assign_type)) { + // Try supertype test + if (_is_type_compatible(assign_type, lv->datatype)) { + _mark_line_as_unsafe(lv->line); + } else { + // Try implict conversion + if (lv->datatype.kind != DataType::BUILTIN || !_is_type_compatible(lv->datatype, assign_type, true)) { + _set_error("Assigned value type (" + assign_type.to_string() + ") doesn't match the variable's type (" + + lv->datatype.to_string() + ").", + lv->line); + return; + } + // Replace assigment with implict conversion + BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>(); + convert->line = lv->line; + convert->function = GDScriptFunctions::TYPE_CONVERT; + + ConstantNode *tgt_type = alloc_node<ConstantNode>(); + tgt_type->line = lv->line; + tgt_type->value = (int)lv->datatype.builtin_type; + + OperatorNode *convert_call = alloc_node<OperatorNode>(); + convert_call->line = lv->line; + convert_call->op = OperatorNode::OP_CALL; + convert_call->arguments.push_back(convert); + convert_call->arguments.push_back(lv->assign); + convert_call->arguments.push_back(tgt_type); + + lv->assign = convert_call; + lv->assign_op->arguments[1] = convert_call; + } + } + if (lv->datatype.infer_type) { + if (!assign_type.has_type) { + _set_error("Assigned value does not have a set type, variable type cannot be inferred.", lv->line); + return; + } + lv->datatype = assign_type; + lv->datatype.is_constant = false; + } + if (lv->datatype.has_type && !assign_type.has_type) { + _mark_line_as_unsafe(lv->line); + } + } + last_var_assign = lv->assign; + + // TODO: Make a warning + /* + if (lv->assignments == 0) { + _set_error("Variable '" + String(lv->name) + "' is never assigned.", lv->line); + return; + } + */ + } break; + case Node::TYPE_OPERATOR: { + OperatorNode *op = static_cast<OperatorNode *>(statement); + + switch (op->op) { + case OperatorNode::OP_ASSIGN: + case OperatorNode::OP_ASSIGN_ADD: + case OperatorNode::OP_ASSIGN_SUB: + case OperatorNode::OP_ASSIGN_MUL: + case OperatorNode::OP_ASSIGN_DIV: + case OperatorNode::OP_ASSIGN_MOD: + case OperatorNode::OP_ASSIGN_SHIFT_LEFT: + case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: + case OperatorNode::OP_ASSIGN_BIT_AND: + case OperatorNode::OP_ASSIGN_BIT_OR: + case OperatorNode::OP_ASSIGN_BIT_XOR: { + if (op->arguments.size() < 2) { + _set_error("Parser bug: operation without enough arguments.", op->line, op->column); + return; + } + + if (op->arguments[1] == last_var_assign) { + // Assignment was already checked + break; + } + + _mark_line_as_safe(op->line); + + DataType lh_type = _reduce_node_type(op->arguments[0]); + + if (error_set) { + return; + } + + if (!lh_type.has_type) { + if (op->arguments[0]->type == Node::TYPE_OPERATOR) { + _mark_line_as_unsafe(op->line); + } + } else if (lh_type.is_constant) { + _set_error("Cannot assign a new value to a constant.", op->line); + return; + } + + DataType rh_type; + if (op->op != OperatorNode::OP_ASSIGN) { + // Validate operation + DataType arg_type = _reduce_node_type(op->arguments[1]); + if (!arg_type.has_type) { + _mark_line_as_unsafe(op->line); + break; + } + + Variant::Operator oper = _get_variant_operation(op->op); + bool valid = false; + rh_type = _get_operation_type(oper, lh_type, arg_type, valid); + + if (!valid) { + _set_error("Invalid operand types ('" + lh_type.to_string() + "' and '" + arg_type.to_string() + + "') to assignment operator '" + Variant::get_operator_name(oper) + "'.", + op->line); + return; + } + } else { + rh_type = _reduce_node_type(op->arguments[1]); + } + + if (!_is_type_compatible(lh_type, rh_type)) { + // Try supertype test + if (_is_type_compatible(rh_type, lh_type)) { + _mark_line_as_unsafe(op->line); + } else { + // Try implict conversion + if (lh_type.kind != DataType::BUILTIN || !_is_type_compatible(lh_type, rh_type, true)) { + _set_error("Assigned value type (" + rh_type.to_string() + ") doesn't match the variable's type (" + + lh_type.to_string() + ").", + op->line); + return; + } + // Replace assigment with implict conversion + BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>(); + convert->line = op->line; + convert->function = GDScriptFunctions::TYPE_CONVERT; + + ConstantNode *tgt_type = alloc_node<ConstantNode>(); + tgt_type->line = op->line; + tgt_type->value = (int)lh_type.builtin_type; + + OperatorNode *convert_call = alloc_node<OperatorNode>(); + convert_call->line = op->line; + convert_call->op = OperatorNode::OP_CALL; + convert_call->arguments.push_back(convert); + convert_call->arguments.push_back(op->arguments[1]); + convert_call->arguments.push_back(tgt_type); + + op->arguments[1] = convert_call; + } + } + if (!rh_type.has_type && (op->op != OperatorNode::OP_ASSIGN || lh_type.has_type || op->arguments[0]->type == Node::TYPE_OPERATOR)) { + _mark_line_as_unsafe(op->line); + } + } break; + case OperatorNode::OP_CALL: + case OperatorNode::OP_PARENT_CALL: { + _mark_line_as_safe(op->line); + _reduce_function_call_type(op); + if (error_set) return; + } break; + default: { + _mark_line_as_safe(op->line); + _reduce_node_type(op); // Test for safety anyway + // TODO: Make this a warning + /*_set_error("Standalone expression, nothing is done in this line.", statement->line); + return; */ + } + } + } break; + case Node::TYPE_CONTROL_FLOW: { + ControlFlowNode *cf = static_cast<ControlFlowNode *>(statement); + _mark_line_as_safe(cf->line); + + switch (cf->cf_type) { + case ControlFlowNode::CF_RETURN: { + DataType function_type = current_function->get_datatype(); + + DataType ret_type; + if (cf->arguments.size() > 0) { + ret_type = _reduce_node_type(cf->arguments[0]); + if (error_set) { + return; + } + } + + if (!function_type.has_type) break; + + if (function_type.kind == DataType::BUILTIN && function_type.builtin_type == Variant::NIL) { + // Return void, should not have arguments + if (cf->arguments.size() > 0) { + _set_error("Void function cannot return a value.", cf->line, cf->column); + return; + } + } else { + // Return something, cannot be empty + if (cf->arguments.size() == 0) { + _set_error("Non-void function must return a value.", cf->line, cf->column); + return; + } + + if (!_is_type_compatible(function_type, ret_type)) { + _set_error("Returned value type (" + ret_type.to_string() + ") doesn't match the function return type (" + + function_type.to_string() + ").", + cf->line, cf->column); + return; + } + } + } break; + case ControlFlowNode::CF_MATCH: { + MatchNode *match_node = cf->match; + _transform_match_statment(match_node); + } break; + default: { + if (cf->body_else) { + _mark_line_as_safe(cf->body_else->line); + } + for (int i = 0; i < cf->arguments.size(); i++) { + _reduce_node_type(cf->arguments[i]); + } + } break; + } + } break; + case Node::TYPE_CONSTANT: { + ConstantNode *cn = static_cast<ConstantNode *>(statement); + // Strings are fine since they can be multiline comments + if (cn->value.get_type() == Variant::STRING) { + break; + } + } // falthrough + default: { + _mark_line_as_safe(statement->line); + _reduce_node_type(statement); // Test for safety anyway + // TODO: Make this a warning + /* _set_error("Standalone expression, nothing is done in this line.", statement->line); + return; */ + } + } + } + + // Parse sub blocks + for (int i = 0; i < p_block->sub_blocks.size(); i++) { + current_block = p_block->sub_blocks[i]; + _check_block_types(current_block); + current_block = p_block; + if (error_set) return; + } +} + void GDScriptParser::_set_error(const String &p_error, int p_line, int p_column) { if (error_set) @@ -4467,10 +7547,39 @@ Error GDScriptParser::_parse(const String &p_base_path) { _set_error("Parse Error: " + tokenizer->get_token_error()); } + if (error_set && !for_completion) { + return ERR_PARSE_ERROR; + } + + _determine_inheritance(main_class); + + if (error_set) { + return ERR_PARSE_ERROR; + } + + current_class = main_class; + current_function = NULL; + current_block = NULL; +#ifdef DEBUG_ENABLED + if (for_completion) check_types = false; +#else + check_types = false; +#endif + + // Resolve all class-level stuff before getting into function blocks + _check_class_level_types(main_class); + if (error_set) { + return ERR_PARSE_ERROR; + } + // Resolve the function blocks + _check_class_blocks_types(main_class); + + if (error_set) { return ERR_PARSE_ERROR; } + return OK; } @@ -4488,7 +7597,7 @@ Error GDScriptParser::parse_bytecode(const Vector<uint8_t> &p_bytecode, const St return ret; } -Error GDScriptParser::parse(const String &p_code, const String &p_base_path, bool p_just_validate, const String &p_self_path, bool p_for_completion) { +Error GDScriptParser::parse(const String &p_code, const String &p_base_path, bool p_just_validate, const String &p_self_path, bool p_for_completion, Set<int> *r_safe_lines) { clear(); @@ -4498,6 +7607,9 @@ Error GDScriptParser::parse(const String &p_code, const String &p_base_path, boo validating = p_just_validate; for_completion = p_for_completion; +#ifdef DEBUG_ENABLED + safe_lines = r_safe_lines; +#endif // DEBUG_ENABLED tokenizer = tt; Error ret = _parse(p_base_path); memdelete(tt); @@ -4550,7 +7662,11 @@ void GDScriptParser::clear() { pending_newline = -1; parenthesis = 0; current_export.type = Variant::NIL; + check_types = true; error = ""; +#ifdef DEBUG_ENABLED + safe_lines = NULL; +#endif // DEBUG_ENABLED } GDScriptParser::CompletionType GDScriptParser::get_completion_type() { diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h index b88a59537c..48f256b4c6 100644 --- a/modules/gdscript/gdscript_parser.h +++ b/modules/gdscript/gdscript_parser.h @@ -37,8 +37,68 @@ #include "object.h" #include "script_language.h" +struct GDScriptDataType; + class GDScriptParser { public: + struct ClassNode; + + struct DataType { + enum { + BUILTIN, + NATIVE, + SCRIPT, + GDSCRIPT, + CLASS, + UNRESOLVED + } kind; + + bool has_type; + bool is_constant; + bool is_meta_type; // Whether the value can be used as a type + bool infer_type; + + Variant::Type builtin_type; + StringName native_type; + Ref<Script> script_type; + ClassNode *class_type; + + String to_string() const; + + bool operator==(const DataType &other) const { + if (!has_type || !other.has_type) { + return true; // Can be considered equal for parsing purpose + } + if (kind != other.kind) { + return false; + } + switch (kind) { + case BUILTIN: { + return builtin_type == other.builtin_type; + } break; + case NATIVE: { + return native_type == other.native_type; + } break; + case GDSCRIPT: + case SCRIPT: { + return script_type == other.script_type; + } break; + case CLASS: { + return class_type == other.class_type; + } break; + } + return false; + } + + DataType() : + has_type(false), + is_constant(false), + is_meta_type(false), + infer_type(false), + builtin_type(Variant::NIL), + class_type(NULL) {} + }; + struct Node { enum Type { @@ -55,6 +115,7 @@ public: TYPE_OPERATOR, TYPE_CONTROL_FLOW, TYPE_LOCAL_VAR, + TYPE_CAST, TYPE_ASSERT, TYPE_BREAKPOINT, TYPE_NEWLINE, @@ -65,11 +126,17 @@ public: int column; Type type; + virtual DataType get_datatype() const { return DataType(); } + virtual void set_datatype(const DataType &p_datatype) {} + virtual ~Node() {} }; struct FunctionNode; struct BlockNode; + struct ConstantNode; + struct LocalVarNode; + struct OperatorNode; struct ClassNode : public Node { @@ -78,6 +145,7 @@ public: bool extends_used; StringName extends_file; Vector<StringName> extends_class; + DataType base_type; struct Member { PropertyInfo _export; @@ -85,15 +153,17 @@ public: Variant default_value; #endif StringName identifier; + DataType data_type; StringName setter; StringName getter; int line; Node *expression; + OperatorNode *initial_assignment; MultiplayerAPI::RPCMode rpc_mode; }; struct Constant { - StringName identifier; Node *expression; + DataType type; }; struct Signal { @@ -103,7 +173,7 @@ public: Vector<ClassNode *> subclasses; Vector<Member> variables; - Vector<Constant> constant_expressions; + Map<StringName, Constant> constant_expressions; Vector<FunctionNode *> functions; Vector<FunctionNode *> static_functions; Vector<Signal> _signals; @@ -126,15 +196,22 @@ public: bool _static; MultiplayerAPI::RPCMode rpc_mode; + bool has_yield; StringName name; + DataType return_type; Vector<StringName> arguments; + Vector<DataType> argument_types; Vector<Node *> default_values; BlockNode *body; + virtual DataType get_datatype() const { return return_type; } + virtual void set_datatype(const DataType &p_datatype) { return_type = p_datatype; } + FunctionNode() { type = TYPE_FUNCTION; _static = false; rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; + has_yield = false; } }; @@ -142,10 +219,9 @@ public: ClassNode *parent_class; BlockNode *parent_block; - Map<StringName, int> locals; List<Node *> statements; - Vector<StringName> variables; - Vector<int> variable_lines; + Map<StringName, LocalVarNode *> variables; + bool has_return; Node *if_condition; //tiny hack to improve code completion on if () blocks @@ -158,6 +234,7 @@ public: end_line = -1; parent_block = NULL; parent_class = NULL; + has_return = false; } }; @@ -174,28 +251,53 @@ public: struct IdentifierNode : public Node { StringName name; - IdentifierNode() { type = TYPE_IDENTIFIER; } + BlockNode *declared_block; // Simplify lookup by checking if it is declared locally + DataType datatype; + virtual DataType get_datatype() const { return datatype; } + virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; } + IdentifierNode() { + type = TYPE_IDENTIFIER; + declared_block = NULL; + } }; struct LocalVarNode : public Node { StringName name; Node *assign; + OperatorNode *assign_op; + int assignments; + DataType datatype; + virtual DataType get_datatype() const { return datatype; } + virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; } LocalVarNode() { type = TYPE_LOCAL_VAR; assign = NULL; + assign_op = NULL; + assignments = 0; } }; struct ConstantNode : public Node { Variant value; + DataType datatype; + virtual DataType get_datatype() const { return datatype; } + virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; } ConstantNode() { type = TYPE_CONSTANT; } }; struct ArrayNode : public Node { Vector<Node *> elements; - ArrayNode() { type = TYPE_ARRAY; } + DataType datatype; + virtual DataType get_datatype() const { return datatype; } + virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; } + ArrayNode() { + type = TYPE_ARRAY; + datatype.has_type = true; + datatype.kind = DataType::BUILTIN; + datatype.builtin_type = Variant::ARRAY; + } }; struct DictionaryNode : public Node { @@ -207,7 +309,15 @@ public: }; Vector<Pair> elements; - DictionaryNode() { type = TYPE_DICTIONARY; } + DataType datatype; + virtual DataType get_datatype() const { return datatype; } + virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; } + DictionaryNode() { + type = TYPE_DICTIONARY; + datatype.has_type = true; + datatype.kind = DataType::BUILTIN; + datatype.builtin_type = Variant::DICTIONARY; + } }; struct SelfNode : public Node { @@ -229,10 +339,6 @@ public: OP_POS, OP_NOT, OP_BIT_INVERT, - OP_PREINC, - OP_PREDEC, - OP_INC, - OP_DEC, //binary operators (in precedence order) OP_IN, OP_EQUAL, @@ -273,6 +379,9 @@ public: Operator op; Vector<Node *> arguments; + DataType datatype; + virtual DataType get_datatype() const { return datatype; } + virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; } OperatorNode() { type = TYPE_OPERATOR; } }; @@ -340,6 +449,15 @@ public: } }; + struct CastNode : public Node { + Node *source_node; + DataType cast_type; + DataType return_type; + virtual DataType get_datatype() const { return return_type; } + virtual void set_datatype(const DataType &p_datatype) { return_type = p_datatype; } + CastNode() { type = TYPE_CAST; } + }; + struct AssertNode : public Node { Node *condition; AssertNode() { type = TYPE_ASSERT; } @@ -362,76 +480,6 @@ public: }; }; - /* - struct OperatorNode : public Node { - - DataType return_cache; - Operator op; - Vector<Node*> arguments; - virtual DataType get_datatype() const { return return_cache; } - - OperatorNode() { type=TYPE_OPERATOR; return_cache=TYPE_VOID; } - }; - - struct VariableNode : public Node { - - DataType datatype_cache; - StringName name; - virtual DataType get_datatype() const { return datatype_cache; } - - VariableNode() { type=TYPE_VARIABLE; datatype_cache=TYPE_VOID; } - }; - - struct ConstantNode : public Node { - - DataType datatype; - Variant value; - virtual DataType get_datatype() const { return datatype; } - - ConstantNode() { type=TYPE_CONSTANT; } - }; - - struct BlockNode : public Node { - - Map<StringName,DataType> variables; - List<Node*> statements; - BlockNode() { type=TYPE_BLOCK; } - }; - - struct ControlFlowNode : public Node { - - FlowOperation flow_op; - Vector<Node*> statements; - ControlFlowNode() { type=TYPE_CONTROL_FLOW; flow_op=FLOW_OP_IF;} - }; - - struct MemberNode : public Node { - - DataType datatype; - StringName name; - Node* owner; - virtual DataType get_datatype() const { return datatype; } - MemberNode() { type=TYPE_MEMBER; } - }; - - - struct ProgramNode : public Node { - - struct Function { - StringName name; - FunctionNode*function; - }; - - Map<StringName,DataType> builtin_variables; - Map<StringName,DataType> preexisting_variables; - - Vector<Function> functions; - BlockNode *body; - - ProgramNode() { type=TYPE_PROGRAM; } - }; -*/ - enum CompletionType { COMPLETION_NONE, COMPLETION_BUILT_IN_TYPE_CONSTANT, @@ -446,6 +494,8 @@ public: COMPLETION_VIRTUAL_FUNC, COMPLETION_YIELD, COMPLETION_ASSIGN, + COMPLETION_TYPE_HINT, + COMPLETION_TYPE_HINT_INDEX, }; private: @@ -463,6 +513,10 @@ private: String error; int error_line; int error_column; + bool check_types; +#ifdef DEBUG_ENABLED + Set<int> *safe_lines; +#endif // DEBUG_ENABLED int pending_newline; @@ -507,7 +561,7 @@ private: PatternNode *_parse_pattern(bool p_static); void _parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode *> &p_branches, bool p_static); - void _transform_match_statment(BlockNode *p_block, MatchNode *p_match_statement); + void _transform_match_statment(MatchNode *p_match_statement); void _generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings); void _parse_block(BlockNode *p_block, bool p_static); @@ -515,13 +569,43 @@ private: void _parse_class(ClassNode *p_class); bool _end_statement(); + void _determine_inheritance(ClassNode *p_class); + bool _parse_type(DataType &r_type, bool p_can_be_void = false); + DataType _resolve_type(const DataType &p_source, int p_line); + DataType _type_from_variant(const Variant &p_value) const; + DataType _type_from_property(const PropertyInfo &p_property, bool p_nil_is_variant = true) const; + DataType _type_from_gdtype(const GDScriptDataType &p_gdtype) const; + DataType _get_operation_type(const Variant::Operator p_op, const DataType &p_a, const DataType &p_b, bool &r_valid) const; + Variant::Operator _get_variant_operation(const OperatorNode::Operator &p_op) const; + bool _get_function_signature(DataType &p_base_type, const StringName &p_function, DataType &r_return_type, List<DataType> &r_arg_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) const; + bool _get_member_type(const DataType &p_base_type, const StringName &p_member, DataType &r_member_type) const; + bool _is_type_compatible(const DataType &p_container, const DataType &p_expression, bool p_allow_implicit_conversion = false) const; + + DataType _reduce_node_type(Node *p_node); + DataType _reduce_function_call_type(const OperatorNode *p_call); + DataType _reduce_identifier_type(const DataType *p_base_type, const StringName &p_identifier, int p_line); + void _check_class_level_types(ClassNode *p_class); + void _check_class_blocks_types(ClassNode *p_class); + void _check_function_types(FunctionNode *p_function); + void _check_block_types(BlockNode *p_block); + _FORCE_INLINE_ void _mark_line_as_safe(int p_line) const { +#ifdef DEBUG_ENABLED + if (safe_lines) safe_lines->insert(p_line); +#endif // DEBUG_ENABLED + } + _FORCE_INLINE_ void _mark_line_as_unsafe(int p_line) const { +#ifdef DEBUG_ENABLED + if (safe_lines) safe_lines->erase(p_line); +#endif // DEBUG_ENABLED + } + Error _parse(const String &p_base_path); public: String get_error() const; int get_error_line() const; int get_error_column() const; - Error parse(const String &p_code, const String &p_base_path = "", bool p_just_validate = false, const String &p_self_path = "", bool p_for_completion = false); + Error parse(const String &p_code, const String &p_base_path = "", bool p_just_validate = false, const String &p_self_path = "", bool p_for_completion = false, Set<int> *r_safe_lines = NULL); Error parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path = "", const String &p_self_path = ""); bool is_tool_script() const; diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp index 1d30871e3f..940bdcbc8d 100644 --- a/modules/gdscript/gdscript_tokenizer.cpp +++ b/modules/gdscript/gdscript_tokenizer.cpp @@ -101,6 +101,8 @@ const char *GDScriptTokenizer::token_names[TK_MAX] = { "setget", "const", "var", + "as", + "void", "enum", "preload", "assert", @@ -125,6 +127,7 @@ const char *GDScriptTokenizer::token_names[TK_MAX] = { "'.'", "'?'", "':'", + "'->'", "'$'", "'\\n'", "PI", @@ -197,6 +200,8 @@ static const _kws _keyword_list[] = { { GDScriptTokenizer::TK_PR_EXPORT, "export" }, { GDScriptTokenizer::TK_PR_SETGET, "setget" }, { GDScriptTokenizer::TK_PR_VAR, "var" }, + { GDScriptTokenizer::TK_PR_AS, "as" }, + { GDScriptTokenizer::TK_PR_VOID, "void" }, { GDScriptTokenizer::TK_PR_PRELOAD, "preload" }, { GDScriptTokenizer::TK_PR_ASSERT, "assert" }, { GDScriptTokenizer::TK_PR_YIELD, "yield" }, @@ -707,11 +712,9 @@ void GDScriptTokenizerText::_advance() { if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_SUB); INCPOS(1); - /* - } else if (GETCHAR(1)=='-') { - _make_token(TK_OP_MINUS_MINUS); + } else if (GETCHAR(1) == '>') { + _make_token(TK_FORWARD_ARROW); INCPOS(1); - */ } else { _make_token(TK_OP_SUB); } diff --git a/modules/gdscript/gdscript_tokenizer.h b/modules/gdscript/gdscript_tokenizer.h index c1f611fe73..5bd303224c 100644 --- a/modules/gdscript/gdscript_tokenizer.h +++ b/modules/gdscript/gdscript_tokenizer.h @@ -106,6 +106,8 @@ public: TK_PR_SETGET, TK_PR_CONST, TK_PR_VAR, + TK_PR_AS, + TK_PR_VOID, TK_PR_ENUM, TK_PR_PRELOAD, TK_PR_ASSERT, @@ -131,6 +133,7 @@ public: TK_QUESTION_MARK, TK_COLON, TK_DOLLAR, + TK_FORWARD_ARROW, TK_NEWLINE, TK_CONST_PI, TK_CONST_TAU, diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp index 0168be3a26..437c0d57fa 100644 --- a/modules/jpg/image_loader_jpegd.cpp +++ b/modules/jpg/image_loader_jpegd.cpp @@ -121,9 +121,7 @@ static Ref<Image> _jpegd_mem_loader_func(const uint8_t *p_png, int p_size) { Ref<Image> img; img.instance(); Error err = jpeg_load_image_from_buffer(img.ptr(), p_png, p_size); - if (err) - ERR_PRINT("Couldn't initialize ImageLoaderJPG with the given resource."); - + ERR_FAIL_COND_V(err, Ref<Image>()); return img; } diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index 8f9b2b3cac..996e73a4bb 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -121,7 +121,7 @@ void CSharpLanguage::init() { #ifdef TOOLS_ENABLED EditorNode::add_init_callback(&gdsharp_editor_init_callback); - GLOBAL_DEF("mono/export/include_scripts_content", true); + GLOBAL_DEF("mono/export/include_scripts_content", false); #endif } diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index df597ba776..7f9732c297 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -292,7 +292,7 @@ public: virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; virtual bool is_using_templates(); virtual void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script); - /* TODO */ virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const { return true; } + /* TODO */ virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, Set<int> *r_safe_lines = NULL) const { return true; } virtual String validate_path(const String &p_path) const; virtual Script *create_script() const; virtual bool has_named_classes() const; diff --git a/modules/mono/editor/godotsharp_editor.cpp b/modules/mono/editor/godotsharp_editor.cpp index 998da8bda3..faeb58e5a7 100644 --- a/modules/mono/editor/godotsharp_editor.cpp +++ b/modules/mono/editor/godotsharp_editor.cpp @@ -278,13 +278,11 @@ GodotSharpEditor::GodotSharpEditor(EditorNode *p_editor) { about_label->set_autowrap(true); String about_text = String("C# support in Godot Engine is a brand new feature and a work in progress.\n") + - "It is at the alpha stage and thus not suitable for use in production.\n\n" + - "As of Godot 3.0, C# support is not feature-complete and may crash in some situations. " + - "Bugs and usability issues will be addressed gradually over 3.0.x and 3.x releases, " + + "It is currently in an alpha stage and is not suitable for use in production.\n\n" + + "As of Godot 3.1, C# support is not feature-complete and may crash in some situations. " + + "Bugs and usability issues will be addressed gradually over future 3.x releases, " + "including compatibility breaking changes as new features are implemented for a better overall C# experience.\n\n" + - "The main missing feature is the ability to export games using C# assemblies - you will therefore be able to develop and run games in the editor, " + - "but not to share them as standalone binaries yet. This feature is of course high on the priority list and should be available as soon as possible.\n\n" + - "If you experience issues with this Mono build, please report them on Godot's issue tracker with details about your system, Mono version, IDE, etc.:\n\n" + + "If you experience issues with this Mono build, please report them on Godot's issue tracker with details about your system, Mono version, IDE, etc:\n\n" + " https://github.com/godotengine/godot/issues\n\n" + "Your critical feedback at this stage will play a great role in shaping the C# support in future releases, so thank you!"; about_label->set_text(about_text); diff --git a/modules/mono/glue/cs_files/Basis.cs b/modules/mono/glue/cs_files/Basis.cs index aa49a5e04f..c280d32c61 100644 --- a/modules/mono/glue/cs_files/Basis.cs +++ b/modules/mono/glue/cs_files/Basis.cs @@ -343,17 +343,17 @@ namespace Godot { var tr = this; - real_t temp = this[0, 1]; - this[0, 1] = this[1, 0]; - this[1, 0] = temp; + real_t temp = tr[0, 1]; + tr[0, 1] = tr[1, 0]; + tr[1, 0] = temp; - temp = this[0, 2]; - this[0, 2] = this[2, 0]; - this[2, 0] = temp; + temp = tr[0, 2]; + tr[0, 2] = tr[2, 0]; + tr[2, 0] = temp; - temp = this[1, 2]; - this[1, 2] = this[2, 1]; - this[2, 1] = temp; + temp = tr[1, 2]; + tr[1, 2] = tr[2, 1]; + tr[2, 1] = temp; return tr; } diff --git a/modules/mono/glue/cs_files/GD.cs b/modules/mono/glue/cs_files/GD.cs index ec1534cb9a..e2457ff98b 100644 --- a/modules/mono/glue/cs_files/GD.cs +++ b/modules/mono/glue/cs_files/GD.cs @@ -1,4 +1,9 @@ using System; +#if REAL_T_IS_DOUBLE +using real_t = System.Double; +#else +using real_t = System.Single; +#endif // TODO: Add comments describing what this class does. It is not obvious. @@ -16,22 +21,22 @@ namespace Godot return NativeCalls.godot_icall_Godot_convert(what, type); } - public static float Db2Linear(float db) + public static real_t Db2Linear(real_t db) { - return (float)Math.Exp(db * 0.11512925464970228420089957273422); + return (real_t)Math.Exp(db * 0.11512925464970228420089957273422); } - public static float Dectime(float value, float amount, float step) + public static real_t DecTime(real_t value, real_t amount, real_t step) { - float sgn = value < 0 ? -1.0f : 1.0f; - float val = Mathf.Abs(value); + real_t sgn = Mathf.Sign(value); + real_t val = Mathf.Abs(value); val -= amount * step; - if (val < 0.0f) - val = 0.0f; + if (val < 0) + val = 0; return val * sgn; } - public static FuncRef Funcref(Object instance, string funcname) + public static FuncRef FuncRef(Object instance, string funcname) { var ret = new FuncRef(); ret.SetInstance(instance); @@ -49,9 +54,9 @@ namespace Godot return NativeCalls.godot_icall_Godot_instance_from_id(instanceId); } - public static double Linear2Db(double linear) + public static real_t Linear2Db(real_t linear) { - return Math.Log(linear) * 8.6858896380650365530225783783321; + return (real_t)(Math.Log(linear) * 8.6858896380650365530225783783321); } public static Resource Load(string path) @@ -69,22 +74,22 @@ namespace Godot Print(System.Environment.StackTrace); } - public static void Printerr(params object[] what) + public static void PrintErr(params object[] what) { NativeCalls.godot_icall_Godot_printerr(what); } - public static void Printraw(params object[] what) + public static void PrintRaw(params object[] what) { NativeCalls.godot_icall_Godot_printraw(what); } - public static void Prints(params object[] what) + public static void PrintS(params object[] what) { NativeCalls.godot_icall_Godot_prints(what); } - public static void Printt(params object[] what) + public static void PrintT(params object[] what) { NativeCalls.godot_icall_Godot_printt(what); } @@ -183,7 +188,7 @@ namespace Godot return NativeCalls.godot_icall_Godot_var2str(var); } - public static WeakRef Weakref(Object obj) + public static WeakRef WeakRef(Object obj) { return NativeCalls.godot_icall_Godot_weakref(Object.GetPtr(obj)); } diff --git a/modules/mono/glue/cs_files/VERSION.txt b/modules/mono/glue/cs_files/VERSION.txt index b8626c4cff..7ed6ff82de 100755 --- a/modules/mono/glue/cs_files/VERSION.txt +++ b/modules/mono/glue/cs_files/VERSION.txt @@ -1 +1 @@ -4 +5 diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp index 9331092171..af9fea6681 100644 --- a/modules/visual_script/visual_script.cpp +++ b/modules/visual_script/visual_script.cpp @@ -2402,7 +2402,7 @@ void VisualScriptLanguage::make_template(const String &p_class_name, const Strin script->set_instance_base_type(p_base_class_name); } -bool VisualScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const { +bool VisualScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, Set<int> *r_safe_lines) const { return false; } diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h index aaa6dfea11..b163203a3a 100644 --- a/modules/visual_script/visual_script.h +++ b/modules/visual_script/visual_script.h @@ -563,7 +563,7 @@ public: virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; virtual bool is_using_templates(); virtual void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script); - virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL) const; + virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL, Set<int> *r_safe_lines = NULL) const; virtual Script *create_script() const; virtual bool has_named_classes() const; virtual bool supports_builtin_mode() const; diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp index cdf2d75e96..42b2c77777 100644 --- a/modules/webp/image_loader_webp.cpp +++ b/modules/webp/image_loader_webp.cpp @@ -116,64 +116,73 @@ static Ref<Image> _webp_lossy_unpack(const PoolVector<uint8_t> &p_buffer) { return img; } -Error ImageLoaderWEBP::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { +Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p_buffer_len) { - uint32_t size = f->get_len(); - PoolVector<uint8_t> src_image; - src_image.resize(size); + ERR_FAIL_NULL_V(p_image, ERR_INVALID_PARAMETER); WebPBitstreamFeatures features; - - PoolVector<uint8_t>::Write src_w = src_image.write(); - f->get_buffer(src_w.ptr(), size); - ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_EOF); - - if (WebPGetFeatures(src_w.ptr(), size, &features) != VP8_STATUS_OK) { - f->close(); - //ERR_EXPLAIN("Error decoding WEBP image: "+p_file); + if (WebPGetFeatures(p_buffer, p_buffer_len, &features) != VP8_STATUS_OK) { + // ERR_EXPLAIN("Error decoding WEBP image"); ERR_FAIL_V(ERR_FILE_CORRUPT); } - /* - print_line("width: " + itos(features.width)); - print_line("height: " + itos(features.height)); - print_line("alpha: " + itos(features.has_alpha)); - */ - - src_w = PoolVector<uint8_t>::Write(); - PoolVector<uint8_t> dst_image; int datasize = features.width * features.height * (features.has_alpha ? 4 : 3); dst_image.resize(datasize); - - PoolVector<uint8_t>::Read src_r = src_image.read(); PoolVector<uint8_t>::Write dst_w = dst_image.write(); bool errdec = false; if (features.has_alpha) { - errdec = WebPDecodeRGBAInto(src_r.ptr(), size, dst_w.ptr(), datasize, 4 * features.width) == NULL; + errdec = WebPDecodeRGBAInto(p_buffer, p_buffer_len, dst_w.ptr(), datasize, 4 * features.width) == NULL; } else { - errdec = WebPDecodeRGBInto(src_r.ptr(), size, dst_w.ptr(), datasize, 3 * features.width) == NULL; + errdec = WebPDecodeRGBInto(p_buffer, p_buffer_len, dst_w.ptr(), datasize, 3 * features.width) == NULL; } + dst_w = PoolVector<uint8_t>::Write(); - //ERR_EXPLAIN("Error decoding webp! - "+p_file); + //ERR_EXPLAIN("Error decoding webp!"); ERR_FAIL_COND_V(errdec, ERR_FILE_CORRUPT); - src_r = PoolVector<uint8_t>::Read(); - dst_w = PoolVector<uint8_t>::Write(); - p_image->create(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image); return OK; } +static Ref<Image> _webp_mem_loader_func(const uint8_t *p_png, int p_size) { + + Ref<Image> img; + img.instance(); + Error err = webp_load_image_from_buffer(img.ptr(), p_png, p_size); + ERR_FAIL_COND_V(err, Ref<Image>()); + return img; +} + +Error ImageLoaderWEBP::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { + + PoolVector<uint8_t> src_image; + int src_image_len = f->get_len(); + ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); + src_image.resize(src_image_len); + + PoolVector<uint8_t>::Write w = src_image.write(); + + f->get_buffer(&w[0], src_image_len); + + f->close(); + + Error err = webp_load_image_from_buffer(p_image.ptr(), w.ptr(), src_image_len); + + w = PoolVector<uint8_t>::Write(); + + return err; +} + void ImageLoaderWEBP::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("webp"); } ImageLoaderWEBP::ImageLoaderWEBP() { - + Image::_webp_mem_loader_func = _webp_mem_loader_func; Image::lossy_packer = _webp_lossy_pack; Image::lossy_unpacker = _webp_lossy_unpack; } diff --git a/platform/android/audio_driver_jandroid.cpp b/platform/android/audio_driver_jandroid.cpp index 3d80e76707..b9f1f1eab0 100644 --- a/platform/android/audio_driver_jandroid.cpp +++ b/platform/android/audio_driver_jandroid.cpp @@ -78,9 +78,9 @@ Error AudioDriverAndroid::init() { // __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device"); JNIEnv *env = ThreadAndroid::get_env(); - int mix_rate = GLOBAL_DEF("audio/mix_rate", 44100); + int mix_rate = GLOBAL_DEF_RST("audio/mix_rate", 44100); - int latency = GLOBAL_DEF("audio/output_latency", 25); + int latency = GLOBAL_DEF_RST("audio/output_latency", 25); unsigned int buffer_size = next_power_of_2(latency * mix_rate / 1000); if (OS::get_singleton()->is_stdout_verbose()) { print_line("audio buffer size: " + itos(buffer_size)); diff --git a/platform/android/detect.py b/platform/android/detect.py index 971368db17..ada36e2814 100644 --- a/platform/android/detect.py +++ b/platform/android/detect.py @@ -139,8 +139,13 @@ def configure(env): ## Build type if (env["target"].startswith("release")): - env.Append(LINKFLAGS=['-O2']) - env.Append(CPPFLAGS=['-O2', '-DNDEBUG', '-ffast-math', '-funsafe-math-optimizations', '-fomit-frame-pointer']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Append(LINKFLAGS=['-O2']) + env.Append(CPPFLAGS=['-O2', '-DNDEBUG', '-ffast-math', '-funsafe-math-optimizations', '-fomit-frame-pointer']) + else: #optimize for size + env.Append(CPPFLAGS=['-Os', '-DNDEBUG']) + env.Append(LINKFLAGS=['-Os']) + if (can_vectorize): env.Append(CPPFLAGS=['-ftree-vectorize']) if (env["target"] == "release_debug"): diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp index 9188f09f21..cc512263bc 100644 --- a/platform/android/os_android.cpp +++ b/platform/android/os_android.cpp @@ -124,6 +124,10 @@ void OS_Android::set_opengl_extensions(const char *p_gl_extensions) { gl_extensions = p_gl_extensions; } +int OS_Android::get_current_video_driver() const { + return video_driver_index; +} + Error OS_Android::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { bool use_gl3 = get_gl_version_code_func() >= 0x00030000; @@ -136,9 +140,11 @@ Error OS_Android::initialize(const VideoMode &p_desired, int p_video_driver, int if (use_gl2) { RasterizerGLES2::register_config(); RasterizerGLES2::make_current(); + video_driver_index = VIDEO_DRIVER_GLES2; } else { RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); + video_driver_index = VIDEO_DRIVER_GLES3; } visual_server = memnew(VisualServerRaster); diff --git a/platform/android/os_android.h b/platform/android/os_android.h index ac901d4832..c4220906a3 100644 --- a/platform/android/os_android.h +++ b/platform/android/os_android.h @@ -137,6 +137,7 @@ private: AlertFunc alert_func; //power_android *power_manager; + int video_driver_index; public: // functions used by main to initialize/deintialize the OS @@ -146,6 +147,8 @@ public: virtual int get_audio_driver_count() const; virtual const char *get_audio_driver_name(int p_driver) const; + virtual int get_current_video_driver() const; + virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); diff --git a/platform/haiku/audio_driver_media_kit.cpp b/platform/haiku/audio_driver_media_kit.cpp index 278a994c54..1f901c4919 100644 --- a/platform/haiku/audio_driver_media_kit.cpp +++ b/platform/haiku/audio_driver_media_kit.cpp @@ -43,7 +43,7 @@ Error AudioDriverMediaKit::init() { speaker_mode = SPEAKER_MODE_STEREO; channels = 2; - int latency = GLOBAL_DEF("audio/output_latency", 25); + int latency = GLOBAL_DEF_RST("audio/output_latency", 25); buffer_size = next_power_of_2(latency * mix_rate / 1000); samples_in = memnew_arr(int32_t, buffer_size * channels); diff --git a/platform/haiku/os_haiku.cpp b/platform/haiku/os_haiku.cpp index 97fab5ca0d..209cb5cec4 100644 --- a/platform/haiku/os_haiku.cpp +++ b/platform/haiku/os_haiku.cpp @@ -80,6 +80,10 @@ const char *OS_Haiku::get_video_driver_name(int p_driver) const { return "GLES3"; } +int OS_Haiku::get_current_video_driver() const { + return video_driver_index; +} + Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { main_loop = NULL; current_video_mode = p_desired; @@ -124,6 +128,8 @@ Error OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p } */ + video_driver_index = p_video_driver; + input = memnew(InputDefault); window->SetInput(input); diff --git a/platform/haiku/os_haiku.h b/platform/haiku/os_haiku.h index 615ae682ef..13d4420bde 100644 --- a/platform/haiku/os_haiku.h +++ b/platform/haiku/os_haiku.h @@ -51,6 +51,7 @@ private: Rasterizer *rasterizer; VisualServer *visual_server; VideoMode current_video_mode; + int video_driver_index; PowerHaiku *power_manager; #ifdef MEDIA_KIT_ENABLED @@ -66,6 +67,7 @@ private: protected: virtual int get_video_driver_count() const; virtual const char *get_video_driver_name(int p_driver) const; + virtual int get_current_video_driver() const; virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); virtual void finalize(); diff --git a/platform/iphone/detect.py b/platform/iphone/detect.py index 25674c2b47..b13a1e9643 100644 --- a/platform/iphone/detect.py +++ b/platform/iphone/detect.py @@ -47,8 +47,12 @@ def configure(env): if (env["target"].startswith("release")): env.Append(CPPFLAGS=['-DNDEBUG', '-DNS_BLOCK_ASSERTIONS=1']) - env.Append(CPPFLAGS=['-O2', '-ftree-vectorize', '-fomit-frame-pointer', '-ffast-math', '-funsafe-math-optimizations']) - env.Append(LINKFLAGS=['-O2']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Append(CPPFLAGS=['-O2', '-ftree-vectorize', '-fomit-frame-pointer', '-ffast-math', '-funsafe-math-optimizations']) + env.Append(LINKFLAGS=['-O2']) + else: #optimize for size + env.Append(CPPFLAGS=['-Os', '-ftree-vectorize']) + env.Append(LINKFLAGS=['-Os']) if env["target"] == "release_debug": env.Append(CPPFLAGS=['-DDEBUG_ENABLED']) diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp index 4caf4bd933..a4538a6673 100644 --- a/platform/iphone/os_iphone.cpp +++ b/platform/iphone/os_iphone.cpp @@ -93,8 +93,14 @@ void OSIPhone::initialize_core() { set_data_dir(data_dir); }; +int OSIPhone::get_current_video_driver() const { + return video_driver_index; +} + Error OSIPhone::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { + video_driver_index = p_video_driver; //this may be misleading + RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h index 8dc1ae6dc2..db2912ad93 100644 --- a/platform/iphone/os_iphone.h +++ b/platform/iphone/os_iphone.h @@ -77,6 +77,8 @@ private: virtual int get_video_driver_count() const; virtual const char *get_video_driver_name(int p_driver) const; + virtual int get_current_video_driver() const; + virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); @@ -112,6 +114,8 @@ private: int virtual_keyboard_height; + int video_driver_index; + public: bool iterate(); diff --git a/platform/javascript/os_javascript.cpp b/platform/javascript/os_javascript.cpp index c05ae03ec6..b9d586e233 100644 --- a/platform/javascript/os_javascript.cpp +++ b/platform/javascript/os_javascript.cpp @@ -643,6 +643,9 @@ const char *OS_JavaScript::get_audio_driver_name(int p_driver) const { } // Lifecycle +int OS_JavaScript::get_current_video_driver() const { + return video_driver_index; +} void OS_JavaScript::initialize_core() { @@ -669,6 +672,8 @@ Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, RasterizerGLES2::make_current(); break; } + + video_driver_index = p_video_driver; EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes); ERR_EXPLAIN("WebGL " + itos(attributes.majorVersion) + ".0 not available"); ERR_FAIL_COND_V(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS, ERR_UNAVAILABLE); diff --git a/platform/javascript/os_javascript.h b/platform/javascript/os_javascript.h index 503c92585b..915320fe39 100644 --- a/platform/javascript/os_javascript.h +++ b/platform/javascript/os_javascript.h @@ -81,7 +81,11 @@ class OS_JavaScript : public OS_Unix { static void file_access_close_callback(const String &p_file, int p_flags); + int video_driver_index; + protected: + virtual int get_current_video_driver() const; + virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); diff --git a/platform/osx/detect.py b/platform/osx/detect.py index 72b8aa99f8..1cc5c619fe 100644 --- a/platform/osx/detect.py +++ b/platform/osx/detect.py @@ -39,14 +39,21 @@ def configure(env): ## Build type if (env["target"] == "release"): - env.Prepend(CCFLAGS=['-O3', '-ffast-math', '-fomit-frame-pointer', '-ftree-vectorize', '-msse2']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Prepend(CCFLAGS=['-O3', '-ffast-math', '-fomit-frame-pointer', '-ftree-vectorize', '-msse2']) + else: #optimize for size + env.Prepend(CCFLAGS=['-Os','-ftree-vectorize', '-msse2']) + if (env["debug_symbols"] == "yes"): env.Prepend(CCFLAGS=['-g1']) if (env["debug_symbols"] == "full"): env.Prepend(CCFLAGS=['-g2']) elif (env["target"] == "release_debug"): - env.Prepend(CCFLAGS=['-O2', '-DDEBUG_ENABLED']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Prepend(CCFLAGS=['-O2', '-DDEBUG_ENABLED']) + else: #optimize for size + env.Prepend(CCFLAGS=['-Os', '-DDEBUG_ENABLED']) if (env["debug_symbols"] == "yes"): env.Prepend(CCFLAGS=['-g1']) if (env["debug_symbols"] == "full"): diff --git a/platform/osx/os_osx.h b/platform/osx/os_osx.h index 7bd5b16f36..3d14a6d4fb 100644 --- a/platform/osx/os_osx.h +++ b/platform/osx/os_osx.h @@ -137,6 +137,9 @@ public: void _update_window(); + int video_driver_index; + virtual int get_current_video_driver() const; + protected: virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm index 41a19ac992..282f5e2d1b 100644 --- a/platform/osx/os_osx.mm +++ b/platform/osx/os_osx.mm @@ -1176,6 +1176,10 @@ static void displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplay displays_arrangement_dirty = true; } +int OS_OSX::get_current_video_driver() const { + return video_driver_index; +} + Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { /*** OSX INITIALIZATION ***/ @@ -1272,6 +1276,8 @@ Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_a ADD_ATTR2(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core); } + video_driver_index = p_video_driver; + ADD_ATTR2(NSOpenGLPFAColorSize, colorBits); /* diff --git a/platform/server/os_server.cpp b/platform/server/os_server.cpp index 3b1be780d4..1c17780ad7 100644 --- a/platform/server/os_server.cpp +++ b/platform/server/os_server.cpp @@ -28,16 +28,17 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "os_server.h" + #include "drivers/dummy/audio_driver_dummy.h" #include "drivers/dummy/rasterizer_dummy.h" #include "drivers/dummy/texture_loader_dummy.h" #include "print_string.h" #include "servers/visual/visual_server_raster.h" -#include <stdio.h> -#include <stdlib.h> #include "main/main.h" +#include <stdio.h> +#include <stdlib.h> #include <unistd.h> int OS_Server::get_video_driver_count() const { @@ -58,6 +59,10 @@ const char *OS_Server::get_audio_driver_name(int p_driver) const { return "Dummy"; } +int OS_Server::get_current_video_driver() const { + return video_driver_index; +} + void OS_Server::initialize_core() { crash_handler.initialize(); @@ -73,6 +78,8 @@ Error OS_Server::initialize(const VideoMode &p_desired, int p_video_driver, int RasterizerDummy::make_current(); + video_driver_index = p_video_driver; // unused in server platform, but should still be initialized + visual_server = memnew(VisualServerRaster); visual_server->init(); diff --git a/platform/server/os_server.h b/platform/server/os_server.h index f1a880ecc2..07d70e5236 100644 --- a/platform/server/os_server.h +++ b/platform/server/os_server.h @@ -30,12 +30,12 @@ #ifndef OS_SERVER_H #define OS_SERVER_H -#include "../x11/crash_handler_x11.h" -#include "../x11/power_x11.h" #include "drivers/dummy/texture_loader_dummy.h" #include "drivers/rtaudio/audio_driver_rtaudio.h" #include "drivers/unix/os_unix.h" #include "main/input_default.h" +#include "platform/x11/crash_handler_x11.h" +#include "platform/x11/power_x11.h" #include "servers/audio_server.h" #include "servers/visual/rasterizer.h" #include "servers/visual_server.h" @@ -47,7 +47,6 @@ class OS_Server : public OS_Unix { - //Rasterizer *rasterizer; VisualServer *visual_server; VideoMode current_videomode; List<String> args; @@ -66,12 +65,14 @@ class OS_Server : public OS_Unix { CrashHandler crash_handler; + int video_driver_index; + ResourceFormatDummyTexture *resource_loader_dummy; protected: virtual int get_video_driver_count() const; virtual const char *get_video_driver_name(int p_driver) const; - + virtual int get_current_video_driver() const; virtual int get_audio_driver_count() const; virtual const char *get_audio_driver_name(int p_driver) const; diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp index 25326ae794..8549a44ce5 100644 --- a/platform/uwp/os_uwp.cpp +++ b/platform/uwp/os_uwp.cpp @@ -77,6 +77,10 @@ Size2 OSUWP::get_window_size() const { return size; } +int OSUWP::get_current_video_driver() const { + return video_driver_index; +} + void OSUWP::set_window_size(const Size2 p_size) { Windows::Foundation::Size new_size; @@ -237,6 +241,8 @@ Error OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_au } gl_context->set_use_vsync(vm.use_vsync); + video_driver_index = p_video_driver; + visual_server = memnew(VisualServerRaster); // FIXME: Reimplement threaded rendering? Or remove? /* diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h index 0f7f068652..3b48063fe9 100644 --- a/platform/uwp/os_uwp.h +++ b/platform/uwp/os_uwp.h @@ -99,6 +99,7 @@ private: Windows::UI::Core::CoreWindow ^ window; VideoMode video_mode; + int video_driver_index; MainLoop *main_loop; @@ -154,6 +155,7 @@ private: // functions used by main to initialize/deintialize the OS protected: virtual int get_video_driver_count() const; + virtual int get_current_video_driver() const; virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); diff --git a/platform/windows/detect.py b/platform/windows/detect.py index 05806d2fe8..cacb573236 100644 --- a/platform/windows/detect.py +++ b/platform/windows/detect.py @@ -166,12 +166,18 @@ def configure_msvc(env, manual_msvc_config): # Build type if (env["target"] == "release"): - env.Append(CCFLAGS=['/O2']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Append(CCFLAGS=['/O2']) + else: # optimize for size + env.Append(CCFLAGS=['/O1']) env.Append(LINKFLAGS=['/SUBSYSTEM:WINDOWS']) env.Append(LINKFLAGS=['/ENTRY:mainCRTStartup']) elif (env["target"] == "release_debug"): - env.Append(CCFLAGS=['/O2']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Append(CCFLAGS=['/O2']) + else: # optimize for size + env.Append(CCFLAGS=['/O1']) env.AppendUnique(CPPDEFINES = ['DEBUG_ENABLED']) env.Append(LINKFLAGS=['/SUBSYSTEM:CONSOLE']) @@ -247,10 +253,14 @@ def configure_mingw(env): if (env["target"] == "release"): env.Append(CCFLAGS=['-msse2']) - if (env["bits"] == "64"): - env.Append(CCFLAGS=['-O3']) - else: - env.Append(CCFLAGS=['-O2']) + if (env["optimize"] == "speed"): #optimize for speed (default) + if (env["bits"] == "64"): + env.Append(CCFLAGS=['-O3']) + else: + env.Append(CCFLAGS=['-O2']) + else: #optimize for size + env.Prepend(CCFLAGS=['-Os']) + env.Append(LINKFLAGS=['-Wl,--subsystem,windows']) @@ -265,7 +275,11 @@ def configure_mingw(env): env.Prepend(CCFLAGS=['-g1']) if (env["debug_symbols"] == "full"): env.Prepend(CCFLAGS=['-g2']) - + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Append(CCFLAGS=['-O2']) + else: #optimize for size + env.Prepend(CCFLAGS=['-Os']) + elif (env["target"] == "debug"): env.Append(CCFLAGS=['-g3', '-DDEBUG_ENABLED', '-DDEBUG_MEMORY_ENABLED']) diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index 05d16a5964..ac37e1246d 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -1012,6 +1012,10 @@ typedef enum _SHC_PROCESS_DPI_AWARENESS { SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2 } SHC_PROCESS_DPI_AWARENESS; +int OS_Windows::get_current_video_driver() const { + return video_driver_index; +} + Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { main_loop = NULL; @@ -1181,6 +1185,8 @@ Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int RasterizerGLES3::make_current(); } + video_driver_index = p_video_driver; // FIXME TODO - FIX IF DRIVER DETECTION HAPPENS AND GLES2 MUST BE USED + gl_context->set_use_vsync(video_mode.use_vsync); #endif diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index 19af63bae0..b99d3e3422 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -134,6 +134,7 @@ class OS_Windows : public OS { PowerWindows *power_manager; + int video_driver_index; #ifdef WASAPI_ENABLED AudioDriverWASAPI driver_wasapi; #endif @@ -153,6 +154,8 @@ class OS_Windows : public OS { // functions used by main to initialize/deintialize the OS protected: + virtual int get_current_video_driver() const; + virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); diff --git a/platform/x11/detect.py b/platform/x11/detect.py index 09e16ad078..feaa2e598f 100644 --- a/platform/x11/detect.py +++ b/platform/x11/detect.py @@ -62,6 +62,7 @@ def get_opts(): EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), BoolVariable('separate_debug_symbols', 'Create a separate file containing debugging symbols', False), BoolVariable('touch', 'Enable touch events', True), + BoolVariable('execinfo', 'Use libexecinfo on systems where glibc is not available', False), ] @@ -81,14 +82,22 @@ def configure(env): if (env["target"] == "release"): # -O3 -ffast-math is identical to -Ofast. We need to split it out so we can selectively disable # -ffast-math in code for which it generates wrong results. - env.Prepend(CCFLAGS=['-O3', '-ffast-math']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Prepend(CCFLAGS=['-O3', '-ffast-math']) + else: #optimize for size + env.Prepend(CCFLAGS=['-Os']) + if (env["debug_symbols"] == "yes"): env.Prepend(CCFLAGS=['-g1']) if (env["debug_symbols"] == "full"): env.Prepend(CCFLAGS=['-g2']) elif (env["target"] == "release_debug"): - env.Prepend(CCFLAGS=['-O2', '-ffast-math', '-DDEBUG_ENABLED']) + if (env["optimize"] == "speed"): #optimize for speed (default) + env.Prepend(CCFLAGS=['-O2', '-ffast-math', '-DDEBUG_ENABLED']) + else: #optimize for size + env.Prepend(CCFLAGS=['-Os', '-DDEBUG_ENABLED']) + if (env["debug_symbols"] == "yes"): env.Prepend(CCFLAGS=['-g1']) if (env["debug_symbols"] == "full"): @@ -276,6 +285,9 @@ def configure(env): env.Append(LIBS=['dl']) if (platform.system().find("BSD") >= 0): + env["execinfo"] = True + + if env["execinfo"]: env.Append(LIBS=['execinfo']) ## Cross-compilation diff --git a/platform/x11/os_x11.cpp b/platform/x11/os_x11.cpp index 2adc8bfb50..af0e02173f 100644 --- a/platform/x11/os_x11.cpp +++ b/platform/x11/os_x11.cpp @@ -84,6 +84,10 @@ void OS_X11::initialize_core() { OS_Unix::initialize_core(); } +int OS_X11::get_current_video_driver() const { + return video_driver_index; +} + Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { long im_event_mask = 0; @@ -285,6 +289,8 @@ Error OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_a } break; } + video_driver_index = p_video_driver; // FIXME TODO - FIX IF DRIVER DETECTION HAPPENS AND GLES2 MUST BE USED + context_gl->set_use_vsync(current_videomode.use_vsync); #endif @@ -1825,8 +1831,8 @@ void OS_X11::process_xevents() { GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime); } #ifdef TOUCH_ENABLED - // Grab touch devices to avoid OS gesture interference - /*for (int i = 0; i < touch.devices.size(); ++i) { + // Grab touch devices to avoid OS gesture interference + /*for (int i = 0; i < touch.devices.size(); ++i) { XIGrabDevice(x11_display, touch.devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &touch.event_mask); }*/ #endif diff --git a/platform/x11/os_x11.h b/platform/x11/os_x11.h index 8cab23fe63..b67bc824be 100644 --- a/platform/x11/os_x11.h +++ b/platform/x11/os_x11.h @@ -180,6 +180,7 @@ class OS_X11 : public OS_Unix { CrashHandler crash_handler; + int video_driver_index; int audio_driver_index; unsigned int capture_idle; bool maximized; @@ -195,6 +196,8 @@ class OS_X11 : public OS_Unix { Bool xrandr_ext_ok; protected: + virtual int get_current_video_driver() const; + virtual void initialize_core(); virtual Error initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver); virtual void finalize(); diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp index 8787a2c735..d5a61b0b6b 100644 --- a/scene/2d/physics_body_2d.cpp +++ b/scene/2d/physics_body_2d.cpp @@ -30,6 +30,7 @@ #include "physics_body_2d.h" +#include "core/core_string_names.h" #include "core/method_bind_ext.gen.inc" #include "engine.h" #include "math_funcs.h" @@ -186,28 +187,75 @@ real_t StaticBody2D::get_constant_angular_velocity() const { return constant_angular_velocity; } +#ifndef DISABLE_DEPRECATED void StaticBody2D::set_friction(real_t p_friction) { + ERR_EXPLAIN("The method set_friction has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + ERR_FAIL_COND(p_friction < 0 || p_friction > 1); - friction = p_friction; - Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, friction); + if (physics_material_override.is_null()) { + physics_material_override.instance(); + } + physics_material_override->set_friction(p_friction); + _reload_physics_characteristics(); } + real_t StaticBody2D::get_friction() const { - return friction; + ERR_EXPLAIN("The method get_friction has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + + if (physics_material_override.is_null()) { + return 1; + } + + return physics_material_override->get_friction(); } void StaticBody2D::set_bounce(real_t p_bounce) { + ERR_EXPLAIN("The method set_bounce has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1); - bounce = p_bounce; - Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, bounce); + if (physics_material_override.is_null()) { + physics_material_override.instance(); + } + physics_material_override->set_bounce(p_bounce); + _reload_physics_characteristics(); } + real_t StaticBody2D::get_bounce() const { - return bounce; + ERR_EXPLAIN("The method get_bounce has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + + if (physics_material_override.is_null()) { + return 0; + } + + return physics_material_override->get_bounce(); +} +#endif + +void StaticBody2D::set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override) { + if (physics_material_override.is_valid()) { + physics_material_override->disconnect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics"); + } + + physics_material_override = p_physics_material_override; + + if (physics_material_override.is_valid()) { + physics_material_override->connect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics"); + } + _reload_physics_characteristics(); +} + +Ref<PhysicsMaterial> StaticBody2D::get_physics_material_override() const { + return physics_material_override; } void StaticBody2D::_bind_methods() { @@ -222,23 +270,41 @@ void StaticBody2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &StaticBody2D::set_bounce); ClassDB::bind_method(D_METHOD("get_bounce"), &StaticBody2D::get_bounce); + ClassDB::bind_method(D_METHOD("set_physics_material_override", "physics_material_override"), &StaticBody2D::set_physics_material_override); + ClassDB::bind_method(D_METHOD("get_physics_material_override"), &StaticBody2D::get_physics_material_override); + + ClassDB::bind_method(D_METHOD("_reload_physics_characteristics"), &StaticBody2D::_reload_physics_characteristics); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "constant_linear_velocity"), "set_constant_linear_velocity", "get_constant_linear_velocity"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "constant_angular_velocity"), "set_constant_angular_velocity", "get_constant_angular_velocity"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "physics_material_override", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsMaterial"), "set_physics_material_override", "get_physics_material_override"); } StaticBody2D::StaticBody2D() : PhysicsBody2D(Physics2DServer::BODY_MODE_STATIC) { constant_angular_velocity = 0; - bounce = 0; - friction = 1; } StaticBody2D::~StaticBody2D() { } +void StaticBody2D::_reload_physics_characteristics() { + if (physics_material_override.is_null()) { + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, 0); + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, 1); + Physics2DServer::get_singleton()->body_set_combine_mode(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, Physics2DServer::COMBINE_MODE_INHERIT); + Physics2DServer::get_singleton()->body_set_combine_mode(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, Physics2DServer::COMBINE_MODE_INHERIT); + } else { + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, physics_material_override->get_bounce()); + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, physics_material_override->get_friction()); + Physics2DServer::get_singleton()->body_set_combine_mode(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, (Physics2DServer::CombineMode)physics_material_override->get_bounce_combine_mode()); + Physics2DServer::get_singleton()->body_set_combine_mode(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, (Physics2DServer::CombineMode)physics_material_override->get_friction_combine_mode()); + } +} + void RigidBody2D::_body_enter_tree(ObjectID p_id) { Object *obj = ObjectDB::get_instance(p_id); @@ -545,28 +611,72 @@ real_t RigidBody2D::get_weight() const { return mass * real_t(GLOBAL_DEF("physics/2d/default_gravity", 98)) / 10; } +#ifndef DISABLE_DEPRECATED void RigidBody2D::set_friction(real_t p_friction) { + ERR_EXPLAIN("The method set_friction has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED ERR_FAIL_COND(p_friction < 0 || p_friction > 1); - friction = p_friction; - Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, friction); + if (physics_material_override.is_null()) { + physics_material_override.instance(); + } + physics_material_override->set_friction(p_friction); + _reload_physics_characteristics(); } real_t RigidBody2D::get_friction() const { - return friction; + ERR_EXPLAIN("The method get_friction has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + + if (physics_material_override.is_null()) { + return 1; + } + + return physics_material_override->get_friction(); } void RigidBody2D::set_bounce(real_t p_bounce) { + ERR_EXPLAIN("The method set_bounce has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1); - bounce = p_bounce; - Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, bounce); + if (physics_material_override.is_null()) { + physics_material_override.instance(); + } + physics_material_override->set_bounce(p_bounce); + _reload_physics_characteristics(); } real_t RigidBody2D::get_bounce() const { - return bounce; + ERR_EXPLAIN("The method get_bounce has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + + if (physics_material_override.is_null()) { + return 0; + } + + return physics_material_override->get_bounce(); +} +#endif + +void RigidBody2D::set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override) { + if (physics_material_override.is_valid()) { + physics_material_override->disconnect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics"); + } + + physics_material_override = p_physics_material_override; + + if (physics_material_override.is_valid()) { + physics_material_override->connect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics"); + } + _reload_physics_characteristics(); +} + +Ref<PhysicsMaterial> RigidBody2D::get_physics_material_override() const { + return physics_material_override; } void RigidBody2D::set_gravity_scale(real_t p_gravity_scale) { @@ -843,6 +953,11 @@ void RigidBody2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &RigidBody2D::set_bounce); ClassDB::bind_method(D_METHOD("get_bounce"), &RigidBody2D::get_bounce); + ClassDB::bind_method(D_METHOD("set_physics_material_override", "physics_material_override"), &RigidBody2D::set_physics_material_override); + ClassDB::bind_method(D_METHOD("get_physics_material_override"), &RigidBody2D::get_physics_material_override); + + ClassDB::bind_method(D_METHOD("_reload_physics_characteristics"), &RigidBody2D::_reload_physics_characteristics); + ClassDB::bind_method(D_METHOD("set_gravity_scale", "gravity_scale"), &RigidBody2D::set_gravity_scale); ClassDB::bind_method(D_METHOD("get_gravity_scale"), &RigidBody2D::get_gravity_scale); @@ -903,6 +1018,7 @@ void RigidBody2D::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::REAL, "weight", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01", PROPERTY_USAGE_EDITOR), "set_weight", "get_weight"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "physics_material_override", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsMaterial"), "set_physics_material_override", "get_physics_material_override"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator"); ADD_PROPERTY(PropertyInfo(Variant::INT, "continuous_cd", PROPERTY_HINT_ENUM, "Disabled,Cast Ray,Cast Shape"), "set_continuous_collision_detection_mode", "get_continuous_collision_detection_mode"); @@ -941,9 +1057,7 @@ RigidBody2D::RigidBody2D() : mode = MODE_RIGID; - bounce = 0; mass = 1; - friction = 1; gravity_scale = 1; linear_damp = -1; @@ -969,6 +1083,20 @@ RigidBody2D::~RigidBody2D() { memdelete(contact_monitor); } +void RigidBody2D::_reload_physics_characteristics() { + if (physics_material_override.is_null()) { + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, 0); + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, 1); + Physics2DServer::get_singleton()->body_set_combine_mode(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, Physics2DServer::COMBINE_MODE_INHERIT); + Physics2DServer::get_singleton()->body_set_combine_mode(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, Physics2DServer::COMBINE_MODE_INHERIT); + } else { + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, physics_material_override->get_bounce()); + Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, physics_material_override->get_friction()); + Physics2DServer::get_singleton()->body_set_combine_mode(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, (Physics2DServer::CombineMode)physics_material_override->get_bounce_combine_mode()); + Physics2DServer::get_singleton()->body_set_combine_mode(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, (Physics2DServer::CombineMode)physics_material_override->get_friction_combine_mode()); + } +} + ////////////////////////// Ref<KinematicCollision2D> KinematicBody2D::_move(const Vector2 &p_motion, bool p_infinite_inertia, bool p_exclude_raycast_shapes, bool p_test_only) { diff --git a/scene/2d/physics_body_2d.h b/scene/2d/physics_body_2d.h index 7bda6ce817..bd100f6228 100644 --- a/scene/2d/physics_body_2d.h +++ b/scene/2d/physics_body_2d.h @@ -32,6 +32,7 @@ #define PHYSICS_BODY_2D_H #include "scene/2d/collision_object_2d.h" +#include "scene/resources/physics_material.h" #include "servers/physics_2d_server.h" #include "vset.h" @@ -79,18 +80,21 @@ class StaticBody2D : public PhysicsBody2D { Vector2 constant_linear_velocity; real_t constant_angular_velocity; - real_t bounce; - real_t friction; + Ref<PhysicsMaterial> physics_material_override; protected: static void _bind_methods(); public: +#ifndef DISABLE_DEPRECATED void set_friction(real_t p_friction); real_t get_friction() const; void set_bounce(real_t p_bounce); real_t get_bounce() const; +#endif + void set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override); + Ref<PhysicsMaterial> get_physics_material_override() const; void set_constant_linear_velocity(const Vector2 &p_vel); void set_constant_angular_velocity(real_t p_vel); @@ -100,6 +104,9 @@ public: StaticBody2D(); ~StaticBody2D(); + +private: + void _reload_physics_characteristics(); }; class RigidBody2D : public PhysicsBody2D { @@ -125,9 +132,8 @@ private: Physics2DDirectBodyState *state; Mode mode; - real_t bounce; real_t mass; - real_t friction; + Ref<PhysicsMaterial> physics_material_override; real_t gravity_scale; real_t linear_damp; real_t angular_damp; @@ -204,11 +210,16 @@ public: void set_weight(real_t p_weight); real_t get_weight() const; +#ifndef DISABLE_DEPRECATED void set_friction(real_t p_friction); real_t get_friction() const; void set_bounce(real_t p_bounce); real_t get_bounce() const; +#endif + + void set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override); + Ref<PhysicsMaterial> get_physics_material_override() const; void set_gravity_scale(real_t p_gravity_scale); real_t get_gravity_scale() const; @@ -261,6 +272,9 @@ public: RigidBody2D(); ~RigidBody2D(); + +private: + void _reload_physics_characteristics(); }; VARIANT_ENUM_CAST(RigidBody2D::Mode); diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp index 9a343ca0f0..72c3ed7425 100644 --- a/scene/2d/tile_map.cpp +++ b/scene/2d/tile_map.cpp @@ -62,7 +62,7 @@ void TileMap::_notification(int p_what) { pending_update = true; _recreate_quadrants(); - _update_dirty_quadrants(); + update_dirty_quadrants(); RID space = get_world_2d()->get_space(); _update_quadrant_transform(); _update_quadrant_space(space); @@ -245,7 +245,7 @@ void TileMap::_fix_cell_transform(Transform2D &xform, const Cell &p_cell, const xform.elements[2].y += offset.y; } -void TileMap::_update_dirty_quadrants() { +void TileMap::update_dirty_quadrants() { if (!pending_update) return; @@ -721,7 +721,7 @@ void TileMap::_make_quadrant_dirty(Map<PosKey, Quadrant>::Element *Q, bool updat return; if (update) { - _update_dirty_quadrants(); + call_deferred("update_dirty_quadrants"); } } @@ -1026,7 +1026,7 @@ void TileMap::_recreate_quadrants() { Q->get().cells.insert(E->key()); _make_quadrant_dirty(Q, false); } - _update_dirty_quadrants(); + update_dirty_quadrants(); } void TileMap::_clear_quadrants() { @@ -1630,7 +1630,7 @@ void TileMap::_bind_methods() { ClassDB::bind_method(D_METHOD("_clear_quadrants"), &TileMap::_clear_quadrants); ClassDB::bind_method(D_METHOD("_recreate_quadrants"), &TileMap::_recreate_quadrants); - ClassDB::bind_method(D_METHOD("_update_dirty_quadrants"), &TileMap::_update_dirty_quadrants); + ClassDB::bind_method(D_METHOD("update_dirty_quadrants"), &TileMap::update_dirty_quadrants); ClassDB::bind_method(D_METHOD("update_bitmask_area", "position"), &TileMap::update_bitmask_area); ClassDB::bind_method(D_METHOD("update_bitmask_region", "start", "end"), &TileMap::update_bitmask_region, DEFVAL(Vector2()), DEFVAL(Vector2())); diff --git a/scene/2d/tile_map.h b/scene/2d/tile_map.h index 79d79ca59f..c8aceac17d 100644 --- a/scene/2d/tile_map.h +++ b/scene/2d/tile_map.h @@ -191,7 +191,6 @@ private: void _make_quadrant_dirty(Map<PosKey, Quadrant>::Element *Q, bool update = true); void _recreate_quadrants(); void _clear_quadrants(); - void _update_dirty_quadrants(); void _update_quadrant_space(const RID &p_space); void _update_quadrant_transform(); void _recompute_rect_cache(); @@ -251,6 +250,8 @@ public: void update_cell_bitmask(int p_x, int p_y); void update_dirty_bitmask(); + void update_dirty_quadrants(); + void set_collision_layer(uint32_t p_layer); uint32_t get_collision_layer() const; diff --git a/scene/3d/collision_object.h b/scene/3d/collision_object.h index f31d65e411..f8ef04b78f 100644 --- a/scene/3d/collision_object.h +++ b/scene/3d/collision_object.h @@ -39,6 +39,7 @@ class CollisionObject : public Spatial { GDCLASS(CollisionObject, Spatial); bool area; + RID rid; struct ShapeData { diff --git a/scene/3d/collision_shape.h b/scene/3d/collision_shape.h index c9c91a5824..6ca8e80ea1 100644 --- a/scene/3d/collision_shape.h +++ b/scene/3d/collision_shape.h @@ -49,6 +49,7 @@ class CollisionShape : public Spatial { void resource_changed(RES res); bool disabled; +protected: void _create_debug_shape(); void _update_in_shape_owner(bool p_xform_only = false); diff --git a/scene/3d/cpu_particles.cpp b/scene/3d/cpu_particles.cpp index 2e897c1c73..c3b0196316 100644 --- a/scene/3d/cpu_particles.cpp +++ b/scene/3d/cpu_particles.cpp @@ -25,6 +25,8 @@ void CPUParticles::set_emitting(bool p_emitting) { update_mutex->lock(); #endif VS::get_singleton()->connect("frame_pre_draw", this, "_update_render_thread"); + VS::get_singleton()->instance_geometry_set_flag(get_instance(), VS::INSTANCE_FLAG_REDRAW_FRAME_IF_VISIBLE, true); + #ifndef NO_THREADS update_mutex->unlock(); #endif @@ -446,6 +448,8 @@ float rand_from_seed_m1_p1(uint32_t &seed) { void CPUParticles::_particles_process(float p_delta) { + p_delta *= speed_scale; + int pcount = particles.size(); PoolVector<Particle>::Write w = particles.write(); @@ -475,7 +479,7 @@ void CPUParticles::_particles_process(float p_delta) { if (!emitting && !p.active) continue; - float restart_time = float(i) / float(pcount); + float restart_time = (float(i) / float(pcount)) * lifetime; float local_delta = p_delta; if (randomness_ratio > 0.0) { @@ -643,7 +647,7 @@ void CPUParticles::_particles_process(float p_delta) { uint32_t alt_seed = p.seed; p.time += local_delta; - p.custom[1] += p.time / lifetime; + p.custom[1] = p.time / lifetime; float tex_linear_velocity = 0.0; if (curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) { @@ -979,6 +983,7 @@ void CPUParticles::_notification(int p_what) { update_mutex->lock(); #endif VS::get_singleton()->connect("frame_pre_draw", this, "_update_render_thread"); + VS::get_singleton()->instance_geometry_set_flag(get_instance(), VS::INSTANCE_FLAG_REDRAW_FRAME_IF_VISIBLE, true); #ifndef NO_THREADS update_mutex->unlock(); #endif @@ -992,6 +997,7 @@ void CPUParticles::_notification(int p_what) { update_mutex->lock(); #endif VS::get_singleton()->disconnect("frame_pre_draw", this, "_update_render_thread"); + VS::get_singleton()->instance_geometry_set_flag(get_instance(), VS::INSTANCE_FLAG_REDRAW_FRAME_IF_VISIBLE, false); #ifndef NO_THREADS update_mutex->unlock(); #endif @@ -1018,6 +1024,8 @@ void CPUParticles::_notification(int p_what) { update_mutex->lock(); #endif VS::get_singleton()->disconnect("frame_pre_draw", this, "_update_render_thread"); + VS::get_singleton()->instance_geometry_set_flag(get_instance(), VS::INSTANCE_FLAG_REDRAW_FRAME_IF_VISIBLE, false); + #ifndef NO_THREADS update_mutex->unlock(); #endif diff --git a/scene/3d/light.cpp b/scene/3d/light.cpp index dbedd47298..16164cf3bf 100644 --- a/scene/3d/light.cpp +++ b/scene/3d/light.cpp @@ -307,7 +307,6 @@ Light::Light(VisualServer::LightType p_type) { set_param(PARAM_SHADOW_NORMAL_BIAS, 0.0); set_param(PARAM_SHADOW_BIAS, 0.15); set_disable_scale(true); - print_line("disabling light scale?"); } Light::Light() { diff --git a/scene/3d/mesh_instance.cpp b/scene/3d/mesh_instance.cpp index e836a6154a..722eadb9ca 100644 --- a/scene/3d/mesh_instance.cpp +++ b/scene/3d/mesh_instance.cpp @@ -36,6 +36,7 @@ #include "scene/resources/material.h" #include "scene/scene_string_names.h" #include "skeleton.h" + bool MeshInstance::_set(const StringName &p_name, const Variant &p_value) { //this is not _too_ bad performance wise, really. it only arrives here if the property was not set anywhere else. diff --git a/scene/3d/mesh_instance.h b/scene/3d/mesh_instance.h index 5d359cd4d5..0dfec538f9 100644 --- a/scene/3d/mesh_instance.h +++ b/scene/3d/mesh_instance.h @@ -41,6 +41,7 @@ class MeshInstance : public GeometryInstance { GDCLASS(MeshInstance, GeometryInstance); +protected: Ref<Mesh> mesh; NodePath skeleton_path; diff --git a/scene/3d/physics_body.cpp b/scene/3d/physics_body.cpp index e851c8d643..7529a0e524 100644 --- a/scene/3d/physics_body.cpp +++ b/scene/3d/physics_body.cpp @@ -30,6 +30,7 @@ #include "physics_body.h" +#include "core/core_string_names.h" #include "engine.h" #include "method_bind_ext.gen.inc" #include "scene/scene_string_names.h" @@ -121,23 +122,23 @@ bool PhysicsBody::get_collision_layer_bit(int p_bit) const { void PhysicsBody::add_collision_exception_with(Node *p_node) { ERR_FAIL_NULL(p_node); - PhysicsBody *physics_body = Object::cast_to<PhysicsBody>(p_node); - if (!physics_body) { - ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type"); + CollisionObject *collision_object = Object::cast_to<CollisionObject>(p_node); + if (!collision_object) { + ERR_EXPLAIN("Collision exception only works between two CollisionObject"); } - ERR_FAIL_COND(!physics_body); - PhysicsServer::get_singleton()->body_add_collision_exception(get_rid(), physics_body->get_rid()); + ERR_FAIL_COND(!collision_object); + PhysicsServer::get_singleton()->body_add_collision_exception(get_rid(), collision_object->get_rid()); } void PhysicsBody::remove_collision_exception_with(Node *p_node) { ERR_FAIL_NULL(p_node); - PhysicsBody *physics_body = Object::cast_to<PhysicsBody>(p_node); - if (!physics_body) { - ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type"); + CollisionObject *collision_object = Object::cast_to<CollisionObject>(p_node); + if (!collision_object) { + ERR_EXPLAIN("Collision exception only works between two CollisionObject"); } - ERR_FAIL_COND(!physics_body); - PhysicsServer::get_singleton()->body_remove_collision_exception(get_rid(), physics_body->get_rid()); + ERR_FAIL_COND(!collision_object); + PhysicsServer::get_singleton()->body_remove_collision_exception(get_rid(), collision_object->get_rid()); } void PhysicsBody::_set_layers(uint32_t p_mask) { @@ -178,28 +179,75 @@ PhysicsBody::PhysicsBody(PhysicsServer::BodyMode p_mode) : collision_mask = 1; } +#ifndef DISABLE_DEPRECATED void StaticBody::set_friction(real_t p_friction) { + ERR_EXPLAIN("The method set_friction has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + ERR_FAIL_COND(p_friction < 0 || p_friction > 1); - friction = p_friction; - PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, friction); + if (physics_material_override.is_null()) { + physics_material_override.instance(); + } + physics_material_override->set_friction(p_friction); + _reload_physics_characteristics(); } + real_t StaticBody::get_friction() const { - return friction; + ERR_EXPLAIN("The method get_friction has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + + if (physics_material_override.is_null()) { + return 1; + } + + return physics_material_override->get_friction(); } void StaticBody::set_bounce(real_t p_bounce) { + ERR_EXPLAIN("The method set_bounce has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1); - bounce = p_bounce; - PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, bounce); + if (physics_material_override.is_null()) { + physics_material_override.instance(); + } + physics_material_override->set_bounce(p_bounce); + _reload_physics_characteristics(); } + real_t StaticBody::get_bounce() const { - return bounce; + ERR_EXPLAIN("The method get_bounce has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + + if (physics_material_override.is_null()) { + return 0; + } + + return physics_material_override->get_bounce(); +} +#endif + +void StaticBody::set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override) { + if (physics_material_override.is_valid()) { + physics_material_override->disconnect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics"); + } + + physics_material_override = p_physics_material_override; + + if (physics_material_override.is_valid()) { + physics_material_override->connect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics"); + } + _reload_physics_characteristics(); +} + +Ref<PhysicsMaterial> StaticBody::get_physics_material_override() const { + return physics_material_override; } void StaticBody::set_constant_linear_velocity(const Vector3 &p_vel) { @@ -236,24 +284,39 @@ void StaticBody::_bind_methods() { ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &StaticBody::set_bounce); ClassDB::bind_method(D_METHOD("get_bounce"), &StaticBody::get_bounce); + ClassDB::bind_method(D_METHOD("set_physics_material_override", "physics_material_override"), &StaticBody::set_physics_material_override); + ClassDB::bind_method(D_METHOD("get_physics_material_override"), &StaticBody::get_physics_material_override); + + ClassDB::bind_method(D_METHOD("_reload_physics_characteristics"), &StaticBody::_reload_physics_characteristics); + ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &PhysicsBody::add_collision_exception_with); ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &PhysicsBody::remove_collision_exception_with); ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce"); - + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "physics_material_override", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsMaterial"), "set_physics_material_override", "get_physics_material_override"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_linear_velocity"), "set_constant_linear_velocity", "get_constant_linear_velocity"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_angular_velocity"), "set_constant_angular_velocity", "get_constant_angular_velocity"); } StaticBody::StaticBody() : PhysicsBody(PhysicsServer::BODY_MODE_STATIC) { - - bounce = 0; - friction = 1; } -StaticBody::~StaticBody() { +StaticBody::~StaticBody() {} + +void StaticBody::_reload_physics_characteristics() { + if (physics_material_override.is_null()) { + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, 0); + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, 1); + PhysicsServer::get_singleton()->body_set_combine_mode(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, PhysicsServer::COMBINE_MODE_INHERIT); + PhysicsServer::get_singleton()->body_set_combine_mode(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, PhysicsServer::COMBINE_MODE_INHERIT); + } else { + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, physics_material_override->get_bounce()); + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, physics_material_override->get_friction()); + PhysicsServer::get_singleton()->body_set_combine_mode(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, physics_material_override->get_bounce_combine_mode()); + PhysicsServer::get_singleton()->body_set_combine_mode(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, physics_material_override->get_friction_combine_mode()); + } } void RigidBody::_body_enter_tree(ObjectID p_id) { @@ -550,28 +613,67 @@ real_t RigidBody::get_weight() const { return mass * real_t(GLOBAL_DEF("physics/3d/default_gravity", 9.8)); } +#ifndef DISABLE_DEPRECATED void RigidBody::set_friction(real_t p_friction) { + ERR_EXPLAIN("The method set_friction has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED ERR_FAIL_COND(p_friction < 0 || p_friction > 1); - friction = p_friction; - PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, friction); + if (physics_material_override.is_null()) { + physics_material_override.instance(); + } + physics_material_override->set_friction(p_friction); + _reload_physics_characteristics(); } real_t RigidBody::get_friction() const { - return friction; + ERR_EXPLAIN("The method get_friction has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + if (physics_material_override.is_null()) { + return 1; + } + + return physics_material_override->get_friction(); } void RigidBody::set_bounce(real_t p_bounce) { - + ERR_EXPLAIN("The method set_bounce has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1); - bounce = p_bounce; - PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, bounce); + if (physics_material_override.is_null()) { + physics_material_override.instance(); + } + physics_material_override->set_bounce(p_bounce); + _reload_physics_characteristics(); } real_t RigidBody::get_bounce() const { + ERR_EXPLAIN("The method get_bounce has been deprecated and will be removed in the future, use physical material") + WARN_DEPRECATED + if (physics_material_override.is_null()) { + return 0; + } - return bounce; + return physics_material_override->get_bounce(); +} +#endif + +void RigidBody::set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override) { + if (physics_material_override.is_valid()) { + physics_material_override->disconnect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics"); + } + + physics_material_override = p_physics_material_override; + + if (physics_material_override.is_valid()) { + physics_material_override->connect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics"); + } + _reload_physics_characteristics(); +} + +Ref<PhysicsMaterial> RigidBody::get_physics_material_override() const { + return physics_material_override; } void RigidBody::set_gravity_scale(real_t p_gravity_scale) { @@ -812,6 +914,11 @@ void RigidBody::_bind_methods() { ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &RigidBody::set_bounce); ClassDB::bind_method(D_METHOD("get_bounce"), &RigidBody::get_bounce); + ClassDB::bind_method(D_METHOD("set_physics_material_override", "physics_material_override"), &RigidBody::set_physics_material_override); + ClassDB::bind_method(D_METHOD("get_physics_material_override"), &RigidBody::get_physics_material_override); + + ClassDB::bind_method(D_METHOD("_reload_physics_characteristics"), &RigidBody::_reload_physics_characteristics); + ClassDB::bind_method(D_METHOD("set_linear_velocity", "linear_velocity"), &RigidBody::set_linear_velocity); ClassDB::bind_method(D_METHOD("get_linear_velocity"), &RigidBody::get_linear_velocity); @@ -865,6 +972,7 @@ void RigidBody::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::REAL, "weight", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01", PROPERTY_USAGE_EDITOR), "set_weight", "get_weight"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "physics_material_override", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsMaterial"), "set_physics_material_override", "get_physics_material_override"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "continuous_cd"), "set_use_continuous_collision_detection", "is_using_continuous_collision_detection"); @@ -903,9 +1011,7 @@ RigidBody::RigidBody() : mode = MODE_RIGID; - bounce = 0; mass = 1; - friction = 1; max_contacts_reported = 0; state = NULL; @@ -929,6 +1035,21 @@ RigidBody::~RigidBody() { if (contact_monitor) memdelete(contact_monitor); } + +void RigidBody::_reload_physics_characteristics() { + if (physics_material_override.is_null()) { + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, 0); + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, 1); + PhysicsServer::get_singleton()->body_set_combine_mode(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, PhysicsServer::COMBINE_MODE_INHERIT); + PhysicsServer::get_singleton()->body_set_combine_mode(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, PhysicsServer::COMBINE_MODE_INHERIT); + } else { + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, physics_material_override->get_bounce()); + PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, physics_material_override->get_friction()); + PhysicsServer::get_singleton()->body_set_combine_mode(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, physics_material_override->get_bounce_combine_mode()); + PhysicsServer::get_singleton()->body_set_combine_mode(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, physics_material_override->get_friction_combine_mode()); + } +} + ////////////////////////////////////////////////////// ////////////////////////// @@ -2228,6 +2349,7 @@ void PhysicalBone::set_bounce(real_t p_bounce) { bounce = p_bounce; PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, bounce); } + real_t PhysicalBone::get_bounce() const { return bounce; diff --git a/scene/3d/physics_body.h b/scene/3d/physics_body.h index 7236eba685..44d6502be1 100644 --- a/scene/3d/physics_body.h +++ b/scene/3d/physics_body.h @@ -32,6 +32,7 @@ #define PHYSICS_BODY__H #include "scene/3d/collision_object.h" +#include "scene/resources/physics_material.h" #include "servers/physics_server.h" #include "skeleton.h" #include "vset.h" @@ -81,18 +82,22 @@ class StaticBody : public PhysicsBody { Vector3 constant_linear_velocity; Vector3 constant_angular_velocity; - real_t bounce; - real_t friction; + Ref<PhysicsMaterial> physics_material_override; protected: static void _bind_methods(); public: +#ifndef DISABLE_DEPRECATED void set_friction(real_t p_friction); real_t get_friction() const; void set_bounce(real_t p_bounce); real_t get_bounce() const; +#endif + + void set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override); + Ref<PhysicsMaterial> get_physics_material_override() const; void set_constant_linear_velocity(const Vector3 &p_vel); void set_constant_angular_velocity(const Vector3 &p_vel); @@ -102,6 +107,9 @@ public: StaticBody(); ~StaticBody(); + +private: + void _reload_physics_characteristics(); }; class RigidBody : public PhysicsBody { @@ -121,9 +129,8 @@ protected: PhysicsDirectBodyState *state; Mode mode; - real_t bounce; real_t mass; - real_t friction; + Ref<PhysicsMaterial> physics_material_override; Vector3 linear_velocity; Vector3 angular_velocity; @@ -196,11 +203,16 @@ public: void set_weight(real_t p_weight); real_t get_weight() const; +#ifndef DISABLE_DEPRECATED void set_friction(real_t p_friction); real_t get_friction() const; void set_bounce(real_t p_bounce); real_t get_bounce() const; +#endif + + void set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override); + Ref<PhysicsMaterial> get_physics_material_override() const; void set_linear_velocity(const Vector3 &p_velocity); Vector3 get_linear_velocity() const; @@ -249,6 +261,9 @@ public: RigidBody(); ~RigidBody(); + +private: + void _reload_physics_characteristics(); }; VARIANT_ENUM_CAST(RigidBody::Mode); diff --git a/scene/3d/soft_body.cpp b/scene/3d/soft_body.cpp new file mode 100644 index 0000000000..8498dc34c0 --- /dev/null +++ b/scene/3d/soft_body.cpp @@ -0,0 +1,740 @@ +/*************************************************************************/ +/* soft_physics_body.cpp */ +/* Author: AndreaCatania */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* 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 "soft_body.h" +#include "os/os.h" +#include "scene/3d/collision_object.h" +#include "scene/3d/skeleton.h" +#include "servers/physics_server.h" + +SoftBodyVisualServerHandler::SoftBodyVisualServerHandler() {} + +void SoftBodyVisualServerHandler::prepare(RID p_mesh, int p_surface) { + clear(); + + ERR_FAIL_COND(!p_mesh.is_valid()); + + mesh = p_mesh; + surface = p_surface; + + const uint32_t surface_format = VS::get_singleton()->mesh_surface_get_format(mesh, surface); + const int surface_vertex_len = VS::get_singleton()->mesh_surface_get_array_len(mesh, p_surface); + const int surface_index_len = VS::get_singleton()->mesh_surface_get_array_index_len(mesh, p_surface); + uint32_t surface_offsets[VS::ARRAY_MAX]; + + buffer = VS::get_singleton()->mesh_surface_get_array(mesh, surface); + stride = VS::get_singleton()->mesh_surface_make_offsets_from_format(surface_format, surface_vertex_len, surface_index_len, surface_offsets); + offset_vertices = surface_offsets[VS::ARRAY_VERTEX]; + offset_normal = surface_offsets[VS::ARRAY_NORMAL]; +} + +void SoftBodyVisualServerHandler::clear() { + + if (mesh.is_valid()) { + buffer.resize(0); + } + + mesh = RID(); +} + +void SoftBodyVisualServerHandler::open() { + write_buffer = buffer.write(); +} + +void SoftBodyVisualServerHandler::close() { + write_buffer = PoolVector<uint8_t>::Write(); +} + +void SoftBodyVisualServerHandler::commit_changes() { + VS::get_singleton()->mesh_surface_update_region(mesh, surface, 0, buffer); +} + +void SoftBodyVisualServerHandler::set_vertex(int p_vertex_id, const void *p_vector3) { + copymem(&write_buffer[p_vertex_id * stride + offset_vertices], p_vector3, sizeof(float) * 3); +} + +void SoftBodyVisualServerHandler::set_normal(int p_vertex_id, const void *p_vector3) { + copymem(&write_buffer[p_vertex_id * stride + offset_normal], p_vector3, sizeof(float) * 3); +} + +void SoftBodyVisualServerHandler::set_aabb(const AABB &p_aabb) { + VS::get_singleton()->mesh_set_custom_aabb(mesh, p_aabb); +} + +SoftBody::PinnedPoint::PinnedPoint() : + point_index(-1), + spatial_attachment(NULL) { +} + +SoftBody::PinnedPoint::PinnedPoint(const PinnedPoint &obj_tocopy) { + point_index = obj_tocopy.point_index; + spatial_attachment_path = obj_tocopy.spatial_attachment_path; + spatial_attachment = obj_tocopy.spatial_attachment; + vertex_offset_transform = obj_tocopy.vertex_offset_transform; +} + +void SoftBody::_update_pickable() { + if (!is_inside_tree()) + return; + bool pickable = ray_pickable && is_inside_tree() && is_visible_in_tree(); + PhysicsServer::get_singleton()->soft_body_set_ray_pickable(physics_rid, pickable); +} + +bool SoftBody::_set(const StringName &p_name, const Variant &p_value) { + String name = p_name; + String which = name.get_slicec('/', 0); + + if ("pinned_points" == which) { + + return _set_property_pinned_points_indices(p_value); + + } else if ("attachments" == which) { + + int idx = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); + + return _set_property_pinned_points_attachment(idx, what, p_value); + } + + return false; +} + +bool SoftBody::_get(const StringName &p_name, Variant &r_ret) const { + String name = p_name; + String which = name.get_slicec('/', 0); + + if ("pinned_points" == which) { + Array arr_ret; + const int pinned_points_indices_size = pinned_points_indices.size(); + PoolVector<PinnedPoint>::Read r = pinned_points_indices.read(); + arr_ret.resize(pinned_points_indices_size); + + for (int i = 0; i < pinned_points_indices_size; ++i) { + arr_ret[i] = r[i].point_index; + } + + r_ret = arr_ret; + return true; + + } else if ("attachments" == which) { + + int idx = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); + + return _get_property_pinned_points(idx, what, r_ret); + } + + return false; +} + +void SoftBody::_get_property_list(List<PropertyInfo> *p_list) const { + + const int pinned_points_indices_size = pinned_points_indices.size(); + + p_list->push_back(PropertyInfo(Variant::POOL_INT_ARRAY, "pinned_points")); + + for (int i = 0; i < pinned_points_indices_size; ++i) { + p_list->push_back(PropertyInfo(Variant::INT, "attachments/" + itos(i) + "/point_index")); + p_list->push_back(PropertyInfo(Variant::NODE_PATH, "attachments/" + itos(i) + "/spatial_attachment_path")); + } +} + +bool SoftBody::_set_property_pinned_points_indices(const Array &p_indices) { + + const int p_indices_size = p_indices.size(); + + { // Remove the pined points on physics server that will be removed by resize + PoolVector<PinnedPoint>::Read r = pinned_points_indices.read(); + if (p_indices_size < pinned_points_indices.size()) { + for (int i = pinned_points_indices.size() - 1; i >= p_indices_size; --i) { + pin_point(r[i].point_index, false); + } + } + } + + pinned_points_indices.resize(p_indices_size); + + PoolVector<PinnedPoint>::Write w = pinned_points_indices.write(); + int point_index; + for (int i = 0; i < p_indices_size; ++i) { + point_index = p_indices.get(i); + if (w[i].point_index != point_index) { + if (-1 != w[i].point_index) + pin_point(w[i].point_index, false); + w[i].point_index = point_index; + pin_point(w[i].point_index, true); + } + } + return true; +} + +bool SoftBody::_set_property_pinned_points_attachment(int p_item, const String &p_what, const Variant &p_value) { + if (pinned_points_indices.size() <= p_item) { + return false; + } + + if ("spatial_attachment_path" == p_what) { + PoolVector<PinnedPoint>::Write w = pinned_points_indices.write(); + pin_point(w[p_item].point_index, true, p_value); + } else { + return false; + } + + return true; +} + +bool SoftBody::_get_property_pinned_points(int p_item, const String &p_what, Variant &r_ret) const { + if (pinned_points_indices.size() <= p_item) { + return false; + } + PoolVector<PinnedPoint>::Read r = pinned_points_indices.read(); + + if ("point_index" == p_what) { + r_ret = r[p_item].point_index; + } else if ("spatial_attachment_path" == p_what) { + r_ret = r[p_item].spatial_attachment_path; + } else { + return false; + } + + return true; +} + +void SoftBody::_changed_callback(Object *p_changed, const char *p_prop) { +#ifdef TOOLS_ENABLED + if (p_changed == this) { + update_configuration_warning(); + } +#endif +} + +void SoftBody::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_ENTER_WORLD: { + + if (Engine::get_singleton()->is_editor_hint()) + add_change_receptor(this); + + RID space = get_world()->get_space(); + PhysicsServer::get_singleton()->soft_body_set_space(physics_rid, space); + PhysicsServer::get_singleton()->soft_body_set_transform(physics_rid, get_global_transform()); + update_physics_server(); + } break; + case NOTIFICATION_READY: { + if (!parent_collision_ignore.is_empty()) + add_collision_exception_with(get_node(parent_collision_ignore)); + + } break; + case NOTIFICATION_TRANSFORM_CHANGED: { + + if (!simulation_started) { + PhysicsServer::get_singleton()->soft_body_set_transform(physics_rid, get_global_transform()); + + _update_cache_pin_points_datas(); + // Submit bone attachment + const int pinned_points_indices_size = pinned_points_indices.size(); + PoolVector<PinnedPoint>::Read r = pinned_points_indices.read(); + for (int i = 0; i < pinned_points_indices_size; ++i) { + if (!r[i].spatial_attachment) { + // Use soft body position to update the point position + PhysicsServer::get_singleton()->soft_body_move_point(physics_rid, r[i].point_index, (get_global_transform() * r[i].vertex_offset_transform).origin); + } else { + PhysicsServer::get_singleton()->soft_body_move_point(physics_rid, r[i].point_index, (r[i].spatial_attachment->get_global_transform() * r[i].vertex_offset_transform).origin); + } + } + } + } break; + case NOTIFICATION_VISIBILITY_CHANGED: { + + _update_pickable(); + + } break; + case NOTIFICATION_EXIT_WORLD: { + + PhysicsServer::get_singleton()->soft_body_set_space(physics_rid, RID()); + + } break; + } + +#ifdef TOOLS_ENABLED + + if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) { + if (Engine::get_singleton()->is_editor_hint()) { + update_configuration_warning(); + } + } + +#endif +} + +void SoftBody::_bind_methods() { + + ClassDB::bind_method(D_METHOD("_draw_soft_mesh"), &SoftBody::_draw_soft_mesh); + + ClassDB::bind_method(D_METHOD("set_collision_mask", "collision_mask"), &SoftBody::set_collision_mask); + ClassDB::bind_method(D_METHOD("get_collision_mask"), &SoftBody::get_collision_mask); + + ClassDB::bind_method(D_METHOD("set_collision_layer", "collision_layer"), &SoftBody::set_collision_layer); + ClassDB::bind_method(D_METHOD("get_collision_layer"), &SoftBody::get_collision_layer); + + ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &SoftBody::set_collision_mask_bit); + ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &SoftBody::get_collision_mask_bit); + + ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &SoftBody::set_collision_layer_bit); + ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &SoftBody::get_collision_layer_bit); + + ClassDB::bind_method(D_METHOD("set_parent_collision_ignore", "parent_collision_ignore"), &SoftBody::set_parent_collision_ignore); + ClassDB::bind_method(D_METHOD("get_parent_collision_ignore"), &SoftBody::get_parent_collision_ignore); + + ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &SoftBody::add_collision_exception_with); + ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &SoftBody::remove_collision_exception_with); + + ClassDB::bind_method(D_METHOD("set_simulation_precision", "simulation_precision"), &SoftBody::set_simulation_precision); + ClassDB::bind_method(D_METHOD("get_simulation_precision"), &SoftBody::get_simulation_precision); + + ClassDB::bind_method(D_METHOD("set_total_mass", "mass"), &SoftBody::set_total_mass); + ClassDB::bind_method(D_METHOD("get_total_mass"), &SoftBody::get_total_mass); + + ClassDB::bind_method(D_METHOD("set_linear_stiffness", "linear_stiffness"), &SoftBody::set_linear_stiffness); + ClassDB::bind_method(D_METHOD("get_linear_stiffness"), &SoftBody::get_linear_stiffness); + + ClassDB::bind_method(D_METHOD("set_areaAngular_stiffness", "areaAngular_stiffness"), &SoftBody::set_areaAngular_stiffness); + ClassDB::bind_method(D_METHOD("get_areaAngular_stiffness"), &SoftBody::get_areaAngular_stiffness); + + ClassDB::bind_method(D_METHOD("set_volume_stiffness", "volume_stiffness"), &SoftBody::set_volume_stiffness); + ClassDB::bind_method(D_METHOD("get_volume_stiffness"), &SoftBody::get_volume_stiffness); + + ClassDB::bind_method(D_METHOD("set_pressure_coefficient", "pressure_coefficient"), &SoftBody::set_pressure_coefficient); + ClassDB::bind_method(D_METHOD("get_pressure_coefficient"), &SoftBody::get_pressure_coefficient); + + ClassDB::bind_method(D_METHOD("set_pose_matching_coefficient", "pose_matching_coefficient"), &SoftBody::set_pose_matching_coefficient); + ClassDB::bind_method(D_METHOD("get_pose_matching_coefficient"), &SoftBody::get_pose_matching_coefficient); + + ClassDB::bind_method(D_METHOD("set_damping_coefficient", "damping_coefficient"), &SoftBody::set_damping_coefficient); + ClassDB::bind_method(D_METHOD("get_damping_coefficient"), &SoftBody::get_damping_coefficient); + + ClassDB::bind_method(D_METHOD("set_drag_coefficient", "drag_coefficient"), &SoftBody::set_drag_coefficient); + ClassDB::bind_method(D_METHOD("get_drag_coefficient"), &SoftBody::get_drag_coefficient); + + ClassDB::bind_method(D_METHOD("set_ray_pickable", "ray_pickable"), &SoftBody::set_ray_pickable); + ClassDB::bind_method(D_METHOD("is_ray_pickable"), &SoftBody::is_ray_pickable); + + ADD_GROUP("Collision", "collision_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask"); + + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "parent_collision_ignore", PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE, "Parent collision object"), "set_parent_collision_ignore", "get_parent_collision_ignore"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "simulation_precision", PROPERTY_HINT_RANGE, "1,100,1"), "set_simulation_precision", "get_simulation_precision"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "total_mass", PROPERTY_HINT_RANGE, "0.01,10000,1"), "set_total_mass", "get_total_mass"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "linear_stiffness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_linear_stiffness", "get_linear_stiffness"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "areaAngular_stiffness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_areaAngular_stiffness", "get_areaAngular_stiffness"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "volume_stiffness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_volume_stiffness", "get_volume_stiffness"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "pressure_coefficient"), "set_pressure_coefficient", "get_pressure_coefficient"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping_coefficient", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_damping_coefficient", "get_damping_coefficient"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "drag_coefficient", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_coefficient", "get_drag_coefficient"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "pose_matching_coefficient", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_pose_matching_coefficient", "get_pose_matching_coefficient"); +} + +String SoftBody::get_configuration_warning() const { + + String warning = MeshInstance::get_configuration_warning(); + + if (get_mesh().is_null()) { + if (!warning.empty()) + warning += "\n\n"; + + warning += TTR("This body will be ignored until you set a mesh"); + } + + Transform t = get_transform(); + if ((ABS(t.basis.get_axis(0).length() - 1.0) > 0.05 || ABS(t.basis.get_axis(1).length() - 1.0) > 0.05 || ABS(t.basis.get_axis(0).length() - 1.0) > 0.05)) { + if (!warning.empty()) + warning += "\n\n"; + + warning += TTR("Size changes to SoftBody will be overriden by the physics engine when running.\nChange the size in children collision shapes instead."); + } + + return warning; +} + +void SoftBody::_draw_soft_mesh() { + if (get_mesh().is_null()) + return; + + if (!visual_server_handler.is_ready()) { + + visual_server_handler.prepare(get_mesh()->get_rid(), 0); + + /// Necessary in order to render the mesh correctly (Soft body nodes are in global space) + simulation_started = true; + call_deferred("set_as_toplevel", true); + call_deferred("set_transform", Transform()); + } + + visual_server_handler.open(); + PhysicsServer::get_singleton()->soft_body_update_visual_server(physics_rid, &visual_server_handler); + visual_server_handler.close(); + + visual_server_handler.commit_changes(); +} + +void SoftBody::update_physics_server() { + + if (Engine::get_singleton()->is_editor_hint()) + return; + + if (get_mesh().is_valid()) { + + become_mesh_owner(); + PhysicsServer::get_singleton()->soft_body_set_mesh(physics_rid, get_mesh()); + VS::get_singleton()->connect("frame_pre_draw", this, "_draw_soft_mesh"); + } else { + + PhysicsServer::get_singleton()->soft_body_set_mesh(physics_rid, NULL); + VS::get_singleton()->disconnect("frame_pre_draw", this, "_draw_soft_mesh"); + } +} + +void SoftBody::become_mesh_owner() { + if (mesh.is_null()) + return; + + if (!mesh_owner) { + mesh_owner = true; + + ERR_FAIL_COND(!mesh->get_surface_count()); + + // Get current mesh array and create new mesh array with necessary flag for softbody + Array surface_arrays = mesh->surface_get_arrays(0); + Array surface_blend_arrays = mesh->surface_get_blend_shape_arrays(0); + uint32_t surface_format = mesh->surface_get_format(0); + + surface_format &= ~(Mesh::ARRAY_COMPRESS_VERTEX | Mesh::ARRAY_COMPRESS_NORMAL); + surface_format |= Mesh::ARRAY_FLAG_USE_DYNAMIC_UPDATE; + + Ref<ArrayMesh> soft_mesh; + soft_mesh.instance(); + soft_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, surface_arrays, surface_blend_arrays, surface_format); + + set_mesh(soft_mesh); + + Vector<Ref<Material> > copy_materials; + copy_materials.append_array(materials); + for (int i = copy_materials.size() - 1; 0 <= i; --i) { + set_surface_material(i, copy_materials[i]); + } + } +} + +void SoftBody::set_collision_mask(uint32_t p_mask) { + collision_mask = p_mask; + PhysicsServer::get_singleton()->soft_body_set_collision_mask(physics_rid, p_mask); +} + +uint32_t SoftBody::get_collision_mask() const { + return collision_mask; +} +void SoftBody::set_collision_layer(uint32_t p_layer) { + collision_layer = p_layer; + PhysicsServer::get_singleton()->soft_body_set_collision_layer(physics_rid, p_layer); +} + +uint32_t SoftBody::get_collision_layer() const { + return collision_layer; +} + +void SoftBody::set_collision_mask_bit(int p_bit, bool p_value) { + uint32_t mask = get_collision_mask(); + if (p_value) + mask |= 1 << p_bit; + else + mask &= ~(1 << p_bit); + set_collision_mask(mask); +} + +bool SoftBody::get_collision_mask_bit(int p_bit) const { + return get_collision_mask() & (1 << p_bit); +} + +void SoftBody::set_collision_layer_bit(int p_bit, bool p_value) { + uint32_t layer = get_collision_layer(); + if (p_value) + layer |= 1 << p_bit; + else + layer &= ~(1 << p_bit); + set_collision_layer(layer); +} + +bool SoftBody::get_collision_layer_bit(int p_bit) const { + return get_collision_layer() & (1 << p_bit); +} + +void SoftBody::set_parent_collision_ignore(const NodePath &p_parent_collision_ignore) { + parent_collision_ignore = p_parent_collision_ignore; +} + +const NodePath &SoftBody::get_parent_collision_ignore() const { + return parent_collision_ignore; +} + +void SoftBody::set_pinned_points_indices(PoolVector<SoftBody::PinnedPoint> p_pinned_points_indices) { + pinned_points_indices = p_pinned_points_indices; + PoolVector<PinnedPoint>::Read w = pinned_points_indices.read(); + for (int i = pinned_points_indices.size() - 1; 0 <= i; --i) { + pin_point(p_pinned_points_indices[i].point_index, true); + } +} + +PoolVector<SoftBody::PinnedPoint> SoftBody::get_pinned_points_indices() { + return pinned_points_indices; +} + +void SoftBody::add_collision_exception_with(Node *p_node) { + ERR_FAIL_NULL(p_node); + CollisionObject *collision_object = Object::cast_to<CollisionObject>(p_node); + if (!collision_object) { + ERR_EXPLAIN("Collision exception only works between two CollisionObject"); + } + ERR_FAIL_COND(!collision_object); + PhysicsServer::get_singleton()->soft_body_add_collision_exception(physics_rid, collision_object->get_rid()); +} + +void SoftBody::remove_collision_exception_with(Node *p_node) { + ERR_FAIL_NULL(p_node); + CollisionObject *collision_object = Object::cast_to<CollisionObject>(p_node); + if (!collision_object) { + ERR_EXPLAIN("Collision exception only works between two CollisionObject"); + } + ERR_FAIL_COND(!collision_object); + PhysicsServer::get_singleton()->soft_body_remove_collision_exception(physics_rid, collision_object->get_rid()); +} + +int SoftBody::get_simulation_precision() { + return PhysicsServer::get_singleton()->soft_body_get_simulation_precision(physics_rid); +} + +void SoftBody::set_simulation_precision(int p_simulation_precision) { + PhysicsServer::get_singleton()->soft_body_set_simulation_precision(physics_rid, p_simulation_precision); +} + +real_t SoftBody::get_total_mass() { + return PhysicsServer::get_singleton()->soft_body_get_total_mass(physics_rid); +} + +void SoftBody::set_total_mass(real_t p_total_mass) { + PhysicsServer::get_singleton()->soft_body_set_total_mass(physics_rid, p_total_mass); +} + +void SoftBody::set_linear_stiffness(real_t p_linear_stiffness) { + PhysicsServer::get_singleton()->soft_body_set_linear_stiffness(physics_rid, p_linear_stiffness); +} + +real_t SoftBody::get_linear_stiffness() { + return PhysicsServer::get_singleton()->soft_body_get_linear_stiffness(physics_rid); +} + +void SoftBody::set_areaAngular_stiffness(real_t p_areaAngular_stiffness) { + PhysicsServer::get_singleton()->soft_body_set_areaAngular_stiffness(physics_rid, p_areaAngular_stiffness); +} + +real_t SoftBody::get_areaAngular_stiffness() { + return PhysicsServer::get_singleton()->soft_body_get_areaAngular_stiffness(physics_rid); +} + +void SoftBody::set_volume_stiffness(real_t p_volume_stiffness) { + PhysicsServer::get_singleton()->soft_body_set_volume_stiffness(physics_rid, p_volume_stiffness); +} + +real_t SoftBody::get_volume_stiffness() { + return PhysicsServer::get_singleton()->soft_body_get_volume_stiffness(physics_rid); +} + +real_t SoftBody::get_pressure_coefficient() { + return PhysicsServer::get_singleton()->soft_body_get_pressure_coefficient(physics_rid); +} + +void SoftBody::set_pose_matching_coefficient(real_t p_pose_matching_coefficient) { + PhysicsServer::get_singleton()->soft_body_set_pose_matching_coefficient(physics_rid, p_pose_matching_coefficient); +} + +real_t SoftBody::get_pose_matching_coefficient() { + return PhysicsServer::get_singleton()->soft_body_get_pose_matching_coefficient(physics_rid); +} + +void SoftBody::set_pressure_coefficient(real_t p_pressure_coefficient) { + PhysicsServer::get_singleton()->soft_body_set_pressure_coefficient(physics_rid, p_pressure_coefficient); +} + +real_t SoftBody::get_damping_coefficient() { + return PhysicsServer::get_singleton()->soft_body_get_damping_coefficient(physics_rid); +} + +void SoftBody::set_damping_coefficient(real_t p_damping_coefficient) { + PhysicsServer::get_singleton()->soft_body_set_damping_coefficient(physics_rid, p_damping_coefficient); +} + +real_t SoftBody::get_drag_coefficient() { + return PhysicsServer::get_singleton()->soft_body_get_drag_coefficient(physics_rid); +} + +void SoftBody::set_drag_coefficient(real_t p_drag_coefficient) { + PhysicsServer::get_singleton()->soft_body_set_drag_coefficient(physics_rid, p_drag_coefficient); +} + +Vector3 SoftBody::get_point_transform(int p_point_index) { + return PhysicsServer::get_singleton()->soft_body_get_point_global_position(physics_rid, p_point_index); +} + +void SoftBody::pin_point_toggle(int p_point_index) { + pin_point(p_point_index, !(-1 != _has_pinned_point(p_point_index))); +} + +void SoftBody::pin_point(int p_point_index, bool pin, const NodePath &p_spatial_attachment_path) { + _pin_point_on_physics_server(p_point_index, pin); + if (pin) { + _add_pinned_point(p_point_index, p_spatial_attachment_path); + } else { + _remove_pinned_point(p_point_index); + } +} + +bool SoftBody::is_point_pinned(int p_point_index) const { + return -1 != _has_pinned_point(p_point_index); +} + +void SoftBody::set_ray_pickable(bool p_ray_pickable) { + + ray_pickable = p_ray_pickable; + _update_pickable(); +} + +bool SoftBody::is_ray_pickable() const { + + return ray_pickable; +} + +SoftBody::SoftBody() : + MeshInstance(), + physics_rid(PhysicsServer::get_singleton()->soft_body_create()), + mesh_owner(false), + collision_mask(1), + collision_layer(1), + simulation_started(false), + pinned_points_cache_dirty(true) { + + PhysicsServer::get_singleton()->body_attach_object_instance_id(physics_rid, get_instance_id()); +} + +SoftBody::~SoftBody() { +} + +void SoftBody::reset_softbody_pin() { + PhysicsServer::get_singleton()->soft_body_remove_all_pinned_points(physics_rid); + PoolVector<PinnedPoint>::Read pps = pinned_points_indices.read(); + for (int i = pinned_points_indices.size() - 1; 0 < i; --i) { + PhysicsServer::get_singleton()->soft_body_pin_point(physics_rid, pps[i].point_index, true); + } +} + +void SoftBody::_update_cache_pin_points_datas() { + if (pinned_points_cache_dirty) { + pinned_points_cache_dirty = false; + + PoolVector<PinnedPoint>::Write w = pinned_points_indices.write(); + for (int i = pinned_points_indices.size() - 1; 0 <= i; --i) { + + if (!w[i].spatial_attachment_path.is_empty()) { + w[i].spatial_attachment = Object::cast_to<Spatial>(get_node(w[i].spatial_attachment_path)); + if (w[i].spatial_attachment) { + + Transform point_global_transform(get_global_transform()); + point_global_transform.translate(PhysicsServer::get_singleton()->soft_body_get_point_offset(physics_rid, w[i].point_index)); + + // Local transform relative to spatial attachment node + w[i].vertex_offset_transform = w[i].spatial_attachment->get_global_transform().affine_inverse() * point_global_transform; + continue; + } else { + ERR_PRINTS("The node with path: " + String(w[i].spatial_attachment_path) + " was not found or is not a spatial node."); + } + } + // Local transform relative to Soft body + w[i].vertex_offset_transform.origin = PhysicsServer::get_singleton()->soft_body_get_point_offset(physics_rid, w[i].point_index); + w[i].vertex_offset_transform.basis = Basis(); + } + } +} + +void SoftBody::_pin_point_on_physics_server(int p_point_index, bool pin) { + PhysicsServer::get_singleton()->soft_body_pin_point(physics_rid, p_point_index, pin); +} + +void SoftBody::_add_pinned_point(int p_point_index, const NodePath &p_spatial_attachment_path) { + SoftBody::PinnedPoint *pinned_point; + if (-1 == _get_pinned_point(p_point_index, pinned_point)) { + // Create new + PinnedPoint pp; + pp.point_index = p_point_index; + pp.spatial_attachment_path = p_spatial_attachment_path; + pinned_points_indices.push_back(pp); + } else { + // Update + pinned_point->point_index = p_point_index; + pinned_point->spatial_attachment_path = p_spatial_attachment_path; + } +} + +void SoftBody::_remove_pinned_point(int p_point_index) { + const int id(_has_pinned_point(p_point_index)); + if (-1 != id) { + pinned_points_indices.remove(id); + } +} + +int SoftBody::_get_pinned_point(int p_point_index, SoftBody::PinnedPoint *&r_point) const { + const int id = _has_pinned_point(p_point_index); + if (-1 == id) { + r_point = NULL; + return -1; + } else { + r_point = const_cast<SoftBody::PinnedPoint *>(&pinned_points_indices.read()[id]); + return id; + } +} + +int SoftBody::_has_pinned_point(int p_point_index) const { + PoolVector<PinnedPoint>::Read r = pinned_points_indices.read(); + for (int i = pinned_points_indices.size() - 1; 0 <= i; --i) { + if (p_point_index == r[i].point_index) { + return i; + } + } + return -1; +} diff --git a/scene/3d/soft_body.h b/scene/3d/soft_body.h new file mode 100644 index 0000000000..f44f337698 --- /dev/null +++ b/scene/3d/soft_body.h @@ -0,0 +1,197 @@ +/*************************************************************************/ +/* soft_physics_body.h */ +/* Author: AndreaCatania */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* 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 SOFT_PHYSICS_BODY_H +#define SOFT_PHYSICS_BODY_H + +#include "scene/3d/mesh_instance.h" + +class SoftBody; + +class SoftBodyVisualServerHandler { + + friend class SoftBody; + + RID mesh; + int surface; + PoolVector<uint8_t> buffer; + uint32_t stride; + uint32_t offset_vertices; + uint32_t offset_normal; + + PoolVector<uint8_t>::Write write_buffer; + +private: + SoftBodyVisualServerHandler(); + bool is_ready() { return mesh.is_valid(); } + void prepare(RID p_mesh_rid, int p_surface); + void clear(); + void open(); + void close(); + void commit_changes(); + +public: + void set_vertex(int p_vertex_id, const void *p_vector3); + void set_normal(int p_vertex_id, const void *p_vector3); + void set_aabb(const AABB &p_aabb); +}; + +class SoftBody : public MeshInstance { + GDCLASS(SoftBody, MeshInstance); + +public: + struct PinnedPoint { + int point_index; + NodePath spatial_attachment_path; + Spatial *spatial_attachment; // Cache + /// This is the offset from the soft body to point or attachment to point + /// Depend if the spatial_attachment_node is NULL or not + Transform vertex_offset_transform; // Cache + + PinnedPoint(); + PinnedPoint(const PinnedPoint &obj_tocopy); + }; + +private: + SoftBodyVisualServerHandler visual_server_handler; + + RID physics_rid; + + bool mesh_owner; + uint32_t collision_mask; + uint32_t collision_layer; + NodePath parent_collision_ignore; + PoolVector<PinnedPoint> pinned_points_indices; + bool simulation_started; + bool pinned_points_cache_dirty; + + Ref<ArrayMesh> debug_mesh_cache; + class MeshInstance *debug_mesh; + + bool capture_input_on_drag; + bool ray_pickable; + + void _update_pickable(); + +protected: + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; + + bool _set_property_pinned_points_indices(const Array &p_indices); + bool _set_property_pinned_points_attachment(int p_item, const String &p_what, const Variant &p_value); + bool _get_property_pinned_points(int p_item, const String &p_what, Variant &r_ret) const; + + virtual void _changed_callback(Object *p_changed, const char *p_prop); + + void _notification(int p_what); + static void _bind_methods(); + + virtual String get_configuration_warning() const; + +protected: + void _draw_soft_mesh(); + +public: + void update_physics_server(); + void become_mesh_owner(); + + void set_collision_mask(uint32_t p_mask); + uint32_t get_collision_mask() const; + + void set_collision_layer(uint32_t p_layer); + uint32_t get_collision_layer() const; + + void set_collision_mask_bit(int p_bit, bool p_value); + bool get_collision_mask_bit(int p_bit) const; + + void set_collision_layer_bit(int p_bit, bool p_value); + bool get_collision_layer_bit(int p_bit) const; + + void set_parent_collision_ignore(const NodePath &p_parent_collision_ignore); + const NodePath &get_parent_collision_ignore() const; + + void set_pinned_points_indices(PoolVector<PinnedPoint> p_pinned_points_indices); + PoolVector<PinnedPoint> get_pinned_points_indices(); + + void set_simulation_precision(int p_simulation_precision); + int get_simulation_precision(); + + void set_total_mass(real_t p_total_mass); + real_t get_total_mass(); + + void set_linear_stiffness(real_t p_linear_stiffness); + real_t get_linear_stiffness(); + + void set_areaAngular_stiffness(real_t p_areaAngular_stiffness); + real_t get_areaAngular_stiffness(); + + void set_volume_stiffness(real_t p_volume_stiffness); + real_t get_volume_stiffness(); + + void set_pressure_coefficient(real_t p_pressure_coefficient); + real_t get_pressure_coefficient(); + + void set_pose_matching_coefficient(real_t p_pose_matching_coefficient); + real_t get_pose_matching_coefficient(); + + void set_damping_coefficient(real_t p_damping_coefficient); + real_t get_damping_coefficient(); + + void set_drag_coefficient(real_t p_drag_coefficient); + real_t get_drag_coefficient(); + + void add_collision_exception_with(Node *p_node); + void remove_collision_exception_with(Node *p_node); + + Vector3 get_point_transform(int p_point_index); + + void pin_point_toggle(int p_point_index); + void pin_point(int p_point_index, bool pin, const NodePath &p_spatial_attachment_path = NodePath()); + bool is_point_pinned(int p_point_index) const; + + void set_ray_pickable(bool p_ray_pickable); + bool is_ray_pickable() const; + + SoftBody(); + ~SoftBody(); + +private: + void reset_softbody_pin(); + void _update_cache_pin_points_datas(); + void _pin_point_on_physics_server(int p_point_index, bool pin); + void _add_pinned_point(int p_point_index, const NodePath &p_spatial_attachment_path); + void _remove_pinned_point(int p_point_index); + int _get_pinned_point(int p_point_index, PinnedPoint *&r_point) const; + int _has_pinned_point(int p_point_index) const; +}; + +#endif // SOFT_PHYSICS_BODY_H diff --git a/scene/3d/vehicle_body.cpp b/scene/3d/vehicle_body.cpp index 385956dc16..4b870ca54c 100644 --- a/scene/3d/vehicle_body.cpp +++ b/scene/3d/vehicle_body.cpp @@ -942,8 +942,6 @@ VehicleBody::VehicleBody() : engine_force = 0; brake = 0; - friction = 1; - state = NULL; ccd = false; diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp index eac2c8d0c1..111620dac1 100644 --- a/scene/animation/animation_player.cpp +++ b/scene/animation/animation_player.cpp @@ -549,6 +549,12 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, float int s = params.size(); ERR_CONTINUE(s > VARIANT_ARG_MAX); +#ifdef DEBUG_ENABLED + if (!nc->node->has_method(method)) { + ERR_PRINTS("Invalid method call '" + method + "'. '" + a->get_name() + "' at node '" + get_path() + "'."); + } +#endif + if (can_call) { MessageQueue::get_singleton()->push_call( nc->node, diff --git a/scene/gui/control.cpp b/scene/gui/control.cpp index 068af42260..17c349858f 100644 --- a/scene/gui/control.cpp +++ b/scene/gui/control.cpp @@ -2188,10 +2188,17 @@ void Control::set_tooltip(const String &p_tooltip) { data.tooltip = p_tooltip; } + String Control::get_tooltip(const Point2 &p_pos) const { return data.tooltip; } +Control *Control::make_custom_tooltip(const String &p_text) const { + if (get_script_instance()) { + return const_cast<Control *>(this)->call("_make_custom_tooltip", p_text); + } + return NULL; +} void Control::set_default_cursor_shape(CursorShape p_shape) { @@ -2820,6 +2827,7 @@ void Control::_bind_methods() { BIND_VMETHOD(MethodInfo(Variant::OBJECT, "get_drag_data", PropertyInfo(Variant::VECTOR2, "position"))); BIND_VMETHOD(MethodInfo(Variant::BOOL, "can_drop_data", PropertyInfo(Variant::VECTOR2, "position"), PropertyInfo(Variant::NIL, "data"))); BIND_VMETHOD(MethodInfo("drop_data", PropertyInfo(Variant::VECTOR2, "position"), PropertyInfo(Variant::NIL, "data"))); + BIND_VMETHOD(MethodInfo(Variant::OBJECT, "_make_custom_tooltip", PropertyInfo(Variant::STRING, "for_text"))); ADD_GROUP("Anchor", "anchor_"); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "anchor_left", PROPERTY_HINT_RANGE, "0,1,0.01"), "_set_anchor", "get_anchor", MARGIN_LEFT); diff --git a/scene/gui/control.h b/scene/gui/control.h index fa5274d854..94231867d7 100644 --- a/scene/gui/control.h +++ b/scene/gui/control.h @@ -454,6 +454,7 @@ public: void set_tooltip(const String &p_tooltip); virtual String get_tooltip(const Point2 &p_pos) const; + virtual Control *make_custom_tooltip(const String &p_text) const; /* CURSOR */ diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp index ce2e3538da..857ae8ff4c 100644 --- a/scene/gui/rich_text_label.cpp +++ b/scene/gui/rich_text_label.cpp @@ -1253,6 +1253,9 @@ void RichTextLabel::_validate_line_caches(ItemFrame *p_frame) { //validate invalid lines Size2 size = get_size(); + if (fixed_width != -1) { + size.width = fixed_width; + } Rect2 text_rect = _get_text_rect(); Color font_color_shadow = get_color("font_color_shadow"); bool use_outline = get_constant("shadow_as_outline"); @@ -2245,6 +2248,21 @@ int RichTextLabel::get_total_character_count() const { return tc; } +void RichTextLabel::set_fixed_size_to_width(int p_width) { + fixed_width = p_width; + minimum_size_changed(); +} + +Size2 RichTextLabel::get_minimum_size() const { + + if (fixed_width != -1) { + const_cast<RichTextLabel *>(this)->_validate_line_caches(main); + return Size2(fixed_width, const_cast<RichTextLabel *>(this)->get_content_height()); + } + + return Size2(); +} + RichTextLabel::RichTextLabel() { main = memnew(ItemFrame); @@ -2287,6 +2305,7 @@ RichTextLabel::RichTextLabel() { percent_visible = 1; visible_line_count = 0; + fixed_width = -1; set_clip_contents(true); } diff --git a/scene/gui/rich_text_label.h b/scene/gui/rich_text_label.h index af368af46a..06e9b8efe3 100644 --- a/scene/gui/rich_text_label.h +++ b/scene/gui/rich_text_label.h @@ -293,6 +293,8 @@ private: void _update_all_lines(); + int fixed_width; + protected: void _notification(int p_what); @@ -368,6 +370,9 @@ public: void set_percent_visible(float p_percent); float get_percent_visible() const; + void set_fixed_size_to_width(int p_width); + virtual Size2 get_minimum_size() const; + RichTextLabel(); ~RichTextLabel(); }; diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp index 218b5060a1..90cb475a7b 100644 --- a/scene/gui/text_edit.cpp +++ b/scene/gui/text_edit.cpp @@ -290,6 +290,7 @@ void TextEdit::Text::insert(int p_at, const String &p_text) { Line line; line.marked = false; + line.safe = false; line.breakpoint = false; line.hidden = false; line.width_cache = -1; @@ -972,7 +973,7 @@ void TextEdit::_notification(int p_what) { fc = line_num_padding + fc; } - cache.font->draw(ci, Point2(cache.style_normal->get_margin(MARGIN_LEFT) + cache.breakpoint_gutter_width + ofs_x, yofs + cache.font->get_ascent()), fc, cache.line_number_color); + cache.font->draw(ci, Point2(cache.style_normal->get_margin(MARGIN_LEFT) + cache.breakpoint_gutter_width + ofs_x, yofs + cache.font->get_ascent()), fc, text.is_safe(line) ? cache.safe_line_number_color : cache.line_number_color); } } @@ -4314,6 +4315,7 @@ void TextEdit::_update_caches() { cache.caret_color = get_color("caret_color"); cache.caret_background_color = get_color("caret_background_color"); cache.line_number_color = get_color("line_number_color"); + cache.safe_line_number_color = get_color("safe_line_number_color"); cache.font_color = get_color("font_color"); cache.font_selected_color = get_color("font_selected_color"); cache.keyword_color = get_color("keyword_color"); @@ -4885,6 +4887,17 @@ void TextEdit::set_line_as_marked(int p_line, bool p_marked) { update(); } +void TextEdit::set_line_as_safe(int p_line, bool p_safe) { + ERR_FAIL_INDEX(p_line, text.size()); + text.set_safe(p_line, p_safe); + update(); +} + +bool TextEdit::is_line_set_as_safe(int p_line) const { + ERR_FAIL_INDEX_V(p_line, text.size(), false); + return text.is_safe(p_line); +} + bool TextEdit::is_line_set_as_breakpoint(int p_line) const { ERR_FAIL_INDEX_V(p_line, text.size(), false); diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h index 586f4c8e93..34d69bb508 100644 --- a/scene/gui/text_edit.h +++ b/scene/gui/text_edit.h @@ -76,6 +76,7 @@ public: bool marked : 1; bool breakpoint : 1; bool hidden : 1; + bool safe : 1; int wrap_amount_cache : 24; Map<int, ColorRegionInfo> region_info; String data; @@ -106,6 +107,8 @@ public: bool is_breakpoint(int p_line) const { return text[p_line].breakpoint; } void set_hidden(int p_line, bool p_hidden) { text[p_line].hidden = p_hidden; } bool is_hidden(int p_line) const { return text[p_line].hidden; } + void set_safe(int p_line, bool p_safe) { text[p_line].safe = p_safe; } + bool is_safe(int p_line) const { return text[p_line].safe; } void insert(int p_at, const String &p_text); void remove(int p_at); int size() const { return text.size(); } @@ -165,6 +168,7 @@ private: Color caret_color; Color caret_background_color; Color line_number_color; + Color safe_line_number_color; Color font_color; Color font_selected_color; Color keyword_color; @@ -472,6 +476,8 @@ public: void set_line_as_marked(int p_line, bool p_marked); void set_line_as_breakpoint(int p_line, bool p_breakpoint); bool is_line_set_as_breakpoint(int p_line) const; + void set_line_as_safe(int p_line, bool p_safe); + bool is_line_set_as_safe(int p_line) const; void get_breakpoints(List<int> *p_breakpoints) const; Array get_breakpoints_array() const; void remove_breakpoints(); diff --git a/scene/main/node.cpp b/scene/main/node.cpp index e1333bcae2..b7b26d1c55 100644 --- a/scene/main/node.cpp +++ b/scene/main/node.cpp @@ -809,6 +809,22 @@ bool Node::is_processing_internal() const { return data.idle_process_internal; } +void Node::set_process_priority(int p_priority) { + data.process_priority = p_priority; + + if (is_processing()) + data.tree->make_group_changed("idle_process"); + + if (is_processing_internal()) + data.tree->make_group_changed("idle_process_internal"); + + if (is_physics_processing()) + data.tree->make_group_changed("physics_process"); + + if (is_physics_processing_internal()) + data.tree->make_group_changed("physics_process_internal"); +} + void Node::set_process_input(bool p_enable) { if (p_enable == data.input) @@ -1388,6 +1404,11 @@ bool Node::is_greater_than(const Node *p_node) const { return res; } +bool Node::has_priority_higher_than(const Node *p_node) const { + ERR_FAIL_NULL_V(p_node, false); + return data.process_priority > p_node->data.process_priority; +} + void Node::get_owned_by(Node *p_by, List<Node *> *p_owned) { if (data.owner == p_by) @@ -2608,6 +2629,7 @@ void Node::_bind_methods() { ClassDB::bind_method(D_METHOD("is_physics_processing"), &Node::is_physics_processing); ClassDB::bind_method(D_METHOD("get_process_delta_time"), &Node::get_process_delta_time); ClassDB::bind_method(D_METHOD("set_process", "enable"), &Node::set_process); + ClassDB::bind_method(D_METHOD("set_process_priority", "priority"), &Node::set_process_priority); ClassDB::bind_method(D_METHOD("is_processing"), &Node::is_processing); ClassDB::bind_method(D_METHOD("set_process_input", "enable"), &Node::set_process_input); ClassDB::bind_method(D_METHOD("is_processing_input"), &Node::is_processing_input); @@ -2759,6 +2781,7 @@ Node::Node() { data.tree = NULL; data.physics_process = false; data.idle_process = false; + data.process_priority = 0; data.physics_process_internal = false; data.idle_process_internal = false; data.inside_tree = false; diff --git a/scene/main/node.h b/scene/main/node.h index 341349de79..4b8f584ba7 100644 --- a/scene/main/node.h +++ b/scene/main/node.h @@ -70,6 +70,11 @@ public: bool operator()(const Node *p_a, const Node *p_b) const { return p_b->is_greater_than(p_a); } }; + struct ComparatorWithPriority { + + bool operator()(const Node *p_a, const Node *p_b) const { return p_b->has_priority_higher_than(p_a) || p_b->is_greater_than(p_a); } + }; + private: struct GroupData { @@ -118,6 +123,7 @@ private: //should move all the stuff below to bits bool physics_process; bool idle_process; + int process_priority; bool physics_process_internal; bool idle_process_internal; @@ -259,6 +265,7 @@ public: bool is_a_parent_of(const Node *p_node) const; bool is_greater_than(const Node *p_node) const; + bool has_priority_higher_than(const Node *p_node) const; NodePath get_path() const; NodePath get_path_to(const Node *p_node) const; @@ -319,6 +326,8 @@ public: void set_process_internal(bool p_idle_process_internal); bool is_processing_internal() const; + void set_process_priority(int p_priority); + void set_process_input(bool p_enable); bool is_processing_input() const; diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp index 6438616cf2..3424c4edac 100644 --- a/scene/main/scene_tree.cpp +++ b/scene/main/scene_tree.cpp @@ -132,6 +132,12 @@ void SceneTree::remove_from_group(const StringName &p_group, Node *p_node) { group_map.erase(E); } +void SceneTree::make_group_changed(const StringName &p_group) { + Map<StringName, Group>::Element *E = group_map.find(p_group); + if (E) + E->get().changed = true; +} + void SceneTree::flush_transform_notifications() { SelfList<Node> *n = xform_change_list.first(); @@ -165,7 +171,7 @@ void SceneTree::_flush_ugc() { ugc_locked = false; } -void SceneTree::_update_group_order(Group &g) { +void SceneTree::_update_group_order(Group &g, bool p_use_priority) { if (!g.changed) return; @@ -175,8 +181,13 @@ void SceneTree::_update_group_order(Group &g) { Node **nodes = &g.nodes[0]; int node_count = g.nodes.size(); - SortArray<Node *, Node::Comparator> node_sort; - node_sort.sort(nodes, node_count); + if (p_use_priority) { + SortArray<Node *, Node::ComparatorWithPriority> node_sort; + node_sort.sort(nodes, node_count); + } else { + SortArray<Node *, Node::Comparator> node_sort; + node_sort.sort(nodes, node_count); + } g.changed = false; } @@ -921,7 +932,7 @@ void SceneTree::_notify_group_pause(const StringName &p_group, int p_notificatio if (g.nodes.empty()) return; - _update_group_order(g); + _update_group_order(g, p_notification == Node::NOTIFICATION_PROCESS || p_notification == Node::NOTIFICATION_INTERNAL_PROCESS || p_notification == Node::NOTIFICATION_PHYSICS_PROCESS || p_notification == Node::NOTIFICATION_INTERNAL_PHYSICS_PROCESS); //copy, so copy on write happens in case something is removed from process while being called //performance is not lost because only if something is added/removed the vector is copied. diff --git a/scene/main/scene_tree.h b/scene/main/scene_tree.h index aa8d78b1e1..11201097d4 100644 --- a/scene/main/scene_tree.h +++ b/scene/main/scene_tree.h @@ -161,7 +161,7 @@ private: bool ugc_locked; void _flush_ugc(); - _FORCE_INLINE_ void _update_group_order(Group &g); + _FORCE_INLINE_ void _update_group_order(Group &g, bool p_use_priority = false); void _update_listener(); Array _get_nodes_in_group(const StringName &p_group); @@ -204,6 +204,7 @@ private: Group *add_to_group(const StringName &p_group, Node *p_node); void remove_from_group(const StringName &p_group, Node *p_node); + void make_group_changed(const StringName &p_group); void _notify_group_pause(const StringName &p_group, int p_notification); void _call_input_pause(const StringName &p_group, const StringName &p_method, const Ref<InputEvent> &p_input); diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp index 01302d4214..9013d276c7 100644 --- a/scene/main/viewport.cpp +++ b/scene/main/viewport.cpp @@ -41,7 +41,7 @@ #include "scene/3d/spatial.h" #include "scene/gui/control.h" #include "scene/gui/label.h" -#include "scene/gui/panel.h" +#include "scene/gui/panel_container.h" #include "scene/main/timer.h" #include "scene/resources/mesh.h" #include "scene/scene_string_names.h" @@ -166,9 +166,9 @@ ViewportTexture::~ViewportTexture() { ///////////////////////////////////// -class TooltipPanel : public Panel { +class TooltipPanel : public PanelContainer { - GDCLASS(TooltipPanel, Panel) + GDCLASS(TooltipPanel, PanelContainer) public: TooltipPanel(){}; }; @@ -1305,10 +1305,11 @@ void Viewport::_gui_cancel_tooltip() { if (gui.tooltip_popup) { gui.tooltip_popup->queue_delete(); gui.tooltip_popup = NULL; + gui.tooltip_label = NULL; } } -String Viewport::_gui_get_tooltip(Control *p_control, const Vector2 &p_pos) { +String Viewport::_gui_get_tooltip(Control *p_control, const Vector2 &p_pos, Control **r_which) { Vector2 pos = p_pos; String tooltip; @@ -1317,6 +1318,10 @@ String Viewport::_gui_get_tooltip(Control *p_control, const Vector2 &p_pos) { tooltip = p_control->get_tooltip(pos); + if (r_which) { + *r_which = p_control; + } + if (tooltip != String()) break; pos = p_control->get_transform().xform(pos); @@ -1338,41 +1343,49 @@ void Viewport::_gui_show_tooltip() { return; } - String tooltip = _gui_get_tooltip(gui.tooltip, gui.tooltip->get_global_transform().xform_inv(gui.tooltip_pos)); + Control *which = NULL; + String tooltip = _gui_get_tooltip(gui.tooltip, gui.tooltip->get_global_transform().xform_inv(gui.tooltip_pos), &which); if (tooltip.length() == 0) return; // bye if (gui.tooltip_popup) { memdelete(gui.tooltip_popup); gui.tooltip_popup = NULL; + gui.tooltip_label = NULL; } - if (!gui.tooltip) { + if (!which) { return; } - Control *rp = gui.tooltip->get_root_parent_control(); + Control *rp = which; //->get_root_parent_control(); if (!rp) return; - gui.tooltip_popup = memnew(TooltipPanel); + gui.tooltip_popup = which->make_custom_tooltip(tooltip); + + if (!gui.tooltip_popup) { + gui.tooltip_popup = memnew(TooltipPanel); + + gui.tooltip_label = memnew(TooltipLabel); + gui.tooltip_popup->add_child(gui.tooltip_label); + + Ref<StyleBox> ttp = gui.tooltip_label->get_stylebox("panel", "TooltipPanel"); + + gui.tooltip_label->set_anchor_and_margin(MARGIN_LEFT, Control::ANCHOR_BEGIN, ttp->get_margin(MARGIN_LEFT)); + gui.tooltip_label->set_anchor_and_margin(MARGIN_TOP, Control::ANCHOR_BEGIN, ttp->get_margin(MARGIN_TOP)); + gui.tooltip_label->set_anchor_and_margin(MARGIN_RIGHT, Control::ANCHOR_END, -ttp->get_margin(MARGIN_RIGHT)); + gui.tooltip_label->set_anchor_and_margin(MARGIN_BOTTOM, Control::ANCHOR_END, -ttp->get_margin(MARGIN_BOTTOM)); + gui.tooltip_label->set_text(tooltip.strip_edges()); + } rp->add_child(gui.tooltip_popup); gui.tooltip_popup->force_parent_owned(); - gui.tooltip_label = memnew(TooltipLabel); - gui.tooltip_popup->add_child(gui.tooltip_label); gui.tooltip_popup->set_as_toplevel(true); - gui.tooltip_popup->hide(); - - Ref<StyleBox> ttp = gui.tooltip_label->get_stylebox("panel", "TooltipPanel"); + //gui.tooltip_popup->hide(); - gui.tooltip_label->set_anchor_and_margin(MARGIN_LEFT, Control::ANCHOR_BEGIN, ttp->get_margin(MARGIN_LEFT)); - gui.tooltip_label->set_anchor_and_margin(MARGIN_TOP, Control::ANCHOR_BEGIN, ttp->get_margin(MARGIN_TOP)); - gui.tooltip_label->set_anchor_and_margin(MARGIN_RIGHT, Control::ANCHOR_END, -ttp->get_margin(MARGIN_RIGHT)); - gui.tooltip_label->set_anchor_and_margin(MARGIN_BOTTOM, Control::ANCHOR_END, -ttp->get_margin(MARGIN_BOTTOM)); - gui.tooltip_label->set_text(tooltip.strip_edges()); - Rect2 r(gui.tooltip_pos + Point2(10, 10), gui.tooltip_label->get_minimum_size() + ttp->get_minimum_size()); - Rect2 vr = gui.tooltip_label->get_viewport_rect(); + Rect2 r(gui.tooltip_pos + Point2(10, 10), gui.tooltip_popup->get_minimum_size()); + Rect2 vr = gui.tooltip_popup->get_viewport_rect(); if (r.size.x + r.position.x > vr.size.x) r.position.x = vr.size.x - r.size.x; else if (r.position.x < 0) @@ -1891,13 +1904,18 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) { bool is_tooltip_shown = false; if (gui.tooltip_popup) { - if (can_tooltip) { + if (can_tooltip && gui.tooltip) { String tooltip = _gui_get_tooltip(over, gui.tooltip->get_global_transform().xform_inv(mpos)); if (tooltip.length() == 0) _gui_cancel_tooltip(); - else if (tooltip == gui.tooltip_label->get_text()) + else if (gui.tooltip_label) { + if (tooltip == gui.tooltip_label->get_text()) { + is_tooltip_shown = true; + } + } else if (tooltip == String(gui.tooltip_popup->call("get_tooltip_text"))) { is_tooltip_shown = true; + } } else _gui_cancel_tooltip(); } diff --git a/scene/main/viewport.h b/scene/main/viewport.h index 3000398540..e717d27069 100644 --- a/scene/main/viewport.h +++ b/scene/main/viewport.h @@ -255,7 +255,7 @@ private: Control *key_focus; Control *mouse_over; Control *tooltip; - Panel *tooltip_popup; + Control *tooltip_popup; Label *tooltip_label; Point2 tooltip_pos; Point2 last_mouse_pos; @@ -312,7 +312,7 @@ private: void _gui_remove_root_control(List<Control *>::Element *RI); void _gui_remove_subwindow_control(List<Control *>::Element *SI); - String _gui_get_tooltip(Control *p_control, const Vector2 &p_pos); + String _gui_get_tooltip(Control *p_control, const Vector2 &p_pos, Control **r_which = NULL); void _gui_cancel_tooltip(); void _gui_show_tooltip(); diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp index 8f78e137b4..0d69c037fe 100644 --- a/scene/register_scene_types.cpp +++ b/scene/register_scene_types.cpp @@ -199,10 +199,12 @@ #include "scene/3d/remote_transform.h" #include "scene/3d/room_instance.h" #include "scene/3d/skeleton.h" +#include "scene/3d/soft_body.h" #include "scene/3d/sprite_3d.h" #include "scene/3d/vehicle_body.h" #include "scene/3d/visibility_notifier.h" #include "scene/resources/environment.h" +#include "scene/resources/physics_material.h" #endif static ResourceFormatLoaderTheme *resource_loader_theme = NULL; @@ -312,21 +314,19 @@ void register_scene_types() { ClassDB::register_class<CenterContainer>(); ClassDB::register_class<ScrollContainer>(); ClassDB::register_class<PanelContainer>(); - ClassDB::register_virtual_class<SplitContainer>(); - ClassDB::register_class<HSplitContainer>(); - ClassDB::register_class<VSplitContainer>(); - ClassDB::register_class<GraphNode>(); - ClassDB::register_class<GraphEdit>(); OS::get_singleton()->yield(); //may take time to init ClassDB::register_class<TextureProgress>(); ClassDB::register_class<ItemList>(); + ClassDB::register_class<LineEdit>(); + ClassDB::register_class<VideoPlayer>(); + #ifndef ADVANCED_GUI_DISABLED ClassDB::register_class<FileDialog>(); - ClassDB::register_class<LineEdit>(); + ClassDB::register_class<PopupMenu>(); ClassDB::register_class<Tree>(); @@ -343,9 +343,13 @@ void register_scene_types() { ClassDB::register_class<WindowDialog>(); ClassDB::register_class<AcceptDialog>(); ClassDB::register_class<ConfirmationDialog>(); - ClassDB::register_class<VideoPlayer>(); ClassDB::register_class<MarginContainer>(); ClassDB::register_class<ViewportContainer>(); + ClassDB::register_virtual_class<SplitContainer>(); + ClassDB::register_class<HSplitContainer>(); + ClassDB::register_class<VSplitContainer>(); + ClassDB::register_class<GraphNode>(); + ClassDB::register_class<GraphEdit>(); OS::get_singleton()->yield(); //may take time to init @@ -425,6 +429,7 @@ void register_scene_types() { ClassDB::register_class<KinematicCollision>(); ClassDB::register_class<KinematicBody>(); ClassDB::register_class<PhysicalBone>(); + ClassDB::register_class<SoftBody>(); ClassDB::register_class<VehicleBody>(); ClassDB::register_class<VehicleWheel>(); @@ -588,6 +593,8 @@ void register_scene_types() { OS::get_singleton()->yield(); //may take time to init ClassDB::register_class<SpatialVelocityTracker>(); + + ClassDB::register_class<PhysicsMaterial>(); #endif ClassDB::register_class<World>(); ClassDB::register_class<Environment>(); diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp index d4432b969f..fe12e2f5f6 100644 --- a/scene/resources/default_theme/default_theme.cpp +++ b/scene/resources/default_theme/default_theme.cpp @@ -476,6 +476,7 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const theme->set_color("symbol_color", "TextEdit", control_font_color_hover); theme->set_color("brace_mismatch_color", "TextEdit", Color(1, 0.2, 0.2)); theme->set_color("line_number_color", "TextEdit", Color::html("66aaaaaa")); + theme->set_color("safe_line_number_color", "TextEdit", Color::html("99aac8aa")); theme->set_color("function_color", "TextEdit", Color::html("66a2ce")); theme->set_color("member_variable_color", "TextEdit", Color::html("e64e59")); theme->set_color("number_color", "TextEdit", Color::html("EB9532")); diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp index b0620d3363..fe87dcdd2c 100644 --- a/scene/resources/mesh.cpp +++ b/scene/resources/mesh.cpp @@ -40,7 +40,6 @@ void Mesh::_clear_triangle_mesh() const { triangle_mesh.unref(); - ; } Ref<TriangleMesh> Mesh::generate_triangle_mesh() const { @@ -110,6 +109,54 @@ Ref<TriangleMesh> Mesh::generate_triangle_mesh() const { return triangle_mesh; } +void Mesh::generate_debug_mesh_lines(Vector<Vector3> &r_lines) { + + Ref<TriangleMesh> tm = generate_triangle_mesh(); + if (tm.is_null()) + return; + + PoolVector<int> triangle_indices; + tm->get_indices(&triangle_indices); + const int triangles_num = tm->get_triangles().size(); + PoolVector<Vector3> vertices = tm->get_vertices(); + + r_lines.resize(tm->get_triangles().size() * 6); // 3 lines x 2 points each line + + PoolVector<int>::Read ind_r = triangle_indices.read(); + PoolVector<Vector3>::Read ver_r = vertices.read(); + for (int j = 0, x = 0, i = 0; i < triangles_num; j += 6, x += 3, ++i) { + // Triangle line 1 + r_lines[j + 0] = ver_r[ind_r[x + 0]]; + r_lines[j + 1] = ver_r[ind_r[x + 1]]; + + // Triangle line 2 + r_lines[j + 2] = ver_r[ind_r[x + 1]]; + r_lines[j + 3] = ver_r[ind_r[x + 2]]; + + // Triangle line 3 + r_lines[j + 4] = ver_r[ind_r[x + 2]]; + r_lines[j + 5] = ver_r[ind_r[x + 0]]; + } +} +void Mesh::generate_debug_mesh_indices(Vector<Vector3> &r_points) { + Ref<TriangleMesh> tm = generate_triangle_mesh(); + if (tm.is_null()) + return; + + PoolVector<Vector3> vertices = tm->get_vertices(); + + int vertices_size = vertices.size(); + r_points.resize(vertices_size); + for (int i = 0; i < vertices_size; ++i) { + r_points[i] = vertices[i]; + } +} + +bool Mesh::surface_is_softbody_friendly(int p_idx) const { + const uint32_t surface_format = surface_get_format(p_idx); + return (surface_format & Mesh::ARRAY_FLAG_USE_DYNAMIC_UPDATE && (!(surface_format & Mesh::ARRAY_COMPRESS_VERTEX)) && (!(surface_format & Mesh::ARRAY_COMPRESS_NORMAL))); +} + PoolVector<Face3> Mesh::get_faces() const { Ref<TriangleMesh> tm = generate_triangle_mesh(); @@ -484,6 +531,10 @@ void Mesh::_bind_methods() { BIND_ENUM_CONSTANT(ARRAY_MAX); } +void Mesh::clear_cache() { + _clear_triangle_mesh(); +} + Mesh::Mesh() { } diff --git a/scene/resources/mesh.h b/scene/resources/mesh.h index a3fb068569..2127eaae4c 100644 --- a/scene/resources/mesh.h +++ b/scene/resources/mesh.h @@ -123,6 +123,7 @@ public: virtual int get_surface_count() const = 0; virtual int surface_get_array_len(int p_idx) const = 0; virtual int surface_get_array_index_len(int p_idx) const = 0; + virtual bool surface_is_softbody_friendly(int p_idx) const; virtual Array surface_get_arrays(int p_surface) const = 0; virtual Array surface_get_blend_shape_arrays(int p_surface) const = 0; virtual uint32_t surface_get_format(int p_idx) const = 0; @@ -133,6 +134,8 @@ public: PoolVector<Face3> get_faces() const; Ref<TriangleMesh> generate_triangle_mesh() const; + void generate_debug_mesh_lines(Vector<Vector3> &r_lines); + void generate_debug_mesh_indices(Vector<Vector3> &r_points); Ref<Shape> create_trimesh_shape() const; Ref<Shape> create_convex_shape() const; @@ -143,6 +146,7 @@ public: void set_lightmap_size_hint(const Vector2 &p_size); Size2 get_lightmap_size_hint() const; + void clear_cache(); Mesh(); }; diff --git a/scene/resources/physics_material.cpp b/scene/resources/physics_material.cpp new file mode 100644 index 0000000000..de3cfd1371 --- /dev/null +++ b/scene/resources/physics_material.cpp @@ -0,0 +1,94 @@ +/*************************************************************************/ +/* physics_material.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* 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 "physics_material.h" + +bool PhysicsMaterial::_set(const StringName &p_name, const Variant &p_value) { + if (p_name == "bounce") { + set_bounce(p_value); + } else if (p_name == "bounce_combine_mode") { + set_bounce_combine_mode(static_cast<PhysicsServer::CombineMode>(int(p_value))); + } else if (p_name == "friction") { + set_friction(p_value); + } else if (p_name == "friction_combine_mode") { + set_friction_combine_mode(static_cast<PhysicsServer::CombineMode>(int(p_value))); + } else { + return false; + } + + emit_changed(); + return true; +} + +bool PhysicsMaterial::_get(const StringName &p_name, Variant &r_ret) const { + if (p_name == "bounce") { + r_ret = bounce; + } else if (p_name == "bounce_combine_mode") { + r_ret = int(bounce_combine_mode); + } else if (p_name == "friction") { + r_ret = friction; + } else if (p_name == "friction_combine_mode") { + r_ret = int(friction_combine_mode); + } else { + return false; + } + + return true; +} + +void PhysicsMaterial::_get_property_list(List<PropertyInfo> *p_list) const { + p_list->push_back(PropertyInfo(Variant::REAL, "bounce")); + p_list->push_back(PropertyInfo(Variant::INT, "bounce_combine_mode", PROPERTY_HINT_ENUM, "Max,Min,Multiply,Average")); + p_list->push_back(PropertyInfo(Variant::REAL, "friction")); + p_list->push_back(PropertyInfo(Variant::INT, "friction_combine_mode", PROPERTY_HINT_ENUM, "Max,Min,Multiply,Average")); +} + +void PhysicsMaterial::_bind_methods() {} + +void PhysicsMaterial::set_bounce(real_t p_val) { + bounce = p_val; +} + +void PhysicsMaterial::set_bounce_combine_mode(PhysicsServer::CombineMode p_val) { + bounce_combine_mode = p_val; +} + +void PhysicsMaterial::set_friction(real_t p_val) { + friction = p_val; +} + +void PhysicsMaterial::set_friction_combine_mode(PhysicsServer::CombineMode p_val) { + friction_combine_mode = p_val; +} + +PhysicsMaterial::PhysicsMaterial() : + bounce(0), + bounce_combine_mode(PhysicsServer::COMBINE_MODE_MAX), + friction(0), + friction_combine_mode(PhysicsServer::COMBINE_MODE_MULTIPLY) {} diff --git a/scene/resources/physics_material.h b/scene/resources/physics_material.h new file mode 100644 index 0000000000..a6cb8c288e --- /dev/null +++ b/scene/resources/physics_material.h @@ -0,0 +1,70 @@ +/*************************************************************************/ +/* physics_material.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* 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 physics_material_override_H +#define physics_material_override_H + +#include "resource.h" +#include "servers/physics_server.h" + +class PhysicsMaterial : public Resource { + + GDCLASS(PhysicsMaterial, Resource); + OBJ_SAVE_TYPE(PhysicsMaterial); + RES_BASE_EXTENSION("PhyMat"); + + real_t bounce; + PhysicsServer::CombineMode bounce_combine_mode; + real_t friction; + PhysicsServer::CombineMode friction_combine_mode; + +protected: + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; + + static void _bind_methods(); + +public: + void set_bounce(real_t p_val); + _FORCE_INLINE_ real_t get_bounce() const { return bounce; } + + void set_bounce_combine_mode(PhysicsServer::CombineMode p_val); + _FORCE_INLINE_ PhysicsServer::CombineMode get_bounce_combine_mode() const { return bounce_combine_mode; } + + void set_friction(real_t p_val); + _FORCE_INLINE_ real_t get_friction() const { return friction; } + + void set_friction_combine_mode(PhysicsServer::CombineMode p_val); + _FORCE_INLINE_ PhysicsServer::CombineMode get_friction_combine_mode() const { return friction_combine_mode; } + + PhysicsMaterial(); +}; + +#endif // physics_material_override_H diff --git a/scene/resources/surface_tool.cpp b/scene/resources/surface_tool.cpp index 5a42873d79..3df9ab26a4 100644 --- a/scene/resources/surface_tool.cpp +++ b/scene/resources/surface_tool.cpp @@ -421,6 +421,7 @@ Ref<ArrayMesh> SurfaceTool::commit(const Ref<ArrayMesh> &p_existing, uint32_t p_ Array a = commit_to_arrays(); mesh->add_surface_from_arrays(primitive, a, Array(), p_flags); + if (material.is_valid()) mesh->surface_set_material(surface, material); diff --git a/servers/audio/audio_driver_dummy.cpp b/servers/audio/audio_driver_dummy.cpp index 1ca2334392..be36c3b748 100644 --- a/servers/audio/audio_driver_dummy.cpp +++ b/servers/audio/audio_driver_dummy.cpp @@ -44,7 +44,7 @@ Error AudioDriverDummy::init() { speaker_mode = SPEAKER_MODE_STEREO; channels = 2; - int latency = GLOBAL_DEF("audio/output_latency", DEFAULT_OUTPUT_LATENCY); + int latency = GLOBAL_DEF_RST("audio/output_latency", DEFAULT_OUTPUT_LATENCY); buffer_frames = closest_power_of_2(latency * mix_rate / 1000); samples_in = memnew_arr(int32_t, buffer_frames * channels); diff --git a/servers/audio_server.cpp b/servers/audio_server.cpp index ef794ac380..ceb843c031 100644 --- a/servers/audio_server.cpp +++ b/servers/audio_server.cpp @@ -903,8 +903,8 @@ void AudioServer::init_channels_and_buffers() { void AudioServer::init() { - channel_disable_threshold_db = GLOBAL_DEF("audio/channel_disable_threshold_db", -60.0); - channel_disable_frames = float(GLOBAL_DEF("audio/channel_disable_time", 2.0)) * get_mix_rate(); + channel_disable_threshold_db = GLOBAL_DEF_RST("audio/channel_disable_threshold_db", -60.0); + channel_disable_frames = float(GLOBAL_DEF_RST("audio/channel_disable_time", 2.0)) * get_mix_rate(); buffer_size = 1024; //hardcoded for now init_channels_and_buffers(); @@ -920,7 +920,7 @@ void AudioServer::init() { set_edited(false); //avoid editors from thinking this was edited #endif - GLOBAL_DEF("audio/video_delay_compensation_ms", 0); + GLOBAL_DEF_RST("audio/video_delay_compensation_ms", 0); } void AudioServer::update() { diff --git a/servers/physics/body_pair_sw.cpp b/servers/physics/body_pair_sw.cpp index 2a6a9e08ae..5a41b621eb 100644 --- a/servers/physics/body_pair_sw.cpp +++ b/servers/physics/body_pair_sw.cpp @@ -211,6 +211,44 @@ bool BodyPairSW::_test_ccd(real_t p_step, BodySW *p_A, int p_shape_A, const Tran return true; } +real_t combine_bounce(BodySW *A, BodySW *B) { + const PhysicsServer::CombineMode cm = A->get_bounce_combine_mode(); + + switch (cm) { + case PhysicsServer::COMBINE_MODE_INHERIT: + if (B->get_bounce_combine_mode() != PhysicsServer::COMBINE_MODE_INHERIT) + return combine_bounce(B, A); + // else use MAX [This is used when the two bodies doesn't use physical material] + case PhysicsServer::COMBINE_MODE_MAX: + return MAX(A->get_bounce(), B->get_bounce()); + case PhysicsServer::COMBINE_MODE_MIN: + return MIN(A->get_bounce(), B->get_bounce()); + case PhysicsServer::COMBINE_MODE_MULTIPLY: + return A->get_bounce() * B->get_bounce(); + default: // Is always PhysicsServer::COMBINE_MODE_AVERAGE: + return (A->get_bounce() + B->get_bounce()) / 2; + } +} + +real_t combine_friction(BodySW *A, BodySW *B) { + const PhysicsServer::CombineMode cm = A->get_friction_combine_mode(); + + switch (cm) { + case PhysicsServer::COMBINE_MODE_INHERIT: + if (B->get_friction_combine_mode() != PhysicsServer::COMBINE_MODE_INHERIT) + return combine_friction(B, A); + // else use Multiply [This is used when the two bodies doesn't use physical material] + case PhysicsServer::COMBINE_MODE_MULTIPLY: + return A->get_friction() * B->get_friction(); + case PhysicsServer::COMBINE_MODE_MAX: + return MAX(A->get_friction(), B->get_friction()); + case PhysicsServer::COMBINE_MODE_MIN: + return MIN(A->get_friction(), B->get_friction()); + default: // Is always PhysicsServer::COMBINE_MODE_AVERAGE: + return (A->get_friction() + B->get_friction()) / 2; + } +} + bool BodyPairSW::setup(real_t p_step) { //cannot collide @@ -331,7 +369,7 @@ bool BodyPairSW::setup(real_t p_step) { c.acc_bias_impulse = 0; c.acc_bias_impulse_center_of_mass = 0; - c.bounce = MAX(A->get_bounce(), B->get_bounce()); + c.bounce = combine_bounce(A, B); if (c.bounce) { Vector3 crA = A->get_angular_velocity().cross(c.rA); @@ -421,7 +459,7 @@ void BodyPairSW::solve(real_t p_step) { //friction impulse - real_t friction = A->get_friction() * B->get_friction(); + real_t friction = combine_friction(A, B); Vector3 lvA = A->get_linear_velocity() + A->get_angular_velocity().cross(c.rA); Vector3 lvB = B->get_linear_velocity() + B->get_angular_velocity().cross(c.rB); diff --git a/servers/physics/body_sw.cpp b/servers/physics/body_sw.cpp index cc9681193c..59f987fc17 100644 --- a/servers/physics/body_sw.cpp +++ b/servers/physics/body_sw.cpp @@ -423,6 +423,22 @@ void BodySW::_compute_area_gravity_and_dampenings(const AreaSW *p_area) { area_angular_damp += p_area->get_angular_damp(); } +void BodySW::set_combine_mode(PhysicsServer::BodyParameter p_param, PhysicsServer::CombineMode p_mode) { + if (p_param == PhysicsServer::BODY_PARAM_BOUNCE) { + bounce_combine_mode = p_mode; + } else { + friction_combine_mode = p_mode; + } +} + +PhysicsServer::CombineMode BodySW::get_combine_mode(PhysicsServer::BodyParameter p_param) const { + if (p_param == PhysicsServer::BODY_PARAM_BOUNCE) { + return bounce_combine_mode; + } else { + return friction_combine_mode; + } +} + void BodySW::set_axis_lock(PhysicsServer::BodyAxis p_axis, bool lock) { if (lock) { locked_axis |= p_axis; diff --git a/servers/physics/body_sw.h b/servers/physics/body_sw.h index fd2ab16b84..25eb20f5d8 100644 --- a/servers/physics/body_sw.h +++ b/servers/physics/body_sw.h @@ -49,6 +49,8 @@ class BodySW : public CollisionObjectSW { real_t mass; real_t bounce; real_t friction; + PhysicsServer::CombineMode bounce_combine_mode; + PhysicsServer::CombineMode friction_combine_mode; real_t linear_damp; real_t angular_damp; @@ -298,6 +300,12 @@ public: _FORCE_INLINE_ Vector3 get_gravity() const { return gravity; } _FORCE_INLINE_ real_t get_bounce() const { return bounce; } + void set_combine_mode(PhysicsServer::BodyParameter p_param, PhysicsServer::CombineMode p_mode); + PhysicsServer::CombineMode get_combine_mode(PhysicsServer::BodyParameter p_param) const; + + _FORCE_INLINE_ PhysicsServer::CombineMode get_bounce_combine_mode() const { return bounce_combine_mode; } + _FORCE_INLINE_ PhysicsServer::CombineMode get_friction_combine_mode() const { return friction_combine_mode; } + void set_axis_lock(PhysicsServer::BodyAxis p_axis, bool lock); bool is_axis_locked(PhysicsServer::BodyAxis p_axis) const; diff --git a/servers/physics/physics_server_sw.cpp b/servers/physics/physics_server_sw.cpp index 6c25ad43f9..f1e0cbef29 100644 --- a/servers/physics/physics_server_sw.cpp +++ b/servers/physics/physics_server_sw.cpp @@ -701,6 +701,20 @@ real_t PhysicsServerSW::body_get_param(RID p_body, BodyParameter p_param) const return body->get_param(p_param); }; +void PhysicsServerSW::body_set_combine_mode(RID p_body, BodyParameter p_param, CombineMode p_mode) { + BodySW *body = body_owner.get(p_body); + ERR_FAIL_COND(!body); + + body->set_combine_mode(p_param, p_mode); +} + +PhysicsServer::CombineMode PhysicsServerSW::body_get_combine_mode(RID p_body, BodyParameter p_param) const { + BodySW *body = body_owner.get(p_body); + ERR_FAIL_COND_V(!body, COMBINE_MODE_INHERIT); + + return body->get_combine_mode(p_param); +} + void PhysicsServerSW::body_set_kinematic_safe_margin(RID p_body, real_t p_margin) { BodySW *body = body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -1367,6 +1381,8 @@ void PhysicsServerSW::init() { void PhysicsServerSW::step(real_t p_step) { +#ifndef _3D_DISABLED + if (!active) return; @@ -1387,6 +1403,7 @@ void PhysicsServerSW::step(real_t p_step) { active_objects += E->get()->get_active_objects(); collision_pairs += E->get()->get_collision_pairs(); } +#endif } void PhysicsServerSW::sync(){ @@ -1395,6 +1412,8 @@ void PhysicsServerSW::sync(){ void PhysicsServerSW::flush_queries() { +#ifndef _3D_DISABLED + if (!active) return; @@ -1441,6 +1460,7 @@ void PhysicsServerSW::flush_queries() { ScriptDebugger::get_singleton()->add_profiling_frame_data("physics", values); } +#endif }; void PhysicsServerSW::finish() { diff --git a/servers/physics/physics_server_sw.h b/servers/physics/physics_server_sw.h index 3f56ba26d0..7e9700d026 100644 --- a/servers/physics/physics_server_sw.h +++ b/servers/physics/physics_server_sw.h @@ -188,6 +188,10 @@ public: virtual void body_set_param(RID p_body, BodyParameter p_param, real_t p_value); virtual real_t body_get_param(RID p_body, BodyParameter p_param) const; + /// p_param accept only Bounce and Friction + virtual void body_set_combine_mode(RID p_body, BodyParameter p_param, CombineMode p_mode); + virtual CombineMode body_get_combine_mode(RID p_body, BodyParameter p_param) const; + virtual void body_set_kinematic_safe_margin(RID p_body, real_t p_margin); virtual real_t body_get_kinematic_safe_margin(RID p_body) const; @@ -230,6 +234,72 @@ public: // this function only works on physics process, errors and returns null otherwise virtual PhysicsDirectBodyState *body_get_direct_state(RID p_body); + /* SOFT BODY */ + + virtual RID soft_body_create(bool p_init_sleeping = false) { return RID(); } + + virtual void soft_body_update_visual_server(RID p_body, class SoftBodyVisualServerHandler *p_visual_server_handler) {} + + virtual void soft_body_set_space(RID p_body, RID p_space) {} + virtual RID soft_body_get_space(RID p_body) const { return RID(); } + + virtual void soft_body_set_collision_layer(RID p_body, uint32_t p_layer) {} + virtual uint32_t soft_body_get_collision_layer(RID p_body) const { return 0; } + + virtual void soft_body_set_collision_mask(RID p_body, uint32_t p_mask) {} + virtual uint32_t soft_body_get_collision_mask(RID p_body) const { return 0; } + + virtual void soft_body_add_collision_exception(RID p_body, RID p_body_b) {} + virtual void soft_body_remove_collision_exception(RID p_body, RID p_body_b) {} + virtual void soft_body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) {} + + virtual void soft_body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) {} + virtual Variant soft_body_get_state(RID p_body, BodyState p_state) const { return Variant(); } + + virtual void soft_body_set_transform(RID p_body, const Transform &p_transform) {} + virtual Vector3 soft_body_get_vertex_position(RID p_body, int vertex_index) const { return Vector3(); } + + virtual void soft_body_set_ray_pickable(RID p_body, bool p_enable) {} + virtual bool soft_body_is_ray_pickable(RID p_body) const { return false; } + + virtual void soft_body_set_simulation_precision(RID p_body, int p_simulation_precision) {} + virtual int soft_body_get_simulation_precision(RID p_body) { return 0; } + + virtual void soft_body_set_total_mass(RID p_body, real_t p_total_mass) {} + virtual real_t soft_body_get_total_mass(RID p_body) { return 0.; } + + virtual void soft_body_set_linear_stiffness(RID p_body, real_t p_stiffness) {} + virtual real_t soft_body_get_linear_stiffness(RID p_body) { return 0.; } + + virtual void soft_body_set_areaAngular_stiffness(RID p_body, real_t p_stiffness) {} + virtual real_t soft_body_get_areaAngular_stiffness(RID p_body) { return 0.; } + + virtual void soft_body_set_volume_stiffness(RID p_body, real_t p_stiffness) {} + virtual real_t soft_body_get_volume_stiffness(RID p_body) { return 0.; } + + virtual void soft_body_set_pressure_coefficient(RID p_body, real_t p_pressure_coefficient) {} + virtual real_t soft_body_get_pressure_coefficient(RID p_body) { return 0.; } + + virtual void soft_body_set_pose_matching_coefficient(RID p_body, real_t p_pose_matching_coefficient) {} + virtual real_t soft_body_get_pose_matching_coefficient(RID p_body) { return 0.; } + + virtual void soft_body_set_damping_coefficient(RID p_body, real_t p_damping_coefficient) {} + virtual real_t soft_body_get_damping_coefficient(RID p_body) { return 0.; } + + virtual void soft_body_set_drag_coefficient(RID p_body, real_t p_drag_coefficient) {} + virtual real_t soft_body_get_drag_coefficient(RID p_body) { return 0.; } + + virtual void soft_body_set_mesh(RID p_body, const REF &p_mesh) {} + + virtual void soft_body_move_point(RID p_body, int p_point_index, const Vector3 &p_global_position) {} + virtual Vector3 soft_body_get_point_global_position(RID p_body, int p_point_index) { return Vector3(); } + + virtual Vector3 soft_body_get_point_offset(RID p_body, int p_point_index) const { return Vector3(); } + + virtual void soft_body_remove_all_pinned_points(RID p_body) {} + virtual void soft_body_pin_point(RID p_body, int p_point_index, bool p_pin) {} + virtual bool soft_body_is_point_pinned(RID p_body, int p_point_index) { return 0; } + /* JOINT API */ virtual RID joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B); diff --git a/servers/physics_2d/body_2d_sw.cpp b/servers/physics_2d/body_2d_sw.cpp index aa063d6c1e..fcd2a65ee7 100644 --- a/servers/physics_2d/body_2d_sw.cpp +++ b/servers/physics_2d/body_2d_sw.cpp @@ -405,6 +405,22 @@ void Body2DSW::_compute_area_gravity_and_dampenings(const Area2DSW *p_area) { area_angular_damp += p_area->get_angular_damp(); } +void Body2DSW::set_combine_mode(Physics2DServer::BodyParameter p_param, Physics2DServer::CombineMode p_mode) { + if (p_param == Physics2DServer::BODY_PARAM_BOUNCE) { + bounce_combine_mode = p_mode; + } else { + friction_combine_mode = p_mode; + } +} + +Physics2DServer::CombineMode Body2DSW::get_combine_mode(Physics2DServer::BodyParameter p_param) const { + if (p_param == Physics2DServer::BODY_PARAM_BOUNCE) { + return bounce_combine_mode; + } else { + return friction_combine_mode; + } +} + void Body2DSW::integrate_forces(real_t p_step) { if (mode == Physics2DServer::BODY_MODE_STATIC) diff --git a/servers/physics_2d/body_2d_sw.h b/servers/physics_2d/body_2d_sw.h index 782adf3416..301bd6b299 100644 --- a/servers/physics_2d/body_2d_sw.h +++ b/servers/physics_2d/body_2d_sw.h @@ -54,6 +54,8 @@ class Body2DSW : public CollisionObject2DSW { real_t mass; real_t bounce; real_t friction; + Physics2DServer::CombineMode bounce_combine_mode; + Physics2DServer::CombineMode friction_combine_mode; real_t _inv_mass; real_t _inv_inertia; @@ -256,6 +258,12 @@ public: _FORCE_INLINE_ real_t get_linear_damp() const { return linear_damp; } _FORCE_INLINE_ real_t get_angular_damp() const { return angular_damp; } + void set_combine_mode(Physics2DServer::BodyParameter p_param, Physics2DServer::CombineMode p_mode); + Physics2DServer::CombineMode get_combine_mode(Physics2DServer::BodyParameter p_param) const; + + _FORCE_INLINE_ Physics2DServer::CombineMode get_bounce_combine_mode() const { return bounce_combine_mode; } + _FORCE_INLINE_ Physics2DServer::CombineMode get_friction_combine_mode() const { return friction_combine_mode; } + void integrate_forces(real_t p_step); void integrate_velocities(real_t p_step); diff --git a/servers/physics_2d/body_pair_2d_sw.cpp b/servers/physics_2d/body_pair_2d_sw.cpp index 61c0e0063f..be8dcf6fa8 100644 --- a/servers/physics_2d/body_pair_2d_sw.cpp +++ b/servers/physics_2d/body_pair_2d_sw.cpp @@ -219,6 +219,44 @@ bool BodyPair2DSW::_test_ccd(real_t p_step, Body2DSW *p_A, int p_shape_A, const return true; } +real_t combine_bounce(Body2DSW *A, Body2DSW *B) { + const Physics2DServer::CombineMode cm = A->get_bounce_combine_mode(); + + switch (cm) { + case Physics2DServer::COMBINE_MODE_INHERIT: + if (B->get_bounce_combine_mode() != Physics2DServer::COMBINE_MODE_INHERIT) + return combine_bounce(B, A); + // else use MAX [This is used when the two bodies doesn't use physical material] + case Physics2DServer::COMBINE_MODE_MAX: + return MAX(A->get_bounce(), B->get_bounce()); + case Physics2DServer::COMBINE_MODE_MIN: + return MIN(A->get_bounce(), B->get_bounce()); + case Physics2DServer::COMBINE_MODE_MULTIPLY: + return A->get_bounce() * B->get_bounce(); + default: // Is always Physics2DServer::COMBINE_MODE_AVERAGE: + return (A->get_bounce() + B->get_bounce()) / 2; + } +} + +real_t combine_friction(Body2DSW *A, Body2DSW *B) { + const Physics2DServer::CombineMode cm = A->get_friction_combine_mode(); + + switch (cm) { + case Physics2DServer::COMBINE_MODE_INHERIT: + if (B->get_friction_combine_mode() != Physics2DServer::COMBINE_MODE_INHERIT) + return combine_friction(B, A); + // else use Multiply [This is used when the two bodies doesn't use physical material] + case Physics2DServer::COMBINE_MODE_MULTIPLY: + return A->get_friction() * B->get_friction(); + case Physics2DServer::COMBINE_MODE_MAX: + return MAX(A->get_friction(), B->get_friction()); + case Physics2DServer::COMBINE_MODE_MIN: + return MIN(A->get_friction(), B->get_friction()); + default: // Is always Physics2DServer::COMBINE_MODE_AVERAGE: + return (A->get_friction() + B->get_friction()) / 2; + } +} + bool BodyPair2DSW::setup(real_t p_step) { //cannot collide @@ -432,7 +470,7 @@ bool BodyPair2DSW::setup(real_t p_step) { #endif - c.bounce = MAX(A->get_bounce(), B->get_bounce()); + c.bounce = combine_bounce(A, B); if (c.bounce) { Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x); @@ -488,7 +526,7 @@ void BodyPair2DSW::solve(real_t p_step) { real_t jnOld = c.acc_normal_impulse; c.acc_normal_impulse = MAX(jnOld + jn, 0.0f); - real_t friction = A->get_friction() * B->get_friction(); + real_t friction = combine_friction(A, B); real_t jtMax = friction * c.acc_normal_impulse; real_t jt = -vt * c.mass_tangent; diff --git a/servers/physics_2d/physics_2d_server_sw.cpp b/servers/physics_2d/physics_2d_server_sw.cpp index a473e0beb2..cfcef8cb04 100644 --- a/servers/physics_2d/physics_2d_server_sw.cpp +++ b/servers/physics_2d/physics_2d_server_sw.cpp @@ -789,6 +789,22 @@ real_t Physics2DServerSW::body_get_param(RID p_body, BodyParameter p_param) cons return body->get_param(p_param); }; +void Physics2DServerSW::body_set_combine_mode(RID p_body, BodyParameter p_param, CombineMode p_mode) { + + Body2DSW *body = body_owner.get(p_body); + ERR_FAIL_COND(!body); + + body->set_combine_mode(p_param, p_mode); +} + +Physics2DServer::CombineMode Physics2DServerSW::body_get_combine_mode(RID p_body, BodyParameter p_param) const { + + Body2DSW *body = body_owner.get(p_body); + ERR_FAIL_COND_V(!body, COMBINE_MODE_INHERIT); + + return body->get_combine_mode(p_param); +} + void Physics2DServerSW::body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) { Body2DSW *body = body_owner.get(p_body); diff --git a/servers/physics_2d/physics_2d_server_sw.h b/servers/physics_2d/physics_2d_server_sw.h index e5961b9011..bf00746063 100644 --- a/servers/physics_2d/physics_2d_server_sw.h +++ b/servers/physics_2d/physics_2d_server_sw.h @@ -200,6 +200,10 @@ public: virtual void body_set_param(RID p_body, BodyParameter p_param, real_t p_value); virtual real_t body_get_param(RID p_body, BodyParameter p_param) const; + /// p_param accept only Bounce and Friction + virtual void body_set_combine_mode(RID p_body, BodyParameter p_param, CombineMode p_mode); + virtual CombineMode body_get_combine_mode(RID p_body, BodyParameter p_param) const; + virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant); virtual Variant body_get_state(RID p_body, BodyState p_state) const; diff --git a/servers/physics_2d/physics_2d_server_wrap_mt.h b/servers/physics_2d/physics_2d_server_wrap_mt.h index 3119b930d7..a85cd5ef8d 100644 --- a/servers/physics_2d/physics_2d_server_wrap_mt.h +++ b/servers/physics_2d/physics_2d_server_wrap_mt.h @@ -211,6 +211,9 @@ public: FUNC3(body_set_param, RID, BodyParameter, real_t); FUNC2RC(real_t, body_get_param, RID, BodyParameter); + FUNC3(body_set_combine_mode, RID, BodyParameter, CombineMode); + FUNC2RC(CombineMode, body_get_combine_mode, RID, BodyParameter); + FUNC3(body_set_state, RID, BodyState, const Variant &); FUNC2RC(Variant, body_get_state, RID, BodyState); diff --git a/servers/physics_2d_server.h b/servers/physics_2d_server.h index 1d04fbc5c6..89c649af49 100644 --- a/servers/physics_2d_server.h +++ b/servers/physics_2d_server.h @@ -416,6 +416,19 @@ public: virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value) = 0; virtual float body_get_param(RID p_body, BodyParameter p_param) const = 0; + enum CombineMode { + COMBINE_MODE_MAX, + COMBINE_MODE_MIN, + COMBINE_MODE_MULTIPLY, + COMBINE_MODE_AVERAGE, + + COMBINE_MODE_INHERIT /// Inherit from other body or use COMBINE_MODE_MAX (Restitution) COMBINE_MODE_MULTIPLY (Friction) + }; + + /// p_param accept only Bounce and Friction + virtual void body_set_combine_mode(RID p_body, BodyParameter p_param, CombineMode p_mode) = 0; + virtual CombineMode body_get_combine_mode(RID p_body, BodyParameter p_param) const = 0; + //state enum BodyState { BODY_STATE_TRANSFORM, diff --git a/servers/physics_server.cpp b/servers/physics_server.cpp index de173491b2..b4bd4cb35f 100644 --- a/servers/physics_server.cpp +++ b/servers/physics_server.cpp @@ -400,6 +400,8 @@ void PhysicsShapeQueryResult::_bind_methods() { void PhysicsServer::_bind_methods() { +#ifndef _3D_DISABLED + ClassDB::bind_method(D_METHOD("shape_create", "type"), &PhysicsServer::shape_create); ClassDB::bind_method(D_METHOD("shape_set_data", "shape", "data"), &PhysicsServer::shape_set_data); @@ -737,6 +739,8 @@ void PhysicsServer::_bind_methods() { BIND_ENUM_CONSTANT(BODY_AXIS_ANGULAR_X); BIND_ENUM_CONSTANT(BODY_AXIS_ANGULAR_Y); BIND_ENUM_CONSTANT(BODY_AXIS_ANGULAR_Z); + +#endif } PhysicsServer::PhysicsServer() { diff --git a/servers/physics_server.h b/servers/physics_server.h index 8ecf17c0e6..497d23c555 100644 --- a/servers/physics_server.h +++ b/servers/physics_server.h @@ -399,6 +399,19 @@ public: virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value) = 0; virtual float body_get_param(RID p_body, BodyParameter p_param) const = 0; + enum CombineMode { + COMBINE_MODE_MAX, + COMBINE_MODE_MIN, + COMBINE_MODE_MULTIPLY, + COMBINE_MODE_AVERAGE, + + COMBINE_MODE_INHERIT /// Inherit from other body or use COMBINE_MODE_MAX (Restitution) COMBINE_MODE_MULTIPLY (Friction) + }; + + /// p_param accept only Bounce and Friction + virtual void body_set_combine_mode(RID p_body, BodyParameter p_param, CombineMode p_mode) = 0; + virtual CombineMode body_get_combine_mode(RID p_body, BodyParameter p_param) const = 0; + virtual void body_set_kinematic_safe_margin(RID p_body, real_t p_margin) = 0; virtual real_t body_get_kinematic_safe_margin(RID p_body) const = 0; @@ -477,6 +490,72 @@ public: virtual bool body_test_motion(RID p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result = NULL) = 0; + /* SOFT BODY */ + + virtual RID soft_body_create(bool p_init_sleeping = false) = 0; + + virtual void soft_body_update_visual_server(RID p_body, class SoftBodyVisualServerHandler *p_visual_server_handler) = 0; + + virtual void soft_body_set_space(RID p_body, RID p_space) = 0; + virtual RID soft_body_get_space(RID p_body) const = 0; + + virtual void soft_body_set_mesh(RID p_body, const REF &p_mesh) = 0; + + virtual void soft_body_set_collision_layer(RID p_body, uint32_t p_layer) = 0; + virtual uint32_t soft_body_get_collision_layer(RID p_body) const = 0; + + virtual void soft_body_set_collision_mask(RID p_body, uint32_t p_mask) = 0; + virtual uint32_t soft_body_get_collision_mask(RID p_body) const = 0; + + virtual void soft_body_add_collision_exception(RID p_body, RID p_body_b) = 0; + virtual void soft_body_remove_collision_exception(RID p_body, RID p_body_b) = 0; + virtual void soft_body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) = 0; + + virtual void soft_body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) = 0; + virtual Variant soft_body_get_state(RID p_body, BodyState p_state) const = 0; + + virtual void soft_body_set_transform(RID p_body, const Transform &p_transform) = 0; + virtual Vector3 soft_body_get_vertex_position(RID p_body, int vertex_index) const = 0; + + virtual void soft_body_set_ray_pickable(RID p_body, bool p_enable) = 0; + virtual bool soft_body_is_ray_pickable(RID p_body) const = 0; + + virtual void soft_body_set_simulation_precision(RID p_body, int p_simulation_precision) = 0; + virtual int soft_body_get_simulation_precision(RID p_body) = 0; + + virtual void soft_body_set_total_mass(RID p_body, real_t p_total_mass) = 0; + virtual real_t soft_body_get_total_mass(RID p_body) = 0; + + virtual void soft_body_set_linear_stiffness(RID p_body, real_t p_stiffness) = 0; + virtual real_t soft_body_get_linear_stiffness(RID p_body) = 0; + + virtual void soft_body_set_areaAngular_stiffness(RID p_body, real_t p_stiffness) = 0; + virtual real_t soft_body_get_areaAngular_stiffness(RID p_body) = 0; + + virtual void soft_body_set_volume_stiffness(RID p_body, real_t p_stiffness) = 0; + virtual real_t soft_body_get_volume_stiffness(RID p_body) = 0; + + virtual void soft_body_set_pressure_coefficient(RID p_body, real_t p_pressure_coefficient) = 0; + virtual real_t soft_body_get_pressure_coefficient(RID p_body) = 0; + + virtual void soft_body_set_pose_matching_coefficient(RID p_body, real_t p_pose_matching_coefficient) = 0; + virtual real_t soft_body_get_pose_matching_coefficient(RID p_body) = 0; + + virtual void soft_body_set_damping_coefficient(RID p_body, real_t p_damping_coefficient) = 0; + virtual real_t soft_body_get_damping_coefficient(RID p_body) = 0; + + virtual void soft_body_set_drag_coefficient(RID p_body, real_t p_drag_coefficient) = 0; + virtual real_t soft_body_get_drag_coefficient(RID p_body) = 0; + + virtual void soft_body_move_point(RID p_body, int p_point_index, const Vector3 &p_global_position) = 0; + virtual Vector3 soft_body_get_point_global_position(RID p_body, int p_point_index) = 0; + + virtual Vector3 soft_body_get_point_offset(RID p_body, int p_point_index) const = 0; + + virtual void soft_body_remove_all_pinned_points(RID p_body) = 0; + virtual void soft_body_pin_point(RID p_body, int p_point_index, bool p_pin) = 0; + virtual bool soft_body_is_point_pinned(RID p_body, int p_point_index) = 0; + /* JOINT API */ enum JointType { diff --git a/servers/visual/rasterizer.h b/servers/visual/rasterizer.h index 0b37d266e7..a8f4377ce7 100644 --- a/servers/visual/rasterizer.h +++ b/servers/visual/rasterizer.h @@ -104,10 +104,12 @@ public: VS::ShadowCastingSetting cast_shadows; + //fit in 32 bits bool mirror : 8; bool receive_shadows : 8; bool visible : 8; - bool baked_light : 8; //this flag is only to know if it actually did use baked light + bool baked_light : 4; //this flag is only to know if it actually did use baked light + bool redraw_if_visible : 4; float depth; //used for sorting @@ -131,6 +133,7 @@ public: depth_layer = 0; layer_mask = 1; baked_light = false; + redraw_if_visible = false; lightmap_capture = NULL; } }; @@ -277,6 +280,7 @@ public: virtual AABB mesh_get_custom_aabb(RID p_mesh) const = 0; virtual AABB mesh_get_aabb(RID p_mesh, RID p_skeleton) const = 0; + virtual void mesh_clear(RID p_mesh) = 0; /* MULTIMESH API */ diff --git a/servers/visual/visual_server_scene.cpp b/servers/visual/visual_server_scene.cpp index 697c890c9a..887cd7429a 100644 --- a/servers/visual/visual_server_scene.cpp +++ b/servers/visual/visual_server_scene.cpp @@ -820,6 +820,11 @@ void VisualServerScene::instance_geometry_set_flag(RID p_instance, VS::InstanceF instance->baked_light = p_enabled; } break; + case VS::INSTANCE_FLAG_REDRAW_FRAME_IF_VISIBLE: { + + instance->redraw_if_visible = p_enabled; + + } break; } } void VisualServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting) { @@ -1644,7 +1649,8 @@ void VisualServerScene::_light_instance_update_shadow(Instance *p_instance, cons } void VisualServerScene::render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) { - // render to mono camera +// render to mono camera +#ifndef _3D_DISABLED Camera *camera = camera_owner.getornull(p_camera); ERR_FAIL_COND(!camera); @@ -1679,6 +1685,7 @@ void VisualServerScene::render_camera(RID p_camera, RID p_scenario, Size2 p_view _prepare_scene(camera->transform, camera_matrix, ortho, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID()); _render_scene(camera->transform, camera_matrix, ortho, camera->env, p_scenario, p_shadow_atlas, RID(), -1); +#endif } void VisualServerScene::render_camera(Ref<ARVRInterface> &p_interface, ARVRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) { @@ -1871,6 +1878,10 @@ void VisualServerScene::_prepare_scene(const Transform p_cam_transform, const Ca InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data); + if (ins->redraw_if_visible) { + VisualServerRaster::redraw_request(); + } + if (ins->base_type == VS::INSTANCE_PARTICLES) { //particles visible? process them VSG::storage->particles_request_process(ins->base); @@ -2102,6 +2113,8 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform, const Cam void VisualServerScene::render_empty_scene(RID p_scenario, RID p_shadow_atlas) { +#ifndef _3D_DISABLED + Scenario *scenario = scenario_owner.getornull(p_scenario); RID environment; @@ -2110,6 +2123,7 @@ void VisualServerScene::render_empty_scene(RID p_scenario, RID p_shadow_atlas) { else environment = scenario->fallback_environment; VSG::scene_render->render_scene(Transform(), CameraMatrix(), true, NULL, 0, NULL, 0, NULL, 0, environment, p_shadow_atlas, scenario->reflection_atlas, RID(), 0); +#endif } bool VisualServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) { diff --git a/servers/visual_server.cpp b/servers/visual_server.cpp index dffaccc0d4..8e21341cee 100644 --- a/servers/visual_server.cpp +++ b/servers/visual_server.cpp @@ -795,6 +795,140 @@ Error VisualServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint32_ return OK; } +uint32_t VisualServer::mesh_surface_get_format_offset(uint32_t p_format, int p_vertex_len, int p_index_len, int p_array_index) const { + uint32_t offsets[ARRAY_MAX]; + mesh_surface_make_offsets_from_format(p_format, p_vertex_len, p_index_len, offsets); + return offsets[p_array_index]; +} + +uint32_t VisualServer::mesh_surface_get_format_stride(uint32_t p_format, int p_vertex_len, int p_index_len) const { + uint32_t offsets[ARRAY_MAX]; + return mesh_surface_make_offsets_from_format(p_format, p_vertex_len, p_index_len, offsets); +} + +uint32_t VisualServer::mesh_surface_make_offsets_from_format(uint32_t p_format, int p_vertex_len, int p_index_len, uint32_t *r_offsets) const { + + int total_elem_size = 0; + + for (int i = 0; i < VS::ARRAY_MAX; i++) { + + r_offsets[i] = 0; //reset + + if (!(p_format & (1 << i))) // no array + continue; + + int elem_size = 0; + + switch (i) { + + case VS::ARRAY_VERTEX: { + + if (p_format & ARRAY_FLAG_USE_2D_VERTICES) { + elem_size = 2; + } else { + elem_size = 3; + } + + if (p_format & ARRAY_COMPRESS_VERTEX) { + elem_size *= sizeof(int16_t); + } else { + elem_size *= sizeof(float); + } + + if (elem_size == 6) { + elem_size = 8; + } + + } break; + case VS::ARRAY_NORMAL: { + + if (p_format & ARRAY_COMPRESS_NORMAL) { + elem_size = sizeof(uint32_t); + } else { + elem_size = sizeof(float) * 3; + } + + } break; + + case VS::ARRAY_TANGENT: { + if (p_format & ARRAY_COMPRESS_TANGENT) { + elem_size = sizeof(uint32_t); + } else { + elem_size = sizeof(float) * 4; + } + + } break; + case VS::ARRAY_COLOR: { + + if (p_format & ARRAY_COMPRESS_COLOR) { + elem_size = sizeof(uint32_t); + } else { + elem_size = sizeof(float) * 4; + } + } break; + case VS::ARRAY_TEX_UV: { + if (p_format & ARRAY_COMPRESS_TEX_UV) { + elem_size = sizeof(uint32_t); + } else { + elem_size = sizeof(float) * 2; + } + + } break; + + case VS::ARRAY_TEX_UV2: { + if (p_format & ARRAY_COMPRESS_TEX_UV2) { + elem_size = sizeof(uint32_t); + } else { + elem_size = sizeof(float) * 2; + } + + } break; + case VS::ARRAY_WEIGHTS: { + + if (p_format & ARRAY_COMPRESS_WEIGHTS) { + elem_size = sizeof(uint16_t) * 4; + } else { + elem_size = sizeof(float) * 4; + } + + } break; + case VS::ARRAY_BONES: { + + if (p_format & ARRAY_FLAG_USE_16_BIT_BONES) { + elem_size = sizeof(uint16_t) * 4; + } else { + elem_size = sizeof(uint32_t); + } + + } break; + case VS::ARRAY_INDEX: { + + if (p_index_len <= 0) { + ERR_PRINT("index_array_len==NO_INDEX_ARRAY"); + break; + } + /* determine whether using 16 or 32 bits indices */ + if (p_vertex_len >= (1 << 16)) { + + elem_size = 4; + + } else { + elem_size = 2; + } + r_offsets[i] = elem_size; + continue; + } break; + default: { + ERR_FAIL_V(0); + } + } + + r_offsets[i] = total_elem_size; + total_elem_size += elem_size; + } + return total_elem_size; +} + void VisualServer::mesh_add_surface_from_arrays(RID p_mesh, PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, uint32_t p_compress_format) { ERR_FAIL_INDEX(p_primitive, VS::PRIMITIVE_MAX); @@ -1543,10 +1677,10 @@ void VisualServer::_bind_methods() { ClassDB::bind_method(D_METHOD("texture_debug_usage"), &VisualServer::_texture_debug_usage_bind); ClassDB::bind_method(D_METHOD("textures_keep_original", "enable"), &VisualServer::textures_keep_original); - +#ifndef _3D_DISABLED ClassDB::bind_method(D_METHOD("sky_create"), &VisualServer::sky_create); ClassDB::bind_method(D_METHOD("sky_set_texture", "sky", "cube_map", "radiance_size"), &VisualServer::sky_set_texture); - +#endif ClassDB::bind_method(D_METHOD("shader_create"), &VisualServer::shader_create); ClassDB::bind_method(D_METHOD("shader_set_code", "shader", "code"), &VisualServer::shader_set_code); ClassDB::bind_method(D_METHOD("shader_get_code", "shader"), &VisualServer::shader_get_code); @@ -1564,11 +1698,14 @@ void VisualServer::_bind_methods() { ClassDB::bind_method(D_METHOD("material_set_next_pass", "material", "next_material"), &VisualServer::material_set_next_pass); ClassDB::bind_method(D_METHOD("mesh_create"), &VisualServer::mesh_create); + ClassDB::bind_method(D_METHOD("mesh_surface_get_format_offset", "format", "vertex_len", "index_len", "array_index"), &VisualServer::mesh_surface_get_format_offset); + ClassDB::bind_method(D_METHOD("mesh_surface_get_format_stride", "format", "vertex_len", "index_len"), &VisualServer::mesh_surface_get_format_stride); ClassDB::bind_method(D_METHOD("mesh_add_surface_from_arrays", "mesh", "primtive", "arrays", "blend_shapes", "compress_format"), &VisualServer::mesh_add_surface_from_arrays, DEFVAL(Array()), DEFVAL(ARRAY_COMPRESS_DEFAULT)); ClassDB::bind_method(D_METHOD("mesh_set_blend_shape_count", "mesh", "amount"), &VisualServer::mesh_set_blend_shape_count); ClassDB::bind_method(D_METHOD("mesh_get_blend_shape_count", "mesh"), &VisualServer::mesh_get_blend_shape_count); ClassDB::bind_method(D_METHOD("mesh_set_blend_shape_mode", "mesh", "mode"), &VisualServer::mesh_set_blend_shape_mode); ClassDB::bind_method(D_METHOD("mesh_get_blend_shape_mode", "mesh"), &VisualServer::mesh_get_blend_shape_mode); + ClassDB::bind_method(D_METHOD("mesh_surface_update_region", "mesh", "surface", "offset", "data"), &VisualServer::mesh_surface_update_region); ClassDB::bind_method(D_METHOD("mesh_surface_set_material", "mesh", "surface", "material"), &VisualServer::mesh_surface_set_material); ClassDB::bind_method(D_METHOD("mesh_surface_get_material", "mesh", "surface"), &VisualServer::mesh_surface_get_material); ClassDB::bind_method(D_METHOD("mesh_surface_get_array_len", "mesh", "surface"), &VisualServer::mesh_surface_get_array_len); @@ -1603,7 +1740,7 @@ void VisualServer::_bind_methods() { ClassDB::bind_method(D_METHOD("multimesh_set_visible_instances", "multimesh", "visible"), &VisualServer::multimesh_set_visible_instances); ClassDB::bind_method(D_METHOD("multimesh_get_visible_instances", "multimesh"), &VisualServer::multimesh_get_visible_instances); ClassDB::bind_method(D_METHOD("multimesh_set_as_bulk_array", "multimesh", "array"), &VisualServer::multimesh_set_as_bulk_array); - +#ifndef _3D_DISABLED ClassDB::bind_method(D_METHOD("immediate_create"), &VisualServer::immediate_create); ClassDB::bind_method(D_METHOD("immediate_begin", "immediate", "primitive", "texture"), &VisualServer::immediate_begin, DEFVAL(RID())); ClassDB::bind_method(D_METHOD("immediate_vertex", "immediate", "vertex"), &VisualServer::immediate_vertex); @@ -1617,6 +1754,7 @@ void VisualServer::_bind_methods() { ClassDB::bind_method(D_METHOD("immediate_clear", "immediate"), &VisualServer::immediate_clear); ClassDB::bind_method(D_METHOD("immediate_set_material", "immediate", "material"), &VisualServer::immediate_set_material); ClassDB::bind_method(D_METHOD("immediate_get_material", "immediate"), &VisualServer::immediate_get_material); +#endif ClassDB::bind_method(D_METHOD("skeleton_create"), &VisualServer::skeleton_create); ClassDB::bind_method(D_METHOD("skeleton_allocate", "skeleton", "bones", "is_2d_skeleton"), &VisualServer::skeleton_allocate, DEFVAL(false)); @@ -1626,6 +1764,7 @@ void VisualServer::_bind_methods() { ClassDB::bind_method(D_METHOD("skeleton_bone_set_transform_2d", "skeleton", "bone", "transform"), &VisualServer::skeleton_bone_set_transform_2d); ClassDB::bind_method(D_METHOD("skeleton_bone_get_transform_2d", "skeleton", "bone"), &VisualServer::skeleton_bone_get_transform_2d); +#ifndef _3D_DISABLED ClassDB::bind_method(D_METHOD("directional_light_create"), &VisualServer::directional_light_create); ClassDB::bind_method(D_METHOD("omni_light_create"), &VisualServer::omni_light_create); ClassDB::bind_method(D_METHOD("spot_light_create"), &VisualServer::spot_light_create); @@ -1695,7 +1834,7 @@ void VisualServer::_bind_methods() { ClassDB::bind_method(D_METHOD("lightmap_capture_get_octree", "capture"), &VisualServer::lightmap_capture_get_octree); ClassDB::bind_method(D_METHOD("lightmap_capture_set_energy", "capture", "energy"), &VisualServer::lightmap_capture_set_energy); ClassDB::bind_method(D_METHOD("lightmap_capture_get_energy", "capture"), &VisualServer::lightmap_capture_get_energy); - +#endif ClassDB::bind_method(D_METHOD("particles_create"), &VisualServer::particles_create); ClassDB::bind_method(D_METHOD("particles_set_emitting", "particles", "emitting"), &VisualServer::particles_set_emitting); ClassDB::bind_method(D_METHOD("particles_get_emitting", "particles"), &VisualServer::particles_get_emitting); @@ -1782,6 +1921,8 @@ void VisualServer::_bind_methods() { ClassDB::bind_method(D_METHOD("scenario_set_reflection_atlas_size", "scenario", "p_size", "subdiv"), &VisualServer::scenario_set_reflection_atlas_size); ClassDB::bind_method(D_METHOD("scenario_set_fallback_environment", "scenario", "environment"), &VisualServer::scenario_set_fallback_environment); +#ifndef _3D_DISABLED + ClassDB::bind_method(D_METHOD("instance_create2", "base", "scenario"), &VisualServer::instance_create2); ClassDB::bind_method(D_METHOD("instance_create"), &VisualServer::instance_create); ClassDB::bind_method(D_METHOD("instance_set_base", "instance", "base"), &VisualServer::instance_set_base); @@ -1806,7 +1947,7 @@ void VisualServer::_bind_methods() { ClassDB::bind_method(D_METHOD("instances_cull_aabb", "aabb", "scenario"), &VisualServer::_instances_cull_aabb_bind, DEFVAL(RID())); ClassDB::bind_method(D_METHOD("instances_cull_ray", "from", "to", "scenario"), &VisualServer::_instances_cull_ray_bind, DEFVAL(RID())); ClassDB::bind_method(D_METHOD("instances_cull_convex", "convex", "scenario"), &VisualServer::_instances_cull_convex_bind, DEFVAL(RID())); - +#endif ClassDB::bind_method(D_METHOD("canvas_create"), &VisualServer::canvas_create); ClassDB::bind_method(D_METHOD("canvas_set_item_mirroring", "canvas", "item", "mirroring"), &VisualServer::canvas_set_item_mirroring); ClassDB::bind_method(D_METHOD("canvas_set_modulate", "canvas", "color"), &VisualServer::canvas_set_modulate); @@ -1889,13 +2030,14 @@ void VisualServer::_bind_methods() { ClassDB::bind_method(D_METHOD("init"), &VisualServer::init); ClassDB::bind_method(D_METHOD("finish"), &VisualServer::finish); ClassDB::bind_method(D_METHOD("get_render_info", "info"), &VisualServer::get_render_info); +#ifndef _3D_DISABLED + ClassDB::bind_method(D_METHOD("make_sphere_mesh", "latitudes", "longitudes", "radius"), &VisualServer::make_sphere_mesh); ClassDB::bind_method(D_METHOD("get_test_cube"), &VisualServer::get_test_cube); +#endif ClassDB::bind_method(D_METHOD("get_test_texture"), &VisualServer::get_test_texture); ClassDB::bind_method(D_METHOD("get_white_texture"), &VisualServer::get_white_texture); - ClassDB::bind_method(D_METHOD("make_sphere_mesh", "latitudes", "longitudes", "radius"), &VisualServer::make_sphere_mesh); - ClassDB::bind_method(D_METHOD("set_boot_image", "image", "color", "scale"), &VisualServer::set_boot_image); ClassDB::bind_method(D_METHOD("set_default_clear_color", "color"), &VisualServer::set_default_clear_color); @@ -2061,6 +2203,7 @@ void VisualServer::_bind_methods() { BIND_ENUM_CONSTANT(INSTANCE_GEOMETRY_MASK); BIND_ENUM_CONSTANT(INSTANCE_FLAG_USE_BAKED_LIGHT); + BIND_ENUM_CONSTANT(INSTANCE_FLAG_REDRAW_FRAME_IF_VISIBLE); BIND_ENUM_CONSTANT(INSTANCE_FLAG_MAX); BIND_ENUM_CONSTANT(SHADOW_CASTING_SETTING_OFF); diff --git a/servers/visual_server.h b/servers/visual_server.h index 968cb852ed..367642b7d4 100644 --- a/servers/visual_server.h +++ b/servers/visual_server.h @@ -251,6 +251,10 @@ public: virtual RID mesh_create() = 0; + virtual uint32_t mesh_surface_get_format_offset(uint32_t p_format, int p_vertex_len, int p_index_len, int p_array_index) const; + virtual uint32_t mesh_surface_get_format_stride(uint32_t p_format, int p_vertex_len, int p_index_len) const; + /// Returns stride + virtual uint32_t mesh_surface_make_offsets_from_format(uint32_t p_format, int p_vertex_len, int p_index_len, uint32_t *r_offsets) const; virtual void mesh_add_surface_from_arrays(RID p_mesh, PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), uint32_t p_compress_format = ARRAY_COMPRESS_DEFAULT); virtual void mesh_add_surface(RID p_mesh, uint32_t p_format, PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes = Vector<PoolVector<uint8_t> >(), const Vector<AABB> &p_bone_aabbs = Vector<AABB>()) = 0; @@ -805,6 +809,7 @@ public: enum InstanceFlags { INSTANCE_FLAG_USE_BAKED_LIGHT, + INSTANCE_FLAG_REDRAW_FRAME_IF_VISIBLE, INSTANCE_FLAG_MAX }; |