diff options
Diffstat (limited to 'modules')
78 files changed, 2259 insertions, 123 deletions
diff --git a/modules/bullet/SCsub b/modules/bullet/SCsub index 16d694c238..2fe7a1b4c0 100644 --- a/modules/bullet/SCsub +++ b/modules/bullet/SCsub @@ -186,7 +186,11 @@ if env['builtin_bullet']: thirdparty_sources = [thirdparty_dir + file for file in bullet2_src] - env_bullet.Prepend(CPPPATH=[thirdparty_dir]) + # Treat Bullet headers as system headers to avoid raising warnings. Not supported on MSVC. + if not env.msvc: + env_bullet.Append(CPPFLAGS=['-isystem', Dir(thirdparty_dir).path]) + else: + env_bullet.Prepend(CPPPATH=[thirdparty_dir]) # if env['target'] == "debug" or env['target'] == "release_debug": # env_bullet.Append(CPPFLAGS=['-DBT_DEBUG']) diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp index be4e0b88e8..038001996d 100644 --- a/modules/bullet/bullet_physics_server.cpp +++ b/modules/bullet/bullet_physics_server.cpp @@ -267,7 +267,7 @@ RID BulletPhysicsServer::area_get_space(RID p_area) const { void BulletPhysicsServer::area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) { AreaBullet *area = area_owner.get(p_area); - ERR_FAIL_COND(!area) + ERR_FAIL_COND(!area); area->set_spOv_mode(p_mode); } diff --git a/modules/bullet/cone_twist_joint_bullet.cpp b/modules/bullet/cone_twist_joint_bullet.cpp index d9a82d6179..bc7fd52cf6 100644 --- a/modules/bullet/cone_twist_joint_bullet.cpp +++ b/modules/bullet/cone_twist_joint_bullet.cpp @@ -84,7 +84,7 @@ void ConeTwistJointBullet::set_param(PhysicsServer::ConeTwistJointParam p_param, break; default: ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated"); - WARN_DEPRECATED + WARN_DEPRECATED; break; } } diff --git a/modules/bullet/generic_6dof_joint_bullet.cpp b/modules/bullet/generic_6dof_joint_bullet.cpp index 8fed933854..0d2c46c579 100644 --- a/modules/bullet/generic_6dof_joint_bullet.cpp +++ b/modules/bullet/generic_6dof_joint_bullet.cpp @@ -175,7 +175,7 @@ void Generic6DOFJointBullet::set_param(Vector3::Axis p_axis, PhysicsServer::G6DO break; default: ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated"); - WARN_DEPRECATED + WARN_DEPRECATED; break; } } @@ -256,7 +256,7 @@ void Generic6DOFJointBullet::set_flag(Vector3::Axis p_axis, PhysicsServer::G6DOF break; default: ERR_EXPLAIN("This flag " + itos(p_flag) + " is deprecated"); - WARN_DEPRECATED + WARN_DEPRECATED; break; } } diff --git a/modules/bullet/hinge_joint_bullet.cpp b/modules/bullet/hinge_joint_bullet.cpp index 7b99d3d89f..b7e1e1a4c2 100644 --- a/modules/bullet/hinge_joint_bullet.cpp +++ b/modules/bullet/hinge_joint_bullet.cpp @@ -118,7 +118,7 @@ void HingeJointBullet::set_param(PhysicsServer::HingeJointParam p_param, real_t break; default: ERR_EXPLAIN("The HingeJoint parameter " + itos(p_param) + " is deprecated."); - WARN_DEPRECATED + WARN_DEPRECATED; break; } } diff --git a/modules/bullet/pin_joint_bullet.cpp b/modules/bullet/pin_joint_bullet.cpp index 58b090006a..c9c4d1af7e 100644 --- a/modules/bullet/pin_joint_bullet.cpp +++ b/modules/bullet/pin_joint_bullet.cpp @@ -86,7 +86,7 @@ real_t PinJointBullet::get_param(PhysicsServer::PinJointParam p_param) const { return p2pConstraint->m_setting.m_impulseClamp; default: ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated"); - WARN_DEPRECATED + WARN_DEPRECATED; return 0; } } diff --git a/modules/csg/csg.cpp b/modules/csg/csg.cpp index 3a61afa023..aa4d7d7d32 100644 --- a/modules/csg/csg.cpp +++ b/modules/csg/csg.cpp @@ -45,7 +45,7 @@ void CSGBrush::build_from_faces(const PoolVector<Vector3> &p_vertices, const Poo int vc = p_vertices.size(); - ERR_FAIL_COND((vc % 3) != 0) + ERR_FAIL_COND((vc % 3) != 0); PoolVector<Vector3>::Read rv = p_vertices.read(); int uvc = p_uvs.size(); diff --git a/modules/csg/csg_shape.h b/modules/csg/csg_shape.h index a5b2238e6b..2171f27f96 100644 --- a/modules/csg/csg_shape.h +++ b/modules/csg/csg_shape.h @@ -116,9 +116,9 @@ protected: virtual void _validate_property(PropertyInfo &property) const; +public: Array get_meshes() const; -public: void set_operation(Operation p_operation); Operation get_operation() const; diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp index 059c06c37c..50fdc8ab20 100644 --- a/modules/dds/texture_loader_dds.cpp +++ b/modules/dds/texture_loader_dds.cpp @@ -31,6 +31,8 @@ #include "texture_loader_dds.h" #include "core/os/file_access.h" +#define PF_FOURCC(s) (((s)[3] << 24U) | ((s)[2] << 16U) | ((s)[1] << 8U) | ((s)[0])) + enum { DDS_MAGIC = 0x20534444, DDSD_CAPS = 0x00000001, @@ -51,6 +53,7 @@ enum DDSFormat { DDS_DXT5, DDS_ATI1, DDS_ATI2, + DDS_A2XY, DDS_BGRA8, DDS_BGR8, DDS_RGBA8, //flipped in dds @@ -74,9 +77,12 @@ struct DDSFormatInfo { }; static const DDSFormatInfo dds_format_info[DDS_MAX] = { - { "DXT1", true, false, 4, 8, Image::FORMAT_DXT1 }, - { "DXT3", true, false, 4, 16, Image::FORMAT_DXT3 }, - { "DXT5", true, false, 4, 16, Image::FORMAT_DXT5 }, + { "DXT1/BC1", true, false, 4, 8, Image::FORMAT_DXT1 }, + { "DXT3/BC2", true, false, 4, 16, Image::FORMAT_DXT3 }, + { "DXT5/BC3", true, false, 4, 16, Image::FORMAT_DXT5 }, + { "ATI1/BC4", true, false, 4, 8, Image::FORMAT_RGTC_R }, + { "ATI2/3DC/BC5", true, false, 4, 16, Image::FORMAT_RGTC_RG }, + { "A2XY/DXN/BC5", true, false, 4, 16, Image::FORMAT_RGTC_RG }, { "BGRA8", false, false, 1, 4, Image::FORMAT_RGBA8 }, { "BGR8", false, false, 1, 3, Image::FORMAT_RGB8 }, { "RGBA8", false, false, 1, 4, Image::FORMAT_RGBA8 }, @@ -158,22 +164,25 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, DDSFormat dds_format; - if (format_flags & DDPF_FOURCC && format_fourcc == 0x31545844) { //'1TXD' + if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("DXT1")) { dds_format = DDS_DXT1; - } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x33545844) { //'3TXD' + } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("DXT3")) { dds_format = DDS_DXT3; - } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x35545844) { //'5TXD' + } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("DXT5")) { dds_format = DDS_DXT5; - } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x31495441) { //'1ITA' + } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("ATI1")) { dds_format = DDS_ATI1; - } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x32495441) { //'2ITA' + } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("ATI2")) { dds_format = DDS_ATI2; + } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("A2XY")) { + + dds_format = DDS_A2XY; } else if (format_flags & DDPF_RGB && format_flags & DDPF_ALPHAPIXELS && format_rgb_bits == 32 && format_red_mask == 0xff0000 && format_green_mask == 0xff00 && format_blue_mask == 0xff && format_alpha_mask == 0xff000000) { diff --git a/modules/dds/texture_loader_dds.h b/modules/dds/texture_loader_dds.h index 585f2891bf..6ddef4e770 100644 --- a/modules/dds/texture_loader_dds.h +++ b/modules/dds/texture_loader_dds.h @@ -35,7 +35,6 @@ #include "scene/resources/texture.h" class ResourceFormatDDS : public ResourceFormatLoader { - GDCLASS(ResourceFormatDDS, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp index 18dfe08e85..dcb4b7fd75 100644 --- a/modules/enet/networked_multiplayer_enet.cpp +++ b/modules/enet/networked_multiplayer_enet.cpp @@ -80,6 +80,7 @@ Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int ERR_FAIL_COND_V(p_out_bandwidth < 0, ERR_INVALID_PARAMETER); ENetAddress address; + memset(&address, 0, sizeof(address)); #ifdef GODOT_ENET if (bind_ip.is_wildcard()) { @@ -346,7 +347,7 @@ void NetworkedMultiplayerENet::poll() { uint32_t *id = (uint32_t *)event.peer->data; - ERR_CONTINUE(event.packet->dataLength < 8) + ERR_CONTINUE(event.packet->dataLength < 8); uint32_t source = decode_uint32(&event.packet->data[0]); int target = decode_uint32(&event.packet->data[4]); @@ -462,7 +463,7 @@ void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) { ERR_FAIL_COND(!active); ERR_FAIL_COND(!is_server()); - ERR_FAIL_COND(!peer_map.has(p_peer)) + ERR_FAIL_COND(!peer_map.has(p_peer)); if (now) { enet_peer_disconnect_now(peer_map[p_peer], 0); diff --git a/modules/etc/texture_loader_pkm.h b/modules/etc/texture_loader_pkm.h index 860fe8b5df..79c17953fc 100644 --- a/modules/etc/texture_loader_pkm.h +++ b/modules/etc/texture_loader_pkm.h @@ -35,7 +35,6 @@ #include "scene/resources/texture.h" class ResourceFormatPKM : public ResourceFormatLoader { - GDCLASS(ResourceFormatPKM, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; diff --git a/modules/gdnative/android/android_gdn.cpp b/modules/gdnative/android/android_gdn.cpp index 8657935602..624ef19dec 100644 --- a/modules/gdnative/android/android_gdn.cpp +++ b/modules/gdnative/android/android_gdn.cpp @@ -34,6 +34,8 @@ // These entry points are only for the android platform and are simple stubs in all others. #ifdef __ANDROID__ +#include "platform/android/java_godot_wrapper.h" +#include "platform/android/os_android.h" #include "platform/android/thread_jandroid.h" #else #define JNIEnv void @@ -54,20 +56,31 @@ JNIEnv *GDAPI godot_android_get_env() { jobject GDAPI godot_android_get_activity() { #ifdef __ANDROID__ - JNIEnv *env = ThreadAndroid::get_env(); - - jclass activityThread = env->FindClass("android/app/ActivityThread"); - jmethodID currentActivityThread = env->GetStaticMethodID(activityThread, "currentActivityThread", "()Landroid/app/ActivityThread;"); - jobject at = env->CallStaticObjectMethod(activityThread, currentActivityThread); - jmethodID getApplication = env->GetMethodID(activityThread, "getApplication", "()Landroid/app/Application;"); - jobject context = env->CallObjectMethod(at, getApplication); + OS_Android *os_android = (OS_Android *)OS::get_singleton(); + return os_android->get_godot_java()->get_activity(); +#else + return NULL; +#endif +} - return env->NewGlobalRef(context); +jobject GDAPI godot_android_get_surface() { +#ifdef __ANDROID__ + OS_Android *os_android = (OS_Android *)OS::get_singleton(); + return os_android->get_godot_java()->get_surface(); #else return NULL; #endif } +bool GDAPI godot_android_is_activity_resumed() { +#ifdef __ANDROID__ + OS_Android *os_android = (OS_Android *)OS::get_singleton(); + return os_android->get_godot_java()->is_activity_resumed(); +#else + return false; +#endif +} + #ifdef __cplusplus } #endif
\ No newline at end of file diff --git a/modules/gdnative/arvr/arvr_interface_gdnative.cpp b/modules/gdnative/arvr/arvr_interface_gdnative.cpp index c3f8688adb..da01f573ce 100644 --- a/modules/gdnative/arvr/arvr_interface_gdnative.cpp +++ b/modules/gdnative/arvr/arvr_interface_gdnative.cpp @@ -115,6 +115,17 @@ void ARVRInterfaceGDNative::set_anchor_detection_is_enabled(bool p_enable) { interface->set_anchor_detection_is_enabled(data, p_enable); } +int ARVRInterfaceGDNative::get_camera_feed_id() { + + ERR_FAIL_COND_V(interface == NULL, 0); + + if ((interface->version.major > 1) || ((interface->version.major) == 1 && (interface->version.minor >= 1))) { + return (unsigned int)interface->get_camera_feed_id(data); + } else { + return 0; + } +} + bool ARVRInterfaceGDNative::is_stereo() { bool stereo; diff --git a/modules/gdnative/arvr/arvr_interface_gdnative.h b/modules/gdnative/arvr/arvr_interface_gdnative.h index 86396b067a..e0e5b67849 100644 --- a/modules/gdnative/arvr/arvr_interface_gdnative.h +++ b/modules/gdnative/arvr/arvr_interface_gdnative.h @@ -66,6 +66,7 @@ public: /** specific to AR **/ virtual bool get_anchor_detection_is_enabled() const; virtual void set_anchor_detection_is_enabled(bool p_enable); + virtual int get_camera_feed_id(); /** rendering and internal **/ virtual Size2 get_render_targetsize(); diff --git a/modules/gdnative/config.py b/modules/gdnative/config.py index 7898de5523..b9e5afcdf3 100644 --- a/modules/gdnative/config.py +++ b/modules/gdnative/config.py @@ -6,6 +6,7 @@ def configure(env): def get_doc_classes(): return [ + "@NativeScript", "ARVRInterfaceGDNative", "GDNative", "GDNativeLibrary", @@ -13,7 +14,6 @@ def get_doc_classes(): "NativeScript", "PacketPeerGDNative", "PluginScript", - "ResourceFormatLoaderVideoStreamGDNative", "StreamPeerGDNative", "VideoStreamGDNative", "WebRTCPeerConnectionGDNative", diff --git a/modules/stb_vorbis/doc_classes/ResourceImporterOGGVorbis.xml b/modules/gdnative/doc_classes/@NativeScript.xml index 4dd77fed34..cb5de198ac 100644 --- a/modules/stb_vorbis/doc_classes/ResourceImporterOGGVorbis.xml +++ b/modules/gdnative/doc_classes/@NativeScript.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="ResourceImporterOGGVorbis" inherits="ResourceImporter" category="Core" version="3.2"> +<class name="@NativeScript" category="Core" version="3.2"> <brief_description> </brief_description> <description> diff --git a/modules/gdnative/gdnative.h b/modules/gdnative/gdnative.h index ef57387059..1590994ab4 100644 --- a/modules/gdnative/gdnative.h +++ b/modules/gdnative/gdnative.h @@ -165,7 +165,6 @@ public: }; class GDNativeLibraryResourceLoader : public ResourceFormatLoader { - GDCLASS(GDNativeLibraryResourceLoader, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path, Error *r_error); virtual void get_recognized_extensions(List<String> *p_extensions) const; @@ -174,7 +173,6 @@ public: }; class GDNativeLibraryResourceSaver : public ResourceFormatSaver { - GDCLASS(GDNativeLibraryResourceSaver, ResourceFormatSaver) public: virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags); virtual bool recognize(const RES &p_resource) const; diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json index 52c989037e..6c12ee6534 100644 --- a/modules/gdnative/gdnative_api.json +++ b/modules/gdnative/gdnative_api.json @@ -6304,7 +6304,7 @@ "type": "ANDROID", "version": { "major": 1, - "minor": 0 + "minor": 1 }, "next": null, "api": [ @@ -6319,6 +6319,18 @@ "return_type": "jobject", "arguments": [ ] + }, + { + "name": "godot_android_get_surface", + "return_type": "jobject", + "arguments": [ + ] + }, + { + "name": "godot_android_is_activity_resumed", + "return_type": "bool", + "arguments": [ + ] } ] }, diff --git a/modules/gdnative/include/android/godot_android.h b/modules/gdnative/include/android/godot_android.h index 32e86838be..7063e1d2c5 100644 --- a/modules/gdnative/include/android/godot_android.h +++ b/modules/gdnative/include/android/godot_android.h @@ -46,6 +46,8 @@ extern "C" { JNIEnv *GDAPI godot_android_get_env(); jobject GDAPI godot_android_get_activity(); +jobject GDAPI godot_android_get_surface(); +bool GDAPI godot_android_is_activity_resumed(); #ifdef __cplusplus } diff --git a/modules/gdnative/include/arvr/godot_arvr.h b/modules/gdnative/include/arvr/godot_arvr.h index 657090fa70..d465bbde54 100644 --- a/modules/gdnative/include/arvr/godot_arvr.h +++ b/modules/gdnative/include/arvr/godot_arvr.h @@ -64,6 +64,7 @@ typedef struct { // only in 1.1 onwards godot_int (*get_external_texture_for_eye)(void *, godot_int); void (*notification)(void *, godot_int); + godot_int (*get_camera_feed_id)(void *); } godot_arvr_interface_gdnative; void GDAPI godot_arvr_register_interface(const godot_arvr_interface_gdnative *p_interface); diff --git a/modules/gdnative/nativescript/nativescript.h b/modules/gdnative/nativescript/nativescript.h index be1c499714..d60e3ae1ae 100644 --- a/modules/gdnative/nativescript/nativescript.h +++ b/modules/gdnative/nativescript/nativescript.h @@ -382,7 +382,6 @@ public: }; class ResourceFormatLoaderNativeScript : public ResourceFormatLoader { - GDCLASS(ResourceFormatLoaderNativeScript, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; @@ -391,7 +390,6 @@ public: }; class ResourceFormatSaverNativeScript : public ResourceFormatSaver { - GDCLASS(ResourceFormatSaverNativeScript, ResourceFormatSaver) virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); virtual bool recognize(const RES &p_resource) const; virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; diff --git a/modules/gdnative/pluginscript/pluginscript_loader.h b/modules/gdnative/pluginscript/pluginscript_loader.h index 69a2ac6bfe..6218037a15 100644 --- a/modules/gdnative/pluginscript/pluginscript_loader.h +++ b/modules/gdnative/pluginscript/pluginscript_loader.h @@ -40,8 +40,6 @@ class PluginScriptLanguage; class ResourceFormatLoaderPluginScript : public ResourceFormatLoader { - GDCLASS(ResourceFormatLoaderPluginScript, ResourceFormatLoader) - PluginScriptLanguage *_language; public: @@ -54,8 +52,6 @@ public: class ResourceFormatSaverPluginScript : public ResourceFormatSaver { - GDCLASS(ResourceFormatSaverPluginScript, ResourceFormatSaver) - PluginScriptLanguage *_language; public: diff --git a/modules/gdnative/pluginscript/pluginscript_script.cpp b/modules/gdnative/pluginscript/pluginscript_script.cpp index 8dbbd2e4eb..1d6f9db349 100644 --- a/modules/gdnative/pluginscript/pluginscript_script.cpp +++ b/modules/gdnative/pluginscript/pluginscript_script.cpp @@ -39,12 +39,12 @@ #define ASSERT_SCRIPT_VALID() \ { \ ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \ - ERR_FAIL_COND(!can_instance()) \ + ERR_FAIL_COND(!can_instance()); \ } -#define ASSERT_SCRIPT_VALID_V(ret) \ - { \ - ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \ - ERR_FAIL_COND_V(!can_instance(), ret) \ +#define ASSERT_SCRIPT_VALID_V(ret) \ + { \ + ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \ + ERR_FAIL_COND_V(!can_instance(), ret); \ } #else #define ASSERT_SCRIPT_VALID() @@ -77,7 +77,7 @@ PluginScriptInstance *PluginScript::_create_instance(const Variant **p_args, int // There is currently no way to get the constructor function name of the script. // instance->call("__init__", p_args, p_argcount, r_error); if (p_argcount > 0) { - WARN_PRINT("PluginScript doesn't support arguments in the constructor") + WARN_PRINT("PluginScript doesn't support arguments in the constructor"); } return instance; diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.h b/modules/gdnative/videodecoder/video_stream_gdnative.h index aafd02f33d..b9f1c8e4da 100644 --- a/modules/gdnative/videodecoder/video_stream_gdnative.h +++ b/modules/gdnative/videodecoder/video_stream_gdnative.h @@ -197,7 +197,6 @@ public: }; class ResourceFormatLoaderVideoStreamGDNative : public ResourceFormatLoader { - GDCLASS(ResourceFormatLoaderVideoStreamGDNative, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; diff --git a/modules/gdscript/config.py b/modules/gdscript/config.py index 95b40d90af..a525eedaaa 100644 --- a/modules/gdscript/config.py +++ b/modules/gdscript/config.py @@ -6,6 +6,7 @@ def configure(env): def get_doc_classes(): return [ + "@GDScript", "GDScript", "GDScriptFunctionState", "GDScriptNativeClass", diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml new file mode 100644 index 0000000000..b6de5dbf62 --- /dev/null +++ b/modules/gdscript/doc_classes/@GDScript.xml @@ -0,0 +1,1301 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="@GDScript" category="Core" version="3.2"> + <brief_description> + Built-in GDScript functions. + </brief_description> + <description> + List of core built-in GDScript functions. Math functions and other utilities. Everything else is provided by objects. (Keywords: builtin, built in, global functions.) + </description> + <tutorials> + </tutorials> + <methods> + <method name="Color8"> + <return type="Color"> + </return> + <argument index="0" name="r8" type="int"> + </argument> + <argument index="1" name="g8" type="int"> + </argument> + <argument index="2" name="b8" type="int"> + </argument> + <argument index="3" name="a8" type="int" default="255"> + </argument> + <description> + Returns a 32 bit color with red, green, blue and alpha channels. Each channel has 8 bits of information ranging from 0 to 255. + [code]r8[/code] red channel + [code]g8[/code] green channel + [code]b8[/code] blue channel + [code]a8[/code] alpha channel + [codeblock] + red = Color8(255, 0, 0) + [/codeblock] + </description> + </method> + <method name="ColorN"> + <return type="Color"> + </return> + <argument index="0" name="name" type="String"> + </argument> + <argument index="1" name="alpha" type="float" default="1.0"> + </argument> + <description> + Returns a color according to the standardised [code]name[/code] with [code]alpha[/code] ranging from 0 to 1. + [codeblock] + red = ColorN("red", 1) + [/codeblock] + Supported color names: + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflower", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "webgray", "green", "webgreen", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrod", "lightgray", "lightgreen", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "webmaroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navyblue", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "webpurple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen". + </description> + </method> + <method name="abs"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the absolute value of parameter [code]s[/code] (i.e. unsigned value, works for integer and float). + [codeblock] + # a is 1 + a = abs(-1) + [/codeblock] + </description> + </method> + <method name="acos"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the arc cosine of [code]s[/code] in radians. Use to get the angle of cosine [code]s[/code]. + [codeblock] + # c is 0.523599 or 30 degrees if converted with rad2deg(s) + c = acos(0.866025) + [/codeblock] + </description> + </method> + <method name="asin"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the arc sine of [code]s[/code] in radians. Use to get the angle of sine [code]s[/code]. + [codeblock] + # s is 0.523599 or 30 degrees if converted with rad2deg(s) + s = asin(0.5) + [/codeblock] + </description> + </method> + <method name="assert"> + <return type="void"> + </return> + <argument index="0" name="condition" type="bool"> + </argument> + <description> + Asserts that the [code]condition[/code] is [code]true[/code] . If the [code]condition[/code] is [code]false[/code], an error is generated and the program is halted until you resume it. Only executes in debug builds, or when running the game from the editor. Use it for debugging purposes, to make sure a statement is [code]true[/code] during development. + [codeblock] + # Imagine we always want speed to be between 0 and 20 + speed = -10 + assert(speed < 20) # True, the program will continue + assert(speed >= 0) # False, the program will stop + assert(speed >= 0 && speed < 20) # You can also combine the two conditional statements in one check + [/codeblock] + </description> + </method> + <method name="atan"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the arc tangent of [code]s[/code] in radians. Use it to get the angle from an angle's tangent in trigonometry: [code]atan(tan(angle)) == angle[/code]. + The method cannot know in which quadrant the angle should fall. See [method atan2] if you always want an exact angle. + [codeblock] + a = atan(0.5) # a is 0.463648 + [/codeblock] + </description> + </method> + <method name="atan2"> + <return type="float"> + </return> + <argument index="0" name="y" type="float"> + </argument> + <argument index="1" name="x" type="float"> + </argument> + <description> + Returns the arc tangent of [code]y/x[/code] in radians. Use to get the angle of tangent [code]y/x[/code]. To compute the value, the method takes into account the sign of both arguments in order to determine the quadrant. + [codeblock] + a = atan2(0, -1) # a is 3.141593 + [/codeblock] + </description> + </method> + <method name="bytes2var"> + <return type="Variant"> + </return> + <argument index="0" name="bytes" type="PoolByteArray"> + </argument> + <argument index="1" name="allow_objects" type="bool" default="false"> + </argument> + <description> + Decodes a byte array back to a value. When [code]allow_objects[/code] is [code]true[/code] decoding objects is allowed. + [b]WARNING:[/b] Deserialized object can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats (remote code execution). + </description> + </method> + <method name="cartesian2polar"> + <return type="Vector2"> + </return> + <argument index="0" name="x" type="float"> + </argument> + <argument index="1" name="y" type="float"> + </argument> + <description> + Converts a 2D point expressed in the cartesian coordinate system (x and y axis) to the polar coordinate system (a distance from the origin and an angle). + </description> + </method> + <method name="ceil"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Rounds [code]s[/code] upward, returning the smallest integral value that is not less than [code]s[/code]. + [codeblock] + i = ceil(1.45) # i is 2 + i = ceil(1.001) # i is 2 + [/codeblock] + </description> + </method> + <method name="char"> + <return type="String"> + </return> + <argument index="0" name="ascii" type="int"> + </argument> + <description> + Returns a character as a String of the given ASCII code. + [codeblock] + # a is 'A' + a = char(65) + # a is 'a' + a = char(65 + 32) + [/codeblock] + </description> + </method> + <method name="clamp"> + <return type="float"> + </return> + <argument index="0" name="value" type="float"> + </argument> + <argument index="1" name="min" type="float"> + </argument> + <argument index="2" name="max" type="float"> + </argument> + <description> + Clamps [code]value[/code] and returns a value not less than [code]min[/code] and not more than [code]max[/code]. + [codeblock] + speed = 1000 + # a is 20 + a = clamp(speed, 1, 20) + + speed = -10 + # a is 1 + a = clamp(speed, 1, 20) + [/codeblock] + </description> + </method> + <method name="convert"> + <return type="Variant"> + </return> + <argument index="0" name="what" type="Variant"> + </argument> + <argument index="1" name="type" type="int"> + </argument> + <description> + Converts from a type to another in the best way possible. The [code]type[/code] parameter uses the enum TYPE_* in [@GlobalScope]. + [codeblock] + a = Vector2(1, 0) + # prints 1 + print(a.length()) + a = convert(a, TYPE_STRING) + # prints 6 + # (1, 0) is 6 characters + print(a.length()) + [/codeblock] + </description> + </method> + <method name="cos"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the cosine of angle [code]s[/code] in radians. + [codeblock] + # prints 1 and -1 + print(cos(PI * 2)) + print(cos(PI)) + [/codeblock] + </description> + </method> + <method name="cosh"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the hyperbolic cosine of [code]s[/code] in radians. + [codeblock] + # prints 1.543081 + print(cosh(1)) + [/codeblock] + </description> + </method> + <method name="db2linear"> + <return type="float"> + </return> + <argument index="0" name="db" type="float"> + </argument> + <description> + Converts from decibels to linear energy (audio). + </description> + </method> + <method name="decimals"> + <return type="int"> + </return> + <argument index="0" name="step" type="float"> + </argument> + <description> + Deprecated alias for "[method step_decimals]". + </description> + </method> + <method name="dectime"> + <return type="float"> + </return> + <argument index="0" name="value" type="float"> + </argument> + <argument index="1" name="amount" type="float"> + </argument> + <argument index="2" name="step" type="float"> + </argument> + <description> + Returns the result of [code]value[/code] decreased by [code]step[/code] * [code]amount[/code]. + [codeblock] + # a = 59 + a = dectime(60, 10, 0.1)) + [/codeblock] + </description> + </method> + <method name="deg2rad"> + <return type="float"> + </return> + <argument index="0" name="deg" type="float"> + </argument> + <description> + Returns degrees converted to radians. + [codeblock] + # r is 3.141593 + r = deg2rad(180) + [/codeblock] + </description> + </method> + <method name="dict2inst"> + <return type="Object"> + </return> + <argument index="0" name="dict" type="Dictionary"> + </argument> + <description> + Converts a previously converted instance to a dictionary, back into an instance. Useful for deserializing. + </description> + </method> + <method name="ease"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <argument index="1" name="curve" type="float"> + </argument> + <description> + Easing function, based on exponent. 0 is constant, 1 is linear, 0 to 1 is ease-in, 1+ is ease out. Negative values are in-out/out in. + </description> + </method> + <method name="exp"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + The natural exponential function. It raises the mathematical constant [b]e[/b] to the power of [code]s[/code] and returns it. + [b]e[/b] has an approximate value of 2.71828. + [codeblock] + a = exp(2) # approximately 7.39 + [/codeblock] + </description> + </method> + <method name="floor"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Rounds [code]s[/code] to the closest smaller integer and returns it. + [codeblock] + # a is 2 + a = floor(2.99) + # a is -3 + a = floor(-2.99) + [/codeblock] + </description> + </method> + <method name="fmod"> + <return type="float"> + </return> + <argument index="0" name="x" type="float"> + </argument> + <argument index="1" name="y" type="float"> + </argument> + <description> + Returns the floating-point remainder of [code]x/y[/code]. + [codeblock] + # remainder is 1.5 + var remainder = fmod(7, 5.5) + [/codeblock] + </description> + </method> + <method name="fposmod"> + <return type="float"> + </return> + <argument index="0" name="x" type="float"> + </argument> + <argument index="1" name="y" type="float"> + </argument> + <description> + Returns the floating-point remainder of [code]x/y[/code] that wraps equally in positive and negative. + [codeblock] + var i = -10 + while i < 0: + prints(i, fposmod(i, 10)) + i += 1 + [/codeblock] + Produces: + [codeblock] + -10 10 + -9 1 + -8 2 + -7 3 + -6 4 + -5 5 + -4 6 + -3 7 + -2 8 + -1 9 + [/codeblock] + </description> + </method> + <method name="funcref"> + <return type="FuncRef"> + </return> + <argument index="0" name="instance" type="Object"> + </argument> + <argument index="1" name="funcname" type="String"> + </argument> + <description> + Returns a reference to the specified function [code]funcname[/code] in the [code]instance[/code] node. As functions aren't first-class objects in GDscript, use [code]funcref[/code] to store a [FuncRef] in a variable and call it later. + [codeblock] + func foo(): + return("bar") + + a = funcref(self, "foo") + print(a.call_func()) # prints bar + [/codeblock] + </description> + </method> + <method name="get_stack"> + <return type="Array"> + </return> + <description> + Returns an array of dictionaries representing the current call stack. + [codeblock] + func _ready(): + foo() + + func foo(): + bar() + + func bar(): + print(get_stack()) + [/codeblock] + would print + [codeblock] + [{function:bar, line:12, source:res://script.gd}, {function:foo, line:9, source:res://script.gd}, {function:_ready, line:6, source:res://script.gd}] + [/codeblock] + </description> + </method> + <method name="hash"> + <return type="int"> + </return> + <argument index="0" name="var" type="Variant"> + </argument> + <description> + Returns the integer hash of the variable passed. + [codeblock] + print(hash("a")) # prints 177670 + [/codeblock] + </description> + </method> + <method name="inst2dict"> + <return type="Dictionary"> + </return> + <argument index="0" name="inst" type="Object"> + </argument> + <description> + Returns the passed instance converted to a dictionary (useful for serializing). + [codeblock] + var foo = "bar" + func _ready(): + var d = inst2dict(self) + print(d.keys()) + print(d.values()) + [/codeblock] + Prints out: + [codeblock] + [@subpath, @path, foo] + [, res://test.gd, bar] + [/codeblock] + </description> + </method> + <method name="instance_from_id"> + <return type="Object"> + </return> + <argument index="0" name="instance_id" type="int"> + </argument> + <description> + Returns the Object that corresponds to [code]instance_id[/code]. All Objects have a unique instance ID. + [codeblock] + var foo = "bar" + func _ready(): + var id = get_instance_id() + var inst = instance_from_id(id) + print(inst.foo) # prints bar + [/codeblock] + </description> + </method> + <method name="inverse_lerp"> + <return type="float"> + </return> + <argument index="0" name="from" type="float"> + </argument> + <argument index="1" name="to" type="float"> + </argument> + <argument index="2" name="weight" type="float"> + </argument> + <description> + Returns a normalized value considering the given range. + [codeblock] + inverse_lerp(3, 5, 4) # returns 0.5 + [/codeblock] + </description> + </method> + <method name="is_equal_approx"> + <return type="bool"> + </return> + <argument index="0" name="a" type="float"> + </argument> + <argument index="1" name="b" type="float"> + </argument> + <description> + Returns True/False whether [code]a[/code] and [code]b[/code] are approximately equal to each other. + </description> + </method> + <method name="is_inf"> + <return type="bool"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns whether [code]s[/code] is an infinity value (either positive infinity or negative infinity). + </description> + </method> + <method name="is_instance_valid"> + <return type="bool"> + </return> + <argument index="0" name="instance" type="Object"> + </argument> + <description> + Returns whether [code]instance[/code] is a valid object (e.g. has not been deleted from memory). + </description> + </method> + <method name="is_nan"> + <return type="bool"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns whether [code]s[/code] is a NaN (Not-A-Number) value. + </description> + </method> + <method name="is_zero_approx"> + <return type="bool"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns True/False whether [code]s[/code] is zero or almost zero. + </description> + </method> + <method name="len"> + <return type="int"> + </return> + <argument index="0" name="var" type="Variant"> + </argument> + <description> + Returns length of Variant [code]var[/code]. Length is the character count of String, element count of Array, size of Dictionary, etc. + [b]Note:[/b] Generates a fatal error if Variant can not provide a length. + [codeblock] + a = [1, 2, 3, 4] + len(a) # returns 4 + [/codeblock] + </description> + </method> + <method name="lerp"> + <return type="Variant"> + </return> + <argument index="0" name="from" type="Variant"> + </argument> + <argument index="1" name="to" type="Variant"> + </argument> + <argument index="2" name="weight" type="float"> + </argument> + <description> + Linearly interpolates between two values by a normalized value. + If the [code]from[/code] and [code]to[/code] arguments are of type [int] or [float], the return value is a [float]. + If both are of the same vector type ([Vector2], [Vector3] or [Color]), the return value will be of the same type ([code]lerp[/code] then calls the vector type's [code]linear_interpolate[/code] method). + [codeblock] + lerp(0, 4, 0.75) # returns 3.0 + lerp(Vector2(1, 5), Vector2(3, 2), 0.5) # returns Vector2(2, 3.5) + [/codeblock] + </description> + </method> + <method name="linear2db"> + <return type="float"> + </return> + <argument index="0" name="nrg" type="float"> + </argument> + <description> + Converts from linear energy to decibels (audio). + </description> + </method> + <method name="load"> + <return type="Resource"> + </return> + <argument index="0" name="path" type="String"> + </argument> + <description> + Loads a resource from the filesystem located at [code]path[/code]. + [b]Note:[/b] Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing "Copy Path". + [codeblock] + # load a scene called main located in the root of the project directory + var main = load("res://main.tscn") + [/codeblock] + </description> + </method> + <method name="log"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Natural logarithm. The amount of time needed to reach a certain level of continuous growth. + [b]Note:[/b] This is not the same as the log function on your calculator which is a base 10 logarithm. + [codeblock] + log(10) # returns 2.302585 + [/codeblock] + </description> + </method> + <method name="max"> + <return type="float"> + </return> + <argument index="0" name="a" type="float"> + </argument> + <argument index="1" name="b" type="float"> + </argument> + <description> + Returns the maximum of two values. + [codeblock] + max(1, 2) # returns 2 + max(-3.99, -4) # returns -3.99 + [/codeblock] + </description> + </method> + <method name="min"> + <return type="float"> + </return> + <argument index="0" name="a" type="float"> + </argument> + <argument index="1" name="b" type="float"> + </argument> + <description> + Returns the minimum of two values. + [codeblock] + min(1, 2) # returns 1 + min(-3.99, -4) # returns -4 + [/codeblock] + </description> + </method> + <method name="move_toward"> + <return type="float"> + </return> + <argument index="0" name="from" type="float"> + </argument> + <argument index="1" name="to" type="float"> + </argument> + <argument index="2" name="delta" type="float"> + </argument> + <description> + Moves [code]from[/code] toward [code]to[/code] by the [code]delta[/code] value. + Use a negative [code]delta[/code] value to move away. + [codeblock] + move_toward(10, 5, 4) # returns 6 + [/codeblock] + </description> + </method> + <method name="nearest_po2"> + <return type="int"> + </return> + <argument index="0" name="value" type="int"> + </argument> + <description> + Returns the nearest larger power of 2 for integer [code]value[/code]. + [codeblock] + nearest_po2(3) # returns 4 + nearest_po2(4) # returns 4 + nearest_po2(5) # returns 8 + [/codeblock] + </description> + </method> + <method name="parse_json"> + <return type="Variant"> + </return> + <argument index="0" name="json" type="String"> + </argument> + <description> + Parse JSON text to a Variant (use [method typeof] to check if it is what you expect). + Be aware that the JSON specification does not define integer or float types, but only a number type. Therefore, parsing a JSON text will convert all numerical values to [float] types. + Note that JSON objects do not preserve key order like Godot dictionaries, thus you should not rely on keys being in a certain order if a dictionary is constructed from JSON. In contrast, JSON arrays retain the order of their elements: + [codeblock] + p = parse_json('["a", "b", "c"]') + if typeof(p) == TYPE_ARRAY: + print(p[0]) # prints a + else: + print("unexpected results") + [/codeblock] + </description> + </method> + <method name="polar2cartesian"> + <return type="Vector2"> + </return> + <argument index="0" name="r" type="float"> + </argument> + <argument index="1" name="th" type="float"> + </argument> + <description> + Converts a 2D point expressed in the polar coordinate system (a distance from the origin [code]r[/code] and an angle [code]th[/code]) to the cartesian coordinate system (x and y axis). + </description> + </method> + <method name="pow"> + <return type="float"> + </return> + <argument index="0" name="x" type="float"> + </argument> + <argument index="1" name="y" type="float"> + </argument> + <description> + Returns the result of [code]x[/code] raised to the power of [code]y[/code]. + [codeblock] + pow(2, 5) # returns 32 + [/codeblock] + </description> + </method> + <method name="preload"> + <return type="Resource"> + </return> + <argument index="0" name="path" type="String"> + </argument> + <description> + Returns a resource from the filesystem that is loaded during script parsing. + [b]Note:[/b] Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing "Copy Path". + [codeblock] + # load a scene called main located in the root of the project directory + var main = preload("res://main.tscn") + [/codeblock] + </description> + </method> + <method name="print" qualifiers="vararg"> + <return type="void"> + </return> + <description> + Converts one or more arguments to strings in the best way possible and prints them to the console. + [codeblock] + a = [1, 2, 3] + print("a", "b", a) # prints ab[1, 2, 3] + [/codeblock] + </description> + </method> + <method name="print_debug" qualifiers="vararg"> + <return type="void"> + </return> + <description> + Like [method print], but prints only when used in debug mode. + </description> + </method> + <method name="print_stack"> + <return type="void"> + </return> + <description> + Prints a stack track at code location, only works when running with debugger turned on. + Output in the console would look something like this: + [codeblock] + Frame 0 - res://test.gd:16 in function '_process' + [/codeblock] + </description> + </method> + <method name="printerr" qualifiers="vararg"> + <return type="void"> + </return> + <description> + Prints one or more arguments to strings in the best way possible to standard error line. + [codeblock] + printerr("prints to stderr") + [/codeblock] + </description> + </method> + <method name="printraw" qualifiers="vararg"> + <return type="void"> + </return> + <description> + Prints one or more arguments to strings in the best way possible to console. No newline is added at the end. + [codeblock] + printraw("A") + printraw("B") + # prints AB + [/codeblock] + </description> + </method> + <method name="prints" qualifiers="vararg"> + <return type="void"> + </return> + <description> + Prints one or more arguments to the console with a space between each argument. + [codeblock] + prints("A", "B", "C") # prints A B C + [/codeblock] + </description> + </method> + <method name="printt" qualifiers="vararg"> + <return type="void"> + </return> + <description> + Prints one or more arguments to the console with a tab between each argument. + [codeblock] + printt("A", "B", "C") # prints A B C + [/codeblock] + </description> + </method> + <method name="push_error"> + <return type="void"> + </return> + <argument index="0" name="message" type="String"> + </argument> + <description> + Pushes an error message to Godot's built-in debugger and to the OS terminal. + [codeblock] + push_error("test error") # prints "test error" to debugger and terminal as error call + [/codeblock] + </description> + </method> + <method name="push_warning"> + <return type="void"> + </return> + <argument index="0" name="message" type="String"> + </argument> + <description> + Pushes a warning message to Godot's built-in debugger and to the OS terminal. + [codeblock] + push_warning("test warning") # prints "test warning" to debugger and terminal as warning call + [/codeblock] + </description> + </method> + <method name="rad2deg"> + <return type="float"> + </return> + <argument index="0" name="rad" type="float"> + </argument> + <description> + Converts from radians to degrees. + [codeblock] + rad2deg(0.523599) # returns 30 + [/codeblock] + </description> + </method> + <method name="rand_range"> + <return type="float"> + </return> + <argument index="0" name="from" type="float"> + </argument> + <argument index="1" name="to" type="float"> + </argument> + <description> + Random range, any floating point value between [code]from[/code] and [code]to[/code]. + [codeblock] + prints(rand_range(0, 1), rand_range(0, 1)) # prints e.g. 0.135591 0.405263 + [/codeblock] + </description> + </method> + <method name="rand_seed"> + <return type="Array"> + </return> + <argument index="0" name="seed" type="int"> + </argument> + <description> + Random from seed: pass a [code]seed[/code], and an array with both number and new seed is returned. "Seed" here refers to the internal state of the pseudo random number generator. The internal state of the current implementation is 64 bits. + </description> + </method> + <method name="randf"> + <return type="float"> + </return> + <description> + Returns a random floating point value on the interval [code][0, 1][/code]. + [codeblock] + randf() # returns e.g. 0.375671 + [/codeblock] + </description> + </method> + <method name="randi"> + <return type="int"> + </return> + <description> + Returns a random unsigned 32 bit integer. Use remainder to obtain a random value in the interval [code][0, N][/code] (where N is smaller than 2^32 -1). + [codeblock] + randi() # returns random integer between 0 and 2^32 - 1 + randi() % 20 # returns random integer between 0 and 19 + randi() % 100 # returns random integer between 0 and 99 + randi() % 100 + 1 # returns random integer between 1 and 100 + [/codeblock] + </description> + </method> + <method name="randomize"> + <return type="void"> + </return> + <description> + Randomizes the seed (or the internal state) of the random number generator. Current implementation reseeds using a number based on time. + [codeblock] + func _ready(): + randomize() + [/codeblock] + </description> + </method> + <method name="range" qualifiers="vararg"> + <return type="Array"> + </return> + <description> + Returns an array with the given range. Range can be 1 argument N (0 to N-1), two arguments (initial, final-1) or three arguments (initial, final-1, increment). + [codeblock] + for i in range(4): + print(i) + for i in range(2, 5): + print(i) + for i in range(0, 6, 2): + print(i) + [/codeblock] + Output: + [codeblock] + 0 + 1 + 2 + 3 + + 2 + 3 + 4 + + 0 + 2 + 4 + [/codeblock] + </description> + </method> + <method name="range_lerp"> + <return type="float"> + </return> + <argument index="0" name="value" type="float"> + </argument> + <argument index="1" name="istart" type="float"> + </argument> + <argument index="2" name="istop" type="float"> + </argument> + <argument index="3" name="ostart" type="float"> + </argument> + <argument index="4" name="ostop" type="float"> + </argument> + <description> + Maps a [code]value[/code] from range [code][istart, istop][/code] to [code][ostart, ostop][/code]. + [codeblock] + range_lerp(75, 0, 100, -1, 1) # returns 0.5 + [/codeblock] + </description> + </method> + <method name="round"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the integral value that is nearest to [code]s[/code], with halfway cases rounded away from zero. + [codeblock] + round(2.6) # returns 3 + [/codeblock] + </description> + </method> + <method name="seed"> + <return type="void"> + </return> + <argument index="0" name="seed" type="int"> + </argument> + <description> + Sets seed for the random number generator. + [codeblock] + my_seed = "Godot Rocks" + seed(my_seed.hash()) + [/codeblock] + </description> + </method> + <method name="sign"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the sign of [code]s[/code]: -1 or 1. Returns 0 if [code]s[/code] is 0. + [codeblock] + sign(-6) # returns -1 + sign(0) # returns 0 + sign(6) # returns 1 + [/codeblock] + </description> + </method> + <method name="sin"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the sine of angle [code]s[/code] in radians. + [codeblock] + sin(0.523599) # returns 0.5 + [/codeblock] + </description> + </method> + <method name="sinh"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the hyperbolic sine of [code]s[/code]. + [codeblock] + a = log(2.0) # returns 0.693147 + sinh(a) # returns 0.75 + [/codeblock] + </description> + </method> + <method name="smoothstep"> + <return type="float"> + </return> + <argument index="0" name="from" type="float"> + </argument> + <argument index="1" name="to" type="float"> + </argument> + <argument index="2" name="weight" type="float"> + </argument> + <description> + Returns a number smoothly interpolated between the [code]from[/code] and [code]to[/code], based on the [code]weight[/code]. Similar to [method lerp], but interpolates faster at the beginning and slower at the end. + [codeblock] + smoothstep(0, 2, 0.5) # returns 0.15 + smoothstep(0, 2, 1.0) # returns 0.5 + smoothstep(0, 2, 2.0) # returns 1.0 + [/codeblock] + </description> + </method> + <method name="sqrt"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the square root of [code]s[/code]. + [codeblock] + sqrt(9) # returns 3 + [/codeblock] + </description> + </method> + <method name="step_decimals"> + <return type="int"> + </return> + <argument index="0" name="step" type="float"> + </argument> + <description> + Returns the position of the first non-zero digit, after the decimal point. + [codeblock] + # n is 0 + n = step_decimals(5) + # n is 4 + n = step_decimals(1.0005) + # n is 9 + n = step_decimals(0.000000005) + [/codeblock] + </description> + </method> + <method name="stepify"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <argument index="1" name="step" type="float"> + </argument> + <description> + Snaps float value [code]s[/code] to a given [code]step[/code]. + </description> + </method> + <method name="str" qualifiers="vararg"> + <return type="String"> + </return> + <description> + Converts one or more arguments to string in the best way possible. + [codeblock] + var a = [10, 20, 30] + var b = str(a); + len(a) # returns 3 + len(b) # returns 12 + [/codeblock] + </description> + </method> + <method name="str2var"> + <return type="Variant"> + </return> + <argument index="0" name="string" type="String"> + </argument> + <description> + Converts a formatted string that was returned by [method var2str] to the original value. + [codeblock] + a = '{ "a": 1, "b": 2 }' + b = str2var(a) + print(b['a']) # prints 1 + [/codeblock] + </description> + </method> + <method name="tan"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the tangent of angle [code]s[/code] in radians. + [codeblock] + tan(deg2rad(45)) # returns 1 + [/codeblock] + </description> + </method> + <method name="tanh"> + <return type="float"> + </return> + <argument index="0" name="s" type="float"> + </argument> + <description> + Returns the hyperbolic tangent of [code]s[/code]. + [codeblock] + a = log(2.0) # returns 0.693147 + tanh(a) # returns 0.6 + [/codeblock] + </description> + </method> + <method name="to_json"> + <return type="String"> + </return> + <argument index="0" name="var" type="Variant"> + </argument> + <description> + Converts a Variant [code]var[/code] to JSON text and return the result. Useful for serializing data to store or send over the network. + [codeblock] + a = { 'a': 1, 'b': 2 } + b = to_json(a) + print(b) # {"a":1, "b":2} + [/codeblock] + </description> + </method> + <method name="type_exists"> + <return type="bool"> + </return> + <argument index="0" name="type" type="String"> + </argument> + <description> + Returns whether the given class exists in [ClassDB]. + [codeblock] + type_exists("Sprite") # returns true + type_exists("Variant") # returns false + [/codeblock] + </description> + </method> + <method name="typeof"> + <return type="int"> + </return> + <argument index="0" name="what" type="Variant"> + </argument> + <description> + Returns the internal type of the given Variant object, using the TYPE_* enum in [@GlobalScope]. + [codeblock] + p = parse_json('["a", "b", "c"]') + if typeof(p) == TYPE_ARRAY: + print(p[0]) # prints a + else: + print("unexpected results") + [/codeblock] + </description> + </method> + <method name="validate_json"> + <return type="String"> + </return> + <argument index="0" name="json" type="String"> + </argument> + <description> + Checks that [code]json[/code] is valid JSON data. Returns empty string if valid. Returns error message if not valid. + [codeblock] + j = to_json([1, 2, 3]) + v = validate_json(j) + if not v: + print("valid") + else: + prints("invalid", v) + [/codeblock] + </description> + </method> + <method name="var2bytes"> + <return type="PoolByteArray"> + </return> + <argument index="0" name="var" type="Variant"> + </argument> + <argument index="1" name="full_objects" type="bool" default="false"> + </argument> + <description> + Encodes a variable value to a byte array. When [code]full_objects[/code] is [code]true[/code] encoding objects is allowed (and can potentially include code). + </description> + </method> + <method name="var2str"> + <return type="String"> + </return> + <argument index="0" name="var" type="Variant"> + </argument> + <description> + Converts a Variant [code]var[/code] to a formatted string that can later be parsed using [method str2var]. + [codeblock] + a = { 'a': 1, 'b': 2 } + print(var2str(a)) + [/codeblock] + prints + [codeblock] + { + "a": 1, + "b": 2 + } + [/codeblock] + </description> + </method> + <method name="weakref"> + <return type="WeakRef"> + </return> + <argument index="0" name="obj" type="Object"> + </argument> + <description> + Returns a weak reference to an object. + A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it. + </description> + </method> + <method name="wrapf"> + <return type="float"> + </return> + <argument index="0" name="value" type="float"> + </argument> + <argument index="1" name="min" type="float"> + </argument> + <argument index="2" name="max" type="float"> + </argument> + <description> + Wraps float [code]value[/code] between [code]min[/code] and [code]max[/code]. + Usable for creating loop-alike behavior or infinite surfaces. + [codeblock] + # a is 0.5 + a = wrapf(10.5, 0.0, 10.0) + [/codeblock] + [codeblock] + # a is 9.5 + a = wrapf(-0.5, 0.0, 10.0) + [/codeblock] + [codeblock] + # infinite loop between 0.0 and 0.99 + f = wrapf(f + 0.1, 0.0, 1.0) + [/codeblock] + </description> + </method> + <method name="wrapi"> + <return type="int"> + </return> + <argument index="0" name="value" type="int"> + </argument> + <argument index="1" name="min" type="int"> + </argument> + <argument index="2" name="max" type="int"> + </argument> + <description> + Wraps integer [code]value[/code] between [code]min[/code] and [code]max[/code]. + Usable for creating loop-alike behavior or infinite surfaces. + [codeblock] + # a is 0 + a = wrapi(10, 0, 10) + [/codeblock] + [codeblock] + # a is 9 + a = wrapi(-1, 0, 10) + [/codeblock] + [codeblock] + # infinite loop between 0 and 9 + frame = wrapi(frame + 1, 0, 10) + [/codeblock] + </description> + </method> + <method name="yield"> + <return type="GDScriptFunctionState"> + </return> + <argument index="0" name="object" type="Object" default="null"> + </argument> + <argument index="1" name="signal" type="String" default=""""> + </argument> + <description> + Stops the function execution and returns the current suspended state to the calling function. + From the caller, call [method GDScriptFunctionState.resume] on the state to resume execution. This invalidates the state. Within the resumed function, [code]yield()[/code] returns whatever was passed to the [code]resume()[/code] function call. + If passed an object and a signal, the execution is resumed when the object emits the given signal. In this case, [code]yield()[/code] returns the argument passed to [code]emit_signal()[/code] if the signal takes only one argument, or an array containing all the arguments passed to [code]emit_signal()[/code] if the signal takes multiple arguments. + </description> + </method> + </methods> + <constants> + <constant name="PI" value="3.141593"> + Constant that represents how many times the diameter of a circle fits around its perimeter. + </constant> + <constant name="TAU" value="6.283185"> + The circle constant, the circumference of the unit circle. + </constant> + <constant name="INF" value="inf"> + A positive infinity. (For negative infinity, use -INF). + </constant> + <constant name="NAN" value="nan"> + Macro constant that expands to an expression of type float that represents a NaN. + The NaN values are used to identify undefined or non-representable values for floating-point elements, such as the square root of negative numbers or the result of 0/0. + </constant> + </constants> +</class> diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h index 40b773d99f..1756f6eabc 100644 --- a/modules/gdscript/gdscript.h +++ b/modules/gdscript/gdscript.h @@ -509,7 +509,6 @@ public: }; class ResourceFormatLoaderGDScript : public ResourceFormatLoader { - GDCLASS(ResourceFormatLoaderGDScript, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; @@ -519,7 +518,6 @@ public: }; class ResourceFormatSaverGDScript : public ResourceFormatSaver { - GDCLASS(ResourceFormatSaverGDScript, ResourceFormatSaver) public: virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; diff --git a/modules/gdscript/gdscript_functions.cpp b/modules/gdscript/gdscript_functions.cpp index 98263d43e5..0736f3d010 100644 --- a/modules/gdscript/gdscript_functions.cpp +++ b/modules/gdscript/gdscript_functions.cpp @@ -342,7 +342,7 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ VALIDATE_ARG_NUM(0); r_ret = Math::step_decimals((double)*p_args[0]); ERR_EXPLAIN("GDScript method 'decimals' is deprecated and has been renamed to 'step_decimals', please update your code accordingly."); - WARN_DEPRECATED + WARN_DEPRECATED; } break; case MATH_STEP_DECIMALS: { VALIDATE_ARG_COUNT(1); diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index 44a91303e9..ec3e72eef7 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -1995,7 +1995,6 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to } } - ERR_FAIL_V(op); } break; default: { return p_node; @@ -4025,7 +4024,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { ERR_EXPLAIN("Exporting bit flags hint requires string constants."); - WARN_DEPRECATED + WARN_DEPRECATED; break; } if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { @@ -4068,6 +4067,50 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { break; } + if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_2D_RENDER") { + + tokenizer->advance(); + if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { + _set_error("Expected ')' in layers 2D render hint."); + return; + } + current_export.hint = PROPERTY_HINT_LAYERS_2D_RENDER; + break; + } + + if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_2D_PHYSICS") { + + tokenizer->advance(); + if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { + _set_error("Expected ')' in layers 2D physics hint."); + return; + } + current_export.hint = PROPERTY_HINT_LAYERS_2D_PHYSICS; + break; + } + + if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_3D_RENDER") { + + tokenizer->advance(); + if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { + _set_error("Expected ')' in layers 3D render hint."); + return; + } + current_export.hint = PROPERTY_HINT_LAYERS_3D_RENDER; + break; + } + + if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_3D_PHYSICS") { + + tokenizer->advance(); + if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { + _set_error("Expected ')' in layers 3D physics hint."); + return; + } + current_export.hint = PROPERTY_HINT_LAYERS_3D_PHYSICS; + break; + } + if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) { //enumeration current_export.hint = PROPERTY_HINT_ENUM; diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp index 32a014e76d..3caa7b1d12 100644 --- a/modules/gridmap/grid_map.cpp +++ b/modules/gridmap/grid_map.cpp @@ -197,7 +197,7 @@ bool GridMap::get_collision_layer_bit(int p_bit) const { void GridMap::set_theme(const Ref<MeshLibrary> &p_theme) { ERR_EXPLAIN("GridMap.theme/set_theme() is deprecated and will be removed in a future version. Use GridMap.mesh_library/set_mesh_library() instead."); - WARN_DEPRECATED + WARN_DEPRECATED; set_mesh_library(p_theme); } @@ -205,7 +205,7 @@ void GridMap::set_theme(const Ref<MeshLibrary> &p_theme) { Ref<MeshLibrary> GridMap::get_theme() const { ERR_EXPLAIN("GridMap.theme/get_theme() is deprecated and will be removed in a future version. Use GridMap.mesh_library/get_mesh_library() instead."); - WARN_DEPRECATED + WARN_DEPRECATED; return get_mesh_library(); } diff --git a/modules/mono/SCsub b/modules/mono/SCsub index 341d57f3e4..6c3ecee272 100644 --- a/modules/mono/SCsub +++ b/modules/mono/SCsub @@ -20,11 +20,6 @@ if env['tools']: 'glue/cs_glue_version.gen.h' ) -vars = Variables() -vars.Add(BoolVariable('mono_glue', 'Build with the mono glue sources', True)) -vars.Add(BoolVariable('xbuild_fallback', 'If MSBuild is not found, fallback to xbuild', False)) -vars.Update(env_mono) - # Glue sources if env_mono['mono_glue']: env_mono.Append(CPPDEFINES=['MONO_GLUE_ENABLED']) diff --git a/modules/mono/build_scripts/mono_configure.py b/modules/mono/build_scripts/mono_configure.py index 2bce3ed376..c549640d61 100644 --- a/modules/mono/build_scripts/mono_configure.py +++ b/modules/mono/build_scripts/mono_configure.py @@ -47,14 +47,6 @@ def copy_file(src_dir, dst_dir, name): def configure(env, env_mono): - from SCons.Script import BoolVariable, PathVariable, Variables - - envvars = Variables() - envvars.Add(PathVariable('mono_prefix', 'Path to the mono installation directory for the target platform and architecture', '', PathVariable.PathAccept)) - envvars.Add(BoolVariable('mono_static', 'Statically link mono', False)) - envvars.Add(BoolVariable('copy_mono_root', 'Make a copy of the mono installation directory to bundle with the editor', False)) - envvars.Update(env) - bits = env['bits'] is_android = env['platform'] == 'android' diff --git a/modules/mono/build_scripts/patches/fix-mono-android-pthread_mutexattr_setprotocol.diff b/modules/mono/build_scripts/patches/fix-mono-android-pthread_mutexattr_setprotocol.diff deleted file mode 100644 index 21cb1a0cf8..0000000000 --- a/modules/mono/build_scripts/patches/fix-mono-android-pthread_mutexattr_setprotocol.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/mono/utils/mono-os-mutex.h b/mono/utils/mono-os-mutex.h -index e8039bf4094..ee39c0330b3 100644 ---- a/mono/utils/mono-os-mutex.h -+++ b/mono/utils/mono-os-mutex.h -@@ -57,7 +57,7 @@ mono_os_mutex_init_type (mono_mutex_t *mutex, int type) - if (G_UNLIKELY (res != 0)) - g_error ("%s: pthread_mutexattr_settype failed with \"%s\" (%d)", __func__, g_strerror (res), res); - --#ifdef PTHREAD_PRIO_INHERIT -+#if defined(PTHREAD_PRIO_INHERIT) && __ANDROID_API__ >= 28 - /* use PTHREAD_PRIO_INHERIT if possible */ - res = pthread_mutexattr_setprotocol (&attr, PTHREAD_PRIO_INHERIT); - if (G_UNLIKELY (res != 0 && res != ENOTSUP)) diff --git a/modules/mono/config.py b/modules/mono/config.py index 3b2e96765e..9adf4ee6e5 100644 --- a/modules/mono/config.py +++ b/modules/mono/config.py @@ -8,6 +8,16 @@ def configure(env): env.use_ptrcall = True env.add_module_version_string('mono') + from SCons.Script import BoolVariable, PathVariable, Variables + + envvars = Variables() + envvars.Add(PathVariable('mono_prefix', 'Path to the mono installation directory for the target platform and architecture', '', PathVariable.PathAccept)) + envvars.Add(BoolVariable('mono_static', 'Statically link mono', False)) + envvars.Add(BoolVariable('mono_glue', 'Build with the mono glue sources', True)) + envvars.Add(BoolVariable('copy_mono_root', 'Make a copy of the mono installation directory to bundle with the editor', False)) + envvars.Add(BoolVariable('xbuild_fallback', 'If MSBuild is not found, fallback to xbuild', False)) + envvars.Update(env) + def get_doc_classes(): return [ diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index 4a1fb8e5ed..7b16b5609e 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -440,7 +440,6 @@ public: }; class ResourceFormatLoaderCSharpScript : public ResourceFormatLoader { - GDCLASS(ResourceFormatLoaderCSharpScript, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; @@ -449,7 +448,6 @@ public: }; class ResourceFormatSaverCSharpScript : public ResourceFormatSaver { - GDCLASS(ResourceFormatSaverCSharpScript, ResourceFormatSaver) public: virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index cd7774e7a1..2d618f7891 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -2536,13 +2536,8 @@ void BindingsGenerator::_default_argument_from_variant(const Variant &p_val, Arg switch (p_val.get_type()) { case Variant::NIL: - if (ClassDB::class_exists(r_iarg.type.cname)) { - // Object type - r_iarg.default_argument = "null"; - } else { - // Variant - r_iarg.default_argument = "null"; - } + // Either Object type or Variant + r_iarg.default_argument = "null"; break; // Atomic types case Variant::BOOL: diff --git a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml index dc7fc7fe31..894a1b3ced 100644 --- a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml +++ b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml @@ -41,6 +41,8 @@ <argument index="0" name="x" type="float"> </argument> <description> + Returns the 1D noise value [code][-1,1][/code] at the given x-coordinate. + Note: This method actually returns the 2D noise value [code][-1,1][/code] with fixed y-coordinate value 0.0. </description> </method> <method name="get_noise_2d"> diff --git a/modules/opus/audio_stream_opus.cpp b/modules/opus/audio_stream_opus.cpp index fda82295de..70d0f770d8 100644 --- a/modules/opus/audio_stream_opus.cpp +++ b/modules/opus/audio_stream_opus.cpp @@ -313,7 +313,7 @@ int AudioStreamPlaybackOpus::mix(int16_t *p_buffer, int p_frames) { bool ok = op_pcm_seek(opus_file, (loop_restart_time * osrate) + pre_skip) == 0; if (!ok) { playing = false; - ERR_PRINT("loop restart time rejected") + ERR_PRINT("Loop restart time rejected"); } frames_mixed = (loop_restart_time * osrate) + pre_skip; diff --git a/modules/opus/audio_stream_opus.h b/modules/opus/audio_stream_opus.h index f53bff0288..fd07e19e2e 100644 --- a/modules/opus/audio_stream_opus.h +++ b/modules/opus/audio_stream_opus.h @@ -132,7 +132,6 @@ public: }; class ResourceFormatLoaderAudioStreamOpus : public ResourceFormatLoader { - GDCLASS(ResourceFormatLoaderAudioStreamOpus, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; diff --git a/modules/pvr/texture_loader_pvr.h b/modules/pvr/texture_loader_pvr.h index 2808b4ff03..606268e447 100644 --- a/modules/pvr/texture_loader_pvr.h +++ b/modules/pvr/texture_loader_pvr.h @@ -35,7 +35,6 @@ #include "scene/resources/texture.h" class ResourceFormatPVR : public ResourceFormatLoader { - GDCLASS(ResourceFormatPVR, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path, Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; diff --git a/modules/recast/navigation_mesh_editor_plugin.cpp b/modules/recast/navigation_mesh_editor_plugin.cpp index eadc11fcee..9f30806925 100644 --- a/modules/recast/navigation_mesh_editor_plugin.cpp +++ b/modules/recast/navigation_mesh_editor_plugin.cpp @@ -67,9 +67,7 @@ void NavigationMeshEditor::_bake_pressed() { EditorNavigationMeshGenerator::get_singleton()->clear(node->get_navigation_mesh()); EditorNavigationMeshGenerator::get_singleton()->bake(node->get_navigation_mesh(), node); - if (node) { - node->update_gizmo(); - } + node->update_gizmo(); } void NavigationMeshEditor::_clear_pressed() { diff --git a/modules/recast/navigation_mesh_generator.cpp b/modules/recast/navigation_mesh_generator.cpp index 0cac07e3e7..14467dc5c7 100644 --- a/modules/recast/navigation_mesh_generator.cpp +++ b/modules/recast/navigation_mesh_generator.cpp @@ -45,6 +45,10 @@ #include "scene/resources/shape.h" #include "scene/resources/sphere_shape.h" +#ifdef MODULE_CSG_ENABLED +#include "modules/csg/csg_shape.h" +#endif + EditorNavigationMeshGenerator *EditorNavigationMeshGenerator::singleton = NULL; void EditorNavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> &p_verticies) { @@ -134,6 +138,20 @@ void EditorNavigationMeshGenerator::_parse_geometry(Transform p_accumulated_tran } } +#ifdef MODULE_CSG_ENABLED + if (Object::cast_to<CSGShape>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) { + + CSGShape *csg_shape = Object::cast_to<CSGShape>(p_node); + Array meshes = csg_shape->get_meshes(); + if (!meshes.empty()) { + Ref<Mesh> mesh = meshes[1]; + if (mesh.is_valid()) { + _add_mesh(mesh, p_accumulated_transform * csg_shape->get_transform(), p_verticies, p_indices); + } + } + } +#endif + if (Object::cast_to<StaticBody>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES) { StaticBody *static_body = Object::cast_to<StaticBody>(p_node); diff --git a/modules/stb_vorbis/config.py b/modules/stb_vorbis/config.py index d75e41797a..200b8dfd50 100644 --- a/modules/stb_vorbis/config.py +++ b/modules/stb_vorbis/config.py @@ -7,7 +7,6 @@ def configure(env): def get_doc_classes(): return [ "AudioStreamOGGVorbis", - "ResourceImporterOGGVorbis", ] def get_doc_path(): diff --git a/modules/stb_vorbis/register_types.cpp b/modules/stb_vorbis/register_types.cpp index 88a1766e47..ce64626e4b 100644 --- a/modules/stb_vorbis/register_types.cpp +++ b/modules/stb_vorbis/register_types.cpp @@ -29,15 +29,22 @@ /*************************************************************************/ #include "register_types.h" + #include "audio_stream_ogg_vorbis.h" + +#ifdef TOOLS_ENABLED +#include "core/engine.h" #include "resource_importer_ogg_vorbis.h" +#endif void register_stb_vorbis_types() { #ifdef TOOLS_ENABLED - Ref<ResourceImporterOGGVorbis> ogg_import; - ogg_import.instance(); - ResourceFormatImporter::get_singleton()->add_importer(ogg_import); + if (Engine::get_singleton()->is_editor_hint()) { + Ref<ResourceImporterOGGVorbis> ogg_import; + ogg_import.instance(); + ResourceFormatImporter::get_singleton()->add_importer(ogg_import); + } #endif ClassDB::register_class<AudioStreamOGGVorbis>(); } diff --git a/modules/theora/config.py b/modules/theora/config.py index 7504166237..c7713d7607 100644 --- a/modules/theora/config.py +++ b/modules/theora/config.py @@ -6,7 +6,6 @@ def configure(env): def get_doc_classes(): return [ - "ResourceImporterTheora", "VideoStreamTheora", ] diff --git a/modules/theora/video_stream_theora.h b/modules/theora/video_stream_theora.h index 85d73d3c0d..0c37d33358 100644 --- a/modules/theora/video_stream_theora.h +++ b/modules/theora/video_stream_theora.h @@ -186,7 +186,6 @@ public: }; class ResourceFormatLoaderTheora : public ResourceFormatLoader { - GDCLASS(ResourceFormatLoaderTheora, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp index bd84a28c84..a9340b1498 100644 --- a/modules/tinyexr/image_loader_tinyexr.cpp +++ b/modules/tinyexr/image_loader_tinyexr.cpp @@ -122,13 +122,13 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f } if (idxG == -1) { - ERR_PRINT("TinyEXR: G channel not found.") + ERR_PRINT("TinyEXR: G channel not found."); // @todo { free exr_image } return ERR_FILE_CORRUPT; } if (idxB == -1) { - ERR_PRINT("TinyEXR: B channel not found.") + ERR_PRINT("TinyEXR: B channel not found."); // @todo { free exr_image } return ERR_FILE_CORRUPT; } diff --git a/modules/visual_script/config.py b/modules/visual_script/config.py index 07a0450734..04e1a40b81 100644 --- a/modules/visual_script/config.py +++ b/modules/visual_script/config.py @@ -6,6 +6,7 @@ def configure(env): def get_doc_classes(): return [ + "@VisualScript", "VisualScriptBasicTypeConstant", "VisualScriptBuiltinFunc", "VisualScriptClassConstant", diff --git a/modules/gdnative/doc_classes/ResourceFormatLoaderVideoStreamGDNative.xml b/modules/visual_script/doc_classes/@VisualScript.xml index cd8b336778..8d9408e6d4 100644 --- a/modules/gdnative/doc_classes/ResourceFormatLoaderVideoStreamGDNative.xml +++ b/modules/visual_script/doc_classes/@VisualScript.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="ResourceFormatLoaderVideoStreamGDNative" inherits="ResourceFormatLoader" category="Core" version="3.2"> +<class name="@VisualScript" category="Core" version="3.2"> <brief_description> + Built-in visual script functions. </brief_description> <description> + A list of built-in visual script functions, see [VisualScriptBuiltinFunc] and [VisualScript]. </description> <tutorials> </tutorials> diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp index aad6e95845..7c3bad6785 100644 --- a/modules/visual_script/visual_script_editor.cpp +++ b/modules/visual_script/visual_script_editor.cpp @@ -2111,6 +2111,9 @@ void VisualScriptEditor::clear_executing_line() { void VisualScriptEditor::trim_trailing_whitespace() { } +void VisualScriptEditor::insert_final_newline() { +} + void VisualScriptEditor::convert_indent_to_spaces() { } @@ -3756,4 +3759,7 @@ void _VisualScriptEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("remove_custom_node", "name", "category"), &_VisualScriptEditor::remove_custom_node); ADD_SIGNAL(MethodInfo("custom_nodes_updated")); } + +void VisualScriptEditor::validate() { +} #endif diff --git a/modules/visual_script/visual_script_editor.h b/modules/visual_script/visual_script_editor.h index 3d3a49f672..b66d10021a 100644 --- a/modules/visual_script/visual_script_editor.h +++ b/modules/visual_script/visual_script_editor.h @@ -266,6 +266,7 @@ public: virtual void set_executing_line(int p_line); virtual void clear_executing_line(); virtual void trim_trailing_whitespace(); + virtual void insert_final_newline(); virtual void convert_indent_to_spaces(); virtual void convert_indent_to_tabs(); virtual void ensure_focus(); @@ -280,6 +281,7 @@ public: virtual Control *get_edit_menu(); virtual void clear_edit_menu(); virtual bool can_lose_focus_on_node_selection() { return false; } + virtual void validate(); static void register_editor(); diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp index 692705e411..e652abbe6a 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.cpp +++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp @@ -143,8 +143,7 @@ int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_buffer, int p_frames) { bool ok = ov_time_seek(&vf, loop_restart_time) == 0; if (!ok) { playing = false; - //ERR_EXPLAIN("loop restart time rejected"); - ERR_PRINT("loop restart time rejected") + ERR_PRINT("Loop restart time rejected"); } frames_mixed = stream_srate * loop_restart_time; diff --git a/modules/vorbis/audio_stream_ogg_vorbis.h b/modules/vorbis/audio_stream_ogg_vorbis.h index fa9d5fe664..a37867d9f9 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.h +++ b/modules/vorbis/audio_stream_ogg_vorbis.h @@ -127,7 +127,6 @@ public: }; class ResourceFormatLoaderAudioStreamOGGVorbis : public ResourceFormatLoader { - GDCLASS(ResourceFormatLoaderAudioStreamOGGVorbis, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; diff --git a/modules/webm/config.py b/modules/webm/config.py index 72a4073423..ba4dcce2f5 100644 --- a/modules/webm/config.py +++ b/modules/webm/config.py @@ -6,7 +6,6 @@ def configure(env): def get_doc_classes(): return [ - "ResourceImporterWebm", "VideoStreamWebm", ] diff --git a/modules/webm/video_stream_webm.cpp b/modules/webm/video_stream_webm.cpp index 6485c95360..3670edc9ea 100644 --- a/modules/webm/video_stream_webm.cpp +++ b/modules/webm/video_stream_webm.cpp @@ -413,10 +413,11 @@ void VideoStreamPlaybackWebm::delete_pointers() { if (audio_frame) memdelete(audio_frame); - for (int i = 0; i < video_frames_capacity; ++i) - memdelete(video_frames[i]); - if (video_frames) + if (video_frames) { + for (int i = 0; i < video_frames_capacity; ++i) + memdelete(video_frames[i]); memfree(video_frames); + } if (video) memdelete(video); diff --git a/modules/webm/video_stream_webm.h b/modules/webm/video_stream_webm.h index 992095ba4c..4e07c86775 100644 --- a/modules/webm/video_stream_webm.h +++ b/modules/webm/video_stream_webm.h @@ -127,7 +127,6 @@ public: }; class ResourceFormatLoaderWebm : public ResourceFormatLoader { - GDCLASS(ResourceFormatLoaderWebm, ResourceFormatLoader) public: virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; diff --git a/modules/webrtc/config.py b/modules/webrtc/config.py index 2e3a18ad0e..48b4c33c5d 100644 --- a/modules/webrtc/config.py +++ b/modules/webrtc/config.py @@ -7,7 +7,8 @@ def configure(env): def get_doc_classes(): return [ "WebRTCPeerConnection", - "WebRTCDataChannel" + "WebRTCDataChannel", + "WebRTCMultiplayer" ] def get_doc_path(): diff --git a/modules/webrtc/doc_classes/WebRTCDataChannel.xml b/modules/webrtc/doc_classes/WebRTCDataChannel.xml index dcc14d4ddb..7cce97244d 100644 --- a/modules/webrtc/doc_classes/WebRTCDataChannel.xml +++ b/modules/webrtc/doc_classes/WebRTCDataChannel.xml @@ -11,85 +11,106 @@ <return type="void"> </return> <description> + Closes this data channel, notifying the other peer. </description> </method> <method name="get_id" qualifiers="const"> <return type="int"> </return> <description> + Returns the id assigned to this channel during creation (or auto-assigned during negotiation). + If the channel is not negotiated out-of-band the id will only be available after the connection is established (will return [code]65535[/code] until then). </description> </method> <method name="get_label" qualifiers="const"> <return type="String"> </return> <description> + Returns the label assigned to this channel during creation. </description> </method> <method name="get_max_packet_life_time" qualifiers="const"> <return type="int"> </return> <description> + Returns the [code]maxPacketLifeTime[/code] value assigned to this channel during creation. + Will be [code]65535[/code] if not specified. </description> </method> <method name="get_max_retransmits" qualifiers="const"> <return type="int"> </return> <description> + Returns the [code]maxRetransmits[/code] value assigned to this channel during creation. + Will be [code]65535[/code] if not specified. </description> </method> <method name="get_protocol" qualifiers="const"> <return type="String"> </return> <description> + Returns the sub-protocol assigned to this channel during creation. An empty string if not specified. </description> </method> <method name="get_ready_state" qualifiers="const"> <return type="int" enum="WebRTCDataChannel.ChannelState"> </return> <description> + Returns the current state of this channel, see [enum WebRTCDataChannel.ChannelState]. </description> </method> <method name="is_negotiated" qualifiers="const"> <return type="bool"> </return> <description> + Returns [code]true[/code] if this channel was created with out-of-band configuration. </description> </method> <method name="is_ordered" qualifiers="const"> <return type="bool"> </return> <description> + Returns [code]true[/code] if this channel was created with ordering enabled (default). </description> </method> <method name="poll"> <return type="int" enum="Error"> </return> <description> + Reserved, but not used for now. </description> </method> <method name="was_string_packet" qualifiers="const"> <return type="bool"> </return> <description> + Returns [code]true[/code] if the last received packet was transferred as text. See [member write_mode]. </description> </method> </methods> <members> <member name="write_mode" type="int" setter="set_write_mode" getter="get_write_mode" enum="WebRTCDataChannel.WriteMode"> + The transfer mode to use when sending outgoing packet. Either text or binary. </member> </members> <constants> <constant name="WRITE_MODE_TEXT" value="0" enum="WriteMode"> + Tells the channel to send data over this channel as text. An external peer (non-Godot) would receive this as a string. </constant> <constant name="WRITE_MODE_BINARY" value="1" enum="WriteMode"> + Tells the channel to send data over this channel as binary. An external peer (non-Godot) would receive this as array buffer or blob. </constant> <constant name="STATE_CONNECTING" value="0" enum="ChannelState"> + The channel was created, but it's still trying to connect. </constant> <constant name="STATE_OPEN" value="1" enum="ChannelState"> + The channel is currently open, and data can flow over it. </constant> <constant name="STATE_CLOSING" value="2" enum="ChannelState"> + The channel is being closed, no new messages will be accepted, but those already in queue will be flushed. </constant> <constant name="STATE_CLOSED" value="3" enum="ChannelState"> + The channel was closed, or connection failed. </constant> </constants> </class> diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml new file mode 100644 index 0000000000..2b0622fffa --- /dev/null +++ b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml @@ -0,0 +1,85 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="WebRTCMultiplayer" inherits="NetworkedMultiplayerPeer" category="Core" version="3.2"> + <brief_description> + A simple interface to create a peer-to-peer mesh network composed of [WebRTCPeerConnection] that is compatible with the [MultiplayerAPI]. + </brief_description> + <description> + This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.network_peer]. + You can add each [WebRTCPeerConnection] via [method add_peer] or remove them via [method remove_peer]. Peers must be added in [constant WebRTCPeerConnection.STATE_NEW] state to allow it to create the appropriate channels. This class will not create offers nor set descriptions, it will only poll them, and notify connections and disconnections. + [signal NetworkedMultiplayerPeer.connection_succeeded] and [signal NetworkedMultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [NetworkedMultiplayerPeer]. + </description> + <tutorials> + </tutorials> + <methods> + <method name="add_peer"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="peer" type="WebRTCPeerConnection"> + </argument> + <argument index="1" name="peer_id" type="int"> + </argument> + <argument index="2" name="unreliable_lifetime" type="int" default="1"> + </argument> + <description> + Add a new peer to the mesh with the given [code]peer_id[/code]. The [WebRTCPeerConnection] must be in state [constant WebRTCPeerConnection.STATE_NEW]. + Three channels will be created for reliable, unreliable, and ordered transport. The value of [code]unreliable_lifetime[/code] will be passed to the [code]maxPacketLifetime[/code] option when creating unreliable and ordered channels (see [method WebRTCPeerConnection.create_data_channel]). + </description> + </method> + <method name="close"> + <return type="void"> + </return> + <description> + Close all the add peer connections and channels, freeing all resources. + </description> + </method> + <method name="get_peer"> + <return type="Dictionary"> + </return> + <argument index="0" name="peer_id" type="int"> + </argument> + <description> + Return a dictionary representation of the peer with given [code]peer_id[/code] with three keys. [code]connection[/code] containing the [WebRTCPeerConnection] to this peer, [code]channels[/code] an array of three [WebRTCDataChannel], and [code]connected[/code] a boolean representing if the peer connection is currently connected (all three channels are open). + </description> + </method> + <method name="get_peers"> + <return type="Dictionary"> + </return> + <description> + Returns a dictionary which keys are the peer ids and values the peer representation as in [method get_peer] + </description> + </method> + <method name="has_peer"> + <return type="bool"> + </return> + <argument index="0" name="peer_id" type="int"> + </argument> + <description> + Returns [code]true[/code] if the given [code]peer_id[/code] is in the peers map (it might not be connected though). + </description> + </method> + <method name="initialize"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="peer_id" type="int"> + </argument> + <argument index="1" name="server_compatibility" type="bool" default="false"> + </argument> + <description> + Initialize the multiplayer peer with the given [code]peer_id[/code] (must be between 1 and 2147483647). + If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED] and [signal NetworkedMultiplayerPeer.connection_succeeded] will not be emitted. + If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal NetworkedMultiplayerPeer.peer_connected] signals until a peer with id [constant NetworkedMultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal NetworkedMultiplayerPeer.connection_succeeded]. After that the signal [signal NetworkedMultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal NetworkedMultiplayerPeer.server_disconnected] will be emitted and state will become [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED]. + </description> + </method> + <method name="remove_peer"> + <return type="void"> + </return> + <argument index="0" name="peer_id" type="int"> + </argument> + <description> + Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal NetworkedMultiplayerPeer.peer_connected] was emitted for it, then [signal NetworkedMultiplayerPeer.peer_disconnected] will be emitted. + </description> + </method> + </methods> + <constants> + </constants> +</class> diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml index 8b14c60deb..ae709877f4 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml @@ -1,8 +1,15 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="WebRTCPeerConnection" inherits="Reference" category="Core" version="3.2"> <brief_description> + Interface to a WebRTC peer connection. </brief_description> <description> + A WebRTC connection between the local computer and a remote peer. Provides an interface to connect, maintain and monitor the connection. + Setting up a WebRTC connection between two peers from now on) may not seem a trivial task, but it can be broken down into 3 main steps: + - The peer that wants to initiate the connection ([code]A[/code] from now on) creates an offer and send it to the other peer ([code]B[/code] from now on). + - [code]B[/code] receives the offer, generate and answer, and sends it to [code]B[/code]). + - [code]A[/code] and [code]B[/code] then generates and exchange ICE candidates with each other. + After these steps, the connection should become connected. Keep on reading or look into the tutorial for more information. </description> <tutorials> </tutorials> @@ -17,12 +24,14 @@ <argument index="2" name="name" type="String"> </argument> <description> + Add an ice candidate generated by a remote peer (and received over the signaling server). See [signal ice_candidate_created]. </description> </method> <method name="close"> <return type="void"> </return> <description> + Close the peer connection and all data channels associated with it. Note, you cannot reuse this object for a new connection unless you call [method initialize]. </description> </method> <method name="create_data_channel"> @@ -35,18 +44,38 @@ }"> </argument> <description> + Returns a new [WebRTCDataChannel] (or [code]null[/code] on failure) with given [code]label[/code] and optionally configured via the [code]options[/code] dictionary. This method can only be called when the connection is in state [constant STATE_NEW]. + There are two ways to create a working data channel: either call [method create_data_channel] on only one of the peer and listen to [signal data_channel_received] on the other, or call [method create_data_channel] on both peers, with the same values, and the [code]negotiated[/code] option set to [code]true[/code]. + Valid [code]options[/code] are: + [codeblock] + { + "negotiated": true, # When set to true (default off), means the channel is negotiated out of band. "id" must be set too. data_channel_received will not be called. + "id": 1, # When "negotiated" is true this value must also be set to the same value on both peer. + + # Only one of maxRetransmits and maxPacketLifeTime can be specified, not both. They make the channel unreliable (but also better at real time). + "maxRetransmits": 1, # Specify the maximum number of attempt the peer will make to retransmits packets if they are not acknowledged. + "maxPacketLifeTime": 100, # Specify the maximum amount of time before giving up retransmitions of unacknowledged packets (in milliseconds). + "ordered": true, # When in unreliable mode (i.e. either "maxRetransmits" or "maxPacketLifetime" is set), "ordered" (true by default) specify if packet ordering is to be enforced. + + "protocol": "my-custom-protocol", # A custom sub-protocol string for this channel. + } + [/codeblock] + NOTE: You must keep a reference to channels created this way, or it will be closed. </description> </method> <method name="create_offer"> <return type="int" enum="Error"> </return> <description> + Creates a new SDP offer to start a WebRTC connection with a remote peer. At least one [WebRTCDataChannel] must have been created before calling this method. + If this functions returns [code]OK[/code], [signal session_description_created] will be called when the session is ready to be sent. </description> </method> <method name="get_connection_state" qualifiers="const"> <return type="int" enum="WebRTCPeerConnection.ConnectionState"> </return> <description> + Returns the connection state. See [enum ConnectionState]. </description> </method> <method name="initialize"> @@ -57,12 +86,29 @@ }"> </argument> <description> + Re-initialize this peer connection, closing any previously active connection, and going back to state [constant STATE_NEW]. A dictionary of [code]options[/code] can be passed to configure the peer connection. + Valid [code]options[/code] are: + [codeblock] + { + "iceServers": [ + { + "urls": [ "stun:stun.example.com:3478" ], # One or more STUN servers. + }, + { + "urls": [ "turn:turn.example.com:3478" ], # One or more TURN servers. + "username": "a_username", # Optional username for the TURN server. + "credentials": "a_password", # Optional password for the TURN server. + } + ] + } + [/codeblock] </description> </method> <method name="poll"> <return type="int" enum="Error"> </return> <description> + Call this method frequently (e.g. in [method Node._process] or [method Node._physics_process]) to properly receive signals. </description> </method> <method name="set_local_description"> @@ -73,6 +119,8 @@ <argument index="1" name="sdp" type="String"> </argument> <description> + Sets the SDP description of the local peer. This should be called in response to [signal session_description_created]. + If [code]type[/code] is [code]answer[/code] the peer will start emitting [signal ice_candidate_created]. </description> </method> <method name="set_remote_description"> @@ -83,6 +131,9 @@ <argument index="1" name="sdp" type="String"> </argument> <description> + Sets the SDP description of the remote peer. This should be called with the values generated by a remote peer and received over the signaling server. + If [code]type[/code] is [code]offer[/code] the peer will emit [signal session_description_created] with the appropriate answer. + If [code]type[/code] is [code]answer[/code] the peer will start emitting [signal ice_candidate_created]. </description> </method> </methods> @@ -91,6 +142,8 @@ <argument index="0" name="channel" type="Object"> </argument> <description> + Emitted when a new in-band channel is received, i.e. when the channel was created with [code]negotiated: false[/code] (default). + The object will be an instance of [WebRTCDataChannel]. You must keep a reference of it or it will be closed automatically. See [method create_data_channel] </description> </signal> <signal name="ice_candidate_created"> @@ -101,6 +154,7 @@ <argument index="2" name="name" type="String"> </argument> <description> + Emitted when a new ICE candidate has been created. The three parameters are meant to be passed to the remote peer over the signaling server. </description> </signal> <signal name="session_description_created"> @@ -109,21 +163,28 @@ <argument index="1" name="sdp" type="String"> </argument> <description> + Emitted after a successful call to [method create_offer] or [method set_remote_description] (when it generates an answer). The parameters are meant to be passed to [method set_local_description] on this object, and sent to the remote peer over the signaling server. </description> </signal> </signals> <constants> <constant name="STATE_NEW" value="0" enum="ConnectionState"> + The connection is new, data channels and an offer can be created in this state. </constant> <constant name="STATE_CONNECTING" value="1" enum="ConnectionState"> + The peer is connecting, ICE is in progress, non of the transports has failed. </constant> <constant name="STATE_CONNECTED" value="2" enum="ConnectionState"> + The peer is connected, all ICE transports are connected. </constant> <constant name="STATE_DISCONNECTED" value="3" enum="ConnectionState"> + At least one ICE transport is disconnected. </constant> <constant name="STATE_FAILED" value="4" enum="ConnectionState"> + One or more of the ICE transports failed. </constant> <constant name="STATE_CLOSED" value="5" enum="ConnectionState"> + The peer connection is closed (after calling [method close] for example). </constant> </constants> </class> diff --git a/modules/webrtc/register_types.cpp b/modules/webrtc/register_types.cpp index 44e072cc89..58b68d926b 100644 --- a/modules/webrtc/register_types.cpp +++ b/modules/webrtc/register_types.cpp @@ -40,6 +40,7 @@ #include "webrtc_data_channel_gdnative.h" #include "webrtc_peer_connection_gdnative.h" #endif +#include "webrtc_multiplayer.h" void register_webrtc_types() { #ifdef JAVASCRIPT_ENABLED @@ -54,6 +55,7 @@ void register_webrtc_types() { ClassDB::register_class<WebRTCDataChannelGDNative>(); #endif ClassDB::register_virtual_class<WebRTCDataChannel>(); + ClassDB::register_class<WebRTCMultiplayer>(); } void unregister_webrtc_types() {} diff --git a/modules/webrtc/webrtc_data_channel_js.cpp b/modules/webrtc/webrtc_data_channel_js.cpp index 2e7c64aa72..069918cc9c 100644 --- a/modules/webrtc/webrtc_data_channel_js.cpp +++ b/modules/webrtc/webrtc_data_channel_js.cpp @@ -68,7 +68,7 @@ void WebRTCDataChannelJS::_on_error() { } void WebRTCDataChannelJS::_on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string) { - if (in_buffer.space_left() < p_size + 5) { + if (in_buffer.space_left() < (int)(p_size + 5)) { ERR_EXPLAIN("Buffer full! Dropping data"); ERR_FAIL(); } @@ -205,30 +205,45 @@ String WebRTCDataChannelJS::get_label() const { } /* clang-format off */ -#define _JS_GET(PROP) \ +#define _JS_GET(PROP, DEF) \ EM_ASM_INT({ \ var dict = Module.IDHandler.get($0); \ if (!dict || !dict["channel"]) { \ - return 0; \ - }; \ - return dict["channel"].PROP; \ + return DEF; \ + } \ + var out = dict["channel"].PROP; \ + return out === null ? DEF : out; \ }, _js_id) /* clang-format on */ bool WebRTCDataChannelJS::is_ordered() const { - return _JS_GET(ordered); + return _JS_GET(ordered, true); } int WebRTCDataChannelJS::get_id() const { - return _JS_GET(id); + return _JS_GET(id, 65535); } int WebRTCDataChannelJS::get_max_packet_life_time() const { - return _JS_GET(maxPacketLifeTime); + // Can't use macro, webkit workaround. + /* clang-format off */ + return EM_ASM_INT({ + var dict = Module.IDHandler.get($0); + if (!dict || !dict["channel"]) { + return 65535; + } + if (dict["channel"].maxRetransmitTime !== undefined) { + // Guess someone didn't appreciate the standardization process. + return dict["channel"].maxRetransmitTime; + } + var out = dict["channel"].maxPacketLifeTime; + return out === null ? 65535 : out; + }, _js_id); + /* clang-format on */ } int WebRTCDataChannelJS::get_max_retransmits() const { - return _JS_GET(maxRetransmits); + return _JS_GET(maxRetransmits, 65535); } String WebRTCDataChannelJS::get_protocol() const { @@ -236,7 +251,7 @@ String WebRTCDataChannelJS::get_protocol() const { } bool WebRTCDataChannelJS::is_negotiated() const { - return _JS_GET(negotiated); + return _JS_GET(negotiated, false); } WebRTCDataChannelJS::WebRTCDataChannelJS() { diff --git a/modules/webrtc/webrtc_multiplayer.cpp b/modules/webrtc/webrtc_multiplayer.cpp new file mode 100644 index 0000000000..17dafff93a --- /dev/null +++ b/modules/webrtc/webrtc_multiplayer.cpp @@ -0,0 +1,384 @@ +/*************************************************************************/ +/* webrtc_multiplayer.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 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 "webrtc_multiplayer.h" + +#include "core/io/marshalls.h" +#include "core/os/os.h" + +void WebRTCMultiplayer::_bind_methods() { + ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility"), &WebRTCMultiplayer::initialize, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayer::add_peer, DEFVAL(1)); + ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayer::remove_peer); + ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayer::has_peer); + ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayer::get_peer); + ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayer::get_peers); + ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayer::close); +} + +void WebRTCMultiplayer::set_transfer_mode(TransferMode p_mode) { + transfer_mode = p_mode; +} + +NetworkedMultiplayerPeer::TransferMode WebRTCMultiplayer::get_transfer_mode() const { + return transfer_mode; +} + +void WebRTCMultiplayer::set_target_peer(int p_peer_id) { + target_peer = p_peer_id; +} + +/* Returns the ID of the NetworkedMultiplayerPeer who sent the most recent packet: */ +int WebRTCMultiplayer::get_packet_peer() const { + return next_packet_peer; +} + +bool WebRTCMultiplayer::is_server() const { + return unique_id == TARGET_PEER_SERVER; +} + +void WebRTCMultiplayer::poll() { + if (peer_map.size() == 0) + return; + + List<int> remove; + List<int> add; + for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) { + Ref<ConnectedPeer> peer = E->get(); + peer->connection->poll(); + // Check peer state + switch (peer->connection->get_connection_state()) { + case WebRTCPeerConnection::STATE_NEW: + case WebRTCPeerConnection::STATE_CONNECTING: + // Go to next peer, not ready yet. + continue; + case WebRTCPeerConnection::STATE_CONNECTED: + // Good to go, go ahead and check channel state. + break; + default: + // Peer is closed or in error state. Got to next peer. + remove.push_back(E->key()); + continue; + } + // Check channels state + int ready = 0; + for (List<Ref<WebRTCDataChannel> >::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) { + Ref<WebRTCDataChannel> ch = C->get(); + switch (ch->get_ready_state()) { + case WebRTCDataChannel::STATE_CONNECTING: + continue; + case WebRTCDataChannel::STATE_OPEN: + ready++; + continue; + default: + // Channel was closed or in error state, remove peer id. + remove.push_back(E->key()); + } + // We got a closed channel break out, the peer will be removed. + break; + } + // This peer has newly connected, and all channels are now open. + if (ready == peer->channels.size() && !peer->connected) { + peer->connected = true; + add.push_back(E->key()); + } + } + // Remove disconnected peers + for (List<int>::Element *E = remove.front(); E; E = E->next()) { + remove_peer(E->get()); + if (next_packet_peer == E->get()) + next_packet_peer = 0; + } + // Signal newly connected peers + for (List<int>::Element *E = add.front(); E; E = E->next()) { + // Already connected to server: simply notify new peer. + // NOTE: Mesh is always connected. + if (connection_status == CONNECTION_CONNECTED) + emit_signal("peer_connected", E->get()); + + // Server emulation mode suppresses peer_conencted until server connects. + if (server_compat && E->get() == TARGET_PEER_SERVER) { + // Server connected. + connection_status = CONNECTION_CONNECTED; + emit_signal("peer_connected", TARGET_PEER_SERVER); + emit_signal("connection_succeeded"); + // Notify of all previously connected peers + for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) { + if (F->key() != 1 && F->get()->connected) + emit_signal("peer_connected", F->key()); + } + break; // Because we already notified of all newly added peers. + } + } + // Fetch next packet + if (next_packet_peer == 0) + _find_next_peer(); +} + +void WebRTCMultiplayer::_find_next_peer() { + Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.find(next_packet_peer); + if (E) E = E->next(); + // After last. + while (E) { + for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) { + if (F->get()->get_available_packet_count()) { + next_packet_peer = E->key(); + return; + } + } + E = E->next(); + } + E = peer_map.front(); + // Before last + while (E) { + for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) { + if (F->get()->get_available_packet_count()) { + next_packet_peer = E->key(); + return; + } + } + if (E->key() == (int)next_packet_peer) + break; + E = E->next(); + } + // No packet found + next_packet_peer = 0; +} + +void WebRTCMultiplayer::set_refuse_new_connections(bool p_enable) { + refuse_connections = p_enable; +} + +bool WebRTCMultiplayer::is_refusing_new_connections() const { + return refuse_connections; +} + +NetworkedMultiplayerPeer::ConnectionStatus WebRTCMultiplayer::get_connection_status() const { + return connection_status; +} + +Error WebRTCMultiplayer::initialize(int p_self_id, bool p_server_compat) { + ERR_FAIL_COND_V(p_self_id < 0 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER); + unique_id = p_self_id; + server_compat = p_server_compat; + + // Mesh and server are always connected + if (!server_compat || p_self_id == 1) + connection_status = CONNECTION_CONNECTED; + else + connection_status = CONNECTION_CONNECTING; + return OK; +} + +int WebRTCMultiplayer::get_unique_id() const { + ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1); + return unique_id; +} + +void WebRTCMultiplayer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) { + Array channels; + for (List<Ref<WebRTCDataChannel> >::Element *F = p_connected_peer->channels.front(); F; F = F->next()) { + channels.push_back(F->get()); + } + r_dict["connection"] = p_connected_peer->connection; + r_dict["connected"] = p_connected_peer->connected; + r_dict["channels"] = channels; +} + +bool WebRTCMultiplayer::has_peer(int p_peer_id) { + return peer_map.has(p_peer_id); +} + +Dictionary WebRTCMultiplayer::get_peer(int p_peer_id) { + ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary()); + Dictionary out; + _peer_to_dict(peer_map[p_peer_id], out); + return out; +} + +Dictionary WebRTCMultiplayer::get_peers() { + Dictionary out; + for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) { + Dictionary d; + _peer_to_dict(E->get(), d); + out[E->key()] = d; + } + return out; +} + +Error WebRTCMultiplayer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) { + ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(refuse_connections, ERR_UNAUTHORIZED); + // Peer must be valid, and in new state (to create data channels) + ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER); + + Ref<ConnectedPeer> peer = memnew(ConnectedPeer); + peer->connection = p_peer; + + // Initialize data channels + Dictionary cfg; + cfg["negotiated"] = true; + cfg["ordered"] = true; + + cfg["id"] = 1; + peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg); + ERR_FAIL_COND_V(!peer->channels[CH_RELIABLE].is_valid(), FAILED); + + cfg["id"] = 2; + cfg["maxPacketLifetime"] = p_unreliable_lifetime; + peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg); + ERR_FAIL_COND_V(!peer->channels[CH_ORDERED].is_valid(), FAILED); + + cfg["id"] = 3; + cfg["ordered"] = false; + peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg); + ERR_FAIL_COND_V(!peer->channels[CH_UNRELIABLE].is_valid(), FAILED); + + peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map + + return OK; +} + +void WebRTCMultiplayer::remove_peer(int p_peer_id) { + ERR_FAIL_COND(!peer_map.has(p_peer_id)); + Ref<ConnectedPeer> peer = peer_map[p_peer_id]; + peer_map.erase(p_peer_id); + if (peer->connected) { + peer->connected = false; + emit_signal("peer_disconnected", p_peer_id); + if (server_compat && p_peer_id == TARGET_PEER_SERVER) { + emit_signal("server_disconnected"); + connection_status = CONNECTION_DISCONNECTED; + } + } +} + +Error WebRTCMultiplayer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + // Peer not available + if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) { + _find_next_peer(); + ERR_FAIL_V(ERR_UNAVAILABLE); + } + for (List<Ref<WebRTCDataChannel> >::Element *E = peer_map[next_packet_peer]->channels.front(); E; E = E->next()) { + if (E->get()->get_available_packet_count()) { + Error err = E->get()->get_packet(r_buffer, r_buffer_size); + _find_next_peer(); + return err; + } + } + // Channels for that peer were empty. Bug? + _find_next_peer(); + ERR_FAIL_V(ERR_BUG); +} + +Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED); + + int ch = CH_RELIABLE; + switch (transfer_mode) { + case TRANSFER_MODE_RELIABLE: + ch = CH_RELIABLE; + break; + case TRANSFER_MODE_UNRELIABLE_ORDERED: + ch = CH_ORDERED; + break; + case TRANSFER_MODE_UNRELIABLE: + ch = CH_UNRELIABLE; + break; + } + + Map<int, Ref<ConnectedPeer> >::Element *E = NULL; + + if (target_peer > 0) { + + E = peer_map.find(target_peer); + if (!E) { + ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer)); + ERR_FAIL_V(ERR_INVALID_PARAMETER); + } + ERR_FAIL_COND_V(E->value()->channels.size() <= ch, ERR_BUG); + ERR_FAIL_COND_V(!E->value()->channels[ch].is_valid(), ERR_BUG); + return E->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); + + } else { + int exclude = -target_peer; + + for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) { + + // Exclude packet. If target_peer == 0 then don't exclude any packets + if (target_peer != 0 && F->key() == exclude) + continue; + + ERR_CONTINUE(F->value()->channels.size() <= ch || !F->value()->channels[ch].is_valid()); + F->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); + } + } + return OK; +} + +int WebRTCMultiplayer::get_available_packet_count() const { + if (next_packet_peer == 0) + return 0; // To be sure next call to get_packet works if size > 0 . + int size = 0; + for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) { + for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) { + size += F->get()->get_available_packet_count(); + } + } + return size; +} + +int WebRTCMultiplayer::get_max_packet_size() const { + return 1200; +} + +void WebRTCMultiplayer::close() { + peer_map.clear(); + unique_id = 0; + next_packet_peer = 0; + target_peer = 0; + connection_status = CONNECTION_DISCONNECTED; +} + +WebRTCMultiplayer::WebRTCMultiplayer() { + unique_id = 0; + next_packet_peer = 0; + target_peer = 0; + transfer_mode = TRANSFER_MODE_RELIABLE; + refuse_connections = false; + connection_status = CONNECTION_DISCONNECTED; + server_compat = false; +} + +WebRTCMultiplayer::~WebRTCMultiplayer() { + close(); +} diff --git a/modules/webrtc/webrtc_multiplayer.h b/modules/webrtc/webrtc_multiplayer.h new file mode 100644 index 0000000000..82bbfd4f68 --- /dev/null +++ b/modules/webrtc/webrtc_multiplayer.h @@ -0,0 +1,116 @@ +/*************************************************************************/ +/* webrtc_multiplayer.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 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 WEBRTC_MULTIPLAYER_H +#define WEBRTC_MULTIPLAYER_H + +#include "core/io/networked_multiplayer_peer.h" +#include "webrtc_peer_connection.h" + +class WebRTCMultiplayer : public NetworkedMultiplayerPeer { + + GDCLASS(WebRTCMultiplayer, NetworkedMultiplayerPeer); + +protected: + static void _bind_methods(); + +private: + enum { + CH_RELIABLE = 0, + CH_ORDERED = 1, + CH_UNRELIABLE = 2, + CH_RESERVED_MAX = 3 + }; + + class ConnectedPeer : public Reference { + + public: + Ref<WebRTCPeerConnection> connection; + List<Ref<WebRTCDataChannel> > channels; + bool connected; + + ConnectedPeer() { + connected = false; + for (int i = 0; i < CH_RESERVED_MAX; i++) + channels.push_front(Ref<WebRTCDataChannel>()); + } + }; + + uint32_t unique_id; + int target_peer; + int client_count; + bool refuse_connections; + ConnectionStatus connection_status; + TransferMode transfer_mode; + int next_packet_peer; + bool server_compat; + + Map<int, Ref<ConnectedPeer> > peer_map; + + void _peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict); + void _find_next_peer(); + +public: + WebRTCMultiplayer(); + ~WebRTCMultiplayer(); + + Error initialize(int p_self_id, bool p_server_compat = false); + Error add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime = 1); + void remove_peer(int p_peer_id); + bool has_peer(int p_peer_id); + Dictionary get_peer(int p_peer_id); + Dictionary get_peers(); + void close(); + + // PacketPeer + Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet + Error put_packet(const uint8_t *p_buffer, int p_buffer_size); + int get_available_packet_count() const; + int get_max_packet_size() const; + + // NetworkedMultiplayerPeer + void set_transfer_mode(TransferMode p_mode); + TransferMode get_transfer_mode() const; + void set_target_peer(int p_peer_id); + + int get_unique_id() const; + int get_packet_peer() const; + + bool is_server() const; + + void poll(); + + void set_refuse_new_connections(bool p_enable); + bool is_refusing_new_connections() const; + + ConnectionStatus get_connection_status() const; +}; + +#endif diff --git a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml index 8548d21323..103dbd771b 100644 --- a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml +++ b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml @@ -18,6 +18,24 @@ Returns the [WebSocketPeer] associated to the given [code]peer_id[/code]. </description> </method> + <method name="set_buffers"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="input_buffer_size_kb" type="int"> + </argument> + <argument index="1" name="input_max_packets" type="int"> + </argument> + <argument index="2" name="output_buffer_size_kb" type="int"> + </argument> + <argument index="3" name="output_max_packets" type="int"> + </argument> + <description> + Configure the buffers sizes for this WebSocket peer. Default values can be specified in project settings under [code]network/limits[/code]. For server, values are meant per connected peer. + The first two parameters define the size and queued packets limits of the input buffer, the last two of the output buffer. + Buffer sizes are expressed in KiB, so [code]4 = 2^12 = 4096 bytes[/code]. All parameters will be rounded up to the nearest power of two. + NOTE: HTML5 exports only use the input buffer since the output one is managed by browsers. + </description> + </method> </methods> <signals> <signal name="peer_packet"> diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp index aafae8f1c2..409cc9f699 100644 --- a/modules/websocket/emws_client.cpp +++ b/modules/websocket/emws_client.cpp @@ -205,6 +205,12 @@ int EMWSClient::get_max_packet_size() const { return (1 << _in_buf_size) - PROTO_SIZE; } +Error EMWSClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) { + _in_buf_size = nearest_shift(p_in_buffer - 1) + 10; + _in_pkt_size = nearest_shift(p_in_packets - 1); + return OK; +} + EMWSClient::EMWSClient() { _in_buf_size = nearest_shift((int)GLOBAL_GET(WSC_IN_BUF) - 1) + 10; _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_IN_PKT) - 1); diff --git a/modules/websocket/emws_client.h b/modules/websocket/emws_client.h index 9bc29c1913..1811d05eea 100644 --- a/modules/websocket/emws_client.h +++ b/modules/websocket/emws_client.h @@ -49,6 +49,7 @@ private: public: bool _is_connecting; + Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocol = PoolVector<String>()); Ref<WebSocketPeer> get_peer(int p_peer_id) const; void disconnect_from_host(int p_code = 1000, String p_reason = ""); diff --git a/modules/websocket/emws_server.cpp b/modules/websocket/emws_server.cpp index 0eef1c4ba9..c4bb459ad0 100644 --- a/modules/websocket/emws_server.cpp +++ b/modules/websocket/emws_server.cpp @@ -79,6 +79,10 @@ int EMWSServer::get_max_packet_size() const { return 0; } +Error EMWSServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) { + return OK; +} + EMWSServer::EMWSServer() { } diff --git a/modules/websocket/emws_server.h b/modules/websocket/emws_server.h index bb101cd155..a5e5b4090e 100644 --- a/modules/websocket/emws_server.h +++ b/modules/websocket/emws_server.h @@ -42,6 +42,7 @@ class EMWSServer : public WebSocketServer { GDCIIMPL(EMWSServer, WebSocketServer); public: + Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); Error listen(int p_port, PoolVector<String> p_protocols = PoolVector<String>(), bool gd_mp_api = false); void stop(); bool is_listening() const; diff --git a/modules/websocket/lws_client.cpp b/modules/websocket/lws_client.cpp index 08df76293b..f139a4ef66 100644 --- a/modules/websocket/lws_client.cpp +++ b/modules/websocket/lws_client.cpp @@ -215,6 +215,17 @@ uint16_t LWSClient::get_connected_port() const { return 1025; }; +Error LWSClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) { + ERR_EXPLAIN("Buffers sizes can only be set before listening or connecting"); + ERR_FAIL_COND_V(context != NULL, FAILED); + + _in_buf_size = nearest_shift(p_in_buffer - 1) + 10; + _in_pkt_size = nearest_shift(p_in_packets - 1); + _out_buf_size = nearest_shift(p_out_buffer - 1) + 10; + _out_pkt_size = nearest_shift(p_out_packets - 1); + return OK; +} + LWSClient::LWSClient() { _in_buf_size = nearest_shift((int)GLOBAL_GET(WSC_IN_BUF) - 1) + 10; _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_IN_PKT) - 1); diff --git a/modules/websocket/lws_client.h b/modules/websocket/lws_client.h index b3a1237550..df4aabec7f 100644 --- a/modules/websocket/lws_client.h +++ b/modules/websocket/lws_client.h @@ -51,6 +51,7 @@ private: int _out_pkt_size; public: + Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocol = PoolVector<String>()); int get_max_packet_size() const; Ref<WebSocketPeer> get_peer(int p_peer_id) const; diff --git a/modules/websocket/lws_server.cpp b/modules/websocket/lws_server.cpp index 61ccdca74a..482c02dc60 100644 --- a/modules/websocket/lws_server.cpp +++ b/modules/websocket/lws_server.cpp @@ -197,6 +197,17 @@ void LWSServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) { get_peer(p_peer_id)->close(p_code, p_reason); } +Error LWSServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) { + ERR_EXPLAIN("Buffers sizes can only be set before listening or connecting"); + ERR_FAIL_COND_V(context != NULL, FAILED); + + _in_buf_size = nearest_shift(p_in_buffer - 1) + 10; + _in_pkt_size = nearest_shift(p_in_packets - 1); + _out_buf_size = nearest_shift(p_out_buffer - 1) + 10; + _out_pkt_size = nearest_shift(p_out_packets - 1); + return OK; +} + LWSServer::LWSServer() { _in_buf_size = nearest_shift((int)GLOBAL_GET(WSS_IN_BUF) - 1) + 10; _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_IN_PKT) - 1); diff --git a/modules/websocket/lws_server.h b/modules/websocket/lws_server.h index 5096ee0f88..b331852d26 100644 --- a/modules/websocket/lws_server.h +++ b/modules/websocket/lws_server.h @@ -52,6 +52,7 @@ private: int _out_pkt_size; public: + Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); Error listen(int p_port, PoolVector<String> p_protocols = PoolVector<String>(), bool gd_mp_api = false); void stop(); bool is_listening() const; diff --git a/modules/websocket/websocket_client.h b/modules/websocket/websocket_client.h index c464d97c7f..7ddb9468a5 100644 --- a/modules/websocket/websocket_client.h +++ b/modules/websocket/websocket_client.h @@ -67,6 +67,8 @@ public: void _on_disconnect(bool p_was_clean); void _on_error(); + virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0; + WebSocketClient(); ~WebSocketClient(); }; diff --git a/modules/websocket/websocket_multiplayer_peer.cpp b/modules/websocket/websocket_multiplayer_peer.cpp index 6aab8a7e81..23cbf916eb 100644 --- a/modules/websocket/websocket_multiplayer_peer.cpp +++ b/modules/websocket/websocket_multiplayer_peer.cpp @@ -87,6 +87,7 @@ void WebSocketMultiplayerPeer::_clear() { void WebSocketMultiplayerPeer::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_buffers", "input_buffer_size_kb", "input_max_packets", "output_buffer_size_kb", "output_max_packets"), &WebSocketMultiplayerPeer::set_buffers); ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebSocketMultiplayerPeer::get_peer); ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "peer_source"))); diff --git a/modules/websocket/websocket_multiplayer_peer.h b/modules/websocket/websocket_multiplayer_peer.h index b050449ee0..089bc25fe9 100644 --- a/modules/websocket/websocket_multiplayer_peer.h +++ b/modules/websocket/websocket_multiplayer_peer.h @@ -97,6 +97,7 @@ public: virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); /* WebSocketPeer */ + virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0; virtual Ref<WebSocketPeer> get_peer(int p_peer_id) const = 0; void _process_multiplayer(Ref<WebSocketPeer> p_peer, uint32_t p_peer_id); diff --git a/modules/websocket/websocket_server.h b/modules/websocket/websocket_server.h index 7a94c4047b..83c0c10419 100644 --- a/modules/websocket/websocket_server.h +++ b/modules/websocket/websocket_server.h @@ -62,6 +62,8 @@ public: void _on_disconnect(int32_t p_peer_id, bool p_was_clean); void _on_close_request(int32_t p_peer_id, int p_code, String p_reason); + virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0; + WebSocketServer(); ~WebSocketServer(); }; |