diff options
Diffstat (limited to 'modules')
578 files changed, 36793 insertions, 13925 deletions
diff --git a/modules/SCsub b/modules/SCsub index 67f5893db4..dc0420616c 100644 --- a/modules/SCsub +++ b/modules/SCsub @@ -6,17 +6,17 @@ env_modules = env.Clone() Export('env_modules') -env.modules_sources = [ - "register_module_types.gen.cpp", -] +env.modules_sources = [] + +env_modules.add_source_files(env.modules_sources, "register_module_types.gen.cpp") for x in env.module_list: if (x in env.disabled_modules): continue - env_modules.Append(CPPFLAGS=["-DMODULE_" + x.upper() + "_ENABLED"]) + env_modules.Append(CPPDEFINES=["MODULE_" + x.upper() + "_ENABLED"]) SConscript(x + "/SCsub") -if env.split_modules: +if env['split_libmodules']: env.split_lib("modules", env_lib = env_modules) else: lib = env_modules.add_library("modules", env.modules_sources) diff --git a/modules/arkit/SCsub b/modules/arkit/SCsub new file mode 100644 index 0000000000..e605703a72 --- /dev/null +++ b/modules/arkit/SCsub @@ -0,0 +1,12 @@ +#!/usr/bin/env python + +Import('env') +Import('env_modules') + +env_arkit = env_modules.Clone() + +# (iOS) Build as separate static library +modules_sources = [] +env_arkit.add_source_files(modules_sources, "*.cpp") +env_arkit.add_source_files(modules_sources, "*.mm") +mod_lib = env_modules.add_library('#bin/libgodot_arkit_module' + env['LIBSUFFIX'], modules_sources)
\ No newline at end of file diff --git a/modules/arkit/arkit_interface.h b/modules/arkit/arkit_interface.h new file mode 100644 index 0000000000..e1dbca1488 --- /dev/null +++ b/modules/arkit/arkit_interface.h @@ -0,0 +1,125 @@ +/*************************************************************************/ +/* arkit_interface.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 ARKIT_INTERFACE_H +#define ARKIT_INTERFACE_H + +#include "servers/arvr/arvr_interface.h" +#include "servers/arvr/arvr_positional_tracker.h" +#include "servers/camera/camera_feed.h" + +/** + @author Bastiaan Olij <mux213@gmail.com> + + ARKit interface between iPhone and Godot +*/ + +// forward declaration for some needed objects +class ARKitShader; + +class ARKitInterface : public ARVRInterface { + GDCLASS(ARKitInterface, ARVRInterface); + +private: + bool initialized; + bool session_was_started; + bool plane_detection_is_enabled; + bool light_estimation_is_enabled; + real_t ambient_intensity; + real_t ambient_color_temperature; + + Transform transform; + CameraMatrix projection; + float eye_height, z_near, z_far; + + Ref<CameraFeed> feed; + int image_width[2]; + int image_height[2]; + PoolVector<uint8_t> img_data[2]; + + struct anchor_map { + ARVRPositionalTracker *tracker; + unsigned char uuid[16]; + }; + + ///@TODO should use memory map object from Godot? + unsigned int num_anchors; + unsigned int max_anchors; + anchor_map *anchors; + ARVRPositionalTracker *get_anchor_for_uuid(const unsigned char *p_uuid); + void remove_anchor_for_uuid(const unsigned char *p_uuid); + void remove_all_anchors(); + +protected: + static void _bind_methods(); + +public: + void start_session(); + void stop_session(); + + bool get_anchor_detection_is_enabled() const; + void set_anchor_detection_is_enabled(bool p_enable); + virtual int get_camera_feed_id(); + + bool get_light_estimation_is_enabled() const; + void set_light_estimation_is_enabled(bool p_enable); + + real_t get_ambient_intensity() const; + real_t get_ambient_color_temperature() const; + + /* while Godot has its own raycast logic this takes ARKits camera into account and hits on any ARAnchor */ + Array raycast(Vector2 p_screen_coord); + + void notification(int p_what); + + virtual StringName get_name() const; + virtual int get_capabilities() const; + + virtual bool is_initialized() const; + virtual bool initialize(); + virtual void uninitialize(); + + virtual Size2 get_render_targetsize(); + virtual bool is_stereo(); + virtual Transform get_transform_for_eye(ARVRInterface::Eyes p_eye, const Transform &p_cam_transform); + virtual CameraMatrix get_projection_for_eye(ARVRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far); + virtual void commit_for_eye(ARVRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect); + + virtual void process(); + + // called by delegate (void * because C++ and Obj-C don't always mix, should really change all platform/iphone/*.cpp files to .mm) + void _add_or_update_anchor(void *p_anchor); + void _remove_anchor(void *p_anchor); + + ARKitInterface(); + ~ARKitInterface(); +}; + +#endif /* !ARKIT_INTERFACE_H */ diff --git a/modules/arkit/arkit_interface.mm b/modules/arkit/arkit_interface.mm new file mode 100644 index 0000000000..3408477458 --- /dev/null +++ b/modules/arkit/arkit_interface.mm @@ -0,0 +1,752 @@ +/*************************************************************************/ +/* arkit_interface.mm */ +/*************************************************************************/ +/* 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 "core/os/input.h" +#include "core/os/os.h" +#include "scene/resources/surface_tool.h" +#include "servers/visual/visual_server_globals.h" + +#import <ARKit/ARKit.h> +#import <UIKit/UIKit.h> + +#include <dlfcn.h> + +#include "arkit_interface.h" +#include "arkit_session_delegate.h" + +// just a dirty workaround for now, declare these as globals. I'll probably encapsulate ARSession and associated logic into an mm object and change ARKitInterface to a normal cpp object that consumes it. +ARSession *ar_session; +ARKitSessionDelegate *ar_delegate; +NSTimeInterval last_timestamp; + +/* this is called when we initialize or when we come back from having our app pushed to the background, just (re)start our session */ +void ARKitInterface::start_session() { + // We're active... + session_was_started = true; + + // Ignore this if we're not initialized... + if (initialized) { + print_line("Starting ARKit session"); + + Class ARWorldTrackingConfigurationClass = NSClassFromString(@"ARWorldTrackingConfiguration"); + ARWorldTrackingConfiguration *configuration = [ARWorldTrackingConfigurationClass new]; + + configuration.lightEstimationEnabled = light_estimation_is_enabled; + if (plane_detection_is_enabled) { + configuration.planeDetection = ARPlaneDetectionVertical | ARPlaneDetectionHorizontal; + } else { + configuration.planeDetection = 0; + } + + // make sure our camera is on + if (feed.is_valid()) { + feed->set_active(true); + } + + [ar_session runWithConfiguration:configuration]; + } +} + +void ARKitInterface::stop_session() { + session_was_started = false; + + // Ignore this if we're not initialized... + if (initialized) { + // make sure our camera is off + if (feed.is_valid()) { + feed->set_active(false); + } + + [ar_session pause]; + } +} + +void ARKitInterface::notification(int p_what) { + // TODO, this is not being called, need to find out why, possibly because this is not a node. + // in that case we need to find a way to get these notifications! + switch (p_what) { + case MainLoop::NOTIFICATION_WM_FOCUS_IN: { + print_line("Focus in"); + + start_session(); + }; break; + case MainLoop::NOTIFICATION_WM_FOCUS_OUT: { + print_line("Focus out"); + + stop_session(); + }; break; + default: + break; + } +} + +bool ARKitInterface::get_anchor_detection_is_enabled() const { + return plane_detection_is_enabled; +} + +void ARKitInterface::set_anchor_detection_is_enabled(bool p_enable) { + if (plane_detection_is_enabled != p_enable) { + plane_detection_is_enabled = p_enable; + + // Restart our session (this will be ignore if we're not initialised) + if (session_was_started) { + start_session(); + } + } +} + +int ARKitInterface::get_camera_feed_id() { + if (feed.is_null()) { + return 0; + } else { + return feed->get_id(); + } +} + +bool ARKitInterface::get_light_estimation_is_enabled() const { + return light_estimation_is_enabled; +} + +void ARKitInterface::set_light_estimation_is_enabled(bool p_enable) { + if (light_estimation_is_enabled != p_enable) { + light_estimation_is_enabled = p_enable; + + // Restart our session (this will be ignore if we're not initialised) + if (session_was_started) { + start_session(); + } + } +} + +real_t ARKitInterface::get_ambient_intensity() const { + return ambient_intensity; +} + +real_t ARKitInterface::get_ambient_color_temperature() const { + return ambient_color_temperature; +} + +StringName ARKitInterface::get_name() const { + return "ARKit"; +} + +int ARKitInterface::get_capabilities() const { + return ARKitInterface::ARVR_MONO + ARKitInterface::ARVR_AR; +} + +Array ARKitInterface::raycast(Vector2 p_screen_coord) { + Array arr; + Size2 screen_size = OS::get_singleton()->get_window_size(); + CGPoint point; + point.x = p_screen_coord.x / screen_size.x; + point.y = p_screen_coord.y / screen_size.y; + + ///@TODO maybe give more options here, for now we're taking just ARAchors into account that were found during plane detection keeping their size into account + NSArray<ARHitTestResult *> *results = [ar_session.currentFrame hittest:point types:ARHitTestResultTypeExistingPlaneUsingExtent]; + + for (ARHitTestResult *result in results) { + Transform transform; + + matrix_float4x4 m44 = result.worldTransform; + transform.basis.elements[0].x = m44.columns[0][0]; + transform.basis.elements[1].x = m44.columns[0][1]; + transform.basis.elements[2].x = m44.columns[0][2]; + transform.basis.elements[0].y = m44.columns[1][0]; + transform.basis.elements[1].y = m44.columns[1][1]; + transform.basis.elements[2].y = m44.columns[1][2]; + transform.basis.elements[0].z = m44.columns[2][0]; + transform.basis.elements[1].z = m44.columns[2][1]; + transform.basis.elements[2].z = m44.columns[2][2]; + transform.origin.x = m44.columns[3][0]; + transform.origin.y = m44.columns[3][1]; + transform.origin.z = m44.columns[3][2]; + + /* important, NOT scaled to world_scale !! */ + arr.push_back(transform); + } + + return arr; +} + +void ARKitInterface::_bind_methods() { + ClassDB::bind_method(D_METHOD("_notification", "what"), &ARKitInterface::_notification); + + ClassDB::bind_method(D_METHOD("set_light_estimation_is_enabled", "enable"), &ARKitInterface::set_light_estimation_is_enabled); + ClassDB::bind_method(D_METHOD("get_light_estimation_is_enabled"), &ARKitInterface::get_light_estimation_is_enabled); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "light_estimation"), "set_light_estimation_is_enabled", "get_light_estimation_is_enabled"); + + ClassDB::bind_method(D_METHOD("get_ambient_intensity"), &ARKitInterface::get_ambient_intensity); + ClassDB::bind_method(D_METHOD("get_ambient_color_temperature"), &ARKitInterface::get_ambient_color_temperature); + + ClassDB::bind_method(D_METHOD("raycast", "screen_coord"), &ARKitInterface::raycast); +} + +bool ARKitInterface::is_stereo() { + // this is a mono device... + return false; +} + +bool ARKitInterface::is_initialized() const { + return initialized; +} + +bool ARKitInterface::initialize() { + ARVRServer *arvr_server = ARVRServer::get_singleton(); + ERR_FAIL_NULL_V(arvr_server, false); + + if (!initialized) { + print_line("initializing ARKit"); + + // create our ar session and delegate + Class ARSessionClass = NSClassFromString(@"ARSession"); + if (ARSessionClass == Nil) { + void *arkit_handle = dlopen("/System/Library/Frameworks/ARKit.framework/ARKit", RTLD_NOW); + if (arkit_handle) { + ARSessionClass = NSClassFromString(@"ARSession"); + } else { + print_line("ARKit init failed"); + return false; + } + } + ar_session = [ARSessionClass new]; + ar_delegate = [ARKitSessionDelegate new]; + ar_delegate.arkit_interface = this; + ar_session.delegate = ar_delegate; + + // reset our transform + transform = Transform(); + + // make this our primary interface + arvr_server->set_primary_interface(this); + + // make sure we have our feed setup + if (feed.is_null()) { + feed.instance(); + feed->set_name("ARKit"); + + CameraServer *cs = CameraServer::get_singleton(); + if (cs != NULL) { + cs->add_feed(feed); + } + } + feed->set_active(true); + + // yeah! + initialized = true; + + // Start our session... + start_session(); + } + + return true; +} + +void ARKitInterface::uninitialize() { + if (initialized) { + ARVRServer *arvr_server = ARVRServer::get_singleton(); + if (arvr_server != NULL) { + // no longer our primary interface + arvr_server->clear_primary_interface_if(this); + } + + if (feed.is_valid()) { + CameraServer *cs = CameraServer::get_singleton(); + if ((cs != NULL)) { + cs->remove_feed(feed); + } + feed.unref(); + } + + remove_all_anchors(); + + [ar_session release]; + [ar_delegate release]; + ar_session = NULL; + ar_delegate = NULL; + initialized = false; + session_was_started = false; + } +} + +Size2 ARKitInterface::get_render_targetsize() { + _THREAD_SAFE_METHOD_ + + Size2 target_size = OS::get_singleton()->get_window_size(); + + return target_size; +} + +Transform ARKitInterface::get_transform_for_eye(ARVRInterface::Eyes p_eye, const Transform &p_cam_transform) { + _THREAD_SAFE_METHOD_ + + Transform transform_for_eye; + + ARVRServer *arvr_server = ARVRServer::get_singleton(); + ERR_FAIL_NULL_V(arvr_server, transform_for_eye); + + if (initialized) { + float world_scale = arvr_server->get_world_scale(); + + // just scale our origin point of our transform, note that we really shouldn't be using world_scale in ARKit but.... + transform_for_eye = transform; + transform_for_eye.origin *= world_scale; + + transform_for_eye = p_cam_transform * arvr_server->get_reference_frame() * transform_for_eye; + } else { + // huh? well just return what we got.... + transform_for_eye = p_cam_transform; + } + + return transform_for_eye; +} + +CameraMatrix ARKitInterface::get_projection_for_eye(ARVRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) { + // Remember our near and far, it will be used in process when we obtain our projection from our ARKit session. + z_near = p_z_near; + z_far = p_z_far; + + return projection; +} + +void ARKitInterface::commit_for_eye(ARVRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) { + _THREAD_SAFE_METHOD_ + + // We must have a valid render target + ERR_FAIL_COND(!p_render_target.is_valid()); + + // Because we are rendering to our device we must use our main viewport! + ERR_FAIL_COND(p_screen_rect == Rect2()); + + // get the size of our screen + Rect2 screen_rect = p_screen_rect; + + // screen_rect.position.x += screen_rect.size.x; + // screen_rect.size.x = -screen_rect.size.x; + // screen_rect.position.y += screen_rect.size.y; + // screen_rect.size.y = -screen_rect.size.y; + + VSG::rasterizer->set_current_render_target(RID()); + VSG::rasterizer->blit_render_target_to_screen(p_render_target, screen_rect, 0); +} + +ARVRPositionalTracker *ARKitInterface::get_anchor_for_uuid(const unsigned char *p_uuid) { + if (anchors == NULL) { + num_anchors = 0; + max_anchors = 10; + anchors = (anchor_map *)malloc(sizeof(anchor_map) * max_anchors); + } + + ERR_FAIL_NULL_V(anchors, NULL); + + for (unsigned int i = 0; i < num_anchors; i++) { + if (memcmp(anchors[i].uuid, p_uuid, 16) == 0) { + return anchors[i].tracker; + } + } + + if (num_anchors + 1 == max_anchors) { + max_anchors += 10; + anchors = (anchor_map *)realloc(anchors, sizeof(anchor_map) * max_anchors); + ERR_FAIL_NULL_V(anchors, NULL); + } + + ARVRPositionalTracker *new_tracker = memnew(ARVRPositionalTracker); + new_tracker->set_type(ARVRServer::TRACKER_ANCHOR); + + char tracker_name[256]; + sprintf(tracker_name, "Anchor %02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", p_uuid[0], p_uuid[1], p_uuid[2], p_uuid[3], p_uuid[4], p_uuid[5], p_uuid[6], p_uuid[7], p_uuid[8], p_uuid[9], p_uuid[10], p_uuid[11], p_uuid[12], p_uuid[13], p_uuid[14], p_uuid[15]); + + String name = tracker_name; + print_line("Adding tracker " + name); + new_tracker->set_name(name); + + // add our tracker + ARVRServer::get_singleton()->add_tracker(new_tracker); + anchors[num_anchors].tracker = new_tracker; + memcpy(anchors[num_anchors].uuid, p_uuid, 16); + num_anchors++; + + return new_tracker; +} + +void ARKitInterface::remove_anchor_for_uuid(const unsigned char *p_uuid) { + if (anchors != NULL) { + for (unsigned int i = 0; i < num_anchors; i++) { + if (memcmp(anchors[i].uuid, p_uuid, 16) == 0) { + // remove our tracker + ARVRServer::get_singleton()->remove_tracker(anchors[i].tracker); + memdelete(anchors[i].tracker); + + // bring remaining forward + for (unsigned int j = i + 1; j < num_anchors; j++) { + anchors[j - 1] = anchors[j]; + }; + + // decrease count + num_anchors--; + return; + } + } + } +} + +void ARKitInterface::remove_all_anchors() { + if (anchors != NULL) { + for (unsigned int i = 0; i < num_anchors; i++) { + // remove our tracker + ARVRServer::get_singleton()->remove_tracker(anchors[i].tracker); + memdelete(anchors[i].tracker); + }; + + free(anchors); + anchors = NULL; + num_anchors = 0; + } +} + +void ARKitInterface::process() { + _THREAD_SAFE_METHOD_ + + if (@available(iOS 11.0, *)) { + if (initialized) { + // get our next ARFrame + ARFrame *current_frame = ar_session.currentFrame; + if (last_timestamp != current_frame.timestamp) { + // only process if we have a new frame + last_timestamp = current_frame.timestamp; + + // get some info about our screen and orientation + Size2 screen_size = OS::get_singleton()->get_window_size(); + UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; + + // Grab our camera image for our backbuffer + CVPixelBufferRef pixelBuffer = current_frame.capturedImage; + if ((CVPixelBufferGetPlaneCount(pixelBuffer) == 2) && (feed != NULL)) { + // Plane 0 is our Y and Plane 1 is our CbCr buffer + + // ignored, we check each plane separately + // image_width = CVPixelBufferGetWidth(pixelBuffer); + // image_height = CVPixelBufferGetHeight(pixelBuffer); + + // printf("Pixel buffer %i - %i\n", image_width, image_height); + + CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); + + // get our buffers + unsigned char *dataY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0); + unsigned char *dataCbCr = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1); + + if (dataY == NULL) { + print_line("Couldn't access Y pixel buffer data"); + } else if (dataCbCr == NULL) { + print_line("Couldn't access CbCr pixel buffer data"); + } else { + Ref<Image> img[2]; + size_t extraLeft, extraRight, extraTop, extraBottom; + + CVPixelBufferGetExtendedPixels(pixelBuffer, &extraLeft, &extraRight, &extraTop, &extraBottom); + + { + // do Y + int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0); + int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0); + int bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0); + + if ((image_width[0] != new_width) || (image_height[0] != new_height)) { + printf("- Camera padding l:%lu r:%lu t:%lu b:%lu\n", extraLeft, extraRight, extraTop, extraBottom); + printf("- Camera Y plane size: %i, %i - %i\n", new_width, new_height, bytes_per_row); + + image_width[0] = new_width; + image_height[0] = new_height; + img_data[0].resize(new_width * new_height); + } + + PoolVector<uint8_t>::Write w = img_data[0].write(); + if (new_width == bytes_per_row) { + memcpy(w.ptr(), dataY, new_width * new_height); + } else { + int offset_a = 0; + int offset_b = extraLeft + (extraTop * bytes_per_row); + for (int r = 0; r < new_height; r++) { + memcpy(w.ptr() + offset_a, dataY + offset_b, new_width); + offset_a += new_width; + offset_b += bytes_per_row; + } + } + + img[0].instance(); + img[0]->create(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]); + } + + { + // do CbCr + int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1); + int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1); + int bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0); + + if ((image_width[1] != new_width) || (image_height[1] != new_height)) { + printf("- Camera CbCr plane size: %i, %i - %i\n", new_width, new_height, bytes_per_row); + + image_width[1] = new_width; + image_height[1] = new_height; + img_data[1].resize(2 * new_width * new_height); + } + + PoolVector<uint8_t>::Write w = img_data[1].write(); + if ((2 * new_width) == bytes_per_row) { + memcpy(w.ptr(), dataCbCr, 2 * new_width * new_height); + } else { + int offset_a = 0; + int offset_b = extraLeft + (extraTop * bytes_per_row); + for (int r = 0; r < new_height; r++) { + memcpy(w.ptr() + offset_a, dataCbCr + offset_b, 2 * new_width); + offset_a += 2 * new_width; + offset_b += bytes_per_row; + } + } + + img[1].instance(); + img[1]->create(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]); + } + + // set our texture... + feed->set_YCbCr_imgs(img[0], img[1]); + + // now build our transform to display this as a background image that matches our camera + CGAffineTransform affine_transform = [current_frame displayTransformForOrientation:orientation viewportSize:CGSizeMake(screen_size.width, screen_size.height)]; + + // we need to invert this, probably row v.s. column notation + affine_transform = CGAffineTransformInvert(affine_transform); + + if (orientation != UIInterfaceOrientationPortrait) { + affine_transform.b = -affine_transform.b; + affine_transform.d = -affine_transform.d; + affine_transform.ty = 1.0 - affine_transform.ty; + } else { + affine_transform.c = -affine_transform.c; + affine_transform.a = -affine_transform.a; + affine_transform.tx = 1.0 - affine_transform.tx; + } + + Transform2D display_transform = Transform2D( + affine_transform.a, affine_transform.b, + affine_transform.c, affine_transform.d, + affine_transform.tx, affine_transform.ty); + + feed->set_transform(display_transform); + } + + // and unlock + CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); + } + + // Record light estimation to apply to our scene + if (light_estimation_is_enabled) { + ambient_intensity = current_frame.lightEstimate.ambientIntensity; + + ///@TODO it's there, but not there.. what to do with this... + // https://developer.apple.com/documentation/arkit/arlightestimate?language=objc + // ambient_color_temperature = current_frame.lightEstimate.ambientColorTemperature; + } + + // Process our camera + ARCamera *camera = current_frame.camera; + + // strangely enough we have to states, rolling them up into one + if (camera.trackingState == ARTrackingStateNotAvailable) { + // no tracking, would be good if we black out the screen or something... + tracking_state = ARVRInterface::ARVR_NOT_TRACKING; + } else { + if (camera.trackingState == ARTrackingStateNormal) { + tracking_state = ARVRInterface::ARVR_NORMAL_TRACKING; + } else if (camera.trackingStateReason == ARTrackingStateReasonExcessiveMotion) { + tracking_state = ARVRInterface::ARVR_EXCESSIVE_MOTION; + } else if (camera.trackingStateReason == ARTrackingStateReasonInsufficientFeatures) { + tracking_state = ARVRInterface::ARVR_INSUFFICIENT_FEATURES; + } else { + tracking_state = ARVRInterface::ARVR_UNKNOWN_TRACKING; + } + + // copy our current frame transform + matrix_float4x4 m44 = camera.transform; + if (orientation == UIInterfaceOrientationLandscapeLeft) { + transform.basis.elements[0].x = m44.columns[0][0]; + transform.basis.elements[1].x = m44.columns[0][1]; + transform.basis.elements[2].x = m44.columns[0][2]; + transform.basis.elements[0].y = m44.columns[1][0]; + transform.basis.elements[1].y = m44.columns[1][1]; + transform.basis.elements[2].y = m44.columns[1][2]; + } else if (orientation == UIInterfaceOrientationPortrait) { + transform.basis.elements[0].x = m44.columns[1][0]; + transform.basis.elements[1].x = m44.columns[1][1]; + transform.basis.elements[2].x = m44.columns[1][2]; + transform.basis.elements[0].y = -m44.columns[0][0]; + transform.basis.elements[1].y = -m44.columns[0][1]; + transform.basis.elements[2].y = -m44.columns[0][2]; + } else if (orientation == UIInterfaceOrientationLandscapeRight) { + transform.basis.elements[0].x = -m44.columns[0][0]; + transform.basis.elements[1].x = -m44.columns[0][1]; + transform.basis.elements[2].x = -m44.columns[0][2]; + transform.basis.elements[0].y = -m44.columns[1][0]; + transform.basis.elements[1].y = -m44.columns[1][1]; + transform.basis.elements[2].y = -m44.columns[1][2]; + } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) { + // this may not be correct + transform.basis.elements[0].x = m44.columns[1][0]; + transform.basis.elements[1].x = m44.columns[1][1]; + transform.basis.elements[2].x = m44.columns[1][2]; + transform.basis.elements[0].y = m44.columns[0][0]; + transform.basis.elements[1].y = m44.columns[0][1]; + transform.basis.elements[2].y = m44.columns[0][2]; + } + transform.basis.elements[0].z = m44.columns[2][0]; + transform.basis.elements[1].z = m44.columns[2][1]; + transform.basis.elements[2].z = m44.columns[2][2]; + transform.origin.x = m44.columns[3][0]; + transform.origin.y = m44.columns[3][1]; + transform.origin.z = m44.columns[3][2]; + + // copy our current frame projection, investigate using projectionMatrixWithViewportSize:orientation:zNear:zFar: so we can set our own near and far + m44 = [camera projectionMatrixForOrientation:orientation viewportSize:CGSizeMake(screen_size.width, screen_size.height) zNear:z_near zFar:z_far]; + projection.matrix[0][0] = m44.columns[0][0]; + projection.matrix[1][0] = m44.columns[1][0]; + projection.matrix[2][0] = m44.columns[2][0]; + projection.matrix[3][0] = m44.columns[3][0]; + projection.matrix[0][1] = m44.columns[0][1]; + projection.matrix[1][1] = m44.columns[1][1]; + projection.matrix[2][1] = m44.columns[2][1]; + projection.matrix[3][1] = m44.columns[3][1]; + projection.matrix[0][2] = m44.columns[0][2]; + projection.matrix[1][2] = m44.columns[1][2]; + projection.matrix[2][2] = m44.columns[2][2]; + projection.matrix[3][2] = m44.columns[3][2]; + projection.matrix[0][3] = m44.columns[0][3]; + projection.matrix[1][3] = m44.columns[1][3]; + projection.matrix[2][3] = m44.columns[2][3]; + projection.matrix[3][3] = m44.columns[3][3]; + } + } + } + } +} + +void ARKitInterface::_add_or_update_anchor(void *p_anchor) { + _THREAD_SAFE_METHOD_ + + ARAnchor *anchor = (ARAnchor *)p_anchor; + + unsigned char uuid[16]; + [anchor.identifier getUUIDBytes:uuid]; + + ARVRPositionalTracker *tracker = get_anchor_for_uuid(uuid); + if (tracker != NULL) { + // lets update our mesh! (using Arjens code as is for now) + // we should also probably limit how often we do this... + + // can we safely cast this? + ARPlaneAnchor *planeAnchor = (ARPlaneAnchor *)anchor; + + if (planeAnchor.geometry.triangleCount > 0) { + Ref<SurfaceTool> surftool; + surftool.instance(); + surftool->begin(Mesh::PRIMITIVE_TRIANGLES); + + for (int j = planeAnchor.geometry.triangleCount * 3 - 1; j >= 0; j--) { + int16_t index = planeAnchor.geometry.triangleIndices[j]; + simd_float3 vrtx = planeAnchor.geometry.vertices[index]; + simd_float2 textcoord = planeAnchor.geometry.textureCoordinates[index]; + surftool->add_uv(Vector2(textcoord[0], textcoord[1])); + surftool->add_color(Color(0.8, 0.8, 0.8)); + surftool->add_vertex(Vector3(vrtx[0], vrtx[1], vrtx[2])); + } + + surftool->generate_normals(); + tracker->set_mesh(surftool->commit()); + } else { + Ref<Mesh> nomesh; + tracker->set_mesh(nomesh); + } + + // Note, this also contains a scale factor which gives us an idea of the size of the anchor + // We may extract that in our ARVRAnchor class + Basis b; + matrix_float4x4 m44 = anchor.transform; + b.elements[0].x = m44.columns[0][0]; + b.elements[1].x = m44.columns[0][1]; + b.elements[2].x = m44.columns[0][2]; + b.elements[0].y = m44.columns[1][0]; + b.elements[1].y = m44.columns[1][1]; + b.elements[2].y = m44.columns[1][2]; + b.elements[0].z = m44.columns[2][0]; + b.elements[1].z = m44.columns[2][1]; + b.elements[2].z = m44.columns[2][2]; + tracker->set_orientation(b); + tracker->set_rw_position(Vector3(m44.columns[3][0], m44.columns[3][1], m44.columns[3][2])); + } +} + +void ARKitInterface::_remove_anchor(void *p_anchor) { + _THREAD_SAFE_METHOD_ + + ARAnchor *anchor = (ARAnchor *)p_anchor; + + unsigned char uuid[16]; + [anchor.identifier getUUIDBytes:uuid]; + + remove_anchor_for_uuid(uuid); +} + +ARKitInterface::ARKitInterface() { + initialized = false; + session_was_started = false; + plane_detection_is_enabled = false; + light_estimation_is_enabled = false; + ar_session = NULL; + z_near = 0.01; + z_far = 1000.0; + projection.set_perspective(60.0, 1.0, z_near, z_far, false); + anchors = NULL; + num_anchors = 0; + ambient_intensity = 1.0; + ambient_color_temperature = 1.0; + image_width[0] = 0; + image_width[1] = 0; + image_height[0] = 0; + image_height[1] = 0; +} + +ARKitInterface::~ARKitInterface() { + remove_all_anchors(); + + // and make sure we cleanup if we haven't already + if (is_initialized()) { + uninitialize(); + } +} diff --git a/modules/arkit/arkit_session_delegate.h b/modules/arkit/arkit_session_delegate.h new file mode 100644 index 0000000000..9303552ca6 --- /dev/null +++ b/modules/arkit/arkit_session_delegate.h @@ -0,0 +1,50 @@ +/*************************************************************************/ +/* arkit_session_delegate.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 ARKIT_SESSION_DELEGATE_H +#define ARKIT_SESSION_DELEGATE_H + +#import <ARKit/ARKit.h> +#import <UIKit/UIKit.h> + +class ARKitInterface; + +@interface ARKitSessionDelegate : NSObject <ARSessionDelegate> { + ARKitInterface *arkit_interface; +} + +@property(nonatomic) ARKitInterface *arkit_interface; + +- (void)session:(ARSession *)session didAddAnchors:(NSArray<ARAnchor *> *)anchors; +- (void)session:(ARSession *)session didRemoveAnchors:(NSArray<ARAnchor *> *)anchors; +- (void)session:(ARSession *)session didUpdateAnchors:(NSArray<ARAnchor *> *)anchors; +@end + +#endif /* !ARKIT_SESSION_DELEGATE_H */ diff --git a/modules/arkit/arkit_session_delegate.mm b/modules/arkit/arkit_session_delegate.mm new file mode 100644 index 0000000000..d4072fc391 --- /dev/null +++ b/modules/arkit/arkit_session_delegate.mm @@ -0,0 +1,56 @@ +/*************************************************************************/ +/* arkit_session_delegate.mm */ +/*************************************************************************/ +/* 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 "arkit_session_delegate.h" +#include "arkit_interface.h" + +@implementation ARKitSessionDelegate + +@synthesize arkit_interface; + +- (void)session:(ARSession *)session didAddAnchors:(NSArray<ARAnchor *> *)anchors { + for (ARAnchor *anchor in anchors) { + arkit_interface->_add_or_update_anchor(anchor); + } +} + +- (void)session:(ARSession *)session didRemoveAnchors:(NSArray<ARAnchor *> *)anchors { + for (ARAnchor *anchor in anchors) { + arkit_interface->_remove_anchor(anchor); + } +} + +- (void)session:(ARSession *)session didUpdateAnchors:(NSArray<ARAnchor *> *)anchors { + for (ARAnchor *anchor in anchors) { + arkit_interface->_add_or_update_anchor(anchor); + } +} + +@end
\ No newline at end of file diff --git a/modules/arkit/config.py b/modules/arkit/config.py new file mode 100644 index 0000000000..96e41826c5 --- /dev/null +++ b/modules/arkit/config.py @@ -0,0 +1,5 @@ +def can_build(env, platform): + return platform == 'iphone' + +def configure(env): + pass diff --git a/modules/arkit/register_types.cpp b/modules/arkit/register_types.cpp new file mode 100644 index 0000000000..af35828004 --- /dev/null +++ b/modules/arkit/register_types.cpp @@ -0,0 +1,45 @@ +/*************************************************************************/ +/* register_types.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 "register_types.h" + +#include "arkit_interface.h" + +void register_arkit_types() { + // does it make sense to register the class? + + Ref<ARKitInterface> arkit_interface; + arkit_interface.instance(); + ARVRServer::get_singleton()->add_interface(arkit_interface); +} + +void unregister_arkit_types() { + // should clean itself up nicely :) +} diff --git a/modules/thekla_unwrap/register_types.h b/modules/arkit/register_types.h index b911eed622..6ed2065de2 100644 --- a/modules/thekla_unwrap/register_types.h +++ b/modules/arkit/register_types.h @@ -28,5 +28,5 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -void register_thekla_unwrap_types(); -void unregister_thekla_unwrap_types(); +void register_arkit_types(); +void unregister_arkit_types(); diff --git a/modules/assimp/SCsub b/modules/assimp/SCsub index 61a357809a..5e66b50de3 100644 --- a/modules/assimp/SCsub +++ b/modules/assimp/SCsub @@ -4,92 +4,97 @@ Import('env') Import('env_modules') env_assimp = env_modules.Clone() -env_assimp.Append(CPPPATH=['#thirdparty/assimp']) -env_assimp.Append(CPPPATH=['#thirdparty/assimp/include']) -env_assimp.Append(CPPPATH=['#thirdparty/assimp/code/Importer/IFC']) -env_assimp.Append(CPPPATH=['#thirdparty/misc']) -env_assimp.Append(CPPPATH=['#thirdparty/assimp/code']) -env_assimp.Append(CPPPATH=['#thirdparty/assimp/contrib/irrXML/']) -env_assimp.Append(CPPPATH=['#thirdparty/assimp/contrib/unzip/']) -env_assimp.Append(CPPPATH=['#thirdparty/assimp/code/Importer/STEPParser']) -env_assimp.Append(CPPPATH=['#thirdparty/assimp/']) -env_assimp.Append(CPPPATH=['#thirdparty/zlib/']) -env_assimp.Append(CPPPATH=['#thirdparty/assimp/contrib/openddlparser/include']) -env_assimp.Append(CPPPATH=['#thirdparty/assimp/contrib/rapidjson/include']) -env_assimp.Append(CPPPATH=['.']) -#env_assimp.Append(CPPFLAGS=['-DASSIMP_DOUBLE_PRECISION']) # TODO default to what godot is compiled with for future double support -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_BOOST_WORKAROUND']) -env_assimp.Append(CPPFLAGS=['-DOPENDDLPARSER_BUILD']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OWN_ZLIB']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_EXPORT']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_X_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_AMF_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_3DS_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MD3_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MD5_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MDL_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MD2_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_PLY_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_ASE_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OBJ_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_HMP_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_SMD_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MDC_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MD5_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_STL_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_LWO_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_DXF_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_NFF_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_RAW_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_SIB_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OFF_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_AC_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_BVH_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_IRRMESH_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_IRR_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_Q3D_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_B3D_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_COLLADA_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_TERRAGEN_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_CSM_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_3D_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_LWS_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OGRE_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OPENGEX_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MS3D_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_COB_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_BLEND_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_Q3BSP_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_NDO_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_STEP_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_IFC_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_XGL_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_ASSBIN_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_GLTF_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_C4D_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_3MF_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_X3D_IMPORTER']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/include']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/code/Importer/IFC']) +env_assimp.Prepend(CPPPATH=['#thirdparty/misc']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/code']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/common']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/contrib/irrXML/']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/contrib/unzip/']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/code/Importer/STEPParser']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/']) +env_assimp.Prepend(CPPPATH=['#thirdparty/zlib/']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/contrib/openddlparser/include']) +env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/contrib/rapidjson/include']) +env_assimp.Prepend(CPPPATH=['.']) +#env_assimp.Append(CPPDEFINES=['ASSIMP_DOUBLE_PRECISION']) # TODO default to what godot is compiled with for future double support +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_BOOST_WORKAROUND']) +env_assimp.Append(CPPDEFINES=['OPENDDLPARSER_BUILD']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OWN_ZLIB']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_EXPORT']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_X_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_AMF_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_3DS_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MD3_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MD5_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MDL_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MD2_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_PLY_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_ASE_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OBJ_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_HMP_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_SMD_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MDC_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MD5_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_STL_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_LWO_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_DXF_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_NFF_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_RAW_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_SIB_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OFF_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_AC_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_BVH_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_IRRMESH_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_IRR_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_Q3D_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_B3D_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_COLLADA_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_TERRAGEN_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_CSM_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_3D_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_LWS_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OGRE_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OPENGEX_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MS3D_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_COB_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_BLEND_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_Q3BSP_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_NDO_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_STEP_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_IFC_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_XGL_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_ASSBIN_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_C4D_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_3MF_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_X3D_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_GLTF_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_GLTF2_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_SINGLETHREADED']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_M3D_IMPORTER']) +env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MMD_IMPORTER']) -env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_SINGLETHREADED']) - -if (not env.msvc): - env_assimp.Append(CXXFLAGS=['-std=c++11']) -elif (env.msvc == False and env['platform'] == 'windows'): - env_assimp.Append(LDFLAGS=['-pthread']) if(env['platform'] == 'windows'): - env_assimp.Append(CPPFLAGS=['-DPLATFORM_WINDOWS']) - env_assimp.Append(CPPFLAGS=['-DPLATFORM=WINDOWS']) + env_assimp.Append(CPPDEFINES=['PLATFORM_WINDOWS']) + env_assimp.Append(CPPDEFINES=[('PLATFORM', 'WINDOWS')]) elif(env['platform'] == 'x11'): - env_assimp.Append(CPPFLAGS=['-DPLATFORM_LINUX']) - env_assimp.Append(CPPFLAGS=['-DPLATFORM=LINUX']) + env_assimp.Append(CPPDEFINES=['PLATFORM_LINUX']) + env_assimp.Append(CPPDEFINES=[('PLATFORM', 'LINUX')]) elif(env['platform'] == 'osx'): - env_assimp.Append(CPPFLAGS=['-DPLATFORM_DARWIN']) - env_assimp.Append(CPPFLAGS=['-DPLATFORM=DARWIN']) + env_assimp.Append(CPPDEFINES=['PLATFORM_DARWIN']) + env_assimp.Append(CPPDEFINES=[('PLATFORM', 'DARWIN')]) env_thirdparty = env_assimp.Clone() env_thirdparty.disable_warnings() -env_thirdparty.add_source_files(env.modules_sources, Glob('#thirdparty/assimp/code/*.cpp')) +env_thirdparty.add_source_files(env.modules_sources, Glob('#thirdparty/assimp/code/Common/*.cpp')) +env_thirdparty.add_source_files(env.modules_sources, Glob('#thirdparty/assimp/code/PostProcessing/*.cpp')) +env_thirdparty.add_source_files(env.modules_sources, Glob('#thirdparty/assimp/code/Material/*.cpp')) +env_thirdparty.add_source_files(env.modules_sources, Glob('#thirdparty/assimp/code/FBX/*.cpp')) +env_thirdparty.add_source_files(env.modules_sources, Glob('#thirdparty/assimp/code/MMD/*.cpp')) +env_thirdparty.add_source_files(env.modules_sources, Glob('#thirdparty/assimp/code/glTF/*.cpp')) +env_thirdparty.add_source_files(env.modules_sources, Glob('#thirdparty/assimp/code/glTF2/*.cpp')) # Godot's own source files env_assimp.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/assimp/editor_scene_importer_assimp.cpp b/modules/assimp/editor_scene_importer_assimp.cpp index 4662cf9d0a..752b74b9f2 100644 --- a/modules/assimp/editor_scene_importer_assimp.cpp +++ b/modules/assimp/editor_scene_importer_assimp.cpp @@ -28,34 +28,43 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "assimp/DefaultLogger.hpp" -#include "assimp/Importer.hpp" -#include "assimp/LogStream.hpp" -#include "assimp/Logger.hpp" -#include "assimp/SceneCombiner.h" -#include "assimp/cexport.h" -#include "assimp/cimport.h" -#include "assimp/matrix4x4.h" -#include "assimp/pbrmaterial.h" -#include "assimp/postprocess.h" -#include "assimp/scene.h" - -#include "core/bind/core_bind.h" +#include "editor_scene_importer_assimp.h" #include "core/io/image_loader.h" -#include "editor/editor_file_system.h" #include "editor/import/resource_importer_scene.h" -#include "editor_scene_importer_assimp.h" -#include "editor_settings.h" +#include "import_utils.h" #include "scene/3d/camera.h" #include "scene/3d/light.h" #include "scene/3d/mesh_instance.h" -#include "scene/animation/animation_player.h" #include "scene/main/node.h" #include "scene/resources/material.h" #include "scene/resources/surface_tool.h" -#include "zutil.h" + +#include <assimp/matrix4x4.h> +#include <assimp/postprocess.h> +#include <assimp/scene.h> +#include <assimp/Importer.hpp> +#include <assimp/LogStream.hpp> #include <string> +// move into assimp +aiBone *get_bone_by_name(const aiScene *scene, aiString bone_name) { + for (unsigned int mesh_id = 0; mesh_id < scene->mNumMeshes; ++mesh_id) { + aiMesh *mesh = scene->mMeshes[mesh_id]; + + // iterate over all the bones on the mesh for this node only! + for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) { + + aiBone *bone = mesh->mBones[boneIndex]; + if (bone->mName == bone_name) { + printf("matched bone by name: %s\n", bone->mName.C_Str()); + return bone; + } + } + } + + return NULL; +} + void EditorSceneImporterAssimp::get_extensions(List<String> *r_extensions) const { const String import_setting_string = "filesystem/import/open_asset_import/"; @@ -67,18 +76,15 @@ void EditorSceneImporterAssimp::get_extensions(List<String> *r_extensions) const ImportFormat import = { exts, true }; import_format.insert("fbx", import); } - { - Vector<String> exts; - exts.push_back("pmx"); - ImportFormat import = { exts, true }; - import_format.insert("mmd", import); - } for (Map<String, ImportFormat>::Element *E = import_format.front(); E; E = E->next()) { - _register_project_setting_import(E->key(), import_setting_string, E->get().extensions, r_extensions, E->get().is_default); + _register_project_setting_import(E->key(), import_setting_string, E->get().extensions, r_extensions, + E->get().is_default); } } -void EditorSceneImporterAssimp::_register_project_setting_import(const String generic, const String import_setting_string, const Vector<String> &exts, List<String> *r_extensions, const bool p_enabled) const { +void EditorSceneImporterAssimp::_register_project_setting_import(const String generic, const String import_setting_string, + const Vector<String> &exts, List<String> *r_extensions, + const bool p_enabled) const { const String use_generic = "use_" + generic; _GLOBAL_DEF(import_setting_string + use_generic, p_enabled, true); if (ProjectSettings::get_singleton()->get(import_setting_string + use_generic)) { @@ -92,28 +98,17 @@ uint32_t EditorSceneImporterAssimp::get_import_flags() const { return IMPORT_SCENE; } -AssimpStream::AssimpStream() { - // empty -} - -AssimpStream::~AssimpStream() { - // empty -} - -void AssimpStream::write(const char *message) { - print_verbose(String("Open Asset Import: ") + String(message).strip_edges()); -} - void EditorSceneImporterAssimp::_bind_methods() { } -Node *EditorSceneImporterAssimp::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) { +Node *EditorSceneImporterAssimp::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, + List<String> *r_missing_deps, Error *r_err) { Assimp::Importer importer; std::wstring w_path = ProjectSettings::get_singleton()->globalize_path(p_path).c_str(); std::string s_path(w_path.begin(), w_path.end()); importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); // Cannot remove pivot points because the static mesh will be in the wrong place - importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, true); + importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false); int32_t max_bone_weights = 4; //if (p_flags & IMPORT_ANIMATION_EIGHT_WEIGHTS) { // const int eight_bones = 8; @@ -122,36 +117,40 @@ Node *EditorSceneImporterAssimp::import_scene(const String &p_path, uint32_t p_f //} importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); + //importer.SetPropertyFloat(AI_CONFIG_PP_DB_THRESHOLD, 1.0f); int32_t post_process_Steps = aiProcess_CalcTangentSpace | + aiProcess_GlobalScale | + // imports models and listens to their file scale for CM to M conversions //aiProcess_FlipUVs | - //aiProcess_FlipWindingOrder | - aiProcess_DropNormals | - aiProcess_GenSmoothNormals | - aiProcess_JoinIdenticalVertices | + aiProcess_FlipWindingOrder | + // very important for culling so that it is done in the correct order. + //aiProcess_DropNormals | + //aiProcess_GenSmoothNormals | + //aiProcess_JoinIdenticalVertices | aiProcess_ImproveCacheLocality | - aiProcess_LimitBoneWeights | //aiProcess_RemoveRedundantMaterials | // Causes a crash - aiProcess_SplitLargeMeshes | + //aiProcess_SplitLargeMeshes | aiProcess_Triangulate | aiProcess_GenUVCoords | //aiProcess_FindDegenerates | - aiProcess_SortByPType | - aiProcess_FindInvalidData | + //aiProcess_SortByPType | + // aiProcess_FindInvalidData | aiProcess_TransformUVCoords | aiProcess_FindInstances | //aiProcess_FixInfacingNormals | //aiProcess_ValidateDataStructure | aiProcess_OptimizeMeshes | + aiProcess_PopulateArmatureData | //aiProcess_OptimizeGraph | //aiProcess_Debone | - aiProcess_EmbedTextures | - aiProcess_SplitByBoneCount | + // aiProcess_EmbedTextures | + //aiProcess_SplitByBoneCount | 0; - const aiScene *scene = importer.ReadFile(s_path.c_str(), - post_process_Steps); - ERR_EXPLAIN(String("Open Asset Import failed to open: ") + String(importer.GetErrorString())); - ERR_FAIL_COND_V(scene == NULL, NULL); + aiScene *scene = (aiScene *)importer.ReadFile(s_path.c_str(), post_process_Steps); + + ERR_FAIL_COND_V_MSG(scene == NULL, NULL, String("Open Asset Import failed to open: ") + String(importer.GetErrorString())); + return _generate_scene(p_path, scene, p_flags, p_bake_fps, max_bone_weights); } @@ -168,7 +167,8 @@ struct EditorSceneImporterAssetImportInterpolate { float t2 = t * t; float t3 = t2 * t; - return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); + return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); } T bezier(T start, T control_1, T control_2, T end, float t) { @@ -210,7 +210,8 @@ struct EditorSceneImporterAssetImportInterpolate<Quat> { }; template <class T> -T EditorSceneImporterAssimp::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, AssetImportAnimation::Interpolation p_interp) { +T EditorSceneImporterAssimp::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, + AssetImportAnimation::Interpolation p_interp) { //could use binary search, worth it? int idx = -1; for (int i = 0; i < p_times.size(); i++) { @@ -282,1107 +283,660 @@ T EditorSceneImporterAssimp::_interpolate_track(const Vector<float> &p_times, co ERR_FAIL_V(p_values[0]); } -Spatial *EditorSceneImporterAssimp::_generate_scene(const String &p_path, const aiScene *scene, const uint32_t p_flags, int p_bake_fps, const int32_t p_max_bone_weights) { - ERR_FAIL_COND_V(scene == NULL, NULL); - Spatial *root = memnew(Spatial); - AnimationPlayer *ap = NULL; - if (p_flags & IMPORT_ANIMATION) { - ap = memnew(AnimationPlayer); - root->add_child(ap); - ap->set_owner(root); - ap->set_name(TTR("AnimationPlayer")); - } - Set<String> bone_names; - Set<String> light_names; - Set<String> camera_names; - real_t factor = 1.0f; - String ext = p_path.get_file().get_extension().to_lower(); - if ((ext == "fbx")) { - if (scene->mMetaData != NULL) { - scene->mMetaData->Get("UnitScaleFactor", factor); - factor = factor * 0.01f; +aiBone *EditorSceneImporterAssimp::get_bone_from_stack(ImportState &state, aiString name) { + List<aiBone *>::Element *iter; + aiBone *bone = NULL; + for (iter = state.bone_stack.front(); iter; iter = iter->next()) { + bone = (aiBone *)iter->get(); + + if (bone && bone->mName == name) { + state.bone_stack.erase(bone); + return bone; } } - for (size_t l = 0; l < scene->mNumLights; l++) { - Light *light = NULL; + + return NULL; +} + +Spatial * +EditorSceneImporterAssimp::_generate_scene(const String &p_path, aiScene *scene, const uint32_t p_flags, int p_bake_fps, + const int32_t p_max_bone_weights) { + ERR_FAIL_COND_V(scene == NULL, NULL); + + ImportState state; + state.path = p_path; + state.assimp_scene = scene; + state.max_bone_weights = p_max_bone_weights; + state.animation_player = NULL; + + // populate light map + for (unsigned int l = 0; l < scene->mNumLights; l++) { + aiLight *ai_light = scene->mLights[l]; ERR_CONTINUE(ai_light == NULL); - if (ai_light->mType == aiLightSource_DIRECTIONAL) { - light = memnew(DirectionalLight); - Vector3 dir = Vector3(ai_light->mDirection.y, ai_light->mDirection.x, ai_light->mDirection.z); - dir.normalize(); - Transform xform; - Quat quat; - quat.set_euler(dir); - Vector3 pos = Vector3(ai_light->mPosition.x, ai_light->mPosition.y, ai_light->mPosition.z); - pos = factor * pos; - xform.origin = pos; - light->set_transform(xform); - } else if (ai_light->mType == aiLightSource_POINT) { - light = memnew(OmniLight); - Vector3 pos = Vector3(ai_light->mPosition.x, ai_light->mPosition.y, ai_light->mPosition.z); - Transform xform; - xform.origin = pos; - pos = factor * pos; - light->set_transform(xform); - // No idea for energy - light->set_param(Light::PARAM_ATTENUATION, 0.0f); - } else if (ai_light->mType == aiLightSource_SPOT) { - light = memnew(SpotLight); - Vector3 pos = Vector3(ai_light->mPosition.x, ai_light->mPosition.y, ai_light->mPosition.z); - pos = factor * pos; - Transform xform; - xform.origin = pos; - Vector3 dir = Vector3(ai_light->mDirection.y, ai_light->mDirection.x, ai_light->mDirection.z); - dir.normalize(); - Quat quat; - quat.set_euler(dir); - xform.basis = quat; - light->set_transform(xform); - // No idea for energy - light->set_param(Light::PARAM_ATTENUATION, 0.0f); - } - ERR_CONTINUE(light == NULL); - light->set_color(Color(ai_light->mColorDiffuse.r, ai_light->mColorDiffuse.g, ai_light->mColorDiffuse.b)); - root->add_child(light); - light->set_name(_ai_string_to_string(ai_light->mName)); - light->set_owner(root); - light_names.insert(_ai_string_to_string(scene->mLights[l]->mName)); + state.light_cache[AssimpUtils::get_assimp_string(ai_light->mName)] = l; } - for (size_t c = 0; c < scene->mNumCameras; c++) { + + // fill camera cache + for (unsigned int c = 0; c < scene->mNumCameras; c++) { aiCamera *ai_camera = scene->mCameras[c]; - Camera *camera = memnew(Camera); - float near = ai_camera->mClipPlaneNear; - if (Math::is_equal_approx(near, 0.0f)) { - near = 0.1f; - } - camera->set_perspective(Math::rad2deg(ai_camera->mHorizontalFOV) * 2.0f, near, ai_camera->mClipPlaneFar); - Vector3 pos = Vector3(ai_camera->mPosition.x, ai_camera->mPosition.y, ai_camera->mPosition.z); - - Vector3 look_at = Vector3(ai_camera->mLookAt.y, ai_camera->mLookAt.x, ai_camera->mLookAt.z).normalized(); - Quat quat; - quat.set_euler(look_at); - Transform xform; - xform.basis = quat; - xform.set_origin(pos); - root->add_child(camera); - camera->set_transform(xform); - camera->set_name(_ai_string_to_string(ai_camera->mName)); - camera->set_owner(root); - camera_names.insert(_ai_string_to_string(scene->mCameras[c]->mName)); - } - Map<Skeleton *, MeshInstance *> skeletons; - Map<String, Transform> bone_rests; - Vector<MeshInstance *> meshes; - int32_t mesh_count = 0; - Skeleton *s = memnew(Skeleton); - Set<String> removed_bones; - Map<String, Map<uint32_t, String> > path_morph_mesh_names; - _generate_node(p_path, scene, scene->mRootNode, root, root, bone_names, light_names, camera_names, skeletons, bone_rests, meshes, mesh_count, s, p_max_bone_weights, removed_bones, path_morph_mesh_names); - for (Map<Skeleton *, MeshInstance *>::Element *E = skeletons.front(); E; E = E->next()) { - E->key()->localize_rests(); + ERR_CONTINUE(ai_camera == NULL); + state.camera_cache[AssimpUtils::get_assimp_string(ai_camera->mName)] = c; } - Set<String> removed_nodes; - Set<Node *> keep_nodes; - _keep_node(p_path, root, root, keep_nodes); - _fill_kept_node(keep_nodes); - _filter_node(p_path, root, root, keep_nodes, removed_nodes); - if (p_flags & IMPORT_ANIMATION) { - for (size_t i = 0; i < scene->mNumAnimations; i++) { - _import_animation(p_path, meshes, scene, ap, i, p_bake_fps, skeletons, removed_nodes, removed_bones, path_morph_mesh_names); - } - List<StringName> animation_names; - ap->get_animation_list(&animation_names); - if (animation_names.empty()) { - root->remove_child(ap); - memdelete(ap); - } - } - return root; -} -void EditorSceneImporterAssimp::_fill_kept_node(Set<Node *> &keep_nodes) { - for (Set<Node *>::Element *E = keep_nodes.front(); E; E = E->next()) { - Node *node = E->get(); - while (node != NULL) { - if (keep_nodes.has(node) == false) { - keep_nodes.insert(node); - } - node = node->get_parent(); + if (scene->mRootNode) { + state.nodes.push_back(scene->mRootNode); + + // make flat node tree - in order to make processing deterministic + for (unsigned int i = 0; i < scene->mRootNode->mNumChildren; i++) { + _generate_node(state, scene->mRootNode->mChildren[i]); } - } -} -String EditorSceneImporterAssimp::_find_skeleton_bone_root(Map<Skeleton *, MeshInstance *> &skeletons, Map<MeshInstance *, String> &meshes, Spatial *root) { - for (Map<Skeleton *, MeshInstance *>::Element *E = skeletons.front(); E; E = E->next()) { - if (meshes.has(E->get())) { - String name = meshes[E->get()]; - if (name != "") { - return name; + RegenerateBoneStack(state); + + Node *last_valid_parent = NULL; + + List<const aiNode *>::Element *iter; + for (iter = state.nodes.front(); iter; iter = iter->next()) { + const aiNode *element_assimp_node = iter->get(); + const aiNode *parent_assimp_node = element_assimp_node->mParent; + + String node_name = AssimpUtils::get_assimp_string(element_assimp_node->mName); + //print_verbose("node: " + node_name); + + Spatial *spatial = NULL; + Transform transform = AssimpUtils::assimp_matrix_transform(element_assimp_node->mTransformation); + + // retrieve this node bone + aiBone *bone = get_bone_from_stack(state, element_assimp_node->mName); + + if (state.light_cache.has(node_name)) { + spatial = create_light(state, node_name, transform); + } else if (state.camera_cache.has(node_name)) { + spatial = create_camera(state, node_name, transform); + } else if (state.armature_nodes.find(element_assimp_node)) { + // create skeleton + print_verbose("Making skeleton: " + node_name); + Skeleton *skeleton = memnew(Skeleton); + spatial = skeleton; + if (!state.armature_skeletons.has(element_assimp_node)) { + state.armature_skeletons.insert(element_assimp_node, skeleton); + } + } else if (bone != NULL) { + continue; + } else { + spatial = memnew(Spatial); } - } - } - return ""; -} -void EditorSceneImporterAssimp::_set_bone_parent(Skeleton *s, Node *p_owner, aiNode *p_node) { - for (int32_t j = 0; j < s->get_bone_count(); j++) { - String bone_name = s->get_bone_name(j); - const aiNode *ai_bone_node = _ai_find_node(p_node, bone_name); - if (ai_bone_node == NULL) { - continue; - } - ai_bone_node = ai_bone_node->mParent; - while (ai_bone_node != NULL) { - int32_t node_parent_index = -1; - String parent_bone_name = _ai_string_to_string(ai_bone_node->mName); - node_parent_index = s->find_bone(parent_bone_name); - if (node_parent_index != -1) { - s->set_bone_parent(j, node_parent_index); - break; + ERR_CONTINUE_MSG(spatial == NULL, "FBX Import - are we out of ram?"); + // we on purpose set the transform and name after creating the node. + + spatial->set_name(node_name); + spatial->set_global_transform(transform); + + // first element is root + if (iter == state.nodes.front()) { + state.root = spatial; } - ai_bone_node = ai_bone_node->mParent; - } - } -} -void EditorSceneImporterAssimp::_insert_animation_track(const aiScene *p_scene, const String p_path, int p_bake_fps, Ref<Animation> animation, float ticks_per_second, float length, const Skeleton *sk, const aiNodeAnim *track, String node_name, NodePath node_path) { + // flat node map parent lookup tool + state.flat_node_map.insert(element_assimp_node, spatial); - if (track->mNumRotationKeys || track->mNumPositionKeys || track->mNumScalingKeys) { - //make transform track - int track_idx = animation->get_track_count(); - animation->add_track(Animation::TYPE_TRANSFORM); - animation->track_set_path(track_idx, node_path); - //first determine animation length + Map<const aiNode *, Spatial *>::Element *parent_lookup = state.flat_node_map.find(parent_assimp_node); - for (size_t i = 0; i < track->mNumRotationKeys; i++) { - length = MAX(length, track->mRotationKeys[i].mTime / ticks_per_second); - } - for (size_t i = 0; i < track->mNumPositionKeys; i++) { - length = MAX(length, track->mPositionKeys[i].mTime / ticks_per_second); - } - for (size_t i = 0; i < track->mNumScalingKeys; i++) { - length = MAX(length, track->mScalingKeys[i].mTime / ticks_per_second); - } + // note: this always fails on the root node :) keep that in mind this is by design + if (parent_lookup) { + Spatial *parent_node = parent_lookup->value(); - float increment = 1.0 / float(p_bake_fps); - float time = 0.0; - - Vector3 base_pos; - Quat base_rot; - Vector3 base_scale = Vector3(1, 1, 1); - - if (track->mNumRotationKeys != 0) { - aiQuatKey key = track->mRotationKeys[0]; - real_t x = key.mValue.x; - real_t y = key.mValue.y; - real_t z = key.mValue.z; - real_t w = key.mValue.w; - Quat q(x, y, z, w); - q = q.normalized(); - base_rot = q; - } + ERR_FAIL_COND_V_MSG(parent_node == NULL, state.root, + "Parent node invalid even though lookup successful, out of ram?") - if (track->mNumPositionKeys != 0) { - aiVectorKey key = track->mPositionKeys[0]; - real_t x = key.mValue.x; - real_t y = key.mValue.y; - real_t z = key.mValue.z; - base_pos = Vector3(x, y, z); - } + if (spatial != state.root) { + parent_node->add_child(spatial); + spatial->set_owner(state.root); + } else { + // required - think about it root never has a parent yet is valid, anything else without a parent is not valid. + } + } else if (spatial != state.root) { + // if the ainode is not in the tree + // parent it to the last good parent found + if (last_valid_parent) { + last_valid_parent->add_child(spatial); + spatial->set_owner(state.root); + } else { + // this is a serious error? + memdelete(spatial); + } + } - if (track->mNumScalingKeys != 0) { - aiVectorKey key = track->mScalingKeys[0]; - real_t x = key.mValue.x; - real_t y = key.mValue.y; - real_t z = key.mValue.z; - base_scale = Vector3(x, y, z); + // update last valid parent + last_valid_parent = spatial; } + print_verbose("node counts: " + itos(state.nodes.size())); - bool last = false; + // make clean bone stack + RegenerateBoneStack(state); - Vector<Vector3> pos_values; - Vector<float> pos_times; - Vector<Vector3> scale_values; - Vector<float> scale_times; - Vector<Quat> rot_values; - Vector<float> rot_times; + print_verbose("generating godot bone data"); - for (size_t p = 0; p < track->mNumPositionKeys; p++) { - aiVector3D pos = track->mPositionKeys[p].mValue; - pos_values.push_back(Vector3(pos.x, pos.y, pos.z)); - pos_times.push_back(track->mPositionKeys[p].mTime / ticks_per_second); - } + print_verbose("Godot bone stack count: " + itos(state.bone_stack.size())); - for (size_t r = 0; r < track->mNumRotationKeys; r++) { - aiQuaternion quat = track->mRotationKeys[r].mValue; - rot_values.push_back(Quat(quat.x, quat.y, quat.z, quat.w).normalized()); - rot_times.push_back(track->mRotationKeys[r].mTime / ticks_per_second); - } + // This is a list of bones, duplicates are from other meshes and must be dealt with properly + for (List<aiBone *>::Element *element = state.bone_stack.front(); element; element = element->next()) { + aiBone *bone = element->get(); - for (size_t sc = 0; sc < track->mNumScalingKeys; sc++) { - aiVector3D scale = track->mScalingKeys[sc].mValue; - scale_values.push_back(Vector3(scale.x, scale.y, scale.z)); - scale_times.push_back(track->mScalingKeys[sc].mTime / ticks_per_second); - } - while (true) { - Vector3 pos = base_pos; - Quat rot = base_rot; - Vector3 scale = base_scale; + ERR_CONTINUE_MSG(!bone, "invalid bone read from assimp?"); - if (pos_values.size()) { - pos = _interpolate_track<Vector3>(pos_times, pos_values, time, AssetImportAnimation::INTERP_LINEAR); - } + // Utilities for armature lookup - for now only FBX makes these + aiNode *armature_for_bone = bone->mArmature; - if (rot_values.size()) { - rot = _interpolate_track<Quat>(rot_times, rot_values, time, AssetImportAnimation::INTERP_LINEAR).normalized(); - } + // Utilities for bone node lookup - for now only FBX makes these + aiNode *bone_node = bone->mNode; + aiNode *parent_node = bone_node->mParent; - if (scale_values.size()) { - scale = _interpolate_track<Vector3>(scale_times, scale_values, time, AssetImportAnimation::INTERP_LINEAR); - } + String bone_name = AssimpUtils::get_anim_string_from_assimp(bone->mName); + ERR_CONTINUE_MSG(armature_for_bone == NULL, "Armature for bone invalid: " + bone_name); + Skeleton *skeleton = state.armature_skeletons[armature_for_bone]; - if (sk != NULL && sk->find_bone(node_name) != -1) { - Transform xform; - xform.basis.set_quat_scale(rot, scale); - xform.origin = pos; + state.skeleton_bone_map[bone] = skeleton; - int bone = sk->find_bone(node_name); - Transform rest_xform = sk->get_bone_rest(bone); - xform = rest_xform.affine_inverse() * xform; - rot = xform.basis.get_rotation_quat(); - scale = xform.basis.get_scale(); - pos = xform.origin; - } - { - Transform xform; - xform.basis.set_quat_scale(rot, scale); - xform.origin = pos; - Transform anim_xform; - String ext = p_path.get_file().get_extension().to_lower(); - if (ext == "fbx") { - real_t factor = 1.0f; - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("UnitScaleFactor", factor); - } - anim_xform = anim_xform.scaled(Vector3(factor, factor, factor)); - } - xform = anim_xform * xform; - rot = xform.basis.get_rotation_quat(); - scale = xform.basis.get_scale(); - pos = xform.origin; + if (bone_name.empty()) { + bone_name = "untitled_bone_name"; + WARN_PRINT("Untitled bone name detected... report with file please"); } - rot.normalize(); - animation->track_set_interpolation_type(track_idx, Animation::INTERPOLATION_LINEAR); - animation->transform_track_insert_key(track_idx, time, pos, rot, scale); + // todo: this is where skin support goes + if (skeleton && skeleton->find_bone(bone_name) == -1) { + print_verbose("[Godot Glue] Imported bone" + bone_name); + int boneIdx = skeleton->get_bone_count(); - if (last) { - break; - } - time += increment; - if (time >= length) { - last = true; - time = length; + Transform pform = AssimpUtils::assimp_matrix_transform(bone->mNode->mTransformation); + skeleton->add_bone(bone_name); + skeleton->set_bone_rest(boneIdx, pform); + skeleton->set_bone_pose(boneIdx, pform); + + if (parent_node != NULL) { + int parent_bone_id = skeleton->find_bone(AssimpUtils::get_anim_string_from_assimp(parent_node->mName)); + int current_bone_id = boneIdx; + skeleton->set_bone_parent(current_bone_id, parent_bone_id); + } } } - } -} -void EditorSceneImporterAssimp::_import_animation(const String p_path, const Vector<MeshInstance *> p_meshes, const aiScene *p_scene, AnimationPlayer *ap, int32_t p_index, int p_bake_fps, Map<Skeleton *, MeshInstance *> p_skeletons, const Set<String> p_removed_nodes, const Set<String> removed_bones, const Map<String, Map<uint32_t, String> > p_path_morph_mesh_names) { - String name = "Animation"; - aiAnimation const *anim = NULL; - if (p_index != -1) { - anim = p_scene->mAnimations[p_index]; - if (anim->mName.length > 0) { - name = _ai_anim_string_to_string(anim->mName); - } - } + print_verbose("generating mesh phase from skeletal mesh"); - Ref<Animation> animation; - animation.instance(); - float length = 0.0f; - animation->set_name(name); - float ticks_per_second = p_scene->mAnimations[p_index]->mTicksPerSecond; + List<Spatial *> cleanup_template_nodes; - if (p_scene->mMetaData != NULL && Math::is_equal_approx(ticks_per_second, 0.0f)) { - int32_t time_mode = 0; - p_scene->mMetaData->Get("TimeMode", time_mode); - ticks_per_second = _get_fbx_fps(time_mode, p_scene); - } + for (Map<const aiNode *, Spatial *>::Element *key_value_pair = state.flat_node_map.front(); key_value_pair; key_value_pair = key_value_pair->next()) { + const aiNode *assimp_node = key_value_pair->key(); + Spatial *mesh_template = key_value_pair->value(); - if ((p_path.get_file().get_extension().to_lower() == "glb" || p_path.get_file().get_extension().to_lower() == "gltf") && Math::is_equal_approx(ticks_per_second, 0.0f)) { - ticks_per_second = 1000.0f; - } + ERR_CONTINUE(assimp_node == NULL); + ERR_CONTINUE(mesh_template == NULL); - if (Math::is_equal_approx(ticks_per_second, 0.0f)) { - ticks_per_second = 25.0f; - } + Node *parent_node = mesh_template->get_parent(); - length = anim->mDuration / ticks_per_second; - if (anim) { - Map<String, Vector<const aiNodeAnim *> > node_tracks; - for (size_t i = 0; i < anim->mNumChannels; i++) { - const aiNodeAnim *track = anim->mChannels[i]; - String node_name = _ai_string_to_string(track->mNodeName); - NodePath node_path = node_name; - bool is_bone = false; - if (node_name.split(ASSIMP_FBX_KEY).size() > 1) { - String p_track_type = node_name.split(ASSIMP_FBX_KEY)[1]; - if (p_track_type == "_Translation" || p_track_type == "_Rotation" || p_track_type == "_Scaling") { - continue; - } - } - for (Map<Skeleton *, MeshInstance *>::Element *E = p_skeletons.front(); E; E = E->next()) { - Skeleton *sk = E->key(); - const String path = ap->get_owner()->get_path_to(sk); - if (path.empty()) { - continue; - } - if (sk->find_bone(node_name) == -1) { - continue; - } - node_path = path + ":" + node_name; - ERR_CONTINUE(ap->get_owner()->has_node(node_path) == false); - _insert_animation_track(p_scene, p_path, p_bake_fps, animation, ticks_per_second, length, sk, track, node_name, node_path); - is_bone = true; - } - if (is_bone) { - continue; - } - Node *node = ap->get_owner()->find_node(node_name); - if (node == NULL) { - continue; - } - if (p_removed_nodes.has(node_name)) { - continue; - } - const String path = ap->get_owner()->get_path_to(node); - if (path.empty()) { - print_verbose("Can't animate path"); - continue; - } - node_path = path; - if (ap->get_owner()->has_node(node_path) == false) { + if (mesh_template == state.root) { continue; } - _insert_animation_track(p_scene, p_path, p_bake_fps, animation, ticks_per_second, length, NULL, track, node_name, node_path); - } - for (size_t i = 0; i < anim->mNumChannels; i++) { - const aiNodeAnim *track = anim->mChannels[i]; - String node_name = _ai_string_to_string(track->mNodeName); - Vector<String> split_name = node_name.split(ASSIMP_FBX_KEY); - String bare_name = split_name[0]; - Node *node = ap->get_owner()->find_node(bare_name); - if (node != NULL && split_name.size() > 1) { - Map<String, Vector<const aiNodeAnim *> >::Element *E = node_tracks.find(bare_name); - Vector<const aiNodeAnim *> ai_tracks; - if (E) { - ai_tracks = E->get(); - ai_tracks.push_back(anim->mChannels[i]); - } else { - ai_tracks.push_back(anim->mChannels[i]); - } - node_tracks.insert(bare_name, ai_tracks); + + if (parent_node == NULL) { + print_error("Found invalid parent node!"); + continue; // root node } - } - for (Map<Skeleton *, MeshInstance *>::Element *E = p_skeletons.front(); E; E = E->next()) { - Skeleton *sk = E->key(); - Map<String, Vector<const aiNodeAnim *> > anim_tracks; - for (int32_t i = 0; i < sk->get_bone_count(); i++) { - String _bone_name = sk->get_bone_name(i); - Vector<const aiNodeAnim *> ai_tracks; - - if (sk->find_bone(_bone_name) == -1) { - continue; - } - for (size_t j = 0; j < anim->mNumChannels; j++) { - if (_ai_string_to_string(anim->mChannels[j]->mNodeName).split(ASSIMP_FBX_KEY).size() == 1) { - continue; - } - String track_name = _ai_string_to_string(anim->mChannels[j]->mNodeName).split(ASSIMP_FBX_KEY)[0]; - if (track_name != _bone_name) { - continue; + + String node_name = AssimpUtils::get_assimp_string(assimp_node->mName); + Transform node_transform = AssimpUtils::assimp_matrix_transform(assimp_node->mTransformation); + + if (assimp_node->mNumMeshes > 0) { + MeshInstance *mesh = create_mesh(state, assimp_node, node_name, parent_node, node_transform); + if (mesh) { + + parent_node->remove_child(mesh_template); + + // re-parent children + List<Node *> children; + // re-parent all children to new node + // note: since get_child_count will change during execution we must build a list first to be safe. + for (int childId = 0; childId < mesh_template->get_child_count(); childId++) { + // get child + Node *child = mesh_template->get_child(childId); + children.push_back(child); } - if (sk->find_bone(_bone_name) == -1) { - continue; + + for (List<Node *>::Element *element = children.front(); element; element = element->next()) { + // reparent the children to the real mesh node. + mesh_template->remove_child(element->get()); + mesh->add_child(element->get()); + element->get()->set_owner(state.root); } - ai_tracks.push_back(anim->mChannels[j]); - } - if (ai_tracks.size() == 0) { - continue; + + // update mesh in list so that each mesh node is available + // this makes the template unavailable which is the desired behaviour + state.flat_node_map[assimp_node] = mesh; + + cleanup_template_nodes.push_back(mesh_template); + + // clean up this list we don't need it + children.clear(); } - anim_tracks.insert(_bone_name, ai_tracks); - } - for (Map<String, Vector<const aiNodeAnim *> >::Element *F = anim_tracks.front(); F; F = F->next()) { - _insert_pivot_anim_track(p_meshes, F->key(), F->get(), ap, sk, length, ticks_per_second, animation, p_bake_fps, p_path, p_scene); } } - for (Map<String, Vector<const aiNodeAnim *> >::Element *E = node_tracks.front(); E; E = E->next()) { - if (p_removed_nodes.has(E->key())) { - continue; - } - if (removed_bones.find(E->key())) { - continue; - } - _insert_pivot_anim_track(p_meshes, E->key(), E->get(), ap, NULL, length, ticks_per_second, animation, p_bake_fps, p_path, p_scene); - } - for (size_t i = 0; i < anim->mNumMorphMeshChannels; i++) { - const aiMeshMorphAnim *anim_mesh = anim->mMorphMeshChannels[i]; - const String prop_name = _ai_string_to_string(anim_mesh->mName); - const String mesh_name = prop_name.split("*")[0]; - if (p_removed_nodes.has(mesh_name)) { - continue; - } - ERR_CONTINUE(prop_name.split("*").size() != 2); - const MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(ap->get_owner()->find_node(mesh_name)); - ERR_CONTINUE(mesh_instance == NULL); - if (ap->get_owner()->find_node(mesh_instance->get_name()) == NULL) { - print_verbose("Can't find mesh in scene: " + mesh_instance->get_name()); - continue; - } - const String path = ap->get_owner()->get_path_to(mesh_instance); - if (path.empty()) { - print_verbose("Can't find mesh in scene"); - continue; - } - Ref<Mesh> mesh = mesh_instance->get_mesh(); - ERR_CONTINUE(mesh.is_null()); - const Map<String, Map<uint32_t, String> >::Element *E = p_path_morph_mesh_names.find(mesh_name); - ERR_CONTINUE(E == NULL); - for (size_t k = 0; k < anim_mesh->mNumKeys; k++) { - for (size_t j = 0; j < anim_mesh->mKeys[k].mNumValuesAndWeights; j++) { - const Map<uint32_t, String>::Element *F = E->get().find(anim_mesh->mKeys[k].mValues[j]); - ERR_CONTINUE(F == NULL); - const String prop = "blend_shapes/" + F->get(); - const NodePath node_path = String(path) + ":" + prop; - ERR_CONTINUE(ap->get_owner()->has_node(node_path) == false); - int32_t blend_track_idx = -1; - if (animation->find_track(node_path) == -1) { - blend_track_idx = animation->get_track_count(); - animation->add_track(Animation::TYPE_VALUE); - animation->track_set_interpolation_type(blend_track_idx, Animation::INTERPOLATION_LINEAR); - animation->track_set_path(blend_track_idx, node_path); - } else { - blend_track_idx = animation->find_track(node_path); - } - float t = anim_mesh->mKeys[k].mTime / ticks_per_second; - float w = anim_mesh->mKeys[k].mWeights[j]; - animation->track_insert_key(blend_track_idx, t, w); - } + + for (List<Spatial *>::Element *element = cleanup_template_nodes.front(); element; element = element->next()) { + if (element->get()) { + memdelete(element->get()); } } } - animation->set_length(length); - if (animation->get_track_count()) { - ap->add_animation(name, animation); - } -} -void EditorSceneImporterAssimp::_insert_pivot_anim_track(const Vector<MeshInstance *> p_meshes, const String p_node_name, Vector<const aiNodeAnim *> F, AnimationPlayer *ap, Skeleton *sk, float &length, float ticks_per_second, Ref<Animation> animation, int p_bake_fps, const String &p_path, const aiScene *p_scene) { - NodePath node_path; - if (sk != NULL) { - const String path = ap->get_owner()->get_path_to(sk); - if (path.empty()) { - return; - } - if (sk->find_bone(p_node_name) == -1) { - return; - } - node_path = path + ":" + p_node_name; - } else { - Node *node = ap->get_owner()->find_node(p_node_name); - if (node == NULL) { - return; + if (p_flags & IMPORT_ANIMATION && scene->mNumAnimations) { + + state.animation_player = memnew(AnimationPlayer); + state.root->add_child(state.animation_player); + state.animation_player->set_owner(state.root); + + for (uint32_t i = 0; i < scene->mNumAnimations; i++) { + _import_animation(state, i, p_bake_fps); } - const String path = ap->get_owner()->get_path_to(node); - node_path = path; - } - if (node_path.is_empty()) { - return; } + // + // Cleanup operations + // + + state.mesh_cache.clear(); + state.material_cache.clear(); + state.light_cache.clear(); + state.camera_cache.clear(); + state.assimp_node_map.clear(); + state.path_to_image_cache.clear(); + state.nodes.clear(); + state.flat_node_map.clear(); + state.armature_skeletons.clear(); + state.bone_stack.clear(); + return state.root; +} + +void EditorSceneImporterAssimp::_insert_animation_track(ImportState &scene, const aiAnimation *assimp_anim, int track_id, + int anim_fps, Ref<Animation> animation, float ticks_per_second, + Skeleton *skeleton, const NodePath &node_path, + const String &node_name, aiBone *track_bone) { + const aiNodeAnim *assimp_track = assimp_anim->mChannels[track_id]; + //make transform track + int track_idx = animation->get_track_count(); + animation->add_track(Animation::TYPE_TRANSFORM); + animation->track_set_path(track_idx, node_path); + //first determine animation length + + float increment = 1.0 / float(anim_fps); + float time = 0.0; + + bool last = false; + Vector<Vector3> pos_values; Vector<float> pos_times; Vector<Vector3> scale_values; Vector<float> scale_times; Vector<Quat> rot_values; Vector<float> rot_times; - Vector3 base_pos; - Quat base_rot; - Vector3 base_scale = Vector3(1, 1, 1); - bool is_translation = false; - bool is_rotation = false; - bool is_scaling = false; - for (int32_t k = 0; k < F.size(); k++) { - String p_track_type = _ai_string_to_string(F[k]->mNodeName).split(ASSIMP_FBX_KEY)[1]; - if (p_track_type == "_Translation") { - is_translation = is_translation || true; - } else if (p_track_type == "_Rotation") { - is_rotation = is_rotation || true; - } else if (p_track_type == "_Scaling") { - is_scaling = is_scaling || true; - } else { - continue; - } - ERR_CONTINUE(ap->get_owner()->has_node(node_path) == false); - - if (F[k]->mNumRotationKeys || F[k]->mNumPositionKeys || F[k]->mNumScalingKeys) { - if (is_rotation) { - for (size_t i = 0; i < F[k]->mNumRotationKeys; i++) { - length = MAX(length, F[k]->mRotationKeys[i].mTime / ticks_per_second); - } - } - if (is_translation) { - for (size_t i = 0; i < F[k]->mNumPositionKeys; i++) { - length = MAX(length, F[k]->mPositionKeys[i].mTime / ticks_per_second); - } - } - if (is_scaling) { - for (size_t i = 0; i < F[k]->mNumScalingKeys; i++) { - length = MAX(length, F[k]->mScalingKeys[i].mTime / ticks_per_second); - } - } - - if (is_rotation == false && is_translation == false && is_scaling == false) { - return; - } - - if (is_rotation) { - if (F[k]->mNumRotationKeys != 0) { - aiQuatKey key = F[k]->mRotationKeys[0]; - real_t x = key.mValue.x; - real_t y = key.mValue.y; - real_t z = key.mValue.z; - real_t w = key.mValue.w; - Quat q(x, y, z, w); - q = q.normalized(); - base_rot = q; - } - } - - if (is_translation) { - if (F[k]->mNumPositionKeys != 0) { - aiVectorKey key = F[k]->mPositionKeys[0]; - real_t x = key.mValue.x; - real_t y = key.mValue.y; - real_t z = key.mValue.z; - base_pos = Vector3(x, y, z); - } - } - - if (is_scaling) { - if (F[k]->mNumScalingKeys != 0) { - aiVectorKey key = F[k]->mScalingKeys[0]; - real_t x = key.mValue.x; - real_t y = key.mValue.y; - real_t z = key.mValue.z; - base_scale = Vector3(x, y, z); - } - } - if (is_translation) { - for (size_t p = 0; p < F[k]->mNumPositionKeys; p++) { - aiVector3D pos = F[k]->mPositionKeys[p].mValue; - pos_values.push_back(Vector3(pos.x, pos.y, pos.z)); - pos_times.push_back(F[k]->mPositionKeys[p].mTime / ticks_per_second); - } - } + for (size_t p = 0; p < assimp_track->mNumPositionKeys; p++) { + aiVector3D pos = assimp_track->mPositionKeys[p].mValue; + pos_values.push_back(Vector3(pos.x, pos.y, pos.z)); + pos_times.push_back(assimp_track->mPositionKeys[p].mTime / ticks_per_second); + } - if (is_rotation) { - for (size_t r = 0; r < F[k]->mNumRotationKeys; r++) { - aiQuaternion quat = F[k]->mRotationKeys[r].mValue; - rot_values.push_back(Quat(quat.x, quat.y, quat.z, quat.w).normalized()); - rot_times.push_back(F[k]->mRotationKeys[r].mTime / ticks_per_second); - } - } + for (size_t r = 0; r < assimp_track->mNumRotationKeys; r++) { + aiQuaternion quat = assimp_track->mRotationKeys[r].mValue; + rot_values.push_back(Quat(quat.x, quat.y, quat.z, quat.w).normalized()); + rot_times.push_back(assimp_track->mRotationKeys[r].mTime / ticks_per_second); + } - if (is_scaling) { - for (size_t sc = 0; sc < F[k]->mNumScalingKeys; sc++) { - aiVector3D scale = F[k]->mScalingKeys[sc].mValue; - scale_values.push_back(Vector3(scale.x, scale.y, scale.z)); - scale_times.push_back(F[k]->mScalingKeys[sc].mTime / ticks_per_second); - } - } - } + for (size_t sc = 0; sc < assimp_track->mNumScalingKeys; sc++) { + aiVector3D scale = assimp_track->mScalingKeys[sc].mValue; + scale_values.push_back(Vector3(scale.x, scale.y, scale.z)); + scale_times.push_back(assimp_track->mScalingKeys[sc].mTime / ticks_per_second); } - int32_t track_idx = animation->get_track_count(); - animation->add_track(Animation::TYPE_TRANSFORM); - animation->track_set_path(track_idx, node_path); - float increment = 1.0 / float(p_bake_fps); - float time = 0.0; - bool last = false; + while (true) { - Vector3 pos = Vector3(); - Quat rot = Quat(); - Vector3 scale = Vector3(1.0f, 1.0f, 1.0f); - if (is_translation && pos_values.size()) { + Vector3 pos; + Quat rot; + Vector3 scale(1, 1, 1); + + if (pos_values.size()) { pos = _interpolate_track<Vector3>(pos_times, pos_values, time, AssetImportAnimation::INTERP_LINEAR); - Transform anim_xform; - String ext = p_path.get_file().get_extension().to_lower(); - if (ext == "fbx") { - aiNode *ai_node = _ai_find_node(p_scene->mRootNode, p_node_name); - Transform mesh_xform = _get_global_ai_node_transform(p_scene, ai_node); - pos = mesh_xform.origin + pos; - real_t factor = 1.0f; - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("UnitScaleFactor", factor); - factor = factor * 0.01f; - } - pos = pos * factor; - } } - if (is_rotation && rot_values.size()) { - rot = _interpolate_track<Quat>(rot_times, rot_values, time, AssetImportAnimation::INTERP_LINEAR).normalized(); + + if (rot_values.size()) { + rot = _interpolate_track<Quat>(rot_times, rot_values, time, + AssetImportAnimation::INTERP_LINEAR) + .normalized(); } - if (is_scaling && scale_values.size()) { + + if (scale_values.size()) { scale = _interpolate_track<Vector3>(scale_times, scale_values, time, AssetImportAnimation::INTERP_LINEAR); } + + if (skeleton) { + int skeleton_bone = skeleton->find_bone(node_name); + + if (skeleton_bone >= 0 && track_bone) { + + Transform xform; + xform.basis.set_quat_scale(rot, scale); + xform.origin = pos; + + xform = skeleton->get_bone_pose(skeleton_bone).inverse() * xform; + + rot = xform.basis.get_rotation_quat(); + rot.normalize(); + scale = xform.basis.get_scale(); + pos = xform.origin; + } else { + ERR_FAIL_MSG("Skeleton bone lookup failed for skeleton: " + skeleton->get_name()); + } + } + animation->track_set_interpolation_type(track_idx, Animation::INTERPOLATION_LINEAR); animation->transform_track_insert_key(track_idx, time, pos, rot, scale); - if (last) { + if (last) { //done this way so a key is always inserted past the end (for proper interpolation) break; } time += increment; - if (time >= length) { + if (time >= animation->get_length()) { last = true; - time = length; } } } -float EditorSceneImporterAssimp::_get_fbx_fps(int32_t time_mode, const aiScene *p_scene) { - switch (time_mode) { - case AssetImportFbx::TIME_MODE_DEFAULT: return 24; //hack - case AssetImportFbx::TIME_MODE_120: return 120; - case AssetImportFbx::TIME_MODE_100: return 100; - case AssetImportFbx::TIME_MODE_60: return 60; - case AssetImportFbx::TIME_MODE_50: return 50; - case AssetImportFbx::TIME_MODE_48: return 48; - case AssetImportFbx::TIME_MODE_30: return 30; - case AssetImportFbx::TIME_MODE_30_DROP: return 30; - case AssetImportFbx::TIME_MODE_NTSC_DROP_FRAME: return 29.9700262f; - case AssetImportFbx::TIME_MODE_NTSC_FULL_FRAME: return 29.9700262f; - case AssetImportFbx::TIME_MODE_PAL: return 25; - case AssetImportFbx::TIME_MODE_CINEMA: return 24; - case AssetImportFbx::TIME_MODE_1000: return 1000; - case AssetImportFbx::TIME_MODE_CINEMA_ND: return 23.976f; - case AssetImportFbx::TIME_MODE_CUSTOM: - int32_t frame_rate; - p_scene->mMetaData->Get("FrameRate", frame_rate); - return frame_rate; - } - return 0; -} - -Transform EditorSceneImporterAssimp::_get_global_ai_node_transform(const aiScene *p_scene, const aiNode *p_current_node) { - aiNode const *current_node = p_current_node; - Transform xform; - while (current_node != NULL) { - xform = _ai_matrix_transform(current_node->mTransformation) * xform; - current_node = current_node->mParent; - } - return xform; -} +// I really do not like this but need to figure out a better way of removing it later. +Node *EditorSceneImporterAssimp::get_node_by_name(ImportState &state, String name) { + for (Map<const aiNode *, Spatial *>::Element *key_value_pair = state.flat_node_map.front(); key_value_pair; key_value_pair = key_value_pair->next()) { + const aiNode *assimp_node = key_value_pair->key(); + Spatial *node = key_value_pair->value(); -void EditorSceneImporterAssimp::_generate_node_bone(const aiScene *p_scene, const aiNode *p_node, Map<String, bool> &p_mesh_bones, Skeleton *p_skeleton, const String p_path, const int32_t p_max_bone_weights) { - for (size_t i = 0; i < p_node->mNumMeshes; i++) { - const unsigned int mesh_idx = p_node->mMeshes[i]; - const aiMesh *ai_mesh = p_scene->mMeshes[mesh_idx]; - for (size_t j = 0; j < ai_mesh->mNumBones; j++) { - String bone_name = _ai_string_to_string(ai_mesh->mBones[j]->mName); - if (p_skeleton->find_bone(bone_name) != -1) { - continue; - } - p_mesh_bones.insert(bone_name, true); - p_skeleton->add_bone(bone_name); - int32_t idx = p_skeleton->find_bone(bone_name); - Transform xform = _ai_matrix_transform(ai_mesh->mBones[j]->mOffsetMatrix); - String ext = p_path.get_file().get_extension().to_lower(); - if (ext == "fbx") { - Transform mesh_xform = _get_global_ai_node_transform(p_scene, p_node); - mesh_xform.basis = Basis(); - xform = mesh_xform.affine_inverse() * xform; - } - p_skeleton->set_bone_rest(idx, xform.affine_inverse()); + String node_name = AssimpUtils::get_assimp_string(assimp_node->mName); + if (name == node_name && node) { + return node; } } + return NULL; } -void EditorSceneImporterAssimp::_generate_node_bone_parents(const aiScene *p_scene, const aiNode *p_node, Map<String, bool> &p_mesh_bones, Skeleton *p_skeleton, const MeshInstance *p_mi) { - for (size_t i = 0; i < p_node->mNumMeshes; i++) { - const unsigned int mesh_idx = p_node->mMeshes[i]; - const aiMesh *ai_mesh = p_scene->mMeshes[mesh_idx]; - - for (size_t j = 0; j < ai_mesh->mNumBones; j++) { - aiNode *bone_node = p_scene->mRootNode->FindNode(ai_mesh->mBones[j]->mName); - ERR_CONTINUE(bone_node == NULL); - aiNode *bone_node_parent = bone_node->mParent; - while (bone_node_parent != NULL) { - String bone_parent_name = _ai_string_to_string(bone_node_parent->mName); - bone_parent_name = bone_parent_name.split(ASSIMP_FBX_KEY)[0]; - if (bone_parent_name == p_mi->get_name()) { - break; - } - if (p_mi->get_parent() == NULL) { - break; - } - if (bone_parent_name == p_mi->get_parent()->get_name()) { - break; - } - if (bone_node_parent->mParent == p_scene->mRootNode) { - break; - } - if (p_skeleton->find_bone(bone_parent_name) == -1) { - p_mesh_bones.insert(bone_parent_name, true); - } - bone_node_parent = bone_node_parent->mParent; +/* Bone stack is a fifo handler for multiple armatures since armatures aren't a thing in assimp (yet) */ +void EditorSceneImporterAssimp::RegenerateBoneStack(ImportState &state) { + + state.bone_stack.clear(); + // build bone stack list + for (unsigned int mesh_id = 0; mesh_id < state.assimp_scene->mNumMeshes; ++mesh_id) { + aiMesh *mesh = state.assimp_scene->mMeshes[mesh_id]; + + // iterate over all the bones on the mesh for this node only! + for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) { + aiBone *bone = mesh->mBones[boneIndex]; + + // doubtful this is required right now but best to check + if (!state.bone_stack.find(bone)) { + //print_verbose("[assimp] bone stack added: " + String(bone->mName.C_Str()) ); + state.bone_stack.push_back(bone); } } } } -void EditorSceneImporterAssimp::_calculate_skeleton_root(Skeleton *s, const aiScene *p_scene, aiNode *&p_ai_skeleton_root, Map<String, bool> &mesh_bones, const aiNode *p_node) { - if (s->get_bone_count() > 0) { - String bone_name = s->get_bone_name(0); - p_ai_skeleton_root = _ai_find_node(p_scene->mRootNode, bone_name); - for (size_t i = 0; i < p_scene->mRootNode->mNumChildren; i++) { - if (p_ai_skeleton_root == NULL) { - break; - } - aiNode *found = p_scene->mRootNode->mChildren[i]->FindNode(p_ai_skeleton_root->mName); - if (found) { - p_ai_skeleton_root = p_scene->mRootNode->mChildren[i]; - break; - } - } - } - if (p_ai_skeleton_root == NULL) { - p_ai_skeleton_root = p_scene->mRootNode->FindNode(p_node->mName); - while (p_ai_skeleton_root && p_ai_skeleton_root->mParent && p_ai_skeleton_root->mParent != p_scene->mRootNode) { - p_ai_skeleton_root = p_scene->mRootNode->FindNode(p_ai_skeleton_root->mName)->mParent; +/* Bone stack is a fifo handler for multiple armatures since armatures aren't a thing in assimp (yet) */ +void EditorSceneImporterAssimp::RegenerateBoneStack(ImportState &state, aiMesh *mesh) { + state.bone_stack.clear(); + // iterate over all the bones on the mesh for this node only! + for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) { + aiBone *bone = mesh->mBones[boneIndex]; + if (state.bone_stack.find(bone) == NULL) { + state.bone_stack.push_back(bone); } } - p_ai_skeleton_root = _ai_find_node(p_scene->mRootNode, _ai_string_to_string(p_ai_skeleton_root->mName).split(ASSIMP_FBX_KEY)[0]); } -void EditorSceneImporterAssimp::_fill_skeleton(const aiScene *p_scene, const aiNode *p_node, Spatial *p_current, Node *p_owner, Skeleton *p_skeleton, const Map<String, bool> p_mesh_bones, const Map<String, Transform> &p_bone_rests, Set<String> p_tracks, const String p_path, Set<String> &r_removed_bones) { - String node_name = _ai_string_to_string(p_node->mName); - if (p_mesh_bones.find(node_name) != NULL && p_skeleton->find_bone(node_name) == -1) { - r_removed_bones.insert(node_name); - p_skeleton->add_bone(node_name); - int32_t idx = p_skeleton->find_bone(node_name); - Transform xform = _get_global_ai_node_transform(p_scene, p_node); - xform = _format_rot_xform(p_path, p_scene) * xform; - p_skeleton->set_bone_rest(idx, xform); - } +// animation tracks are per bone - for (size_t i = 0; i < p_node->mNumChildren; i++) { - _fill_skeleton(p_scene, p_node->mChildren[i], p_current, p_owner, p_skeleton, p_mesh_bones, p_bone_rests, p_tracks, p_path, r_removed_bones); - } -} +void EditorSceneImporterAssimp::_import_animation(ImportState &state, int p_animation_index, int p_bake_fps) { -void EditorSceneImporterAssimp::_keep_node(const String &p_path, Node *p_current, Node *p_owner, Set<Node *> &r_keep_nodes) { - if (p_current == p_owner) { - r_keep_nodes.insert(p_current); - } + ERR_FAIL_INDEX(p_animation_index, (int)state.assimp_scene->mNumAnimations); - if (p_current->get_class() != Spatial().get_class()) { - r_keep_nodes.insert(p_current); + const aiAnimation *anim = state.assimp_scene->mAnimations[p_animation_index]; + String name = AssimpUtils::get_anim_string_from_assimp(anim->mName); + if (name == String()) { + name = "Animation " + itos(p_animation_index + 1); } + print_verbose("import animation: " + name); + float ticks_per_second = anim->mTicksPerSecond; - for (int i = 0; i < p_current->get_child_count(); i++) { - _keep_node(p_path, p_current->get_child(i), p_owner, r_keep_nodes); + if (state.assimp_scene->mMetaData != NULL && Math::is_equal_approx(ticks_per_second, 0.0f)) { + int32_t time_mode = 0; + state.assimp_scene->mMetaData->Get("TimeMode", time_mode); + ticks_per_second = AssimpUtils::get_fbx_fps(time_mode, state.assimp_scene); } -} -void EditorSceneImporterAssimp::_filter_node(const String &p_path, Node *p_current, Node *p_owner, const Set<Node *> p_keep_nodes, Set<String> &r_removed_nodes) { - if (p_keep_nodes.has(p_current) == false) { - r_removed_nodes.insert(p_current->get_name()); - p_current->queue_delete(); - } - for (int i = 0; i < p_current->get_child_count(); i++) { - _filter_node(p_path, p_current->get_child(i), p_owner, p_keep_nodes, r_removed_nodes); - } -} + //? + //if ((p_path.get_file().get_extension().to_lower() == "glb" || p_path.get_file().get_extension().to_lower() == "gltf") && Math::is_equal_approx(ticks_per_second, 0.0f)) { + // ticks_per_second = 1000.0f; + //} -void EditorSceneImporterAssimp::_generate_node(const String &p_path, const aiScene *p_scene, const aiNode *p_node, Node *p_parent, Node *p_owner, Set<String> &r_bone_name, Set<String> p_light_names, Set<String> p_camera_names, Map<Skeleton *, MeshInstance *> &r_skeletons, const Map<String, Transform> &p_bone_rests, Vector<MeshInstance *> &r_mesh_instances, int32_t &r_mesh_count, Skeleton *p_skeleton, const int32_t p_max_bone_weights, Set<String> &r_removed_bones, Map<String, Map<uint32_t, String> > &r_name_morph_mesh_names) { - Spatial *child_node = NULL; - if (p_node == NULL) { - return; - } - String node_name = _ai_string_to_string(p_node->mName); - real_t factor = 1.0f; - String ext = p_path.get_file().get_extension().to_lower(); - if (ext == "fbx") { - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("UnitScaleFactor", factor); - factor = factor * 0.01f; - } + if (Math::is_equal_approx(ticks_per_second, 0.0f)) { + ticks_per_second = 25.0f; } - { - Transform xform = _ai_matrix_transform(p_node->mTransformation); - - child_node = memnew(Spatial); - p_parent->add_child(child_node); - child_node->set_owner(p_owner); - if (p_node == p_scene->mRootNode) { - if ((ext == "fbx") && p_node == p_scene->mRootNode) { - xform = xform.scaled(Vector3(factor, factor, factor)); - Transform format_xform = _format_rot_xform(p_path, p_scene); - xform = format_xform * xform; - } + + Ref<Animation> animation; + animation.instance(); + animation->set_name(name); + animation->set_length(anim->mDuration / ticks_per_second); + + // generate bone stack for animation import + RegenerateBoneStack(state); + + //regular tracks + for (size_t i = 0; i < anim->mNumChannels; i++) { + const aiNodeAnim *track = anim->mChannels[i]; + String node_name = AssimpUtils::get_assimp_string(track->mNodeName); + print_verbose("track name import: " + node_name); + if (track->mNumRotationKeys == 0 && track->mNumPositionKeys == 0 && track->mNumScalingKeys == 0) { + continue; //do not bother } - child_node->set_transform(xform * child_node->get_transform()); - } - if (p_node->mNumMeshes > 0) { - MeshInstance *mesh_node = memnew(MeshInstance); - p_parent->add_child(mesh_node); - mesh_node->set_owner(p_owner); - mesh_node->set_transform(child_node->get_transform()); + Skeleton *skeleton = NULL; + NodePath node_path; + aiBone *bone = NULL; + + // Import skeleton bone animation for this track + // Any bone will do, no point in processing more than just what is in the skeleton { - Map<String, bool> mesh_bones; - p_skeleton->set_use_bones_in_world_transform(true); - _generate_node_bone(p_scene, p_node, mesh_bones, p_skeleton, p_path, p_max_bone_weights); - Set<String> tracks; - _get_track_set(p_scene, tracks); - aiNode *skeleton_root = NULL; - _calculate_skeleton_root(p_skeleton, p_scene, skeleton_root, mesh_bones, p_node); - _generate_node_bone_parents(p_scene, p_node, mesh_bones, p_skeleton, mesh_node); - if (p_skeleton->get_bone_count() > 0) { - _fill_skeleton(p_scene, skeleton_root, mesh_node, p_owner, p_skeleton, mesh_bones, p_bone_rests, tracks, p_path, r_removed_bones); - _set_bone_parent(p_skeleton, p_owner, p_scene->mRootNode); - } - MeshInstance *mi = Object::cast_to<MeshInstance>(mesh_node); - if (mi) { - r_mesh_instances.push_back(mi); - } - _add_mesh_to_mesh_instance(p_node, p_scene, p_skeleton, p_path, mesh_node, p_owner, r_bone_name, r_mesh_count, p_max_bone_weights, r_name_morph_mesh_names); - } - if (mesh_node != NULL && p_skeleton->get_bone_count() > 0 && p_owner->find_node(p_skeleton->get_name()) == NULL) { - Node *node = p_owner->find_node(_ai_string_to_string(p_scene->mRootNode->mName)); - ERR_FAIL_COND(node == NULL); - node->add_child(p_skeleton); - p_skeleton->set_owner(p_owner); - if (ext == "fbx") { - Transform mesh_xform = _get_global_ai_node_transform(p_scene, p_node); - mesh_xform.origin = Vector3(); - p_skeleton->set_transform(mesh_xform); + bone = get_bone_from_stack(state, track->mNodeName); + + if (bone) { + // get skeleton by bone + skeleton = state.armature_skeletons[bone->mArmature]; + + if (skeleton) { + String path = state.root->get_path_to(skeleton); + path += ":" + node_name; + node_path = path; + + if (node_path != NodePath()) { + _insert_animation_track(state, anim, i, p_bake_fps, animation, ticks_per_second, skeleton, + node_path, node_name, bone); + } else { + print_error("Failed to find valid node path for animation"); + } + } } - r_skeletons.insert(p_skeleton, mesh_node); } - for (size_t i = 0; i < p_node->mNumMeshes; i++) { - if (p_scene->mMeshes[p_node->mMeshes[i]]->HasBones()) { - mesh_node->set_name(node_name); - // Meshes without skeletons must not have skeletons - mesh_node->set_skeleton_path(String(mesh_node->get_path_to(p_owner)) + "/" + p_owner->get_path_to(p_skeleton)); + + // not a bone + // note this is flaky it uses node names which is unreliable + Node *allocated_node = get_node_by_name(state, node_name); + // todo: implement skeleton grabbing for node based animations too :) + // check if node exists, if it does then also apply animation track for node and bones above are all handled. + // this is now inclusive animation handling so that + // we import all the data and do not miss anything. + if (allocated_node) { + node_path = state.root->get_path_to(allocated_node); + + if (node_path != NodePath()) { + _insert_animation_track(state, anim, i, p_bake_fps, animation, ticks_per_second, skeleton, + node_path, node_name, nullptr); } } - child_node->get_parent()->remove_child(child_node); - memdelete(child_node); - child_node = mesh_node; - } else if (p_light_names.has(node_name)) { - Spatial *light_node = Object::cast_to<Light>(p_owner->find_node(node_name)); - ERR_FAIL_COND(light_node == NULL); - if (!p_parent->has_node(light_node->get_path())) { - p_parent->add_child(light_node); - } - light_node->set_owner(p_owner); - light_node->set_transform(child_node->get_transform().scaled(Vector3(factor, factor, factor)) * - light_node->get_transform().scaled(Vector3(factor, factor, factor))); - child_node->get_parent()->remove_child(child_node); - memdelete(child_node); - child_node = light_node; - } else if (p_camera_names.has(node_name)) { - Spatial *camera_node = Object::cast_to<Camera>(p_owner->find_node(node_name)); - ERR_FAIL_COND(camera_node == NULL); - if (!p_parent->has_node(camera_node->get_path())) { - p_parent->add_child(camera_node); - } - camera_node->set_owner(p_owner); - camera_node->set_transform(child_node->get_transform().scaled(Vector3(factor, factor, factor)) * - camera_node->get_transform().scaled(Vector3(factor, factor, factor))); - camera_node->scale(Vector3(factor, factor, factor)); - child_node->get_parent()->remove_child(child_node); - memdelete(child_node); - child_node = camera_node; } - child_node->set_name(node_name); - for (size_t i = 0; i < p_node->mNumChildren; i++) { - _generate_node(p_path, p_scene, p_node->mChildren[i], child_node, p_owner, r_bone_name, p_light_names, p_camera_names, r_skeletons, p_bone_rests, r_mesh_instances, r_mesh_count, p_skeleton, p_max_bone_weights, r_removed_bones, r_name_morph_mesh_names); - } -} -aiNode *EditorSceneImporterAssimp::_ai_find_node(aiNode *ai_child_node, const String bone_name) { + //blend shape tracks - if (_ai_string_to_string(ai_child_node->mName) == bone_name) { - return ai_child_node; - } - aiNode *target = NULL; - for (size_t i = 0; i < ai_child_node->mNumChildren; i++) { + for (size_t i = 0; i < anim->mNumMorphMeshChannels; i++) { - target = _ai_find_node(ai_child_node->mChildren[i], bone_name); - if (target != NULL) { - return target; - } - } - return target; -} + const aiMeshMorphAnim *anim_mesh = anim->mMorphMeshChannels[i]; -Transform EditorSceneImporterAssimp::_format_rot_xform(const String p_path, const aiScene *p_scene) { - String ext = p_path.get_file().get_extension().to_lower(); - - Transform xform; - int32_t up_axis = 0; - Vector3 up_axis_vec3 = Vector3(); - - int32_t front_axis = 0; - Vector3 front_axis_vec3 = Vector3(); - - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("UpAxis", up_axis); - if (up_axis == AssetImportFbx::UP_VECTOR_AXIS_X) { - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("FrontAxis", front_axis); - if (front_axis == AssetImportFbx::FRONT_PARITY_EVEN) { - // y - } else if (front_axis == AssetImportFbx::FRONT_PARITY_ODD) { - // z - //front_axis_vec3 = Vector3(0.0f, Math::deg2rad(-180.f), 0.0f); - } - } - } else if (up_axis == AssetImportFbx::UP_VECTOR_AXIS_Y) { - up_axis_vec3 = Vector3(Math::deg2rad(-90.f), 0.0f, 0.0f); - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("FrontAxis", front_axis); - if (front_axis == AssetImportFbx::FRONT_PARITY_EVEN) { - // x - } else if (front_axis == AssetImportFbx::FRONT_PARITY_ODD) { - // z - } - } - } else if (up_axis == AssetImportFbx::UP_VECTOR_AXIS_Z) { - up_axis_vec3 = Vector3(0.0f, Math ::deg2rad(90.f), 0.0f); - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("FrontAxis", front_axis); - if (front_axis == AssetImportFbx::FRONT_PARITY_EVEN) { - // x - } else if (front_axis == AssetImportFbx::FRONT_PARITY_ODD) { - // y - } - } - } - } + const String prop_name = AssimpUtils::get_assimp_string(anim_mesh->mName); + const String mesh_name = prop_name.split("*")[0]; - int32_t up_axis_sign = 0; - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("UpAxisSign", up_axis_sign); - up_axis_vec3 = up_axis_vec3 * up_axis_sign; - } + ERR_CONTINUE(prop_name.split("*").size() != 2); - int32_t front_axis_sign = 0; - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("FrontAxisSign", front_axis_sign); - front_axis_vec3 = front_axis_vec3 * front_axis_sign; - } + Node *item = get_node_by_name(state, mesh_name); + ERR_CONTINUE_MSG(!item, "failed to look up node by name"); + const MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(item); + ERR_CONTINUE(mesh_instance == NULL); - int32_t coord_axis = 0; - Vector3 coord_axis_vec3 = Vector3(); - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("CoordAxis", coord_axis); - if (coord_axis == AssetImportFbx::COORD_LEFT) { - } else if (coord_axis == AssetImportFbx::COORD_RIGHT) { - } - } + String base_path = state.root->get_path_to(mesh_instance); - int32_t coord_axis_sign = 0; - if (p_scene->mMetaData != NULL) { - p_scene->mMetaData->Get("CoordAxisSign", coord_axis_sign); - } + Ref<Mesh> mesh = mesh_instance->get_mesh(); + ERR_CONTINUE(mesh.is_null()); - Quat up_quat; - up_quat.set_euler(up_axis_vec3); + //add the tracks for this mesh + int base_track = animation->get_track_count(); + for (int j = 0; j < mesh->get_blend_shape_count(); j++) { - Quat coord_quat; - coord_quat.set_euler(coord_axis_vec3); + animation->add_track(Animation::TYPE_VALUE); + animation->track_set_path(base_track + j, base_path + ":blend_shapes/" + mesh->get_blend_shape_name(j)); + } - Quat front_quat; - front_quat.set_euler(front_axis_vec3); + for (size_t k = 0; k < anim_mesh->mNumKeys; k++) { + for (size_t j = 0; j < anim_mesh->mKeys[k].mNumValuesAndWeights; j++) { - xform.basis.set_quat(up_quat * coord_quat * front_quat); - return xform; -} + float t = anim_mesh->mKeys[k].mTime / ticks_per_second; + float w = anim_mesh->mKeys[k].mWeights[j]; -void EditorSceneImporterAssimp::_get_track_set(const aiScene *p_scene, Set<String> &tracks) { - for (size_t i = 0; i < p_scene->mNumAnimations; i++) { - for (size_t j = 0; j < p_scene->mAnimations[i]->mNumChannels; j++) { - aiString ai_name = p_scene->mAnimations[i]->mChannels[j]->mNodeName; - String name = _ai_string_to_string(ai_name); - tracks.insert(name); + animation->track_insert_key(base_track + j, t, w); + } } } + + if (animation->get_track_count()) { + state.animation_player->add_animation(name, animation); + } } +// +// Mesh Generation from indices ? why do we need so much mesh code +// [debt needs looked into] +Ref<Mesh> +EditorSceneImporterAssimp::_generate_mesh_from_surface_indices(ImportState &state, const Vector<int> &p_surface_indices, + const aiNode *assimp_node, Ref<Skin> &skin, + Skeleton *&skeleton_assigned) { -void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, const aiScene *p_scene, Skeleton *s, const String &p_path, MeshInstance *p_mesh_instance, Node *p_owner, Set<String> &r_bone_name, int32_t &r_mesh_count, int32_t p_max_bone_weights, Map<String, Map<uint32_t, String> > &r_name_morph_mesh_names) { Ref<ArrayMesh> mesh; mesh.instance(); bool has_uvs = false; - for (size_t i = 0; i < p_node->mNumMeshes; i++) { - const unsigned int mesh_idx = p_node->mMeshes[i]; - const aiMesh *ai_mesh = p_scene->mMeshes[mesh_idx]; - - Map<uint32_t, Vector<float> > vertex_weight; - Map<uint32_t, Vector<String> > vertex_bone_name; - for (size_t b = 0; b < ai_mesh->mNumBones; b++) { - aiBone *bone = ai_mesh->mBones[b]; - for (size_t w = 0; w < bone->mNumWeights; w++) { - String name = _ai_string_to_string(bone->mName); - aiVertexWeight ai_weights = bone->mWeights[w]; - uint32_t vertexId = ai_weights.mVertexId; - Map<uint32_t, Vector<float> >::Element *result = vertex_weight.find(vertexId); - Vector<float> weights; - if (result != NULL) { - weights.append_array(result->value()); - } - weights.push_back(ai_weights.mWeight); - if (vertex_weight.has(vertexId)) { - vertex_weight[vertexId] = weights; - } else { - vertex_weight.insert(vertexId, weights); + + Map<String, uint32_t> morph_mesh_string_lookup; + + for (int i = 0; i < p_surface_indices.size(); i++) { + const unsigned int mesh_idx = p_surface_indices[0]; + const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_idx]; + for (size_t j = 0; j < ai_mesh->mNumAnimMeshes; j++) { + String ai_anim_mesh_name = AssimpUtils::get_assimp_string(ai_mesh->mAnimMeshes[j]->mName); + if (!morph_mesh_string_lookup.has(ai_anim_mesh_name)) { + morph_mesh_string_lookup.insert(ai_anim_mesh_name, j); + mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED); + if (ai_anim_mesh_name.empty()) { + ai_anim_mesh_name = String("morph_") + itos(j); } - Map<uint32_t, Vector<String> >::Element *bone_result = vertex_bone_name.find(vertexId); - Vector<String> bone_names; - if (bone_result != NULL) { - bone_names.append_array(bone_result->value()); + mesh->add_blend_shape(ai_anim_mesh_name); + } + } + } + // + // Process Vertex Weights + // + for (int i = 0; i < p_surface_indices.size(); i++) { + const unsigned int mesh_idx = p_surface_indices[i]; + const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_idx]; + + Map<uint32_t, Vector<BoneInfo> > vertex_weights; + + if (ai_mesh->mNumBones > 0) { + for (size_t b = 0; b < ai_mesh->mNumBones; b++) { + aiBone *bone = ai_mesh->mBones[b]; + + if (!skeleton_assigned) { + print_verbose("Assigned mesh skeleton during mesh creation"); + skeleton_assigned = state.skeleton_bone_map[bone]; + + if (!skin.is_valid()) { + print_verbose("Configured new skin"); + skin.instance(); + } else { + print_verbose("Reusing existing skin!"); + } } - bone_names.push_back(name); - if (vertex_bone_name.has(vertexId)) { - vertex_bone_name[vertexId] = bone_names; - } else { - vertex_bone_name.insert(vertexId, bone_names); + // skeleton_assigned = + String bone_name = AssimpUtils::get_assimp_string(bone->mName); + int bone_index = skeleton_assigned->find_bone(bone_name); + ERR_CONTINUE(bone_index == -1); + for (size_t w = 0; w < bone->mNumWeights; w++) { + + aiVertexWeight ai_weights = bone->mWeights[w]; + + BoneInfo bi; + uint32_t vertex_index = ai_weights.mVertexId; + bi.bone = bone_index; + bi.weight = ai_weights.mWeight; + + if (!vertex_weights.has(vertex_index)) { + vertex_weights[vertex_index] = Vector<BoneInfo>(); + } + + vertex_weights[vertex_index].push_back(bi); } } } + // + // Create mesh from data from assimp + // + Ref<SurfaceTool> st; st.instance(); st->begin(Mesh::PRIMITIVE_TRIANGLES); for (size_t j = 0; j < ai_mesh->mNumVertices; j++) { + + // Get the texture coordinates if they exist if (ai_mesh->HasTextureCoords(0)) { has_uvs = true; st->add_uv(Vector2(ai_mesh->mTextureCoords[0][j].x, 1.0f - ai_mesh->mTextureCoords[0][j].y)); } + if (ai_mesh->HasTextureCoords(1)) { has_uvs = true; st->add_uv2(Vector2(ai_mesh->mTextureCoords[1][j].x, 1.0f - ai_mesh->mTextureCoords[1][j].y)); } + + // Assign vertex colors if (ai_mesh->HasVertexColors(0)) { - Color color = Color(ai_mesh->mColors[0]->r, ai_mesh->mColors[0]->g, ai_mesh->mColors[0]->b, ai_mesh->mColors[0]->a); + Color color = Color(ai_mesh->mColors[0]->r, ai_mesh->mColors[0]->g, ai_mesh->mColors[0]->b, + ai_mesh->mColors[0]->a); st->add_color(color); } + + // Work out normal calculations? - this needs work it doesn't work properly on huestos if (ai_mesh->mNormals != NULL) { const aiVector3D normals = ai_mesh->mNormals[j]; const Vector3 godot_normal = Vector3(normals.x, normals.y, normals.z); @@ -1397,59 +951,46 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, } } - if (s != NULL && s->get_bone_count() > 0) { - Map<uint32_t, Vector<String> >::Element *I = vertex_bone_name.find(j); - Vector<int32_t> bones; - if (I != NULL) { - Vector<String> bone_names; - bone_names.append_array(I->value()); - for (int32_t f = 0; f < bone_names.size(); f++) { - int32_t bone = s->find_bone(bone_names[f]); - ERR_EXPLAIN("Asset Importer: Mesh can't find bone " + bone_names[f]); - ERR_FAIL_COND(bone == -1); - bones.push_back(bone); - } - if (s->get_bone_count()) { - int32_t add = CLAMP(p_max_bone_weights - bones.size(), 0, p_max_bone_weights); - for (int32_t f = 0; f < add; f++) { - bones.push_back(0); - } - } - st->add_bones(bones); - Map<uint32_t, Vector<float> >::Element *E = vertex_weight.find(j); - Vector<float> weights; - if (E != NULL) { - weights = E->value(); - if (weights.size() != p_max_bone_weights) { - int32_t add = CLAMP(p_max_bone_weights - weights.size(), 0, p_max_bone_weights); - for (int32_t f = 0; f < add; f++) { - weights.push_back(0.0f); - } - } - } - ERR_CONTINUE(weights.size() == 0); - st->add_weights(weights); + // We have vertex weights right? + if (vertex_weights.has(j)) { + + Vector<BoneInfo> bone_info = vertex_weights[j]; + Vector<int> bones; + bones.resize(bone_info.size()); + Vector<float> weights; + weights.resize(bone_info.size()); + + // todo? do we really need to loop over all bones? - assimp may have helper to find all influences on this vertex. + for (int k = 0; k < bone_info.size(); k++) { + bones.write[k] = bone_info[k].bone; + weights.write[k] = bone_info[k].weight; } + + st->add_bones(bones); + st->add_weights(weights); } + + // Assign vertex const aiVector3D pos = ai_mesh->mVertices[j]; + + // note we must include node offset transform as this is relative to world space not local space. Vector3 godot_pos = Vector3(pos.x, pos.y, pos.z); st->add_vertex(godot_pos); } + + // fire replacement for face handling for (size_t j = 0; j < ai_mesh->mNumFaces; j++) { const aiFace face = ai_mesh->mFaces[j]; - ERR_FAIL_COND(face.mNumIndices != 3); - Vector<size_t> order; - order.push_back(2); - order.push_back(1); - order.push_back(0); - for (int32_t k = 0; k < order.size(); k++) { - st->add_index(face.mIndices[order[k]]); + for (unsigned int k = 0; k < face.mNumIndices; k++) { + st->add_index(face.mIndices[k]); } } + if (ai_mesh->HasTangentsAndBitangents() == false && has_uvs) { st->generate_tangents(); } - aiMaterial *ai_material = p_scene->mMaterials[ai_mesh->mMaterialIndex]; + + aiMaterial *ai_material = state.assimp_scene->mMaterials[ai_mesh->mMaterialIndex]; Ref<SpatialMaterial> mat; mat.instance(); @@ -1457,394 +998,202 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, if (AI_SUCCESS == ai_material->Get(AI_MATKEY_TWOSIDED, mat_two_sided)) { if (mat_two_sided > 0) { mat->set_cull_mode(SpatialMaterial::CULL_DISABLED); + } else { + mat->set_cull_mode(SpatialMaterial::CULL_BACK); } } - const String mesh_name = _ai_string_to_string(ai_mesh->mName); aiString mat_name; if (AI_SUCCESS == ai_material->Get(AI_MATKEY_NAME, mat_name)) { - mat->set_name(_ai_string_to_string(mat_name)); + mat->set_name(AssimpUtils::get_assimp_string(mat_name)); } - aiTextureType tex_normal = aiTextureType_NORMALS; - { - aiString ai_filename = aiString(); - String filename = ""; - aiTextureMapMode map_mode[2]; - - if (AI_SUCCESS == ai_material->GetTexture(tex_normal, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) { - filename = _ai_raw_string_to_string(ai_filename); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - - if (texture != NULL) { - if (map_mode != NULL) { - _set_texture_mapping_mode(map_mode, texture); - } - mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true); - mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture); - } - } - } - } + // Culling handling for meshes + + // cull all back faces + mat->set_cull_mode(SpatialMaterial::CULL_DISABLED); + // Now process materials + aiTextureType base_color = aiTextureType_BASE_COLOR; { - aiString ai_filename = aiString(); - String filename = ""; + String filename, path; + AssimpImageData image_data; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_NORMAL_TEXTURE, ai_filename)) { - filename = _ai_raw_string_to_string(ai_filename); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - if (texture != NULL) { - mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true); - mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture); - } + if (AssimpUtils::GetAssimpTexture(state, ai_material, base_color, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); + + // anything transparent must be culled + if (image_data.raw_image->detect_alpha() != Image::ALPHA_NONE) { + mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); + mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); + mat->set_cull_mode( + SpatialMaterial::CULL_DISABLED); // since you can see both sides in transparent mode } + + mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, image_data.texture); } } - aiTextureType tex_emissive = aiTextureType_EMISSIVE; + aiTextureType tex_diffuse = aiTextureType_DIFFUSE; + { + String filename, path; + AssimpImageData image_data; - if (ai_material->GetTextureCount(tex_emissive) > 0) { + if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_diffuse, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); - aiString ai_filename = aiString(); - String filename = ""; - aiTextureMapMode map_mode[2]; - - if (AI_SUCCESS == ai_material->GetTexture(tex_emissive, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) { - filename = _ai_raw_string_to_string(ai_filename); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - if (texture != NULL) { - _set_texture_mapping_mode(map_mode, texture); - mat->set_feature(SpatialMaterial::FEATURE_EMISSION, true); - mat->set_texture(SpatialMaterial::TEXTURE_EMISSION, texture); - } + // anything transparent must be culled + if (image_data.raw_image->detect_alpha() != Image::ALPHA_NONE) { + mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); + mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); + mat->set_cull_mode( + SpatialMaterial::CULL_DISABLED); // since you can see both sides in transparent mode } - } - } - - aiTextureType tex_albedo = aiTextureType_DIFFUSE; - if (ai_material->GetTextureCount(tex_albedo) > 0) { - aiString ai_filename = aiString(); - String filename = ""; - aiTextureMapMode map_mode[2]; - if (AI_SUCCESS == ai_material->GetTexture(tex_albedo, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) { - filename = _ai_raw_string_to_string(ai_filename); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - if (texture != NULL) { - if (texture->get_data()->detect_alpha() != Image::ALPHA_NONE) { - _set_texture_mapping_mode(map_mode, texture); - mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); - mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); - } - mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture); - } - } + mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, image_data.texture); } - } else { + aiColor4D clr_diffuse; if (AI_SUCCESS == ai_material->Get(AI_MATKEY_COLOR_DIFFUSE, clr_diffuse)) { if (Math::is_equal_approx(clr_diffuse.a, 1.0f) == false) { mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); + mat->set_cull_mode( + SpatialMaterial::CULL_DISABLED); // since you can see both sides in transparent mode } mat->set_albedo(Color(clr_diffuse.r, clr_diffuse.g, clr_diffuse.b, clr_diffuse.a)); } } - aiString tex_gltf_base_color_path = aiString(); - aiTextureMapMode map_mode[2]; - if (AI_SUCCESS == ai_material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, &tex_gltf_base_color_path, NULL, NULL, NULL, NULL, map_mode)) { - String filename = _ai_raw_string_to_string(tex_gltf_base_color_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - _find_texture_path(p_path, path, found); - if (texture != NULL) { - if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) { - _set_texture_mapping_mode(map_mode, texture); - mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); - mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); - } - mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture); - } - } - } else { - aiColor4D pbr_base_color; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR, pbr_base_color)) { - if (Math::is_equal_approx(pbr_base_color.a, 1.0f) == false) { - mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); - mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); - } - mat->set_albedo(Color(pbr_base_color.r, pbr_base_color.g, pbr_base_color.b, pbr_base_color.a)); - } - } + aiTextureType tex_normal = aiTextureType_NORMALS; { - aiString tex_fbx_pbs_base_color_path = aiString(); - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_TEXTURE, tex_fbx_pbs_base_color_path)) { - String filename = _ai_raw_string_to_string(tex_fbx_pbs_base_color_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - _find_texture_path(p_path, path, found); - if (texture != NULL) { - if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) { - mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); - mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); - } - mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture); - } - } + String filename, path; + Ref<ImageTexture> texture; + AssimpImageData image_data; + + // Process texture normal map + if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_normal, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); + mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true); + mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, image_data.texture); } else { - aiColor4D pbr_base_color; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_FACTOR, pbr_base_color)) { - mat->set_albedo(Color(pbr_base_color.r, pbr_base_color.g, pbr_base_color.b, pbr_base_color.a)); - } - } - - aiUVTransform pbr_base_color_uv_xform; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_UV_XFORM, pbr_base_color_uv_xform)) { - mat->set_uv1_offset(Vector3(pbr_base_color_uv_xform.mTranslation.x, pbr_base_color_uv_xform.mTranslation.y, 0.0f)); - mat->set_uv1_scale(Vector3(pbr_base_color_uv_xform.mScaling.x, pbr_base_color_uv_xform.mScaling.y, 1.0f)); - } - } - - { - aiString tex_fbx_pbs_normal_path = aiString(); - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_NORMAL_TEXTURE, tex_fbx_pbs_normal_path)) { - String filename = _ai_raw_string_to_string(tex_fbx_pbs_normal_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - _find_texture_path(p_path, path, found); - if (texture != NULL) { + aiString texture_path; + if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_NORMAL_TEXTURE, AI_PROPERTIES, texture_path)) { + if (AssimpUtils::CreateAssimpTexture(state, texture_path, filename, path, image_data)) { mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true); - mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture); + mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, image_data.texture); } } } } - aiString cull_mode; - if (p_node->mMetaData) { - p_node->mMetaData->Get("Culling", cull_mode); - } - if (cull_mode.length != 0 && cull_mode == aiString("CullingOff")) { - mat->set_cull_mode(SpatialMaterial::CULL_DISABLED); - } - + aiTextureType tex_normal_camera = aiTextureType_NORMAL_CAMERA; { - aiString tex_fbx_stingray_normal_path = aiString(); - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_TEXTURE, tex_fbx_stingray_normal_path)) { - String filename = _ai_raw_string_to_string(tex_fbx_stingray_normal_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - _find_texture_path(p_path, path, found); - if (texture != NULL) { - mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true); - mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture); - } - } + String filename, path; + Ref<ImageTexture> texture; + AssimpImageData image_data; + + // Process texture normal map + if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_normal_camera, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); + mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true); + mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, image_data.texture); } } + aiTextureType tex_emission_color = aiTextureType_EMISSION_COLOR; { - aiString tex_fbx_pbs_base_color_path = aiString(); - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_TEXTURE, tex_fbx_pbs_base_color_path)) { - String filename = _ai_raw_string_to_string(tex_fbx_pbs_base_color_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - _find_texture_path(p_path, path, found); - if (texture != NULL) { - if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) { - mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); - mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); - } - mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture); - } - } - } else { - aiColor4D pbr_base_color; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_BASE_COLOR_FACTOR, pbr_base_color)) { - mat->set_albedo(Color(pbr_base_color.r, pbr_base_color.g, pbr_base_color.b, pbr_base_color.a)); - } - } + String filename, path; + Ref<ImageTexture> texture; + AssimpImageData image_data; - aiUVTransform pbr_base_color_uv_xform; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_UV_XFORM, pbr_base_color_uv_xform)) { - mat->set_uv1_offset(Vector3(pbr_base_color_uv_xform.mTranslation.x, pbr_base_color_uv_xform.mTranslation.y, 0.0f)); - mat->set_uv1_scale(Vector3(pbr_base_color_uv_xform.mScaling.x, pbr_base_color_uv_xform.mScaling.y, 1.0f)); + // Process texture normal map + if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_emission_color, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); + mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true); + mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, image_data.texture); } } + aiTextureType tex_metalness = aiTextureType_METALNESS; { - aiString tex_fbx_pbs_emissive_path = aiString(); - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_TEXTURE, tex_fbx_pbs_emissive_path)) { - String filename = _ai_raw_string_to_string(tex_fbx_pbs_emissive_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - _find_texture_path(p_path, path, found); - if (texture != NULL) { - if (texture->get_data()->detect_alpha() == Image::ALPHA_BLEND) { - mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); - mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); - } - mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture); - } - } - } else { - aiColor4D pbr_emmissive_color; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_FACTOR, pbr_emmissive_color)) { - mat->set_emission(Color(pbr_emmissive_color.r, pbr_emmissive_color.g, pbr_emmissive_color.b, pbr_emmissive_color.a)); - } - } + String filename, path; + Ref<ImageTexture> texture; + AssimpImageData image_data; - real_t pbr_emission_intensity; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_INTENSITY_FACTOR, pbr_emission_intensity)) { - mat->set_emission_energy(pbr_emission_intensity); + // Process texture normal map + if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_metalness, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); + mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, image_data.texture); } } - aiString tex_gltf_pbr_metallicroughness_path; - if (AI_SUCCESS == ai_material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, &tex_gltf_pbr_metallicroughness_path)) { - String filename = _ai_raw_string_to_string(tex_gltf_pbr_metallicroughness_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - if (texture != NULL) { - mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture); - mat->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_BLUE); - mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture); - mat->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GREEN); - } - } - } else { - float pbr_roughness = 0.0f; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR, pbr_roughness)) { - mat->set_roughness(pbr_roughness); - } - float pbr_metallic = 0.0f; + aiTextureType tex_roughness = aiTextureType_DIFFUSE_ROUGHNESS; + { + String filename, path; + Ref<ImageTexture> texture; + AssimpImageData image_data; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR, pbr_metallic)) { - mat->set_metallic(pbr_metallic); + // Process texture normal map + if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_roughness, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); + mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, image_data.texture); } } + + aiTextureType tex_emissive = aiTextureType_EMISSIVE; { - aiString tex_fbx_pbs_metallic_path; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_TEXTURE, tex_fbx_pbs_metallic_path)) { - String filename = _ai_raw_string_to_string(tex_fbx_pbs_metallic_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - if (texture != NULL) { - mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture); - mat->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE); - } - } + String filename = ""; + String path = ""; + Ref<Image> texture; + AssimpImageData image_data; + + if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_emissive, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); + mat->set_feature(SpatialMaterial::FEATURE_EMISSION, true); + mat->set_texture(SpatialMaterial::TEXTURE_EMISSION, image_data.texture); } else { - float pbr_metallic = 0.0f; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_FACTOR, pbr_metallic)) { - mat->set_metallic(pbr_metallic); - } - } - - aiString tex_fbx_pbs_rough_path; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_TEXTURE, tex_fbx_pbs_rough_path)) { - String filename = _ai_raw_string_to_string(tex_fbx_pbs_rough_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - if (texture != NULL) { - mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture); - mat->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE); + // Process emission textures + aiString texture_emissive_path; + if (AI_SUCCESS == + ai_material->Get(AI_MATKEY_FBX_MAYA_EMISSION_TEXTURE, AI_PROPERTIES, texture_emissive_path)) { + if (AssimpUtils::CreateAssimpTexture(state, texture_emissive_path, filename, path, image_data)) { + mat->set_feature(SpatialMaterial::FEATURE_EMISSION, true); + mat->set_texture(SpatialMaterial::TEXTURE_EMISSION, image_data.texture); + } + } else { + float pbr_emission = 0.0f; + if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_EMISSIVE_FACTOR, AI_NULL, pbr_emission)) { + mat->set_emission(Color(pbr_emission, pbr_emission, pbr_emission, 1.0f)); } - } - } else { - float pbr_roughness = 0.04f; - - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_FACTOR, pbr_roughness)) { - mat->set_roughness(pbr_roughness); } } } + aiTextureType tex_specular = aiTextureType_SPECULAR; { - aiString tex_fbx_pbs_metallic_path; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_METALNESS_TEXTURE, tex_fbx_pbs_metallic_path)) { - String filename = _ai_raw_string_to_string(tex_fbx_pbs_metallic_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - if (texture != NULL) { - mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture); - mat->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE); - } - } - } else { - float pbr_metallic = 0.0f; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_METALNESS_FACTOR, pbr_metallic)) { - mat->set_metallic(pbr_metallic); - } + String filename, path; + Ref<ImageTexture> texture; + AssimpImageData image_data; + + // Process texture normal map + if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_specular, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); + mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, image_data.texture); } + } - aiString tex_fbx_pbs_rough_path; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_TEXTURE, tex_fbx_pbs_rough_path)) { - String filename = _ai_raw_string_to_string(tex_fbx_pbs_rough_path); - String path = p_path.get_base_dir() + "/" + filename.replace("\\", "/"); - bool found = false; - _find_texture_path(p_path, path, found); - if (found) { - Ref<Texture> texture = _load_texture(p_scene, path); - if (texture != NULL) { - mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture); - mat->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GRAYSCALE); - } - } - } else { - float pbr_roughness = 0.04f; + aiTextureType tex_ao_map = aiTextureType_AMBIENT_OCCLUSION; + { + String filename, path; + Ref<ImageTexture> texture; + AssimpImageData image_data; - if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_FACTOR, pbr_roughness)) { - mat->set_roughness(pbr_roughness); - } + // Process texture normal map + if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_ao_map, filename, path, image_data)) { + AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture); + mat->set_feature(SpatialMaterial::FEATURE_AMBIENT_OCCLUSION, true); + mat->set_texture(SpatialMaterial::TEXTURE_AMBIENT_OCCLUSION, image_data.texture); } } @@ -1852,16 +1201,15 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, Array morphs; morphs.resize(ai_mesh->mNumAnimMeshes); Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES; - Map<uint32_t, String> morph_mesh_idx_names; + for (size_t j = 0; j < ai_mesh->mNumAnimMeshes; j++) { - String ai_anim_mesh_name = _ai_string_to_string(ai_mesh->mAnimMeshes[j]->mName); - mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED); + String ai_anim_mesh_name = AssimpUtils::get_assimp_string(ai_mesh->mAnimMeshes[j]->mName); + if (ai_anim_mesh_name.empty()) { ai_anim_mesh_name = String("morph_") + itos(j); } - mesh->add_blend_shape(ai_anim_mesh_name); - morph_mesh_idx_names.insert(j, ai_anim_mesh_name); + Array array_copy; array_copy.resize(VisualServer::ARRAY_MAX); @@ -1880,12 +1228,11 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, vertices.write()[l] = position; } PoolVector3Array new_vertices = array_copy[VisualServer::ARRAY_VERTEX].duplicate(true); - - for (int32_t l = 0; l < vertices.size(); l++) { + ERR_CONTINUE(vertices.size() != new_vertices.size()); + for (int32_t l = 0; l < new_vertices.size(); l++) { PoolVector3Array::Write w = new_vertices.write(); w[l] = vertices[l]; } - ERR_CONTINUE(vertices.size() != new_vertices.size()); array_copy[VisualServer::ARRAY_VERTEX] = new_vertices; } @@ -1899,7 +1246,7 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, colors.write()[l] = color; } PoolColorArray new_colors = array_copy[VisualServer::ARRAY_COLOR].duplicate(true); - + ERR_CONTINUE(colors.size() != new_colors.size()); for (int32_t l = 0; l < colors.size(); l++) { PoolColorArray::Write w = new_colors.write(); w[l] = colors[l]; @@ -1911,12 +1258,12 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, PoolVector3Array normals; normals.resize(num_vertices); for (size_t l = 0; l < num_vertices; l++) { - const aiVector3D ai_normal = ai_mesh->mAnimMeshes[i]->mNormals[l]; + const aiVector3D ai_normal = ai_mesh->mAnimMeshes[j]->mNormals[l]; Vector3 normal = Vector3(ai_normal.x, ai_normal.y, ai_normal.z); normals.write()[l] = normal; } PoolVector3Array new_normals = array_copy[VisualServer::ARRAY_NORMAL].duplicate(true); - + ERR_CONTINUE(normals.size() != new_normals.size()); for (int l = 0; l < normals.size(); l++) { PoolVector3Array::Write w = new_normals.write(); w[l] = normals[l]; @@ -1929,7 +1276,7 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, tangents.resize(num_vertices); PoolColorArray::Write w = tangents.write(); for (size_t l = 0; l < num_vertices; l++) { - _calc_tangent_from_mesh(ai_mesh, j, l, l, w); + AssimpUtils::calc_tangent_from_mesh(ai_mesh, j, l, l, w); } PoolRealArray new_tangents = array_copy[VisualServer::ARRAY_TANGENT].duplicate(true); ERR_CONTINUE(new_tangents.size() != tangents.size() * 4); @@ -1939,243 +1286,227 @@ void EditorSceneImporterAssimp::_add_mesh_to_mesh_instance(const aiNode *p_node, new_tangents.write()[l + 2] = tangents[l].b; new_tangents.write()[l + 3] = tangents[l].a; } - array_copy[VisualServer::ARRAY_TANGENT] = new_tangents; } morphs[j] = array_copy; } - r_name_morph_mesh_names.insert(_ai_raw_string_to_string(p_node->mName), morph_mesh_idx_names); mesh->add_surface_from_arrays(primitive, array_mesh, morphs); mesh->surface_set_material(i, mat); - mesh->surface_set_name(i, _ai_string_to_string(ai_mesh->mName)); - r_mesh_count++; - print_line(String("Open Asset Import: Created mesh (including instances) ") + _ai_string_to_string(ai_mesh->mName) + " " + itos(r_mesh_count) + " of " + itos(p_scene->mNumMeshes)); + mesh->surface_set_name(i, AssimpUtils::get_assimp_string(ai_mesh->mName)); } - p_mesh_instance->set_mesh(mesh); + + return mesh; } -Ref<Texture> EditorSceneImporterAssimp::_load_texture(const aiScene *p_scene, String p_path) { - Vector<String> split_path = p_path.get_basename().split("*"); - if (split_path.size() == 2) { - size_t texture_idx = split_path[1].to_int(); - ERR_FAIL_COND_V(texture_idx >= p_scene->mNumTextures, Ref<Texture>()); - aiTexture *tex = p_scene->mTextures[texture_idx]; - String filename = _ai_raw_string_to_string(tex->mFilename); - filename = filename.get_file(); - print_verbose("Open Asset Import: Loading embedded texture " + filename); - if (tex->mHeight == 0) { - if (tex->CheckFormat("png")) { - Ref<Image> img = Image::_png_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth); - ERR_FAIL_COND_V(img.is_null(), Ref<Texture>()); - - Ref<ImageTexture> t; - t.instance(); - t->create_from_image(img); - t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY); - return t; - } else if (tex->CheckFormat("jpg")) { - Ref<Image> img = Image::_jpg_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth); - ERR_FAIL_COND_V(img.is_null(), Ref<Texture>()); - Ref<ImageTexture> t; - t.instance(); - t->create_from_image(img); - t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY); - return t; - } else if (tex->CheckFormat("dds")) { - ERR_EXPLAIN("Open Asset Import: Embedded dds not implemented"); - ERR_FAIL_COND_V(true, Ref<Texture>()); - //Ref<Image> img = Image::_dds_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth); - //ERR_FAIL_COND_V(img.is_null(), Ref<Texture>()); - //Ref<ImageTexture> t; - //t.instance(); - //t->create_from_image(img); - //t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY); - //return t; - } - } else { - Ref<Image> img; - img.instance(); - PoolByteArray arr; - uint32_t size = tex->mWidth * tex->mHeight; - arr.resize(size); - memcpy(arr.write().ptr(), tex->pcData, size); - ERR_FAIL_COND_V(arr.size() % 4 != 0, Ref<Texture>()); - //ARGB8888 to RGBA8888 - for (int32_t i = 0; i < arr.size() / 4; i++) { - arr.write().ptr()[(4 * i) + 3] = arr[(4 * i) + 0]; - arr.write().ptr()[(4 * i) + 0] = arr[(4 * i) + 1]; - arr.write().ptr()[(4 * i) + 1] = arr[(4 * i) + 2]; - arr.write().ptr()[(4 * i) + 2] = arr[(4 * i) + 3]; - } - img->create(tex->mWidth, tex->mHeight, true, Image::FORMAT_RGBA8, arr); - ERR_FAIL_COND_V(img.is_null(), Ref<Texture>()); - - Ref<ImageTexture> t; - t.instance(); - t->create_from_image(img); - t->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY); - return t; +/** + * Create a new mesh for the node supplied + */ +MeshInstance * +EditorSceneImporterAssimp::create_mesh(ImportState &state, const aiNode *assimp_node, const String &node_name, Node *active_node, Transform node_transform) { + /* MESH NODE */ + Ref<Mesh> mesh; + Ref<Skin> skin; + // see if we have mesh cache for this. + Vector<int> surface_indices; + + RegenerateBoneStack(state); + + // Configure indices + for (uint32_t i = 0; i < assimp_node->mNumMeshes; i++) { + int mesh_index = assimp_node->mMeshes[i]; + // create list of mesh indexes + surface_indices.push_back(mesh_index); + } + + //surface_indices.sort(); + String mesh_key; + for (int i = 0; i < surface_indices.size(); i++) { + if (i > 0) { + mesh_key += ":"; } - return Ref<Texture>(); + mesh_key += itos(surface_indices[i]); } - Ref<Texture> p_texture = ResourceLoader::load(p_path, "Texture"); - return p_texture; -} -void EditorSceneImporterAssimp::_calc_tangent_from_mesh(const aiMesh *ai_mesh, int i, int tri_index, int index, PoolColorArray::Write &w) { - const aiVector3D normals = ai_mesh->mAnimMeshes[i]->mNormals[tri_index]; - const Vector3 godot_normal = Vector3(normals.x, normals.y, normals.z); - const aiVector3D tangent = ai_mesh->mAnimMeshes[i]->mTangents[tri_index]; - const Vector3 godot_tangent = Vector3(tangent.x, tangent.y, tangent.z); - const aiVector3D bitangent = ai_mesh->mAnimMeshes[i]->mBitangents[tri_index]; - const Vector3 godot_bitangent = Vector3(bitangent.x, bitangent.y, bitangent.z); - float d = godot_normal.cross(godot_tangent).dot(godot_bitangent) > 0.0f ? 1.0f : -1.0f; - Color plane_tangent = Color(tangent.x, tangent.y, tangent.z, d); - w[index] = plane_tangent; -} + Skeleton *skeleton = NULL; + aiNode *armature = NULL; -void EditorSceneImporterAssimp::_set_texture_mapping_mode(aiTextureMapMode *map_mode, Ref<Texture> texture) { - ERR_FAIL_COND(map_mode == NULL); - aiTextureMapMode tex_mode = aiTextureMapMode::aiTextureMapMode_Wrap; - //for (size_t i = 0; i < 3; i++) { - tex_mode = map_mode[0]; - //} - int32_t flags = Texture::FLAGS_DEFAULT; - if (tex_mode == aiTextureMapMode_Wrap) { - //Default - } else if (tex_mode == aiTextureMapMode_Clamp) { - flags = flags & ~Texture::FLAG_REPEAT; - } else if (tex_mode == aiTextureMapMode_Mirror) { - flags = flags | Texture::FLAG_MIRRORED_REPEAT; + if (!state.mesh_cache.has(mesh_key)) { + mesh = _generate_mesh_from_surface_indices(state, surface_indices, assimp_node, skin, skeleton); + state.mesh_cache[mesh_key] = mesh; } - texture->set_flags(flags); -} -void EditorSceneImporterAssimp::_find_texture_path(const String &r_p_path, String &r_path, bool &r_found) { + MeshInstance *mesh_node = memnew(MeshInstance); + mesh = state.mesh_cache[mesh_key]; + mesh_node->set_mesh(mesh); - _Directory dir; + // if we have a valid skeleton set it up + if (skin.is_valid()) { + for (uint32_t i = 0; i < assimp_node->mNumMeshes; i++) { + unsigned int mesh_index = assimp_node->mMeshes[i]; + const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_index]; - List<String> exts; - ImageLoader::get_recognized_extensions(&exts); + // please remember bone id relative to the skin is NOT the mesh relative index. + // it is the index relative to the skeleton that is why + // we have state.bone_id_map, it allows for duplicate bone id's too :) + // hope this makes sense - Vector<String> split_path = r_path.get_basename().split("*"); - if (split_path.size() == 2) { - r_found = true; - return; - } + int bind_count = 0; + for (unsigned int boneId = 0; boneId < ai_mesh->mNumBones; ++boneId) { + aiBone *iterBone = ai_mesh->mBones[boneId]; - if (dir.file_exists(r_p_path.get_base_dir() + r_path.get_file())) { - r_path = r_p_path.get_base_dir() + r_path.get_file(); - r_found = true; - return; - } + // used to reparent mesh to the correct armature later on if assigned. + if (!armature) { + print_verbose("Configured mesh armature, will reparent later to armature"); + armature = iterBone->mArmature; + } - for (int32_t i = 0; i < exts.size(); i++) { - if (r_found) { - return; - } - if (r_found == false) { - _find_texture_path(r_p_path, dir, r_path, r_found, "." + exts[i]); - } - } -} + if (skeleton) { + int id = skeleton->find_bone(AssimpUtils::get_assimp_string(iterBone->mName)); + if (id != -1) { + print_verbose("Set bind bone: mesh: " + itos(mesh_index) + " bone index: " + itos(id)); + Transform t = AssimpUtils::assimp_matrix_transform(iterBone->mOffsetMatrix); -void EditorSceneImporterAssimp::_find_texture_path(const String &p_path, _Directory &dir, String &path, bool &found, String extension) { - String name = path.get_basename() + extension; - if (dir.file_exists(name)) { - found = true; - path = name; - return; - } - String name_ignore_sub_directory = p_path.get_base_dir() + "/" + path.get_file().get_basename() + extension; - if (dir.file_exists(name_ignore_sub_directory)) { - found = true; - path = name_ignore_sub_directory; - return; - } + skin->add_bind(bind_count, t); + skin->set_bind_bone(bind_count, id); + bind_count++; + } + } + } + } - String name_find_texture_sub_directory = p_path.get_base_dir() + "/textures/" + path.get_file().get_basename() + extension; - if (dir.file_exists(name_find_texture_sub_directory)) { - found = true; - path = name_find_texture_sub_directory; - return; - } - String name_find_texture_upper_sub_directory = p_path.get_base_dir() + "/Textures/" + path.get_file().get_basename() + extension; - if (dir.file_exists(name_find_texture_upper_sub_directory)) { - found = true; - path = name_find_texture_upper_sub_directory; - return; - } - String name_find_texture_outside_sub_directory = p_path.get_base_dir() + "/../textures/" + path.get_file().get_basename() + extension; - if (dir.file_exists(name_find_texture_outside_sub_directory)) { - found = true; - path = name_find_texture_outside_sub_directory; - return; + print_verbose("Finished configuring bind pose for skin mesh"); } - String name_find_upper_texture_outside_sub_directory = p_path.get_base_dir() + "/../Textures/" + path.get_file().get_basename() + extension; - if (dir.file_exists(name_find_upper_texture_outside_sub_directory)) { - found = true; - path = name_find_upper_texture_outside_sub_directory; - return; + // this code parents all meshes with bones to the armature they are for + // GLTF2 specification relies on this and we are enforcing it for FBX. + if (armature && state.flat_node_map[armature]) { + Node *armature_parent = state.flat_node_map[armature]; + print_verbose("Parented mesh " + node_name + " to armature " + armature_parent->get_name()); + // static mesh handling + armature_parent->add_child(mesh_node); + // transform must be identity + mesh_node->set_global_transform(Transform()); + mesh_node->set_name(node_name); + mesh_node->set_owner(state.root); + } else { + // static mesh handling + active_node->add_child(mesh_node); + mesh_node->set_global_transform(node_transform); + mesh_node->set_name(node_name); + mesh_node->set_owner(state.root); } -} -String EditorSceneImporterAssimp::_ai_string_to_string(const aiString p_string) const { - Vector<char> raw_name; - raw_name.resize(p_string.length); - memcpy(raw_name.ptrw(), p_string.C_Str(), p_string.length); - String name; - name.parse_utf8(raw_name.ptrw(), raw_name.size()); - if (name.find(":") != -1) { - String replaced_name = name.split(":")[1]; - print_verbose("Replacing " + name + " containing : with " + replaced_name); - name = replaced_name; - } - if (name.find(".") != -1) { - String replaced_name = name.replace(".", ""); - print_verbose("Replacing " + name + " containing . with " + replaced_name); - name = replaced_name; + if (skeleton) { + print_verbose("Attempted to set skeleton path!"); + mesh_node->set_skeleton_path(mesh_node->get_path_to(skeleton)); + mesh_node->set_skin(skin); } - return name; -} -String EditorSceneImporterAssimp::_ai_anim_string_to_string(const aiString p_string) const { - Vector<char> raw_name; - raw_name.resize(p_string.length); - memcpy(raw_name.ptrw(), p_string.C_Str(), p_string.length); - String name; - name.parse_utf8(raw_name.ptrw(), raw_name.size()); - if (name.find(":") != -1) { - String replaced_name = name.split(":")[1]; - print_verbose("Replacing " + name + " containing : with " + replaced_name); - name = replaced_name; - } - return name; + return mesh_node; } -String EditorSceneImporterAssimp::_ai_raw_string_to_string(const aiString p_string) const { - Vector<char> raw_name; - raw_name.resize(p_string.length); - memcpy(raw_name.ptrw(), p_string.C_Str(), p_string.length); - String name; - name.parse_utf8(raw_name.ptrw(), raw_name.size()); - return name; +/** + * Create a light for the scene + * Automatically caches lights for lookup later + */ +Spatial *EditorSceneImporterAssimp::create_light( + ImportState &state, + const String &node_name, + Transform &look_at_transform) { + Light *light = NULL; + aiLight *assimp_light = state.assimp_scene->mLights[state.light_cache[node_name]]; + ERR_FAIL_COND_V(!assimp_light, NULL); + + if (assimp_light->mType == aiLightSource_DIRECTIONAL) { + light = memnew(DirectionalLight); + } else if (assimp_light->mType == aiLightSource_POINT) { + light = memnew(OmniLight); + } else if (assimp_light->mType == aiLightSource_SPOT) { + light = memnew(SpotLight); + } + ERR_FAIL_COND_V(light == NULL, NULL); + + if (assimp_light->mType != aiLightSource_POINT) { + Vector3 pos = Vector3( + assimp_light->mPosition.x, + assimp_light->mPosition.y, + assimp_light->mPosition.z); + Vector3 look_at = Vector3( + assimp_light->mDirection.y, + assimp_light->mDirection.x, + assimp_light->mDirection.z) + .normalized(); + Vector3 up = Vector3( + assimp_light->mUp.x, + assimp_light->mUp.y, + assimp_light->mUp.z); + + look_at_transform.set_look_at(pos, look_at, up); + } + // properties for light variables should be put here. + // not really hugely important yet but we will need them in the future + + light->set_color( + Color(assimp_light->mColorDiffuse.r, assimp_light->mColorDiffuse.g, assimp_light->mColorDiffuse.b)); + + return light; } -Ref<Animation> EditorSceneImporterAssimp::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) { - return Ref<Animation>(); +/** + * Create camera for the scene + */ +Spatial *EditorSceneImporterAssimp::create_camera( + ImportState &state, + const String &node_name, + Transform &look_at_transform) { + aiCamera *camera = state.assimp_scene->mCameras[state.camera_cache[node_name]]; + ERR_FAIL_COND_V(!camera, NULL); + + Camera *camera_node = memnew(Camera); + ERR_FAIL_COND_V(!camera_node, NULL); + float near = camera->mClipPlaneNear; + if (Math::is_equal_approx(near, 0.0f)) { + near = 0.1f; + } + camera_node->set_perspective(Math::rad2deg(camera->mHorizontalFOV) * 2.0f, near, camera->mClipPlaneFar); + Vector3 pos = Vector3(camera->mPosition.x, camera->mPosition.y, camera->mPosition.z); + Vector3 look_at = Vector3(camera->mLookAt.y, camera->mLookAt.x, camera->mLookAt.z).normalized(); + Vector3 up = Vector3(camera->mUp.x, camera->mUp.y, camera->mUp.z); + + look_at_transform.set_look_at(pos + look_at_transform.origin, look_at, up); + return camera_node; } -const Transform EditorSceneImporterAssimp::_ai_matrix_transform(const aiMatrix4x4 p_matrix) { - aiMatrix4x4 matrix = p_matrix; - Transform xform; - xform.set(matrix.a1, matrix.b1, matrix.c1, matrix.a2, matrix.b2, matrix.c2, matrix.a3, matrix.b3, matrix.c3, matrix.a4, matrix.b4, matrix.c4); - xform.basis.inverse(); - xform.basis.transpose(); - Vector3 scale = xform.basis.get_scale(); - Quat rot = xform.basis.get_rotation_quat(); - xform.basis.set_quat_scale(rot, scale); - return xform; +/** + * Generate node + * Recursive call to iterate over all nodes + */ +void EditorSceneImporterAssimp::_generate_node( + ImportState &state, + const aiNode *assimp_node) { + + ERR_FAIL_COND(assimp_node == NULL); + state.nodes.push_back(assimp_node); + String parent_name = AssimpUtils::get_assimp_string(assimp_node->mParent->mName); + + // please note + // duplicate bone names exist + // this is why we only check if the bone exists + // so everything else is useless but the name + // please do not copy any other values from get_bone_by_name. + aiBone *parent_bone = get_bone_by_name(state.assimp_scene, assimp_node->mParent->mName); + aiBone *current_bone = get_bone_by_name(state.assimp_scene, assimp_node->mName); + + // is this an armature + // parent null + // and this is the first bone :) + if (parent_bone == NULL && current_bone) { + state.armature_nodes.push_back(assimp_node->mParent); + print_verbose("found valid armature: " + parent_name); + } + + for (size_t i = 0; i < assimp_node->mNumChildren; i++) { + _generate_node(state, assimp_node->mChildren[i]); + } } diff --git a/modules/assimp/editor_scene_importer_assimp.h b/modules/assimp/editor_scene_importer_assimp.h index 8f9ed434ae..a47d7ac46e 100644 --- a/modules/assimp/editor_scene_importer_assimp.h +++ b/modules/assimp/editor_scene_importer_assimp.h @@ -44,64 +44,35 @@ #include "scene/resources/animation.h" #include "scene/resources/surface_tool.h" -#include "assimp/DefaultLogger.hpp" -#include "assimp/LogStream.hpp" -#include "assimp/Logger.hpp" -#include "assimp/matrix4x4.h" -#include "assimp/scene.h" -#include "assimp/types.h" +#include <assimp/matrix4x4.h> +#include <assimp/scene.h> +#include <assimp/types.h> +#include <assimp/DefaultLogger.hpp> +#include <assimp/LogStream.hpp> +#include <assimp/Logger.hpp> +#include <map> + +#include "import_state.h" +#include "import_utils.h" + +using namespace AssimpImporter; class AssimpStream : public Assimp::LogStream { public: // Constructor - AssimpStream(); + AssimpStream() {} // Destructor - ~AssimpStream(); + ~AssimpStream() {} // Write something using your own functionality - void write(const char *message); + void write(const char *message) { + print_verbose(String("Open Asset Import: ") + String(message).strip_edges()); + } }; -#define AI_MATKEY_FBX_MAYA_BASE_COLOR_FACTOR "$raw.Maya|baseColor", 0, 0 -#define AI_MATKEY_FBX_MAYA_METALNESS_FACTOR "$raw.Maya|metalness", 0, 0 -#define AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_FACTOR "$raw.Maya|diffuseRoughness", 0, 0 - -#define AI_MATKEY_FBX_MAYA_METALNESS_TEXTURE "$raw.Maya|metalness|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_METALNESS_UV_XFORM "$raw.Maya|metalness|uvtrafo", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_TEXTURE "$raw.Maya|diffuseRoughness|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_UV_XFORM "$raw.Maya|diffuseRoughness|uvtrafo", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_BASE_COLOR_TEXTURE "$raw.Maya|baseColor|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_BASE_COLOR_UV_XFORM "$raw.Maya|baseColor|uvtrafo", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_NORMAL_TEXTURE "$raw.Maya|normalCamera|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_NORMAL_UV_XFORM "$raw.Maya|normalCamera|uvtrafo", aiTextureType_UNKNOWN, 0 - -#define AI_MATKEY_FBX_NORMAL_TEXTURE "$raw.Maya|normalCamera|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_NORMAL_UV_XFORM "$raw.Maya|normalCamera|uvtrafo", aiTextureType_UNKNOWN, 0 - -#define AI_MATKEY_FBX_MAYA_STINGRAY_DISPLACEMENT_SCALING_FACTOR "$raw.Maya|displacementscaling", 0, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_BASE_COLOR_FACTOR "$raw.Maya|base_color", 0, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_FACTOR "$raw.Maya|emissive", 0, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_FACTOR "$raw.Maya|metallic", 0, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_FACTOR "$raw.Maya|roughness", 0, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_INTENSITY_FACTOR "$raw.Maya|emissive_intensity", 0, 0 - -#define AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_TEXTURE "$raw.Maya|TEX_normal_map|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_UV_XFORM "$raw.Maya|TEX_normal_map|uvtrafo", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_TEXTURE "$raw.Maya|TEX_color_map|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_UV_XFORM "$raw.Maya|TEX_color_map|uvtrafo", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_TEXTURE "$raw.Maya|TEX_metallic_map|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_UV_XFORM "$raw.Maya|TEX_metallic_map|uvtrafo", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_TEXTURE "$raw.Maya|TEX_roughness_map|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_UV_XFORM "$raw.Maya|TEX_roughness_map|uvtrafo", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_TEXTURE "$raw.Maya|TEX_emissive_map|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_UV_XFORM "$raw.Maya|TEX_emissive_map|uvtrafo", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_AO_TEXTURE "$raw.Maya|TEX_ao_map|file", aiTextureType_UNKNOWN, 0 -#define AI_MATKEY_FBX_MAYA_STINGRAY_AO_UV_XFORM "$raw.Maya|TEX_ao_map|uvtrafo", aiTextureType_UNKNOWN, 0 - class EditorSceneImporterAssimp : public EditorSceneImporter { private: GDCLASS(EditorSceneImporterAssimp, EditorSceneImporter); - const String ASSIMP_FBX_KEY = "_$AssimpFbx$"; struct AssetImportAnimation { enum Interpolation { @@ -112,71 +83,39 @@ private: }; }; - struct AssetImportFbx { - enum ETimeMode { - TIME_MODE_DEFAULT = 0, - TIME_MODE_120 = 1, - TIME_MODE_100 = 2, - TIME_MODE_60 = 3, - TIME_MODE_50 = 4, - TIME_MODE_48 = 5, - TIME_MODE_30 = 6, - TIME_MODE_30_DROP = 7, - TIME_MODE_NTSC_DROP_FRAME = 8, - TIME_MODE_NTSC_FULL_FRAME = 9, - TIME_MODE_PAL = 10, - TIME_MODE_CINEMA = 11, - TIME_MODE_1000 = 12, - TIME_MODE_CINEMA_ND = 13, - TIME_MODE_CUSTOM = 14, - TIME_MODE_TIME_MODE_COUNT = 15 - }; - enum UpAxis { - UP_VECTOR_AXIS_X = 1, - UP_VECTOR_AXIS_Y = 2, - UP_VECTOR_AXIS_Z = 3 - }; - enum FrontAxis { - FRONT_PARITY_EVEN = 1, - FRONT_PARITY_ODD = 2, - }; - - enum CoordAxis { - COORD_RIGHT = 0, - COORD_LEFT = 1 - }; + struct BoneInfo { + uint32_t bone; + float weight; }; - Spatial *_generate_scene(const String &p_path, const aiScene *scene, const uint32_t p_flags, int p_bake_fps, const int32_t p_max_bone_weights); - void _fill_kept_node(Set<Node *> &keep_nodes); - String _find_skeleton_bone_root(Map<Skeleton *, MeshInstance *> &skeletons, Map<MeshInstance *, String> &meshes, Spatial *root); - void _set_bone_parent(Skeleton *s, Node *p_owner, aiNode *p_node); - Transform _get_global_ai_node_transform(const aiScene *p_scene, const aiNode *p_current_node); - void _generate_node_bone(const aiScene *p_scene, const aiNode *p_node, Map<String, bool> &p_mesh_bones, Skeleton *p_skeleton, const String p_path, const int32_t p_max_bone_weights); - void _generate_node_bone_parents(const aiScene *p_scene, const aiNode *p_node, Map<String, bool> &p_mesh_bones, Skeleton *p_skeleton, const MeshInstance *p_mi); - void _calculate_skeleton_root(Skeleton *s, const aiScene *p_scene, aiNode *&p_ai_skeleton_root, Map<String, bool> &mesh_bones, const aiNode *p_node); - void _fill_skeleton(const aiScene *p_scene, const aiNode *p_node, Spatial *p_current, Node *p_owner, Skeleton *p_skeleton, const Map<String, bool> p_mesh_bones, const Map<String, Transform> &p_bone_rests, Set<String> p_tracks, const String p_path, Set<String> &r_removed_bones); - void _keep_node(const String &p_path, Node *p_current, Node *p_owner, Set<Node *> &r_keep_nodes); - void _filter_node(const String &p_path, Node *p_current, Node *p_owner, const Set<Node *> p_keep_nodes, Set<String> &r_removed_nodes); - void _generate_node(const String &p_path, const aiScene *p_scene, const aiNode *p_node, Node *p_parent, Node *p_owner, Set<String> &r_bone_name, Set<String> p_light_names, Set<String> p_camera_names, Map<Skeleton *, MeshInstance *> &r_skeletons, const Map<String, Transform> &p_bone_rests, Vector<MeshInstance *> &r_mesh_instances, int32_t &r_mesh_count, Skeleton *p_skeleton, const int32_t p_max_bone_weights, Set<String> &r_removed_bones, Map<String, Map<uint32_t, String> > &r_name_morph_mesh_names); - aiNode *_ai_find_node(aiNode *ai_child_node, const String bone_name); - Transform _format_rot_xform(const String p_path, const aiScene *p_scene); - void _get_track_set(const aiScene *p_scene, Set<String> &tracks); - void _insert_animation_track(const aiScene *p_scene, const String p_path, int p_bake_fps, Ref<Animation> animation, float ticks_per_second, float length, const Skeleton *sk, const aiNodeAnim *track, String node_name, NodePath node_path); - void _add_mesh_to_mesh_instance(const aiNode *p_node, const aiScene *p_scene, Skeleton *s, const String &p_path, MeshInstance *p_mesh_instance, Node *p_owner, Set<String> &r_bone_name, int32_t &r_mesh_count, int32_t p_max_bone_weights, Map<String, Map<uint32_t, String> > &r_name_morph_mesh_names); - Ref<Texture> _load_texture(const aiScene *p_scene, String p_path); - void _calc_tangent_from_mesh(const aiMesh *ai_mesh, int i, int tri_index, int index, PoolColorArray::Write &w); - void _set_texture_mapping_mode(aiTextureMapMode *map_mode, Ref<Texture> texture); - void _find_texture_path(const String &p_path, String &path, bool &r_found); - void _find_texture_path(const String &p_path, _Directory &dir, String &path, bool &found, String extension); - String _ai_string_to_string(const aiString p_string) const; - String _ai_anim_string_to_string(const aiString p_string) const; - String _ai_raw_string_to_string(const aiString p_string) const; - void _import_animation(const String p_path, const Vector<MeshInstance *> p_meshes, const aiScene *p_scene, AnimationPlayer *ap, int32_t p_index, int p_bake_fps, Map<Skeleton *, MeshInstance *> p_skeletons, const Set<String> p_removed_nodes, const Set<String> removed_bones, const Map<String, Map<uint32_t, String> > p_path_morph_mesh_names); - void _insert_pivot_anim_track(const Vector<MeshInstance *> p_meshes, const String p_node_name, Vector<const aiNodeAnim *> F, AnimationPlayer *ap, Skeleton *sk, float &length, float ticks_per_second, Ref<Animation> animation, int p_bake_fps, const String &p_path, const aiScene *p_scene); - float _get_fbx_fps(int32_t time_mode, const aiScene *p_scene); + + Ref<Mesh> _generate_mesh_from_surface_indices(ImportState &state, const Vector<int> &p_surface_indices, + const aiNode *assimp_node, Ref<Skin> &skin, + Skeleton *&skeleton_assigned); + + // simple object creation functions + Spatial *create_light(ImportState &state, + const String &node_name, + Transform &look_at_transform); + Spatial *create_camera( + ImportState &state, + const String &node_name, + Transform &look_at_transform); + // non recursive - linear so must not use recursive arguments + MeshInstance *create_mesh(ImportState &state, const aiNode *assimp_node, const String &node_name, Node *active_node, Transform node_transform); + // recursive node generator + void _generate_node(ImportState &state, const aiNode *assimp_node); + void _insert_animation_track(ImportState &scene, const aiAnimation *assimp_anim, int track_id, + int anim_fps, Ref<Animation> animation, float ticks_per_second, + Skeleton *skeleton, const NodePath &node_path, + const String &node_name, aiBone *track_bone); + + void _import_animation(ImportState &state, int p_animation_index, int p_bake_fps); + Node *get_node_by_name(ImportState &state, String name); + aiBone *get_bone_from_stack(ImportState &state, aiString name); + Spatial *_generate_scene(const String &p_path, aiScene *scene, const uint32_t p_flags, int p_bake_fps, const int32_t p_max_bone_weights); + template <class T> T _interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, AssetImportAnimation::Interpolation p_interp); - const Transform _ai_matrix_transform(const aiMatrix4x4 p_matrix); void _register_project_setting_import(const String generic, const String import_setting_string, const Vector<String> &exts, List<String> *r_extensions, const bool p_enabled) const; struct ImportFormat { @@ -200,7 +139,11 @@ public: virtual void get_extensions(List<String> *r_extensions) const; virtual uint32_t get_import_flags() const; virtual Node *import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = NULL); - virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps); + Ref<Image> load_image(ImportState &state, const aiScene *p_scene, String p_path); + + static void RegenerateBoneStack(ImportState &state); + + void RegenerateBoneStack(ImportState &state, aiMesh *mesh); }; #endif #endif diff --git a/modules/assimp/godot_update_assimp.sh b/modules/assimp/godot_update_assimp.sh index dcf1e6d4a2..ff8ff59e97 100644..100755 --- a/modules/assimp/godot_update_assimp.sh +++ b/modules/assimp/godot_update_assimp.sh @@ -254,8 +254,9 @@ rm -rf contrib/irrXML rm -rf contrib/Open3DGC rm -rf contrib/openddlparser rm -rf contrib/poly2tri -rm -rf contrib/rapidjson +#rm -rf contrib/rapidjson rm -rf contrib/unzip rm -rf contrib/zip rm -rf contrib/stb_image rm .travis* + diff --git a/modules/assimp/import_state.h b/modules/assimp/import_state.h new file mode 100644 index 0000000000..9859a88c1c --- /dev/null +++ b/modules/assimp/import_state.h @@ -0,0 +1,130 @@ +/*************************************************************************/ +/* import_state.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 EDITOR_SCENE_IMPORT_STATE_H +#define EDITOR_SCENE_IMPORT_STATE_H + +#include "core/bind/core_bind.h" +#include "core/io/resource_importer.h" +#include "core/vector.h" +#include "editor/import/resource_importer_scene.h" +#include "editor/project_settings_editor.h" +#include "scene/3d/mesh_instance.h" +#include "scene/3d/skeleton.h" +#include "scene/3d/spatial.h" +#include "scene/animation/animation_player.h" +#include "scene/resources/animation.h" +#include "scene/resources/surface_tool.h" + +#include <assimp/matrix4x4.h> +#include <assimp/scene.h> +#include <assimp/types.h> +#include <assimp/DefaultLogger.hpp> +#include <assimp/LogStream.hpp> +#include <assimp/Logger.hpp> + +namespace AssimpImporter { +/** Import state is for global scene import data + * This makes the code simpler and contains useful lookups. + */ +struct ImportState { + + String path; + Spatial *root; + const aiScene *assimp_scene; + uint32_t max_bone_weights; + + Map<String, Ref<Mesh> > mesh_cache; + Map<int, Ref<Material> > material_cache; + Map<String, int> light_cache; + Map<String, int> camera_cache; + + // very useful for when you need to ask assimp for the bone mesh + + Map<const aiNode *, Node *> assimp_node_map; + Map<String, Ref<Image> > path_to_image_cache; + + // Generation 3 - determinisitic iteration + // to lower potential recursion errors + List<const aiNode *> nodes; + Map<const aiNode *, Spatial *> flat_node_map; + AnimationPlayer *animation_player; + + // Generation 3 - deterministic armatures + // list of armature nodes - flat and simple to parse + // assimp node, node in godot + List<aiNode *> armature_nodes; + Map<const aiNode *, Skeleton *> armature_skeletons; + Map<aiBone *, Skeleton *> skeleton_bone_map; + // Generation 3 - deterministic bone handling + // bones from the stack are popped when found + // this means we can detect + // what bones are for other armatures + List<aiBone *> bone_stack; +}; + +struct AssimpImageData { + Ref<Image> raw_image; + Ref<ImageTexture> texture; + aiTextureMapMode map_mode[2]; +}; + +/** Recursive state is used to push state into functions instead of specifying them + * This makes the code easier to handle too and add extra arguments without breaking things + */ +struct RecursiveState { + RecursiveState() {} // do not construct :) + RecursiveState( + Transform &_node_transform, + Skeleton *_skeleton, + Spatial *_new_node, + String &_node_name, + aiNode *_assimp_node, + Node *_parent_node, + aiBone *_bone) : + node_transform(_node_transform), + skeleton(_skeleton), + new_node(_new_node), + node_name(_node_name), + assimp_node(_assimp_node), + parent_node(_parent_node), + bone(_bone) {} + + Transform node_transform; + Skeleton *skeleton = NULL; + Spatial *new_node = NULL; + String node_name; + aiNode *assimp_node = NULL; + Node *parent_node = NULL; + aiBone *bone = NULL; +}; +} // namespace AssimpImporter + +#endif // EDITOR_SCENE_IMPORT_STATE_H diff --git a/modules/assimp/import_utils.h b/modules/assimp/import_utils.h new file mode 100644 index 0000000000..bf7552e7db --- /dev/null +++ b/modules/assimp/import_utils.h @@ -0,0 +1,445 @@ +/*************************************************************************/ +/* import_utils.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 IMPORT_UTILS_IMPORTER_ASSIMP_H +#define IMPORT_UTILS_IMPORTER_ASSIMP_H + +#include "core/io/image_loader.h" +#include "import_state.h" + +#include <assimp/SceneCombiner.h> +#include <assimp/cexport.h> +#include <assimp/cimport.h> +#include <assimp/matrix4x4.h> +#include <assimp/pbrmaterial.h> +#include <assimp/postprocess.h> +#include <assimp/scene.h> +#include <assimp/DefaultLogger.hpp> +#include <assimp/Importer.hpp> +#include <assimp/LogStream.hpp> +#include <assimp/Logger.hpp> +#include <string> + +using namespace AssimpImporter; + +#define AI_PROPERTIES aiTextureType_UNKNOWN, 0 +#define AI_NULL 0, 0 +#define AI_MATKEY_FBX_MAYA_BASE_COLOR_FACTOR "$raw.Maya|baseColor" +#define AI_MATKEY_FBX_MAYA_METALNESS_FACTOR "$raw.Maya|metalness" +#define AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_FACTOR "$raw.Maya|diffuseRoughness" + +#define AI_MATKEY_FBX_MAYA_EMISSION_TEXTURE "$raw.Maya|emissionColor|file" +#define AI_MATKEY_FBX_MAYA_EMISSIVE_FACTOR "$raw.Maya|emission" +#define AI_MATKEY_FBX_MAYA_METALNESS_TEXTURE "$raw.Maya|metalness|file" +#define AI_MATKEY_FBX_MAYA_METALNESS_UV_XFORM "$raw.Maya|metalness|uvtrafo" +#define AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_TEXTURE "$raw.Maya|diffuseRoughness|file" +#define AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_UV_XFORM "$raw.Maya|diffuseRoughness|uvtrafo" +#define AI_MATKEY_FBX_MAYA_BASE_COLOR_TEXTURE "$raw.Maya|baseColor|file" +#define AI_MATKEY_FBX_MAYA_BASE_COLOR_UV_XFORM "$raw.Maya|baseColor|uvtrafo" +#define AI_MATKEY_FBX_MAYA_NORMAL_TEXTURE "$raw.Maya|normalCamera|file" +#define AI_MATKEY_FBX_MAYA_NORMAL_UV_XFORM "$raw.Maya|normalCamera|uvtrafo" + +#define AI_MATKEY_FBX_NORMAL_TEXTURE "$raw.Maya|normalCamera|file" +#define AI_MATKEY_FBX_NORMAL_UV_XFORM "$raw.Maya|normalCamera|uvtrafo" + +#define AI_MATKEY_FBX_MAYA_STINGRAY_DISPLACEMENT_SCALING_FACTOR "$raw.Maya|displacementscaling" +#define AI_MATKEY_FBX_MAYA_STINGRAY_BASE_COLOR_FACTOR "$raw.Maya|base_color" +#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_FACTOR "$raw.Maya|emissive" +#define AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_FACTOR "$raw.Maya|metallic" +#define AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_FACTOR "$raw.Maya|roughness" +#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_INTENSITY_FACTOR "$raw.Maya|emissive_intensity" + +#define AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_TEXTURE "$raw.Maya|TEX_normal_map|file" +#define AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_UV_XFORM "$raw.Maya|TEX_normal_map|uvtrafo" +#define AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_TEXTURE "$raw.Maya|TEX_color_map|file" +#define AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_UV_XFORM "$raw.Maya|TEX_color_map|uvtrafo" +#define AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_TEXTURE "$raw.Maya|TEX_metallic_map|file" +#define AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_UV_XFORM "$raw.Maya|TEX_metallic_map|uvtrafo" +#define AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_TEXTURE "$raw.Maya|TEX_roughness_map|file" +#define AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_UV_XFORM "$raw.Maya|TEX_roughness_map|uvtrafo" +#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_TEXTURE "$raw.Maya|TEX_emissive_map|file" +#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_UV_XFORM "$raw.Maya|TEX_emissive_map|uvtrafo" +#define AI_MATKEY_FBX_MAYA_STINGRAY_AO_TEXTURE "$raw.Maya|TEX_ao_map|file" +#define AI_MATKEY_FBX_MAYA_STINGRAY_AO_UV_XFORM "$raw.Maya|TEX_ao_map|uvtrafo" + +/** + * Assimp Utils + * Conversion tools / glue code to convert from assimp to godot +*/ +class AssimpUtils { +public: + /** + * calculate tangents for mesh data from assimp data + */ + static void calc_tangent_from_mesh(const aiMesh *ai_mesh, int i, int tri_index, int index, PoolColorArray::Write &w) { + const aiVector3D normals = ai_mesh->mAnimMeshes[i]->mNormals[tri_index]; + const Vector3 godot_normal = Vector3(normals.x, normals.y, normals.z); + const aiVector3D tangent = ai_mesh->mAnimMeshes[i]->mTangents[tri_index]; + const Vector3 godot_tangent = Vector3(tangent.x, tangent.y, tangent.z); + const aiVector3D bitangent = ai_mesh->mAnimMeshes[i]->mBitangents[tri_index]; + const Vector3 godot_bitangent = Vector3(bitangent.x, bitangent.y, bitangent.z); + float d = godot_normal.cross(godot_tangent).dot(godot_bitangent) > 0.0f ? 1.0f : -1.0f; + Color plane_tangent = Color(tangent.x, tangent.y, tangent.z, d); + w[index] = plane_tangent; + } + + struct AssetImportFbx { + enum ETimeMode { + TIME_MODE_DEFAULT = 0, + TIME_MODE_120 = 1, + TIME_MODE_100 = 2, + TIME_MODE_60 = 3, + TIME_MODE_50 = 4, + TIME_MODE_48 = 5, + TIME_MODE_30 = 6, + TIME_MODE_30_DROP = 7, + TIME_MODE_NTSC_DROP_FRAME = 8, + TIME_MODE_NTSC_FULL_FRAME = 9, + TIME_MODE_PAL = 10, + TIME_MODE_CINEMA = 11, + TIME_MODE_1000 = 12, + TIME_MODE_CINEMA_ND = 13, + TIME_MODE_CUSTOM = 14, + TIME_MODE_TIME_MODE_COUNT = 15 + }; + enum UpAxis { + UP_VECTOR_AXIS_X = 1, + UP_VECTOR_AXIS_Y = 2, + UP_VECTOR_AXIS_Z = 3 + }; + enum FrontAxis { + FRONT_PARITY_EVEN = 1, + FRONT_PARITY_ODD = 2, + }; + + enum CoordAxis { + COORD_RIGHT = 0, + COORD_LEFT = 1 + }; + }; + + /** Get assimp string + * automatically filters the string data + */ + static String get_assimp_string(const aiString &p_string) { + //convert an assimp String to a Godot String + String name; + name.parse_utf8(p_string.C_Str() /*,p_string.length*/); + if (name.find(":") != -1) { + String replaced_name = name.split(":")[1]; + print_verbose("Replacing " + name + " containing : with " + replaced_name); + name = replaced_name; + } + + return name; + } + + static String get_anim_string_from_assimp(const aiString &p_string) { + + String name; + name.parse_utf8(p_string.C_Str() /*,p_string.length*/); + if (name.find(":") != -1) { + String replaced_name = name.split(":")[1]; + print_verbose("Replacing " + name + " containing : with " + replaced_name); + name = replaced_name; + } + return name; + } + + /** + * No filter logic get_raw_string_from_assimp + * This just convers the aiString to a parsed utf8 string + * Without removing special chars etc + */ + static String get_raw_string_from_assimp(const aiString &p_string) { + String name; + name.parse_utf8(p_string.C_Str() /*,p_string.length*/); + return name; + } + + static Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) { + return Ref<Animation>(); + } + + /** + * Converts aiMatrix4x4 to godot Transform + */ + static const Transform assimp_matrix_transform(const aiMatrix4x4 p_matrix) { + aiMatrix4x4 matrix = p_matrix; + Transform xform; + xform.set(matrix.a1, matrix.a2, matrix.a3, matrix.b1, matrix.b2, matrix.b3, matrix.c1, matrix.c2, matrix.c3, matrix.a4, matrix.b4, matrix.c4); + return xform; + } + + /** Get fbx fps for time mode meta data + */ + static float get_fbx_fps(int32_t time_mode, const aiScene *p_scene) { + switch (time_mode) { + case AssetImportFbx::TIME_MODE_DEFAULT: return 24; //hack + case AssetImportFbx::TIME_MODE_120: return 120; + case AssetImportFbx::TIME_MODE_100: return 100; + case AssetImportFbx::TIME_MODE_60: return 60; + case AssetImportFbx::TIME_MODE_50: return 50; + case AssetImportFbx::TIME_MODE_48: return 48; + case AssetImportFbx::TIME_MODE_30: return 30; + case AssetImportFbx::TIME_MODE_30_DROP: return 30; + case AssetImportFbx::TIME_MODE_NTSC_DROP_FRAME: return 29.9700262f; + case AssetImportFbx::TIME_MODE_NTSC_FULL_FRAME: return 29.9700262f; + case AssetImportFbx::TIME_MODE_PAL: return 25; + case AssetImportFbx::TIME_MODE_CINEMA: return 24; + case AssetImportFbx::TIME_MODE_1000: return 1000; + case AssetImportFbx::TIME_MODE_CINEMA_ND: return 23.976f; + case AssetImportFbx::TIME_MODE_CUSTOM: + int32_t frame_rate = -1; + p_scene->mMetaData->Get("FrameRate", frame_rate); + return frame_rate; + } + return 0; + } + + /** + * Get global transform for the current node - so we can use world space rather than + * local space coordinates + * useful if you need global - although recommend using local wherever possible over global + * as you could break fbx scaling :) + */ + static Transform _get_global_assimp_node_transform(const aiNode *p_current_node) { + aiNode const *current_node = p_current_node; + Transform xform; + while (current_node != NULL) { + xform = assimp_matrix_transform(current_node->mTransformation) * xform; + current_node = current_node->mParent; + } + return xform; + } + + /** + * Find hardcoded textures from assimp which could be in many different directories + */ + static void find_texture_path(const String &p_path, _Directory &dir, String &path, bool &found, String extension) { + Vector<String> paths; + paths.push_back(path.get_basename() + extension); + paths.push_back(path + extension); + paths.push_back(path); + paths.push_back(p_path.get_base_dir().plus_file(path.get_file().get_basename() + extension)); + paths.push_back(p_path.get_base_dir().plus_file(path.get_file() + extension)); + paths.push_back(p_path.get_base_dir().plus_file(path.get_file())); + paths.push_back(p_path.get_base_dir().plus_file("textures/" + path.get_file().get_basename() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("textures/" + path.get_file() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("textures/" + path.get_file())); + paths.push_back(p_path.get_base_dir().plus_file("Textures/" + path.get_file().get_basename() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("Textures/" + path.get_file() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("Textures/" + path.get_file())); + paths.push_back(p_path.get_base_dir().plus_file("../Textures/" + path.get_file() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("../Textures/" + path.get_file().get_basename() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("../Textures/" + path.get_file())); + paths.push_back(p_path.get_base_dir().plus_file("../textures/" + path.get_file().get_basename() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("../textures/" + path.get_file() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("../textures/" + path.get_file())); + paths.push_back(p_path.get_base_dir().plus_file("texture/" + path.get_file().get_basename() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("texture/" + path.get_file() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("texture/" + path.get_file())); + paths.push_back(p_path.get_base_dir().plus_file("Texture/" + path.get_file().get_basename() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("Texture/" + path.get_file() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("Texture/" + path.get_file())); + paths.push_back(p_path.get_base_dir().plus_file("../Texture/" + path.get_file() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("../Texture/" + path.get_file().get_basename() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("../Texture/" + path.get_file())); + paths.push_back(p_path.get_base_dir().plus_file("../texture/" + path.get_file().get_basename() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("../texture/" + path.get_file() + extension)); + paths.push_back(p_path.get_base_dir().plus_file("../texture/" + path.get_file())); + for (int i = 0; i < paths.size(); i++) { + if (dir.file_exists(paths[i])) { + found = true; + path = paths[i]; + return; + } + } + } + + /** find the texture path for the supplied fbx path inside godot + * very simple lookup for subfolders etc for a texture which may or may not be in a directory + */ + static void find_texture_path(const String &r_p_path, String &r_path, bool &r_found) { + _Directory dir; + + List<String> exts; + ImageLoader::get_recognized_extensions(&exts); + + Vector<String> split_path = r_path.get_basename().split("*"); + if (split_path.size() == 2) { + r_found = true; + return; + } + + if (dir.file_exists(r_p_path.get_base_dir() + r_path.get_file())) { + r_path = r_p_path.get_base_dir() + r_path.get_file(); + r_found = true; + return; + } + + for (int32_t i = 0; i < exts.size(); i++) { + if (r_found) { + return; + } + find_texture_path(r_p_path, dir, r_path, r_found, "." + exts[i]); + } + } + + /** + * set_texture_mapping_mode + * Helper to check the mapping mode of the texture (repeat, clamp and mirror) + */ + static void set_texture_mapping_mode(aiTextureMapMode *map_mode, Ref<ImageTexture> texture) { + ERR_FAIL_COND(texture.is_null()); + ERR_FAIL_COND(map_mode == NULL); + aiTextureMapMode tex_mode = map_mode[0]; + + int32_t flags = Texture::FLAGS_DEFAULT; + if (tex_mode == aiTextureMapMode_Wrap) { + //Default + } else if (tex_mode == aiTextureMapMode_Clamp) { + flags = flags & ~Texture::FLAG_REPEAT; + } else if (tex_mode == aiTextureMapMode_Mirror) { + flags = flags | Texture::FLAG_MIRRORED_REPEAT; + } + texture->set_flags(flags); + } + + /** + * Load or load from cache image :) + */ + static Ref<Image> load_image(ImportState &state, const aiScene *p_scene, String p_path) { + + Map<String, Ref<Image> >::Element *match = state.path_to_image_cache.find(p_path); + + // if our cache contains this image then don't bother + if (match) { + return match->get(); + } + + Vector<String> split_path = p_path.get_basename().split("*"); + if (split_path.size() == 2) { + size_t texture_idx = split_path[1].to_int(); + ERR_FAIL_COND_V(texture_idx >= p_scene->mNumTextures, Ref<Image>()); + aiTexture *tex = p_scene->mTextures[texture_idx]; + String filename = AssimpUtils::get_raw_string_from_assimp(tex->mFilename); + filename = filename.get_file(); + print_verbose("Open Asset Import: Loading embedded texture " + filename); + if (tex->mHeight == 0) { + if (tex->CheckFormat("png")) { + Ref<Image> img = Image::_png_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth); + ERR_FAIL_COND_V(img.is_null(), Ref<Image>()); + state.path_to_image_cache.insert(p_path, img); + return img; + } else if (tex->CheckFormat("jpg")) { + Ref<Image> img = Image::_jpg_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth); + ERR_FAIL_COND_V(img.is_null(), Ref<Image>()); + state.path_to_image_cache.insert(p_path, img); + return img; + } else if (tex->CheckFormat("dds")) { + ERR_FAIL_COND_V_MSG(true, Ref<Image>(), "Open Asset Import: Embedded dds not implemented"); + } + } else { + Ref<Image> img; + img.instance(); + PoolByteArray arr; + uint32_t size = tex->mWidth * tex->mHeight; + arr.resize(size); + memcpy(arr.write().ptr(), tex->pcData, size); + ERR_FAIL_COND_V(arr.size() % 4 != 0, Ref<Image>()); + //ARGB8888 to RGBA8888 + for (int32_t i = 0; i < arr.size() / 4; i++) { + arr.write().ptr()[(4 * i) + 3] = arr[(4 * i) + 0]; + arr.write().ptr()[(4 * i) + 0] = arr[(4 * i) + 1]; + arr.write().ptr()[(4 * i) + 1] = arr[(4 * i) + 2]; + arr.write().ptr()[(4 * i) + 2] = arr[(4 * i) + 3]; + } + img->create(tex->mWidth, tex->mHeight, true, Image::FORMAT_RGBA8, arr); + ERR_FAIL_COND_V(img.is_null(), Ref<Image>()); + state.path_to_image_cache.insert(p_path, img); + return img; + } + return Ref<Image>(); + } else { + Ref<Texture> texture = ResourceLoader::load(p_path); + ERR_FAIL_COND_V(texture.is_null(), Ref<Image>()); + Ref<Image> image = texture->get_data(); + ERR_FAIL_COND_V(image.is_null(), Ref<Image>()); + state.path_to_image_cache.insert(p_path, image); + return image; + } + + return Ref<Image>(); + } + + /* create texture from assimp data, if found in path */ + static bool CreateAssimpTexture( + AssimpImporter::ImportState &state, + aiString texture_path, + String &filename, + String &path, + AssimpImageData &image_state) { + filename = get_raw_string_from_assimp(texture_path); + path = state.path.get_base_dir().plus_file(filename.replace("\\", "/")); + bool found = false; + find_texture_path(state.path, path, found); + if (found) { + image_state.raw_image = AssimpUtils::load_image(state, state.assimp_scene, path); + if (image_state.raw_image.is_valid()) { + image_state.texture.instance(); + image_state.texture->create_from_image(image_state.raw_image); + image_state.texture->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY); + return true; + } + } + + return false; + } + /** GetAssimpTexture + * Designed to retrieve textures for you + */ + static bool GetAssimpTexture( + AssimpImporter::ImportState &state, + aiMaterial *ai_material, + aiTextureType texture_type, + String &filename, + String &path, + AssimpImageData &image_state) { + aiString ai_filename = aiString(); + if (AI_SUCCESS == ai_material->GetTexture(texture_type, 0, &ai_filename, NULL, NULL, NULL, NULL, image_state.map_mode)) { + return CreateAssimpTexture(state, ai_filename, filename, path, image_state); + } + + return false; + } +}; + +#endif // IMPORT_UTILS_IMPORTER_ASSIMP_H diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp index a8172c7f52..8708430257 100644 --- a/modules/bmp/image_loader_bmp.cpp +++ b/modules/bmp/image_loader_bmp.cpp @@ -33,6 +33,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, const uint8_t *p_buffer, const uint8_t *p_color_buffer, + const uint32_t color_table_size, const bmp_header_s &p_header) { Error err = OK; @@ -46,57 +47,153 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, size_t height = (size_t)p_header.bmp_info_header.bmp_height; size_t bits_per_pixel = (size_t)p_header.bmp_info_header.bmp_bit_count; - if (p_header.bmp_info_header.bmp_compression != 0) { - err = FAILED; + // Check whether we can load it + + if (bits_per_pixel == 1) { + // Requires bit unpacking... + ERR_FAIL_COND_V(width % 8 != 0, ERR_UNAVAILABLE); + ERR_FAIL_COND_V(height % 8 != 0, ERR_UNAVAILABLE); + + } else if (bits_per_pixel == 4) { + // Requires bit unpacking... + ERR_FAIL_COND_V(width % 2 != 0, ERR_UNAVAILABLE); + ERR_FAIL_COND_V(height % 2 != 0, ERR_UNAVAILABLE); + + } else if (bits_per_pixel == 16) { + + ERR_FAIL_V(ERR_UNAVAILABLE); } - if (!(bits_per_pixel == 24 || bits_per_pixel == 32)) { - err = FAILED; + // Image data (might be indexed) + PoolVector<uint8_t> data; + int data_len = 0; + + if (bits_per_pixel <= 8) { // indexed + data_len = width * height; + } else { // color + data_len = width * height * 4; } + ERR_FAIL_COND_V(data_len == 0, ERR_BUG); + err = data.resize(data_len); + + PoolVector<uint8_t>::Write data_w = data.write(); + uint8_t *write_buffer = data_w.ptr(); + + const uint32_t width_bytes = width * bits_per_pixel / 8; + const uint32_t line_width = (width_bytes + 3) & ~3; + + // The actual data traversal is determined by + // the data width in case of 8/4/1 bit images + const uint32_t w = bits_per_pixel >= 24 ? width : width_bytes; + const uint8_t *line = p_buffer + (line_width * (height - 1)); + + for (uint64_t i = 0; i < height; i++) { + const uint8_t *line_ptr = line; + + for (unsigned int j = 0; j < w; j++) { + switch (bits_per_pixel) { + case 1: { + uint8_t color_index = *line_ptr; + + write_buffer[index + 0] = (color_index >> 7) & 1; + write_buffer[index + 1] = (color_index >> 6) & 1; + write_buffer[index + 2] = (color_index >> 5) & 1; + write_buffer[index + 3] = (color_index >> 4) & 1; + write_buffer[index + 4] = (color_index >> 3) & 1; + write_buffer[index + 5] = (color_index >> 2) & 1; + write_buffer[index + 6] = (color_index >> 1) & 1; + write_buffer[index + 7] = (color_index >> 0) & 1; - if (err == OK) { - - uint32_t line_width = ((p_header.bmp_info_header.bmp_width * - p_header.bmp_info_header.bmp_bit_count / 8) + - 3) & - ~3; - - PoolVector<uint8_t> image_data; - err = image_data.resize(width * height * 4); - - PoolVector<uint8_t>::Write image_data_w = image_data.write(); - uint8_t *write_buffer = image_data_w.ptr(); - - const uint8_t *line = p_buffer + (line_width * (height - 1)); - for (unsigned int i = 0; i < height; i++) { - const uint8_t *line_ptr = line; - for (unsigned int j = 0; j < width; j++) { - switch (bits_per_pixel) { - case 24: { - uint32_t color = *((uint32_t *)line_ptr); - - write_buffer[index + 2] = color & 0xff; - write_buffer[index + 1] = (color >> 8) & 0xff; - write_buffer[index + 0] = (color >> 16) & 0xff; - write_buffer[index + 3] = 0xff; - index += 4; - line_ptr += 3; - } break; - case 32: { - uint32_t color = *((uint32_t *)line_ptr); - - write_buffer[index + 2] = color & 0xff; - write_buffer[index + 1] = (color >> 8) & 0xff; - write_buffer[index + 0] = (color >> 16) & 0xff; - write_buffer[index + 3] = color >> 24; - index += 4; - line_ptr += 4; - } break; - } + index += 8; + line_ptr += 1; + } break; + case 4: { + uint8_t color_index = *line_ptr; + + write_buffer[index + 0] = (color_index >> 4) & 0x0f; + write_buffer[index + 1] = color_index & 0x0f; + + index += 2; + line_ptr += 1; + } break; + case 8: { + uint8_t color_index = *line_ptr; + + write_buffer[index] = color_index; + + index += 1; + line_ptr += 1; + } break; + case 24: { + uint32_t color = *((uint32_t *)line_ptr); + + write_buffer[index + 2] = color & 0xff; + write_buffer[index + 1] = (color >> 8) & 0xff; + write_buffer[index + 0] = (color >> 16) & 0xff; + write_buffer[index + 3] = 0xff; + + index += 4; + line_ptr += 3; + } break; + case 32: { + uint32_t color = *((uint32_t *)line_ptr); + + write_buffer[index + 2] = color & 0xff; + write_buffer[index + 1] = (color >> 8) & 0xff; + write_buffer[index + 0] = (color >> 16) & 0xff; + write_buffer[index + 3] = color >> 24; + + index += 4; + line_ptr += 4; + } break; } - line -= line_width; } - p_image->create(width, height, 0, Image::FORMAT_RGBA8, image_data); + line -= line_width; + } + + if (p_color_buffer == NULL || color_table_size == 0) { // regular pixels + + p_image->create(width, height, 0, Image::FORMAT_RGBA8, data); + + } else { // data is in indexed format, extend it + + // Palette data + PoolVector<uint8_t> palette_data; + palette_data.resize(color_table_size * 4); + + PoolVector<uint8_t>::Write palette_data_w = palette_data.write(); + uint8_t *pal = palette_data_w.ptr(); + + const uint8_t *cb = p_color_buffer; + + for (unsigned int i = 0; i < color_table_size; ++i) { + uint32_t color = *((uint32_t *)cb); + + pal[i * 4 + 0] = (color >> 16) & 0xff; + pal[i * 4 + 1] = (color >> 8) & 0xff; + pal[i * 4 + 2] = (color)&0xff; + pal[i * 4 + 3] = 0xff; + + cb += 4; + } + // Extend palette to image + PoolVector<uint8_t> extended_data; + extended_data.resize(data.size() * 4); + + PoolVector<uint8_t>::Write ex_w = extended_data.write(); + uint8_t *dest = ex_w.ptr(); + + const int num_pixels = width * height; + + for (int i = 0; i < num_pixels; i++) { + dest[0] = pal[write_buffer[i] * 4 + 0]; + dest[1] = pal[write_buffer[i] * 4 + 1]; + dest[2] = pal[write_buffer[i] * 4 + 2]; + dest[3] = pal[write_buffer[i] * 4 + 3]; + + dest += 4; + } + p_image->create(width, height, 0, Image::FORMAT_RGBA8, extended_data); } } return err; @@ -108,7 +205,9 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f, bmp_header_s bmp_header; Error err = ERR_INVALID_DATA; - if (f->get_len() > sizeof(bmp_header)) { + // A valid bmp file should always at least have a + // file header and a minimal info header + if (f->get_len() > BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_MIN_SIZE) { // File Header bmp_header.bmp_file_header.bmp_signature = f->get_16(); if (bmp_header.bmp_file_header.bmp_signature == BITMAP_SIGNATURE) { @@ -118,9 +217,14 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f, // Info Header bmp_header.bmp_info_header.bmp_header_size = f->get_32(); + ERR_FAIL_COND_V(bmp_header.bmp_info_header.bmp_header_size < BITMAP_INFO_HEADER_MIN_SIZE, ERR_FILE_CORRUPT); + bmp_header.bmp_info_header.bmp_width = f->get_32(); bmp_header.bmp_info_header.bmp_height = f->get_32(); + bmp_header.bmp_info_header.bmp_planes = f->get_16(); + ERR_FAIL_COND_V(bmp_header.bmp_info_header.bmp_planes != 1, ERR_FILE_CORRUPT); + bmp_header.bmp_info_header.bmp_bit_count = f->get_16(); bmp_header.bmp_info_header.bmp_compression = f->get_32(); bmp_header.bmp_info_header.bmp_size_image = f->get_32(); @@ -129,37 +233,39 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f, bmp_header.bmp_info_header.bmp_colors_used = f->get_32(); bmp_header.bmp_info_header.bmp_important_colors = f->get_32(); - bmp_header.bmp_info_header.bmp_red_mask = f->get_32(); - bmp_header.bmp_info_header.bmp_green_mask = f->get_32(); - bmp_header.bmp_info_header.bmp_blue_mask = f->get_32(); - bmp_header.bmp_info_header.bmp_alpha_mask = f->get_32(); - bmp_header.bmp_info_header.bmp_cs_type = f->get_32(); - for (int i = 0; i < 9; i++) - bmp_header.bmp_info_header.bmp_endpoints[i] = f->get_32(); - - bmp_header.bmp_info_header.bmp_gamma_red = f->get_32(); - bmp_header.bmp_info_header.bmp_gamma_green = f->get_32(); - bmp_header.bmp_info_header.bmp_gamma_blue = f->get_32(); - - f->seek(sizeof(bmp_header.bmp_file_header) + - bmp_header.bmp_info_header.bmp_header_size); + switch (bmp_header.bmp_info_header.bmp_compression) { + case BI_RLE8: + case BI_RLE4: + case BI_CMYKRLE8: + case BI_CMYKRLE4: { + // Stop parsing + String bmp_path = f->get_path(); + f->close(); + ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Compressed BMP files are not supported: " + bmp_path + "."); + } break; + } + // Don't rely on sizeof(bmp_file_header) as structure padding + // adds 2 bytes offset leading to misaligned color table reading + uint32_t ct_offset = BITMAP_FILE_HEADER_SIZE + + bmp_header.bmp_info_header.bmp_header_size; + f->seek(ct_offset); uint32_t color_table_size = 0; - if (bmp_header.bmp_info_header.bmp_bit_count == 1) - color_table_size = 2; - else if (bmp_header.bmp_info_header.bmp_bit_count == 4) - color_table_size = 16; - else if (bmp_header.bmp_info_header.bmp_bit_count == 8) - color_table_size = 256; - PoolVector<uint8_t> bmp_color_table; - if (color_table_size > 0) { - err = bmp_color_table.resize(color_table_size * 4); - PoolVector<uint8_t>::Write bmp_color_table_w = bmp_color_table.write(); - f->get_buffer(bmp_color_table_w.ptr(), - bmp_header.bmp_info_header.bmp_colors_used * 4); + // bmp_colors_used may report 0 despite having a color table + // for 4 and 1 bit images, so don't rely on this information + if (bmp_header.bmp_info_header.bmp_bit_count <= 8) { + // Support 256 colors max + color_table_size = 1 << bmp_header.bmp_info_header.bmp_bit_count; + ERR_FAIL_COND_V(color_table_size == 0, ERR_BUG); } + PoolVector<uint8_t> bmp_color_table; + // Color table is usually 4 bytes per color -> [B][G][R][0] + bmp_color_table.resize(color_table_size * 4); + PoolVector<uint8_t>::Write bmp_color_table_w = bmp_color_table.write(); + f->get_buffer(bmp_color_table_w.ptr(), color_table_size * 4); + f->seek(bmp_header.bmp_file_header.bmp_file_offset); uint32_t bmp_buffer_size = (bmp_header.bmp_file_header.bmp_file_size - @@ -174,7 +280,7 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f, PoolVector<uint8_t>::Read bmp_buffer_r = bmp_buffer.read(); PoolVector<uint8_t>::Read bmp_color_table_r = bmp_color_table.read(); err = convert_to_image(p_image, bmp_buffer_r.ptr(), - bmp_color_table_r.ptr(), bmp_header); + bmp_color_table_r.ptr(), color_table_size, bmp_header); } f->close(); } diff --git a/modules/bmp/image_loader_bmp.h b/modules/bmp/image_loader_bmp.h index d6899061d0..2debb19a1c 100644 --- a/modules/bmp/image_loader_bmp.h +++ b/modules/bmp/image_loader_bmp.h @@ -37,6 +37,22 @@ class ImageLoaderBMP : public ImageFormatLoader { protected: static const unsigned BITMAP_SIGNATURE = 0x4d42; + static const unsigned BITMAP_FILE_HEADER_SIZE = 14; // bmp_file_header_s + static const unsigned BITMAP_INFO_HEADER_MIN_SIZE = 40; // bmp_info_header_s + + enum bmp_compression_s { + BI_RGB = 0x00, + BI_RLE8 = 0x01, // compressed + BI_RLE4 = 0x02, // compressed + BI_BITFIELDS = 0x03, + BI_JPEG = 0x04, + BI_PNG = 0x05, + BI_ALPHABITFIELDS = 0x06, + BI_CMYK = 0x0b, + BI_CMYKRLE8 = 0x0c, // compressed + BI_CMYKRLE4 = 0x0d // compressed + }; + struct bmp_header_s { struct bmp_file_header_s { uint16_t bmp_signature; @@ -57,21 +73,13 @@ protected: uint32_t bmp_pixels_per_meter_y; uint32_t bmp_colors_used; uint32_t bmp_important_colors; - uint32_t bmp_red_mask; - uint32_t bmp_green_mask; - uint32_t bmp_blue_mask; - uint32_t bmp_alpha_mask; - uint32_t bmp_cs_type; - uint32_t bmp_endpoints[9]; - uint32_t bmp_gamma_red; - uint32_t bmp_gamma_green; - uint32_t bmp_gamma_blue; } bmp_info_header; }; static Error convert_to_image(Ref<Image> p_image, const uint8_t *p_buffer, const uint8_t *p_color_buffer, + const uint32_t color_table_size, const bmp_header_s &p_header); public: diff --git a/modules/bullet/SCsub b/modules/bullet/SCsub index 7e714ba43f..ecc8a9b481 100644 --- a/modules/bullet/SCsub +++ b/modules/bullet/SCsub @@ -186,9 +186,13 @@ if env['builtin_bullet']: thirdparty_sources = [thirdparty_dir + file for file in bullet2_src] - env_bullet.Append(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(CCFLAGS=['-DBT_DEBUG']) + # env_bullet.Append(CPPDEFINES=['BT_DEBUG']) env_thirdparty = env_bullet.Clone() env_thirdparty.disable_warnings() diff --git a/modules/bullet/btRayShape.cpp b/modules/bullet/btRayShape.cpp index b902d08eca..b60d6ba693 100644 --- a/modules/bullet/btRayShape.cpp +++ b/modules/bullet/btRayShape.cpp @@ -54,6 +54,11 @@ void btRayShape::setLength(btScalar p_length) { reload_cache(); } +void btRayShape::setMargin(btScalar margin) { + btConvexInternalShape::setMargin(margin); + reload_cache(); +} + void btRayShape::setSlipsOnSlope(bool p_slipsOnSlope) { slipsOnSlope = p_slipsOnSlope; @@ -77,10 +82,9 @@ void btRayShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVecto } void btRayShape::getAabb(const btTransform &t, btVector3 &aabbMin, btVector3 &aabbMax) const { -#define MARGIN_BROADPHASE 0.1 btVector3 localAabbMin(0, 0, 0); - btVector3 localAabbMax(m_shapeAxis * (m_cacheScaledLength + m_collisionMargin)); - btTransformAabb(localAabbMin, localAabbMax, MARGIN_BROADPHASE, t, aabbMin, aabbMax); + btVector3 localAabbMax(m_shapeAxis * m_cacheScaledLength); + btTransformAabb(localAabbMin, localAabbMax, m_collisionMargin, t, aabbMin, aabbMax); } void btRayShape::calculateLocalInertia(btScalar mass, btVector3 &inertia) const { @@ -100,5 +104,5 @@ void btRayShape::reload_cache() { m_cacheScaledLength = m_length * m_localScaling[2]; m_cacheSupportPoint.setIdentity(); - m_cacheSupportPoint.setOrigin(m_shapeAxis * (m_cacheScaledLength + m_collisionMargin)); + m_cacheSupportPoint.setOrigin(m_shapeAxis * m_cacheScaledLength); } diff --git a/modules/bullet/btRayShape.h b/modules/bullet/btRayShape.h index 7fedb74083..09c1f6c241 100644 --- a/modules/bullet/btRayShape.h +++ b/modules/bullet/btRayShape.h @@ -60,7 +60,9 @@ public: void setLength(btScalar p_length); btScalar getLength() const { return m_length; } - void setSlipsOnSlope(bool p_slipOnSlope); + virtual void setMargin(btScalar margin); + + void setSlipsOnSlope(bool p_slipsOnSlope); bool getSlipsOnSlope() const { return slipsOnSlope; } const btTransform &getSupportPoint() const { return m_cacheSupportPoint; } diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp index 44ea061f51..e01928191a 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); } @@ -279,14 +279,14 @@ PhysicsServer::AreaSpaceOverrideMode BulletPhysicsServer::area_get_space_overrid return area->get_spOv_mode(); } -void BulletPhysicsServer::area_add_shape(RID p_area, RID p_shape, const Transform &p_transform) { +void BulletPhysicsServer::area_add_shape(RID p_area, RID p_shape, const Transform &p_transform, bool p_disabled) { AreaBullet *area = area_owner.get(p_area); ERR_FAIL_COND(!area); ShapeBullet *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); - area->add_shape(shape, p_transform); + area->add_shape(shape, p_transform, p_disabled); } void BulletPhysicsServer::area_set_shape(RID p_area, int p_shape_idx, RID p_shape) { @@ -348,13 +348,13 @@ void BulletPhysicsServer::area_set_shape_disabled(RID p_area, int p_shape_idx, b area->set_shape_disabled(p_shape_idx, p_disabled); } -void BulletPhysicsServer::area_attach_object_instance_id(RID p_area, ObjectID p_ID) { +void BulletPhysicsServer::area_attach_object_instance_id(RID p_area, ObjectID p_id) { if (space_owner.owns(p_area)) { return; } AreaBullet *area = area_owner.get(p_area); ERR_FAIL_COND(!area); - area->set_instance_id(p_ID); + area->set_instance_id(p_id); } ObjectID BulletPhysicsServer::area_get_object_instance_id(RID p_area) const { @@ -498,7 +498,7 @@ PhysicsServer::BodyMode BulletPhysicsServer::body_get_mode(RID p_body) const { return body->get_mode(); } -void BulletPhysicsServer::body_add_shape(RID p_body, RID p_shape, const Transform &p_transform) { +void BulletPhysicsServer::body_add_shape(RID p_body, RID p_shape, const Transform &p_transform, bool p_disabled) { RigidBodyBullet *body = rigid_body_owner.get(p_body); ERR_FAIL_COND(!body); @@ -506,7 +506,7 @@ void BulletPhysicsServer::body_add_shape(RID p_body, RID p_shape, const Transfor ShapeBullet *shape = shape_owner.get(p_shape); ERR_FAIL_COND(!shape); - body->add_shape(shape, p_transform); + body->add_shape(shape, p_transform, p_disabled); } void BulletPhysicsServer::body_set_shape(RID p_body, int p_shape_idx, RID p_shape) { @@ -569,11 +569,11 @@ void BulletPhysicsServer::body_clear_shapes(RID p_body) { body->remove_all_shapes(); } -void BulletPhysicsServer::body_attach_object_instance_id(RID p_body, uint32_t p_ID) { +void BulletPhysicsServer::body_attach_object_instance_id(RID p_body, uint32_t p_id) { CollisionObjectBullet *body = get_collisin_object(p_body); ERR_FAIL_COND(!body); - body->set_instance_id(p_ID); + body->set_instance_id(p_id); } uint32_t BulletPhysicsServer::body_get_object_instance_id(RID p_body) const { @@ -1548,8 +1548,7 @@ void BulletPhysicsServer::free(RID p_rid) { bulletdelete(space); } else { - ERR_EXPLAIN("Invalid ID"); - ERR_FAIL(); + ERR_FAIL_MSG("Invalid ID."); } } diff --git a/modules/bullet/bullet_physics_server.h b/modules/bullet/bullet_physics_server.h index 1b74cbf3fc..4c598c84f2 100644 --- a/modules/bullet/bullet_physics_server.h +++ b/modules/bullet/bullet_physics_server.h @@ -45,7 +45,7 @@ */ class BulletPhysicsServer : public PhysicsServer { - GDCLASS(BulletPhysicsServer, PhysicsServer) + GDCLASS(BulletPhysicsServer, PhysicsServer); friend class BulletPhysicsDirectSpaceState; @@ -133,7 +133,7 @@ public: virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode); virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const; - virtual void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform()); + virtual void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false); virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape); virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform); virtual int area_get_shape_count(RID p_area) const; @@ -142,7 +142,7 @@ public: virtual void area_remove_shape(RID p_area, int p_shape_idx); virtual void area_clear_shapes(RID p_area); virtual void area_set_shape_disabled(RID p_area, int p_shape_idx, bool p_disabled); - virtual void area_attach_object_instance_id(RID p_area, ObjectID p_ID); + virtual void area_attach_object_instance_id(RID p_area, ObjectID p_id); virtual ObjectID area_get_object_instance_id(RID p_area) const; /// If you pass as p_area the SpaceBullet you can set some parameters as specified below @@ -174,7 +174,7 @@ public: virtual void body_set_mode(RID p_body, BodyMode p_mode); virtual BodyMode body_get_mode(RID p_body) const; - virtual void body_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform()); + virtual void body_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false); // Not supported, Please remove and add new shape virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape); virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform); @@ -189,7 +189,7 @@ public: virtual void body_clear_shapes(RID p_body); // Used for Rigid and Soft Bodies - virtual void body_attach_object_instance_id(RID p_body, uint32_t p_ID); + virtual void body_attach_object_instance_id(RID p_body, uint32_t p_id); virtual uint32_t body_get_object_instance_id(RID p_body) const; virtual void body_set_enable_continuous_collision_detection(RID p_body, bool p_enable); diff --git a/modules/bullet/collision_object_bullet.cpp b/modules/bullet/collision_object_bullet.cpp index ef5f21fc21..e1800fd3eb 100644 --- a/modules/bullet/collision_object_bullet.cpp +++ b/modules/bullet/collision_object_bullet.cpp @@ -43,7 +43,9 @@ @author AndreaCatania */ -#define enableDynamicAabbTree false +// We enable dynamic AABB tree so that we can actually perform a broadphase on bodies with compound collision shapes. +// This is crucial for the performance of kinematic bodies and for bodies with transforming shapes. +#define enableDynamicAabbTree true CollisionObjectBullet::ShapeWrapper::~ShapeWrapper() {} @@ -57,6 +59,25 @@ void CollisionObjectBullet::ShapeWrapper::set_transform(const btTransform &p_tra transform = p_transform; } +btTransform CollisionObjectBullet::ShapeWrapper::get_adjusted_transform() const { + if (shape->get_type() == PhysicsServer::SHAPE_HEIGHTMAP) { + const HeightMapShapeBullet *hm_shape = (const HeightMapShapeBullet *)shape; // should be safe to cast now + btTransform adjusted_transform; + + // Bullet centers our heightmap: + // https://github.com/bulletphysics/bullet3/blob/master/src/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h#L33 + // This is really counter intuitive so we're adjusting for it + + adjusted_transform.setIdentity(); + adjusted_transform.setOrigin(btVector3(0.0, hm_shape->min_height + ((hm_shape->max_height - hm_shape->min_height) * 0.5), 0.0)); + adjusted_transform *= transform; + + return adjusted_transform; + } else { + return transform; + } +} + void CollisionObjectBullet::ShapeWrapper::claim_bt_shape(const btVector3 &body_scale) { if (!bt_shape) { if (active) @@ -216,8 +237,8 @@ RigidCollisionObjectBullet::~RigidCollisionObjectBullet() { } } -void RigidCollisionObjectBullet::add_shape(ShapeBullet *p_shape, const Transform &p_transform) { - shapes.push_back(ShapeWrapper(p_shape, p_transform, true)); +void RigidCollisionObjectBullet::add_shape(ShapeBullet *p_shape, const Transform &p_transform, bool p_disabled) { + shapes.push_back(ShapeWrapper(p_shape, p_transform, !p_disabled)); p_shape->add_owner(this); reload_shapes(); } @@ -284,8 +305,7 @@ void RigidCollisionObjectBullet::set_shape_transform(int p_index, const Transfor ERR_FAIL_INDEX(p_index, get_shape_count()); shapes.write[p_index].set_transform(p_transform); - // Note, enableDynamicAabbTree is false because on transform change compound is destroyed - reload_shapes(); + shape_changed(p_index); } const btTransform &RigidCollisionObjectBullet::get_bt_shape_transform(int p_index) const { @@ -299,6 +319,8 @@ Transform RigidCollisionObjectBullet::get_shape_transform(int p_index) const { } void RigidCollisionObjectBullet::set_shape_disabled(int p_index, bool p_disabled) { + if (shapes[p_index].active != p_disabled) + return; shapes.write[p_index].active = !p_disabled; shape_changed(p_index); } @@ -342,7 +364,8 @@ void RigidCollisionObjectBullet::reload_shapes() { // Try to optimize by not using compound if (1 == shape_count) { shpWrapper = &shapes.write[0]; - if (shpWrapper->transform.getOrigin().isZero() && shpWrapper->transform.getBasis() == shpWrapper->transform.getBasis().getIdentity()) { + btTransform transform = shpWrapper->get_adjusted_transform(); + if (transform.getOrigin().isZero() && transform.getBasis() == transform.getBasis().getIdentity()) { shpWrapper->claim_bt_shape(body_scale); mainShape = shpWrapper->bt_shape; main_shape_changed(); @@ -356,7 +379,7 @@ void RigidCollisionObjectBullet::reload_shapes() { for (int i(0); i < shape_count; ++i) { shpWrapper = &shapes.write[i]; shpWrapper->claim_bt_shape(body_scale); - btTransform scaled_shape_transform(shpWrapper->transform); + btTransform scaled_shape_transform(shpWrapper->get_adjusted_transform()); scaled_shape_transform.getOrigin() *= body_scale; compoundShape->addChildShape(scaled_shape_transform, shpWrapper->bt_shape); } diff --git a/modules/bullet/collision_object_bullet.h b/modules/bullet/collision_object_bullet.h index 2d4e5c4f1a..04231b0814 100644 --- a/modules/bullet/collision_object_bullet.h +++ b/modules/bullet/collision_object_bullet.h @@ -109,6 +109,7 @@ public: void set_transform(const Transform &p_transform); void set_transform(const btTransform &p_transform); + btTransform get_adjusted_transform() const; void claim_bt_shape(const btVector3 &body_scale); }; @@ -166,14 +167,18 @@ public: _FORCE_INLINE_ const VSet<RID> &get_exceptions() const { return exceptions; } _FORCE_INLINE_ void set_collision_layer(uint32_t p_layer) { - collisionLayer = p_layer; - on_collision_filters_change(); + if (collisionLayer != p_layer) { + collisionLayer = p_layer; + on_collision_filters_change(); + } } _FORCE_INLINE_ uint32_t get_collision_layer() const { return collisionLayer; } _FORCE_INLINE_ void set_collision_mask(uint32_t p_mask) { - collisionMask = p_mask; - on_collision_filters_change(); + if (collisionMask != p_mask) { + collisionMask = p_mask; + on_collision_filters_change(); + } } _FORCE_INLINE_ uint32_t get_collision_mask() const { return collisionMask; } @@ -224,7 +229,7 @@ public: _FORCE_INLINE_ btCollisionShape *get_main_shape() const { return mainShape; } - void add_shape(ShapeBullet *p_shape, const Transform &p_transform = Transform()); + void add_shape(ShapeBullet *p_shape, const Transform &p_transform = Transform(), bool p_disabled = false); void set_shape(int p_index, ShapeBullet *p_shape); int get_shape_count() const; diff --git a/modules/bullet/cone_twist_joint_bullet.cpp b/modules/bullet/cone_twist_joint_bullet.cpp index d9a82d6179..97b9a81f77 100644 --- a/modules/bullet/cone_twist_joint_bullet.cpp +++ b/modules/bullet/cone_twist_joint_bullet.cpp @@ -83,8 +83,7 @@ void ConeTwistJointBullet::set_param(PhysicsServer::ConeTwistJointParam p_param, coneConstraint->setLimit(coneConstraint->getSwingSpan1(), coneConstraint->getSwingSpan2(), coneConstraint->getTwistSpan(), coneConstraint->getLimitSoftness(), coneConstraint->getBiasFactor(), p_value); break; default: - ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated"); - WARN_DEPRECATED + WARN_DEPRECATED_MSG("The parameter " + itos(p_param) + " is deprecated."); break; } } @@ -102,8 +101,7 @@ real_t ConeTwistJointBullet::get_param(PhysicsServer::ConeTwistJointParam p_para case PhysicsServer::CONE_TWIST_JOINT_RELAXATION: return coneConstraint->getRelaxationFactor(); default: - ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated"); - WARN_DEPRECATED; + WARN_DEPRECATED_MSG("The parameter " + itos(p_param) + " is deprecated."); return 0; } } diff --git a/modules/bullet/doc_classes/BulletPhysicsDirectBodyState.xml b/modules/bullet/doc_classes/BulletPhysicsDirectBodyState.xml index 1f91349f32..078bcc45a8 100644 --- a/modules/bullet/doc_classes/BulletPhysicsDirectBodyState.xml +++ b/modules/bullet/doc_classes/BulletPhysicsDirectBodyState.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/bullet/doc_classes/BulletPhysicsServer.xml b/modules/bullet/doc_classes/BulletPhysicsServer.xml index 8adc659b2c..2a37f6af5e 100644 --- a/modules/bullet/doc_classes/BulletPhysicsServer.xml +++ b/modules/bullet/doc_classes/BulletPhysicsServer.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/bullet/generic_6dof_joint_bullet.cpp b/modules/bullet/generic_6dof_joint_bullet.cpp index 8fed933854..4aae87c220 100644 --- a/modules/bullet/generic_6dof_joint_bullet.cpp +++ b/modules/bullet/generic_6dof_joint_bullet.cpp @@ -174,8 +174,7 @@ void Generic6DOFJointBullet::set_param(Vector3::Axis p_axis, PhysicsServer::G6DO sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_equilibriumPoint = p_value; break; default: - ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated"); - WARN_DEPRECATED + WARN_DEPRECATED_MSG("The parameter " + itos(p_param) + " is deprecated."); break; } } @@ -216,8 +215,7 @@ real_t Generic6DOFJointBullet::get_param(Vector3::Axis p_axis, PhysicsServer::G6 case PhysicsServer::G6DOF_JOINT_ANGULAR_SPRING_EQUILIBRIUM_POINT: return sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_equilibriumPoint; default: - ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated"); - WARN_DEPRECATED; + WARN_DEPRECATED_MSG("The parameter " + itos(p_param) + " is deprecated."); return 0; } } @@ -255,8 +253,7 @@ void Generic6DOFJointBullet::set_flag(Vector3::Axis p_axis, PhysicsServer::G6DOF sixDOFConstraint->getRotationalLimitMotor(p_axis)->m_enableSpring = p_value; break; default: - ERR_EXPLAIN("This flag " + itos(p_flag) + " is deprecated"); - WARN_DEPRECATED + WARN_DEPRECATED_MSG("The flag " + itos(p_flag) + " is deprecated."); break; } } diff --git a/modules/bullet/godot_ray_world_algorithm.cpp b/modules/bullet/godot_ray_world_algorithm.cpp index 3e06239453..2ba75b9a98 100644 --- a/modules/bullet/godot_ray_world_algorithm.cpp +++ b/modules/bullet/godot_ray_world_algorithm.cpp @@ -39,6 +39,9 @@ @author AndreaCatania */ +// Epsilon to account for floating point inaccuracies +#define RAY_PENETRATION_DEPTH_EPSILON 0.01 + GodotRayWorldAlgorithm::CreateFunc::CreateFunc(const btDiscreteDynamicsWorld *world) : m_world(world) {} @@ -100,8 +103,8 @@ void GodotRayWorldAlgorithm::processCollision(const btCollisionObjectWrapper *bo btScalar depth(ray_shape->getScaledLength() * (btResult.m_closestHitFraction - 1)); - if (depth >= -ray_shape->getMargin() * 0.5) - depth = 0; + if (depth > -RAY_PENETRATION_DEPTH_EPSILON) + depth = 0.0; if (ray_shape->getSlipsOnSlope()) resultOut->addContactPoint(btResult.m_hitNormalWorld, btResult.m_hitPointWorld, depth); diff --git a/modules/bullet/hinge_joint_bullet.cpp b/modules/bullet/hinge_joint_bullet.cpp index 7b99d3d89f..4d26e729db 100644 --- a/modules/bullet/hinge_joint_bullet.cpp +++ b/modules/bullet/hinge_joint_bullet.cpp @@ -117,8 +117,7 @@ void HingeJointBullet::set_param(PhysicsServer::HingeJointParam p_param, real_t hingeConstraint->setMaxMotorImpulse(p_value); break; default: - ERR_EXPLAIN("The HingeJoint parameter " + itos(p_param) + " is deprecated."); - WARN_DEPRECATED + WARN_DEPRECATED_MSG("The HingeJoint parameter " + itos(p_param) + " is deprecated."); break; } } @@ -143,8 +142,7 @@ real_t HingeJointBullet::get_param(PhysicsServer::HingeJointParam p_param) const case PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE: return hingeConstraint->getMaxMotorImpulse(); default: - ERR_EXPLAIN("The HingeJoint parameter " + itos(p_param) + " is deprecated."); - WARN_DEPRECATED; + WARN_DEPRECATED_MSG("The HingeJoint parameter " + itos(p_param) + " is deprecated."); return 0; } } diff --git a/modules/bullet/pin_joint_bullet.cpp b/modules/bullet/pin_joint_bullet.cpp index 58b090006a..8d404e7f04 100644 --- a/modules/bullet/pin_joint_bullet.cpp +++ b/modules/bullet/pin_joint_bullet.cpp @@ -85,8 +85,7 @@ real_t PinJointBullet::get_param(PhysicsServer::PinJointParam p_param) const { case PhysicsServer::PIN_JOINT_IMPULSE_CLAMP: return p2pConstraint->m_setting.m_impulseClamp; default: - ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated"); - WARN_DEPRECATED + WARN_DEPRECATED_MSG("The parameter " + itos(p_param) + " is deprecated."); return 0; } } diff --git a/modules/bullet/rigid_body_bullet.cpp b/modules/bullet/rigid_body_bullet.cpp index 22f2214898..d611810bfa 100644 --- a/modules/bullet/rigid_body_bullet.cpp +++ b/modules/bullet/rigid_body_bullet.cpp @@ -126,16 +126,16 @@ void BulletPhysicsDirectBodyState::add_torque(const Vector3 &p_torque) { body->apply_torque(p_torque); } -void BulletPhysicsDirectBodyState::apply_central_impulse(const Vector3 &p_j) { - body->apply_central_impulse(p_j); +void BulletPhysicsDirectBodyState::apply_central_impulse(const Vector3 &p_impulse) { + body->apply_central_impulse(p_impulse); } -void BulletPhysicsDirectBodyState::apply_impulse(const Vector3 &p_pos, const Vector3 &p_j) { - body->apply_impulse(p_pos, p_j); +void BulletPhysicsDirectBodyState::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) { + body->apply_impulse(p_pos, p_impulse); } -void BulletPhysicsDirectBodyState::apply_torque_impulse(const Vector3 &p_j) { - body->apply_torque_impulse(p_j); +void BulletPhysicsDirectBodyState::apply_torque_impulse(const Vector3 &p_impulse) { + body->apply_torque_impulse(p_impulse); } void BulletPhysicsDirectBodyState::set_sleep_state(bool p_enable) { @@ -411,6 +411,8 @@ void RigidBodyBullet::on_collision_filters_change() { if (space) { space->reload_collision_filters(this); } + + set_activation_state(true); } void RigidBodyBullet::on_collision_checker_start() { @@ -471,7 +473,7 @@ void RigidBodyBullet::assert_no_constraints() { void RigidBodyBullet::set_activation_state(bool p_active) { if (p_active) { - btBody->setActivationState(ACTIVE_TAG); + btBody->activate(); } else { btBody->setActivationState(WANTS_DEACTIVATION); } @@ -597,6 +599,8 @@ void RigidBodyBullet::set_state(PhysicsServer::BodyState p_state, const Variant if (!can_sleep) { // Can't sleep btBody->forceActivationState(DISABLE_DEACTIVATION); + } else { + btBody->forceActivationState(ACTIVE_TAG); } break; } @@ -726,12 +730,12 @@ bool RigidBodyBullet::is_axis_locked(PhysicsServer::BodyAxis p_axis) const { void RigidBodyBullet::reload_axis_lock() { - btBody->setLinearFactor(btVector3(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_X), !is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Y), !is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Z))); + btBody->setLinearFactor(btVector3(float(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_X)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Y)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Z)))); if (PhysicsServer::BODY_MODE_CHARACTER == mode) { /// When character angular is always locked btBody->setAngularFactor(btVector3(0., 0., 0.)); } else { - btBody->setAngularFactor(btVector3(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_X), !is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Y), !is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Z))); + btBody->setAngularFactor(btVector3(float(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_X)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Y)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Z)))); } } @@ -739,22 +743,20 @@ void RigidBodyBullet::set_continuous_collision_detection(bool p_enable) { if (p_enable) { // This threshold enable CCD if the object moves more than // 1 meter in one simulation frame - btBody->setCcdMotionThreshold(0.1); + btBody->setCcdMotionThreshold(1e-7); /// Calculate using the rule writte below the CCD swept sphere radius /// CCD works on an embedded sphere of radius, make sure this radius /// is embedded inside the convex objects, preferably smaller: /// for an object of dimensions 1 meter, try 0.2 - btScalar radius; + btScalar radius(1.0); if (btBody->getCollisionShape()) { btVector3 center; btBody->getCollisionShape()->getBoundingSphere(center, radius); - } else { - radius = 0; } btBody->setCcdSweptSphereRadius(radius * 0.2); } else { - btBody->setCcdMotionThreshold(0.); + btBody->setCcdMotionThreshold(10000.0); btBody->setCcdSweptSphereRadius(0.); } } @@ -832,7 +834,7 @@ void RigidBodyBullet::reload_shapes() { btBody->updateInertiaTensor(); reload_kinematic_shapes(); - + set_continuous_collision_detection(btBody->getCcdMotionThreshold() < 9998.0); reload_body(); } @@ -866,7 +868,7 @@ void RigidBodyBullet::on_enter_area(AreaBullet *p_area) { if (p_area->is_spOv_gravityPoint()) { ++countGravityPointSpaces; - assert(0 < countGravityPointSpaces); + ERR_FAIL_COND(countGravityPointSpaces <= 0); } } @@ -888,7 +890,7 @@ void RigidBodyBullet::on_exit_area(AreaBullet *p_area) { if (wasTheAreaFound) { if (p_area->is_spOv_gravityPoint()) { --countGravityPointSpaces; - assert(0 <= countGravityPointSpaces); + ERR_FAIL_COND(countGravityPointSpaces < 0); } --areaWhereIamCount; @@ -918,7 +920,7 @@ void RigidBodyBullet::reload_space_override_modificator() { currentArea = areasWhereIam[i]; - if (PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED == currentArea->get_spOv_mode()) { + if (!currentArea || PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED == currentArea->get_spOv_mode()) { continue; } diff --git a/modules/bullet/rigid_body_bullet.h b/modules/bullet/rigid_body_bullet.h index 1e1bea846a..0b6dc997db 100644 --- a/modules/bullet/rigid_body_bullet.h +++ b/modules/bullet/rigid_body_bullet.h @@ -54,7 +54,7 @@ class BulletPhysicsDirectBodyState; /// created by BulletPhysicsServer and is held by the "singleton" variable of this class /// Each time something require it, the body must be set again. class BulletPhysicsDirectBodyState : public PhysicsDirectBodyState { - GDCLASS(BulletPhysicsDirectBodyState, PhysicsDirectBodyState) + GDCLASS(BulletPhysicsDirectBodyState, PhysicsDirectBodyState); static BulletPhysicsDirectBodyState *singleton; @@ -114,8 +114,8 @@ public: virtual void add_force(const Vector3 &p_force, const Vector3 &p_pos); virtual void add_torque(const Vector3 &p_torque); virtual void apply_central_impulse(const Vector3 &p_impulse); - virtual void apply_impulse(const Vector3 &p_pos, const Vector3 &p_j); - virtual void apply_torque_impulse(const Vector3 &p_j); + virtual void apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse); + virtual void apply_torque_impulse(const Vector3 &p_impulse); virtual void set_sleep_state(bool p_enable); virtual bool is_sleeping() const; @@ -305,7 +305,7 @@ public: void reload_axis_lock(); /// Doc: - /// http://www.bulletphysics.org/mediawiki-1.5.8/index.php?title=Anti_tunneling_by_Motion_Clamping + /// https://web.archive.org/web/20180404091446/http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Anti_tunneling_by_Motion_Clamping void set_continuous_collision_detection(bool p_enable); bool is_continuous_collision_detection_enabled() const; diff --git a/modules/bullet/shape_bullet.cpp b/modules/bullet/shape_bullet.cpp index b590d63167..85f47c3bbb 100644 --- a/modules/bullet/shape_bullet.cpp +++ b/modules/bullet/shape_bullet.cpp @@ -148,7 +148,13 @@ btHeightfieldTerrainShape *ShapeBullet::create_shape_height_field(PoolVector<rea const bool flipQuadEdges = false; const void *heightsPtr = p_heights.read().ptr(); - return bulletnew(btHeightfieldTerrainShape(p_width, p_depth, heightsPtr, ignoredHeightScale, p_min_height, p_max_height, YAxis, PHY_FLOAT, flipQuadEdges)); + btHeightfieldTerrainShape *heightfield = bulletnew(btHeightfieldTerrainShape(p_width, p_depth, heightsPtr, ignoredHeightScale, p_min_height, p_max_height, YAxis, PHY_FLOAT, flipQuadEdges)); + + // The shape can be created without params when you do PhysicsServer.shape_create(PhysicsServer.SHAPE_HEIGHTMAP) + if (heightsPtr) + heightfield->buildAccelerator(16); + + return heightfield; } btRayShape *ShapeBullet::create_shape_ray(real_t p_length, bool p_slips_on_slope) { @@ -499,8 +505,7 @@ void HeightMapShapeBullet::set_data(const Variant &p_data) { } } else { - ERR_EXPLAIN("Expected PoolRealArray or float Image."); - ERR_FAIL(); + ERR_FAIL_MSG("Expected PoolRealArray or float Image."); } ERR_FAIL_COND(l_width <= 0); diff --git a/modules/bullet/space_bullet.cpp b/modules/bullet/space_bullet.cpp index 8fb8eba057..d73930775d 100644 --- a/modules/bullet/space_bullet.cpp +++ b/modules/bullet/space_bullet.cpp @@ -42,6 +42,7 @@ #include "servers/physics_server.h" #include "soft_body_bullet.h" +#include <BulletCollision/BroadphaseCollision/btBroadphaseProxy.h> #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h> @@ -459,9 +460,13 @@ void SpaceBullet::remove_area(AreaBullet *p_area) { } void SpaceBullet::reload_collision_filters(AreaBullet *p_area) { - // This is necessary to change collision filter - dynamicsWorld->removeCollisionObject(p_area->get_bt_ghost()); - dynamicsWorld->addCollisionObject(p_area->get_bt_ghost(), p_area->get_collision_layer(), p_area->get_collision_mask()); + btGhostObject *ghost_object = p_area->get_bt_ghost(); + + btBroadphaseProxy *ghost_proxy = ghost_object->getBroadphaseHandle(); + ghost_proxy->m_collisionFilterGroup = p_area->get_collision_layer(); + ghost_proxy->m_collisionFilterMask = p_area->get_collision_mask(); + + dynamicsWorld->refreshBroadphaseProxy(ghost_object); } void SpaceBullet::add_rigid_body(RigidBodyBullet *p_body) { @@ -482,9 +487,13 @@ void SpaceBullet::remove_rigid_body(RigidBodyBullet *p_body) { } void SpaceBullet::reload_collision_filters(RigidBodyBullet *p_body) { - // This is necessary to change collision filter - remove_rigid_body(p_body); - add_rigid_body(p_body); + btRigidBody *rigid_body = p_body->get_bt_rigid_body(); + + btBroadphaseProxy *body_proxy = rigid_body->getBroadphaseProxy(); + body_proxy->m_collisionFilterGroup = p_body->get_collision_layer(); + body_proxy->m_collisionFilterMask = p_body->get_collision_mask(); + + dynamicsWorld->refreshBroadphaseProxy(rigid_body); } void SpaceBullet::add_soft_body(SoftBodyBullet *p_body) { @@ -582,6 +591,8 @@ void SpaceBullet::create_empty_world(bool p_create_soft_world) { world_mem = malloc(sizeof(btDiscreteDynamicsWorld)); } + ERR_FAIL_COND_MSG(!world_mem, "Out of memory."); + if (p_create_soft_world) { collisionConfiguration = bulletnew(GodotSoftCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem))); } else { @@ -934,8 +945,8 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f btVector3 motion; G_TO_B(p_motion, motion); - - { /// phase two - sweep test, from a secure position without margin + if (!motion.fuzzyZero()) { + // Phase two - sweep test, from a secure position without margin const int shape_count(p_body->get_shape_count()); @@ -1043,23 +1054,16 @@ int SpaceBullet::test_ray_separation(RigidBodyBullet *p_body, const Transform &p btVector3 recover_motion(0, 0, 0); int rays_found = 0; + int rays_found_this_round = 0; for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) { - int last_ray_index = recover_from_penetration_ray(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, p_result_max, recover_motion, r_results); + PhysicsServer::SeparationResult *next_results = &r_results[rays_found]; + rays_found_this_round = recover_from_penetration_ray(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, p_result_max - rays_found, recover_motion, next_results); - rays_found = MAX(last_ray_index, rays_found); - if (!rays_found) { - break; - } else { + rays_found += rays_found_this_round; + if (rays_found_this_round == 0) { body_transform.getOrigin() += recover_motion; - } - } - - //optimize results (remove non colliding) - for (int i = 0; i < rays_found; i++) { - if (r_results[i].collision_depth >= 0) { - rays_found--; - SWAP(r_results[i], r_results[rays_found]); + break; } } @@ -1069,18 +1073,47 @@ int SpaceBullet::test_ray_separation(RigidBodyBullet *p_body, const Transform &p struct RecoverPenetrationBroadPhaseCallback : public btBroadphaseAabbCallback { private: + btDbvtVolume bounds; + const btCollisionObject *self_collision_object; uint32_t collision_layer; uint32_t collision_mask; + struct CompoundLeafCallback : btDbvt::ICollide { + private: + RecoverPenetrationBroadPhaseCallback *parent_callback; + btCollisionObject *collision_object; + + public: + CompoundLeafCallback(RecoverPenetrationBroadPhaseCallback *p_parent_callback, btCollisionObject *p_collision_object) : + parent_callback(p_parent_callback), + collision_object(p_collision_object) { + } + + void Process(const btDbvtNode *leaf) { + BroadphaseResult result; + result.collision_object = collision_object; + result.compound_child_index = leaf->dataAsInt; + parent_callback->results.push_back(result); + } + }; + public: - Vector<btCollisionObject *> result_collision_objects; + struct BroadphaseResult { + btCollisionObject *collision_object; + int compound_child_index; + }; + + Vector<BroadphaseResult> results; public: - RecoverPenetrationBroadPhaseCallback(const btCollisionObject *p_self_collision_object, uint32_t p_collision_layer, uint32_t p_collision_mask) : + RecoverPenetrationBroadPhaseCallback(const btCollisionObject *p_self_collision_object, uint32_t p_collision_layer, uint32_t p_collision_mask, btVector3 p_aabb_min, btVector3 p_aabb_max) : self_collision_object(p_self_collision_object), collision_layer(p_collision_layer), - collision_mask(p_collision_mask) {} + collision_mask(p_collision_mask) { + + bounds = btDbvtVolume::FromMM(p_aabb_min, p_aabb_max); + } virtual ~RecoverPenetrationBroadPhaseCallback() {} @@ -1089,35 +1122,98 @@ public: btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject); if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) { if (self_collision_object != proxy->m_clientObject && GodotFilterCallback::test_collision_filters(collision_layer, collision_mask, proxy->m_collisionFilterGroup, proxy->m_collisionFilterMask)) { - result_collision_objects.push_back(co); + if (co->getCollisionShape()->isCompound()) { + const btCompoundShape *cs = static_cast<btCompoundShape *>(co->getCollisionShape()); + + if (cs->getNumChildShapes() > 1) { + const btDbvt *tree = cs->getDynamicAabbTree(); + ERR_FAIL_COND_V(tree == NULL, true); + + // Transform bounds into compound shape local space + const btTransform other_in_compound_space = co->getWorldTransform().inverse(); + const btMatrix3x3 abs_b = other_in_compound_space.getBasis().absolute(); + const btVector3 local_center = other_in_compound_space(bounds.Center()); + const btVector3 local_extent = bounds.Extents().dot3(abs_b[0], abs_b[1], abs_b[2]); + const btVector3 local_aabb_min = local_center - local_extent; + const btVector3 local_aabb_max = local_center + local_extent; + const btDbvtVolume local_bounds = btDbvtVolume::FromMM(local_aabb_min, local_aabb_max); + + // Test collision against compound child shapes using its AABB tree + CompoundLeafCallback compound_leaf_callback(this, co); + tree->collideTV(tree->m_root, local_bounds, compound_leaf_callback); + } else { + // If there's only a single child shape then there's no need to search any more, we know which child overlaps + BroadphaseResult result; + result.collision_object = co; + result.compound_child_index = 0; + results.push_back(result); + } + } else { + BroadphaseResult result; + result.collision_object = co; + result.compound_child_index = -1; + results.push_back(result); + } return true; } } return false; } - - void reset() { - result_collision_objects.clear(); - } }; bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) { - RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask()); + // Calculate the cumulative AABB of all shapes of the kinematic body + btVector3 aabb_min, aabb_max; + bool shapes_found = false; + + for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) { + + const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]); + if (!kin_shape.is_active()) { + continue; + } + + if (kin_shape.shape->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) { + // Skip rayshape in order to implement custom separation process + continue; + } + + btTransform shape_transform = p_body_position * kin_shape.transform; + shape_transform.getOrigin() += r_delta_recover_movement; + + btVector3 shape_aabb_min, shape_aabb_max; + kin_shape.shape->getAabb(shape_transform, shape_aabb_min, shape_aabb_max); - btTransform body_shape_position; - btTransform body_shape_position_recovered; + if (!shapes_found) { + aabb_min = shape_aabb_min; + aabb_max = shape_aabb_max; + shapes_found = true; + } else { + aabb_min.setX((aabb_min.x() < shape_aabb_min.x()) ? aabb_min.x() : shape_aabb_min.x()); + aabb_min.setY((aabb_min.y() < shape_aabb_min.y()) ? aabb_min.y() : shape_aabb_min.y()); + aabb_min.setZ((aabb_min.z() < shape_aabb_min.z()) ? aabb_min.z() : shape_aabb_min.z()); + + aabb_max.setX((aabb_max.x() > shape_aabb_max.x()) ? aabb_max.x() : shape_aabb_max.x()); + aabb_max.setY((aabb_max.y() > shape_aabb_max.y()) ? aabb_max.y() : shape_aabb_max.y()); + aabb_max.setZ((aabb_max.z() > shape_aabb_max.z()) ? aabb_max.z() : shape_aabb_max.z()); + } + } + + // If there are no shapes then there is no penetration either + if (!shapes_found) { + return false; + } - // Broad phase support - btVector3 minAabb, maxAabb; + // Perform broadphase test + RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max); + dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result); bool penetration = false; - // For each shape + // Perform narrowphase per shape for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) { - recover_broad_result.reset(); - const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]); if (!kin_shape.is_active()) { continue; @@ -1128,15 +1224,11 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran continue; } - body_shape_position = p_body_position * kin_shape.transform; - body_shape_position_recovered = body_shape_position; - body_shape_position_recovered.getOrigin() += r_delta_recover_movement; - - kin_shape.shape->getAabb(body_shape_position_recovered, minAabb, maxAabb); - dynamicsWorld->getBroadphase()->aabbTest(minAabb, maxAabb, recover_broad_result); + btTransform shape_transform = p_body_position * kin_shape.transform; + shape_transform.getOrigin() += r_delta_recover_movement; - for (int i = recover_broad_result.result_collision_objects.size() - 1; 0 <= i; --i) { - btCollisionObject *otherObject = recover_broad_result.result_collision_objects[i]; + for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) { + btCollisionObject *otherObject = recover_broad_result.results[i].collision_object; if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) { otherObject->activate(); // Force activation of hitten rigid, soft body continue; @@ -1144,30 +1236,28 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran continue; if (otherObject->getCollisionShape()->isCompound()) { + const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape()); + int shape_idx = recover_broad_result.results[i].compound_child_index; + ERR_FAIL_COND_V(shape_idx < 0 || shape_idx >= cs->getNumChildShapes(), false); - // Each convex shape - btCompoundShape *cs = static_cast<btCompoundShape *>(otherObject->getCollisionShape()); - for (int x = cs->getNumChildShapes() - 1; 0 <= x; --x) { + if (cs->getChildShape(shape_idx)->isConvex()) { + if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(cs->getChildShape(shape_idx)), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { - if (cs->getChildShape(x)->isConvex()) { - if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(cs->getChildShape(x)), otherObject, x, body_shape_position, otherObject->getWorldTransform() * cs->getChildTransform(x), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { - - penetration = true; - } - } else { - if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(x), p_body->get_bt_collision_object(), otherObject, kinIndex, x, body_shape_position, otherObject->getWorldTransform() * cs->getChildTransform(x), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { + penetration = true; + } + } else { + if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { - penetration = true; - } + penetration = true; } } } else if (otherObject->getCollisionShape()->isConvex()) { /// Execute GJK test against object shape - if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(otherObject->getCollisionShape()), otherObject, 0, body_shape_position, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { + if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(otherObject->getCollisionShape()), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { penetration = true; } } else { - if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, body_shape_position, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { + if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) { penetration = true; } @@ -1178,12 +1268,11 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran return penetration; } -bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) { +bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) { // Initialize GJK input btGjkPairDetector::ClosestPointInput gjk_input; gjk_input.m_transformA = p_transformA; - gjk_input.m_transformA.getOrigin() += r_delta_recover_movement; gjk_input.m_transformB = p_transformB; // Perform GJK test @@ -1197,6 +1286,7 @@ bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const bt if (r_recover_result) { if (result.m_distance < r_recover_result->penetration_distance) { r_recover_result->hasPenetration = true; + r_recover_result->local_shape_most_recovered = p_shapeId_A; r_recover_result->other_collision_object = p_objectB; r_recover_result->other_compound_shape_index = p_shapeId_B; r_recover_result->penetration_distance = result.m_distance; @@ -1214,7 +1304,6 @@ bool SpaceBullet::RFP_convex_world_test(const btConvexShape *p_shapeA, const btC /// Contact test btTransform tA(p_transformA); - tA.getOrigin() += r_delta_recover_movement; btCollisionObjectWrapper obA(NULL, p_shapeA, p_objectA, tA, -1, p_shapeId_A); btCollisionObjectWrapper obB(NULL, p_shapeB, p_objectB, p_transformB, -1, p_shapeId_B); @@ -1233,6 +1322,7 @@ bool SpaceBullet::RFP_convex_world_test(const btConvexShape *p_shapeA, const btC if (r_recover_result) { if (contactPointResult.m_penetration_distance < r_recover_result->penetration_distance) { r_recover_result->hasPenetration = true; + r_recover_result->local_shape_most_recovered = p_shapeId_A; r_recover_result->other_collision_object = p_objectB; r_recover_result->other_compound_shape_index = p_shapeId_B; r_recover_result->penetration_distance = contactPointResult.m_penetration_distance; @@ -1246,39 +1336,81 @@ bool SpaceBullet::RFP_convex_world_test(const btConvexShape *p_shapeA, const btC return false; } -void SpaceBullet::convert_to_separation_result(PhysicsServer::SeparationResult *r_result, const SpaceBullet::RecoverResult &p_recover_result, int p_shape_id, const btCollisionObject *p_other_object) const { +int SpaceBullet::add_separation_result(PhysicsServer::SeparationResult *r_result, const SpaceBullet::RecoverResult &p_recover_result, int p_shape_id, const btCollisionObject *p_other_object) const { + + // optimize results (ignore non-colliding) + if (p_recover_result.penetration_distance < 0.0) { + const btRigidBody *btRigid = static_cast<const btRigidBody *>(p_other_object); + CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(p_other_object->getUserPointer()); - const btRigidBody *btRigid = static_cast<const btRigidBody *>(p_other_object); - CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(p_other_object->getUserPointer()); + r_result->collision_depth = p_recover_result.penetration_distance; + B_TO_G(p_recover_result.pointWorld, r_result->collision_point); + B_TO_G(p_recover_result.normal, r_result->collision_normal); + B_TO_G(btRigid->getVelocityInLocalPoint(p_recover_result.pointWorld - btRigid->getWorldTransform().getOrigin()), r_result->collider_velocity); + r_result->collision_local_shape = p_shape_id; + r_result->collider_id = collisionObject->get_instance_id(); + r_result->collider = collisionObject->get_self(); + r_result->collider_shape = p_recover_result.other_compound_shape_index; - r_result->collision_depth = p_recover_result.penetration_distance; - B_TO_G(p_recover_result.pointWorld, r_result->collision_point); - B_TO_G(p_recover_result.normal, r_result->collision_normal); - B_TO_G(btRigid->getVelocityInLocalPoint(p_recover_result.pointWorld - btRigid->getWorldTransform().getOrigin()), r_result->collider_velocity); - r_result->collision_local_shape = p_shape_id; - r_result->collider_id = collisionObject->get_instance_id(); - r_result->collider = collisionObject->get_self(); - r_result->collider_shape = p_recover_result.other_compound_shape_index; + return 1; + } else { + return 0; + } } int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, int p_result_max, btVector3 &r_delta_recover_movement, PhysicsServer::SeparationResult *r_results) { - RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask()); + // Calculate the cumulative AABB of all shapes of the kinematic body + btVector3 aabb_min, aabb_max; + bool shapes_found = false; - btTransform body_shape_position; - btTransform body_shape_position_recovered; + for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) { - // Broad phase support - btVector3 minAabb, maxAabb; + const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]); + if (!kin_shape.is_active()) { + continue; + } + + if (kin_shape.shape->getShapeType() != CUSTOM_CONVEX_SHAPE_TYPE) { + continue; + } - int ray_index = 0; + btTransform shape_transform = p_body_position * kin_shape.transform; + shape_transform.getOrigin() += r_delta_recover_movement; - // For each shape - for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) { + btVector3 shape_aabb_min, shape_aabb_max; + kin_shape.shape->getAabb(shape_transform, shape_aabb_min, shape_aabb_max); + + if (!shapes_found) { + aabb_min = shape_aabb_min; + aabb_max = shape_aabb_max; + shapes_found = true; + } else { + aabb_min.setX((aabb_min.x() < shape_aabb_min.x()) ? aabb_min.x() : shape_aabb_min.x()); + aabb_min.setY((aabb_min.y() < shape_aabb_min.y()) ? aabb_min.y() : shape_aabb_min.y()); + aabb_min.setZ((aabb_min.z() < shape_aabb_min.z()) ? aabb_min.z() : shape_aabb_min.z()); + + aabb_max.setX((aabb_max.x() > shape_aabb_max.x()) ? aabb_max.x() : shape_aabb_max.x()); + aabb_max.setY((aabb_max.y() > shape_aabb_max.y()) ? aabb_max.y() : shape_aabb_max.y()); + aabb_max.setZ((aabb_max.z() > shape_aabb_max.z()) ? aabb_max.z() : shape_aabb_max.z()); + } + } - recover_broad_result.reset(); + // If there are no shapes then there is no penetration either + if (!shapes_found) { + return 0; + } + + // Perform broadphase test + RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max); + dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result); + + int ray_count = 0; + + // Perform narrowphase per shape + for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) { - if (ray_index >= p_result_max) { + if (ray_count >= p_result_max) { break; } @@ -1291,15 +1423,11 @@ int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btT continue; } - body_shape_position = p_body_position * kin_shape.transform; - body_shape_position_recovered = body_shape_position; - body_shape_position_recovered.getOrigin() += r_delta_recover_movement; + btTransform shape_transform = p_body_position * kin_shape.transform; + shape_transform.getOrigin() += r_delta_recover_movement; - kin_shape.shape->getAabb(body_shape_position_recovered, minAabb, maxAabb); - dynamicsWorld->getBroadphase()->aabbTest(minAabb, maxAabb, recover_broad_result); - - for (int i = recover_broad_result.result_collision_objects.size() - 1; 0 <= i; --i) { - btCollisionObject *otherObject = recover_broad_result.result_collision_objects[i]; + for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) { + btCollisionObject *otherObject = recover_broad_result.results[i].collision_object; if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) { otherObject->activate(); // Force activation of hitten rigid, soft body continue; @@ -1307,29 +1435,25 @@ int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btT continue; if (otherObject->getCollisionShape()->isCompound()) { + const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape()); + int shape_idx = recover_broad_result.results[i].compound_child_index; + ERR_FAIL_COND_V(shape_idx < 0 || shape_idx >= cs->getNumChildShapes(), false); - // Each convex shape - btCompoundShape *cs = static_cast<btCompoundShape *>(otherObject->getCollisionShape()); - for (int x = cs->getNumChildShapes() - 1; 0 <= x; --x) { - - RecoverResult recover_result; - if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(x), p_body->get_bt_collision_object(), otherObject, kinIndex, x, body_shape_position, otherObject->getWorldTransform() * cs->getChildTransform(x), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) { + RecoverResult recover_result; + if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) { - convert_to_separation_result(&r_results[ray_index], recover_result, kinIndex, otherObject); - } + ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject); } } else { RecoverResult recover_result; - if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, body_shape_position, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) { + if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) { - convert_to_separation_result(&r_results[ray_index], recover_result, kinIndex, otherObject); + ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject); } } } - - ++ray_index; } - return ray_index; + return ray_count; } diff --git a/modules/bullet/space_bullet.h b/modules/bullet/space_bullet.h index 7bf6a216b5..ecf8a2db9d 100644 --- a/modules/bullet/space_bullet.h +++ b/modules/bullet/space_bullet.h @@ -68,7 +68,8 @@ class btGjkEpaPenetrationDepthSolver; extern ContactAddedCallback gContactAddedCallback; class BulletPhysicsDirectSpaceState : public PhysicsDirectSpaceState { - GDCLASS(BulletPhysicsDirectSpaceState, PhysicsDirectSpaceState) + GDCLASS(BulletPhysicsDirectSpaceState, PhysicsDirectSpaceState); + private: SpaceBullet *space; @@ -207,12 +208,12 @@ private: bool recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = NULL); /// This is an API that recover a kinematic object from penetration /// This allow only Convex Convex test and it always use GJK algorithm, With this API we don't benefit of Bullet special accelerated functions - bool RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = NULL); + bool RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = NULL); /// This is an API that recover a kinematic object from penetration /// Using this we leave Bullet to select the best algorithm, For example GJK in case we have Convex Convex, or a Bullet accelerated algorithm bool RFP_convex_world_test(const btConvexShape *p_shapeA, const btCollisionShape *p_shapeB, btCollisionObject *p_objectA, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = NULL); - void convert_to_separation_result(PhysicsServer::SeparationResult *r_result, const SpaceBullet::RecoverResult &p_recover_result, int p_shape_id, const btCollisionObject *p_other_object) const; + int add_separation_result(PhysicsServer::SeparationResult *r_results, const SpaceBullet::RecoverResult &p_recover_result, int p_shape_id, const btCollisionObject *p_other_object) const; int recover_from_penetration_ray(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, int p_result_max, btVector3 &r_delta_recover_movement, PhysicsServer::SeparationResult *r_results); }; #endif diff --git a/modules/camera/SCsub b/modules/camera/SCsub new file mode 100644 index 0000000000..23f031f06e --- /dev/null +++ b/modules/camera/SCsub @@ -0,0 +1,22 @@ +#!/usr/bin/env python + +Import('env') +Import('env_modules') + +env_camera = env_modules.Clone() + +if env["platform"] == "iphone": + # (iOS) Build as separate static library + modules_sources = [] + env_camera.add_source_files(modules_sources, "register_types.cpp") + env_camera.add_source_files(modules_sources, "camera_ios.mm") + mod_lib = env_modules.add_library('#bin/libgodot_camera_module' + env['LIBSUFFIX'], modules_sources) + +elif env["platform"] == "windows": + env_camera.add_source_files(env.modules_sources, "register_types.cpp") + env_camera.add_source_files(env.modules_sources, "camera_win.cpp") + +elif env["platform"] == "osx": + env_camera.add_source_files(env.modules_sources, "register_types.cpp") + env_camera.add_source_files(env.modules_sources, "camera_osx.mm") + diff --git a/modules/camera/camera_ios.h b/modules/camera/camera_ios.h new file mode 100644 index 0000000000..ceabdba6a3 --- /dev/null +++ b/modules/camera/camera_ios.h @@ -0,0 +1,45 @@ +/*************************************************************************/ +/* camera_ios.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 CAMERAIOS_H +#define CAMERAIOS_H + +#include "servers/camera_server.h" + +class CameraIOS : public CameraServer { +private: +public: + CameraIOS(); + ~CameraIOS(); + + void update_feeds(); +}; + +#endif /* CAMERAIOS_H */
\ No newline at end of file diff --git a/modules/camera/camera_ios.mm b/modules/camera/camera_ios.mm new file mode 100644 index 0000000000..dcf09b28fd --- /dev/null +++ b/modules/camera/camera_ios.mm @@ -0,0 +1,436 @@ +/*************************************************************************/ +/* camera_ios.mm */ +/*************************************************************************/ +/* 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. */ +/*************************************************************************/ + +///@TODO this is a near duplicate of CameraOSX, we should find a way to combine those to minimize code duplication!!!! +// If you fix something here, make sure you fix it there as wel! + +#include "camera_ios.h" +#include "servers/camera/camera_feed.h" + +#import <AVFoundation/AVFoundation.h> +#import <UIKit/UIKit.h> + +////////////////////////////////////////////////////////////////////////// +// MyCaptureSession - This is a little helper class so we can capture our frames + +@interface MyCaptureSession : AVCaptureSession <AVCaptureVideoDataOutputSampleBufferDelegate> { + Ref<CameraFeed> feed; + size_t width[2]; + size_t height[2]; + PoolVector<uint8_t> img_data[2]; + + AVCaptureDeviceInput *input; + AVCaptureVideoDataOutput *output; +} + +@end + +@implementation MyCaptureSession + +- (id)initForFeed:(Ref<CameraFeed>)p_feed andDevice:(AVCaptureDevice *)p_device { + if (self = [super init]) { + NSError *error; + feed = p_feed; + width[0] = 0; + height[0] = 0; + width[1] = 0; + height[1] = 0; + + // prepare our device + [p_device lockForConfiguration:&error]; + + [p_device setFocusMode:AVCaptureFocusModeLocked]; + [p_device setExposureMode:AVCaptureExposureModeLocked]; + [p_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeLocked]; + + [p_device unlockForConfiguration]; + + [self beginConfiguration]; + + // setup our capture + self.sessionPreset = AVCaptureSessionPreset1280x720; + + input = [AVCaptureDeviceInput deviceInputWithDevice:p_device error:&error]; + if (!input) { + print_line("Couldn't get input device for camera"); + } else { + [self addInput:input]; + } + + output = [AVCaptureVideoDataOutput new]; + if (!output) { + print_line("Couldn't get output device for camera"); + } else { + NSDictionary *settings = @{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) }; + output.videoSettings = settings; + + // discard if the data output queue is blocked (as we process the still image) + [output setAlwaysDiscardsLateVideoFrames:YES]; + + // now set ourselves as the delegate to receive new frames. Note that we're doing this on the main thread at the moment, we may need to change this.. + [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()]; + + [self addOutput:output]; + } + + [self commitConfiguration]; + + // kick off our session.. + [self startRunning]; + }; + return self; +} + +- (void)cleanup { + // stop running + [self stopRunning]; + + // cleanup + [self beginConfiguration]; + + if (input) { + [self removeInput:input]; + // don't release this + input = nil; + } + + if (output) { + [self removeOutput:output]; + [output setSampleBufferDelegate:nil queue:NULL]; + [output release]; + output = nil; + } + + [self commitConfiguration]; +} + +- (void)dealloc { + // bye bye + [super dealloc]; +} + +- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { + // This gets called every time our camera has a new image for us to process. + // May need to investigate in a way to throttle this if we get more images then we're rendering frames.. + + // For now, version 1, we're just doing the bare minimum to make this work... + + CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); + // int width = CVPixelBufferGetWidth(pixelBuffer); + // int height = CVPixelBufferGetHeight(pixelBuffer); + + // It says that we need to lock this on the documentation pages but it's not in the samples + // need to lock our base address so we can access our pixel buffers, better safe then sorry? + CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); + + // get our buffers + unsigned char *dataY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0); + unsigned char *dataCbCr = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1); + if (dataY == NULL) { + print_line("Couldn't access Y pixel buffer data"); + } else if (dataCbCr == NULL) { + print_line("Couldn't access CbCr pixel buffer data"); + } else { + UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; + Ref<Image> img[2]; + + { + // do Y + int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0); + int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0); + int _bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0); + + if ((width[0] != new_width) || (height[0] != new_height)) { + // printf("Camera Y plane %i, %i - %i\n", new_width, new_height, bytes_per_row); + + width[0] = new_width; + height[0] = new_height; + img_data[0].resize(new_width * new_height); + } + + PoolVector<uint8_t>::Write w = img_data[0].write(); + memcpy(w.ptr(), dataY, new_width * new_height); + + img[0].instance(); + img[0]->create(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]); + } + + { + // do CbCr + int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1); + int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1); + int bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 1); + + if ((width[1] != new_width) || (height[1] != new_height)) { + // printf("Camera CbCr plane %i, %i - %i\n", new_width, new_height, bytes_per_row); + + width[1] = new_width; + height[1] = new_height; + img_data[1].resize(2 * new_width * new_height); + } + + PoolVector<uint8_t>::Write w = img_data[1].write(); + memcpy(w.ptr(), dataCbCr, 2 * new_width * new_height); + + ///TODO GLES2 doesn't support FORMAT_RG8, need to do some form of conversion + img[1].instance(); + img[1]->create(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]); + } + + // set our texture... + feed->set_YCbCr_imgs(img[0], img[1]); + + // update our matrix to match the orientation, note, before changing anything + // here, be aware that the project orientation settings must match your xcode + // settings or this will go wrong! + Transform2D display_transform; + switch (orientation) { + case UIInterfaceOrientationPortrait: { + display_transform = Transform2D(0.0, -1.0, -1.0, 0.0, 1.0, 1.0); + } break; + case UIInterfaceOrientationLandscapeRight: { + display_transform = Transform2D(1.0, 0.0, 0.0, -1.0, 0.0, 1.0); + } break; + case UIInterfaceOrientationLandscapeLeft: { + display_transform = Transform2D(-1.0, 0.0, 0.0, 1.0, 1.0, 0.0); + } break; + default: { + display_transform = Transform2D(0.0, 1.0, 1.0, 0.0, 0.0, 0.0); + } break; + } + + //TODO: this is correct for the camera on the back, I have a feeling this needs to be inversed for the camera on the front! + feed->set_transform(display_transform); + } + + // and unlock + CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); +} + +@end + +////////////////////////////////////////////////////////////////////////// +// CameraFeedIOS - Subclass for camera feeds in iOS + +class CameraFeedIOS : public CameraFeed { +private: + AVCaptureDevice *device; + MyCaptureSession *capture_session; + +public: + bool get_is_arkit() const; + AVCaptureDevice *get_device() const; + + CameraFeedIOS(); + ~CameraFeedIOS(); + + void set_device(AVCaptureDevice *p_device); + + bool activate_feed(); + void deactivate_feed(); +}; + +AVCaptureDevice *CameraFeedIOS::get_device() const { + return device; +}; + +CameraFeedIOS::CameraFeedIOS() { + capture_session = NULL; + device = NULL; + transform = Transform2D(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); /* should re-orientate this based on device orientation */ +}; + +void CameraFeedIOS::set_device(AVCaptureDevice *p_device) { + device = p_device; + [device retain]; + + // get some info + NSString *device_name = p_device.localizedName; + name = device_name.UTF8String; + position = CameraFeed::FEED_UNSPECIFIED; + if ([p_device position] == AVCaptureDevicePositionBack) { + position = CameraFeed::FEED_BACK; + } else if ([p_device position] == AVCaptureDevicePositionFront) { + position = CameraFeed::FEED_FRONT; + }; +}; + +CameraFeedIOS::~CameraFeedIOS() { + if (capture_session != NULL) { + [capture_session release]; + capture_session = NULL; + }; + + if (device != NULL) { + [device release]; + device = NULL; + }; +}; + +bool CameraFeedIOS::activate_feed() { + if (capture_session) { + // already recording! + } else { + // start camera capture + capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device]; + }; + + return true; +}; + +void CameraFeedIOS::deactivate_feed() { + // end camera capture if we have one + if (capture_session) { + [capture_session cleanup]; + [capture_session release]; + capture_session = NULL; + }; +}; + +////////////////////////////////////////////////////////////////////////// +// MyDeviceNotifications - This is a little helper class gets notifications +// when devices are connected/disconnected + +@interface MyDeviceNotifications : NSObject { + CameraIOS *camera_server; +} + +@end + +@implementation MyDeviceNotifications + +- (void)devices_changed:(NSNotification *)notification { + camera_server->update_feeds(); +} + +- (id)initForServer:(CameraIOS *)p_server { + if (self = [super init]) { + camera_server = p_server; + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasConnectedNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasDisconnectedNotification object:nil]; + }; + return self; +} + +- (void)dealloc { + // remove notifications + [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasConnectedNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasDisconnectedNotification object:nil]; + + [super dealloc]; +} + +@end + +MyDeviceNotifications *device_notifications = nil; + +////////////////////////////////////////////////////////////////////////// +// CameraIOS - Subclass for our camera server on iPhone + +void CameraIOS::update_feeds() { + // this way of doing things is deprecated but still works, + // rewrite to using AVCaptureDeviceDiscoverySession + + AVCaptureDeviceDiscoverySession *session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:[NSArray arrayWithObjects:AVCaptureDeviceTypeBuiltInTelephotoCamera, AVCaptureDeviceTypeBuiltInDualCamera, AVCaptureDeviceTypeBuiltInTrueDepthCamera, AVCaptureDeviceTypeBuiltInWideAngleCamera, nil] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified]; + + // remove devices that are gone.. + for (int i = feeds.size() - 1; i >= 0; i--) { + Ref<CameraFeedIOS> feed(feeds[i]); + + if (feed.is_null()) { + // feed not managed by us + } else if (![session.devices containsObject:feed->get_device()]) { + // remove it from our array, this will also destroy it ;) + remove_feed(feed); + }; + }; + + // add new devices.. + for (AVCaptureDevice *device in session.devices) { + bool found = false; + + for (int i = 0; i < feeds.size() && !found; i++) { + Ref<CameraFeedIOS> feed(feeds[i]); + + if (feed.is_null()) { + // feed not managed by us + } else if (feed->get_device() == device) { + found = true; + }; + }; + + if (!found) { + Ref<CameraFeedIOS> newfeed; + newfeed.instance(); + newfeed->set_device(device); + add_feed(newfeed); + }; + }; +}; + +CameraIOS::CameraIOS() { + // check if we have our usage description + NSString *usage_desc = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSCameraUsageDescription"]; + if (usage_desc == NULL) { + // don't initialise if we don't get anything + print_line("No NSCameraUsageDescription key in pList, no access to cameras."); + return; + } else if (usage_desc.length == 0) { + // don't initialise if we don't get anything + print_line("Empty NSCameraUsageDescription key in pList, no access to cameras."); + return; + } + + // now we'll request access. + // If this is the first time the user will be prompted with the string (iOS will read it). + // Once a decision is made it is returned. If the user wants to change it later on they + // need to go into setting. + print_line("Requesting Camera permissions"); + + [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo + completionHandler:^(BOOL granted) { + if (granted) { + print_line("Access to cameras granted!"); + + // Find available cameras we have at this time + update_feeds(); + + // should only have one of these.... + device_notifications = [[MyDeviceNotifications alloc] initForServer:this]; + } else { + print_line("No access to cameras!"); + } + }]; +}; + +CameraIOS::~CameraIOS() { + [device_notifications release]; +}; diff --git a/modules/mono/editor/monodevelop_instance.h b/modules/camera/camera_osx.h index 3b3af9607b..7477d8e647 100644 --- a/modules/mono/editor/monodevelop_instance.h +++ b/modules/camera/camera_osx.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* monodevelop_instance.h */ +/* camera_osx.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,29 +28,20 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef MONODEVELOP_INSTANCE_H -#define MONODEVELOP_INSTANCE_H +#ifndef CAMERAOSX_H +#define CAMERAOSX_H -#include "core/reference.h" +///@TODO this is a near duplicate of CameraIOS, we should find a way to combine those to minimize code duplication!!!! +// If you fix something here, make sure you fix it there as wel! -#include "../mono_gc_handle.h" -#include "../mono_gd/gd_mono_method.h" - -class MonoDevelopInstance { - - Ref<MonoGCHandle> gc_handle; - GDMonoMethod *execute_method; +#include "servers/camera_server.h" +class CameraOSX : public CameraServer { public: - enum EditorId { - MONODEVELOP = 0, - VISUALSTUDIO_FOR_MAC = 1 - }; - - void execute(const Vector<String> &p_files); - void execute(const String &p_file); + CameraOSX(); + ~CameraOSX(); - MonoDevelopInstance(const String &p_solution, EditorId p_editor_id); + void update_feeds(); }; -#endif // MONODEVELOP_INSTANCE_H +#endif /* CAMERAOSX_H */ diff --git a/modules/camera/camera_osx.mm b/modules/camera/camera_osx.mm new file mode 100644 index 0000000000..2b0f4906fc --- /dev/null +++ b/modules/camera/camera_osx.mm @@ -0,0 +1,362 @@ +/*************************************************************************/ +/* camera_osx.mm */ +/*************************************************************************/ +/* 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. */ +/*************************************************************************/ + +///@TODO this is a near duplicate of CameraIOS, we should find a way to combine those to minimize code duplication!!!! +// If you fix something here, make sure you fix it there as wel! + +#include "camera_osx.h" +#include "servers/camera/camera_feed.h" +#import <AVFoundation/AVFoundation.h> + +////////////////////////////////////////////////////////////////////////// +// MyCaptureSession - This is a little helper class so we can capture our frames + +@interface MyCaptureSession : AVCaptureSession <AVCaptureVideoDataOutputSampleBufferDelegate> { + Ref<CameraFeed> feed; + size_t width[2]; + size_t height[2]; + PoolVector<uint8_t> img_data[2]; + + AVCaptureDeviceInput *input; + AVCaptureVideoDataOutput *output; +} + +@end + +@implementation MyCaptureSession + +- (id)initForFeed:(Ref<CameraFeed>)p_feed andDevice:(AVCaptureDevice *)p_device { + if (self = [super init]) { + NSError *error; + feed = p_feed; + width[0] = 0; + height[0] = 0; + width[1] = 0; + height[1] = 0; + + [self beginConfiguration]; + + input = [AVCaptureDeviceInput deviceInputWithDevice:p_device error:&error]; + if (!input) { + print_line("Couldn't get input device for camera"); + } else { + [self addInput:input]; + } + + output = [AVCaptureVideoDataOutput new]; + if (!output) { + print_line("Couldn't get output device for camera"); + } else { + NSDictionary *settings = @{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) }; + output.videoSettings = settings; + + // discard if the data output queue is blocked (as we process the still image) + [output setAlwaysDiscardsLateVideoFrames:YES]; + + // now set ourselves as the delegate to receive new frames. + [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()]; + + // this takes ownership + [self addOutput:output]; + } + + [self commitConfiguration]; + + // kick off our session.. + [self startRunning]; + }; + return self; +} + +- (void)cleanup { + // stop running + [self stopRunning]; + + // cleanup + [self beginConfiguration]; + + // remove input + if (input) { + [self removeInput:input]; + // don't release this + input = NULL; + } + + // free up our output + if (output) { + [self removeOutput:output]; + [output setSampleBufferDelegate:nil queue:NULL]; + [output release]; + output = NULL; + } + + [self commitConfiguration]; +} + +- (void)dealloc { + // bye bye + [super dealloc]; +} + +- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { + // This gets called every time our camera has a new image for us to process. + // May need to investigate in a way to throttle this if we get more images then we're rendering frames.. + + // For now, version 1, we're just doing the bare minimum to make this work... + CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); + // int _width = CVPixelBufferGetWidth(pixelBuffer); + // int _height = CVPixelBufferGetHeight(pixelBuffer); + + // It says that we need to lock this on the documentation pages but it's not in the samples + // need to lock our base address so we can access our pixel buffers, better safe then sorry? + CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); + + // get our buffers + unsigned char *dataY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0); + unsigned char *dataCbCr = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1); + if (dataY == NULL) { + print_line("Couldn't access Y pixel buffer data"); + } else if (dataCbCr == NULL) { + print_line("Couldn't access CbCr pixel buffer data"); + } else { + Ref<Image> img[2]; + + { + // do Y + size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0); + size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0); + + if ((width[0] != new_width) || (height[0] != new_height)) { + width[0] = new_width; + height[0] = new_height; + img_data[0].resize(new_width * new_height); + } + + PoolVector<uint8_t>::Write w = img_data[0].write(); + memcpy(w.ptr(), dataY, new_width * new_height); + + img[0].instance(); + img[0]->create(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]); + } + + { + // do CbCr + size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1); + size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1); + + if ((width[1] != new_width) || (height[1] != new_height)) { + width[1] = new_width; + height[1] = new_height; + img_data[1].resize(2 * new_width * new_height); + } + + PoolVector<uint8_t>::Write w = img_data[1].write(); + memcpy(w.ptr(), dataCbCr, 2 * new_width * new_height); + + ///TODO GLES2 doesn't support FORMAT_RG8, need to do some form of conversion + img[1].instance(); + img[1]->create(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]); + } + + // set our texture... + feed->set_YCbCr_imgs(img[0], img[1]); + } + + // and unlock + CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); +} + +@end + +////////////////////////////////////////////////////////////////////////// +// CameraFeedOSX - Subclass for camera feeds in OSX + +class CameraFeedOSX : public CameraFeed { +private: + AVCaptureDevice *device; + MyCaptureSession *capture_session; + +public: + AVCaptureDevice *get_device() const; + + CameraFeedOSX(); + ~CameraFeedOSX(); + + void set_device(AVCaptureDevice *p_device); + + bool activate_feed(); + void deactivate_feed(); +}; + +AVCaptureDevice *CameraFeedOSX::get_device() const { + return device; +}; + +CameraFeedOSX::CameraFeedOSX() { + device = NULL; + capture_session = NULL; +}; + +void CameraFeedOSX::set_device(AVCaptureDevice *p_device) { + device = p_device; + [device retain]; + + // get some info + NSString *device_name = p_device.localizedName; + name = device_name.UTF8String; + position = CameraFeed::FEED_UNSPECIFIED; + if ([p_device position] == AVCaptureDevicePositionBack) { + position = CameraFeed::FEED_BACK; + } else if ([p_device position] == AVCaptureDevicePositionFront) { + position = CameraFeed::FEED_FRONT; + }; +}; + +CameraFeedOSX::~CameraFeedOSX() { + if (capture_session != NULL) { + [capture_session release]; + capture_session = NULL; + }; + + if (device != NULL) { + [device release]; + device = NULL; + }; +}; + +bool CameraFeedOSX::activate_feed() { + if (capture_session) { + // already recording! + } else { + // start camera capture + capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device]; + }; + + return true; +}; + +void CameraFeedOSX::deactivate_feed() { + // end camera capture if we have one + if (capture_session) { + [capture_session cleanup]; + [capture_session release]; + capture_session = NULL; + }; +}; + +////////////////////////////////////////////////////////////////////////// +// MyDeviceNotifications - This is a little helper class gets notifications +// when devices are connected/disconnected + +@interface MyDeviceNotifications : NSObject { + CameraOSX *camera_server; +} + +@end + +@implementation MyDeviceNotifications + +- (void)devices_changed:(NSNotification *)notification { + camera_server->update_feeds(); +} + +- (id)initForServer:(CameraOSX *)p_server { + if (self = [super init]) { + camera_server = p_server; + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasConnectedNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasDisconnectedNotification object:nil]; + }; + return self; +} + +- (void)dealloc { + // remove notifications + [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasConnectedNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasDisconnectedNotification object:nil]; + + [super dealloc]; +} + +@end + +MyDeviceNotifications *device_notifications = nil; + +////////////////////////////////////////////////////////////////////////// +// CameraOSX - Subclass for our camera server on OSX + +void CameraOSX::update_feeds() { + NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; + + // remove devices that are gone.. + for (int i = feeds.size() - 1; i >= 0; i--) { + Ref<CameraFeedOSX> feed = (Ref<CameraFeedOSX>)feeds[i]; + + if (![devices containsObject:feed->get_device()]) { + // remove it from our array, this will also destroy it ;) + remove_feed(feed); + }; + }; + + // add new devices.. + for (AVCaptureDevice *device in devices) { + bool found = false; + for (int i = 0; i < feeds.size() && !found; i++) { + Ref<CameraFeedOSX> feed = (Ref<CameraFeedOSX>)feeds[i]; + if (feed->get_device() == device) { + found = true; + }; + }; + + if (!found) { + Ref<CameraFeedOSX> newfeed; + newfeed.instance(); + newfeed->set_device(device); + + // assume display camera so inverse + Transform2D transform = Transform2D(-1.0, 0.0, 0.0, -1.0, 1.0, 1.0); + newfeed->set_transform(transform); + + add_feed(newfeed); + }; + }; +}; + +CameraOSX::CameraOSX() { + // Find available cameras we have at this time + update_feeds(); + + // should only have one of these.... + device_notifications = [[MyDeviceNotifications alloc] initForServer:this]; +}; + +CameraOSX::~CameraOSX() { + [device_notifications release]; +}; diff --git a/modules/camera/camera_win.cpp b/modules/camera/camera_win.cpp new file mode 100644 index 0000000000..10787d0d0a --- /dev/null +++ b/modules/camera/camera_win.cpp @@ -0,0 +1,98 @@ +/*************************************************************************/ +/* camera_win.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 "camera_win.h" + +///@TODO sorry guys, I got about 80% through implementing this using DirectShow only +// to find out Microsoft deprecated half the API and its replacement is as confusing +// as they could make it. Joey suggested looking into libuvc which offers a more direct +// route to webcams over USB and this is very promising but it wouldn't compile on +// windows for me...I've gutted the classes I implemented DirectShow in just to have +// a skeleton for someone to work on, mail me for more details or if you want a copy.... + +////////////////////////////////////////////////////////////////////////// +// CameraFeedWindows - Subclass for our camera feed on windows + +/// @TODO need to implement this + +class CameraFeedWindows : public CameraFeed { +private: +protected: +public: + CameraFeedWindows(); + virtual ~CameraFeedWindows(); + + bool activate_feed(); + void deactivate_feed(); +}; + +CameraFeedWindows::CameraFeedWindows(){ + ///@TODO implement this, should store information about our available camera +}; + +CameraFeedWindows::~CameraFeedWindows() { + // make sure we stop recording if we are! + if (is_active()) { + deactivate_feed(); + }; + + ///@TODO free up anything used by this +}; + +bool CameraFeedWindows::activate_feed() { + ///@TODO this should activate our camera and start the process of capturing frames + + return true; +}; + +///@TODO we should probably have a callback method here that is being called by the +// camera API which provides frames and call back into the CameraServer to update our texture + +void CameraFeedWindows::deactivate_feed(){ + ///@TODO this should deactivate our camera and stop the process of capturing frames +}; + +////////////////////////////////////////////////////////////////////////// +// CameraWindows - Subclass for our camera server on windows + +void CameraWindows::add_active_cameras(){ + ///@TODO scan through any active cameras and create CameraFeedWindows objects for them +}; + +CameraWindows::CameraWindows() { + // Find cameras active right now + add_active_cameras(); + + // need to add something that will react to devices being connected/removed... +}; + +CameraWindows::~CameraWindows(){ + +}; diff --git a/modules/camera/camera_win.h b/modules/camera/camera_win.h new file mode 100644 index 0000000000..22ce9aa43f --- /dev/null +++ b/modules/camera/camera_win.h @@ -0,0 +1,46 @@ +/*************************************************************************/ +/* camera_win.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 CAMERAWIN_H +#define CAMERAWIN_H + +#include "servers/camera/camera_feed.h" +#include "servers/camera_server.h" + +class CameraWindows : public CameraServer { +private: + void add_active_cameras(); + +public: + CameraWindows(); + ~CameraWindows(); +}; + +#endif /* CAMERAWIN_H */ diff --git a/modules/camera/config.py b/modules/camera/config.py new file mode 100644 index 0000000000..d308c04195 --- /dev/null +++ b/modules/camera/config.py @@ -0,0 +1,5 @@ +def can_build(env, platform): + return platform == 'iphone' or platform == 'osx' or platform == 'windows' + +def configure(env): + pass diff --git a/modules/camera/register_types.cpp b/modules/camera/register_types.cpp new file mode 100644 index 0000000000..313df40112 --- /dev/null +++ b/modules/camera/register_types.cpp @@ -0,0 +1,56 @@ +/*************************************************************************/ +/* register_types.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 "register_types.h" + +#if defined(WINDOWS_ENABLED) +#include "camera_win.h" +#endif +#if defined(IPHONE_ENABLED) +#include "camera_ios.h" +#endif +#if defined(OSX_ENABLED) +#include "camera_osx.h" +#endif + +void register_camera_types() { +#if defined(WINDOWS_ENABLED) + CameraServer::make_default<CameraWindows>(); +#endif +#if defined(IPHONE_ENABLED) + CameraServer::make_default<CameraIOS>(); +#endif +#if defined(OSX_ENABLED) + CameraServer::make_default<CameraOSX>(); +#endif +} + +void unregister_camera_types() { +} diff --git a/modules/camera/register_types.h b/modules/camera/register_types.h new file mode 100644 index 0000000000..0ccb0885d0 --- /dev/null +++ b/modules/camera/register_types.h @@ -0,0 +1,32 @@ +/*************************************************************************/ +/* register_types.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. */ +/*************************************************************************/ + +void register_camera_types(); +void unregister_camera_types(); diff --git a/modules/csg/csg.cpp b/modules/csg/csg.cpp index 0eb539b182..925fff0cc8 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(); @@ -114,7 +114,7 @@ void CSGBrush::_regen_face_aabbs() { faces.write[i].aabb.position = faces[i].vertices[0]; faces.write[i].aabb.expand_to(faces[i].vertices[1]); faces.write[i].aabb.expand_to(faces[i].vertices[2]); - faces.write[i].aabb.grow_by(faces[i].aabb.get_longest_axis_size() * 0.001); //make it a tad bigger to avoid num precision erros + faces.write[i].aabb.grow_by(faces[i].aabb.get_longest_axis_size() * 0.001); //make it a tad bigger to avoid num precision errors } } @@ -242,7 +242,7 @@ void CSGBrushOperation::BuildPoly::_clip_segment(const CSGBrush *p_brush, int p_ //check if edge and poly share a vertex, of so, assign it to segment_idx for (int i = 0; i < points.size(); i++) { for (int j = 0; j < 2; j++) { - if (segment[j].distance_to(points[i].point) < CMP_EPSILON) { + if (segment[j].is_equal_approx(points[i].point)) { segment_idx[j] = i; inserted_points.push_back(i); break; @@ -310,7 +310,7 @@ void CSGBrushOperation::BuildPoly::_clip_segment(const CSGBrush *p_brush, int p_ Vector2 edgeseg[2] = { points[edges[i].points[0]].point, points[edges[i].points[1]].point }; Vector2 closest = Geometry::get_closest_point_to_segment_2d(segment[j], edgeseg); - if (closest.distance_to(segment[j]) < CMP_EPSILON) { + if (closest.is_equal_approx(segment[j])) { //point rest of this edge res = closest; found = true; @@ -439,7 +439,7 @@ void CSGBrushOperation::BuildPoly::clip(const CSGBrush *p_brush, int p_face, Mes //transform A points to 2D - if (segment[0].distance_to(segment[1]) < CMP_EPSILON) + if (segment[0].is_equal_approx(segment[1])) return; //too small _clip_segment(p_brush, p_face, segment, mesh_merge, p_for_B); @@ -461,10 +461,10 @@ void CSGBrushOperation::_collision_callback(const CSGBrush *A, int p_face_a, Map { //check if either is a degenerate - if (va[0].distance_to(va[1]) < CMP_EPSILON || va[0].distance_to(va[2]) < CMP_EPSILON || va[1].distance_to(va[2]) < CMP_EPSILON) + if (va[0].is_equal_approx(va[1]) || va[0].is_equal_approx(va[2]) || va[1].is_equal_approx(va[2])) return; - if (vb[0].distance_to(vb[1]) < CMP_EPSILON || vb[0].distance_to(vb[2]) < CMP_EPSILON || vb[1].distance_to(vb[2]) < CMP_EPSILON) + if (vb[0].is_equal_approx(vb[1]) || vb[0].is_equal_approx(vb[2]) || vb[1].is_equal_approx(vb[2])) return; } @@ -611,7 +611,7 @@ void CSGBrushOperation::_add_poly_points(const BuildPoly &p_poly, int p_edge, in { EdgeSort es; - es.angle = 0; //wont be checked here + es.angle = 0; //won't be checked here es.edge = p_edge; es.prev_point = p_from_point; es.edge_point = p_to_point; @@ -1018,15 +1018,15 @@ int CSGBrushOperation::MeshMerge::_create_bvh(BVH *p_bvh, BVH **p_bb, int p_from max_depth = p_depth; } - if (p_size <= BVH_LIMIT) { + if (p_size == 0) { + + return -1; + } else if (p_size <= BVH_LIMIT) { for (int i = 0; i < p_size - 1; i++) { p_bb[p_from + i]->next = p_bb[p_from + i + 1] - p_bvh; } return p_bb[p_from] - p_bvh; - } else if (p_size == 0) { - - return -1; } AABB aabb; diff --git a/modules/csg/csg_gizmos.cpp b/modules/csg/csg_gizmos.cpp index d4069b901f..0d26943af6 100644 --- a/modules/csg/csg_gizmos.cpp +++ b/modules/csg/csg_gizmos.cpp @@ -34,8 +34,18 @@ CSGShapeSpatialGizmoPlugin::CSGShapeSpatialGizmoPlugin() { - Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/csg", Color(0.2, 0.5, 1, 0.1)); - create_material("shape_material", gizmo_color); + Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/csg", Color(0.0, 0.4, 1, 0.15)); + create_material("shape_union_material", gizmo_color); + create_material("shape_union_solid_material", gizmo_color); + gizmo_color.invert(); + create_material("shape_subtraction_material", gizmo_color); + create_material("shape_subtraction_solid_material", gizmo_color); + gizmo_color.r = 0.95; + gizmo_color.g = 0.95; + gizmo_color.b = 0.95; + create_material("shape_intersection_material", gizmo_color); + create_material("shape_intersection_solid_material", gizmo_color); + create_handle_material("handles"); } @@ -120,6 +130,10 @@ void CSGShapeSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_i Vector3 ra, rb; Geometry::get_closest_points_between_segments(Vector3(), Vector3(4096, 0, 0), sg[0], sg[1], ra, rb); float d = ra.x; + if (SpatialEditor::get_singleton()->is_snap_enabled()) { + d = Math::stepify(d, SpatialEditor::get_singleton()->get_translate_snap()); + } + if (d < 0.001) d = 0.001; @@ -135,6 +149,10 @@ void CSGShapeSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_i Vector3 ra, rb; Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb); float d = ra[p_idx]; + if (SpatialEditor::get_singleton()->is_snap_enabled()) { + d = Math::stepify(d, SpatialEditor::get_singleton()->get_translate_snap()); + } + if (d < 0.001) d = 0.001; @@ -154,6 +172,9 @@ void CSGShapeSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_i Vector3 ra, rb; Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb); float d = axis.dot(ra); + if (SpatialEditor::get_singleton()->is_snap_enabled()) { + d = Math::stepify(d, SpatialEditor::get_singleton()->get_translate_snap()); + } if (d < 0.001) d = 0.001; @@ -173,6 +194,9 @@ void CSGShapeSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_i Vector3 ra, rb; Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb); float d = axis.dot(ra); + if (SpatialEditor::get_singleton()->is_snap_enabled()) { + d = Math::stepify(d, SpatialEditor::get_singleton()->get_translate_snap()); + } if (d < 0.001) d = 0.001; @@ -297,7 +321,19 @@ void CSGShapeSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) { p_gizmo->clear(); - Ref<Material> material = get_material("shape_material", p_gizmo); + Ref<Material> material; + switch (cs->get_operation()) { + case CSGShape::OPERATION_UNION: + material = get_material("shape_union_material", p_gizmo); + break; + case CSGShape::OPERATION_INTERSECTION: + material = get_material("shape_intersection_material", p_gizmo); + break; + case CSGShape::OPERATION_SUBTRACTION: + material = get_material("shape_subtraction_material", p_gizmo); + break; + } + Ref<Material> handles_material = get_material("handles"); PoolVector<Vector3> faces = cs->get_brush_faces(); @@ -320,6 +356,30 @@ void CSGShapeSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) { p_gizmo->add_lines(lines, material); p_gizmo->add_collision_segments(lines); + if (p_gizmo->is_selected()) { + // Draw a translucent representation of the CSG node + Ref<ArrayMesh> mesh = memnew(ArrayMesh); + Array array; + array.resize(Mesh::ARRAY_MAX); + array[Mesh::ARRAY_VERTEX] = faces; + mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, array); + + Ref<Material> solid_material; + switch (cs->get_operation()) { + case CSGShape::OPERATION_UNION: + solid_material = get_material("shape_union_solid_material", p_gizmo); + break; + case CSGShape::OPERATION_INTERSECTION: + solid_material = get_material("shape_intersection_solid_material", p_gizmo); + break; + case CSGShape::OPERATION_SUBTRACTION: + solid_material = get_material("shape_subtraction_solid_material", p_gizmo); + break; + } + + p_gizmo->add_mesh(mesh, false, Ref<SkinReference>(), solid_material); + } + if (Object::cast_to<CSGSphere>(cs)) { CSGSphere *s = Object::cast_to<CSGSphere>(cs); diff --git a/modules/csg/csg_gizmos.h b/modules/csg/csg_gizmos.h index 0915d05111..d38dafc936 100644 --- a/modules/csg/csg_gizmos.h +++ b/modules/csg/csg_gizmos.h @@ -55,7 +55,8 @@ public: }; class EditorPluginCSG : public EditorPlugin { - GDCLASS(EditorPluginCSG, EditorPlugin) + GDCLASS(EditorPluginCSG, EditorPlugin); + public: EditorPluginCSG(EditorNode *p_editor); }; diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp index 775ec67ba6..9409b33f24 100644 --- a/modules/csg/csg_shape.cpp +++ b/modules/csg/csg_shape.cpp @@ -282,7 +282,7 @@ void CSGShape::_update_shape() { root_mesh.unref(); //byebye root mesh CSGBrush *n = _get_brush(); - ERR_FAIL_COND(!n); + ERR_FAIL_COND_MSG(!n, "Cannot get CSGBrush."); OAHashMap<Vector3, Vector3> vec_map; @@ -436,10 +436,10 @@ void CSGShape::_update_shape() { } // unset write access - surfaces.write[i].verticesw = PoolVector<Vector3>::Write(); - surfaces.write[i].normalsw = PoolVector<Vector3>::Write(); - surfaces.write[i].uvsw = PoolVector<Vector2>::Write(); - surfaces.write[i].tansw = PoolVector<float>::Write(); + surfaces.write[i].verticesw.release(); + surfaces.write[i].normalsw.release(); + surfaces.write[i].uvsw.release(); + surfaces.write[i].tansw.release(); if (surfaces[i].last_added == 0) continue; @@ -557,6 +557,7 @@ void CSGShape::set_operation(Operation p_operation) { operation = p_operation; _make_dirty(); + update_gizmo(); } CSGShape::Operation CSGShape::get_operation() const { @@ -724,6 +725,7 @@ CSGBrush *CSGMesh::_build_brush() { PoolVector<bool> smooth; PoolVector<Ref<Material> > materials; PoolVector<Vector2> uvs; + Ref<Material> material = get_material(); for (int i = 0; i < mesh->get_surface_count(); i++) { @@ -760,7 +762,12 @@ CSGBrush *CSGMesh::_build_brush() { uvr_used = true; } - Ref<Material> mat = mesh->surface_get_material(i); + Ref<Material> mat; + if (material.is_valid()) { + mat = material; + } else { + mat = mesh->surface_get_material(i); + } PoolVector<int> aindices = arrays[Mesh::ARRAY_INDEX]; if (aindices.size()) { @@ -866,6 +873,18 @@ void CSGMesh::_mesh_changed() { update_gizmo(); } +void CSGMesh::set_material(const Ref<Material> &p_material) { + if (material == p_material) + return; + material = p_material; + _make_dirty(); +} + +Ref<Material> CSGMesh::get_material() const { + + return material; +} + void CSGMesh::_bind_methods() { ClassDB::bind_method(D_METHOD("set_mesh", "mesh"), &CSGMesh::set_mesh); @@ -873,7 +892,11 @@ void CSGMesh::_bind_methods() { ClassDB::bind_method(D_METHOD("_mesh_changed"), &CSGMesh::_mesh_changed); + ClassDB::bind_method(D_METHOD("set_material", "material"), &CSGMesh::set_material); + ClassDB::bind_method(D_METHOD("get_material"), &CSGMesh::get_material); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "SpatialMaterial,ShaderMaterial"), "set_material", "get_material"); } void CSGMesh::set_mesh(const Ref<Mesh> &p_mesh) { @@ -1044,6 +1067,7 @@ void CSGSphere::set_radius(const float p_radius) { radius = p_radius; _make_dirty(); update_gizmo(); + _change_notify("radius"); } float CSGSphere::get_radius() const { @@ -1228,6 +1252,7 @@ void CSGBox::set_width(const float p_width) { width = p_width; _make_dirty(); update_gizmo(); + _change_notify("width"); } float CSGBox::get_width() const { @@ -1238,6 +1263,7 @@ void CSGBox::set_height(const float p_height) { height = p_height; _make_dirty(); update_gizmo(); + _change_notify("height"); } float CSGBox::get_height() const { @@ -1248,6 +1274,7 @@ void CSGBox::set_depth(const float p_depth) { depth = p_depth; _make_dirty(); update_gizmo(); + _change_notify("depth"); } float CSGBox::get_depth() const { @@ -1442,6 +1469,7 @@ void CSGCylinder::set_radius(const float p_radius) { radius = p_radius; _make_dirty(); update_gizmo(); + _change_notify("radius"); } float CSGCylinder::get_radius() const { @@ -1452,6 +1480,7 @@ void CSGCylinder::set_height(const float p_height) { height = p_height; _make_dirty(); update_gizmo(); + _change_notify("height"); } float CSGCylinder::get_height() const { @@ -1667,6 +1696,7 @@ void CSGTorus::set_inner_radius(const float p_inner_radius) { inner_radius = p_inner_radius; _make_dirty(); update_gizmo(); + _change_notify("inner_radius"); } float CSGTorus::get_inner_radius() const { @@ -1677,6 +1707,7 @@ void CSGTorus::set_outer_radius(const float p_outer_radius) { outer_radius = p_outer_radius; _make_dirty(); update_gizmo(); + _change_notify("outer_radius"); } float CSGTorus::get_outer_radius() const { @@ -1794,11 +1825,9 @@ CSGBrush *CSGPolygon::_build_brush() { path_cache = path; - if (path_cache) { - path_cache->connect("tree_exited", this, "_path_exited"); - path_cache->connect("curve_changed", this, "_path_changed"); - path_cache = NULL; - } + path_cache->connect("tree_exited", this, "_path_exited"); + path_cache->connect("curve_changed", this, "_path_changed"); + path_cache = NULL; } curve = path->get_curve(); if (curve.is_null()) @@ -2060,6 +2089,9 @@ CSGBrush *CSGPolygon::_build_brush() { for (int i = 0; i <= splits; i++) { float ofs = i * path_interval; + if (ofs > bl) { + ofs = bl; + } if (i == splits && path_joined) { ofs = 0.0; } @@ -2383,7 +2415,7 @@ NodePath CSGPolygon::get_path_node() const { } void CSGPolygon::set_path_interval(float p_interval) { - ERR_FAIL_COND(p_interval < 0.001); + ERR_FAIL_COND_MSG(p_interval < 0.001, "Path interval cannot be smaller than 0.001."); path_interval = p_interval; _make_dirty(); update_gizmo(); diff --git a/modules/csg/csg_shape.h b/modules/csg/csg_shape.h index 1622fb3a15..6c9419b3c2 100644 --- a/modules/csg/csg_shape.h +++ b/modules/csg/csg_shape.h @@ -38,8 +38,8 @@ #include "scene/resources/concave_polygon_shape.h" #include "thirdparty/misc/mikktspace.h" -class CSGShape : public VisualInstance { - GDCLASS(CSGShape, VisualInstance); +class CSGShape : public GeometryInstance { + GDCLASS(CSGShape, GeometryInstance); public: enum Operation { @@ -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; @@ -156,7 +156,8 @@ public: VARIANT_ENUM_CAST(CSGShape::Operation) class CSGCombiner : public CSGShape { - GDCLASS(CSGCombiner, CSGShape) + GDCLASS(CSGCombiner, CSGShape); + private: virtual CSGBrush *_build_brush(); @@ -165,7 +166,7 @@ public: }; class CSGPrimitive : public CSGShape { - GDCLASS(CSGPrimitive, CSGShape) + GDCLASS(CSGPrimitive, CSGShape); private: bool invert_faces; @@ -182,11 +183,12 @@ public: }; class CSGMesh : public CSGPrimitive { - GDCLASS(CSGMesh, CSGPrimitive) + GDCLASS(CSGMesh, CSGPrimitive); virtual CSGBrush *_build_brush(); Ref<Mesh> mesh; + Ref<Material> material; void _mesh_changed(); @@ -196,11 +198,14 @@ protected: public: void set_mesh(const Ref<Mesh> &p_mesh); Ref<Mesh> get_mesh(); + + void set_material(const Ref<Material> &p_material); + Ref<Material> get_material() const; }; class CSGSphere : public CSGPrimitive { - GDCLASS(CSGSphere, CSGPrimitive) + GDCLASS(CSGSphere, CSGPrimitive); virtual CSGBrush *_build_brush(); Ref<Material> material; @@ -233,7 +238,7 @@ public: class CSGBox : public CSGPrimitive { - GDCLASS(CSGBox, CSGPrimitive) + GDCLASS(CSGBox, CSGPrimitive); virtual CSGBrush *_build_brush(); Ref<Material> material; @@ -262,7 +267,7 @@ public: class CSGCylinder : public CSGPrimitive { - GDCLASS(CSGCylinder, CSGPrimitive) + GDCLASS(CSGCylinder, CSGPrimitive); virtual CSGBrush *_build_brush(); Ref<Material> material; @@ -299,7 +304,7 @@ public: class CSGTorus : public CSGPrimitive { - GDCLASS(CSGTorus, CSGPrimitive) + GDCLASS(CSGTorus, CSGPrimitive); virtual CSGBrush *_build_brush(); Ref<Material> material; @@ -336,7 +341,7 @@ public: class CSGPolygon : public CSGPrimitive { - GDCLASS(CSGPolygon, CSGPrimitive) + GDCLASS(CSGPolygon, CSGPrimitive); public: enum Mode { @@ -399,7 +404,7 @@ public: void set_spin_degrees(float p_spin_degrees); float get_spin_degrees() const; - void set_spin_sides(int p_sides); + void set_spin_sides(int p_spin_sides); int get_spin_sides() const; void set_path_node(const NodePath &p_path); diff --git a/modules/csg/doc_classes/CSGBox.xml b/modules/csg/doc_classes/CSGBox.xml index 1684850f0a..14f5a1952e 100644 --- a/modules/csg/doc_classes/CSGBox.xml +++ b/modules/csg/doc_classes/CSGBox.xml @@ -8,21 +8,19 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="depth" type="float" setter="set_depth" getter="get_depth"> + <member name="depth" type="float" setter="set_depth" getter="get_depth" default="2.0"> Depth of the box measured from the center of the box. </member> - <member name="height" type="float" setter="set_height" getter="get_height"> + <member name="height" type="float" setter="set_height" getter="get_height" default="2.0"> Height of the box measured from the center of the box. </member> <member name="material" type="Material" setter="set_material" getter="get_material"> The material used to render the box. </member> - <member name="width" type="float" setter="set_width" getter="get_width"> + <member name="width" type="float" setter="set_width" getter="get_width" default="2.0"> Width of the box measured from the center of the box. </member> </members> diff --git a/modules/csg/doc_classes/CSGCombiner.xml b/modules/csg/doc_classes/CSGCombiner.xml index 819a4a3a22..51428b25f8 100644 --- a/modules/csg/doc_classes/CSGCombiner.xml +++ b/modules/csg/doc_classes/CSGCombiner.xml @@ -8,8 +8,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/csg/doc_classes/CSGCylinder.xml b/modules/csg/doc_classes/CSGCylinder.xml index 50a88d6773..9fc0281887 100644 --- a/modules/csg/doc_classes/CSGCylinder.xml +++ b/modules/csg/doc_classes/CSGCylinder.xml @@ -8,28 +8,26 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="cone" type="bool" setter="set_cone" getter="is_cone"> - If true a cone is created, the [member radius] will only apply to one side. + <member name="cone" type="bool" setter="set_cone" getter="is_cone" default="false"> + If [code]true[/code] a cone is created, the [member radius] will only apply to one side. </member> - <member name="height" type="float" setter="set_height" getter="get_height"> + <member name="height" type="float" setter="set_height" getter="get_height" default="1.0"> The height of the cylinder. </member> <member name="material" type="Material" setter="set_material" getter="get_material"> The material used to render the cylinder. </member> - <member name="radius" type="float" setter="set_radius" getter="get_radius"> + <member name="radius" type="float" setter="set_radius" getter="get_radius" default="1.0"> The radius of the cylinder. </member> - <member name="sides" type="int" setter="set_sides" getter="get_sides"> + <member name="sides" type="int" setter="set_sides" getter="get_sides" default="8"> The number of sides of the cylinder, the higher this number the more detail there will be in the cylinder. </member> - <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces"> - If true the normals of the cylinder are set to give a smooth effect making the cylinder seem rounded. When false the cylinder will have a flat shaded look. + <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces" default="true"> + If [code]true[/code] the normals of the cylinder are set to give a smooth effect making the cylinder seem rounded. If [code]false[/code] the cylinder will have a flat shaded look. </member> </members> <constants> diff --git a/modules/csg/doc_classes/CSGMesh.xml b/modules/csg/doc_classes/CSGMesh.xml index fc9815d7c0..afe0bc262d 100644 --- a/modules/csg/doc_classes/CSGMesh.xml +++ b/modules/csg/doc_classes/CSGMesh.xml @@ -8,11 +8,11 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> + <member name="material" type="Material" setter="set_material" getter="get_material"> + </member> <member name="mesh" type="Mesh" setter="set_mesh" getter="get_mesh"> The mesh resource to use as a CSG shape. </member> diff --git a/modules/csg/doc_classes/CSGPolygon.xml b/modules/csg/doc_classes/CSGPolygon.xml index ae75f7e01b..0ecee92cd5 100644 --- a/modules/csg/doc_classes/CSGPolygon.xml +++ b/modules/csg/doc_classes/CSGPolygon.xml @@ -8,31 +8,29 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="depth" type="float" setter="set_depth" getter="get_depth"> + <member name="depth" type="float" setter="set_depth" getter="get_depth" default="1.0"> Extrusion depth when [member mode] is [constant MODE_DEPTH]. </member> <member name="material" type="Material" setter="set_material" getter="get_material"> Material to use for the resulting mesh. </member> - <member name="mode" type="int" setter="set_mode" getter="get_mode" enum="CSGPolygon.Mode"> + <member name="mode" type="int" setter="set_mode" getter="get_mode" enum="CSGPolygon.Mode" default="0"> Extrusion mode. </member> <member name="path_continuous_u" type="bool" setter="set_path_continuous_u" getter="is_path_continuous_u"> - If true the u component of our uv will continuously increase in unison with the distance traveled along our path when [member mode] is [constant MODE_PATH]. + If [code]true[/code] the u component of our uv will continuously increase in unison with the distance traveled along our path when [member mode] is [constant MODE_PATH]. </member> <member name="path_interval" type="float" setter="set_path_interval" getter="get_path_interval"> Interval at which a new extrusion slice is added along the path when [member mode] is [constant MODE_PATH]. </member> <member name="path_joined" type="bool" setter="set_path_joined" getter="is_path_joined"> - If true the start and end of our path are joined together ensuring there is no seam when [member mode] is [constant MODE_PATH]. + If [code]true[/code] the start and end of our path are joined together ensuring there is no seam when [member mode] is [constant MODE_PATH]. </member> <member name="path_local" type="bool" setter="set_path_local" getter="is_path_local"> - If false we extrude centered on our path, if true we extrude in relation to the position of our CSGPolygon when [member mode] is [constant MODE_PATH]. + If [code]false[/code] we extrude centered on our path, if [code]true[/code] we extrude in relation to the position of our CSGPolygon when [member mode] is [constant MODE_PATH]. </member> <member name="path_node" type="NodePath" setter="set_path_node" getter="get_path_node"> The [Shape] object containing the path along which we extrude when [member mode] is [constant MODE_PATH]. @@ -40,10 +38,10 @@ <member name="path_rotation" type="int" setter="set_path_rotation" getter="get_path_rotation" enum="CSGPolygon.PathRotation"> The method by which each slice is rotated along the path when [member mode] is [constant MODE_PATH]. </member> - <member name="polygon" type="PoolVector2Array" setter="set_polygon" getter="get_polygon"> + <member name="polygon" type="PoolVector2Array" setter="set_polygon" getter="get_polygon" default="PoolVector2Array( 0, 0, 0, 1, 1, 1, 1, 0 )"> Point array that defines the shape that we'll extrude. </member> - <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces"> + <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces" default="false"> Generates smooth normals so smooth shading is applied to our mesh. </member> <member name="spin_degrees" type="float" setter="set_spin_degrees" getter="get_spin_degrees"> diff --git a/modules/csg/doc_classes/CSGPrimitive.xml b/modules/csg/doc_classes/CSGPrimitive.xml index 502a8230e4..6c2f837637 100644 --- a/modules/csg/doc_classes/CSGPrimitive.xml +++ b/modules/csg/doc_classes/CSGPrimitive.xml @@ -7,12 +7,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="invert_faces" type="bool" setter="set_invert_faces" getter="is_inverting_faces"> + <member name="invert_faces" type="bool" setter="set_invert_faces" getter="is_inverting_faces" default="false"> Invert the faces of the mesh. </member> </members> diff --git a/modules/csg/doc_classes/CSGShape.xml b/modules/csg/doc_classes/CSGShape.xml index ccfc5a04c0..755d8df67e 100644 --- a/modules/csg/doc_classes/CSGShape.xml +++ b/modules/csg/doc_classes/CSGShape.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="CSGShape" inherits="VisualInstance" category="Core" version="3.2"> +<class name="CSGShape" inherits="GeometryInstance" category="Core" version="3.2"> <brief_description> The CSG base class. </brief_description> @@ -8,8 +8,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_collision_layer_bit" qualifiers="const"> <return type="bool"> @@ -39,7 +37,7 @@ <return type="bool"> </return> <description> - Returns true if this is a root shape and is thus the object that is rendered. + Returns [code]true[/code] if this is a root shape and is thus the object that is rendered. </description> </method> <method name="set_collision_layer_bit"> @@ -66,23 +64,23 @@ </method> </methods> <members> - <member name="calculate_tangents" type="bool" setter="set_calculate_tangents" getter="is_calculating_tangents"> + <member name="calculate_tangents" type="bool" setter="set_calculate_tangents" getter="is_calculating_tangents" default="true"> Calculate tangents for the CSG shape which allows the use of normal maps. This is only applied on the root shape, this setting is ignored on any child. </member> - <member name="collision_layer" type="int" setter="set_collision_layer" getter="get_collision_layer"> + <member name="collision_layer" type="int" setter="set_collision_layer" getter="get_collision_layer" default="1"> The physics layers this area is in. Collidable objects can exist in any of 32 different layers. These layers work like a tagging system, and are not visual. A collidable can use these layers to select with which objects it can collide, using the collision_mask property. A contact is detected if object A is in any of the layers that object B scans, or object B is in any layer scanned by object A. </member> - <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask"> + <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask" default="1"> The physics layers this CSG shape scans for collisions. </member> - <member name="operation" type="int" setter="set_operation" getter="get_operation" enum="CSGShape.Operation"> + <member name="operation" type="int" setter="set_operation" getter="get_operation" enum="CSGShape.Operation" default="0"> The operation that is performed on this shape. This is ignored for the first CSG child node as the operation is between this node and the previous child of this nodes parent. </member> - <member name="snap" type="float" setter="set_snap" getter="get_snap"> + <member name="snap" type="float" setter="set_snap" getter="get_snap" default="0.001"> </member> - <member name="use_collision" type="bool" setter="set_use_collision" getter="is_using_collision"> + <member name="use_collision" type="bool" setter="set_use_collision" getter="is_using_collision" default="false"> Adds a collision shape to the physics engine for our CSG shape. This will always act like a static body. Note that the collision shape is still active even if the CSG shape itself is hidden. </member> </members> @@ -94,7 +92,7 @@ Only intersecting geometry remains, the rest is removed. </constant> <constant name="OPERATION_SUBTRACTION" value="2" enum="Operation"> - The second shape is susbtracted from the first, leaving a dent with it's shape. + The second shape is subtracted from the first, leaving a dent with its shape. </constant> </constants> </class> diff --git a/modules/csg/doc_classes/CSGSphere.xml b/modules/csg/doc_classes/CSGSphere.xml index 088c9f14eb..714e725acb 100644 --- a/modules/csg/doc_classes/CSGSphere.xml +++ b/modules/csg/doc_classes/CSGSphere.xml @@ -8,25 +8,23 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> <member name="material" type="Material" setter="set_material" getter="get_material"> The material used to render the sphere. </member> - <member name="radial_segments" type="int" setter="set_radial_segments" getter="get_radial_segments"> + <member name="radial_segments" type="int" setter="set_radial_segments" getter="get_radial_segments" default="12"> Number of vertical slices for the sphere. </member> - <member name="radius" type="float" setter="set_radius" getter="get_radius"> + <member name="radius" type="float" setter="set_radius" getter="get_radius" default="1.0"> Radius of the sphere. </member> - <member name="rings" type="int" setter="set_rings" getter="get_rings"> + <member name="rings" type="int" setter="set_rings" getter="get_rings" default="6"> Number of horizontal slices for the sphere. </member> - <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces"> - If true the normals of the sphere are set to give a smooth effect making the sphere seem rounded. When false the sphere will have a flat shaded look. + <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces" default="true"> + If [code]true[/code] the normals of the sphere are set to give a smooth effect making the sphere seem rounded. If [code]false[/code] the sphere will have a flat shaded look. </member> </members> <constants> diff --git a/modules/csg/doc_classes/CSGTorus.xml b/modules/csg/doc_classes/CSGTorus.xml index 946637bd2c..5dc6bb8380 100644 --- a/modules/csg/doc_classes/CSGTorus.xml +++ b/modules/csg/doc_classes/CSGTorus.xml @@ -8,28 +8,26 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="inner_radius" type="float" setter="set_inner_radius" getter="get_inner_radius"> + <member name="inner_radius" type="float" setter="set_inner_radius" getter="get_inner_radius" default="2.0"> The inner radius of the torus. </member> <member name="material" type="Material" setter="set_material" getter="get_material"> The material used to render the torus. </member> - <member name="outer_radius" type="float" setter="set_outer_radius" getter="get_outer_radius"> + <member name="outer_radius" type="float" setter="set_outer_radius" getter="get_outer_radius" default="3.0"> The outer radius of the torus. </member> - <member name="ring_sides" type="int" setter="set_ring_sides" getter="get_ring_sides"> + <member name="ring_sides" type="int" setter="set_ring_sides" getter="get_ring_sides" default="6"> The number of edges each ring of the torus is constructed of. </member> - <member name="sides" type="int" setter="set_sides" getter="get_sides"> + <member name="sides" type="int" setter="set_sides" getter="get_sides" default="8"> The number of slices the torus is constructed of. </member> - <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces"> - If true the normals of the torus are set to give a smooth effect making the torus seem rounded. When false the torus will have a flat shaded look. + <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces" default="true"> + If [code]true[/code] the normals of the torus are set to give a smooth effect making the torus seem rounded. If [code]false[/code] the torus will have a flat shaded look. </member> </members> <constants> diff --git a/modules/csg/icons/icon_c_s_g_box.svg b/modules/csg/icons/icon_c_s_g_box.svg new file mode 100644 index 0000000000..67e34df444 --- /dev/null +++ b/modules/csg/icons/icon_c_s_g_box.svg @@ -0,0 +1,6 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<path transform="translate(0 1036.4)" d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1h-2zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1v-1z" fill="#84c2ff"/> +<path transform="translate(0 1036.4)" d="m8 0.94531-7 3.5v7.2227l7 3.5 0.29492-0.14844c-0.18282-0.30101-0.29492-0.64737-0.29492-1.0195v-2c0-0.72651 0.40824-1.3664 1-1.7168v-1.6699l4-2v1.3867h1c0.36419 0 0.70336 0.10754 1 0.2832v-3.8379zm0 2.1152 3.9395 1.9707-3.9395 1.9688-3.9395-1.9688zm-5 3.5527 4 2v3.9414l-4-2.002z" fill="#fc9c9c" stroke-width="1.0667"/> +</g> +</svg> diff --git a/modules/csg/icons/icon_c_s_g_capsule.svg b/modules/csg/icons/icon_c_s_g_capsule.svg new file mode 100644 index 0000000000..92a7b5a870 --- /dev/null +++ b/modules/csg/icons/icon_c_s_g_capsule.svg @@ -0,0 +1,6 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g> +<path d="m8 1c-2.7527 0-5 2.2418-5 4.9902v4.0176c0 2.7484 2.2473 4.9922 5 4.9922 0.092943 0 0.18367-0.008623 0.27539-0.013672-0.17055-0.29341-0.27539-0.62792-0.27539-0.98633v-2c0-0.72887 0.41095-1.3691 1.0059-1.7188v-0.28125c0.34771-0.034464 0.68259-0.10691 1.0156-0.19922 0.10394-0.99856 0.95603-1.8008 1.9785-1.8008h1v-2.0098c0-2.7484-2.2473-4.9902-5-4.9902zm-1.0059 2.127v4.8574c-0.66556-0.1047-1.2974-0.37231-1.9941-0.66211v-1.3223c0-1.3474 0.79841-2.4642 1.9941-2.873zm2.0117 0c1.1957 0.4088 1.9941 1.5256 1.9941 2.873v1.3457c-0.68406 0.3054-1.3142 0.57292-1.9941 0.66602v-4.8848zm-4.0059 6.334c0.67836 0.2231 1.3126 0.44599 1.9941 0.52539v2.8848c-1.1957-0.4092-1.9941-1.5237-1.9941-2.8711v-0.53906z" fill="#fc9c9c"/> +<path d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1z" fill="#84c2ff"/> +</g> +</svg> diff --git a/modules/csg/icons/icon_c_s_g_combiner.svg b/modules/csg/icons/icon_c_s_g_combiner.svg new file mode 100644 index 0000000000..cce2902e24 --- /dev/null +++ b/modules/csg/icons/icon_c_s_g_combiner.svg @@ -0,0 +1,8 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<path transform="translate(0 1036.4)" d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1h-2zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1v-1z" fill="#84c2ff"/> +<g fill="#fc9c9c"> +<path transform="translate(0 1036.4)" d="m3 1c-1.1046 0-2 0.89543-2 2h2zm2 0v2h2v-2zm4 0v2h2v-2zm4 0v2h2c0-1.1046-0.89543-2-2-2zm-12 4v2h2v-2zm12 0v2h2v-2zm-12 4v2h2v-2zm0 4c0 1.1046 0.89543 2 2 2v-2zm4 0v2h2v-2z" fill="#fc9c9c"/> +</g> +</g> +</svg> diff --git a/modules/csg/icons/icon_c_s_g_cylinder.svg b/modules/csg/icons/icon_c_s_g_cylinder.svg new file mode 100644 index 0000000000..645a74c79b --- /dev/null +++ b/modules/csg/icons/icon_c_s_g_cylinder.svg @@ -0,0 +1,6 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 14.999999 14.999999" xmlns="http://www.w3.org/2000/svg"> +<g> +<path transform="scale(.9375)" d="m8 1c-1.7469 0-3.328 0.22648-4.5586 0.63672-0.61528 0.20512-1.1471 0.45187-1.5898 0.80078-0.44272 0.34891-0.85156 0.88101-0.85156 1.5625v8c0 0.68149 0.40884 1.2155 0.85156 1.5645 0.44272 0.34891 0.97457 0.59577 1.5898 0.80078 1.2306 0.41024 2.8117 0.63477 4.5586 0.63477 0.095648 0 0.18467-0.008426 0.2793-0.009766-0.1722-0.29446-0.2793-0.62995-0.2793-0.99023v-1c-1.5668 0-2.9867-0.2195-3.9277-0.5332-0.46329-0.15435-0.90474-0.33752-1.0723-0.4668v-5.8125c0.1468 0.058667 0.2835 0.12515 0.44141 0.17773 1.2306 0.41024 2.8117 0.63477 4.5586 0.63477s3.328-0.22453 4.5586-0.63477c0.15791-0.052267 0.29461-0.11864 0.44141-0.17773v1.8125h1c0.36396 0 0.70348 0.10774 1 0.2832v-4.2832c0-0.68149-0.40884-1.2136-0.85156-1.5625-0.44272-0.34891-0.97457-0.59566-1.5898-0.80078-1.2306-0.41024-2.8117-0.63672-4.5586-0.63672zm0 2c1.5668 0 2.9867 0.22145 3.9277 0.53516 0.46368 0.15456 0.80138 0.33741 0.96875 0.4668-0.16752 0.12928-0.50546 0.3105-0.96875 0.46484-0.94102 0.31371-2.361 0.5332-3.9277 0.5332s-2.9867-0.2195-3.9277-0.5332c-0.46329-0.15435-0.80123-0.33556-0.96875-0.46484 0.16737-0.12939 0.50507-0.31224 0.96875-0.4668 0.94102-0.31371 2.361-0.53516 3.9277-0.53516z" fill="#fc9c9c" stroke-width="1.0667"/> +<path d="m11.25 8.4375c-0.51938 0-0.9375 0.41812-0.9375 0.9375v0.9375h1.875v1.875h0.9375c0.51938 0 0.9375-0.41812 0.9375-0.9375v-1.875c0-0.51938-0.41812-0.9375-0.9375-0.9375zm0.9375 3.75h-1.875v-1.875h-0.9375c-0.51938 0-0.9375 0.41812-0.9375 0.9375v1.875c0 0.51938 0.41812 0.9375 0.9375 0.9375h1.875c0.51938 0 0.9375-0.41812 0.9375-0.9375z" fill="#84c2ff"/> +</g> +</svg> diff --git a/modules/csg/icons/icon_c_s_g_mesh.svg b/modules/csg/icons/icon_c_s_g_mesh.svg new file mode 100644 index 0000000000..6e940a4aa5 --- /dev/null +++ b/modules/csg/icons/icon_c_s_g_mesh.svg @@ -0,0 +1,6 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g> +<path d="m3 1c-1.1046 0-2 0.89543-2 2 5.649e-4 0.71397 0.38169 1.3735 1 1.7305v6.541c-0.61771 0.35663-0.99874 1.0152-1 1.7285 0 1.1046 0.89543 2 2 2 0.71397-5.65e-4 1.3735-0.38169 1.7305-1h3.2695v-2h-3.2715c-0.17478-0.30301-0.42598-0.55488-0.72852-0.73047v-5.8555l4.916 4.916c0.31428-0.20669 0.68609-0.33008 1.084-0.33008 0-0.3979 0.12338-0.76971 0.33008-1.084l-4.916-4.916h5.8574c0.17478 0.30301 0.42598 0.55488 0.72852 0.73047v3.2695h2v-3.2715c0.61771-0.35663 0.99874-1.0152 1-1.7285 0-1.1046-0.89543-2-2-2-0.71397 5.648e-4 -1.3735 0.38169-1.7305 1h-6.541c-0.35663-0.61771-1.0152-0.99874-1.7285-1z" fill="#fc9c9c"/> +<path d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1z" fill="#84c2ff"/> +</g> +</svg> diff --git a/modules/csg/icons/icon_c_s_g_polygon.svg b/modules/csg/icons/icon_c_s_g_polygon.svg new file mode 100644 index 0000000000..71b03cb8e6 --- /dev/null +++ b/modules/csg/icons/icon_c_s_g_polygon.svg @@ -0,0 +1,6 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<path transform="translate(0 1036.4)" d="m7.9629 1.002c-0.14254 0.00487-0.28238 0.04016-0.41016 0.10352l-6 3c-0.33878 0.16944-0.55276 0.51574-0.55273 0.89453v5.832c-0.105 0.61631 0.37487 1.1768 1 1.168h5v2c2.16e-5 0.67546 0.64487 1.1297 1.2617 0.95898-0.16118-0.28721-0.26172-0.61135-0.26172-0.95898v-2c0-0.72673 0.40794-1.3664 1-1.7168v-1.666l4-2v1.3828h1c0.36397 0 0.70348 0.10774 1 0.2832v-3.2773c6e-6 -0.00195 6e-6 -0.0039094 0-0.0058594 2.6e-5 -0.37879-0.21395-0.72509-0.55273-0.89453l-6-3c-0.15022-0.074574-0.31679-0.11017-0.48438-0.10352zm0.037109 2.1172l3.7637 1.8809-2.7637 1.3809v-1.3809c-5.52e-5 -0.55226-0.44774-0.99994-1-1h-1.7617l1.7617-0.88086zm-5 2.8809h4v4h-4v-4z" color="#000000" color-rendering="auto" dominant-baseline="auto" fill="#fc9c9c" image-rendering="auto" shape-rendering="auto" solid-color="#000000" style="font-feature-settings:normal;font-variant-alternates:normal;font-variant-caps:normal;font-variant-ligatures:normal;font-variant-numeric:normal;font-variant-position:normal;isolation:auto;mix-blend-mode:normal;shape-padding:0;text-decoration-color:#000000;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-orientation:mixed;text-transform:none;white-space:normal"/> +<path transform="translate(0 1036.4)" d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1h-2zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1v-1z" fill="#84c2ff"/> +</g> +</svg> diff --git a/modules/csg/icons/icon_c_s_g_sphere.svg b/modules/csg/icons/icon_c_s_g_sphere.svg new file mode 100644 index 0000000000..f81b566993 --- /dev/null +++ b/modules/csg/icons/icon_c_s_g_sphere.svg @@ -0,0 +1,6 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g> +<path d="m8 1c-3.8541 0-7 3.1459-7 7 0 3.8542 3.1459 7 7 7 0.093042 0 0.18321-0.01004 0.27539-0.013672-0.17055-0.29341-0.27539-0.62792-0.27539-0.98633v-2c0-0.72673 0.40794-1.3664 1-1.7168v-0.33398c0.34074-0.019259 0.67728-0.069097 1.0156-0.10547 0.083091-1.0187 0.94713-1.8438 1.9844-1.8438h2c0.35841 0 0.69292 0.10484 0.98633 0.27539 0.003633-0.092184 0.013672-0.18235 0.013672-0.27539 0-3.8541-3.1459-7-7-7zm-1 2.0977v4.8711c-1.2931-0.071342-2.6061-0.29819-3.9434-0.69141 0.30081-2.0978 1.8852-3.7665 3.9434-4.1797zm2 0c2.0549 0.41253 3.637 2.0767 3.9414 4.1699-1.3046 0.36677-2.6158 0.60259-3.9414 0.6875v-4.8574zm-5.7793 6.2988c1.2733 0.31892 2.5337 0.50215 3.7793 0.5625v2.9414c-1.8291-0.36719-3.266-1.7339-3.7793-3.5039z" fill="#fc9c9c"/> +<path d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1z" fill="#84c2ff"/> +</g> +</svg> diff --git a/modules/csg/icons/icon_c_s_g_torus.svg b/modules/csg/icons/icon_c_s_g_torus.svg new file mode 100644 index 0000000000..3d30aa47b2 --- /dev/null +++ b/modules/csg/icons/icon_c_s_g_torus.svg @@ -0,0 +1,6 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<path transform="translate(0 1036.4)" d="m8 3c-1.8145 0-3.4691 0.41721-4.7461 1.1621-1.277 0.745-2.2539 1.9082-2.2539 3.3379 0 1.4298 0.9769 2.5949 2.2539 3.3398 1.277 0.7449 2.9316 1.1602 4.7461 1.1602 0-1.0907 0.90931-2 2-2 0-0.080836 0.013744-0.15778 0.023438-0.23633-0.61769 0.14673-1.3008 0.23633-2.0234 0.23633-1.4992 0-2.8437-0.36687-3.7383-0.88867-0.89456-0.5219-1.2617-1.108-1.2617-1.6113 0-0.5032 0.36716-1.0876 1.2617-1.6094 0.89456-0.5219 2.2391-0.89062 3.7383-0.89062s2.8437 0.36872 3.7383 0.89062c0.89456 0.5218 1.2617 1.1062 1.2617 1.6094 0 0.15978-0.053679 0.32822-0.13281 0.5h1.1328c0.32481 0 0.62893 0.088408 0.90234 0.23047 0.057552-0.23582 0.097656-0.47718 0.097656-0.73047 0-1.4297-0.9769-2.5929-2.2539-3.3379-1.277-0.7449-2.9316-1.1621-4.7461-1.1621z" color="#000000" color-rendering="auto" dominant-baseline="auto" fill="#fc9c9c" image-rendering="auto" shape-rendering="auto" solid-color="#000000" style="font-feature-settings:normal;font-variant-alternates:normal;font-variant-caps:normal;font-variant-ligatures:normal;font-variant-numeric:normal;font-variant-position:normal;isolation:auto;mix-blend-mode:normal;shape-padding:0;text-decoration-color:#000000;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-orientation:mixed;text-transform:none;white-space:normal"/> +<path transform="translate(0 1036.4)" d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1h-2zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1v-1z" fill="#84c2ff"/> +</g> +</svg> diff --git a/modules/cvtt/SCsub b/modules/cvtt/SCsub index fcc69d8371..746b23ca28 100644 --- a/modules/cvtt/SCsub +++ b/modules/cvtt/SCsub @@ -6,19 +6,18 @@ Import('env_modules') env_cvtt = env_modules.Clone() # Thirdparty source files -if env['builtin_squish']: - thirdparty_dir = "#thirdparty/cvtt/" - thirdparty_sources = [ - "ConvectionKernels.cpp" - ] +thirdparty_dir = "#thirdparty/cvtt/" +thirdparty_sources = [ + "ConvectionKernels.cpp" +] - thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] +thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - env_cvtt.Append(CPPPATH=[thirdparty_dir]) +env_cvtt.Prepend(CPPPATH=[thirdparty_dir]) - env_thirdparty = env_cvtt.Clone() - env_thirdparty.disable_warnings() - env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources) +env_thirdparty = env_cvtt.Clone() +env_thirdparty.disable_warnings() +env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources) # Godot source files env_cvtt.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/cvtt/image_compress_cvtt.cpp b/modules/cvtt/image_compress_cvtt.cpp index 0a70ff535f..17b0038780 100644 --- a/modules/cvtt/image_compress_cvtt.cpp +++ b/modules/cvtt/image_compress_cvtt.cpp @@ -145,7 +145,7 @@ void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::CompressS int h = p_image->get_height(); bool is_ldr = (p_image->get_format() <= Image::FORMAT_RGBA8); - bool is_hdr = (p_image->get_format() == Image::FORMAT_RGBH); + bool is_hdr = (p_image->get_format() >= Image::FORMAT_RH) && (p_image->get_format() <= Image::FORMAT_RGBE9995); if (!is_ldr && !is_hdr) { return; // Not a usable source format @@ -175,6 +175,10 @@ void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::CompressS bool is_signed = false; if (is_hdr) { + if (p_image->get_format() != Image::FORMAT_RGBH) { + p_image->convert(Image::FORMAT_RGBH); + } + PoolVector<uint8_t>::Read rb = p_image->get_data().read(); const uint16_t *source_data = reinterpret_cast<const uint16_t *>(&rb[0]); @@ -384,8 +388,8 @@ void image_decompress_cvtt(Image *p_image) { h >>= 1; } - rb = PoolVector<uint8_t>::Read(); - wb = PoolVector<uint8_t>::Write(); + rb.release(); + wb.release(); p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data); } diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp index 0a94690989..16a0f9d6ee 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) ((uint32_t)(((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 }, @@ -102,8 +108,7 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, if (r_error) *r_error = ERR_FILE_CORRUPT; - ERR_EXPLAIN("Unable to open DDS texture file: " + p_path); - ERR_FAIL_COND_V(err != OK, RES()); + ERR_FAIL_COND_V_MSG(err != OK, RES(), "Unable to open DDS texture file '" + p_path + "'."); uint32_t magic = f->get_32(); uint32_t hsize = f->get_32(); @@ -122,8 +127,7 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, if (magic != DDS_MAGIC || hsize != 124 || !(flags & DDSD_PIXELFORMAT) || !(flags & DDSD_CAPS)) { - ERR_EXPLAIN("Invalid or Unsupported DDS texture file: " + p_path); - ERR_FAIL_V(RES()); + ERR_FAIL_V_MSG(RES(), "Invalid or unsupported DDS texture file '" + p_path + "'."); } /* uint32_t format_size = */ f->get_32(); @@ -158,22 +162,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) { @@ -209,9 +216,7 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, } else { printf("unrecognized fourcc %x format_flags: %x - rgbbits %i - red_mask %x green mask %x blue mask %x alpha mask %x\n", format_fourcc, format_flags, format_rgb_bits, format_red_mask, format_green_mask, format_blue_mask, format_alpha_mask); - ERR_EXPLAIN("Unrecognized or Unsupported color layout in DDS: " + p_path); - - ERR_FAIL_V(RES()); + ERR_FAIL_V_MSG(RES(), "Unrecognized or unsupported color layout in DDS '" + p_path + "'."); } if (!(flags & DDSD_MIPMAPCOUNT)) @@ -242,7 +247,6 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, src_data.resize(size); PoolVector<uint8_t>::Write wb = src_data.write(); f->get_buffer(wb.ptr(), size); - wb = PoolVector<uint8_t>::Write(); } else if (info.palette) { @@ -287,8 +291,6 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, if (colsize == 4) wb[dst_ofs + 3] = palette[src_ofs + 3]; } - - wb = PoolVector<uint8_t>::Write(); } else { //uncompressed generic... @@ -432,10 +434,9 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, } break; - default: {} + default: { + } } - - wb = PoolVector<uint8_t>::Write(); } Ref<Image> img = memnew(Image(width, height, mipmaps - 1, info.format, src_data)); 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/SCsub b/modules/enet/SCsub index a57a4b29ea..485c33b1a8 100644 --- a/modules/enet/SCsub +++ b/modules/enet/SCsub @@ -21,8 +21,8 @@ if env['builtin_enet']: ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - env_enet.Append(CPPPATH=[thirdparty_dir]) - env_enet.Append(CPPFLAGS=["-DGODOT_ENET"]) + env_enet.Prepend(CPPPATH=[thirdparty_dir]) + env_enet.Append(CPPDEFINES=["GODOT_ENET"]) env_thirdparty = env_enet.Clone() env_thirdparty.disable_warnings() diff --git a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml index c1bec533dd..78a8e94012 100644 --- a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml +++ b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="NetworkedMultiplayerENet" inherits="NetworkedMultiplayerPeer" category="Core" version="3.2"> <brief_description> - PacketPeer implementation using the ENet library. + PacketPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library. </brief_description> <description> A PacketPeer implementation that should be passed to [member SceneTree.network_peer] after being initialized as either a client or server. Events can then be handled by connecting to [SceneTree] signals. @@ -10,8 +10,6 @@ <link>https://docs.godotengine.org/en/latest/tutorials/networking/high_level_multiplayer.html</link> <link>http://enet.bespin.org/usergroup0.html</link> </tutorials> - <demos> - </demos> <methods> <method name="close_connection"> <return type="void"> @@ -36,7 +34,7 @@ <argument index="4" name="client_port" type="int" default="0"> </argument> <description> - Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]www.example.com[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]192.168.1.1[/code]). The [code]port[/code] is the port the server is listening on. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [code]OK[/code] if a client was created, [code]ERR_ALREADY_IN_USE[/code] if this NetworkedMultiplayerEnet instance already has an open connection (in which case you need to call [method close_connection] first) or [code]ERR_CANT_CREATE[/code] if the client could not be created. If [code]client_port[/code] is specified, the client will also listen to the given port, this is useful in some NAT traversal technique. + Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]"www.example.com"[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]"192.168.1.1"[/code]). The [code]port[/code] is the port the server is listening on. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [constant OK] if a client was created, [constant ERR_ALREADY_IN_USE] if this NetworkedMultiplayerENet instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the client could not be created. If [code]client_port[/code] is specified, the client will also listen to the given port; this is useful for some NAT traversal techniques. </description> </method> <method name="create_server"> @@ -51,7 +49,7 @@ <argument index="3" name="out_bandwidth" type="int" default="0"> </argument> <description> - Create server that listens to connections via [code]port[/code]. The port needs to be an available, unused port between 0 and 65535. Note that ports below 1024 are privileged and may require elevated permissions depending on the platform. To change the interface the server listens on, use [method set_bind_ip]. The default IP is the wildcard [code]*[/code], which listens on all available interfaces. [code]max_clients[/code] is the maximum number of clients that are allowed at once, any number up to 4096 may be used, although the achievable number of simultaneous clients may be far lower and depends on the application. For additional details on the bandwidth parameters, see [method create_client]. Returns [code]OK[/code] if a server was created, [code]ERR_ALREADY_IN_USE[/code] if this NetworkedMultiplayerEnet instance already has an open connection (in which case you need to call [method close_connection] first) or [code]ERR_CANT_CREATE[/code] if the server could not be created. + Create server that listens to connections via [code]port[/code]. The port needs to be an available, unused port between 0 and 65535. Note that ports below 1024 are privileged and may require elevated permissions depending on the platform. To change the interface the server listens on, use [method set_bind_ip]. The default IP is the wildcard [code]"*"[/code], which listens on all available interfaces. [code]max_clients[/code] is the maximum number of clients that are allowed at once, any number up to 4096 may be used, although the achievable number of simultaneous clients may be far lower and depends on the application. For additional details on the bandwidth parameters, see [method create_client]. Returns [constant OK] if a server was created, [constant ERR_ALREADY_IN_USE] if this NetworkedMultiplayerENet instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the server could not be created. </description> </method> <method name="disconnect_peer"> @@ -62,7 +60,7 @@ <argument index="1" name="now" type="bool" default="false"> </argument> <description> - Disconnect the given peer. If "now" is set to true, the connection will be closed immediately without flushing queued messages. + Disconnect the given peer. If "now" is set to [code]true[/code], the connection will be closed immediately without flushing queued messages. </description> </method> <method name="get_last_packet_channel" qualifiers="const"> @@ -103,39 +101,44 @@ <argument index="0" name="ip" type="String"> </argument> <description> - The IP used when creating a server. This is set to the wildcard [code]*[/code] by default, which binds to all available interfaces. The given IP needs to be in IPv4 or IPv6 address format, for example: [code]192.168.1.1[/code]. + The IP used when creating a server. This is set to the wildcard [code]"*"[/code] by default, which binds to all available interfaces. The given IP needs to be in IPv4 or IPv6 address format, for example: [code]"192.168.1.1"[/code]. </description> </method> </methods> <members> - <member name="always_ordered" type="bool" setter="set_always_ordered" getter="is_always_ordered"> - Always use [code]TRANSFER_MODE_ORDERED[/code] in place of [code]TRANSFER_MODE_UNRELIABLE[/code]. This is the only way to use ordering with the RPC system. + <member name="always_ordered" type="bool" setter="set_always_ordered" getter="is_always_ordered" default="false"> + Enforce ordered packets when using [constant NetworkedMultiplayerPeer.TRANSFER_MODE_UNRELIABLE] (thus behaving similarly to [constant NetworkedMultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED]). This is the only way to use ordering with the RPC system. </member> - <member name="channel_count" type="int" setter="set_channel_count" getter="get_channel_count"> - The number of channels to be used by ENet. Default: [code]3[/code]. Channels are used to separate different kinds of data. In realiable or ordered mode, for example, the packet delivery order is ensured on a per channel basis. + <member name="channel_count" type="int" setter="set_channel_count" getter="get_channel_count" default="3"> + The number of channels to be used by ENet. Channels are used to separate different kinds of data. In reliable or ordered mode, for example, the packet delivery order is ensured on a per channel basis. </member> - <member name="compression_mode" type="int" setter="set_compression_mode" getter="get_compression_mode" enum="NetworkedMultiplayerENet.CompressionMode"> - The compression method used for network packets. Default is no compression. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all. + <member name="compression_mode" type="int" setter="set_compression_mode" getter="get_compression_mode" enum="NetworkedMultiplayerENet.CompressionMode" default="0"> + The compression method used for network packets. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all. </member> - <member name="transfer_channel" type="int" setter="set_transfer_channel" getter="get_transfer_channel"> - Set the default channel to be used to transfer data. By default this value is [code]-1[/code] which means that ENet will only use 2 channels, one for reliable and one for unreliable packets. Channel [code]0[/code] is reserved, and cannot be used. Setting this member to any value between [code]0[/code] and [member channel_count] (excluded) will force ENet to use that channel for sending data. + <member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" override="true" default="false" /> + <member name="server_relay" type="bool" setter="set_server_relay_enabled" getter="is_server_relay_enabled" default="true"> + Enable or disable the server feature that notifies clients of other peers' connection/disconnection, and relays messages between them. When this option is [code]false[/code], clients won't be automatically notified of other peers and won't be able to send them packets through the server. </member> + <member name="transfer_channel" type="int" setter="set_transfer_channel" getter="get_transfer_channel" default="-1"> + Set the default channel to be used to transfer data. By default, this value is [code]-1[/code] which means that ENet will only use 2 channels, one for reliable and one for unreliable packets. Channel [code]0[/code] is reserved, and cannot be used. Setting this member to any value between [code]0[/code] and [member channel_count] (excluded) will force ENet to use that channel for sending data. + </member> + <member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="NetworkedMultiplayerPeer.TransferMode" default="2" /> </members> <constants> <constant name="COMPRESS_NONE" value="0" enum="CompressionMode"> - No compression. + No compression. This uses the most bandwidth, but has the upside of requiring the fewest CPU resources. </constant> <constant name="COMPRESS_RANGE_CODER" value="1" enum="CompressionMode"> - ENet's buildin range encoding. + ENet's built-in range encoding. </constant> <constant name="COMPRESS_FASTLZ" value="2" enum="CompressionMode"> - FastLZ compression. + [url=http://fastlz.org/]FastLZ[/url] compression. This option uses less CPU resources compared to [constant COMPRESS_ZLIB], at the expense of using more bandwidth. </constant> <constant name="COMPRESS_ZLIB" value="3" enum="CompressionMode"> - zlib compression. + [url=https://www.zlib.net/]Zlib[/url] compression. This option uses less bandwidth compared to [constant COMPRESS_FASTLZ], at the expense of using more CPU resources. </constant> <constant name="COMPRESS_ZSTD" value="4" enum="CompressionMode"> - ZStandard compression. + [url=https://facebook.github.io/zstd/]Zstandard[/url] compression. </constant> </constants> </class> diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp index 000917507a..2f5307d041 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()) { @@ -231,7 +232,7 @@ void NetworkedMultiplayerENet::poll() { break; } - // A client joined with an invalid ID (neagtive values, 0, and 1 are reserved). + // A client joined with an invalid ID (negative values, 0, and 1 are reserved). // Probably trying to exploit us. if (server && ((int)event.data < 2 || peer_map.has((int)event.data))) { enet_peer_reset(event.peer); @@ -254,6 +255,10 @@ void NetworkedMultiplayerENet::poll() { emit_signal("peer_connected", *new_id); if (server) { + // Do not notify other peers when server_relay is disabled. + if (!server_relay) + break; + // Someone connected, notify all the peers available for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { @@ -286,31 +291,34 @@ void NetworkedMultiplayerENet::poll() { if (!server) { emit_signal("connection_failed"); } - } else { + // Never fully connected. + break; + } - if (server) { - // Someone disconnected, notify everyone else - for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { + if (!server) { - if (E->key() == *id) - continue; + // Client just disconnected from server. + emit_signal("server_disconnected"); + close_connection(); + return; + } else if (server_relay) { - ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]); - encode_uint32(*id, &packet->data[4]); - enet_peer_send(E->get(), SYSCH_CONFIG, packet); - } - } else { - emit_signal("server_disconnected"); - close_connection(); - return; - } + // Server just received a client disconnect and is in relay mode, notify everyone else. + for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { - emit_signal("peer_disconnected", *id); - peer_map.erase(*id); - memdelete(id); + if (E->key() == *id) + continue; + + ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE); + encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]); + encode_uint32(*id, &packet->data[4]); + enet_peer_send(E->get(), SYSCH_CONFIG, packet); + } } + emit_signal("peer_disconnected", *id); + peer_map.erase(*id); + memdelete(id); } break; case ENET_EVENT_TYPE_RECEIVE: { @@ -346,11 +354,10 @@ void NetworkedMultiplayerENet::poll() { uint32_t *id = (uint32_t *)event.peer->data; - ERR_CONTINUE(event.packet->dataLength < 12) + ERR_CONTINUE(event.packet->dataLength < 8); uint32_t source = decode_uint32(&event.packet->data[0]); int target = decode_uint32(&event.packet->data[4]); - uint32_t flags = decode_uint32(&event.packet->data[8]); packet.from = source; packet.channel = event.channelID; @@ -361,7 +368,13 @@ void NetworkedMultiplayerENet::poll() { packet.from = *id; - if (target == 0) { + if (target == 1) { + // To myself and only myself + incoming_packets.push_back(packet); + } else if (!server_relay) { + // No other destination is allowed when server is not relaying + continue; + } else if (target == 0) { // Re-send to everyone but sender :| incoming_packets.push_back(packet); @@ -371,7 +384,7 @@ void NetworkedMultiplayerENet::poll() { if (uint32_t(E->key()) == source) // Do not resend to self continue; - ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags); + ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags); enet_peer_send(E->get(), event.channelID, packet2); } @@ -385,7 +398,7 @@ void NetworkedMultiplayerENet::poll() { if (uint32_t(E->key()) == source || E->key() == -target) // Do not resend to self, also do not send to excluded continue; - ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags); + ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags); enet_peer_send(E->get(), event.channelID, packet2); } @@ -398,9 +411,6 @@ void NetworkedMultiplayerENet::poll() { enet_packet_destroy(packet.packet); } - } else if (target == 1) { - // To myself and only myself - incoming_packets.push_back(packet); } else { // To someone else, specifically ERR_CONTINUE(!peer_map.has(target)); @@ -440,6 +450,8 @@ void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) { for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { if (E->get()) { enet_peer_disconnect_now(E->get(), unique_id); + int *id = (int *)(E->get()->data); + memdelete(id); peers_disconnected = true; } } @@ -455,6 +467,7 @@ void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) { enet_host_destroy(host); active = false; incoming_packets.clear(); + peer_map.clear(); unique_id = 1; // Server is 1 connection_status = CONNECTION_DISCONNECTED; } @@ -463,7 +476,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); @@ -471,10 +484,13 @@ void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) { // enet_peer_disconnect_now doesn't generate ENET_EVENT_TYPE_DISCONNECT, // notify everyone else, send disconnect signal & remove from peer_map like in poll() + int *id = NULL; for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { - if (E->key() == p_peer) + if (E->key() == p_peer) { + id = (int *)(E->get()->data); continue; + } ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE); encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]); @@ -482,6 +498,9 @@ void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) { enet_peer_send(E->get(), SYSCH_CONFIG, packet); } + if (id) + memdelete(id); + emit_signal("peer_disconnected", p_peer); peer_map.erase(p_peer); } else { @@ -503,8 +522,8 @@ Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buff current_packet = incoming_packets.front()->get(); incoming_packets.pop_front(); - *r_buffer = (const uint8_t *)(¤t_packet.packet->data[12]); - r_buffer_size = current_packet.packet->dataLength - 12; + *r_buffer = (const uint8_t *)(¤t_packet.packet->data[8]); + r_buffer_size = current_packet.packet->dataLength - 8; return OK; } @@ -543,17 +562,13 @@ Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer if (target_peer != 0) { E = peer_map.find(ABS(target_peer)); - if (!E) { - ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer)); - ERR_FAIL_V(ERR_INVALID_PARAMETER); - } + ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer '" + itos(target_peer) + "'."); } - ENetPacket *packet = enet_packet_create(NULL, p_buffer_size + 12, packet_flags); + ENetPacket *packet = enet_packet_create(NULL, p_buffer_size + 8, packet_flags); encode_uint32(unique_id, &packet->data[0]); // Source ID encode_uint32(target_peer, &packet->data[4]); // Dest ID - encode_uint32(packet_flags, &packet->data[8]); // Dest ID - copymem(&packet->data[12], p_buffer, p_buffer_size); + copymem(&packet->data[8], p_buffer, p_buffer_size); if (server) { @@ -690,7 +705,9 @@ size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer * case COMPRESS_ZSTD: { mode = Compression::MODE_ZSTD; } break; - default: { ERR_FAIL_V(0); } + default: { + ERR_FAIL_V(0); + } } int req_size = Compression::get_max_compressed_buffer_size(ofs, mode); @@ -727,7 +744,8 @@ size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD); } break; - default: {} + default: { + } } if (ret < 0) { return 0; @@ -792,11 +810,7 @@ int NetworkedMultiplayerENet::get_peer_port(int p_peer_id) const { void NetworkedMultiplayerENet::set_transfer_channel(int p_channel) { ERR_FAIL_COND(p_channel < -1 || p_channel >= channel_count); - - if (p_channel == SYSCH_CONFIG) { - ERR_EXPLAIN("Channel " + itos(SYSCH_CONFIG) + " is reserved"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(p_channel == SYSCH_CONFIG, "Channel " + itos(SYSCH_CONFIG) + " is reserved."); transfer_channel = p_channel; } @@ -823,6 +837,16 @@ bool NetworkedMultiplayerENet::is_always_ordered() const { return always_ordered; } +void NetworkedMultiplayerENet::set_server_relay_enabled(bool p_enabled) { + ERR_FAIL_COND(active); + + server_relay = p_enabled; +} + +bool NetworkedMultiplayerENet::is_server_relay_enabled() const { + return server_relay; +} + void NetworkedMultiplayerENet::_bind_methods() { ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0)); @@ -843,11 +867,14 @@ void NetworkedMultiplayerENet::_bind_methods() { ClassDB::bind_method(D_METHOD("get_channel_count"), &NetworkedMultiplayerENet::get_channel_count); ClassDB::bind_method(D_METHOD("set_always_ordered", "ordered"), &NetworkedMultiplayerENet::set_always_ordered); ClassDB::bind_method(D_METHOD("is_always_ordered"), &NetworkedMultiplayerENet::is_always_ordered); + ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &NetworkedMultiplayerENet::set_server_relay_enabled); + ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &NetworkedMultiplayerENet::is_server_relay_enabled); ADD_PROPERTY(PropertyInfo(Variant::INT, "compression_mode", PROPERTY_HINT_ENUM, "None,Range Coder,FastLZ,ZLib,ZStd"), "set_compression_mode", "get_compression_mode"); ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_channel"), "set_transfer_channel", "get_transfer_channel"); ADD_PROPERTY(PropertyInfo(Variant::INT, "channel_count"), "set_channel_count", "get_channel_count"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "always_ordered"), "set_always_ordered", "is_always_ordered"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled"); BIND_ENUM_CONSTANT(COMPRESS_NONE); BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER); @@ -861,6 +888,7 @@ NetworkedMultiplayerENet::NetworkedMultiplayerENet() { active = false; server = false; refuse_connections = false; + server_relay = true; unique_id = 0; target_peer = 0; current_packet.packet = NULL; @@ -880,7 +908,9 @@ NetworkedMultiplayerENet::NetworkedMultiplayerENet() { NetworkedMultiplayerENet::~NetworkedMultiplayerENet() { - close_connection(); + if (active) { + close_connection(); + } } // Sets IP for ENet to bind when using create_server or create_client diff --git a/modules/enet/networked_multiplayer_enet.h b/modules/enet/networked_multiplayer_enet.h index 957d0830cb..1c4c15ae7b 100644 --- a/modules/enet/networked_multiplayer_enet.h +++ b/modules/enet/networked_multiplayer_enet.h @@ -38,7 +38,8 @@ class NetworkedMultiplayerENet : public NetworkedMultiplayerPeer { - GDCLASS(NetworkedMultiplayerENet, NetworkedMultiplayerPeer) + GDCLASS(NetworkedMultiplayerENet, NetworkedMultiplayerPeer); + public: enum CompressionMode { COMPRESS_NONE, @@ -77,6 +78,7 @@ private: ENetHost *host; bool refuse_connections; + bool server_relay; ConnectionStatus connection_status; @@ -157,6 +159,8 @@ public: int get_channel_count() const; void set_always_ordered(bool p_ordered); bool is_always_ordered() const; + void set_server_relay_enabled(bool p_enabled); + bool is_server_relay_enabled() const; NetworkedMultiplayerENet(); ~NetworkedMultiplayerENet(); diff --git a/modules/etc/SCsub b/modules/etc/SCsub index 6e963ef766..1742d3534f 100644 --- a/modules/etc/SCsub +++ b/modules/etc/SCsub @@ -27,11 +27,7 @@ thirdparty_sources = [ ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] -env_etc.Append(CPPPATH=[thirdparty_dir]) - -# upstream uses c++11 -if not env.msvc: - env_etc.Append(CCFLAGS="-std=c++11") +env_etc.Prepend(CPPPATH=[thirdparty_dir]) env_thirdparty = env_etc.Clone() env_thirdparty.disable_warnings() diff --git a/modules/etc/image_etc.cpp b/modules/etc/image_etc.cpp index 5410d367db..f0cbf6ae28 100644 --- a/modules/etc/image_etc.cpp +++ b/modules/etc/image_etc.cpp @@ -115,7 +115,8 @@ static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_f case Image::FORMAT_RGBA5551: { detected_channels = Image::DETECTED_RGBA; } break; - default: {} + default: { + } } } @@ -167,6 +168,7 @@ static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_f } PoolVector<uint8_t>::Read r = img->get_data().read(); + ERR_FAIL_COND(!r.ptr()); unsigned int target_size = Image::get_image_data_size(imgw, imgh, etc_format, p_img->has_mipmaps()); int mmc = 1 + (p_img->has_mipmaps() ? Image::get_image_required_mipmaps(imgw, imgh, etc_format) : 0); diff --git a/modules/etc/texture_loader_pkm.cpp b/modules/etc/texture_loader_pkm.cpp index f302834222..da6da74025 100644 --- a/modules/etc/texture_loader_pkm.cpp +++ b/modules/etc/texture_loader_pkm.cpp @@ -56,17 +56,14 @@ RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path, if (r_error) *r_error = ERR_FILE_CORRUPT; - ERR_EXPLAIN("Unable to open PKM texture file: " + p_path); - ERR_FAIL_COND_V(err != OK, RES()); + ERR_FAIL_COND_V_MSG(err != OK, RES(), "Unable to open PKM texture file '" + p_path + "'."); // big endian f->set_endian_swap(true); ETC1Header h; - ERR_EXPLAIN("Invalid or Unsupported PKM texture file: " + p_path); f->get_buffer((uint8_t *)&h.tag, sizeof(h.tag)); - if (strncmp(h.tag, "PKM 10", sizeof(h.tag))) - ERR_FAIL_V(RES()); + ERR_FAIL_COND_V_MSG(strncmp(h.tag, "PKM 10", sizeof(h.tag)), RES(), "Invalid or unsupported PKM texture file '" + p_path + "'."); h.format = f->get_16(); h.texWidth = f->get_16(); @@ -80,7 +77,7 @@ RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path, src_data.resize(size); PoolVector<uint8_t>::Write wb = src_data.write(); f->get_buffer(wb.ptr(), size); - wb = PoolVector<uint8_t>::Write(); + wb.release(); int mipmaps = h.format; int width = h.origWidth; @@ -94,6 +91,8 @@ RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path, if (r_error) *r_error = OK; + f->close(); + memdelete(f); return texture; } 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/freetype/SCsub b/modules/freetype/SCsub index 3e2068b8db..8f4a8de895 100644 --- a/modules/freetype/SCsub +++ b/modules/freetype/SCsub @@ -12,7 +12,6 @@ if env['builtin_freetype']: thirdparty_dir = "#thirdparty/freetype/" thirdparty_sources = [ "src/autofit/autofit.c", - "src/base/ftapi.c", "src/base/ftbase.c", "src/base/ftbbox.c", "src/base/ftbdf.c", @@ -62,24 +61,27 @@ if env['builtin_freetype']: # Globally too, as freetype is used in scene (see bottom) env.Append(CCFLAGS=['/FI', '"modules/freetype/uwpdef.h"']) - sfnt = thirdparty_dir + 'src/sfnt/sfnt.c' - if env['platform'] == 'javascript': - # Forcibly undefine this macro so SIMD is not used in this file, - # since currently unsupported in WASM - sfnt = env_freetype.Object(sfnt, CPPFLAGS=['-U__OPTIMIZE__']) - thirdparty_sources += [sfnt] - - env_freetype.Append(CPPPATH=[thirdparty_dir + "/include"]) + env_freetype.Prepend(CPPPATH=[thirdparty_dir + "/include"]) # Also needed in main env for scene/ - env.Append(CPPPATH=[thirdparty_dir + "/include"]) + env.Prepend(CPPPATH=[thirdparty_dir + "/include"]) - env_freetype.Append(CCFLAGS=['-DFT2_BUILD_LIBRARY', '-DFT_CONFIG_OPTION_USE_PNG']) - if (env['target'] != 'release'): - env_freetype.Append(CCFLAGS=['-DZLIB_DEBUG']) + env_freetype.Append(CPPDEFINES=['FT2_BUILD_LIBRARY', 'FT_CONFIG_OPTION_USE_PNG']) + if (env['target'] == 'debug'): + env_freetype.Append(CPPDEFINES=['ZLIB_DEBUG']) # Also requires libpng headers if env['builtin_libpng']: - env_freetype.Append(CPPPATH=["#thirdparty/libpng"]) + env_freetype.Prepend(CPPPATH=["#thirdparty/libpng"]) + + sfnt = thirdparty_dir + 'src/sfnt/sfnt.c' + # Must be done after all CPPDEFINES are being set so we can copy them. + if env['platform'] == 'javascript': + # Forcibly undefine this macro so SIMD is not used in this file, + # since currently unsupported in WASM + tmp_env = env_freetype.Clone() + tmp_env.Append(CPPFLAGS=['-U__OPTIMIZE__']) + sfnt = tmp_env.Object(sfnt) + thirdparty_sources += [sfnt] env_thirdparty = env_freetype.Clone() env_thirdparty.disable_warnings() @@ -101,4 +103,4 @@ if env['builtin_freetype']: # Godot source files env_freetype.add_source_files(env.modules_sources, "*.cpp") # Used in scene/, needs to be in main env -env.Append(CCFLAGS=['-DFREETYPE_ENABLED']) +env.Append(CPPDEFINES=['FREETYPE_ENABLED']) diff --git a/modules/gdnative/SCsub b/modules/gdnative/SCsub index 235f0b97bb..0cdd585558 100644 --- a/modules/gdnative/SCsub +++ b/modules/gdnative/SCsub @@ -12,7 +12,7 @@ env_gdnative.add_source_files(env.modules_sources, "nativescript/*.cpp") env_gdnative.add_source_files(env.modules_sources, "gdnative_library_singleton_editor.cpp") env_gdnative.add_source_files(env.modules_sources, "gdnative_library_editor_plugin.cpp") -env_gdnative.Append(CPPPATH=['#modules/gdnative/include/']) +env_gdnative.Prepend(CPPPATH=['#modules/gdnative/include/']) Export('env_gdnative') @@ -36,7 +36,7 @@ if ARGUMENTS.get('gdnative_wrapper', False): gensource, = env_gdnative.CommandNoCache('gdnative_wrapper_code.gen.cpp', 'gdnative_api.json', run_in_subprocess(gdnative_builders.build_gdnative_wrapper_code)) gd_wrapper_env = env.Clone() - gd_wrapper_env.Append(CPPPATH=['#modules/gdnative/include/']) + gd_wrapper_env.Prepend(CPPPATH=['#modules/gdnative/include/']) if gd_wrapper_env['use_lto']: if not env.msvc: 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 8c602e0cba..bd6eb575d0 100644 --- a/modules/gdnative/arvr/arvr_interface_gdnative.cpp +++ b/modules/gdnative/arvr/arvr_interface_gdnative.cpp @@ -33,9 +33,13 @@ #include "servers/arvr/arvr_positional_tracker.h" #include "servers/visual/visual_server_globals.h" +void ARVRInterfaceGDNative::_bind_methods() { + ADD_PROPERTY_DEFAULT("interface_is_initialized", false); + ADD_PROPERTY_DEFAULT("ar_is_anchor_detection_enabled", false); +} + ARVRInterfaceGDNative::ARVRInterfaceGDNative() { - // testing - printf("Construct gdnative interface\n"); + print_verbose("Construct gdnative interface\n"); // we won't have our data pointer until our library gets set data = NULL; @@ -44,9 +48,9 @@ ARVRInterfaceGDNative::ARVRInterfaceGDNative() { } ARVRInterfaceGDNative::~ARVRInterfaceGDNative() { - printf("Destruct gdnative interface\n"); + print_verbose("Destruct gdnative interface\n"); - if (is_initialized()) { + if (interface != NULL && is_initialized()) { uninitialize(); }; @@ -99,13 +103,10 @@ int ARVRInterfaceGDNative::get_capabilities() const { } bool ARVRInterfaceGDNative::get_anchor_detection_is_enabled() const { - bool enabled; ERR_FAIL_COND_V(interface == NULL, false); - enabled = interface->get_anchor_detection_is_enabled(data); - - return enabled; + return interface->get_anchor_detection_is_enabled(data); } void ARVRInterfaceGDNative::set_anchor_detection_is_enabled(bool p_enable) { @@ -115,6 +116,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; @@ -126,21 +138,16 @@ bool ARVRInterfaceGDNative::is_stereo() { } bool ARVRInterfaceGDNative::is_initialized() const { - bool initialized; ERR_FAIL_COND_V(interface == NULL, false); - initialized = interface->is_initialized(data); - - return initialized; + return interface->is_initialized(data); } bool ARVRInterfaceGDNative::initialize() { - bool initialized; - ERR_FAIL_COND_V(interface == NULL, false); - initialized = interface->initialize(data); + bool initialized = interface->initialize(data); if (initialized) { // if we successfully initialize our interface and we don't have a primary interface yet, this becomes our primary interface @@ -222,6 +229,15 @@ void ARVRInterfaceGDNative::process() { interface->process(data); } +void ARVRInterfaceGDNative::notification(int p_what) { + ERR_FAIL_COND(interface == NULL); + + // this is only available in interfaces that implement 1.1 or later + if ((interface->version.major > 1) || ((interface->version.major == 1) && (interface->version.minor > 0))) { + interface->notification(data, p_what); + } +} + ///////////////////////////////////////////////////////////////////////////////////// // some helper callbacks @@ -229,8 +245,7 @@ extern "C" { void GDAPI godot_arvr_register_interface(const godot_arvr_interface_gdnative *p_interface) { // If our major version is 0 or bigger then 10, we're likely looking at our constructor pointer from an older plugin - ERR_EXPLAINC("GDNative ARVR interfaces build for Godot 3.0 are not supported"); - ERR_FAIL_COND((p_interface->version.major == 0) || (p_interface->version.major > 10)); + ERR_FAIL_COND_MSG((p_interface->version.major == 0) || (p_interface->version.major > 10), "GDNative ARVR interfaces build for Godot 3.0 are not supported."); Ref<ARVRInterfaceGDNative> new_interface; new_interface.instance(); diff --git a/modules/gdnative/arvr/arvr_interface_gdnative.h b/modules/gdnative/arvr/arvr_interface_gdnative.h index 3f966ece51..ab7090876a 100644 --- a/modules/gdnative/arvr/arvr_interface_gdnative.h +++ b/modules/gdnative/arvr/arvr_interface_gdnative.h @@ -41,7 +41,7 @@ */ class ARVRInterfaceGDNative : public ARVRInterface { - GDCLASS(ARVRInterfaceGDNative, ARVRInterface) + GDCLASS(ARVRInterfaceGDNative, ARVRInterface); void cleanup(); @@ -49,6 +49,8 @@ protected: const godot_arvr_interface_gdnative *interface; void *data; + static void _bind_methods(); + public: /** general interface information **/ ARVRInterfaceGDNative(); @@ -66,6 +68,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(); @@ -82,6 +85,7 @@ public: virtual void commit_for_eye(ARVRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect); virtual void process(); + virtual void notification(int p_what); }; #endif // ARVR_INTERFACE_GDNATIVE_H diff --git a/modules/gdnative/config.py b/modules/gdnative/config.py index a36e76287a..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,9 +14,10 @@ def get_doc_classes(): "NativeScript", "PacketPeerGDNative", "PluginScript", - "ResourceFormatLoaderVideoStreamGDNative", "StreamPeerGDNative", "VideoStreamGDNative", + "WebRTCPeerConnectionGDNative", + "WebRTCDataChannelGDNative", ] def get_doc_path(): diff --git a/modules/stb_vorbis/doc_classes/ResourceImporterOGGVorbis.xml b/modules/gdnative/doc_classes/@NativeScript.xml index ade485e717..cb5de198ac 100644 --- a/modules/stb_vorbis/doc_classes/ResourceImporterOGGVorbis.xml +++ b/modules/gdnative/doc_classes/@NativeScript.xml @@ -1,13 +1,11 @@ <?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> </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml b/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml index afb014d608..47c2ee3358 100644 --- a/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml +++ b/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml @@ -1,15 +1,13 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="ARVRInterfaceGDNative" inherits="ARVRInterface" category="Core" version="3.2"> <brief_description> - GDNative wrapper for an ARVR interface + GDNative wrapper for an ARVR interface. </brief_description> <description> - This is a wrapper class for GDNative implementations of the ARVR interface. To use a GDNative ARVR interface simply instantiate this object and set your GDNative library containing the ARVR interface implementation. + This is a wrapper class for GDNative implementations of the ARVR interface. To use a GDNative ARVR interface, simply instantiate this object and set your GDNative library containing the ARVR interface implementation. </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/gdnative/doc_classes/GDNative.xml b/modules/gdnative/doc_classes/GDNative.xml index e5a59aad07..8750ddc56d 100644 --- a/modules/gdnative/doc_classes/GDNative.xml +++ b/modules/gdnative/doc_classes/GDNative.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="call_native"> <return type="Variant"> diff --git a/modules/gdnative/doc_classes/GDNativeLibrary.xml b/modules/gdnative/doc_classes/GDNativeLibrary.xml index ba5278d440..aa48ab44f2 100644 --- a/modules/gdnative/doc_classes/GDNativeLibrary.xml +++ b/modules/gdnative/doc_classes/GDNativeLibrary.xml @@ -1,37 +1,50 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GDNativeLibrary" inherits="Resource" category="Core" version="3.2"> <brief_description> + An external library containing functions or script classes to use in Godot. </brief_description> <description> + A GDNative library can implement [NativeScript]s, global functions to call with the [GDNative] class, or low-level engine extensions through interfaces such as [ARVRInterfaceGDNative]. The library must be compiled for each platform and architecture that the project will run on. </description> <tutorials> + <link>https://docs.godotengine.org/en/latest/tutorials/plugins/gdnative/gdnative-c-example.html</link> + <link>https://docs.godotengine.org/en/latest/tutorials/plugins/gdnative/gdnative-cpp-example.html</link> </tutorials> - <demos> - </demos> <methods> <method name="get_current_dependencies" qualifiers="const"> <return type="PoolStringArray"> </return> <description> + Returns paths to all dependency libraries for the current platform and architecture. </description> </method> <method name="get_current_library_path" qualifiers="const"> <return type="String"> </return> <description> + Returns the path to the dynamic library file for the current platform and architecture. </description> </method> </methods> <members> <member name="config_file" type="ConfigFile" setter="set_config_file" getter="get_config_file"> + This resource in INI-style [ConfigFile] format, as in [code].gdnlib[/code] files. </member> - <member name="load_once" type="bool" setter="set_load_once" getter="should_load_once"> + <member name="load_once" type="bool" setter="set_load_once" getter="should_load_once" default="true"> + If [code]true[/code], Godot loads only one copy of the library and each script that references the library will share static data like static or global variables. + If [code]false[/code], Godot loads a separate copy of the library into memory for each script that references it. </member> - <member name="reloadable" type="bool" setter="set_reloadable" getter="is_reloadable"> + <member name="reloadable" type="bool" setter="set_reloadable" getter="is_reloadable" default="true"> + If [code]true[/code], the editor will temporarily unload the library whenever the user switches away from the editor window, allowing the user to recompile the library without restarting Godot. + [b]Note:[/b] If the library defines tool scripts that run inside the editor, [code]reloadable[/code] must be [code]false[/code]. Otherwise, the editor will attempt to unload the tool scripts while they're in use and crash. </member> - <member name="singleton" type="bool" setter="set_singleton" getter="is_singleton"> + <member name="singleton" type="bool" setter="set_singleton" getter="is_singleton" default="false"> + If [code]true[/code], Godot loads the library at startup rather than the first time a script uses the library, calling [code]{prefix}gdnative_singleton[/code] after initializing the library (where [code]{prefix}[/code] is the value of [member symbol_prefix]). The library remains loaded as long as Godot is running. + [b]Note:[/b] A singleton library cannot be [member reloadable]. </member> - <member name="symbol_prefix" type="String" setter="set_symbol_prefix" getter="get_symbol_prefix"> + <member name="symbol_prefix" type="String" setter="set_symbol_prefix" getter="get_symbol_prefix" default=""godot_""> + The prefix this library's entry point functions begin with. For example, a GDNativeLibrary would declare its [code]gdnative_init[/code] function as [code]godot_gdnative_init[/code] by default. + On platforms that require statically linking libraries (currently only iOS), each library must have a different [code]symbol_prefix[/code]. </member> </members> <constants> diff --git a/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml b/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml index ba481a6d6e..b9a01672a6 100644 --- a/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml +++ b/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/gdnative/doc_classes/NativeScript.xml b/modules/gdnative/doc_classes/NativeScript.xml index c50f9eee22..dc735546e3 100644 --- a/modules/gdnative/doc_classes/NativeScript.xml +++ b/modules/gdnative/doc_classes/NativeScript.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_class_documentation" qualifiers="const"> <return type="String"> @@ -44,7 +42,7 @@ </description> </method> <method name="new" qualifiers="vararg"> - <return type="Object"> + <return type="Variant"> </return> <description> Constructs a new object of the base type with a script of this type already attached. @@ -53,13 +51,13 @@ </method> </methods> <members> - <member name="class_name" type="String" setter="set_class_name" getter="get_class_name"> + <member name="class_name" type="String" setter="set_class_name" getter="get_class_name" default=""""> </member> <member name="library" type="GDNativeLibrary" setter="set_library" getter="get_library"> </member> - <member name="script_class_icon_path" type="String" setter="set_script_class_icon_path" getter="get_script_class_icon_path"> + <member name="script_class_icon_path" type="String" setter="set_script_class_icon_path" getter="get_script_class_icon_path" default=""""> </member> - <member name="script_class_name" type="String" setter="set_script_class_name" getter="get_script_class_name"> + <member name="script_class_name" type="String" setter="set_script_class_name" getter="get_script_class_name" default=""""> </member> </members> <constants> diff --git a/modules/gdnative/doc_classes/PacketPeerGDNative.xml b/modules/gdnative/doc_classes/PacketPeerGDNative.xml index f4d7d22f5b..acfb597cff 100644 --- a/modules/gdnative/doc_classes/PacketPeerGDNative.xml +++ b/modules/gdnative/doc_classes/PacketPeerGDNative.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/gdnative/doc_classes/PluginScript.xml b/modules/gdnative/doc_classes/PluginScript.xml index 8510708124..33b5f02bd4 100644 --- a/modules/gdnative/doc_classes/PluginScript.xml +++ b/modules/gdnative/doc_classes/PluginScript.xml @@ -6,11 +6,9 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="new" qualifiers="vararg"> - <return type="Object"> + <return type="Variant"> </return> <description> Returns a new instance of the script. diff --git a/modules/gdnative/doc_classes/StreamPeerGDNative.xml b/modules/gdnative/doc_classes/StreamPeerGDNative.xml index eddebf4889..f7e0d76fdb 100644 --- a/modules/gdnative/doc_classes/StreamPeerGDNative.xml +++ b/modules/gdnative/doc_classes/StreamPeerGDNative.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/gdnative/doc_classes/VideoStreamGDNative.xml b/modules/gdnative/doc_classes/VideoStreamGDNative.xml index d5c5ed7ccf..ed7678b7be 100644 --- a/modules/gdnative/doc_classes/VideoStreamGDNative.xml +++ b/modules/gdnative/doc_classes/VideoStreamGDNative.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_file"> <return type="String"> diff --git a/modules/gdnative/doc_classes/ResourceFormatLoaderVideoStreamGDNative.xml b/modules/gdnative/doc_classes/WebRTCDataChannelGDNative.xml index 8e7f4698ff..ac18ec6020 100644 --- a/modules/gdnative/doc_classes/ResourceFormatLoaderVideoStreamGDNative.xml +++ b/modules/gdnative/doc_classes/WebRTCDataChannelGDNative.xml @@ -1,13 +1,11 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="ResourceFormatLoaderVideoStreamGDNative" inherits="ResourceFormatLoader" category="Core" version="3.2"> +<class name="WebRTCDataChannelGDNative" inherits="WebRTCDataChannel" category="Core" version="3.2"> <brief_description> </brief_description> <description> </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/gdnative/doc_classes/WebRTCPeerConnectionGDNative.xml b/modules/gdnative/doc_classes/WebRTCPeerConnectionGDNative.xml new file mode 100644 index 0000000000..44cb8e5db8 --- /dev/null +++ b/modules/gdnative/doc_classes/WebRTCPeerConnectionGDNative.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="WebRTCPeerConnectionGDNative" inherits="WebRTCPeerConnection" category="Core" version="3.2"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <constants> + </constants> +</class> diff --git a/modules/gdnative/gdnative.cpp b/modules/gdnative/gdnative.cpp index e8278825bc..ee9e71d4a0 100644 --- a/modules/gdnative/gdnative.cpp +++ b/modules/gdnative/gdnative.cpp @@ -48,7 +48,7 @@ static const bool default_reloadable = true; // Defined in gdnative_api_struct.gen.cpp extern const godot_gdnative_core_api_struct api_struct; -Map<String, Vector<Ref<GDNative> > > *GDNativeLibrary::loaded_libraries = NULL; +Map<String, Vector<Ref<GDNative> > > GDNativeLibrary::loaded_libraries; GDNativeLibrary::GDNativeLibrary() { config_file.instance(); @@ -57,10 +57,6 @@ GDNativeLibrary::GDNativeLibrary() { load_once = default_load_once; singleton = default_singleton; reloadable = default_reloadable; - - if (GDNativeLibrary::loaded_libraries == NULL) { - GDNativeLibrary::loaded_libraries = memnew((Map<String, Vector<Ref<GDNative> > >)); - } } GDNativeLibrary::~GDNativeLibrary() { @@ -243,7 +239,7 @@ void GDNativeLibrary::_bind_methods() { ClassDB::bind_method(D_METHOD("set_symbol_prefix", "symbol_prefix"), &GDNativeLibrary::set_symbol_prefix); ClassDB::bind_method(D_METHOD("set_reloadable", "reloadable"), &GDNativeLibrary::set_reloadable); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "config_file", PROPERTY_HINT_RESOURCE_TYPE, "ConfigFile"), "set_config_file", "get_config_file"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "config_file", PROPERTY_HINT_RESOURCE_TYPE, "ConfigFile", 0), "set_config_file", "get_config_file"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "load_once"), "set_load_once", "should_load_once"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "singleton"), "set_singleton", "is_singleton"); @@ -272,8 +268,7 @@ void GDNative::_bind_methods() { } void GDNative::set_library(Ref<GDNativeLibrary> p_library) { - ERR_EXPLAIN("Tried to change library of GDNative when it is already set"); - ERR_FAIL_COND(library.is_valid()); + ERR_FAIL_COND_MSG(library.is_valid(), "Tried to change library of GDNative when it is already set."); library = p_library; } @@ -318,10 +313,10 @@ bool GDNative::initialize() { #endif if (library->should_load_once()) { - if (GDNativeLibrary::loaded_libraries->has(lib_path)) { + if (GDNativeLibrary::loaded_libraries.has(lib_path)) { // already loaded. Don't load again. // copy some of the stuff instead - this->native_handle = (*GDNativeLibrary::loaded_libraries)[lib_path][0]->native_handle; + this->native_handle = GDNativeLibrary::loaded_libraries[lib_path][0]->native_handle; initialized = true; return true; } @@ -344,7 +339,7 @@ bool GDNative::initialize() { if (err || !library_init) { OS::get_singleton()->close_dynamic_library(native_handle); native_handle = NULL; - ERR_PRINT("Failed to obtain godot_gdnative_init symbol"); + ERR_PRINTS("Failed to obtain " + library->get_symbol_prefix() + "gdnative_init symbol"); return false; } @@ -377,11 +372,11 @@ bool GDNative::initialize() { initialized = true; - if (library->should_load_once() && !GDNativeLibrary::loaded_libraries->has(lib_path)) { + if (library->should_load_once() && !GDNativeLibrary::loaded_libraries.has(lib_path)) { Vector<Ref<GDNative> > gdnatives; gdnatives.resize(1); gdnatives.write[0] = Ref<GDNative>(this); - GDNativeLibrary::loaded_libraries->insert(lib_path, gdnatives); + GDNativeLibrary::loaded_libraries.insert(lib_path, gdnatives); } return true; @@ -395,7 +390,7 @@ bool GDNative::terminate() { } if (library->should_load_once()) { - Vector<Ref<GDNative> > *gdnatives = &(*GDNativeLibrary::loaded_libraries)[library->get_current_library_path()]; + Vector<Ref<GDNative> > *gdnatives = &GDNativeLibrary::loaded_libraries[library->get_current_library_path()]; if (gdnatives->size() > 1) { // there are other GDNative's still using this library, so we actually don't terminate gdnatives->erase(Ref<GDNative>(this)); @@ -404,8 +399,8 @@ bool GDNative::terminate() { } else if (gdnatives->size() == 1) { // we're the last one, terminate! gdnatives->clear(); - // wew this looks scary, but all it does is remove the entry completely - GDNativeLibrary::loaded_libraries->erase(GDNativeLibrary::loaded_libraries->find(library->get_current_library_path())); + // whew this looks scary, but all it does is remove the entry completely + GDNativeLibrary::loaded_libraries.erase(GDNativeLibrary::loaded_libraries.find(library->get_current_library_path())); } } diff --git a/modules/gdnative/gdnative.h b/modules/gdnative/gdnative.h index 492dc5beaa..408af26753 100644 --- a/modules/gdnative/gdnative.h +++ b/modules/gdnative/gdnative.h @@ -45,9 +45,9 @@ class GDNativeLibraryResourceLoader; class GDNative; class GDNativeLibrary : public Resource { - GDCLASS(GDNativeLibrary, Resource) + GDCLASS(GDNativeLibrary, Resource); - static Map<String, Vector<Ref<GDNative> > > *loaded_libraries; + static Map<String, Vector<Ref<GDNative> > > loaded_libraries; friend class GDNativeLibraryResourceLoader; friend class GDNative; @@ -99,16 +99,20 @@ public: } _FORCE_INLINE_ void set_load_once(bool p_load_once) { + config_file->set_value("general", "load_once", p_load_once); load_once = p_load_once; } _FORCE_INLINE_ void set_singleton(bool p_singleton) { + config_file->set_value("general", "singleton", p_singleton); singleton = p_singleton; } _FORCE_INLINE_ void set_symbol_prefix(String p_symbol_prefix) { + config_file->set_value("general", "symbol_prefix", p_symbol_prefix); symbol_prefix = p_symbol_prefix; } _FORCE_INLINE_ void set_reloadable(bool p_reloadable) { + config_file->set_value("general", "reloadable", p_reloadable); reloadable = p_reloadable; } @@ -133,7 +137,7 @@ struct GDNativeCallRegistry { }; class GDNative : public Reference { - GDCLASS(GDNative, Reference) + GDCLASS(GDNative, Reference); Ref<GDNativeLibrary> library; @@ -161,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; @@ -170,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/array.cpp b/modules/gdnative/gdnative/array.cpp index 6849ff03d7..e97a75cca8 100644 --- a/modules/gdnative/gdnative/array.cpp +++ b/modules/gdnative/gdnative/array.cpp @@ -305,13 +305,13 @@ void GDAPI godot_array_sort_custom(godot_array *p_self, godot_object *p_obj, con godot_int GDAPI godot_array_bsearch(godot_array *p_self, const godot_variant *p_value, const godot_bool p_before) { Array *self = (Array *)p_self; - return self->bsearch((const Variant *)p_value, p_before); + return self->bsearch(*(const Variant *)p_value, p_before); } godot_int GDAPI godot_array_bsearch_custom(godot_array *p_self, const godot_variant *p_value, godot_object *p_obj, const godot_string *p_func, const godot_bool p_before) { Array *self = (Array *)p_self; const String *func = (const String *)p_func; - return self->bsearch_custom((const Variant *)p_value, (Object *)p_obj, *func, p_before); + return self->bsearch_custom(*(const Variant *)p_value, (Object *)p_obj, *func, p_before); } void GDAPI godot_array_destroy(godot_array *p_self) { @@ -327,6 +327,15 @@ godot_array GDAPI godot_array_duplicate(const godot_array *p_self, const godot_b return res; } +godot_array GDAPI godot_array_slice(const godot_array *p_self, const godot_int p_begin, const godot_int p_end, const godot_int p_step, const godot_bool p_deep) { + const Array *self = (const Array *)p_self; + godot_array res; + Array *val = (Array *)&res; + memnew_placement(val, Array); + *val = self->slice(p_begin, p_end, p_step, p_deep); + return res; +} + godot_variant GDAPI godot_array_max(const godot_array *p_self) { const Array *self = (const Array *)p_self; godot_variant v; diff --git a/modules/gdnative/gdnative/dictionary.cpp b/modules/gdnative/gdnative/dictionary.cpp index 2c6c9e2de2..fff3fc3625 100644 --- a/modules/gdnative/gdnative/dictionary.cpp +++ b/modules/gdnative/gdnative/dictionary.cpp @@ -55,6 +55,15 @@ void GDAPI godot_dictionary_destroy(godot_dictionary *p_self) { self->~Dictionary(); } +godot_dictionary GDAPI godot_dictionary_duplicate(const godot_dictionary *p_self, const godot_bool p_deep) { + const Dictionary *self = (const Dictionary *)p_self; + godot_dictionary res; + Dictionary *val = (Dictionary *)&res; + memnew_placement(val, Dictionary); + *val = self->duplicate(p_deep); + return res; +} + godot_int GDAPI godot_dictionary_size(const godot_dictionary *p_self) { const Dictionary *self = (const Dictionary *)p_self; return self->size(); diff --git a/modules/gdnative/gdnative/pool_arrays.cpp b/modules/gdnative/gdnative/pool_arrays.cpp index 74c540ca14..23791af67e 100644 --- a/modules/gdnative/gdnative/pool_arrays.cpp +++ b/modules/gdnative/gdnative/pool_arrays.cpp @@ -129,6 +129,11 @@ godot_int GDAPI godot_pool_byte_array_size(const godot_pool_byte_array *p_self) return self->size(); } +godot_bool GDAPI godot_pool_byte_array_empty(const godot_pool_byte_array *p_self) { + const PoolVector<uint8_t> *self = (const PoolVector<uint8_t> *)p_self; + return self->empty(); +} + void GDAPI godot_pool_byte_array_destroy(godot_pool_byte_array *p_self) { ((PoolVector<uint8_t> *)p_self)->~PoolVector(); } @@ -218,6 +223,11 @@ godot_int GDAPI godot_pool_int_array_size(const godot_pool_int_array *p_self) { return self->size(); } +godot_bool GDAPI godot_pool_int_array_empty(const godot_pool_int_array *p_self) { + const PoolVector<godot_int> *self = (const PoolVector<godot_int> *)p_self; + return self->empty(); +} + void GDAPI godot_pool_int_array_destroy(godot_pool_int_array *p_self) { ((PoolVector<godot_int> *)p_self)->~PoolVector(); } @@ -307,6 +317,11 @@ godot_int GDAPI godot_pool_real_array_size(const godot_pool_real_array *p_self) return self->size(); } +godot_bool GDAPI godot_pool_real_array_empty(const godot_pool_real_array *p_self) { + const PoolVector<godot_real> *self = (const PoolVector<godot_real> *)p_self; + return self->empty(); +} + void GDAPI godot_pool_real_array_destroy(godot_pool_real_array *p_self) { ((PoolVector<godot_real> *)p_self)->~PoolVector(); } @@ -404,6 +419,11 @@ godot_int GDAPI godot_pool_string_array_size(const godot_pool_string_array *p_se return self->size(); } +godot_bool GDAPI godot_pool_string_array_empty(const godot_pool_string_array *p_self) { + const PoolVector<String> *self = (const PoolVector<String> *)p_self; + return self->empty(); +} + void GDAPI godot_pool_string_array_destroy(godot_pool_string_array *p_self) { ((PoolVector<String> *)p_self)->~PoolVector(); } @@ -500,6 +520,11 @@ godot_int GDAPI godot_pool_vector2_array_size(const godot_pool_vector2_array *p_ return self->size(); } +godot_bool GDAPI godot_pool_vector2_array_empty(const godot_pool_vector2_array *p_self) { + const PoolVector<Vector2> *self = (const PoolVector<Vector2> *)p_self; + return self->empty(); +} + void GDAPI godot_pool_vector2_array_destroy(godot_pool_vector2_array *p_self) { ((PoolVector<Vector2> *)p_self)->~PoolVector(); } @@ -596,6 +621,11 @@ godot_int GDAPI godot_pool_vector3_array_size(const godot_pool_vector3_array *p_ return self->size(); } +godot_bool GDAPI godot_pool_vector3_array_empty(const godot_pool_vector3_array *p_self) { + const PoolVector<Vector3> *self = (const PoolVector<Vector3> *)p_self; + return self->empty(); +} + void GDAPI godot_pool_vector3_array_destroy(godot_pool_vector3_array *p_self) { ((PoolVector<Vector3> *)p_self)->~PoolVector(); } @@ -692,6 +722,11 @@ godot_int GDAPI godot_pool_color_array_size(const godot_pool_color_array *p_self return self->size(); } +godot_bool GDAPI godot_pool_color_array_empty(const godot_pool_color_array *p_self) { + const PoolVector<Color> *self = (const PoolVector<Color> *)p_self; + return self->empty(); +} + void GDAPI godot_pool_color_array_destroy(godot_pool_color_array *p_self) { ((PoolVector<Color> *)p_self)->~PoolVector(); } diff --git a/modules/gdnative/gdnative/string.cpp b/modules/gdnative/gdnative/string.cpp index 913c57eb56..9086121940 100644 --- a/modules/gdnative/gdnative/string.cpp +++ b/modules/gdnative/gdnative/string.cpp @@ -186,6 +186,20 @@ godot_bool GDAPI godot_string_ends_with(const godot_string *p_self, const godot_ return self->ends_with(*string); } +godot_int GDAPI godot_string_count(const godot_string *p_self, godot_string p_what, godot_int p_from, godot_int p_to) { + const String *self = (const String *)p_self; + String *what = (String *)&p_what; + + return self->count(*what, p_from, p_to); +} + +godot_int GDAPI godot_string_countn(const godot_string *p_self, godot_string p_what, godot_int p_from, godot_int p_to) { + const String *self = (const String *)p_self; + String *what = (String *)&p_what; + + return self->countn(*what, p_from, p_to); +} + godot_int GDAPI godot_string_find(const godot_string *p_self, godot_string p_what) { const String *self = (const String *)p_self; String *what = (String *)&p_what; diff --git a/modules/gdnative/gdnative/variant.cpp b/modules/gdnative/gdnative/variant.cpp index 8f0d5a2db4..ac4d5a86b2 100644 --- a/modules/gdnative/gdnative/variant.cpp +++ b/modules/gdnative/gdnative/variant.cpp @@ -518,7 +518,7 @@ void GDAPI godot_variant_evaluate(godot_variant_operator p_op, const godot_varia const Variant *a = (const Variant *)p_a; const Variant *b = (const Variant *)p_b; Variant *ret = (Variant *)r_ret; - Variant::evaluate(op, a, b, *ret, *r_valid); + Variant::evaluate(op, *a, *b, *ret, *r_valid); } #ifdef __cplusplus diff --git a/modules/gdnative/gdnative/vector2.cpp b/modules/gdnative/gdnative/vector2.cpp index 8fa29580d6..d82f2c692d 100644 --- a/modules/gdnative/gdnative/vector2.cpp +++ b/modules/gdnative/gdnative/vector2.cpp @@ -77,6 +77,14 @@ godot_bool GDAPI godot_vector2_is_normalized(const godot_vector2 *p_self) { return self->is_normalized(); } +godot_vector2 GDAPI godot_vector2_direction_to(const godot_vector2 *p_self, const godot_vector2 *p_to) { + godot_vector2 dest; + const Vector2 *self = (const Vector2 *)p_self; + const Vector2 *to = (const Vector2 *)p_to; + *((Vector2 *)&dest) = self->direction_to(*to); + return dest; +} + godot_real GDAPI godot_vector2_distance_to(const godot_vector2 *p_self, const godot_vector2 *p_to) { const Vector2 *self = (const Vector2 *)p_self; const Vector2 *to = (const Vector2 *)p_to; @@ -119,6 +127,14 @@ godot_vector2 GDAPI godot_vector2_cubic_interpolate(const godot_vector2 *p_self, return dest; } +godot_vector2 GDAPI godot_vector2_move_toward(const godot_vector2 *p_self, const godot_vector2 *p_to, const godot_real p_delta) { + godot_vector2 dest; + const Vector2 *self = (const Vector2 *)p_self; + const Vector2 *to = (const Vector2 *)p_to; + *((Vector2 *)&dest) = self->move_toward(*to, p_delta); + return dest; +} + godot_vector2 GDAPI godot_vector2_rotated(const godot_vector2 *p_self, const godot_real p_phi) { godot_vector2 dest; const Vector2 *self = (const Vector2 *)p_self; diff --git a/modules/gdnative/gdnative/vector3.cpp b/modules/gdnative/gdnative/vector3.cpp index ef86c6f7e9..15a8ef9a2e 100644 --- a/modules/gdnative/gdnative/vector3.cpp +++ b/modules/gdnative/gdnative/vector3.cpp @@ -124,6 +124,14 @@ godot_vector3 GDAPI godot_vector3_cubic_interpolate(const godot_vector3 *p_self, return dest; } +godot_vector3 GDAPI godot_vector3_move_toward(const godot_vector3 *p_self, const godot_vector3 *p_to, const godot_real p_delta) { + godot_vector3 dest; + const Vector3 *self = (const Vector3 *)p_self; + const Vector3 *to = (const Vector3 *)p_to; + *((Vector3 *)&dest) = self->move_toward(*to, p_delta); + return dest; +} + godot_real GDAPI godot_vector3_dot(const godot_vector3 *p_self, const godot_vector3 *p_b) { const Vector3 *self = (const Vector3 *)p_self; const Vector3 *b = (const Vector3 *)p_b; @@ -174,6 +182,14 @@ godot_vector3 GDAPI godot_vector3_ceil(const godot_vector3 *p_self) { return dest; } +godot_vector3 GDAPI godot_vector3_direction_to(const godot_vector3 *p_self, const godot_vector3 *p_to) { + godot_vector3 dest; + const Vector3 *self = (const Vector3 *)p_self; + const Vector3 *to = (const Vector3 *)p_to; + *((Vector3 *)&dest) = self->direction_to(*to); + return dest; +} + godot_real GDAPI godot_vector3_distance_to(const godot_vector3 *p_self, const godot_vector3 *p_b) { const Vector3 *self = (const Vector3 *)p_self; const Vector3 *b = (const Vector3 *)p_b; diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json index 71e7eecd1d..9e5295a936 100644 --- a/modules/gdnative/gdnative_api.json +++ b/modules/gdnative/gdnative_api.json @@ -11,7 +11,138 @@ "major": 1, "minor": 1 }, - "next": null, + "next": { + "type": "CORE", + "version": { + "major": 1, + "minor": 2 + }, + "next": null, + "api": [ + { + "name": "godot_dictionary_duplicate", + "return_type": "godot_dictionary", + "arguments": [ + ["const godot_dictionary *", "p_self"], + ["const godot_bool", "p_deep"] + ] + }, + { + "name": "godot_vector3_move_toward", + "return_type": "godot_vector3", + "arguments": [ + ["const godot_vector3 *", "p_self"], + ["const godot_vector3 *", "p_to"], + ["const godot_real", "p_delta"] + ] + }, + { + "name": "godot_vector2_move_toward", + "return_type": "godot_vector2", + "arguments": [ + ["const godot_vector2 *", "p_self"], + ["const godot_vector2 *", "p_to"], + ["const godot_real", "p_delta"] + ] + }, + { + "name": "godot_string_count", + "return_type": "godot_int", + "arguments": [ + ["const godot_string *", "p_self"], + ["godot_string", "p_what"], + ["godot_int", "p_from"], + ["godot_int", "p_to"] + ] + }, + { + "name": "godot_string_countn", + "return_type": "godot_int", + "arguments": [ + ["const godot_string *", "p_self"], + ["godot_string", "p_what"], + ["godot_int", "p_from"], + ["godot_int", "p_to"] + ] + }, + { + "name": "godot_vector3_direction_to", + "return_type": "godot_vector3", + "arguments": [ + ["const godot_vector3 *", "p_self"], + ["const godot_vector3 *", "p_to"] + ] + }, + { + "name": "godot_vector2_direction_to", + "return_type": "godot_vector2", + "arguments": [ + ["const godot_vector2 *", "p_self"], + ["const godot_vector2 *", "p_to"] + ] + }, + { + "name": "godot_array_slice", + "return_type": "godot_array", + "arguments": [ + ["const godot_array *", "p_self"], + ["const godot_int", "p_begin"], + ["const godot_int", "p_end"], + ["const godot_int", "p_step"], + ["const godot_bool", "p_deep"] + ] + }, + { + "name": "godot_pool_byte_array_empty", + "return_type": "godot_bool", + "arguments": [ + ["const godot_pool_byte_array *", "p_self"] + ] + }, + { + "name": "godot_pool_int_array_empty", + "return_type": "godot_bool", + "arguments": [ + ["const godot_pool_int_array *", "p_self"] + ] + }, + { + "name": "godot_pool_real_array_empty", + "return_type": "godot_bool", + "arguments": [ + ["const godot_pool_real_array *", "p_self"] + ] + }, + { + "name": "godot_pool_string_array_empty", + "return_type": "godot_bool", + "arguments": [ + ["const godot_pool_string_array *", "p_self"] + ] + }, + { + "name": "godot_pool_vector2_array_empty", + "return_type": "godot_bool", + "arguments": [ + ["const godot_pool_vector2_array *", "p_self"] + ] + }, + { + "name": "godot_pool_vector3_array_empty", + "return_type": "godot_bool", + "arguments": [ + ["const godot_pool_vector3_array *", "p_self"] + ] + }, + { + "name": "godot_pool_color_array_empty", + "return_type": "godot_bool", + "arguments": [ + ["const godot_pool_color_array *", "p_self"] + ] + } + ] + }, "api": [ { "name": "godot_color_to_abgr32", @@ -6269,7 +6400,7 @@ "type": "ANDROID", "version": { "major": 1, - "minor": 0 + "minor": 1 }, "next": null, "api": [ @@ -6284,6 +6415,18 @@ "return_type": "jobject", "arguments": [ ] + }, + { + "name": "godot_android_get_surface", + "return_type": "jobject", + "arguments": [ + ] + }, + { + "name": "godot_android_is_activity_resumed", + "return_type": "bool", + "arguments": [ + ] } ] }, @@ -6427,30 +6570,62 @@ "major": 3, "minor": 1 }, - "next": null, + "next": { + "type": "NET", + "version": { + "major": 3, + "minor": 2 + }, + "next": null, + "api": [ + { + "name": "godot_net_set_webrtc_library", + "return_type": "godot_error", + "arguments": [ + ["const godot_net_webrtc_library *", "p_library"] + ] + }, + { + "name": "godot_net_bind_webrtc_peer_connection", + "return_type": "void", + "arguments": [ + ["godot_object *", "p_obj"], + ["const godot_net_webrtc_peer_connection *", "p_interface"] + ] + }, + { + "name": "godot_net_bind_webrtc_data_channel", + "return_type": "void", + "arguments": [ + ["godot_object *", "p_obj"], + ["const godot_net_webrtc_data_channel *", "p_interface"] + ] + } + ] + }, "api": [ { "name": "godot_net_bind_stream_peer", "return_type": "void", "arguments": [ - ["godot_object *", "p_obj"], - ["const godot_net_stream_peer *", "p_interface"] + ["godot_object *", "p_obj"], + ["const godot_net_stream_peer *", "p_interface"] ] }, { "name": "godot_net_bind_packet_peer", "return_type": "void", "arguments": [ - ["godot_object *", "p_obj"], - ["const godot_net_packet_peer *", "p_interface"] + ["godot_object *", "p_obj"], + ["const godot_net_packet_peer *", "p_interface"] ] }, { "name": "godot_net_bind_multiplayer_peer", "return_type": "void", "arguments": [ - ["godot_object *", "p_obj"], - ["const godot_net_multiplayer_peer *", "p_interface"] + ["godot_object *", "p_obj"], + ["const godot_net_multiplayer_peer *", "p_interface"] ] } ] diff --git a/modules/gdnative/gdnative_builders.py b/modules/gdnative/gdnative_builders.py index 7ab0e01108..20c1a2233c 100644 --- a/modules/gdnative/gdnative_builders.py +++ b/modules/gdnative/gdnative_builders.py @@ -185,7 +185,7 @@ def _build_gdnative_api_struct_source(api): 'extern const godot_gdnative_core_' + ('{0}_{1}_api_struct api_{0}_{1}'.format(core['version']['major'], core['version']['minor'])) + ' = {', '\tGDNATIVE_' + core['type'] + ',', '\t{' + str(core['version']['major']) + ', ' + str(core['version']['minor']) + '},', - '\t' + ('NULL' if not core['next'] else ('(const godot_gdnative_api_struct *)& api_{0}_{1}'.format(core['version']['major'], core['version']['minor']))) + ',' + '\t' + ('NULL' if not core['next'] else ('(const godot_gdnative_api_struct *)& api_{0}_{1}'.format(core['next']['version']['major'], core['next']['version']['minor']))) + ',' ] for funcdef in core['api']: diff --git a/modules/gdnative/gdnative_library_editor_plugin.cpp b/modules/gdnative/gdnative_library_editor_plugin.cpp index e2a69b1635..5c84222797 100644 --- a/modules/gdnative/gdnative_library_editor_plugin.cpp +++ b/modules/gdnative/gdnative_library_editor_plugin.cpp @@ -66,10 +66,18 @@ void GDNativeLibraryEditor::_update_tree() { tree->clear(); TreeItem *root = tree->create_item(); - for (Map<String, NativePlatformConfig>::Element *E = platforms.front(); E; E = E->next()) { + PopupMenu *filter_list = filter->get_popup(); + String text = ""; + for (int i = 0; i < filter_list->get_item_count(); i++) { - if (showing_platform != E->key() && showing_platform != "All") + if (!filter_list->is_item_checked(i)) { continue; + } + Map<String, NativePlatformConfig>::Element *E = platforms.find(filter_list->get_item_metadata(i)); + if (!text.empty()) { + text += ", "; + } + text += E->get().name; TreeItem *platform = tree->create_item(root); platform->set_text(0, E->get().name); @@ -119,6 +127,7 @@ void GDNativeLibraryEditor::_update_tree() { platform->set_collapsed(collapsed_items.find(E->get().name) != NULL); } + filter->set_text(text); } void GDNativeLibraryEditor::_on_item_button(Object *item, int column, int id) { @@ -162,9 +171,10 @@ void GDNativeLibraryEditor::_on_dependencies_selected(const PoolStringArray &fil _set_target_value(file_dialog->get_meta("section"), file_dialog->get_meta("target"), files); } -void GDNativeLibraryEditor::_on_filter_selected(int id) { +void GDNativeLibraryEditor::_on_filter_selected(int index) { - showing_platform = filter->get_item_metadata(id); + PopupMenu *filter_list = filter->get_popup(); + filter_list->set_item_checked(index, !filter_list->is_item_checked(index)); _update_tree(); } @@ -214,7 +224,6 @@ void GDNativeLibraryEditor::_erase_entry(const String &platform, const String &e if (List<String>::Element *E = platforms[platform].entries.find(entry)) { String target = platform + "." + entry; - Ref<ConfigFile> config = library->get_config_file(); platforms[platform].entries.erase(E); _set_target_value("entry", target, ""); @@ -265,8 +274,6 @@ void GDNativeLibraryEditor::_translate_to_config_file() { GDNativeLibraryEditor::GDNativeLibraryEditor() { - showing_platform = "All"; - { // Define platforms NativePlatformConfig platform_windows; platform_windows.name = "Windows"; @@ -336,20 +343,21 @@ GDNativeLibraryEditor::GDNativeLibraryEditor() { Label *label = memnew(Label); label->set_text(TTR("Platform:")); hbox->add_child(label); - filter = memnew(OptionButton); - hbox->add_child(filter); + filter = memnew(MenuButton); filter->set_h_size_flags(SIZE_EXPAND_FILL); + filter->set_text_align(filter->ALIGN_LEFT); + hbox->add_child(filter); + PopupMenu *filter_list = filter->get_popup(); + filter_list->set_hide_on_checkable_item_selection(false); int idx = 0; - filter->add_item(TTR("All"), idx); - filter->set_item_metadata(idx, "All"); - idx += 1; for (Map<String, NativePlatformConfig>::Element *E = platforms.front(); E; E = E->next()) { - filter->add_item(E->get().name, idx); - filter->set_item_metadata(idx, E->key()); + filter_list->add_check_item(E->get().name, idx); + filter_list->set_item_metadata(idx, E->key()); + filter_list->set_item_checked(idx, true); idx += 1; } - filter->connect("item_selected", this, "_on_filter_selected"); + filter_list->connect("index_pressed", this, "_on_filter_selected"); tree = memnew(Tree); container->add_child(tree); @@ -387,11 +395,9 @@ GDNativeLibraryEditor::GDNativeLibraryEditor() { void GDNativeLibraryEditorPlugin::edit(Object *p_node) { - if (Object::cast_to<GDNativeLibrary>(p_node)) { - library_editor->edit(Object::cast_to<GDNativeLibrary>(p_node)); - library_editor->show(); - } else - library_editor->hide(); + Ref<GDNativeLibrary> new_library = Object::cast_to<GDNativeLibrary>(p_node); + if (new_library.is_valid()) + library_editor->edit(new_library); } bool GDNativeLibraryEditorPlugin::handles(Object *p_node) const { diff --git a/modules/gdnative/gdnative_library_editor_plugin.h b/modules/gdnative/gdnative_library_editor_plugin.h index e7d50ba29f..8c1449f55a 100644 --- a/modules/gdnative/gdnative_library_editor_plugin.h +++ b/modules/gdnative/gdnative_library_editor_plugin.h @@ -61,7 +61,7 @@ class GDNativeLibraryEditor : public Control { }; Tree *tree; - OptionButton *filter; + MenuButton *filter; EditorFileDialog *file_dialog; ConfirmationDialog *new_architecture_dialog; LineEdit *new_architecture_input; diff --git a/modules/gdnative/gdnative_library_singleton_editor.cpp b/modules/gdnative/gdnative_library_singleton_editor.cpp index 55bc16fccc..389b353a51 100644 --- a/modules/gdnative/gdnative_library_singleton_editor.cpp +++ b/modules/gdnative/gdnative_library_singleton_editor.cpp @@ -32,11 +32,16 @@ #include "gdnative_library_singleton_editor.h" #include "gdnative.h" -void GDNativeLibrarySingletonEditor::_find_gdnative_singletons(EditorFileSystemDirectory *p_dir, const Set<String> &enabled_list) { +#include "editor/editor_node.h" + +Set<String> GDNativeLibrarySingletonEditor::_find_singletons_recursive(EditorFileSystemDirectory *p_dir) { + + Set<String> file_paths; // check children for (int i = 0; i < p_dir->get_file_count(); i++) { + String file_name = p_dir->get_file(i); String file_type = p_dir->get_file_type(i); if (file_type != "GDNativeLibrary") { @@ -45,23 +50,57 @@ void GDNativeLibrarySingletonEditor::_find_gdnative_singletons(EditorFileSystemD Ref<GDNativeLibrary> lib = ResourceLoader::load(p_dir->get_file_path(i)); if (lib.is_valid() && lib->is_singleton()) { - String path = p_dir->get_file_path(i); - TreeItem *ti = libraries->create_item(libraries->get_root()); - ti->set_text(0, path.get_file()); - ti->set_tooltip(0, path); - ti->set_metadata(0, path); - ti->set_cell_mode(1, TreeItem::CELL_MODE_RANGE); - ti->set_text(1, "Disabled,Enabled"); - bool enabled = enabled_list.has(path) ? true : false; - - ti->set_range(1, enabled ? 1 : 0); - ti->set_custom_color(1, enabled ? Color(0, 1, 0) : Color(1, 0, 0)); + file_paths.insert(p_dir->get_file_path(i)); } } // check subdirectories for (int i = 0; i < p_dir->get_subdir_count(); i++) { - _find_gdnative_singletons(p_dir->get_subdir(i), enabled_list); + Set<String> paths = _find_singletons_recursive(p_dir->get_subdir(i)); + + for (Set<String>::Element *E = paths.front(); E; E = E->next()) { + file_paths.insert(E->get()); + } + } + + return file_paths; +} + +void GDNativeLibrarySingletonEditor::_discover_singletons() { + + EditorFileSystemDirectory *dir = EditorFileSystem::get_singleton()->get_filesystem(); + + Set<String> file_paths = _find_singletons_recursive(dir); + + bool changed = false; + Array current_files; + if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) { + current_files = ProjectSettings::get_singleton()->get("gdnative/singletons"); + } + Array files; + for (Set<String>::Element *E = file_paths.front(); E; E = E->next()) { + if (!current_files.has(E->get())) { + changed = true; + } + files.append(E->get()); + } + + // Check for removed files + if (!changed) { + // Removed singleton + for (int j = 0; j < current_files.size(); j++) { + if (!files.has(current_files[j])) { + changed = true; + break; + } + } + } + + if (changed) { + + ProjectSettings::get_singleton()->set("gdnative/singletons", files); + _update_libraries(); // So singleton options (i.e. disabled) updates too + ProjectSettings::get_singleton()->save(); } } @@ -69,22 +108,40 @@ void GDNativeLibrarySingletonEditor::_update_libraries() { updating = true; libraries->clear(); - libraries->create_item(); //rppt + libraries->create_item(); // root item - Vector<String> enabled_paths; + Array singletons; if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) { - enabled_paths = ProjectSettings::get_singleton()->get("gdnative/singletons"); + singletons = ProjectSettings::get_singleton()->get("gdnative/singletons"); } - Set<String> enabled_list; - for (int i = 0; i < enabled_paths.size(); i++) { - enabled_list.insert(enabled_paths[i]); + Array singletons_disabled; + if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons_disabled")) { + singletons_disabled = ProjectSettings::get_singleton()->get("gdnative/singletons_disabled"); } - EditorFileSystemDirectory *fs = EditorFileSystem::get_singleton()->get_filesystem(); - if (fs) { - _find_gdnative_singletons(fs, enabled_list); + Array updated_disabled; + for (int i = 0; i < singletons.size(); i++) { + bool enabled = true; + String path = singletons[i]; + if (singletons_disabled.has(path)) { + enabled = false; + updated_disabled.push_back(path); + } + TreeItem *ti = libraries->create_item(libraries->get_root()); + ti->set_text(0, path.get_file()); + ti->set_tooltip(0, path); + ti->set_metadata(0, path); + ti->set_cell_mode(1, TreeItem::CELL_MODE_RANGE); + ti->set_text(1, "Disabled,Enabled"); + ti->set_range(1, enabled ? 1 : 0); + ti->set_custom_color(1, enabled ? Color(0, 1, 0) : Color(1, 0, 0)); + ti->set_editable(1, true); } + // The singletons list changed, we must update the settings + if (updated_disabled.size() != singletons_disabled.size()) + ProjectSettings::get_singleton()->set("gdnative/singletons_disabled", updated_disabled); + updating = false; } @@ -99,24 +156,29 @@ void GDNativeLibrarySingletonEditor::_item_edited() { bool enabled = item->get_range(1); String path = item->get_metadata(0); - Vector<String> enabled_paths; - if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) { - enabled_paths = ProjectSettings::get_singleton()->get("gdnative/singletons"); + Array disabled_paths; + Array undo_paths; + if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons_disabled")) { + disabled_paths = ProjectSettings::get_singleton()->get("gdnative/singletons_disabled"); + // Duplicate so redo works (not a reference) + disabled_paths = disabled_paths.duplicate(); + // For undo, so we can reset the property. + undo_paths = disabled_paths.duplicate(); } if (enabled) { - if (enabled_paths.find(path) == -1) { - enabled_paths.push_back(path); - } + disabled_paths.erase(path); } else { - enabled_paths.erase(path); + if (disabled_paths.find(path) == -1) + disabled_paths.push_back(path); } - if (enabled_paths.size()) { - ProjectSettings::get_singleton()->set("gdnative/singletons", enabled_paths); - } else { - ProjectSettings::get_singleton()->set("gdnative/singletons", Variant()); - } + undo_redo->create_action(enabled ? TTR("Enabled GDNative Singleton") : TTR("Disabled GDNative Singleton")); + undo_redo->add_do_property(ProjectSettings::get_singleton(), "gdnative/singletons_disabled", disabled_paths); + undo_redo->add_do_method(this, "_update_libraries"); + undo_redo->add_undo_property(ProjectSettings::get_singleton(), "gdnative/singletons_disabled", undo_paths); + undo_redo->add_undo_method(this, "_update_libraries"); + undo_redo->commit_action(); } void GDNativeLibrarySingletonEditor::_notification(int p_what) { @@ -131,9 +193,12 @@ void GDNativeLibrarySingletonEditor::_notification(int p_what) { void GDNativeLibrarySingletonEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_item_edited"), &GDNativeLibrarySingletonEditor::_item_edited); + ClassDB::bind_method(D_METHOD("_discover_singletons"), &GDNativeLibrarySingletonEditor::_discover_singletons); + ClassDB::bind_method(D_METHOD("_update_libraries"), &GDNativeLibrarySingletonEditor::_update_libraries); } GDNativeLibrarySingletonEditor::GDNativeLibrarySingletonEditor() { + undo_redo = EditorNode::get_singleton()->get_undo_redo(); libraries = memnew(Tree); libraries->set_columns(2); libraries->set_column_titles_visible(true); @@ -143,6 +208,7 @@ GDNativeLibrarySingletonEditor::GDNativeLibrarySingletonEditor() { add_margin_child(TTR("Libraries: "), libraries, true); updating = false; libraries->connect("item_edited", this, "_item_edited"); + EditorFileSystem::get_singleton()->connect("filesystem_changed", this, "_discover_singletons"); } #endif // TOOLS_ENABLED diff --git a/modules/gdnative/gdnative_library_singleton_editor.h b/modules/gdnative/gdnative_library_singleton_editor.h index cf5ab23501..b43080dfdb 100644 --- a/modules/gdnative/gdnative_library_singleton_editor.h +++ b/modules/gdnative/gdnative_library_singleton_editor.h @@ -36,18 +36,24 @@ #include "editor/project_settings_editor.h" class GDNativeLibrarySingletonEditor : public VBoxContainer { + GDCLASS(GDNativeLibrarySingletonEditor, VBoxContainer); + +private: Tree *libraries; + UndoRedo *undo_redo; bool updating; - void _update_libraries(); - void _find_gdnative_singletons(EditorFileSystemDirectory *p_dir, const Set<String> &enabled_list); - void _item_edited(); + static Set<String> _find_singletons_recursive(EditorFileSystemDirectory *p_dir); protected: void _notification(int p_what); static void _bind_methods(); + void _discover_singletons(); + void _item_edited(); + void _update_libraries(); + public: GDNativeLibrarySingletonEditor(); }; diff --git a/modules/gdnative/icons/icon_g_d_native_library.svg b/modules/gdnative/icons/icon_g_d_native_library.svg new file mode 100644 index 0000000000..b494c7af6e --- /dev/null +++ b/modules/gdnative/icons/icon_g_d_native_library.svg @@ -0,0 +1,5 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<path transform="translate(0 1036.4)" d="m7 1l-0.56445 2.2578a5 5 0 0 0 -0.68945 0.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -0.28516 0.68555l-2.2539 0.5625v2l2.2578 0.56445a5 5 0 0 0 0.2793 0.6875l-1.1934 1.9902 1.4141 1.4141 1.9941-1.1953a5 5 0 0 0 0.68555 0.28516l0.5625 2.2539v-5.2695a2 2 0 0 1 -1 -1.7305 2 2 0 0 1 1 -1.7285v-0.27148h1 4.5762a5 5 0 0 0 -0.11328 -0.25195l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -0.68555 -0.28516l-0.5625-2.2539h-2zm2 7v1 5 1h5c0.55228 0 1-0.4477 1-1v-5c0-0.5523-0.44772-1-1-1v4l-1-1-1 1v-4h-3z" fill="#e0e0e0"/> +</g> +</svg> diff --git a/modules/gdnative/icons/icon_native_script.svg b/modules/gdnative/icons/icon_native_script.svg new file mode 100644 index 0000000000..fb9e135627 --- /dev/null +++ b/modules/gdnative/icons/icon_native_script.svg @@ -0,0 +1,5 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<path transform="translate(0 1036.4)" d="m7 1l-0.56445 2.2578a5 5 0 0 0 -0.68945 0.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -0.28516 0.68555l-2.2539 0.5625h3v1 1h2v-0.95117a2 2 0 0 1 0 -0.048828 2 2 0 0 1 2 -2 2 2 0 0 1 2 2v1h5v-2l-2.2578-0.56445a5 5 0 0 0 -0.2793 -0.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -0.68555 -0.28516l-0.5625-2.2539h-2zm-6 7v4 4h2a3 3 0 0 0 3 -3 3 3 0 0 0 -3 -3v-2h-2zm6 0v2h2v-2h-2zm3 2v6h2v-4a1 1 0 0 1 1 1v3h2v-3a3 3 0 0 0 -3 -3h-2zm-7 2a1 1 0 0 1 1 1 1 1 0 0 1 -1 1v-2zm4 0v4h2v-4h-2z" fill="#e0e0e0"/> +</g> +</svg> 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 321b471d0e..d465bbde54 100644 --- a/modules/gdnative/include/arvr/godot_arvr.h +++ b/modules/gdnative/include/arvr/godot_arvr.h @@ -63,6 +63,8 @@ typedef struct { void (*process)(void *); // 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/include/gdnative/array.h b/modules/gdnative/include/gdnative/array.h index 10ef8a73d2..a27626325e 100644 --- a/modules/gdnative/include/gdnative/array.h +++ b/modules/gdnative/include/gdnative/array.h @@ -132,6 +132,8 @@ void GDAPI godot_array_destroy(godot_array *p_self); godot_array GDAPI godot_array_duplicate(const godot_array *p_self, const godot_bool p_deep); +godot_array GDAPI godot_array_slice(const godot_array *p_self, const godot_int p_begin, const godot_int p_end, const godot_int p_step, const godot_bool p_deep); + godot_variant GDAPI godot_array_max(const godot_array *p_self); godot_variant GDAPI godot_array_min(const godot_array *p_self); diff --git a/modules/gdnative/include/gdnative/dictionary.h b/modules/gdnative/include/gdnative/dictionary.h index 14e35b4692..483cd9c4e3 100644 --- a/modules/gdnative/include/gdnative/dictionary.h +++ b/modules/gdnative/include/gdnative/dictionary.h @@ -63,6 +63,8 @@ void GDAPI godot_dictionary_new(godot_dictionary *r_dest); void GDAPI godot_dictionary_new_copy(godot_dictionary *r_dest, const godot_dictionary *p_src); void GDAPI godot_dictionary_destroy(godot_dictionary *p_self); +godot_dictionary GDAPI godot_dictionary_duplicate(const godot_dictionary *p_self, const godot_bool p_deep); + godot_int GDAPI godot_dictionary_size(const godot_dictionary *p_self); godot_bool GDAPI godot_dictionary_empty(const godot_dictionary *p_self); diff --git a/modules/gdnative/include/gdnative/gdnative.h b/modules/gdnative/include/gdnative/gdnative.h index 3c457bf5a7..884bcf60d2 100644 --- a/modules/gdnative/include/gdnative/gdnative.h +++ b/modules/gdnative/include/gdnative/gdnative.h @@ -67,7 +67,7 @@ extern "C" { ////// Error typedef enum { - GODOT_OK, + GODOT_OK, // (0) GODOT_FAILED, ///< Generic fail error GODOT_ERR_UNAVAILABLE, ///< What is requested is unsupported/unavailable GODOT_ERR_UNCONFIGURED, ///< The object being used hasn't been properly set up yet @@ -97,12 +97,12 @@ typedef enum { GODOT_ERR_CONNECTION_ERROR, GODOT_ERR_CANT_ACQUIRE_RESOURCE, GODOT_ERR_CANT_FORK, - GODOT_ERR_INVALID_DATA, ///< Data passed is invalid (30) + GODOT_ERR_INVALID_DATA, ///< Data passed is invalid (30) GODOT_ERR_INVALID_PARAMETER, ///< Parameter passed is invalid GODOT_ERR_ALREADY_EXISTS, ///< When adding, item already exists GODOT_ERR_DOES_NOT_EXIST, ///< When retrieving/erasing, it item does not exist GODOT_ERR_DATABASE_CANT_READ, ///< database is full - GODOT_ERR_DATABASE_CANT_WRITE, ///< database is full (35) + GODOT_ERR_DATABASE_CANT_WRITE, ///< database is full (35) GODOT_ERR_COMPILATION_FAILED, GODOT_ERR_METHOD_NOT_FOUND, GODOT_ERR_LINK_FAILED, diff --git a/modules/gdnative/include/gdnative/pool_arrays.h b/modules/gdnative/include/gdnative/pool_arrays.h index 96730ab085..63e8267f0e 100644 --- a/modules/gdnative/include/gdnative/pool_arrays.h +++ b/modules/gdnative/include/gdnative/pool_arrays.h @@ -191,6 +191,8 @@ uint8_t GDAPI godot_pool_byte_array_get(const godot_pool_byte_array *p_self, con godot_int GDAPI godot_pool_byte_array_size(const godot_pool_byte_array *p_self); +godot_bool GDAPI godot_pool_byte_array_empty(const godot_pool_byte_array *p_self); + void GDAPI godot_pool_byte_array_destroy(godot_pool_byte_array *p_self); // int @@ -222,6 +224,8 @@ godot_int GDAPI godot_pool_int_array_get(const godot_pool_int_array *p_self, con godot_int GDAPI godot_pool_int_array_size(const godot_pool_int_array *p_self); +godot_bool GDAPI godot_pool_int_array_empty(const godot_pool_int_array *p_self); + void GDAPI godot_pool_int_array_destroy(godot_pool_int_array *p_self); // real @@ -253,6 +257,8 @@ godot_real GDAPI godot_pool_real_array_get(const godot_pool_real_array *p_self, godot_int GDAPI godot_pool_real_array_size(const godot_pool_real_array *p_self); +godot_bool GDAPI godot_pool_real_array_empty(const godot_pool_real_array *p_self); + void GDAPI godot_pool_real_array_destroy(godot_pool_real_array *p_self); // string @@ -284,6 +290,8 @@ godot_string GDAPI godot_pool_string_array_get(const godot_pool_string_array *p_ godot_int GDAPI godot_pool_string_array_size(const godot_pool_string_array *p_self); +godot_bool GDAPI godot_pool_string_array_empty(const godot_pool_string_array *p_self); + void GDAPI godot_pool_string_array_destroy(godot_pool_string_array *p_self); // vector2 @@ -315,6 +323,8 @@ godot_vector2 GDAPI godot_pool_vector2_array_get(const godot_pool_vector2_array godot_int GDAPI godot_pool_vector2_array_size(const godot_pool_vector2_array *p_self); +godot_bool GDAPI godot_pool_vector2_array_empty(const godot_pool_vector2_array *p_self); + void GDAPI godot_pool_vector2_array_destroy(godot_pool_vector2_array *p_self); // vector3 @@ -346,6 +356,8 @@ godot_vector3 GDAPI godot_pool_vector3_array_get(const godot_pool_vector3_array godot_int GDAPI godot_pool_vector3_array_size(const godot_pool_vector3_array *p_self); +godot_bool GDAPI godot_pool_vector3_array_empty(const godot_pool_vector3_array *p_self); + void GDAPI godot_pool_vector3_array_destroy(godot_pool_vector3_array *p_self); // color @@ -377,6 +389,8 @@ godot_color GDAPI godot_pool_color_array_get(const godot_pool_color_array *p_sel godot_int GDAPI godot_pool_color_array_size(const godot_pool_color_array *p_self); +godot_bool GDAPI godot_pool_color_array_empty(const godot_pool_color_array *p_self); + void GDAPI godot_pool_color_array_destroy(godot_pool_color_array *p_self); // diff --git a/modules/gdnative/include/gdnative/string.h b/modules/gdnative/include/gdnative/string.h index f045ac9d58..7500d70f20 100644 --- a/modules/gdnative/include/gdnative/string.h +++ b/modules/gdnative/include/gdnative/string.h @@ -102,6 +102,8 @@ godot_bool GDAPI godot_string_begins_with_char_array(const godot_string *p_self, godot_array GDAPI godot_string_bigrams(const godot_string *p_self); godot_string GDAPI godot_string_chr(wchar_t p_character); godot_bool GDAPI godot_string_ends_with(const godot_string *p_self, const godot_string *p_string); +godot_int GDAPI godot_string_count(const godot_string *p_self, godot_string p_what, godot_int p_from, godot_int p_to); +godot_int GDAPI godot_string_countn(const godot_string *p_self, godot_string p_what, godot_int p_from, godot_int p_to); godot_int GDAPI godot_string_find(const godot_string *p_self, godot_string p_what); godot_int GDAPI godot_string_find_from(const godot_string *p_self, godot_string p_what, godot_int p_from); godot_int GDAPI godot_string_findmk(const godot_string *p_self, const godot_array *p_keys); diff --git a/modules/gdnative/include/gdnative/vector2.h b/modules/gdnative/include/gdnative/vector2.h index 9e37b8e0c6..15a6c80887 100644 --- a/modules/gdnative/include/gdnative/vector2.h +++ b/modules/gdnative/include/gdnative/vector2.h @@ -71,6 +71,8 @@ godot_real GDAPI godot_vector2_length_squared(const godot_vector2 *p_self); godot_bool GDAPI godot_vector2_is_normalized(const godot_vector2 *p_self); +godot_vector2 GDAPI godot_vector2_direction_to(const godot_vector2 *p_self, const godot_vector2 *p_b); + godot_real GDAPI godot_vector2_distance_to(const godot_vector2 *p_self, const godot_vector2 *p_to); godot_real GDAPI godot_vector2_distance_squared_to(const godot_vector2 *p_self, const godot_vector2 *p_to); @@ -83,6 +85,8 @@ godot_vector2 GDAPI godot_vector2_linear_interpolate(const godot_vector2 *p_self godot_vector2 GDAPI godot_vector2_cubic_interpolate(const godot_vector2 *p_self, const godot_vector2 *p_b, const godot_vector2 *p_pre_a, const godot_vector2 *p_post_b, const godot_real p_t); +godot_vector2 GDAPI godot_vector2_move_toward(const godot_vector2 *p_self, const godot_vector2 *p_to, const godot_real p_delta); + godot_vector2 GDAPI godot_vector2_rotated(const godot_vector2 *p_self, const godot_real p_phi); godot_vector2 GDAPI godot_vector2_tangent(const godot_vector2 *p_self); diff --git a/modules/gdnative/include/gdnative/vector3.h b/modules/gdnative/include/gdnative/vector3.h index 61f0c6c62e..ee7d029028 100644 --- a/modules/gdnative/include/gdnative/vector3.h +++ b/modules/gdnative/include/gdnative/vector3.h @@ -90,6 +90,8 @@ godot_vector3 GDAPI godot_vector3_linear_interpolate(const godot_vector3 *p_self godot_vector3 GDAPI godot_vector3_cubic_interpolate(const godot_vector3 *p_self, const godot_vector3 *p_b, const godot_vector3 *p_pre_a, const godot_vector3 *p_post_b, const godot_real p_t); +godot_vector3 GDAPI godot_vector3_move_toward(const godot_vector3 *p_self, const godot_vector3 *p_to, const godot_real p_delta); + godot_real GDAPI godot_vector3_dot(const godot_vector3 *p_self, const godot_vector3 *p_b); godot_vector3 GDAPI godot_vector3_cross(const godot_vector3 *p_self, const godot_vector3 *p_b); @@ -104,6 +106,8 @@ godot_vector3 GDAPI godot_vector3_floor(const godot_vector3 *p_self); godot_vector3 GDAPI godot_vector3_ceil(const godot_vector3 *p_self); +godot_vector3 GDAPI godot_vector3_direction_to(const godot_vector3 *p_self, const godot_vector3 *p_b); + godot_real GDAPI godot_vector3_distance_to(const godot_vector3 *p_self, const godot_vector3 *p_b); godot_real GDAPI godot_vector3_distance_squared_to(const godot_vector3 *p_self, const godot_vector3 *p_b); diff --git a/modules/gdnative/include/nativescript/godot_nativescript.h b/modules/gdnative/include/nativescript/godot_nativescript.h index f3b9f7fb31..8a05b6cfa3 100644 --- a/modules/gdnative/include/nativescript/godot_nativescript.h +++ b/modules/gdnative/include/nativescript/godot_nativescript.h @@ -56,7 +56,7 @@ typedef enum { GODOT_PROPERTY_HINT_ENUM, ///< hint_text= "val1,val2,val3,etc" GODOT_PROPERTY_HINT_EXP_EASING, /// exponential easing function (Math::ease) GODOT_PROPERTY_HINT_LENGTH, ///< hint_text= "length" (as integer) - GODOT_PROPERTY_HINT_SPRITE_FRAME, + GODOT_PROPERTY_HINT_SPRITE_FRAME, // FIXME: Obsolete: drop whenever we can break compat GODOT_PROPERTY_HINT_KEY_ACCEL, ///< hint_text= "length" (as integer) GODOT_PROPERTY_HINT_FLAGS, ///< hint_text= "flag1,flag2,etc" (as bit flags) GODOT_PROPERTY_HINT_LAYERS_2D_RENDER, @@ -64,9 +64,9 @@ typedef enum { GODOT_PROPERTY_HINT_LAYERS_3D_RENDER, GODOT_PROPERTY_HINT_LAYERS_3D_PHYSICS, GODOT_PROPERTY_HINT_FILE, ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc," - GODOT_PROPERTY_HINT_DIR, ///< a directort path must be passed + GODOT_PROPERTY_HINT_DIR, ///< a directory path must be passed GODOT_PROPERTY_HINT_GLOBAL_FILE, ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc," - GODOT_PROPERTY_HINT_GLOBAL_DIR, ///< a directort path must be passed + GODOT_PROPERTY_HINT_GLOBAL_DIR, ///< a directory path must be passed GODOT_PROPERTY_HINT_RESOURCE_TYPE, ///< a resource object type GODOT_PROPERTY_HINT_MULTILINE_TEXT, ///< used for string properties that can contain multiple lines GODOT_PROPERTY_HINT_PLACEHOLDER_TEXT, ///< used to set a placeholder text for string properties @@ -98,8 +98,8 @@ typedef enum { GODOT_PROPERTY_USAGE_INTERNATIONALIZED = 64, //hint for internationalized strings GODOT_PROPERTY_USAGE_GROUP = 128, //used for grouping props in the editor GODOT_PROPERTY_USAGE_CATEGORY = 256, - GODOT_PROPERTY_USAGE_STORE_IF_NONZERO = 512, //only store if nonzero - GODOT_PROPERTY_USAGE_STORE_IF_NONONE = 1024, //only store if false + GODOT_PROPERTY_USAGE_STORE_IF_NONZERO = 512, // FIXME: Obsolete: drop whenever we can break compat + GODOT_PROPERTY_USAGE_STORE_IF_NONONE = 1024, // FIXME: Obsolete: drop whenever we can break compat GODOT_PROPERTY_USAGE_NO_INSTANCE_STATE = 2048, GODOT_PROPERTY_USAGE_RESTART_IF_CHANGED = 4096, GODOT_PROPERTY_USAGE_SCRIPT_VARIABLE = 8192, diff --git a/modules/gdnative/include/net/godot_net.h b/modules/gdnative/include/net/godot_net.h index d7de04e725..3a411755c1 100644 --- a/modules/gdnative/include/net/godot_net.h +++ b/modules/gdnative/include/net/godot_net.h @@ -115,4 +115,7 @@ void GDAPI godot_net_bind_multiplayer_peer(godot_object *p_obj, const godot_net_ } #endif +// WebRTC Bindings +#include "net/godot_webrtc.h" + #endif /* GODOT_NATIVENET_H */ diff --git a/modules/gdnative/include/net/godot_webrtc.h b/modules/gdnative/include/net/godot_webrtc.h new file mode 100644 index 0000000000..783f7b727d --- /dev/null +++ b/modules/gdnative/include/net/godot_webrtc.h @@ -0,0 +1,122 @@ +/*************************************************************************/ +/* godot_webrtc.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 GODOT_NATIVEWEBRTC_H +#define GODOT_NATIVEWEBRTC_H + +#include <gdnative/gdnative.h> + +#ifdef __cplusplus +extern "C" { +#endif + +#define GODOT_NET_WEBRTC_API_MAJOR 3 +#define GODOT_NET_WEBRTC_API_MINOR 2 + +/* Library Interface (used to set default GDNative WebRTC implementation */ +typedef struct { + godot_gdnative_api_version version; /* version of our API */ + + /* Called when the library is unset as default interface via godot_net_set_webrtc_library */ + void (*unregistered)(); + + /* Used by WebRTCPeerConnection create when GDNative is the default implementation. */ + /* Takes a pointer to WebRTCPeerConnectionGDNative, should bind and return OK, failure if binding was unsuccessful. */ + godot_error (*create_peer_connection)(godot_object *); + + void *next; /* For extension */ +} godot_net_webrtc_library; + +/* WebRTCPeerConnection interface */ +typedef struct { + godot_gdnative_api_version version; /* version of our API */ + + godot_object *data; /* User reference */ + + /* This is WebRTCPeerConnection */ + godot_int (*get_connection_state)(const void *); + + godot_error (*initialize)(void *, const godot_dictionary *); + godot_object *(*create_data_channel)(void *, const char *p_channel_name, const godot_dictionary *); + godot_error (*create_offer)(void *); + godot_error (*create_answer)(void *); /* unused for now, should be done automatically on set_local_description */ + godot_error (*set_remote_description)(void *, const char *, const char *); + godot_error (*set_local_description)(void *, const char *, const char *); + godot_error (*add_ice_candidate)(void *, const char *, int, const char *); + godot_error (*poll)(void *); + void (*close)(void *); + + void *next; /* For extension? */ +} godot_net_webrtc_peer_connection; + +/* WebRTCDataChannel interface */ +typedef struct { + godot_gdnative_api_version version; /* version of our API */ + + godot_object *data; /* User reference */ + + /* This is PacketPeer */ + godot_error (*get_packet)(void *, const uint8_t **, int *); + godot_error (*put_packet)(void *, const uint8_t *, int); + godot_int (*get_available_packet_count)(const void *); + godot_int (*get_max_packet_size)(const void *); + + /* This is WebRTCDataChannel */ + void (*set_write_mode)(void *, godot_int); + godot_int (*get_write_mode)(const void *); + bool (*was_string_packet)(const void *); + + godot_int (*get_ready_state)(const void *); + const char *(*get_label)(const void *); + bool (*is_ordered)(const void *); + int (*get_id)(const void *); + int (*get_max_packet_life_time)(const void *); + int (*get_max_retransmits)(const void *); + const char *(*get_protocol)(const void *); + bool (*is_negotiated)(const void *); + + godot_error (*poll)(void *); + void (*close)(void *); + + void *next; /* For extension? */ +} godot_net_webrtc_data_channel; + +/* Set the default GDNative library */ +godot_error GDAPI godot_net_set_webrtc_library(const godot_net_webrtc_library *); +/* Binds a WebRTCPeerConnectionGDNative to the provided interface */ +void GDAPI godot_net_bind_webrtc_peer_connection(godot_object *p_obj, const godot_net_webrtc_peer_connection *); +/* Binds a WebRTCDataChannelGDNative to the provided interface */ +void GDAPI godot_net_bind_webrtc_data_channel(godot_object *p_obj, const godot_net_webrtc_data_channel *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/modules/gdnative/include/pluginscript/godot_pluginscript.h b/modules/gdnative/include/pluginscript/godot_pluginscript.h index 968f91ae9f..a9e83d1524 100644 --- a/modules/gdnative/include/pluginscript/godot_pluginscript.h +++ b/modules/gdnative/include/pluginscript/godot_pluginscript.h @@ -136,7 +136,7 @@ typedef struct { godot_bool (*validate)(godot_pluginscript_language_data *p_data, const godot_string *p_script, int *r_line_error, int *r_col_error, godot_string *r_test_error, const godot_string *p_path, godot_pool_string_array *r_functions); int (*find_function)(godot_pluginscript_language_data *p_data, const godot_string *p_function, const godot_string *p_code); // Can be NULL godot_string (*make_function)(godot_pluginscript_language_data *p_data, const godot_string *p_class, const godot_string *p_name, const godot_pool_string_array *p_args); - godot_error (*complete_code)(godot_pluginscript_language_data *p_data, const godot_string *p_code, const godot_string *p_base_path, godot_object *p_owner, godot_array *r_options, godot_bool *r_force, godot_string *r_call_hint); + godot_error (*complete_code)(godot_pluginscript_language_data *p_data, const godot_string *p_code, const godot_string *p_path, godot_object *p_owner, godot_array *r_options, godot_bool *r_force, godot_string *r_call_hint); void (*auto_indent_code)(godot_pluginscript_language_data *p_data, godot_string *p_code, int p_from_line, int p_to_line); void (*add_global_constant)(godot_pluginscript_language_data *p_data, const godot_string *p_variable, const godot_variant *p_value); diff --git a/modules/gdnative/nativescript/SCsub b/modules/gdnative/nativescript/SCsub index 5841ad5531..92c9d6630d 100644 --- a/modules/gdnative/nativescript/SCsub +++ b/modules/gdnative/nativescript/SCsub @@ -4,7 +4,6 @@ Import('env') Import('env_gdnative') env_gdnative.add_source_files(env.modules_sources, '*.cpp') -env_gdnative.Append(CPPFLAGS=['-DGDAPI_BUILT_IN']) if "platform" in env and env["platform"] in ["x11", "iphone"]: env.Append(LINKFLAGS=["-rdynamic"]) diff --git a/modules/gdnative/nativescript/api_generator.cpp b/modules/gdnative/nativescript/api_generator.cpp index 4577c7327a..eace195c33 100644 --- a/modules/gdnative/nativescript/api_generator.cpp +++ b/modules/gdnative/nativescript/api_generator.cpp @@ -108,6 +108,7 @@ struct ClassAPI { ClassDB::APIType api_type; bool is_singleton; + String singleton_name; bool is_instanciable; // @Unclear bool is_reference; @@ -139,6 +140,34 @@ static String get_type_name(const PropertyInfo &info) { } /* + * Some comparison helper functions we need + */ + +struct MethodInfoComparator { + StringName::AlphCompare compare; + bool operator()(const MethodInfo &p_a, const MethodInfo &p_b) const { + + return compare(p_a.name, p_b.name); + } +}; + +struct PropertyInfoComparator { + StringName::AlphCompare compare; + bool operator()(const PropertyInfo &p_a, const PropertyInfo &p_b) const { + + return compare(p_a.name, p_b.name); + } +}; + +struct ConstantAPIComparator { + NoCaseComparator compare; + bool operator()(const ConstantAPI &p_a, const ConstantAPI &p_b) const { + + return compare(p_a.constant_name, p_b.constant_name); + } +}; + +/* * Reads the entire Godot API to a list */ List<ClassAPI> generate_c_api_classes() { @@ -147,6 +176,7 @@ List<ClassAPI> generate_c_api_classes() { List<StringName> classes; ClassDB::get_class_list(&classes); + classes.sort_custom<StringName::AlphCompare>(); // Register global constants as a fake GlobalConstants singleton class { @@ -154,6 +184,7 @@ List<ClassAPI> generate_c_api_classes() { global_constants_api.class_name = L"GlobalConstants"; global_constants_api.api_type = ClassDB::API_CORE; global_constants_api.is_singleton = true; + global_constants_api.singleton_name = L"GlobalConstants"; global_constants_api.is_instanciable = false; const int constants_count = GlobalConstants::get_global_constant_count(); for (int i = 0; i < constants_count; ++i) { @@ -162,6 +193,7 @@ List<ClassAPI> generate_c_api_classes() { constant_api.constant_value = GlobalConstants::get_global_constant_value(i); global_constants_api.constants.push_back(constant_api); } + global_constants_api.constants.sort_custom<ConstantAPIComparator>(); api.push_back(global_constants_api); } @@ -178,6 +210,9 @@ List<ClassAPI> generate_c_api_classes() { name.remove(0); } class_api.is_singleton = Engine::get_singleton()->has_singleton(name); + if (class_api.is_singleton) { + class_api.singleton_name = name; + } } class_api.is_instanciable = !class_api.is_singleton && ClassDB::can_instance(class_name); @@ -193,6 +228,7 @@ List<ClassAPI> generate_c_api_classes() { { List<String> constant; ClassDB::get_integer_constant_list(class_name, &constant, true); + constant.sort_custom<NoCaseComparator>(); for (List<String>::Element *c = constant.front(); c != NULL; c = c->next()) { ConstantAPI constant_api; constant_api.constant_name = c->get(); @@ -206,6 +242,7 @@ List<ClassAPI> generate_c_api_classes() { { List<MethodInfo> signals_; ClassDB::get_signal_list(class_name, &signals_, true); + signals_.sort_custom<MethodInfoComparator>(); for (int i = 0; i < signals_.size(); i++) { SignalAPI signal; @@ -245,6 +282,7 @@ List<ClassAPI> generate_c_api_classes() { { List<PropertyInfo> properties; ClassDB::get_property_list(class_name, &properties, true); + properties.sort_custom<PropertyInfoComparator>(); for (List<PropertyInfo>::Element *p = properties.front(); p != NULL; p = p->next()) { PropertyAPI property_api; @@ -272,6 +310,7 @@ List<ClassAPI> generate_c_api_classes() { { List<MethodInfo> methods; ClassDB::get_method_list(class_name, &methods, true); + methods.sort_custom<MethodInfoComparator>(); for (List<MethodInfo>::Element *m = methods.front(); m != NULL; m = m->next()) { MethodAPI method_api; @@ -387,6 +426,7 @@ static List<String> generate_c_api_json(const List<ClassAPI> &p_api) { source.push_back("\t\t\"base_class\": \"" + api.super_class_name + "\",\n"); source.push_back(String("\t\t\"api_type\": \"") + (api.api_type == ClassDB::API_CORE ? "core" : (api.api_type == ClassDB::API_EDITOR ? "tools" : "none")) + "\",\n"); source.push_back(String("\t\t\"singleton\": ") + (api.is_singleton ? "true" : "false") + ",\n"); + source.push_back("\t\t\"singleton_name\": \"" + api.singleton_name + "\",\n"); source.push_back(String("\t\t\"instanciable\": ") + (api.is_instanciable ? "true" : "false") + ",\n"); source.push_back(String("\t\t\"is_reference\": ") + (api.is_reference ? "true" : "false") + ",\n"); // @Unclear diff --git a/modules/gdnative/nativescript/godot_nativescript.cpp b/modules/gdnative/nativescript/godot_nativescript.cpp index 863999d6d4..979e47f7b9 100644 --- a/modules/gdnative/nativescript/godot_nativescript.cpp +++ b/modules/gdnative/nativescript/godot_nativescript.cpp @@ -104,11 +104,7 @@ void GDAPI godot_nativescript_register_method(void *p_gdnative_handle, const cha String *s = (String *)p_gdnative_handle; Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - - if (!E) { - ERR_EXPLAIN("Attempted to register method on non-existent class!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!E, "Attempted to register method on non-existent class."); NativeScriptDesc::Method method; method.method = p_method; @@ -123,11 +119,7 @@ void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const c String *s = (String *)p_gdnative_handle; Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - - if (!E) { - ERR_EXPLAIN("Attempted to register method on non-existent class!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!E, "Attempted to register method on non-existent class."); NativeScriptDesc::Property property; property.default_value = *(Variant *)&p_attr->default_value; @@ -148,11 +140,7 @@ void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const cha String *s = (String *)p_gdnative_handle; Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - - if (!E) { - ERR_EXPLAIN("Attempted to register method on non-existent class!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!E, "Attempted to register method on non-existent class."); List<PropertyInfo> args; Vector<Variant> default_args; @@ -213,17 +201,10 @@ void GDAPI godot_nativescript_set_method_argument_information(void *p_gdnative_h String *s = (String *)p_gdnative_handle; Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - - if (!E) { - ERR_EXPLAIN("Attempted to add argument information for a method on a non-existent class!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!E, "Attempted to add argument information for a method on a non-existent class."); Map<StringName, NativeScriptDesc::Method>::Element *method = E->get().methods.find(p_function_name); - if (!method) { - ERR_EXPLAIN("Attempted to add argument information to non-existent method!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!method, "Attempted to add argument information to non-existent method."); MethodInfo *method_information = &method->get().info; @@ -247,11 +228,7 @@ void GDAPI godot_nativescript_set_class_documentation(void *p_gdnative_handle, c String *s = (String *)p_gdnative_handle; Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - - if (!E) { - ERR_EXPLAIN("Attempted to add documentation to a non-existent class!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!E, "Attempted to add documentation to a non-existent class."); E->get().documentation = *(String *)&p_documentation; } @@ -260,17 +237,10 @@ void GDAPI godot_nativescript_set_method_documentation(void *p_gdnative_handle, String *s = (String *)p_gdnative_handle; Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - - if (!E) { - ERR_EXPLAIN("Attempted to add documentation to a method on a non-existent class!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!E, "Attempted to add documentation to a method on a non-existent class."); Map<StringName, NativeScriptDesc::Method>::Element *method = E->get().methods.find(p_function_name); - if (!method) { - ERR_EXPLAIN("Attempted to add documentatino to non-existent method!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!method, "Attempted to add documentation to non-existent method."); method->get().documentation = *(String *)&p_documentation; } @@ -279,17 +249,10 @@ void GDAPI godot_nativescript_set_property_documentation(void *p_gdnative_handle String *s = (String *)p_gdnative_handle; Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - - if (!E) { - ERR_EXPLAIN("Attempted to add documentation to a property on a non-existent class!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!E, "Attempted to add documentation to a property on a non-existent class."); OrderedHashMap<StringName, NativeScriptDesc::Property>::Element property = E->get().properties.find(p_path); - if (!property) { - ERR_EXPLAIN("Attempted to add documentation to non-existent property!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!property, "Attempted to add documentation to non-existent property."); property.get().documentation = *(String *)&p_documentation; } @@ -298,17 +261,10 @@ void GDAPI godot_nativescript_set_signal_documentation(void *p_gdnative_handle, String *s = (String *)p_gdnative_handle; Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - - if (!E) { - ERR_EXPLAIN("Attempted to add documentation to a signal on a non-existent class!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!E, "Attempted to add documentation to a signal on a non-existent class."); Map<StringName, NativeScriptDesc::Signal>::Element *signal = E->get().signals_.find(p_signal_name); - if (!signal) { - ERR_EXPLAIN("Attempted to add documentation to non-existent signal!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!signal, "Attempted to add documentation to non-existent signal."); signal->get().documentation = *(String *)&p_documentation; } @@ -325,11 +281,7 @@ void GDAPI godot_nativescript_set_type_tag(void *p_gdnative_handle, const char * String *s = (String *)p_gdnative_handle; Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name); - - if (!E) { - ERR_EXPLAIN("Attempted to set type tag on a non-existent class!"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(!E, "Attempted to set type tag on a non-existent class."); E->get().type_tag = p_type_tag; } diff --git a/modules/gdnative/nativescript/nativescript.cpp b/modules/gdnative/nativescript/nativescript.cpp index 5cf144d4fe..768b12baea 100644 --- a/modules/gdnative/nativescript/nativescript.cpp +++ b/modules/gdnative/nativescript/nativescript.cpp @@ -32,6 +32,7 @@ #include "gdnative/gdnative.h" +#include "core/core_string_names.h" #include "core/global_constants.h" #include "core/io/file_access_encrypted.h" #include "core/os/file_access.h" @@ -78,7 +79,7 @@ void NativeScript::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::STRING, "script_class_name"), "set_script_class_name", "get_script_class_name"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "script_class_icon_path", PROPERTY_HINT_FILE), "set_script_class_icon_path", "get_script_class_icon_path"); - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &NativeScript::_new, MethodInfo(Variant::OBJECT, "new")); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &NativeScript::_new, MethodInfo("new")); } #define NSL NativeScriptLanguage::get_singleton() @@ -118,7 +119,10 @@ String NativeScript::get_class_name() const { void NativeScript::set_library(Ref<GDNativeLibrary> p_library) { if (!library.is_null()) { - WARN_PRINT("library on NativeScript already set. Do nothing."); + WARN_PRINT("Library in NativeScript already set. Do nothing."); + return; + } + if (p_library.is_null()) { return; } library = p_library; @@ -401,10 +405,7 @@ void NativeScript::get_script_property_list(List<PropertyInfo> *p_list) const { String NativeScript::get_class_documentation() const { NativeScriptDesc *script_data = get_script_desc(); - if (!script_data) { - ERR_EXPLAIN("Attempt to get class documentation on invalid NativeScript"); - ERR_FAIL_V(""); - } + ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get class documentation on invalid NativeScript."); return script_data->documentation; } @@ -412,10 +413,7 @@ String NativeScript::get_class_documentation() const { String NativeScript::get_method_documentation(const StringName &p_method) const { NativeScriptDesc *script_data = get_script_desc(); - if (!script_data) { - ERR_EXPLAIN("Attempt to get method documentation on invalid NativeScript"); - ERR_FAIL_V(""); - } + ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get method documentation on invalid NativeScript."); while (script_data) { @@ -428,17 +426,13 @@ String NativeScript::get_method_documentation(const StringName &p_method) const script_data = script_data->base_data; } - ERR_EXPLAIN("Attempt to get method documentation for non-existent method"); - ERR_FAIL_V(""); + ERR_FAIL_V_MSG("", "Attempt to get method documentation for non-existent method."); } String NativeScript::get_signal_documentation(const StringName &p_signal_name) const { NativeScriptDesc *script_data = get_script_desc(); - if (!script_data) { - ERR_EXPLAIN("Attempt to get signal documentation on invalid NativeScript"); - ERR_FAIL_V(""); - } + ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get signal documentation on invalid NativeScript."); while (script_data) { @@ -451,17 +445,13 @@ String NativeScript::get_signal_documentation(const StringName &p_signal_name) c script_data = script_data->base_data; } - ERR_EXPLAIN("Attempt to get signal documentation for non-existent signal"); - ERR_FAIL_V(""); + ERR_FAIL_V_MSG("", "Attempt to get signal documentation for non-existent signal."); } String NativeScript::get_property_documentation(const StringName &p_path) const { NativeScriptDesc *script_data = get_script_desc(); - if (!script_data) { - ERR_EXPLAIN("Attempt to get property documentation on invalid NativeScript"); - ERR_FAIL_V(""); - } + ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get property documentation on invalid NativeScript."); while (script_data) { @@ -474,8 +464,7 @@ String NativeScript::get_property_documentation(const StringName &p_path) const script_data = script_data->base_data; } - ERR_EXPLAIN("Attempt to get property documentation for non-existent signal"); - ERR_FAIL_V(""); + ERR_FAIL_V_MSG("", "Attempt to get property documentation for non-existent signal."); } Variant NativeScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { @@ -654,10 +643,7 @@ void NativeScriptInstance::get_property_list(List<PropertyInfo> *p_properties) c Variant res = *(Variant *)&result; godot_variant_destroy(&result); - if (res.get_type() != Variant::ARRAY) { - ERR_EXPLAIN("_get_property_list must return an array of dictionaries"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(res.get_type() != Variant::ARRAY, "_get_property_list must return an array of dictionaries."); Array arr = res; for (int i = 0; i < arr.size(); i++) { @@ -771,6 +757,26 @@ void NativeScriptInstance::notification(int p_notification) { call_multilevel("_notification", args, 1); } +String NativeScriptInstance::to_string(bool *r_valid) { + if (has_method(CoreStringNames::get_singleton()->_to_string)) { + Variant::CallError ce; + Variant ret = call(CoreStringNames::get_singleton()->_to_string, NULL, 0, ce); + if (ce.error == Variant::CallError::CALL_OK) { + if (ret.get_type() != Variant::STRING) { + if (r_valid) + *r_valid = false; + ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringNames::get_singleton()->_to_string + ", must be a String."); + } + if (r_valid) + *r_valid = true; + return ret.operator String(); + } + } + if (r_valid) + *r_valid = false; + return String(); +} + void NativeScriptInstance::refcount_incremented() { Variant::CallError err; call("_refcount_incremented", NULL, 0, err); @@ -1309,7 +1315,7 @@ void NativeScriptLanguage::unregister_binding_functions(int p_idx) { for (Set<Vector<void *> *>::Element *E = binding_instances.front(); E; E = E->next()) { Vector<void *> &binding_data = *E->get(); - if (binding_data[p_idx] && binding_functions[p_idx].second.free_instance_binding_data) + if (p_idx < binding_data.size() && binding_data[p_idx] && binding_functions[p_idx].second.free_instance_binding_data) binding_functions[p_idx].second.free_instance_binding_data(binding_functions[p_idx].second.data, binding_data[p_idx]); } @@ -1322,10 +1328,7 @@ void NativeScriptLanguage::unregister_binding_functions(int p_idx) { void *NativeScriptLanguage::get_instance_binding_data(int p_idx, Object *p_object) { ERR_FAIL_INDEX_V(p_idx, binding_functions.size(), NULL); - if (!binding_functions[p_idx].first) { - ERR_EXPLAIN("Tried to get binding data for a nativescript binding that does not exist"); - ERR_FAIL_V(NULL); - } + ERR_FAIL_COND_V_MSG(!binding_functions[p_idx].first, NULL, "Tried to get binding data for a nativescript binding that does not exist."); Vector<void *> *binding_data = (Vector<void *> *)p_object->get_script_instance_binding(lang_idx); @@ -1345,7 +1348,7 @@ void *NativeScriptLanguage::get_instance_binding_data(int p_idx, Object *p_objec if (!(*binding_data)[p_idx]) { - const void *global_type_tag = global_type_tags[p_idx].get(p_object->get_class_name()); + const void *global_type_tag = get_global_type_tag(p_idx, p_object->get_class_name()); // no binding data yet, soooooo alloc new one \o/ (*binding_data).write[p_idx] = binding_functions[p_idx].second.alloc_instance_binding_data(binding_functions[p_idx].second.data, global_type_tag, (godot_object *)p_object); @@ -1454,6 +1457,9 @@ const void *NativeScriptLanguage::get_global_type_tag(int p_idx, StringName p_cl const HashMap<StringName, const void *> &tags = global_type_tags[p_idx]; + if (!tags.has(p_class_name)) + return NULL; + const void *tag = tags.get(p_class_name); return tag; @@ -1474,8 +1480,7 @@ void NativeScriptLanguage::init_library(const Ref<GDNativeLibrary> &lib) { #endif // See if this library was "registered" already. const String &lib_path = lib->get_current_library_path(); - ERR_EXPLAIN(lib->get_name() + " does not have a library for the current platform"); - ERR_FAIL_COND(lib_path.length() == 0); + ERR_FAIL_COND_MSG(lib_path.length() == 0, lib->get_name() + " does not have a library for the current platform."); Map<String, Ref<GDNative> >::Element *E = library_gdnatives.find(lib_path); if (!E) { diff --git a/modules/gdnative/nativescript/nativescript.h b/modules/gdnative/nativescript/nativescript.h index a6865c6243..79a41df107 100644 --- a/modules/gdnative/nativescript/nativescript.h +++ b/modules/gdnative/nativescript/nativescript.h @@ -99,7 +99,7 @@ struct NativeScriptDesc { }; class NativeScript : public Script { - GDCLASS(NativeScript, Script) + GDCLASS(NativeScript, Script); #ifdef TOOLS_ENABLED Set<PlaceHolderScriptInstance *> placeholders; @@ -208,6 +208,7 @@ public: virtual bool has_method(const StringName &p_method) const; virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error); virtual void notification(int p_notification); + String to_string(bool *r_valid); virtual Ref<Script> get_script() const; virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const; virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const; @@ -369,7 +370,7 @@ inline NativeScriptDesc *NativeScript::get_script_desc() const { } class NativeReloadNode : public Node { - GDCLASS(NativeReloadNode, Node) + GDCLASS(NativeReloadNode, Node); bool unloaded; public: @@ -381,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; @@ -390,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/net/SCsub b/modules/gdnative/net/SCsub index e915703935..18ab9986b0 100644 --- a/modules/gdnative/net/SCsub +++ b/modules/gdnative/net/SCsub @@ -3,5 +3,11 @@ Import('env') Import('env_gdnative') -env_gdnative.add_source_files(env.modules_sources, '*.cpp') +env_net = env_gdnative.Clone() + +has_webrtc = env_net["module_webrtc_enabled"] +if has_webrtc: + env_net.Append(CPPDEFINES=['WEBRTC_GDNATIVE_ENABLED']) + +env_net.add_source_files(env.modules_sources, '*.cpp') diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.cpp b/modules/gdnative/net/multiplayer_peer_gdnative.cpp index bdeba149d2..d2c95efa77 100644 --- a/modules/gdnative/net/multiplayer_peer_gdnative.cpp +++ b/modules/gdnative/net/multiplayer_peer_gdnative.cpp @@ -113,6 +113,8 @@ NetworkedMultiplayerPeer::ConnectionStatus MultiplayerPeerGDNative::get_connecti } void MultiplayerPeerGDNative::_bind_methods() { + ADD_PROPERTY_DEFAULT("transfer_mode", TRANSFER_MODE_UNRELIABLE); + ADD_PROPERTY_DEFAULT("refuse_new_connections", true); } extern "C" { diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.h b/modules/gdnative/net/multiplayer_peer_gdnative.h index 7d48dc60d1..6fbc62aaa1 100644 --- a/modules/gdnative/net/multiplayer_peer_gdnative.h +++ b/modules/gdnative/net/multiplayer_peer_gdnative.h @@ -36,7 +36,7 @@ #include "modules/gdnative/include/net/godot_net.h" class MultiplayerPeerGDNative : public NetworkedMultiplayerPeer { - GDCLASS(MultiplayerPeerGDNative, NetworkedMultiplayerPeer) + GDCLASS(MultiplayerPeerGDNative, NetworkedMultiplayerPeer); protected: static void _bind_methods(); diff --git a/modules/gdnative/net/packet_peer_gdnative.h b/modules/gdnative/net/packet_peer_gdnative.h index 742fa4e7d5..8483217210 100644 --- a/modules/gdnative/net/packet_peer_gdnative.h +++ b/modules/gdnative/net/packet_peer_gdnative.h @@ -36,7 +36,7 @@ #include "modules/gdnative/include/net/godot_net.h" class PacketPeerGDNative : public PacketPeer { - GDCLASS(PacketPeerGDNative, PacketPeer) + GDCLASS(PacketPeerGDNative, PacketPeer); protected: static void _bind_methods(); diff --git a/modules/mono/editor/mono_build_info.cpp b/modules/gdnative/net/webrtc_gdnative.cpp index b386c06435..d77fa057c5 100644 --- a/modules/mono/editor/mono_build_info.cpp +++ b/modules/gdnative/net/webrtc_gdnative.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* mono_build_info.cpp */ +/* webrtc_gdnative.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,35 +28,33 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "mono_build_info.h" +#include "modules/gdnative/gdnative.h" +#include "modules/gdnative/include/net/godot_net.h" -#include "../godotsharp_dirs.h" -#include "../mono_gd/gd_mono_utils.h" +#ifdef WEBRTC_GDNATIVE_ENABLED +#include "modules/webrtc/webrtc_data_channel_gdnative.h" +#include "modules/webrtc/webrtc_peer_connection_gdnative.h" +#endif -uint32_t MonoBuildInfo::Hasher::hash(const MonoBuildInfo &p_key) { +extern "C" { - uint32_t hash = 0; - - GDMonoUtils::hash_combine(hash, p_key.solution.hash()); - GDMonoUtils::hash_combine(hash, p_key.configuration.hash()); - - return hash; +void GDAPI godot_net_bind_webrtc_peer_connection(godot_object *p_obj, const godot_net_webrtc_peer_connection *p_impl) { +#ifdef WEBRTC_GDNATIVE_ENABLED + ((WebRTCPeerConnectionGDNative *)p_obj)->set_native_webrtc_peer_connection(p_impl); +#endif } -bool MonoBuildInfo::operator==(const MonoBuildInfo &p_b) const { - - return p_b.solution == solution && p_b.configuration == configuration; +void GDAPI godot_net_bind_webrtc_data_channel(godot_object *p_obj, const godot_net_webrtc_data_channel *p_impl) { +#ifdef WEBRTC_GDNATIVE_ENABLED + ((WebRTCDataChannelGDNative *)p_obj)->set_native_webrtc_data_channel(p_impl); +#endif } -String MonoBuildInfo::get_log_dirpath() { - - return GodotSharpDirs::get_build_logs_dir().plus_file(solution.md5_text() + "_" + configuration); +godot_error GDAPI godot_net_set_webrtc_library(const godot_net_webrtc_library *p_lib) { +#ifdef WEBRTC_GDNATIVE_ENABLED + return (godot_error)WebRTCPeerConnectionGDNative::set_default_library(p_lib); +#else + return ERR_UNAVAILABLE; +#endif } - -MonoBuildInfo::MonoBuildInfo() {} - -MonoBuildInfo::MonoBuildInfo(const String &p_solution, const String &p_config) { - - solution = p_solution; - configuration = p_config; } diff --git a/modules/gdnative/pluginscript/pluginscript_instance.h b/modules/gdnative/pluginscript/pluginscript_instance.h index b279fdad8b..381c334231 100644 --- a/modules/gdnative/pluginscript/pluginscript_instance.h +++ b/modules/gdnative/pluginscript/pluginscript_instance.h @@ -62,7 +62,7 @@ public: virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error); #if 0 // Rely on default implementations provided by ScriptInstance for the moment. - // Note that multilevel call could be removed in 3.0 release, so stay tunned + // Note that multilevel call could be removed in 3.0 release, so stay tuned // (see https://godotengine.org/qa/9244/can-override-the-_ready-and-_process-functions-child-classes) virtual void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount); virtual void call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount); diff --git a/modules/gdnative/pluginscript/pluginscript_language.cpp b/modules/gdnative/pluginscript/pluginscript_language.cpp index c9d92c09ed..22898a73ce 100644 --- a/modules/gdnative/pluginscript/pluginscript_language.cpp +++ b/modules/gdnative/pluginscript/pluginscript_language.cpp @@ -159,19 +159,20 @@ String PluginScriptLanguage::make_function(const String &p_class, const String & return String(); } -Error PluginScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_force, String &r_call_hint) { +Error PluginScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_force, String &r_call_hint) { if (_desc.complete_code) { Array options; godot_error tmp = _desc.complete_code( _data, (godot_string *)&p_code, - (godot_string *)&p_base_path, + (godot_string *)&p_path, (godot_object *)p_owner, (godot_array *)&options, &r_force, (godot_string *)&r_call_hint); for (int i = 0; i < options.size(); i++) { - r_options->push_back(String(options[i])); + ScriptCodeCompletionOption option(options[i], ScriptCodeCompletionOption::KIND_PLAIN_TEXT); + r_options->push_back(option); } return (Error)tmp; } @@ -199,7 +200,7 @@ void PluginScriptLanguage::get_recognized_extensions(List<String> *p_extensions) } void PluginScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const { - // TODO: provid this statically in `godot_pluginscript_language_desc` ? + // TODO: provide this statically in `godot_pluginscript_language_desc` ? if (_desc.get_public_functions) { Array functions; _desc.get_public_functions(_data, (godot_array *)&functions); @@ -211,12 +212,12 @@ void PluginScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) c } void PluginScriptLanguage::get_public_constants(List<Pair<String, Variant> > *p_constants) const { - // TODO: provid this statically in `godot_pluginscript_language_desc` ? + // TODO: provide this statically in `godot_pluginscript_language_desc` ? if (_desc.get_public_constants) { Dictionary constants; _desc.get_public_constants(_data, (godot_dictionary *)&constants); for (const Variant *key = constants.next(); key; key = constants.next(key)) { - Variant value = constants[key]; + Variant value = constants[*key]; p_constants->push_back(Pair<String, Variant>(*key, value)); } } diff --git a/modules/gdnative/pluginscript/pluginscript_language.h b/modules/gdnative/pluginscript/pluginscript_language.h index 991be0bf12..7b3844d0b0 100644 --- a/modules/gdnative/pluginscript/pluginscript_language.h +++ b/modules/gdnative/pluginscript/pluginscript_language.h @@ -81,7 +81,7 @@ public: virtual bool can_inherit_from_file() { return true; } virtual int find_function(const String &p_function, const String &p_code) const; virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const; - virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_force, String &r_call_hint); + virtual Error complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_force, String &r_call_hint); virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const; virtual void add_global_constant(const StringName &p_variable, const Variant &p_value); 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 3450a032c5..6bb521173f 100644 --- a/modules/gdnative/pluginscript/pluginscript_script.cpp +++ b/modules/gdnative/pluginscript/pluginscript_script.cpp @@ -34,17 +34,15 @@ #include "pluginscript_instance.h" #include "pluginscript_script.h" -#if DEBUG_ENABLED -#define __ASSERT_SCRIPT_REASON "Cannot retrieve pluginscript class for this script, is you code correct ?" -#define ASSERT_SCRIPT_VALID() \ - { \ - ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \ - ERR_FAIL_COND(!can_instance()) \ - } -#define ASSERT_SCRIPT_VALID_V(ret) \ - { \ - ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \ - ERR_FAIL_COND_V(!can_instance(), ret) \ +#ifdef DEBUG_ENABLED +#define __ASSERT_SCRIPT_REASON "Cannot retrieve PluginScript class for this script, is your code correct?" +#define ASSERT_SCRIPT_VALID() \ + { \ + ERR_FAIL_COND_MSG(!can_instance(), __ASSERT_SCRIPT_REASON); \ + } +#define ASSERT_SCRIPT_VALID_V(ret) \ + { \ + ERR_FAIL_COND_V_MSG(!can_instance(), ret, __ASSERT_SCRIPT_REASON); \ } #else #define ASSERT_SCRIPT_VALID() @@ -52,7 +50,7 @@ #endif void PluginScript::_bind_methods() { - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &PluginScript::_new, MethodInfo(Variant::OBJECT, "new")); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &PluginScript::_new, MethodInfo("new")); } PluginScriptInstance *PluginScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, Variant::CallError &r_error) { @@ -77,7 +75,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; @@ -197,8 +195,7 @@ ScriptInstance *PluginScript::instance_create(Object *p_this) { // if (ScriptDebugger::get_singleton()) { // _language->debug_break_parse(get_path(), 0, msg); // } - ERR_EXPLAIN(msg); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, msg); } } @@ -229,6 +226,8 @@ void PluginScript::set_source_code(const String &p_code) { } Error PluginScript::reload(bool p_keep_state) { + ERR_FAIL_COND_V(!_language, ERR_UNCONFIGURED); + _language->lock(); ERR_FAIL_COND_V(!p_keep_state && _instances.size(), ERR_ALREADY_IN_USE); _language->unlock(); @@ -252,7 +251,19 @@ Error PluginScript::reload(bool p_keep_state) { (godot_string *)&_path, (godot_string *)&_source, (godot_error *)&err); +// Manifest's attributes must be explicitly freed +#define FREE_SCRIPT_MANIFEST(manifest) \ + { \ + godot_string_name_destroy(&manifest.name); \ + godot_string_name_destroy(&manifest.base); \ + godot_dictionary_destroy(&manifest.member_lines); \ + godot_array_destroy(&manifest.methods); \ + godot_array_destroy(&manifest.signals); \ + godot_array_destroy(&manifest.properties); \ + } + if (err) { + FREE_SCRIPT_MANIFEST(manifest); // TODO: GDscript uses `ScriptDebugger` here to jump into the parsing error return err; } @@ -270,8 +281,8 @@ Error PluginScript::reload(bool p_keep_state) { _ref_base_parent = res; } else { String name = *(StringName *)&manifest.name; - ERR_EXPLAIN(_path + ": Script '" + name + "' has an invalid parent '" + *base_name + "'."); - ERR_FAIL_V(ERR_PARSE_ERROR); + FREE_SCRIPT_MANIFEST(manifest); + ERR_FAIL_V_MSG(ERR_PARSE_ERROR, _path + ": Script '" + name + "' has an invalid parent '" + *base_name + "'."); } } } @@ -284,7 +295,7 @@ Error PluginScript::reload(bool p_keep_state) { Dictionary *members = (Dictionary *)&manifest.member_lines; for (const Variant *key = members->next(); key != NULL; key = members->next(key)) { - _member_lines[*key] = (*members)[key]; + _member_lines[*key] = (*members)[*key]; } Array *methods = (Array *)&manifest.methods; for (int i = 0; i < methods->size(); ++i) { @@ -319,13 +330,6 @@ Error PluginScript::reload(bool p_keep_state) { _methods_rpc_mode[pi.name] = MultiplayerAPI::RPCMode(int(var)); } } - // Manifest's attributes must be explicitly freed - godot_string_name_destroy(&manifest.name); - godot_string_name_destroy(&manifest.base); - godot_dictionary_destroy(&manifest.member_lines); - godot_array_destroy(&manifest.methods); - godot_array_destroy(&manifest.signals); - godot_array_destroy(&manifest.properties); #ifdef TOOLS_ENABLED /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) { @@ -333,7 +337,10 @@ Error PluginScript::reload(bool p_keep_state) { _update_placeholder(E->get()); }*/ #endif + + FREE_SCRIPT_MANIFEST(manifest); return OK; +#undef FREE_SCRIPT_MANIFEST } void PluginScript::get_script_method_list(List<MethodInfo> *r_methods) const { @@ -403,9 +410,7 @@ Error PluginScript::load_source_code(const String &p_path) { PoolVector<uint8_t> sourcef; Error err; FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); - if (err) { - ERR_FAIL_COND_V(err, err); - } + ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + p_path + "'."); int len = f->get_len(); sourcef.resize(len + 1); @@ -418,8 +423,7 @@ Error PluginScript::load_source_code(const String &p_path) { String s; if (s.parse_utf8((const char *)w.ptr())) { - ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); - ERR_FAIL_V(ERR_INVALID_DATA); + ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode."); } _source = s; @@ -473,6 +477,8 @@ MultiplayerAPI::RPCMode PluginScript::get_rset_mode(const StringName &p_variable PluginScript::PluginScript() : _data(NULL), + _desc(NULL), + _language(NULL), _tool(false), _valid(false), _script_list(this) { @@ -490,11 +496,15 @@ void PluginScript::init(PluginScriptLanguage *language) { } PluginScript::~PluginScript() { - _desc->finish(_data); + if (_desc && _data) { + _desc->finish(_data); + } #ifdef DEBUG_ENABLED - _language->lock(); - _language->_script_list.remove(&_script_list); - _language->unlock(); + if (_language) { + _language->lock(); + _language->_script_list.remove(&_script_list); + _language->unlock(); + } #endif } diff --git a/modules/gdnative/pluginscript/register_types.cpp b/modules/gdnative/pluginscript/register_types.cpp index b7ab887e11..3b46f33afb 100644 --- a/modules/gdnative/pluginscript/register_types.cpp +++ b/modules/gdnative/pluginscript/register_types.cpp @@ -114,6 +114,8 @@ void unregister_pluginscript_types() { for (List<PluginScriptLanguage *>::Element *e = pluginscript_languages.front(); e; e = e->next()) { PluginScriptLanguage *language = e->get(); ScriptServer::unregister_language(language); + ResourceLoader::remove_resource_format_loader(language->get_resource_loader()); + ResourceSaver::remove_resource_format_saver(language->get_resource_saver()); memdelete(language); } } diff --git a/modules/gdnative/register_types.cpp b/modules/gdnative/register_types.cpp index 2094dca6e4..fa59c704d5 100644 --- a/modules/gdnative/register_types.cpp +++ b/modules/gdnative/register_types.cpp @@ -50,97 +50,6 @@ #include "editor/editor_node.h" #include "gdnative_library_editor_plugin.h" #include "gdnative_library_singleton_editor.h" -// Class used to discover singleton gdnative files - -static void actual_discoverer_handler(); - -class GDNativeSingletonDiscover : public Object { - // GDCLASS(GDNativeSingletonDiscover, Object) - - virtual String get_class() const { - // okay, this is a really dirty hack. - // We're overriding get_class so we can connect it to a signal - // This works because get_class is a virtual method, so we don't - // need to register a new class to ClassDB just for this one - // little signal. - - actual_discoverer_handler(); - - return "Object"; - } -}; - -static Set<String> get_gdnative_singletons(EditorFileSystemDirectory *p_dir) { - - Set<String> file_paths; - - // check children - - for (int i = 0; i < p_dir->get_file_count(); i++) { - String file_name = p_dir->get_file(i); - String file_type = p_dir->get_file_type(i); - - if (file_type != "GDNativeLibrary") { - continue; - } - - Ref<GDNativeLibrary> lib = ResourceLoader::load(p_dir->get_file_path(i)); - if (lib.is_valid() && lib->is_singleton()) { - file_paths.insert(p_dir->get_file_path(i)); - } - } - - // check subdirectories - for (int i = 0; i < p_dir->get_subdir_count(); i++) { - Set<String> paths = get_gdnative_singletons(p_dir->get_subdir(i)); - - for (Set<String>::Element *E = paths.front(); E; E = E->next()) { - file_paths.insert(E->get()); - } - } - - return file_paths; -} - -static void actual_discoverer_handler() { - - EditorFileSystemDirectory *dir = EditorFileSystem::get_singleton()->get_filesystem(); - - Set<String> file_paths = get_gdnative_singletons(dir); - - bool changed = false; - Array current_files; - if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) { - current_files = ProjectSettings::get_singleton()->get("gdnative/singletons"); - } - Array files; - files.resize(file_paths.size()); - int i = 0; - for (Set<String>::Element *E = file_paths.front(); E; i++, E = E->next()) { - if (!current_files.has(E->get())) { - changed = true; - } - files.set(i, E->get()); - } - - // Check for removed files - if (!changed) { - for (int j = 0; j < current_files.size(); j++) { - if (!file_paths.has(current_files[j])) { - changed = true; - break; - } - } - } - - if (changed) { - - ProjectSettings::get_singleton()->set("gdnative/singletons", files); - ProjectSettings::get_singleton()->save(); - } -} - -static GDNativeSingletonDiscover *discoverer = NULL; class GDNativeExportPlugin : public EditorExportPlugin { @@ -191,6 +100,11 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty } String entry_lib_path = config->get_value("entry", key); + if (!entry_lib_path.begins_with("res://")) { + print_line("Skipping export of out-of-project library " + entry_lib_path); + continue; + } + add_shared_object(entry_lib_path, tags); } } @@ -220,6 +134,10 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty Vector<String> dependency_paths = config->get_value("dependencies", key); for (int i = 0; i < dependency_paths.size(); i++) { + if (!dependency_paths[i].begins_with("res://")) { + print_line("Skipping export of out-of-project library " + dependency_paths[i]); + continue; + } add_shared_object(dependency_paths[i], tags); } } @@ -240,7 +158,7 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty String additional_code = "extern void register_dynamic_symbol(char *name, void *address);\n" "extern void add_ios_init_callback(void (*cb)());\n"; String linker_flags = ""; - for (unsigned int i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) { + for (unsigned long i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) { String full_name = lib->get_symbol_prefix() + expected_symbols[i].name; String code = declare_pattern.replace("$name", full_name); code = code.replace("$weak", expected_symbols[i].is_required ? "" : " __attribute__((weak))"); @@ -256,7 +174,7 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty additional_code += String("void $prefixinit() {\n").replace("$prefix", lib->get_symbol_prefix()); String register_pattern = " if (&$name) register_dynamic_symbol((char *)\"$name\", (void *)$name);\n"; - for (unsigned int i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) { + for (unsigned long i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) { String full_name = lib->get_symbol_prefix() + expected_symbols[i].name; additional_code += register_pattern.replace("$name", full_name); } @@ -275,9 +193,6 @@ static void editor_init_callback() { library_editor->set_name(TTR("GDNative")); ProjectSettingsEditor::get_singleton()->get_tabs()->add_child(library_editor); - discoverer = memnew(GDNativeSingletonDiscover); - EditorFileSystem::get_singleton()->connect("filesystem_changed", discoverer, "get_class"); - Ref<GDNativeExportPlugin> export_plugin; export_plugin.instance(); @@ -335,30 +250,36 @@ void register_gdnative_types() { if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) { singletons = ProjectSettings::get_singleton()->get("gdnative/singletons"); } - - singleton_gdnatives.resize(singletons.size()); + Array excluded = Array(); + if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons_disabled")) { + excluded = ProjectSettings::get_singleton()->get("gdnative/singletons_disabled"); + } for (int i = 0; i < singletons.size(); i++) { String path = singletons[i]; - Ref<GDNativeLibrary> lib = ResourceLoader::load(path); + if (excluded.has(path)) + continue; - singleton_gdnatives.write[i].instance(); - singleton_gdnatives.write[i]->set_library(lib); + Ref<GDNativeLibrary> lib = ResourceLoader::load(path); + Ref<GDNative> singleton; + singleton.instance(); + singleton->set_library(lib); - if (!singleton_gdnatives.write[i]->initialize()) { + if (!singleton->initialize()) { // Can't initialize. Don't make a native_call then continue; } void *proc_ptr; - Error err = singleton_gdnatives[i]->get_symbol( + Error err = singleton->get_symbol( lib->get_symbol_prefix() + "gdnative_singleton", proc_ptr); if (err != OK) { - ERR_PRINT((String("No godot_gdnative_singleton in \"" + singleton_gdnatives[i]->get_library()->get_current_library_path()) + "\" found").utf8().get_data()); + ERR_PRINTS("No " + lib->get_symbol_prefix() + "gdnative_singleton in \"" + singleton->get_library()->get_current_library_path() + "\" found"); } else { + singleton_gdnatives.push_back(singleton); ((void (*)())proc_ptr)(); } } @@ -388,12 +309,6 @@ void unregister_gdnative_types() { memdelete(GDNativeCallRegistry::singleton); -#ifdef TOOLS_ENABLED - if (Engine::get_singleton()->is_editor_hint() && discoverer != NULL) { - memdelete(discoverer); - } -#endif - ResourceLoader::remove_resource_format_loader(resource_loader_gdnlib); resource_loader_gdnlib.unref(); diff --git a/modules/gdnative/videodecoder/SCsub b/modules/gdnative/videodecoder/SCsub index 8d9c1ff50e..04cc8ed604 100644 --- a/modules/gdnative/videodecoder/SCsub +++ b/modules/gdnative/videodecoder/SCsub @@ -5,5 +5,5 @@ Import('env_modules') env_vsdecoder_gdnative = env_modules.Clone() -env_vsdecoder_gdnative.Append(CPPPATH=['#modules/gdnative/include/']) +env_vsdecoder_gdnative.Prepend(CPPPATH=['#modules/gdnative/include/']) env_vsdecoder_gdnative.add_source_files(env.modules_sources, '*.cpp') diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.cpp b/modules/gdnative/videodecoder/video_stream_gdnative.cpp index 8fcebe7855..ab14f01858 100644 --- a/modules/gdnative/videodecoder/video_stream_gdnative.cpp +++ b/modules/gdnative/videodecoder/video_stream_gdnative.cpp @@ -61,8 +61,8 @@ int64_t GDAPI godot_videodecoder_file_seek(void *ptr, int64_t pos, int whence) { // file FileAccess *file = reinterpret_cast<FileAccess *>(ptr); - size_t len = file->get_len(); if (file) { + size_t len = file->get_len(); switch (whence) { case SEEK_SET: { // Just for explicitness @@ -123,9 +123,12 @@ bool VideoStreamPlaybackGDNative::open_file(const String &p_file) { godot_vector2 vec = interface->get_texture_size(data_struct); texture_size = *(Vector2 *)&vec; + // Only do memset if num_channels > 0 otherwise it will crash. + if (num_channels > 0) { + pcm = (float *)memalloc(num_channels * AUX_BUFFER_SIZE * sizeof(float)); + memset(pcm, 0, num_channels * AUX_BUFFER_SIZE * sizeof(float)); + } - pcm = (float *)memalloc(num_channels * AUX_BUFFER_SIZE * sizeof(float)); - memset(pcm, 0, num_channels * AUX_BUFFER_SIZE * sizeof(float)); pcm_write_idx = -1; samples_decoded = 0; @@ -146,28 +149,35 @@ void VideoStreamPlaybackGDNative::update(float p_delta) { ERR_FAIL_COND(interface == NULL); interface->update(data_struct, p_delta); - if (pcm_write_idx >= 0) { - // Previous remains - int mixed = mix_callback(mix_udata, pcm, samples_decoded); - if (mixed == samples_decoded) { - pcm_write_idx = -1; - } else { - samples_decoded -= mixed; - pcm_write_idx += mixed; + // Don't mix if there's no audio (num_channels == 0). + if (mix_callback && num_channels > 0) { + if (pcm_write_idx >= 0) { + // Previous remains + int mixed = mix_callback(mix_udata, pcm + pcm_write_idx * num_channels, samples_decoded); + if (mixed == samples_decoded) { + pcm_write_idx = -1; + } else { + samples_decoded -= mixed; + pcm_write_idx += mixed; + } } - } - if (pcm_write_idx < 0) { - samples_decoded = interface->get_audioframe(data_struct, pcm, AUX_BUFFER_SIZE); - pcm_write_idx = mix_callback(mix_udata, pcm, samples_decoded); - if (pcm_write_idx == samples_decoded) { - pcm_write_idx = -1; - } else { - samples_decoded -= pcm_write_idx; + if (pcm_write_idx < 0) { + samples_decoded = interface->get_audioframe(data_struct, pcm, AUX_BUFFER_SIZE); + pcm_write_idx = mix_callback(mix_udata, pcm, samples_decoded); + if (pcm_write_idx == samples_decoded) { + pcm_write_idx = -1; + } else { + samples_decoded -= pcm_write_idx; + } } } - while (interface->get_playback_position(data_struct) < time && playing) { + if (seek_backward) { + update_texture(); + seek_backward = false; + } + while (interface->get_playback_position(data_struct) < time && playing) { update_texture(); } } @@ -195,6 +205,7 @@ VideoStreamPlaybackGDNative::VideoStreamPlaybackGDNative() : mix_callback(NULL), num_channels(-1), time(0), + seek_backward(false), mix_rate(0), delay_compensation(0), pcm(NULL), @@ -259,13 +270,20 @@ void VideoStreamPlaybackGDNative::stop() { void VideoStreamPlaybackGDNative::seek(float p_time) { ERR_FAIL_COND(interface == NULL); interface->seek(data_struct, p_time); + if (p_time < time) + seek_backward = true; + time = p_time; + // reset audio buffers + memset(pcm, 0, num_channels * AUX_BUFFER_SIZE * sizeof(float)); + pcm_write_idx = -1; + samples_decoded = 0; } void VideoStreamPlaybackGDNative::set_paused(bool p_paused) { paused = p_paused; } -Ref<Texture> VideoStreamPlaybackGDNative::get_texture() { +Ref<Texture> VideoStreamPlaybackGDNative::get_texture() const { return texture; } diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.h b/modules/gdnative/videodecoder/video_stream_gdnative.h index aafd02f33d..5ff7acb616 100644 --- a/modules/gdnative/videodecoder/video_stream_gdnative.h +++ b/modules/gdnative/videodecoder/video_stream_gdnative.h @@ -121,6 +121,7 @@ class VideoStreamPlaybackGDNative : public VideoStreamPlayback { int num_channels; float time; + bool seek_backward; int mix_rate; double delay_compensation; @@ -167,7 +168,7 @@ public: //virtual int mix(int16_t* p_buffer,int p_frames)=0; - virtual Ref<Texture> get_texture(); + virtual Ref<Texture> get_texture() const; virtual void update(float p_delta); virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata); @@ -197,7 +198,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/SCsub b/modules/gdscript/SCsub index 6904154953..74e653ce43 100644 --- a/modules/gdscript/SCsub +++ b/modules/gdscript/SCsub @@ -8,4 +8,12 @@ env_gdscript = env_modules.Clone() env_gdscript.add_source_files(env.modules_sources, "*.cpp") if env['tools']: - env_gdscript.add_source_files(env.modules_sources, "./editor/*.cpp") + env_gdscript.add_source_files(env.modules_sources, "./editor/*.cpp") + + # Those two modules are required for the language server protocol + if env['module_jsonrpc_enabled'] and env['module_websocket_enabled']: + env_gdscript.add_source_files(env.modules_sources, "./language_server/*.cpp") + else: + # Using a define in the disabled case, to avoid having an extra define + # in regular builds where all modules are enabled. + env_gdscript.Append(CPPDEFINES=['GDSCRIPT_NO_LSP']) 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..502a68cd61 --- /dev/null +++ b/modules/gdscript/doc_classes/@GDScript.xml @@ -0,0 +1,1406 @@ +<?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 color constructed from integer red, green, blue, and alpha channels. Each channel should have 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 = char(65) # a is "A" + a = char(65 + 32) # a is "a" + [/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 Variant.Type] values. + [codeblock] + a = Vector2(1, 0) + # Prints 1 + print(a.length()) + a = convert(a, TYPE_STRING) + # Prints 6 as "(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 then -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. + For exponents to other bases use the method [method pow]. + [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.0 + a = floor(2.99) + # a is -3.0 + a = floor(-2.99) + [/codeblock] + [b]Note:[/b] This method returns a float. If you need an integer, you can use [code]int(s)[/code] directly. + </description> + </method> + <method name="fmod"> + <return type="float"> + </return> + <argument index="0" name="a" type="float"> + </argument> + <argument index="1" name="b" type="float"> + </argument> + <description> + Returns the floating-point remainder of [code]a/b[/code], keeping the sign of [code]a[/code]. + [codeblock] + # Remainder is 1.5 + var remainder = fmod(7, 5.5) + [/codeblock] + For the integer remainder operation, use the % operator. + </description> + </method> + <method name="fposmod"> + <return type="float"> + </return> + <argument index="0" name="a" type="float"> + </argument> + <argument index="1" name="b" type="float"> + </argument> + <description> + Returns the floating-point modulus of [code]a/b[/code] that wraps equally in positive and negative. + [codeblock] + var i = -6 + while i < 5: + prints(i, fposmod(i, 3)) + i += 1 + [/codeblock] + Produces: + [codeblock] + -6 0 + -5 1 + -4 2 + -3 0 + -2 1 + -1 2 + 0 0 + 1 1 + 2 2 + 3 0 + 4 1 + [/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 [code]true[/code] if [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 [code]true[/code] if [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="lerp_angle"> + <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> + Linearly interpolates between two angles (in radians) by a normalized value. + Similar to [method lerp] but interpolate correctly when the angles wrap around [constant @GDScript.TAU]. + [codeblock] + extends Sprite + var elapsed = 0.0 + func _process(delta): + var min_angle = deg2rad(0.0) + var max_angle = deg2rad(90.0) + rotation = lerp_angle(min_angle, max_angle, elapsed) + elapsed += delta + [/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 FileSystem dock and choosing [b]Copy Path[/b]. + [codeblock] + # Load a scene called main located in the root of the project directory. + var main = load("res://main.tscn") + [/codeblock] + [b]Important:[/b] The path must be absolute, a local path will just return [code]null[/code]. + </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 most calculators, which uses 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="ord"> + <return type="int"> + </return> + <argument index="0" name="char" type="String"> + </argument> + <description> + </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="posmod"> + <return type="int"> + </return> + <argument index="0" name="a" type="int"> + </argument> + <argument index="1" name="b" type="int"> + </argument> + <description> + Returns the integer modulus of [code]a/b[/code] that wraps equally in positive and negative. + [codeblock] + var i = -6 + while i < 5: + prints(i, posmod(i, 3)) + i += 1 + [/codeblock] + Produces: + [codeblock] + -6 0 + -5 1 + -4 2 + -3 0 + -2 1 + -1 2 + 0 0 + 1 1 + 2 2 + 3 0 + 4 1 + [/codeblock] + </description> + </method> + <method name="pow"> + <return type="float"> + </return> + <argument index="0" name="base" type="float"> + </argument> + <argument index="1" name="exp" 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] + [b]Note:[/b] Due to limitations with Godot's built-in console, this only prints to the terminal. If you need to print in the editor, use another method, such as [method print]. + </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. Note that the maximum return value is 10, which is a design decision in the implementation. + [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]. This can also be used to round a floating point number to an arbitrary number of decimals. + [codeblock] + stepify(100, 32) # Returns 96 + stepify(3.14159, 0.01) # Returns 3.14 + [/codeblock] + </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 [enum Variant.Type] values. + [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 an empty string if valid, or an error message otherwise. + [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] + [codeblock] + # Infinite rotation (in radians) + angle = wrapf(angle + 0.1, 0.0, TAU) + [/codeblock] + [b]Note:[/b] If you just want to wrap between 0.0 and [code]n[/code] (where [code]n[/code] is a positive floating-point value), it is better for performance to use the [method fmod] method like [code]fmod(number, n)[/code]. + [code]wrapf[/code] is more flexible than using the [method fmod] approach by giving the user a simple control over the minimum value. It also fully supports negative numbers, e.g. + [codeblock] + # Infinite rotation (in radians) + angle = wrapf(angle + 0.1, -PI, PI) + [/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] + [b]Note:[/b] If you just want to wrap between 0 and [code]n[/code] (where [code]n[/code] is a positive integer value), it is better for performance to use the modulo operator like [code]number % n[/code]. + [code]wrapi[/code] is more flexible than using the modulo approach by giving the user a simple control over the minimum value. It also fully supports negative numbers, e.g. + [codeblock] + # result is -2 + var result = wrapi(-6, -5, -1) + [/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. + You can also use [code]yield[/code] to wait for a function to finish: + [codeblock] + func _ready(): + yield(do_something(), "completed") + yield(do_something_else(), "completed") + print("All functions are done!") + + func do_something(): + print("Something is done!") + + func do_something_else(): + print("Something else is done!") + + # prints: + # Something is done! + # Something else is done! + # All functions are done! + [/codeblock] + When yielding on a function, the [code]completed[/code] signal will be emitted automatically when the function returns. It can, therefore, be used as the [code]signal[/code] parameter of the [code]yield[/code] method to resume. + If you are planning on calling the same function within a loop, you should consider using [code]yield(get_tree(), "idle_frame")[/code] also. + </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/doc_classes/GDScript.xml b/modules/gdscript/doc_classes/GDScript.xml index 46796c68eb..8e175a7ab8 100644 --- a/modules/gdscript/doc_classes/GDScript.xml +++ b/modules/gdscript/doc_classes/GDScript.xml @@ -4,14 +4,12 @@ A script implemented in the GDScript programming language. </brief_description> <description> - A script implemented in the GDScript programming language. The script exends the functionality of all objects that instance it. + A script implemented in the GDScript programming language. The script extends the functionality of all objects that instance it. [method new] creates a new instance of the script. [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes. </description> <tutorials> <link>https://docs.godotengine.org/en/latest/getting_started/scripting/gdscript/index.html</link> </tutorials> - <demos> - </demos> <methods> <method name="get_as_byte_code" qualifiers="const"> <return type="PoolByteArray"> @@ -21,7 +19,7 @@ </description> </method> <method name="new" qualifiers="vararg"> - <return type="Object"> + <return type="Variant"> </return> <description> Returns a new instance of the script. diff --git a/modules/gdscript/doc_classes/GDScriptFunctionState.xml b/modules/gdscript/doc_classes/GDScriptFunctionState.xml index f38f39b612..690953108f 100644 --- a/modules/gdscript/doc_classes/GDScriptFunctionState.xml +++ b/modules/gdscript/doc_classes/GDScriptFunctionState.xml @@ -8,8 +8,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="is_valid" qualifiers="const"> <return type="bool"> diff --git a/modules/gdscript/doc_classes/GDScriptNativeClass.xml b/modules/gdscript/doc_classes/GDScriptNativeClass.xml index e86b69c31c..70583d47a7 100644 --- a/modules/gdscript/doc_classes/GDScriptNativeClass.xml +++ b/modules/gdscript/doc_classes/GDScriptNativeClass.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="new"> <return type="Variant"> diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp index 4f59b06ae6..4d6279074c 100644 --- a/modules/gdscript/editor/gdscript_highlighter.cpp +++ b/modules/gdscript/editor/gdscript_highlighter.cpp @@ -56,6 +56,10 @@ static bool _is_hex_symbol(CharType c) { return ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); } +static bool _is_bin_symbol(CharType c) { + return (c == '0' || c == '1'); +} + Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) { Map<int, TextEdit::HighlighterInfo> color_map; @@ -76,6 +80,7 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_ bool in_member_variable = false; bool in_node_path = false; bool is_hex_notation = false; + bool is_bin_notation = false; bool expect_type = false; Color keyword_color; Color color; @@ -118,14 +123,26 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_ is_hex_notation = false; } + // disallow anything not a 0 or 1 + if (is_bin_notation && (_is_bin_symbol(str[j]))) { + is_number = true; + } else if (is_bin_notation) { + is_bin_notation = false; + is_number = false; + } else { + is_bin_notation = false; + } + // check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation - if ((str[j] == '.' || str[j] == 'x' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) { + if ((str[j] == '.' || str[j] == 'x' || str[j] == 'b' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) { is_number = true; is_symbol = false; is_char = false; if (str[j] == 'x' && str[j - 1] == '0') { is_hex_notation = true; + } else if (str[j] == 'b' && str[j - 1] == '0') { + is_bin_notation = true; } } @@ -230,7 +247,7 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_ in_function_args = false; } - if (expect_type && prev_is_char) { + if (expect_type && (prev_is_char || str[j] == '=')) { expect_type = false; } @@ -330,7 +347,7 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_ return color_map; } -String GDScriptSyntaxHighlighter::get_name() { +String GDScriptSyntaxHighlighter::get_name() const { return "GDScript"; } @@ -347,20 +364,28 @@ void GDScriptSyntaxHighlighter::_update_cache() { number_color = text_editor->get_color("number_color"); member_color = text_editor->get_color("member_variable_color"); - EditorSettings *settings = EditorSettings::get_singleton(); - String text_editor_color_theme = settings->get("text_editor/theme/color_theme"); + const String text_editor_color_theme = EditorSettings::get_singleton()->get("text_editor/theme/color_theme"); + const bool default_theme = text_editor_color_theme == "Default"; - bool default_theme = text_editor_color_theme == "Default"; - bool dark_theme = settings->is_dark_theme(); - - function_definition_color = Color::html(default_theme ? "#01e1ff" : dark_theme ? "#01e1ff" : "#00a5ba"); - node_path_color = Color::html(default_theme ? "#64c15a" : dark_theme ? "64c15a" : "#518b4b"); + if (default_theme || EditorSettings::get_singleton()->is_dark_theme()) { + function_definition_color = Color(0.4, 0.9, 1.0); + node_path_color = Color(0.39, 0.76, 0.35); + } else { + function_definition_color = Color(0.0, 0.65, 0.73); + node_path_color = Color(0.32, 0.55, 0.29); + } EDITOR_DEF("text_editor/highlighting/gdscript/function_definition_color", function_definition_color); EDITOR_DEF("text_editor/highlighting/gdscript/node_path_color", node_path_color); if (text_editor_color_theme == "Adaptive" || default_theme) { - settings->set_initial_value("text_editor/highlighting/gdscript/function_definition_color", function_definition_color, true); - settings->set_initial_value("text_editor/highlighting/gdscript/node_path_color", node_path_color, true); + EditorSettings::get_singleton()->set_initial_value( + "text_editor/highlighting/gdscript/function_definition_color", + function_definition_color, + true); + EditorSettings::get_singleton()->set_initial_value( + "text_editor/highlighting/gdscript/node_path_color", + node_path_color, + true); } function_definition_color = EDITOR_GET("text_editor/highlighting/gdscript/function_definition_color"); diff --git a/modules/gdscript/editor/gdscript_highlighter.h b/modules/gdscript/editor/gdscript_highlighter.h index 9dc10a5d1b..9ba2c80552 100644 --- a/modules/gdscript/editor/gdscript_highlighter.h +++ b/modules/gdscript/editor/gdscript_highlighter.h @@ -65,7 +65,7 @@ public: virtual void _update_cache(); virtual Map<int, TextEdit::HighlighterInfo> _get_line_syntax_highlighting(int p_line); - virtual String get_name(); + virtual String get_name() const; virtual List<String> get_supported_languages(); }; diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 4385cf12ad..2f620df8fb 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -30,6 +30,7 @@ #include "gdscript.h" +#include "core/core_string_names.h" #include "core/engine.h" #include "core/global_constants.h" #include "core/io/file_access_encrypted.h" @@ -66,10 +67,7 @@ void GDScriptNativeClass::_bind_methods() { Variant GDScriptNativeClass::_new() { Object *o = instance(); - if (!o) { - ERR_EXPLAIN("Class type: '" + String(name) + "' is not instantiable."); - ERR_FAIL_COND_V(!o, Variant()); - } + ERR_FAIL_COND_V_MSG(!o, Variant(), "Class type: '" + String(name) + "' is not instantiable."); Reference *ref = Object::cast_to<Reference>(o); if (ref) { @@ -101,7 +99,7 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco #endif instance->owner->set_script_instance(instance); - /* STEP 2, INITIALIZE AND CONSRTUCT */ + /* STEP 2, INITIALIZE AND CONSTRUCT */ #ifndef NO_THREADS GDScriptLanguage::singleton->lock->lock(); @@ -157,8 +155,7 @@ Variant GDScript::_new(const Variant **p_args, int p_argcount, Variant::CallErro } else { owner = memnew(Reference); //by default, no base means use reference } - ERR_EXPLAIN("Can't inherit from a virtual class"); - ERR_FAIL_COND_V(!owner, Variant()); + ERR_FAIL_COND_V_MSG(!owner, Variant(), "Can't inherit from a virtual class."); Reference *r = Object::cast_to<Reference>(owner); if (r) { @@ -202,7 +199,7 @@ StringName GDScript::get_instance_base_type() const { if (native.is_valid()) return native->get_name(); - if (base.is_valid()) + if (base.is_valid() && base->is_valid()) return base->get_instance_base_type(); return StringName(); } @@ -226,7 +223,7 @@ void GDScript::get_script_method_list(List<MethodInfo> *p_list) const { const GDScript *current = this; while (current) { - for (const Map<StringName, GDScriptFunction *>::Element *E = member_functions.front(); E; E = E->next()) { + for (const Map<StringName, GDScriptFunction *>::Element *E = current->member_functions.front(); E; E = E->next()) { GDScriptFunction *func = E->get(); MethodInfo mi; mi.name = E->key(); @@ -325,13 +322,12 @@ ScriptInstance *GDScript::instance_create(Object *p_this) { if (ScriptDebugger::get_singleton()) { GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'"); } - ERR_EXPLAIN("Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'"); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type '" + p_this->get_class() + "'" + "."); } } Variant::CallError unchecked_error; - return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error); + return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this) != NULL, unchecked_error); } PlaceHolderScriptInstance *GDScript::placeholder_instance_create(Object *p_this) { @@ -490,7 +486,7 @@ bool GDScript::_update_exports() { placeholder_fallback_enabled = false; - if (base_cache.is_valid()) { + if (base_cache.is_valid() && base_cache->is_valid()) { if (base_cache->_update_exports()) { changed = true; } @@ -597,7 +593,7 @@ Error GDScript::reload(bool p_keep_state) { return err; } } -#if DEBUG_ENABLED +#ifdef DEBUG_ENABLED for (const List<GDScriptWarning>::Element *E = parser.get_warnings().front(); E; E = E->next()) { const GDScriptWarning &warning = E->get(); if (ScriptDebugger::get_singleton()) { @@ -647,10 +643,7 @@ Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p Map<StringName, GDScriptFunction *>::Element *E = top->member_functions.find(p_method); if (E) { - if (!E->get()->is_static()) { - ERR_EXPLAIN("Can't call non-static function: '" + String(p_method) + "' in script."); - ERR_FAIL_V(Variant()); - } + ERR_FAIL_COND_V_MSG(!E->get()->is_static(), Variant(), "Can't call non-static function '" + String(p_method) + "' in script."); return E->get()->call(NULL, p_args, p_argcount, r_error); } @@ -717,7 +710,7 @@ void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const { void GDScript::_bind_methods() { - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo(Variant::OBJECT, "new")); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo("new")); ClassDB::bind_method(D_METHOD("get_as_byte_code"), &GDScript::get_as_byte_code); } @@ -825,8 +818,7 @@ Error GDScript::load_source_code(const String &p_path) { String s; if (s.parse_utf8((const char *)w.ptr())) { - ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); - ERR_FAIL_V(ERR_INVALID_DATA); + ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode."); } source = s; @@ -1064,7 +1056,7 @@ Variant::Type GDScriptInstance::get_property_type(const StringName &p_name, bool } void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const { - // exported members, not doen yet! + // exported members, not done yet! const GDScript *sptr = script.ptr(); List<PropertyInfo> props; @@ -1078,11 +1070,8 @@ void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const Variant ret = const_cast<GDScriptFunction *>(E->get())->call(const_cast<GDScriptInstance *>(this), NULL, 0, err); if (err.error == Variant::CallError::CALL_OK) { - if (ret.get_type() != Variant::ARRAY) { + ERR_FAIL_COND_MSG(ret.get_type() != Variant::ARRAY, "Wrong type for _get_property_list, must be an array of dictionaries."); - ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries."); - ERR_FAIL(); - } Array arr = ret; for (int i = 0; i < arr.size(); i++) { @@ -1166,8 +1155,6 @@ bool GDScriptInstance::has_method(const StringName &p_method) const { } Variant GDScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { - //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str()); - GDScript *sptr = script.ptr(); while (sptr) { Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method); @@ -1234,6 +1221,26 @@ void GDScriptInstance::notification(int p_notification) { } } +String GDScriptInstance::to_string(bool *r_valid) { + if (has_method(CoreStringNames::get_singleton()->_to_string)) { + Variant::CallError ce; + Variant ret = call(CoreStringNames::get_singleton()->_to_string, NULL, 0, ce); + if (ce.error == Variant::CallError::CALL_OK) { + if (ret.get_type() != Variant::STRING) { + if (r_valid) + *r_valid = false; + ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringNames::get_singleton()->_to_string + ", must be a String."); + } + if (r_valid) + *r_valid = true; + return ret.operator String(); + } + } + if (r_valid) + *r_valid = false; + return String(); +} + Ref<Script> GDScriptInstance::get_script() const { return script; @@ -1943,7 +1950,11 @@ String GDScriptWarning::get_message() const { } break; case UNUSED_VARIABLE: { CHECK_SYMBOLS(1); - return "The local variable '" + symbols[0] + "' is declared but never used in the block."; + return "The local variable '" + symbols[0] + "' is declared but never used in the block. If this is intended, prefix it with an underscore: '_" + symbols[0] + "'"; + } break; + case SHADOWED_VARIABLE: { + CHECK_SYMBOLS(2); + return "The local variable '" + symbols[0] + "' is shadowing an already-defined variable at line " + symbols[1] + "."; } break; case UNUSED_CLASS_VARIABLE: { CHECK_SYMBOLS(1); @@ -1951,7 +1962,7 @@ String GDScriptWarning::get_message() const { } break; case UNUSED_ARGUMENT: { CHECK_SYMBOLS(2); - return "The argument '" + symbols[1] + "' is never used in the function '" + symbols[0] + "'."; + return "The argument '" + symbols[1] + "' is never used in the function '" + symbols[0] + "'. If this is intended, prefix it with an underscore: '_" + symbols[1] + "'"; } break; case UNREACHABLE_CODE: { CHECK_SYMBOLS(1); @@ -2031,8 +2042,7 @@ String GDScriptWarning::get_message() const { } break; case WARNING_MAX: break; // Can't happen, but silences warning } - ERR_EXPLAIN("Invalid GDScript warning code: " + get_name_from_code(code)); - ERR_FAIL_V(String()); + ERR_FAIL_V_MSG(String(), "Invalid GDScript warning code: " + get_name_from_code(code) + "."); #undef CHECK_SYMBOLS } @@ -2048,6 +2058,7 @@ String GDScriptWarning::get_name_from_code(Code p_code) { "UNASSIGNED_VARIABLE", "UNASSIGNED_VARIABLE_OP_ASSIGN", "UNUSED_VARIABLE", + "SHADOWED_VARIABLE", "UNUSED_CLASS_VARIABLE", "UNUSED_ARGUMENT", "UNREACHABLE_CODE", @@ -2083,8 +2094,7 @@ GDScriptWarning::Code GDScriptWarning::get_code_from_name(const String &p_name) } } - ERR_EXPLAIN("Invalid GDScript warning name: " + p_name); - ERR_FAIL_V(WARNING_MAX); + ERR_FAIL_V_MSG(WARNING_MAX, "Invalid GDScript warning name: " + p_name); } #endif // DEBUG_ENABLED @@ -2129,10 +2139,12 @@ GDScriptLanguage::GDScriptLanguage() { #ifdef DEBUG_ENABLED GLOBAL_DEF("debug/gdscript/warnings/enable", true); GLOBAL_DEF("debug/gdscript/warnings/treat_warnings_as_errors", false); + GLOBAL_DEF("debug/gdscript/warnings/exclude_addons", true); GLOBAL_DEF("debug/gdscript/completion/autocomplete_setters_and_getters", false); for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) { String warning = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)i).to_lower(); - GLOBAL_DEF("debug/gdscript/warnings/" + warning, !warning.begins_with("unsafe_")); + bool default_enabled = !warning.begins_with("unsafe_") && i != GDScriptWarning::UNUSED_CLASS_VARIABLE; + GLOBAL_DEF("debug/gdscript/warnings/" + warning, default_enabled); } #endif // DEBUG_ENABLED } @@ -2165,11 +2177,11 @@ RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_ori script->set_script_path(p_original_path); // script needs this. script->set_path(p_original_path); Error err = script->load_byte_code(p_path); - ERR_FAIL_COND_V(err != OK, RES()); + ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot load byte code from file '" + p_path + "'."); } else { Error err = script->load_source_code(p_path); - ERR_FAIL_COND_V(err != OK, RES()); + ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot load source code from file '" + p_path + "'."); script->set_script_path(p_original_path); // script needs this. script->set_path(p_original_path); @@ -2205,7 +2217,7 @@ String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) con void ResourceFormatLoaderGDScript::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { FileAccessRef file = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND(!file); + ERR_FAIL_COND_MSG(!file, "Cannot open file '" + p_path + "'."); String source = file->get_as_utf8_string(); if (source.empty()) { @@ -2232,10 +2244,7 @@ Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resou Error err; FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); - if (err) { - - ERR_FAIL_COND_V(err, err); - } + ERR_FAIL_COND_V_MSG(err, err, "Cannot save GDScript file '" + p_path + "'."); file->store_string(source); if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h index ded873c7d3..a5ad23c75d 100644 --- a/modules/gdscript/gdscript.h +++ b/modules/gdscript/gdscript.h @@ -251,6 +251,7 @@ public: Variant debug_get_member_by_index(int p_idx) const { return members[p_idx]; } virtual void notification(int p_notification); + String to_string(bool *r_valid); virtual Ref<Script> get_script() const; @@ -273,6 +274,7 @@ struct GDScriptWarning { UNASSIGNED_VARIABLE, // Variable used but never assigned UNASSIGNED_VARIABLE_OP_ASSIGN, // Variable never assigned but used in an assignment operation (+=, *=, etc) UNUSED_VARIABLE, // Local variable is declared but never used + SHADOWED_VARIABLE, // Variable name shadowed by other variable UNUSED_CLASS_VARIABLE, // Class variable is declared but never used in the file UNUSED_ARGUMENT, // Function argument is never used UNREACHABLE_CODE, // Code after a return statement @@ -406,9 +408,10 @@ public: csi.resize(_debug_call_stack_pos); for (int i = 0; i < _debug_call_stack_pos; i++) { csi.write[_debug_call_stack_pos - i - 1].line = _call_stack[i].line ? *_call_stack[i].line : 0; - if (_call_stack[i].function) + if (_call_stack[i].function) { csi.write[_debug_call_stack_pos - i - 1].func = _call_stack[i].function->get_name(); - csi.write[_debug_call_stack_pos - i - 1].file = _call_stack[i].function->get_script()->get_path(); + csi.write[_debug_call_stack_pos - i - 1].file = _call_stack[i].function->get_script()->get_path(); + } } return csi; } @@ -444,6 +447,7 @@ public: virtual void get_reserved_words(List<String> *p_words) const; virtual void get_comment_delimiters(List<String> *p_delimiters) const; virtual void get_string_delimiters(List<String> *p_delimiters) const; + virtual String _get_processed_template(const String &p_template, const String &p_base_class_name) const; virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; virtual bool is_using_templates(); virtual void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script); @@ -454,9 +458,9 @@ public: virtual bool can_inherit_from_file() { return true; } virtual int find_function(const String &p_function, const String &p_code) const; virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const; - virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_forced, String &r_call_hint); + virtual Error complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint); #ifdef TOOLS_ENABLED - virtual Error lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result); + virtual Error lookup_code(const String &p_code, const String &p_symbol, const String &p_path, Object *p_owner, LookupResult &r_result); #endif virtual String _get_indentation() const; virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const; @@ -505,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; @@ -515,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_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index ae67521749..dea2225e91 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -480,16 +480,16 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: switch (cast_type.kind) { case GDScriptDataType::BUILTIN: { codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_BUILTIN); - codegen.opcodes.push_back(cn->cast_type.builtin_type); + codegen.opcodes.push_back(cast_type.builtin_type); } break; case GDScriptDataType::NATIVE: { int class_idx; - if (GDScriptLanguage::get_singleton()->get_global_map().has(cn->cast_type.native_type)) { + if (GDScriptLanguage::get_singleton()->get_global_map().has(cast_type.native_type)) { - class_idx = GDScriptLanguage::get_singleton()->get_global_map()[cn->cast_type.native_type]; + class_idx = GDScriptLanguage::get_singleton()->get_global_map()[cast_type.native_type]; class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root) } else { - _set_error("Invalid native class type '" + String(cn->cast_type.native_type) + "'.", cn); + _set_error("Invalid native class type '" + String(cast_type.native_type) + "'.", cn); return -1; } codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_NATIVE); // perform operator @@ -498,7 +498,7 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: case GDScriptDataType::SCRIPT: case GDScriptDataType::GDSCRIPT: { - Variant script = cn->cast_type.script_type; + Variant script = cast_type.script_type; int idx = codegen.get_constant_pos(script); idx |= GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS; //make it a local constant (faster access) @@ -1073,7 +1073,7 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: int set_index; bool named = false; - if (static_cast<const GDScriptParser::OperatorNode *>(op)->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED) { + if (op->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED) { set_index = codegen.get_name_map_pos(static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1])->name); named = true; @@ -1241,8 +1241,7 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: } break; default: { - ERR_EXPLAIN("Bug in bytecode compiler, unexpected operator #" + itos(on->op) + " in parse tree while parsing expression."); - ERR_FAIL_V(0); //unreachable code + ERR_FAIL_V_MSG(0, "Bug in bytecode compiler, unexpected operator #" + itos(on->op) + " in parse tree while parsing expression."); //unreachable code } break; } @@ -1255,12 +1254,9 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser:: //TYPE_TYPE, default: { - ERR_EXPLAIN("Bug in bytecode compiler, unexpected node in parse tree while parsing expression."); - ERR_FAIL_V(-1); //unreachable code + ERR_FAIL_V_MSG(-1, "Bug in bytecode compiler, unexpected node in parse tree while parsing expression."); //unreachable code } break; } - - ERR_FAIL_V(-1); //unreachable code } Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::BlockNode *p_block, int p_stack_level, int p_break_addr, int p_continue_addr) { @@ -1524,8 +1520,16 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Blo if (ret2 < 0) return ERR_PARSE_ERROR; + int message_ret = 0; + if (as->message) { + message_ret = _parse_expression(codegen, as->message, p_stack_level + 1, false); + if (message_ret < 0) + return ERR_PARSE_ERROR; + } + codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSERT); codegen.opcodes.push_back(ret2); + codegen.opcodes.push_back(message_ret); #endif } break; case GDScriptParser::Node::TYPE_BREAKPOINT: { @@ -1863,6 +1867,19 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar p_script->base = base; p_script->_base = base.ptr(); p_script->member_indices = base->member_indices; + + if (p_class->base_type.kind == GDScriptParser::DataType::CLASS) { + if (!parsed_classes.has(p_script->_base)) { + if (parsing_classes.has(p_script->_base)) { + _set_error("Cyclic class reference for '" + String(p_class->name) + "'.", p_class); + return ERR_PARSE_ERROR; + } + Error err = _parse_class_level(p_script->_base, p_class->base_type.class_type, p_keep_state); + if (err) { + return err; + } + } + } } break; default: { _set_error("Parser bug: invalid inheritance.", p_class); @@ -1964,12 +1981,12 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar for (int i = 0; i < p_class->subclasses.size(); i++) { StringName name = p_class->subclasses[i]->name; - - GDScript *subclass = p_script->subclasses[name].ptr(); + Ref<GDScript> &subclass = p_script->subclasses[name]; + GDScript *subclass_ptr = subclass.ptr(); // Subclass might still be parsing, just skip it - if (!parsed_classes.has(subclass) && !parsing_classes.has(subclass)) { - Error err = _parse_class_level(subclass, p_class->subclasses[i], p_keep_state); + if (!parsed_classes.has(subclass_ptr) && !parsing_classes.has(subclass_ptr)) { + Error err = _parse_class_level(subclass_ptr, p_class->subclasses[i], p_keep_state); if (err) return err; } @@ -2055,7 +2072,7 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa } instance->owner->set_script_instance(instance); - /* STEP 2, INITIALIZE AND CONSRTUCT */ + /* STEP 2, INITIALIZE AND CONSTRUCT */ Variant::CallError ce; p_script->initializer->call(instance, NULL, 0, ce); diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp index fafc73b7e6..280bc37dc0 100644 --- a/modules/gdscript/gdscript_editor.cpp +++ b/modules/gdscript/gdscript_editor.cpp @@ -44,48 +44,62 @@ void GDScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const p_delimiters->push_back("#"); } + void GDScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const { p_delimiters->push_back("\" \""); p_delimiters->push_back("' '"); p_delimiters->push_back("\"\"\" \"\"\""); } + +String GDScriptLanguage::_get_processed_template(const String &p_template, const String &p_base_class_name) const { + + String processed_template = p_template; + +#ifdef TOOLS_ENABLED + if (EDITOR_DEF("text_editor/completion/add_type_hints", false)) { + processed_template = processed_template.replace("%INT_TYPE%", ": int"); + processed_template = processed_template.replace("%STRING_TYPE%", ": String"); + processed_template = processed_template.replace("%FLOAT_TYPE%", ": float"); + processed_template = processed_template.replace("%VOID_RETURN%", " -> void"); + } else { + processed_template = processed_template.replace("%INT_TYPE%", ""); + processed_template = processed_template.replace("%STRING_TYPE%", ""); + processed_template = processed_template.replace("%FLOAT_TYPE%", ""); + processed_template = processed_template.replace("%VOID_RETURN%", ""); + } +#else + processed_template = processed_template.replace("%INT_TYPE%", ""); + processed_template = processed_template.replace("%STRING_TYPE%", ""); + processed_template = processed_template.replace("%FLOAT_TYPE%", ""); + processed_template = processed_template.replace("%VOID_RETURN%", ""); +#endif + + processed_template = processed_template.replace("%BASE%", p_base_class_name); + processed_template = processed_template.replace("%TS%", _get_indentation()); + + return processed_template; +} + Ref<Script> GDScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const { String _template = "extends %BASE%\n" "\n" + "\n" "# Declare member variables here. Examples:\n" "# var a%INT_TYPE% = 2\n" "# var b%STRING_TYPE% = \"text\"\n" "\n" + "\n" "# Called when the node enters the scene tree for the first time.\n" "func _ready()%VOID_RETURN%:\n" "%TS%pass # Replace with function body.\n" "\n" + "\n" "# Called every frame. 'delta' is the elapsed time since the previous frame.\n" "#func _process(delta%FLOAT_TYPE%)%VOID_RETURN%:\n" "#%TS%pass\n"; -#ifdef TOOLS_ENABLED - if (EDITOR_DEF("text_editor/completion/add_type_hints", false)) { - _template = _template.replace("%INT_TYPE%", ": int"); - _template = _template.replace("%STRING_TYPE%", ": String"); - _template = _template.replace("%FLOAT_TYPE%", ": float"); - _template = _template.replace("%VOID_RETURN%", " -> void"); - } else { - _template = _template.replace("%INT_TYPE%", ""); - _template = _template.replace("%STRING_TYPE%", ""); - _template = _template.replace("%FLOAT_TYPE%", ""); - _template = _template.replace("%VOID_RETURN%", ""); - } -#else - _template = _template.replace("%INT_TYPE%", ""); - _template = _template.replace("%STRING_TYPE%", ""); - _template = _template.replace("%FLOAT_TYPE%", ""); - _template = _template.replace("%VOID_RETURN%", ""); -#endif - - _template = _template.replace("%BASE%", p_base_class_name); - _template = _template.replace("%TS%", _get_indentation()); + _template = _get_processed_template(_template, p_base_class_name); Ref<GDScript> script; script.instance(); @@ -101,10 +115,8 @@ bool GDScriptLanguage::is_using_templates() { void GDScriptLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) { - String src = p_script->get_source_code(); - src = src.replace("%BASE%", p_base_class_name); - src = src.replace("%TS%", _get_indentation()); - p_script->set_source_code(src); + String _template = _get_processed_template(p_script->get_source_code(), p_base_class_name); + p_script->set_source_code(_template); } bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { @@ -150,7 +162,11 @@ bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int & for (int i = 0; i < cl->subclasses.size(); i++) { for (int j = 0; j < cl->subclasses[i]->functions.size(); j++) { - funcs[cl->subclasses[i]->functions[j]->line] = String(cl->subclasses[i]->name) + "." + String(cl->subclasses[i]->functions[j]->name); + funcs[cl->subclasses[i]->functions[j]->line] = String(cl->subclasses[i]->name) + "." + cl->subclasses[i]->functions[j]->name; + } + for (int j = 0; j < cl->subclasses[i]->static_functions.size(); j++) { + + funcs[cl->subclasses[i]->static_functions[j]->line] = String(cl->subclasses[i]->name) + "." + cl->subclasses[i]->static_functions[j]->name; } } @@ -210,7 +226,7 @@ bool GDScriptLanguage::debug_break_parse(const String &p_file, int p_line, const _debug_parse_err_line = p_line; _debug_parse_err_file = p_file; _debug_error = p_error; - ScriptDebugger::get_singleton()->debug(this, false); + ScriptDebugger::get_singleton()->debug(this, false, true); return true; } else { return false; @@ -224,7 +240,8 @@ bool GDScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) _debug_parse_err_line = -1; _debug_parse_err_file = ""; _debug_error = p_error; - ScriptDebugger::get_singleton()->debug(this, p_allow_continue); + bool is_error_breakpoint = p_error != "Breakpoint"; + ScriptDebugger::get_singleton()->debug(this, p_allow_continue, is_error_breakpoint); return true; } else { return false; @@ -373,8 +390,6 @@ void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant> String GDScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) { - if (_debug_parse_err_line >= 0) - return ""; return ""; } @@ -500,10 +515,14 @@ struct GDScriptCompletionIdentifier { assigned_expression(NULL) {} }; -static void _get_directory_contents(EditorFileSystemDirectory *p_dir, Set<String> &r_list) { +static void _get_directory_contents(EditorFileSystemDirectory *p_dir, Map<String, ScriptCodeCompletionOption> &r_list) { + + const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\""; for (int i = 0; i < p_dir->get_file_count(); i++) { - r_list.insert("\"" + p_dir->get_file_path(i) + "\""); + ScriptCodeCompletionOption option(p_dir->get_file_path(i), ScriptCodeCompletionOption::KIND_FILE_PATH); + option.insert_text = quote_style + option.display + quote_style; + r_list.insert(option.display, option); } for (int i = 0; i < p_dir->get_subdir_count(); i++) { @@ -619,7 +638,7 @@ static GDScriptCompletionIdentifier _type_from_gdtype(const GDScriptDataType &p_ switch (p_gdtype.kind) { case GDScriptDataType::UNINITIALIZED: { - ERR_EXPLAIN("Uninitialized completion. Please report a bug."); + ERR_PRINT("Uninitialized completion. Please report a bug."); } break; case GDScriptDataType::BUILTIN: { ci.type.kind = GDScriptParser::DataType::BUILTIN; @@ -1061,7 +1080,8 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G case GDScriptParser::OperatorNode::OP_BIT_AND: vop = Variant::OP_BIT_AND; break; case GDScriptParser::OperatorNode::OP_BIT_OR: vop = Variant::OP_BIT_OR; break; case GDScriptParser::OperatorNode::OP_BIT_XOR: vop = Variant::OP_BIT_XOR; break; - default: {} + default: { + } } if (vop == Variant::OP_MAX) { @@ -1116,7 +1136,8 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G } break; } } break; - default: {} + default: { + } } // It may have found a null, but that's never useful @@ -1794,14 +1815,15 @@ static String _make_arguments_hint(const GDScriptParser::FunctionNode *p_functio return arghint; } -static void _find_enumeration_candidates(const String p_enum_hint, Set<String> &r_result) { +static void _find_enumeration_candidates(const String p_enum_hint, Map<String, ScriptCodeCompletionOption> &r_result) { if (p_enum_hint.find(".") == -1) { // Global constant StringName current_enum = p_enum_hint; for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) { if (GlobalConstants::get_global_constant_enum(i) == current_enum) { - r_result.insert(GlobalConstants::get_global_constant_name(i)); + ScriptCodeCompletionOption option(GlobalConstants::get_global_constant_name(i), ScriptCodeCompletionOption::KIND_ENUM); + r_result.insert(option.display, option); } } } else { @@ -1816,15 +1838,17 @@ static void _find_enumeration_candidates(const String p_enum_hint, Set<String> & ClassDB::get_enum_constants(class_name, enum_name, &enum_constants); for (List<StringName>::Element *E = enum_constants.front(); E; E = E->next()) { String candidate = class_name + "." + E->get(); - r_result.insert(candidate); + ScriptCodeCompletionOption option(candidate, ScriptCodeCompletionOption::KIND_ENUM); + r_result.insert(option.display, option); } } } -static void _find_identifiers_in_block(const GDScriptCompletionContext &p_context, Set<String> &r_result) { +static void _find_identifiers_in_block(const GDScriptCompletionContext &p_context, Map<String, ScriptCodeCompletionOption> &r_result) { for (Map<StringName, GDScriptParser::LocalVarNode *>::Element *E = p_context.block->variables.front(); E; E = E->next()) { if (E->get()->line < p_context.line) { - r_result.insert(E->key().operator String()); + ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_VARIABLE); + r_result.insert(option.display, option); } } if (p_context.block->parent_block) { @@ -1834,40 +1858,47 @@ static void _find_identifiers_in_block(const GDScriptCompletionContext &p_contex } } -static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Set<String> &r_result); +static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result); -static void _find_identifiers_in_class(const GDScriptCompletionContext &p_context, bool p_static, bool p_only_functions, bool p_parent_only, Set<String> &r_result) { +static void _find_identifiers_in_class(const GDScriptCompletionContext &p_context, bool p_static, bool p_only_functions, bool p_parent_only, Map<String, ScriptCodeCompletionOption> &r_result) { if (!p_parent_only) { if (!p_static && !p_only_functions) { for (int i = 0; i < p_context._class->variables.size(); i++) { - r_result.insert(p_context._class->variables[i].identifier); + ScriptCodeCompletionOption option(p_context._class->variables[i].identifier, ScriptCodeCompletionOption::KIND_MEMBER); + r_result.insert(option.display, option); } } if (!p_only_functions) { for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_context._class->constant_expressions.front(); E; E = E->next()) { - r_result.insert(E->key()); + ScriptCodeCompletionOption option(E->key(), ScriptCodeCompletionOption::KIND_CONSTANT); + r_result.insert(option.display, option); } for (int i = 0; i < p_context._class->subclasses.size(); i++) { - r_result.insert(p_context._class->subclasses[i]->name); + ScriptCodeCompletionOption option(p_context._class->subclasses[i]->name, ScriptCodeCompletionOption::KIND_CLASS); + r_result.insert(option.display, option); } } for (int i = 0; i < p_context._class->static_functions.size(); i++) { + ScriptCodeCompletionOption option(p_context._class->static_functions[i]->name.operator String(), ScriptCodeCompletionOption::KIND_FUNCTION); if (p_context._class->static_functions[i]->arguments.size()) { - r_result.insert(p_context._class->static_functions[i]->name.operator String() + "("); + option.insert_text += "("; } else { - r_result.insert(p_context._class->static_functions[i]->name.operator String() + "()"); + option.insert_text += "()"; } + r_result.insert(option.display, option); } if (!p_static) { for (int i = 0; i < p_context._class->functions.size(); i++) { + ScriptCodeCompletionOption option(p_context._class->functions[i]->name.operator String(), ScriptCodeCompletionOption::KIND_FUNCTION); if (p_context._class->functions[i]->arguments.size()) { - r_result.insert(p_context._class->functions[i]->name.operator String() + "("); + option.insert_text += "("; } else { - r_result.insert(p_context._class->functions[i]->name.operator String() + "()"); + option.insert_text += "()"; } + r_result.insert(option.display, option); } } } @@ -1885,12 +1916,14 @@ static void _find_identifiers_in_class(const GDScriptCompletionContext &p_contex _find_identifiers_in_base(c, base_type, p_only_functions, r_result); } -static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Set<String> &r_result) { +static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result) { GDScriptParser::DataType base_type = p_base.type; bool _static = base_type.is_meta_type; if (_static && base_type.kind != GDScriptParser::DataType::BUILTIN) { - r_result.insert("new("); + ScriptCodeCompletionOption option("new", ScriptCodeCompletionOption::KIND_FUNCTION); + option.insert_text += "("; + r_result.insert(option.display, option); } while (base_type.has_type) { @@ -1907,27 +1940,40 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context Ref<GDScript> script = base_type.script_type; if (script.is_valid()) { if (!_static && !p_only_functions) { + if (p_context.base && p_context.base->get_script_instance()) { + List<PropertyInfo> members; + p_context.base->get_script_instance()->get_property_list(&members); + for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) { + ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER); + r_result.insert(option.display, option); + } + } for (const Set<StringName>::Element *E = script->get_members().front(); E; E = E->next()) { - r_result.insert(E->get().operator String()); + ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_MEMBER); + r_result.insert(option.display, option); } } if (!p_only_functions) { for (const Map<StringName, Variant>::Element *E = script->get_constants().front(); E; E = E->next()) { - r_result.insert(E->key().operator String()); + ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CONSTANT); + r_result.insert(option.display, option); } } for (const Map<StringName, GDScriptFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) { if (!_static || E->get()->is_static()) { + ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_FUNCTION); if (E->get()->get_argument_count()) { - r_result.insert(E->key().operator String() + "("); + option.insert_text += "("; } else { - r_result.insert(E->key().operator String() + "()"); + option.insert_text += "()"; } + r_result.insert(option.display, option); } } if (!p_only_functions) { for (const Map<StringName, Ref<GDScript> >::Element *E = script->get_subclasses().front(); E; E = E->next()) { - r_result.insert(E->key().operator String()); + ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS); + r_result.insert(option.display, option); } } base_type = GDScriptParser::DataType(); @@ -1938,7 +1984,7 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context } else { base_type.has_type = script->get_instance_base_type() != StringName(); base_type.kind = GDScriptParser::DataType::NATIVE; - base_type.script_type = script->get_instance_base_type(); + base_type.native_type = script->get_instance_base_type(); } } else { return; @@ -1951,25 +1997,29 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context List<PropertyInfo> members; scr->get_script_property_list(&members); for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) { - r_result.insert(E->get().name); + ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER); + r_result.insert(option.display, option); } } if (!p_only_functions) { Map<StringName, Variant> constants; scr->get_constants(&constants); for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) { - r_result.insert(E->key().operator String()); + ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CONSTANT); + r_result.insert(option.display, option); } } List<MethodInfo> methods; scr->get_script_method_list(&methods); for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION); if (E->get().arguments.size()) { - r_result.insert(E->get().name + "("); + option.insert_text += "("; } else { - r_result.insert(E->get().name + "()"); + option.insert_text += "()"; } + r_result.insert(option.display, option); } Ref<Script> base_script = scr->get_base_script(); @@ -1996,7 +2046,8 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context List<String> constants; ClassDB::get_integer_constant_list(type, &constants); for (List<String>::Element *E = constants.front(); E; E = E->next()) { - r_result.insert(E->get()); + ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CONSTANT); + r_result.insert(option.display, option); } if (!_static) { @@ -2009,7 +2060,8 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context if (E->get().name.find("/") != -1) { continue; } - r_result.insert(E->get().name); + ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER); + r_result.insert(option.display, option); } } } @@ -2022,11 +2074,13 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context if (E->get().name.begins_with("_")) { continue; } + ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION); if (E->get().arguments.size()) { - r_result.insert(E->get().name + "("); + option.insert_text += "("; } else { - r_result.insert(E->get().name + "()"); + option.insert_text += "()"; } + r_result.insert(option.display, option); } } @@ -2041,11 +2095,12 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context if (!p_only_functions) { List<PropertyInfo> members; - tmp.get_property_list(&members); + p_base.value.get_property_list(&members); for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) { if (String(E->get().name).find("/") == -1) { - r_result.insert(E->get().name); + ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER); + r_result.insert(option.display, option); } } } @@ -2053,11 +2108,13 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context List<MethodInfo> methods; tmp.get_method_list(&methods); for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { + ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION); if (E->get().arguments.size()) { - r_result.insert(E->get().name + "("); + option.insert_text += "("; } else { - r_result.insert(E->get().name + "()"); + option.insert_text += "()"; } + r_result.insert(option.display, option); } return; @@ -2069,7 +2126,7 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context } } -static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p_only_functions, Set<String> &r_result) { +static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result) { const GDScriptParser::BlockNode *block = p_context.block; @@ -2078,7 +2135,8 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p const GDScriptParser::FunctionNode *f = p_context.function; for (int i = 0; i < f->arguments.size(); i++) { - r_result.insert(f->arguments[i].operator String()); + ScriptCodeCompletionOption option(f->arguments[i].operator String(), ScriptCodeCompletionOption::KIND_PLAIN_TEXT); + r_result.insert(option.display, option); } } @@ -2103,11 +2161,13 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p for (int i = 0; i < GDScriptFunctions::FUNC_MAX; i++) { MethodInfo mi = GDScriptFunctions::get_info(GDScriptFunctions::Function(i)); + ScriptCodeCompletionOption option(String(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))), ScriptCodeCompletionOption::KIND_FUNCTION); if (mi.arguments.size() || (mi.flags & METHOD_FLAG_VARARG)) { - r_result.insert(String(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))) + "("); + option.insert_text += "("; } else { - r_result.insert(String(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))) + "()"); + option.insert_text += "()"; } + r_result.insert(option.display, option); } static const char *_type_names[Variant::VARIANT_MAX] = { @@ -2117,7 +2177,8 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p }; for (int i = 0; i < Variant::VARIANT_MAX; i++) { - r_result.insert(_type_names[i]); + ScriptCodeCompletionOption option(_type_names[i], ScriptCodeCompletionOption::KIND_CLASS); + r_result.insert(option.display, option); } static const char *_keywords[] = { @@ -2131,7 +2192,8 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p const char **kw = _keywords; while (*kw) { - r_result.insert(*kw); + ScriptCodeCompletionOption option(*kw, ScriptCodeCompletionOption::KIND_PLAIN_TEXT); + r_result.insert(option.display, option); kw++; } @@ -2145,7 +2207,8 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p } String path = ProjectSettings::get_singleton()->get(s); if (path.begins_with("*")) { - r_result.insert(s.get_slice("/", 1)); + ScriptCodeCompletionOption option(s.get_slice("/", 1), ScriptCodeCompletionOption::KIND_CONSTANT); + r_result.insert(option.display, option); } } @@ -2153,19 +2216,22 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p List<StringName> named_scripts; ScriptServer::get_global_class_list(&named_scripts); for (List<StringName>::Element *E = named_scripts.front(); E; E = E->next()) { - r_result.insert(E->get().operator String()); + ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_CLASS); + r_result.insert(option.display, option); } // Native classes for (const Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) { - r_result.insert(E->key().operator String()); + ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS); + r_result.insert(option.display, option); } } -static void _find_call_arguments(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, int p_argidx, bool p_static, Set<String> &r_result, String &r_arghint) { +static void _find_call_arguments(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, int p_argidx, bool p_static, Map<String, ScriptCodeCompletionOption> &r_result, String &r_arghint) { Variant base = p_base.value; GDScriptParser::DataType base_type = p_base.type; - bool _static = false; + + const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\""; while (base_type.has_type) { switch (base_type.kind) { @@ -2176,18 +2242,18 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con return; } } - if (!_static) { - for (int i = 0; i < base_type.class_type->functions.size(); i++) { - if (base_type.class_type->functions[i]->name == p_method) { - r_arghint = _make_arguments_hint(base_type.class_type->functions[i], p_argidx); - return; - } + for (int i = 0; i < base_type.class_type->functions.size(); i++) { + if (base_type.class_type->functions[i]->name == p_method) { + r_arghint = _make_arguments_hint(base_type.class_type->functions[i], p_argidx); + return; } } if ((p_method == "connect" || p_method == "emit_signal") && p_argidx == 0) { for (int i = 0; i < base_type.class_type->_signals.size(); i++) { - r_result.insert("\"" + base_type.class_type->_signals[i].name.operator String() + "\""); + ScriptCodeCompletionOption option(base_type.class_type->_signals[i].name.operator String(), ScriptCodeCompletionOption::KIND_SIGNAL); + option.insert_text = quote_style + option.display + quote_style; + r_result.insert(option.display, option); } } @@ -2200,7 +2266,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con List<MethodInfo> signals; gds->get_script_signal_list(&signals); for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { - r_result.insert("\"" + E->get().name + "\""); + ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_SIGNAL); + option.insert_text = quote_style + option.display + quote_style; + r_result.insert(option.display, option); } } Ref<GDScript> base_script = gds->get_base_script(); @@ -2238,7 +2306,8 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con List<String> options; obj->get_argument_options(p_method, p_argidx, &options); for (List<String>::Element *F = options.front(); F; F = F->next()) { - r_result.insert(F->get()); + ScriptCodeCompletionOption option(F->get(), ScriptCodeCompletionOption::KIND_FUNCTION); + r_result.insert(option.display, option); } } } @@ -2259,7 +2328,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con List<MethodInfo> signals; ClassDB::get_signal_list(class_name, &signals); for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { - r_result.insert("\"" + E->get().name + "\""); + ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_SIGNAL); + option.insert_text = quote_style + option.display + quote_style; + r_result.insert(option.display, option); } } @@ -2274,7 +2345,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con continue; } String name = s.get_slice("/", 1); - r_result.insert("\"/root/" + name + "\""); + ScriptCodeCompletionOption option("/root/" + name, ScriptCodeCompletionOption::KIND_NODE_PATH); + option.insert_text = quote_style + option.display + quote_style; + r_result.insert(option.display, option); } } @@ -2288,7 +2361,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con continue; } String name = s.get_slice("/", 1); - r_result.insert("\"" + name + "\""); + ScriptCodeCompletionOption option(name, ScriptCodeCompletionOption::KIND_CONSTANT); + option.insert_text = quote_style + option.display + quote_style; + r_result.insert(option.display, option); } } @@ -2321,7 +2396,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con } } -static void _find_call_arguments(GDScriptCompletionContext &p_context, const GDScriptParser::Node *p_node, int p_argidx, Set<String> &r_result, bool &r_forced, String &r_arghint) { +static void _find_call_arguments(GDScriptCompletionContext &p_context, const GDScriptParser::Node *p_node, int p_argidx, Map<String, ScriptCodeCompletionOption> &r_result, bool &r_forced, String &r_arghint) { + + const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\""; if (!p_node || p_node->type != GDScriptParser::Node::TYPE_OPERATOR) { return; @@ -2437,23 +2514,27 @@ static void _find_call_arguments(GDScriptCompletionContext &p_context, const GDS _find_call_arguments(p_context, ci, function, p_argidx, _static, r_result, r_arghint); if (function == "connect" && p_argidx == 2) { - Set<String> methods; + Map<String, ScriptCodeCompletionOption> methods; _find_identifiers_in_base(p_context, connect_base, true, methods); - for (Set<String>::Element *E = methods.front(); E; E = E->next()) { - r_result.insert("\"" + E->get().replace("(", "").replace(")", "") + "\""); + for (Map<String, ScriptCodeCompletionOption>::Element *E = methods.front(); E; E = E->next()) { + ScriptCodeCompletionOption &option = E->value(); + option.insert_text = quote_style + option.display + quote_style; + r_result.insert(option.display, option); } } r_forced = r_result.size() > 0; } -Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_forced, String &r_call_hint) { +Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint) { + + const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\""; GDScriptParser parser; - parser.parse(p_code, p_base_path, false, "", true); + parser.parse(p_code, p_path.get_base_dir(), false, p_path, true); r_forced = false; - Set<String> options; + Map<String, ScriptCodeCompletionOption> options; GDScriptCompletionContext context; context._class = parser.get_completion_class(); context.block = parser.get_completion_block(); @@ -2462,7 +2543,7 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base if (!context._class || context._class->owner == NULL) { context.base = p_owner; - context.base_path = p_base_path; + context.base_path = p_path.get_base_dir(); } bool is_function = false; @@ -2474,7 +2555,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base List<StringName> constants; Variant::get_constants_for_type(parser.get_completion_built_in_constant(), &constants); for (List<StringName>::Element *E = constants.front(); E; E = E->next()) { - options.insert(E->get().operator String()); + ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_CONSTANT); + options.insert(option.display, option); } } break; case GDScriptParser::COMPLETION_PARENT_FUNCTION: { @@ -2482,7 +2564,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base } break; case GDScriptParser::COMPLETION_FUNCTION: { is_function = true; - } // fallthrough + FALLTHROUGH; + } case GDScriptParser::COMPLETION_IDENTIFIER: { _find_identifiers(context, is_function, options); } break; @@ -2498,9 +2581,11 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base r_forced = true; String idopt = opt.unquote(); if (idopt.replace("/", "_").is_valid_identifier()) { - options.insert(idopt); + ScriptCodeCompletionOption option(idopt, ScriptCodeCompletionOption::KIND_NODE_PATH); + options.insert(option.display, option); } else { - options.insert(opt); + ScriptCodeCompletionOption option(opt, ScriptCodeCompletionOption::KIND_NODE_PATH); + options.insert(option.display, option); } } } @@ -2515,13 +2600,15 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base continue; } String name = s.get_slice("/", 1); - options.insert("\"/root/" + name + "\""); + ScriptCodeCompletionOption option(quote_style + "/root/" + name + quote_style, ScriptCodeCompletionOption::KIND_NODE_PATH); + options.insert(option.display, option); } } } break; case GDScriptParser::COMPLETION_METHOD: { is_function = true; - } // fallthrough + FALLTHROUGH; + } case GDScriptParser::COMPLETION_INDEX: { const GDScriptParser::Node *node = parser.get_completion_node(); if (node->type != GDScriptParser::Node::TYPE_OPERATOR) { @@ -2637,7 +2724,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base } method_hint += ":"; - options.insert(method_hint); + ScriptCodeCompletionOption option(method_hint, ScriptCodeCompletionOption::KIND_FUNCTION); + options.insert(option.display, option); } } break; case GDScriptParser::COMPLETION_YIELD: { @@ -2655,7 +2743,9 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base switch (base_type.kind) { case GDScriptParser::DataType::CLASS: { for (int i = 0; i < base_type.class_type->_signals.size(); i++) { - options.insert("\"" + base_type.class_type->_signals[i].name.operator String() + "\""); + ScriptCodeCompletionOption option(base_type.class_type->_signals[i].name.operator String(), ScriptCodeCompletionOption::KIND_SIGNAL); + option.insert_text = quote_style + option.display + quote_style; + options.insert(option.display, option); } base_type = base_type.class_type->base_type; } break; @@ -2666,7 +2756,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base List<MethodInfo> signals; scr->get_script_signal_list(&signals); for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { - options.insert("\"" + E->get().name + "\""); + ScriptCodeCompletionOption option(quote_style + E->get().name + quote_style, ScriptCodeCompletionOption::KIND_SIGNAL); + options.insert(option.display, option); } Ref<Script> base_script = scr->get_base_script(); if (base_script.is_valid()) { @@ -2693,7 +2784,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base List<MethodInfo> signals; ClassDB::get_signal_list(class_name, &signals); for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { - options.insert("\"" + E->get().name + "\""); + ScriptCodeCompletionOption option(quote_style + E->get().name + quote_style, ScriptCodeCompletionOption::KIND_SIGNAL); + options.insert(option.display, option); } } break; default: { @@ -2730,18 +2822,31 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base c.line = E->value().expression->line; if (_guess_expression_type(c, E->value().expression, constant)) { if (constant.type.has_type && constant.type.is_meta_type) { - options.insert(E->key().operator String()); + ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS); + options.insert(option.display, option); } } } for (int i = 0; i < clss->subclasses.size(); i++) { if (clss->subclasses[i]->name != StringName()) { - options.insert(clss->subclasses[i]->name.operator String()); + ScriptCodeCompletionOption option(clss->subclasses[i]->name.operator String(), ScriptCodeCompletionOption::KIND_CLASS); + options.insert(option.display, option); } } clss = clss->owner; for (int i = 0; i < Variant::VARIANT_MAX; i++) { - options.insert(Variant::get_type_name((Variant::Type)i)); + ScriptCodeCompletionOption option(Variant::get_type_name((Variant::Type)i), ScriptCodeCompletionOption::KIND_CLASS); + options.insert(option.display, option); + } + List<PropertyInfo> props; + ProjectSettings::get_singleton()->get_property_list(&props); + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + String s = E->get().name; + if (!s.begins_with("autoload/")) { + continue; + } + ScriptCodeCompletionOption option(s.get_slice("/", 1), ScriptCodeCompletionOption::KIND_CLASS); + options.insert(option.display, option); } } @@ -2755,18 +2860,21 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base if (Engine::get_singleton()->has_singleton(class_name)) { continue; } - options.insert(class_name); + ScriptCodeCompletionOption option(class_name, ScriptCodeCompletionOption::KIND_CLASS); + options.insert(option.display, option); } // Named scripts List<StringName> named_scripts; ScriptServer::get_global_class_list(&named_scripts); for (List<StringName>::Element *E = named_scripts.front(); E; E = E->next()) { - options.insert(E->get().operator String()); + ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_CLASS); + options.insert(option.display, option); } if (parser.get_completion_identifier_is_function()) { - options.insert("void"); + ScriptCodeCompletionOption option("void", ScriptCodeCompletionOption::KIND_PLAIN_TEXT); + options.insert(option.display, option); } r_forced = true; } break; @@ -2813,13 +2921,15 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base c2.line = E->value().expression->line; if (_guess_expression_type(c2, E->value().expression, constant)) { if (constant.type.has_type && constant.type.is_meta_type) { - options.insert(E->key().operator String()); + ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS); + options.insert(option.display, option); } } } for (int i = 0; i < base_type.class_type->subclasses.size(); i++) { if (base_type.class_type->subclasses[i]->name != StringName()) { - options.insert(base_type.class_type->subclasses[i]->name.operator String()); + ScriptCodeCompletionOption option(base_type.class_type->subclasses[i]->name.operator String(), ScriptCodeCompletionOption::KIND_CLASS); + options.insert(option.display, option); } } @@ -2837,7 +2947,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) { Ref<Script> const_scr = E->value(); if (const_scr.is_valid()) { - options.insert(E->key().operator String()); + ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS); + options.insert(option.display, option); } } Ref<Script> base_script = scr->get_base_script(); @@ -2859,7 +2970,7 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base } break; } - for (Set<String>::Element *E = options.front(); E; E = E->next()) { + for (Map<String, ScriptCodeCompletionOption>::Element *E = options.front(); E; E = E->next()) { r_options->push_back(E->get()); } @@ -2868,7 +2979,7 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base #else -Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_forced, String &r_call_hint) { +Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint) { return OK; } @@ -2879,7 +2990,7 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base String GDScriptLanguage::_get_indentation() const { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { - bool use_space_indentation = EDITOR_DEF("text_editor/indent/type", 0); + bool use_space_indentation = EDITOR_DEF("text_editor/indent/type", false); if (use_space_indentation) { int indent_size = EDITOR_DEF("text_editor/indent/size", 4); @@ -2997,8 +3108,8 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co } } } + base_type = base_type.class_type->base_type; } - base_type = base_type.class_type->base_type; } break; case GDScriptParser::DataType::SCRIPT: case GDScriptParser::DataType::GDSCRIPT: { @@ -3139,7 +3250,7 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co return ERR_CANT_RESOLVE; } -Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result) { +Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_path, Object *p_owner, LookupResult &r_result) { //before parsing, try the usual stuff if (ClassDB::class_exists(p_symbol)) { @@ -3181,7 +3292,7 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol } GDScriptParser parser; - parser.parse(p_code, p_base_path, false, "", true); + parser.parse(p_code, p_path.get_base_dir(), false, p_path, true); if (parser.get_completion_type() == GDScriptParser::COMPLETION_NONE) { return ERR_CANT_RESOLVE; @@ -3193,7 +3304,7 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol context.block = parser.get_completion_block(); context.line = parser.get_completion_line(); context.base = p_owner; - context.base_path = p_base_path; + context.base_path = p_path.get_base_dir(); if (context._class && context._class->extends_class.size() > 0) { bool success = false; @@ -3218,7 +3329,8 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol case GDScriptParser::COMPLETION_PARENT_FUNCTION: case GDScriptParser::COMPLETION_FUNCTION: { is_function = true; - } // fallthrough + FALLTHROUGH; + } case GDScriptParser::COMPLETION_IDENTIFIER: { if (!is_function) { @@ -3349,7 +3461,8 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol } break; case GDScriptParser::COMPLETION_METHOD: { is_function = true; - } // fallthrough + FALLTHROUGH; + } case GDScriptParser::COMPLETION_INDEX: { const GDScriptParser::Node *node = parser.get_completion_node(); if (node->type != GDScriptParser::Node::TYPE_OPERATOR) { @@ -3371,7 +3484,8 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol return OK; } } break; - default: {} + default: { + } } return ERR_CANT_RESOLVE; diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp index cff9ba55b8..0a01321851 100644 --- a/modules/gdscript/gdscript_function.cpp +++ b/modules/gdscript/gdscript_function.cpp @@ -86,8 +86,7 @@ Variant *GDScriptFunction::_get_variant(int p_address, GDScriptInstance *p_insta o = o->_owner; } - ERR_EXPLAIN("GDScriptCompiler bug..."); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "GDScriptCompiler bug."); } break; case ADDR_TYPE_LOCAL_CONSTANT: { #ifdef DEBUG_ENABLED @@ -128,40 +127,17 @@ Variant *GDScriptFunction::_get_variant(int p_address, GDScriptInstance *p_insta } break; } - ERR_EXPLAIN("Bad Code! (Addressing Mode)"); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Bad code! (unknown addressing mode)."); return NULL; } -String GDScriptFunction::_get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const { - - String err_text; - - if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { - int errorarg = p_err.argument; - err_text = "Invalid type in " + p_where + ". Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(p_err.expected) + "."; - } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { - err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; - } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { - err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; - } else if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) { - err_text = "Invalid call. Nonexistent " + p_where + "."; - } else if (p_err.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) { - err_text = "Attempt to call " + p_where + " on a null instance."; - } else { - err_text = "Bug, call error: #" + itos(p_err.error); - } - - return err_text; -} - #ifdef DEBUG_ENABLED -static String _get_var_type(const Variant *p_type) { +static String _get_var_type(const Variant *p_var) { String basestr; - if (p_type->get_type() == Variant::OBJECT) { - Object *bobj = *p_type; + if (p_var->get_type() == Variant::OBJECT) { + Object *bobj = *p_var; if (!bobj) { basestr = "null instance"; } else { @@ -176,12 +152,42 @@ static String _get_var_type(const Variant *p_type) { } } else { - basestr = Variant::get_type_name(p_type->get_type()); + basestr = Variant::get_type_name(p_var->get_type()); } return basestr; } -#endif +#endif // DEBUG_ENABLED + +String GDScriptFunction::_get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const { + + String err_text; + + if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { + int errorarg = p_err.argument; + // Handle the Object to Object case separately as we don't have further class details. +#ifdef DEBUG_ENABLED + if (p_err.expected == Variant::OBJECT && argptrs[errorarg]->get_type() == p_err.expected) { + err_text = "Invalid type in " + p_where + ". The Object-derived class of argument " + itos(errorarg + 1) + " (" + _get_var_type(argptrs[errorarg]) + ") is not a subclass of the expected argument class."; + } else +#endif // DEBUG_ENABLED + { + err_text = "Invalid type in " + p_where + ". Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(p_err.expected) + "."; + } + } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { + err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { + err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) { + err_text = "Invalid call. Nonexistent " + p_where + "."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) { + err_text = "Attempt to call " + p_where + " on a null instance."; + } else { + err_text = "Bug, call error: #" + itos(p_err.error); + } + + return err_text; +} #if defined(__GNUC__) #define OPCODES_TABLE \ @@ -391,8 +397,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a if (unlikely(m_cond)) { \ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. Breaking..:"); \ OPCODE_BREAK; \ - } else \ - _err_error_exists = false; \ + } \ } #define CHECK_SPACE(m_space) \ @@ -425,6 +430,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a profile.frame_call_count++; } bool exit_ok = false; + bool yielded = false; #endif #ifdef DEBUG_ENABLED @@ -1317,6 +1323,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a #ifdef DEBUG_ENABLED exit_ok = true; + yielded = true; #endif OPCODE_BREAK; } @@ -1411,7 +1418,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a if (!container->iter_init(*counter, valid)) { #ifdef DEBUG_ENABLED if (!valid) { - err_text = "Unable to iterate on object of type " + Variant::get_type_name(container->get_type()) + "'."; + err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "'."; OPCODE_BREAK; } #endif @@ -1424,7 +1431,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a *iterator = container->iter_get(*counter, valid); #ifdef DEBUG_ENABLED if (!valid) { - err_text = "Unable to obtain iterator object of type " + Variant::get_type_name(container->get_type()) + "'."; + err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "'."; OPCODE_BREAK; } #endif @@ -1444,7 +1451,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a if (!container->iter_next(*counter, valid)) { #ifdef DEBUG_ENABLED if (!valid) { - err_text = "Unable to iterate on object of type " + Variant::get_type_name(container->get_type()) + "' (type changed since first iteration?)."; + err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "' (type changed since first iteration?)."; OPCODE_BREAK; } #endif @@ -1457,7 +1464,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a *iterator = container->iter_get(*counter, valid); #ifdef DEBUG_ENABLED if (!valid) { - err_text = "Unable to obtain iterator object of type " + Variant::get_type_name(container->get_type()) + "' (but was obtained on first iteration?)."; + err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "' (but was obtained on first iteration?)."; OPCODE_BREAK; } #endif @@ -1467,20 +1474,25 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a DISPATCH_OPCODE; OPCODE(OPCODE_ASSERT) { - CHECK_SPACE(2); + CHECK_SPACE(3); #ifdef DEBUG_ENABLED GET_VARIANT_PTR(test, 1); + GET_VARIANT_PTR(message, 2); bool result = test->booleanize(); if (!result) { - - err_text = "Assertion failed."; + const String &message_str = *message; + if (message_str.empty()) { + err_text = "Assertion failed."; + } else { + err_text = "Assertion failed: " + message_str; + } OPCODE_BREAK; } #endif - ip += 2; + ip += 3; } DISPATCH_OPCODE; @@ -1548,14 +1560,14 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a //error // function, file, line, error, explanation String err_file; - if (p_instance) + if (p_instance && ObjectDB::instance_validate(p_instance->owner) && p_instance->script->is_valid() && p_instance->script->path != "") err_file = p_instance->script->path; else if (script) err_file = script->path; if (err_file == "") err_file = "<built-in>"; String err_func = name; - if (p_instance && p_instance->script->name != "") + if (p_instance && ObjectDB::instance_validate(p_instance->owner) && p_instance->script->is_valid() && p_instance->script->name != "") err_func = p_instance->script->name + "." + err_func; int err_line = line; if (err_text == "") { @@ -1583,15 +1595,24 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a GDScriptLanguage::get_singleton()->script_frame_time += time_taken - function_call_time; } - if (ScriptDebugger::get_singleton()) - GDScriptLanguage::get_singleton()->exit_function(); + // Check if this is the last time the function is resuming from yield + // Will be true if never yielded as well + // When it's the last resume it will postpone the exit from stack, + // so the debugger knows which function triggered the resume of the next function (if any) + if (!p_state || yielded) { + if (ScriptDebugger::get_singleton()) + GDScriptLanguage::get_singleton()->exit_function(); #endif - if (_stack_size) { - //free stack - for (int i = 0; i < _stack_size; i++) - stack[i].~Variant(); + if (_stack_size) { + //free stack + for (int i = 0; i < _stack_size; i++) + stack[i].~Variant(); + } + +#ifdef DEBUG_ENABLED } +#endif return retvalue; } @@ -1765,20 +1786,9 @@ GDScriptFunction::~GDScriptFunction() { Variant GDScriptFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { - if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { -#ifdef DEBUG_ENABLED - ERR_EXPLAIN("Resumed after yield, but class instance is gone"); - ERR_FAIL_V(Variant()); -#else - return Variant(); -#endif - } - Variant arg; r_error.error = Variant::CallError::CALL_OK; - ERR_FAIL_COND_V(!function, Variant()); - if (p_argcount == 0) { r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_error.argument = 1; @@ -1804,33 +1814,7 @@ Variant GDScriptFunctionState::_signal_callback(const Variant **p_args, int p_ar return Variant(); } - state.result = arg; - Variant ret = function->call(NULL, NULL, 0, r_error, &state); - - bool completed = true; - - // If the return value is a GDScriptFunctionState reference, - // then the function did yield again after resuming. - if (ret.is_ref()) { - GDScriptFunctionState *gdfs = Object::cast_to<GDScriptFunctionState>(ret); - if (gdfs && gdfs->function == function) { - completed = false; - gdfs->first_state = first_state.is_valid() ? first_state : Ref<GDScriptFunctionState>(this); - } - } - - function = NULL; //cleaned up; - state.result = Variant(); - - if (completed) { - if (first_state.is_valid()) { - first_state->emit_signal("completed", ret); - } else { - emit_signal("completed", ret); - } - } - - return ret; + return resume(arg); } bool GDScriptFunctionState::is_valid(bool p_extended_check) const { @@ -1852,8 +1836,7 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) { ERR_FAIL_COND_V(!function, Variant()); if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { #ifdef DEBUG_ENABLED - ERR_EXPLAIN("Resumed after yield, but class instance is gone"); - ERR_FAIL_V(Variant()); + ERR_FAIL_V_MSG(Variant(), "Resumed function '" + String(function->get_name()) + "()' after yield, but class instance is gone. At script: " + state.script->get_path() + ":" + itos(state.line)); #else return Variant(); #endif @@ -1884,6 +1867,17 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) { } else { emit_signal("completed", ret); } + +#ifdef DEBUG_ENABLED + if (ScriptDebugger::get_singleton()) + GDScriptLanguage::get_singleton()->exit_function(); + if (state.stack_size) { + //free stack + Variant *stack = (Variant *)state.stack.ptr(); + for (int i = 0; i < state.stack_size; i++) + stack[i].~Variant(); + } +#endif } return ret; diff --git a/modules/gdscript/gdscript_functions.cpp b/modules/gdscript/gdscript_functions.cpp index 46c9efd54f..9e05c7b574 100644 --- a/modules/gdscript/gdscript_functions.cpp +++ b/modules/gdscript/gdscript_functions.cpp @@ -58,6 +58,7 @@ const char *GDScriptFunctions::get_func_name(Function p_func) { "sqrt", "fmod", "fposmod", + "posmod", "floor", "ceil", "round", @@ -68,12 +69,18 @@ const char *GDScriptFunctions::get_func_name(Function p_func) { "exp", "is_nan", "is_inf", + "is_equal_approx", + "is_zero_approx", "ease", "decimals", + "step_decimals", "stepify", "lerp", + "lerp_angle", "inverse_lerp", "range_lerp", + "smoothstep", + "move_toward", "dectime", "randomize", "randi", @@ -99,6 +106,7 @@ const char *GDScriptFunctions::get_func_name(Function p_func) { "typeof", "type_exists", "char", + "ord", "str", "print", "printt", @@ -238,6 +246,12 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ VALIDATE_ARG_NUM(1); r_ret = Math::fposmod((double)*p_args[0], (double)*p_args[1]); } break; + case MATH_POSMOD: { + VALIDATE_ARG_COUNT(2); + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + r_ret = Math::posmod((int)*p_args[0], (int)*p_args[1]); + } break; case MATH_FLOOR: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); @@ -315,6 +329,17 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ VALIDATE_ARG_NUM(0); r_ret = Math::is_inf((double)*p_args[0]); } break; + case MATH_ISEQUALAPPROX: { + VALIDATE_ARG_COUNT(2); + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + r_ret = Math::is_equal_approx((real_t)*p_args[0], (real_t)*p_args[1]); + } break; + case MATH_ISZEROAPPROX: { + VALIDATE_ARG_COUNT(1); + VALIDATE_ARG_NUM(0); + r_ret = Math::is_zero_approx((real_t)*p_args[0]); + } break; case MATH_EASE: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); @@ -325,6 +350,12 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); r_ret = Math::step_decimals((double)*p_args[0]); + WARN_DEPRECATED_MSG("GDScript method 'decimals' is deprecated and has been renamed to 'step_decimals', please update your code accordingly."); + } break; + case MATH_STEP_DECIMALS: { + VALIDATE_ARG_COUNT(1); + VALIDATE_ARG_NUM(0); + r_ret = Math::step_decimals((double)*p_args[0]); } break; case MATH_STEPIFY: { VALIDATE_ARG_COUNT(2); @@ -353,6 +384,13 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ } break; } } break; + case MATH_LERP_ANGLE: { + VALIDATE_ARG_COUNT(3); + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + VALIDATE_ARG_NUM(2); + r_ret = Math::lerp_angle((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]); + } break; case MATH_INVERSE_LERP: { VALIDATE_ARG_COUNT(3); VALIDATE_ARG_NUM(0); @@ -369,6 +407,20 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ VALIDATE_ARG_NUM(4); r_ret = Math::range_lerp((double)*p_args[0], (double)*p_args[1], (double)*p_args[2], (double)*p_args[3], (double)*p_args[4]); } break; + case MATH_SMOOTHSTEP: { + VALIDATE_ARG_COUNT(3); + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + VALIDATE_ARG_NUM(2); + r_ret = Math::smoothstep((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]); + } break; + case MATH_MOVE_TOWARD: { + VALIDATE_ARG_COUNT(3); + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + VALIDATE_ARG_NUM(2); + r_ret = Math::move_toward((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]); + } break; case MATH_DECTIME: { VALIDATE_ARG_COUNT(3); VALIDATE_ARG_NUM(0); @@ -520,37 +572,32 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ } break; case OBJ_WEAKREF: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type() != Variant::OBJECT) { - + if (p_args[0]->get_type() == Variant::OBJECT) { + if (p_args[0]->is_ref()) { + Ref<WeakRef> wref = memnew(WeakRef); + REF r = *p_args[0]; + if (r.is_valid()) { + wref->set_ref(r); + } + r_ret = wref; + } else { + Ref<WeakRef> wref = memnew(WeakRef); + Object *obj = *p_args[0]; + if (obj) { + wref->set_obj(obj); + } + r_ret = wref; + } + } else if (p_args[0]->get_type() == Variant::NIL) { + Ref<WeakRef> wref = memnew(WeakRef); + r_ret = wref; + } else { r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; r_error.argument = 0; r_error.expected = Variant::OBJECT; r_ret = Variant(); return; } - - if (p_args[0]->is_ref()) { - - REF r = *p_args[0]; - if (!r.is_valid()) { - r_ret = Variant(); - return; - } - - Ref<WeakRef> wref = memnew(WeakRef); - wref->set_ref(r); - r_ret = wref; - } else { - Object *obj = *p_args[0]; - if (!obj) { - r_ret = Variant(); - return; - } - Ref<WeakRef> wref = memnew(WeakRef); - wref->set_obj(obj); - r_ret = wref; - } - } break; case FUNC_FUNCREF: { VALIDATE_ARG_COUNT(2); @@ -614,6 +661,33 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ CharType result[2] = { *p_args[0], 0 }; r_ret = String(result); } break; + case TEXT_ORD: { + + VALIDATE_ARG_COUNT(1); + + if (p_args[0]->get_type() != Variant::STRING) { + + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + r_ret = Variant(); + return; + } + + String str = p_args[0]->operator String(); + + if (str.length() != 1) { + + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + r_ret = RTR("Expected a string of length 1 (a character)."); + return; + } + + r_ret = str.get(0); + + } break; case TEXT_STR: { if (p_arg_count < 1) { r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; @@ -1052,27 +1126,13 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ Dictionary d; d["@subpath"] = cp; - d["@path"] = p->path; - - p = base.ptr(); - - while (p) { - - for (Set<StringName>::Element *E = p->members.front(); E; E = E->next()) { + d["@path"] = p->get_path(); - Variant value; - if (ins->get(E->get(), value)) { - - String k = E->get(); - if (!d.has(k)) { - d[k] = value; - } - } + for (Map<StringName, GDScript::MemberInfo>::Element *E = base->member_indices.front(); E; E = E->next()) { + if (!d.has(E->key())) { + d[E->key()] = ins->members[E->get().index]; } - - p = p->_base; } - r_ret = d; } } @@ -1200,6 +1260,7 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_ if (err != OK) { r_ret = Variant(); + ERR_PRINTS(vformat("Error parsing JSON at line %s: %s", errl, errs)); } } break; @@ -1419,6 +1480,7 @@ bool GDScriptFunctions::is_deterministic(Function p_func) { case MATH_SQRT: case MATH_FMOD: case MATH_FPOSMOD: + case MATH_POSMOD: case MATH_FLOOR: case MATH_CEIL: case MATH_ROUND: @@ -1431,10 +1493,13 @@ bool GDScriptFunctions::is_deterministic(Function p_func) { case MATH_ISINF: case MATH_EASE: case MATH_DECIMALS: + case MATH_STEP_DECIMALS: case MATH_STEPIFY: case MATH_LERP: case MATH_INVERSE_LERP: case MATH_RANGE_LERP: + case MATH_SMOOTHSTEP: + case MATH_MOVE_TOWARD: case MATH_DECTIME: case MATH_DEG2RAD: case MATH_RAD2DEG: @@ -1452,6 +1517,7 @@ bool GDScriptFunctions::is_deterministic(Function p_func) { case TYPE_OF: case TYPE_EXISTS: case TEXT_CHAR: + case TEXT_ORD: case TEXT_STR: case COLOR8: case LEN: @@ -1528,15 +1594,20 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { return mi; } break; case MATH_FMOD: { - MethodInfo mi("fmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + MethodInfo mi("fmod", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b")); mi.return_val.type = Variant::REAL; return mi; } break; case MATH_FPOSMOD: { - MethodInfo mi("fposmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + MethodInfo mi("fposmod", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b")); mi.return_val.type = Variant::REAL; return mi; } break; + case MATH_POSMOD: { + MethodInfo mi("posmod", PropertyInfo(Variant::INT, "a"), PropertyInfo(Variant::INT, "b")); + mi.return_val.type = Variant::INT; + return mi; + } break; case MATH_FLOOR: { MethodInfo mi("floor", PropertyInfo(Variant::REAL, "s")); mi.return_val.type = Variant::REAL; @@ -1563,7 +1634,7 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { return mi; } break; case MATH_POW: { - MethodInfo mi("pow", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + MethodInfo mi("pow", PropertyInfo(Variant::REAL, "base"), PropertyInfo(Variant::REAL, "exp")); mi.return_val.type = Variant::REAL; return mi; } break; @@ -1587,6 +1658,16 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { mi.return_val.type = Variant::BOOL; return mi; } break; + case MATH_ISEQUALAPPROX: { + MethodInfo mi("is_equal_approx", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b")); + mi.return_val.type = Variant::BOOL; + return mi; + } break; + case MATH_ISZEROAPPROX: { + MethodInfo mi("is_zero_approx", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::BOOL; + return mi; + } break; case MATH_EASE: { MethodInfo mi("ease", PropertyInfo(Variant::REAL, "s"), PropertyInfo(Variant::REAL, "curve")); mi.return_val.type = Variant::REAL; @@ -1594,7 +1675,12 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { } break; case MATH_DECIMALS: { MethodInfo mi("decimals", PropertyInfo(Variant::REAL, "step")); - mi.return_val.type = Variant::REAL; + mi.return_val.type = Variant::INT; + return mi; + } break; + case MATH_STEP_DECIMALS: { + MethodInfo mi("step_decimals", PropertyInfo(Variant::REAL, "step")); + mi.return_val.type = Variant::INT; return mi; } break; case MATH_STEPIFY: { @@ -1608,6 +1694,11 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; return mi; } break; + case MATH_LERP_ANGLE: { + MethodInfo mi("lerp_angle", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to"), PropertyInfo(Variant::REAL, "weight")); + mi.return_val.type = Variant::REAL; + return mi; + } break; case MATH_INVERSE_LERP: { MethodInfo mi("inverse_lerp", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to"), PropertyInfo(Variant::REAL, "weight")); mi.return_val.type = Variant::REAL; @@ -1618,6 +1709,16 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { mi.return_val.type = Variant::REAL; return mi; } break; + case MATH_SMOOTHSTEP: { + MethodInfo mi("smoothstep", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to"), PropertyInfo(Variant::REAL, "weight")); + mi.return_val.type = Variant::REAL; + return mi; + } break; + case MATH_MOVE_TOWARD: { + MethodInfo mi("move_toward", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to"), PropertyInfo(Variant::REAL, "delta")); + mi.return_val.type = Variant::REAL; + return mi; + } break; case MATH_DECTIME: { MethodInfo mi("dectime", PropertyInfo(Variant::REAL, "value"), PropertyInfo(Variant::REAL, "amount"), PropertyInfo(Variant::REAL, "step")); mi.return_val.type = Variant::REAL; @@ -1759,6 +1860,13 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) { return mi; } break; + case TEXT_ORD: { + + MethodInfo mi("ord", PropertyInfo(Variant::STRING, "char")); + mi.return_val.type = Variant::INT; + return mi; + + } break; case TEXT_STR: { MethodInfo mi("str"); diff --git a/modules/gdscript/gdscript_functions.h b/modules/gdscript/gdscript_functions.h index fcb8f32e54..9ea5dd46cf 100644 --- a/modules/gdscript/gdscript_functions.h +++ b/modules/gdscript/gdscript_functions.h @@ -49,6 +49,7 @@ public: MATH_SQRT, MATH_FMOD, MATH_FPOSMOD, + MATH_POSMOD, MATH_FLOOR, MATH_CEIL, MATH_ROUND, @@ -59,12 +60,18 @@ public: MATH_EXP, MATH_ISNAN, MATH_ISINF, + MATH_ISEQUALAPPROX, + MATH_ISZEROAPPROX, MATH_EASE, MATH_DECIMALS, + MATH_STEP_DECIMALS, MATH_STEPIFY, MATH_LERP, + MATH_LERP_ANGLE, MATH_INVERSE_LERP, MATH_RANGE_LERP, + MATH_SMOOTHSTEP, + MATH_MOVE_TOWARD, MATH_DECTIME, MATH_RANDOMIZE, MATH_RAND, @@ -90,6 +97,7 @@ public: TYPE_OF, TYPE_EXISTS, TEXT_CHAR, + TEXT_ORD, TEXT_STR, TEXT_PRINT, TEXT_PRINT_TABBED, diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index e75b8a14a3..ef1a282e51 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -89,8 +89,8 @@ bool GDScriptParser::_enter_indent_block(BlockNode *p_block) { if (tokenizer->get_token() != GDScriptTokenizer::TK_NEWLINE) { // be more python-like - int current = tab_level.back()->get(); - tab_level.push_back(current); + IndentLevel current_level = indent_level.back()->get(); + indent_level.push_back(current_level); return true; //_set_error("newline expected after ':'."); //return false; @@ -105,12 +105,19 @@ bool GDScriptParser::_enter_indent_block(BlockNode *p_block) { } else if (tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE) { int indent = tokenizer->get_token_line_indent(); - int current = tab_level.back()->get(); - if (indent <= current) { + int tabs = tokenizer->get_token_line_tab_indent(); + IndentLevel current_level = indent_level.back()->get(); + IndentLevel new_indent(indent, tabs); + if (new_indent.is_mixed(current_level)) { + _set_error("Mixed tabs and spaces in indentation."); return false; } - tab_level.push_back(indent); + if (indent <= current_level.indent) { + return false; + } + + indent_level.push_back(new_indent); tokenizer->advance(); return true; @@ -125,7 +132,7 @@ bool GDScriptParser::_enter_indent_block(BlockNode *p_block) { } } -bool GDScriptParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete) { +bool GDScriptParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete, bool p_parsing_constant) { if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); @@ -149,7 +156,7 @@ bool GDScriptParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bo return false; } - Node *arg = _parse_expression(p_parent, p_static); + Node *arg = _parse_expression(p_parent, p_static, false, p_parsing_constant); if (!arg) { return false; } @@ -252,6 +259,16 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s } } + // Check that the next token is not TK_CURSOR and if it is, the offset should be incremented. + int next_valid_offset = 1; + if (tokenizer->get_token(next_valid_offset) == GDScriptTokenizer::TK_CURSOR) { + next_valid_offset++; + // There is a chunk of the identifier that also needs to be ignored (not always there!) + if (tokenizer->get_token(next_valid_offset) == GDScriptTokenizer::TK_IDENTIFIER) { + next_valid_offset++; + } + } + if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) { //subexpression () tokenizer->advance(); @@ -282,7 +299,6 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_CURSOR: { - completion_cursor = StringName(); completion_type = COMPLETION_GET_NODE; completion_class = current_class; completion_function = current_function; @@ -464,7 +480,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s } if (!path.is_abs_path() && base_path != "") - path = base_path + "/" + path; + path = base_path.plus_file(path); path = path.replace("///", "//").simplify_path(); if (path == self_path) { @@ -505,7 +521,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s Ref<GDScript> gds = res; if (gds.is_valid() && !gds->is_valid()) { - _set_error("Could not fully preload the script, possible cyclic reference or compilation error. Use 'load()' instead if a cyclic reference is intended."); + _set_error("Couldn't fully preload the script, possible cyclic reference or compilation error. Use \"load()\" instead if a cyclic reference is intended."); return NULL; } @@ -519,7 +535,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_YIELD) { if (!current_function) { - _set_error("yield() can only be used inside function blocks."); + _set_error("\"yield()\" can only be used inside function blocks."); return NULL; } @@ -527,7 +543,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { - _set_error("Expected '(' after 'yield'"); + _set_error("Expected \"(\" after \"yield\"."); return NULL; } @@ -553,7 +569,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s yield->arguments.push_back(object); if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { - _set_error("Expected ',' after first argument of 'yield'"); + _set_error("Expected \",\" after the first argument of \"yield\"."); return NULL; } @@ -579,7 +595,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s yield->arguments.push_back(signal); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { - _set_error("Expected ')' after second argument of 'yield'"); + _set_error("Expected \")\" after the second argument of \"yield\"."); return NULL; } @@ -593,7 +609,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s } else if (tokenizer->get_token() == GDScriptTokenizer::TK_SELF) { if (p_static) { - _set_error("'self'' not allowed in static function or constant expression"); + _set_error("\"self\" isn't allowed in a static function or constant expression."); return NULL; } //constant defined by tokenizer @@ -614,7 +630,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s if (identifier == StringName()) { - _set_error("Built-in type constant or static function expected after '.'"); + _set_error("Built-in type constant or static function expected after \".\"."); return NULL; } if (!Variant::has_constant(bi_type, identifier)) { @@ -640,7 +656,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s id->name = identifier; op->arguments.push_back(id); - if (!_parse_arguments(op, op->arguments, p_static, true)) + if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant)) return NULL; expr = op; @@ -669,7 +685,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s expr = cn; } - } else if (tokenizer->get_token(1) == GDScriptTokenizer::TK_PARENTHESIS_OPEN && tokenizer->is_token_literal()) { + } else if (tokenizer->get_token(next_valid_offset) == GDScriptTokenizer::TK_PARENTHESIS_OPEN && tokenizer->is_token_literal()) { // We check with is_token_literal, as this allows us to use match/sync/etc. as a name //function or constructor @@ -732,7 +748,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s completion_node = op; } if (!replaced) { - if (!_parse_arguments(op, op->arguments, p_static, true)) + if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant)) return NULL; expr = op; } @@ -827,11 +843,12 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s } // Check parents for the constant - if (!bfn && cln->extends_file != StringName()) { - Ref<GDScript> parent = ResourceLoader::load(cln->extends_file); - if (parent.is_valid() && parent->is_valid()) { + if (!bfn) { + // Using current_class instead of cln here, since cln is const* + _determine_inheritance(current_class, false); + if (cln->base_type.has_type && cln->base_type.kind == DataType::GDSCRIPT && cln->base_type.script_type->is_valid()) { Map<StringName, Variant> parent_constants; - parent->get_constants(&parent_constants); + current_class->base_type.script_type->get_constants(&parent_constants); if (parent_constants.has(identifier)) { ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = parent_constants[identifier]; @@ -861,7 +878,6 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s case GDScriptTokenizer::TK_OP_ASSIGN_SUB: case GDScriptTokenizer::TK_OP_ASSIGN: { // Assignment is not really usage - current_function->arguments_usage.write[arg_idx] = current_function->arguments_usage[arg_idx] - 1; } break; default: { current_function->arguments_usage.write[arg_idx] = current_function->arguments_usage[arg_idx] + 1; @@ -888,7 +904,8 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s case GDScriptTokenizer::TK_OP_SUB: e.op = OperatorNode::OP_NEG; break; case GDScriptTokenizer::TK_OP_NOT: e.op = OperatorNode::OP_NOT; break; case GDScriptTokenizer::TK_OP_BIT_INVERT: e.op = OperatorNode::OP_BIT_INVERT; break; - default: {} + default: { + } } tokenizer->advance(); @@ -910,6 +927,10 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_IS && tokenizer->get_token(1) == GDScriptTokenizer::TK_BUILT_IN_TYPE) { // 'is' operator with built-in type + if (!expr) { + _set_error("Expected identifier before 'is' operator"); + return NULL; + } OperatorNode *op = alloc_node<OperatorNode>(); op->op = OperatorNode::OP_IS_BUILTIN; op->arguments.push_back(expr); @@ -1125,7 +1146,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s } } else { tokenizer->advance(); - if (!_parse_arguments(op, op->arguments, p_static)) { + if (!_parse_arguments(op, op->arguments, p_static, false, p_parsing_constant)) { return NULL; } } @@ -1148,10 +1169,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s return NULL; //nothing } - if (!expr) { - ERR_EXPLAIN("GDScriptParser bug, couldn't figure out what expression is..."); - ERR_FAIL_COND_V(!expr, NULL); - } + ERR_FAIL_COND_V_MSG(!expr, NULL, "GDScriptParser bug, couldn't figure out what expression is."); /******************/ /* Parse Indexing */ @@ -1177,22 +1195,14 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s tokenizer->advance(); IdentifierNode *id = alloc_node<IdentifierNode>(); - if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_FUNC) { - //small hack so built in funcs don't obfuscate methods - - id->name = GDScriptFunctions::get_func_name(tokenizer->get_token_built_in_func()); - tokenizer->advance(); - - } else { - StringName identifier; - if (_get_completable_identifier(COMPLETION_METHOD, identifier)) { - completion_node = op; - //indexing stuff - } - - id->name = identifier; + StringName identifier; + if (_get_completable_identifier(COMPLETION_METHOD, identifier)) { + completion_node = op; + //indexing stuff } + id->name = identifier; + op->arguments.push_back(expr); // call what op->arguments.push_back(id); // call func //get arguments @@ -1201,7 +1211,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s _make_completable_call(0); completion_node = op; } - if (!_parse_arguments(op, op->arguments, p_static, true)) + if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant)) return NULL; expr = op; @@ -1216,7 +1226,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s if (_get_completable_identifier(COMPLETION_INDEX, identifier)) { if (identifier == StringName()) { - identifier = "@temp"; //so it parses allright + identifier = "@temp"; //so it parses alright } completion_node = op; @@ -1408,9 +1418,6 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s unary = true; break; case OperatorNode::OP_NEG: - priority = 1; - unary = true; - break; case OperatorNode::OP_POS: priority = 1; unary = true; @@ -1493,7 +1500,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s if (next_op == -1) { _set_error("Yet another parser bug...."); - ERR_FAIL_COND_V(next_op == -1, NULL); + ERR_FAIL_V(NULL); } // OK! create operator.. @@ -1786,8 +1793,6 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to cn->value = v; cn->datatype = _type_from_variant(v); return cn; - - } else if (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && last_not_constant == 0) { } return op; //don't reduce yet @@ -1875,7 +1880,9 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to } } break; - default: { break; } + default: { + break; + } } //now se if all are constants if (!all_constants) @@ -1988,10 +1995,11 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to return op->arguments[2]; } } break; - default: { ERR_FAIL_V(op); } + default: { + ERR_FAIL_V(op); + } } - ERR_FAIL_V(op); } break; default: { return p_node; @@ -2224,10 +2232,12 @@ GDScriptParser::PatternNode *GDScriptParser::_parse_pattern(bool p_static) { } void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode *> &p_branches, bool p_static) { - int indent_level = tab_level.back()->get(); + IndentLevel current_level = indent_level.back()->get(); p_block->has_return = true; + bool catch_all_appeared = false; + while (true) { while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE && _parse_newline()) @@ -2237,13 +2247,11 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran if (error_set) return; - if (indent_level > tab_level.back()->get()) { - return; // go back a level + if (current_level.indent > indent_level.back()->get().indent) { + break; // go back a level } - if (pending_newline != -1) { - pending_newline = -1; - } + pending_newline = -1; PatternBranchNode *branch = alloc_node<PatternBranchNode>(); branch->body = alloc_node<BlockNode>(); @@ -2253,12 +2261,20 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran branch->patterns.push_back(_parse_pattern(p_static)); if (!branch->patterns[0]) { - return; + break; } bool has_binding = branch->patterns[0]->pt_type == PatternNode::PT_BIND; bool catch_all = has_binding || branch->patterns[0]->pt_type == PatternNode::PT_WILDCARD; +#ifdef DEBUG_ENABLED + // Branches after a wildcard or binding are unreachable + if (catch_all_appeared && !current_function->has_unreachable_code) { + _add_warning(GDScriptWarning::UNREACHABLE_CODE, -1, current_function->name.operator String()); + current_function->has_unreachable_code = true; + } +#endif + while (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); branch->patterns.push_back(_parse_pattern(p_static)); @@ -2276,6 +2292,8 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran catch_all = catch_all || pt == PatternNode::PT_WILDCARD; } + catch_all_appeared = catch_all_appeared || catch_all; + if (!_enter_indent_block()) { _set_error("Expected block in pattern branch"); return; @@ -2291,6 +2309,11 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran p_branches.push_back(branch); } + + // Even if all branches return, there is possibility of default fallthrough + if (!catch_all_appeared) { + p_block->has_return = false; + } } void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings) { @@ -2310,7 +2333,7 @@ void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_m // static type check if possible if (pattern_type.has_type && to_match_type.has_type) { if (!_is_type_compatible(to_match_type, pattern_type) && !_is_type_compatible(pattern_type, to_match_type)) { - _set_error("Pattern type (" + pattern_type.to_string() + ") is not compatible with the type of the value to match (" + to_match_type.to_string() + ").", + _set_error("The pattern type (" + pattern_type.to_string() + ") isn't compatible with the type of the value to match (" + to_match_type.to_string() + ").", p_pattern->line); return; } @@ -2679,7 +2702,7 @@ void GDScriptParser::_transform_match_statment(MatchNode *p_match_statement) { void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { - int indent_level = tab_level.back()->get(); + IndentLevel current_level = indent_level.back()->get(); #ifdef DEBUG_ENABLED @@ -2692,9 +2715,13 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { bool is_first_line = true; while (true) { - if (!is_first_line && tab_level.back()->prev() && tab_level.back()->prev()->get() == indent_level) { + if (!is_first_line && indent_level.back()->prev() && indent_level.back()->prev()->get().indent == current_level.indent) { + if (indent_level.back()->prev()->get().is_mixed(current_level)) { + _set_error("Mixed tabs and spaces in indentation."); + return; + } // pythonic single-line expression, don't parse future lines - tab_level.pop_back(); + indent_level.pop_back(); p_block->end_line = tokenizer->get_token_line(); return; } @@ -2704,7 +2731,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { if (error_set) return; - if (indent_level > tab_level.back()->get()) { + if (current_level.indent > indent_level.back()->get().indent) { p_block->end_line = tokenizer->get_token_line(); return; //go back a level } @@ -2762,24 +2789,24 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { case GDScriptTokenizer::TK_CF_PASS: { if (tokenizer->get_token(1) != GDScriptTokenizer::TK_SEMICOLON && tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE && tokenizer->get_token(1) != GDScriptTokenizer::TK_EOF) { - _set_error("Expected ';' or <NewLine>."); + _set_error("Expected \";\" or a line break."); return; } _mark_line_as_safe(tokenizer->get_token_line()); tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON) { - // Ignore semicolon after 'pass' + // Ignore semicolon after 'pass'. tokenizer->advance(); } } break; case GDScriptTokenizer::TK_PR_VAR: { - //variale declaration and (eventual) initialization + // Variable declaration and (eventual) initialization. tokenizer->advance(); int var_line = tokenizer->get_token_line(); if (!tokenizer->is_token_literal(0, true)) { - _set_error("Expected identifier for local variable name."); + _set_error("Expected an identifier for the local variable name."); return; } StringName n = tokenizer->get_token_literal(); @@ -2787,7 +2814,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { if (current_function) { for (int i = 0; i < current_function->arguments.size(); i++) { if (n == current_function->arguments[i]) { - _set_error("Variable '" + String(n) + "' already defined in the scope (at line: " + itos(current_function->line) + ")."); + _set_error("Variable \"" + String(n) + "\" already defined in the scope (at line " + itos(current_function->line) + ")."); return; } } @@ -2795,7 +2822,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { BlockNode *check_block = p_block; while (check_block) { if (check_block->variables.has(n)) { - _set_error("Variable '" + String(n) + "' already defined in the scope (at line: " + itos(check_block->variables[n]->line) + ")."); + _set_error("Variable \"" + String(n) + "\" already defined in the scope (at line " + itos(check_block->variables[n]->line) + ")."); return; } check_block = check_block->parent_block; @@ -2817,7 +2844,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { #endif tokenizer->advance(); } else if (!_parse_type(lv->datatype)) { - _set_error("Expected type for variable."); + _set_error("Expected a type for the variable."); return; } } @@ -2837,15 +2864,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { assigned = subexpr; } else { - ConstantNode *c = alloc_node<ConstantNode>(); - if (lv->datatype.has_type && lv->datatype.kind == DataType::BUILTIN) { - Variant::CallError err; - c->value = Variant::construct(lv->datatype.builtin_type, NULL, 0, err); - } else { - c->value = Variant(); - } - c->line = var_line; - assigned = c; + assigned = _get_default_value_for_type(lv->datatype, var_line); } lv->assign = assigned; //must be added later, to avoid self-referencing. @@ -2865,10 +2884,8 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { lv->assign_op = op; lv->assign = assigned; - lv->assign_op = op; - if (!_end_statement()) { - _set_error("Expected end of statement (var)"); + _set_error("Expected end of statement (\"var\")."); return; } @@ -2897,7 +2914,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { p_block->sub_blocks.push_back(cf_if->body); if (!_enter_indent_block(cf_if->body)) { - _set_error("Expected indented block after 'if'"); + _set_error("Expected an indented block after \"if\"."); p_block->end_line = tokenizer->get_token_line(); return; } @@ -2918,16 +2935,16 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE && _parse_newline()) ; - if (tab_level.back()->get() < indent_level) { //not at current indent level + if (indent_level.back()->get().indent < current_level.indent) { //not at current indent level p_block->end_line = tokenizer->get_token_line(); return; } if (tokenizer->get_token() == GDScriptTokenizer::TK_CF_ELIF) { - if (tab_level.back()->get() > indent_level) { + if (indent_level.back()->get().indent > current_level.indent) { - _set_error("Invalid indent"); + _set_error("Invalid indentation."); return; } @@ -2958,7 +2975,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { p_block->sub_blocks.push_back(cf_if->body); if (!_enter_indent_block(cf_if->body)) { - _set_error("Expected indented block after 'elif'"); + _set_error("Expected an indented block after \"elif\"."); p_block->end_line = tokenizer->get_token_line(); return; } @@ -2973,8 +2990,8 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CF_ELSE) { - if (tab_level.back()->get() > indent_level) { - _set_error("Invalid indent"); + if (indent_level.back()->get().indent > current_level.indent) { + _set_error("Invalid indentation."); return; } @@ -2984,7 +3001,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { p_block->sub_blocks.push_back(cf_if->body_else); if (!_enter_indent_block(cf_if->body_else)) { - _set_error("Expected indented block after 'else'"); + _set_error("Expected an indented block after \"else\"."); p_block->end_line = tokenizer->get_token_line(); return; } @@ -3029,7 +3046,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { p_block->sub_blocks.push_back(cf_while->body); if (!_enter_indent_block(cf_while->body)) { - _set_error("Expected indented block after 'while'"); + _set_error("Expected an indented block after \"while\"."); p_block->end_line = tokenizer->get_token_line(); return; } @@ -3048,7 +3065,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { if (!tokenizer->is_token_literal(0, true)) { - _set_error("identifier expected after 'for'"); + _set_error("Identifier expected after \"for\"."); } IdentifierNode *id = alloc_node<IdentifierNode>(); @@ -3057,7 +3074,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_OP_IN) { - _set_error("'in' expected after identifier"); + _set_error("\"in\" expected after identifier."); return; } @@ -3147,7 +3164,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { p_block->sub_blocks.push_back(cf_for->body); if (!_enter_indent_block(cf_for->body)) { - _set_error("Expected indented block after 'for'"); + _set_error("Expected indented block after \"for\"."); p_block->end_line = tokenizer->get_token_line(); return; } @@ -3174,23 +3191,25 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { } break; case GDScriptTokenizer::TK_CF_CONTINUE: { + _mark_line_as_safe(tokenizer->get_token_line()); tokenizer->advance(); ControlFlowNode *cf_continue = alloc_node<ControlFlowNode>(); cf_continue->cf_type = ControlFlowNode::CF_CONTINUE; p_block->statements.push_back(cf_continue); if (!_end_statement()) { - _set_error("Expected end of statement (continue)"); + _set_error("Expected end of statement (\"continue\")."); return; } } break; case GDScriptTokenizer::TK_CF_BREAK: { + _mark_line_as_safe(tokenizer->get_token_line()); tokenizer->advance(); ControlFlowNode *cf_break = alloc_node<ControlFlowNode>(); cf_break->cf_type = ControlFlowNode::CF_BREAK; p_block->statements.push_back(cf_break); if (!_end_statement()) { - _set_error("Expected end of statement (break)"); + _set_error("Expected end of statement (\"break\")."); return; } } break; @@ -3244,7 +3263,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { match_node->val_to_match = val_to_match; if (!_enter_indent_block()) { - _set_error("Expected indented pattern matching block after 'match'"); + _set_error("Expected indented pattern matching block after \"match\"."); return; } @@ -3271,19 +3290,40 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { case GDScriptTokenizer::TK_PR_ASSERT: { tokenizer->advance(); - Node *condition = _parse_and_reduce_expression(p_block, p_static); - if (!condition) { - if (_recover_from_completion()) { - break; - } + + if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { + _set_error("Expected '(' after assert"); + return; + } + + tokenizer->advance(); + + Vector<Node *> args; + const bool result = _parse_arguments(p_block, args, p_static); + if (!result) { + return; + } + + if (args.empty() || args.size() > 2) { + _set_error("Wrong number of arguments, expected 1 or 2"); return; } + AssertNode *an = alloc_node<AssertNode>(); - an->condition = condition; + an->condition = _reduce_expression(args[0], p_static); + + if (args.size() == 2) { + an->message = _reduce_expression(args[1], p_static); + } else { + ConstantNode *message_node = alloc_node<ConstantNode>(); + message_node->value = String(); + an->message = message_node; + } + p_block->statements.push_back(an); if (!_end_statement()) { - _set_error("Expected end of statement after assert."); + _set_error("Expected end of statement after \"assert\"."); return; } } break; @@ -3294,7 +3334,7 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { p_block->statements.push_back(bn); if (!_end_statement()) { - _set_error("Expected end of statement after breakpoint."); + _set_error("Expected end of statement after \"breakpoint\"."); return; } } break; @@ -3309,7 +3349,12 @@ void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) { } p_block->statements.push_back(expression); if (!_end_statement()) { - _set_error("Expected end of statement after expression."); + // Attempt to guess a better error message if the user "retypes" a variable + if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON && tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) { + _set_error("Unexpected ':=', use '=' instead. Expected end of statement after expression."); + } else { + _set_error(String() + "Expected end of statement after expression, got " + tokenizer->get_token_name(tokenizer->get_token()) + " instead"); + } return; } @@ -3322,32 +3367,45 @@ bool GDScriptParser::_parse_newline() { if (tokenizer->get_token(1) != GDScriptTokenizer::TK_EOF && tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE) { + IndentLevel current_level = indent_level.back()->get(); int indent = tokenizer->get_token_line_indent(); - int current_indent = tab_level.back()->get(); + int tabs = tokenizer->get_token_line_tab_indent(); + IndentLevel new_level(indent, tabs); + + if (new_level.is_mixed(current_level)) { + _set_error("Mixed tabs and spaces in indentation."); + return false; + } - if (indent > current_indent) { - _set_error("Unexpected indent."); + if (indent > current_level.indent) { + _set_error("Unexpected indentation."); return false; } - if (indent < current_indent) { + if (indent < current_level.indent) { - while (indent < current_indent) { + while (indent < current_level.indent) { //exit block - if (tab_level.size() == 1) { - _set_error("Invalid indent. BUG?"); + if (indent_level.size() == 1) { + _set_error("Invalid indentation. Bug?"); return false; } - tab_level.pop_back(); + indent_level.pop_back(); - if (tab_level.back()->get() < indent) { + if (indent_level.back()->get().indent < indent) { _set_error("Unindent does not match any outer indentation level."); return false; } - current_indent = tab_level.back()->get(); + + if (indent_level.back()->get().is_mixed(current_level)) { + _set_error("Mixed tabs and spaces in indentation."); + return false; + } + + current_level = indent_level.back()->get(); } tokenizer->advance(); @@ -3363,13 +3421,13 @@ void GDScriptParser::_parse_extends(ClassNode *p_class) { if (p_class->extends_used) { - _set_error("'extends' already used for this class."); + _set_error("\"extends\" can only be present once per script."); return; } if (!p_class->constant_expressions.empty() || !p_class->subclasses.empty() || !p_class->functions.empty() || !p_class->variables.empty()) { - _set_error("'extends' must be used before anything else."); + _set_error("\"extends\" must be used before anything else."); return; } @@ -3389,7 +3447,7 @@ void GDScriptParser::_parse_extends(ClassNode *p_class) { Variant constant = tokenizer->get_token_constant(); if (constant.get_type() != Variant::STRING) { - _set_error("'extends' constant must be a string."); + _set_error("\"extends\" constant must be a string."); return; } @@ -3424,7 +3482,7 @@ void GDScriptParser::_parse_extends(ClassNode *p_class) { default: { - _set_error("Invalid 'extends' syntax, expected string constant (path) and/or identifier (parent class)."); + _set_error("Invalid \"extends\" syntax, expected string constant (path) and/or identifier (parent class)."); return; } } @@ -3445,7 +3503,7 @@ void GDScriptParser::_parse_extends(ClassNode *p_class) { void GDScriptParser::_parse_class(ClassNode *p_class) { - int indent_level = tab_level.back()->get(); + IndentLevel current_level = indent_level.back()->get(); while (true) { @@ -3453,7 +3511,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (error_set) return; - if (indent_level > tab_level.back()->get()) { + if (current_level.indent > indent_level.back()->get().indent) { p_class->end_line = tokenizer->get_token_line(); return; //go back a level } @@ -3484,32 +3542,52 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (error_set) return; if (!_end_statement()) { - _set_error("Expected end of statement after extends"); + _set_error("Expected end of statement after \"extends\"."); return; } } break; case GDScriptTokenizer::TK_PR_CLASS_NAME: { + _mark_line_as_safe(tokenizer->get_token_line()); if (p_class->owner) { - _set_error("'class_name' is only valid for the main class namespace."); + _set_error("\"class_name\" is only valid for the main class namespace."); + return; + } + if (self_path.begins_with("res://") && self_path.find("::") != -1) { + _set_error("\"class_name\" isn't allowed in built-in scripts."); return; } if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) { - _set_error("'class_name' syntax: 'class_name <UniqueName>'"); + _set_error("\"class_name\" syntax: \"class_name <UniqueName>\""); + return; + } + if (p_class->classname_used) { + _set_error("\"class_name\" can only be present once per script."); return; } + p_class->classname_used = true; + p_class->name = tokenizer->get_token_identifier(1); if (self_path != String() && ScriptServer::is_global_class(p_class->name) && ScriptServer::get_global_class_path(p_class->name) != self_path) { - _set_error("Unique global class '" + p_class->name + "' already exists at path: " + ScriptServer::get_global_class_path(p_class->name)); + _set_error("Unique global class \"" + p_class->name + "\" already exists at path: " + ScriptServer::get_global_class_path(p_class->name)); return; } if (ClassDB::class_exists(p_class->name)) { - _set_error("Class '" + p_class->name + "' shadows a native class."); + _set_error("The class \"" + p_class->name + "\" shadows a native class."); + return; + } + + if (p_class->classname_used && ProjectSettings::get_singleton()->has_setting("autoload/" + p_class->name)) { + const String autoload_path = ProjectSettings::get_singleton()->get_setting("autoload/" + p_class->name); + if (autoload_path.begins_with("*")) { + // It's a singleton, and not just a regular AutoLoad script. + _set_error("The class \"" + p_class->name + "\" conflicts with the AutoLoad singleton of the same name, and is therefore redundant. Remove the class_name declaration to fix this error."); + } return; } @@ -3536,12 +3614,12 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); } else { - _set_error("Optional parameter after 'class_name' must be a string constant file path to an icon."); + _set_error("The optional parameter after \"class_name\" must be a string constant file path to an icon."); return; } } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT) { - _set_error("Class icon must be separated by a comma."); + _set_error("The class icon must be separated by a comma."); return; } @@ -3550,7 +3628,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (p_class->tool) { - _set_error("tool used more than once"); + _set_error("The \"tool\" keyword can only be present once per script."); return; } @@ -3565,7 +3643,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) { - _set_error("'class' syntax: 'class <Name>:' or 'class <Name> extends <BaseClass>:'"); + _set_error("\"class\" syntax: \"class <Name>:\" or \"class <Name> extends <BaseClass>:\""); return; } name = tokenizer->get_token_identifier(1); @@ -3573,23 +3651,23 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { // Check if name is shadowing something else if (ClassDB::class_exists(name) || ClassDB::class_exists("_" + name.operator String())) { - _set_error("Class '" + String(name) + "' shadows a native class."); + _set_error("The class \"" + String(name) + "\" shadows a native class."); return; } if (ScriptServer::is_global_class(name)) { - _set_error("Can't override name of unique global class '" + name + "' already exists at path: " + ScriptServer::get_global_class_path(p_class->name)); + _set_error("Can't override name of the unique global class \"" + name + "\". It already exists at: " + ScriptServer::get_global_class_path(p_class->name)); return; } ClassNode *outer_class = p_class; while (outer_class) { for (int i = 0; i < outer_class->subclasses.size(); i++) { if (outer_class->subclasses[i]->name == name) { - _set_error("Another class named '" + String(name) + "' already exists in this scope (at line " + itos(outer_class->subclasses[i]->line) + ")."); + _set_error("Another class named \"" + String(name) + "\" already exists in this scope (at line " + itos(outer_class->subclasses[i]->line) + ")."); return; } } if (outer_class->constant_expressions.has(name)) { - _set_error("A constant named '" + String(name) + "' already exists in the outer class scope (at line" + itos(outer_class->constant_expressions[name].expression->line) + ")."); + _set_error("A constant named \"" + String(name) + "\" already exists in the outer class scope (at line" + itos(outer_class->constant_expressions[name].expression->line) + ")."); return; } @@ -3633,7 +3711,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { - _set_error("Expected 'func'."); + _set_error("Expected \"func\"."); return; } @@ -3657,18 +3735,18 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (name == StringName()) { - _set_error("Expected identifier after 'func' (syntax: 'func <identifier>([arguments]):' )."); + _set_error("Expected an identifier after \"func\" (syntax: \"func <identifier>([arguments]):\")."); return; } for (int i = 0; i < p_class->functions.size(); i++) { if (p_class->functions[i]->name == name) { - _set_error("Function '" + String(name) + "' already exists in this class (at line: " + itos(p_class->functions[i]->line) + ")."); + _set_error("The function \"" + String(name) + "\" already exists in this class (at line " + itos(p_class->functions[i]->line) + ")."); } } for (int i = 0; i < p_class->static_functions.size(); i++) { if (p_class->static_functions[i]->name == name) { - _set_error("Function '" + String(name) + "' already exists in this class (at line: " + itos(p_class->static_functions[i]->line) + ")."); + _set_error("The function \"" + String(name) + "\" already exists in this class (at line " + itos(p_class->static_functions[i]->line) + ")."); } } @@ -3681,11 +3759,16 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { _add_warning(GDScriptWarning::FUNCTION_CONFLICTS_VARIABLE, -1, name); } } + for (int i = 0; i < p_class->subclasses.size(); i++) { + if (p_class->subclasses[i]->name == name) { + _add_warning(GDScriptWarning::FUNCTION_CONFLICTS_CONSTANT, -1, name); + } + } #endif // DEBUG_ENABLED if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { - _set_error("Expected '(' after identifier (syntax: 'func <identifier>([arguments]):' )."); + _set_error("Expected \"(\" after the identifier (syntax: \"func <identifier>([arguments]):\" )."); return; } @@ -3717,7 +3800,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (!tokenizer->is_token_literal(0, true)) { - _set_error("Expected identifier for argument."); + _set_error("Expected an identifier for an argument."); return; } @@ -3735,7 +3818,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { argtype.infer_type = true; tokenizer->advance(); } else if (!_parse_type(argtype)) { - _set_error("Expected type for argument."); + _set_error("Expected a type for an argument."); return; } } @@ -3784,7 +3867,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { continue; } else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { - _set_error("Expected ',' or ')'."); + _set_error("Expected \",\" or \")\"."); return; } @@ -3813,7 +3896,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (name == "_init") { if (_static) { - _set_error("Constructor cannot be static."); + _set_error("The constructor cannot be static."); return; } @@ -3830,7 +3913,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) { - _set_error("expected '(' for parent constructor arguments."); + _set_error("Expected \"(\" for parent constructor arguments."); return; } tokenizer->advance(); @@ -3850,7 +3933,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { continue; } else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { - _set_error("Expected ',' or ')'."); + _set_error("Expected \",\" or \")\"."); return; } @@ -3875,7 +3958,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() == GDScriptTokenizer::TK_FORWARD_ARROW) { if (!_parse_type(return_type, true)) { - _set_error("Expected return type for function."); + _set_error("Expected a return type for the function."); return; } } @@ -3905,7 +3988,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (!tokenizer->is_token_literal()) { - _set_error("Expected identifier after 'signal'."); + _set_error("Expected an identifier after \"signal\"."); return; } @@ -3929,7 +4012,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } if (!tokenizer->is_token_literal(0, true)) { - _set_error("Expected identifier in signal argument."); + _set_error("Expected an identifier in a \"signal\" argument."); return; } @@ -3943,7 +4026,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); } else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { - _set_error("Expected ',' or ')' after signal parameter identifier."); + _set_error("Expected \",\" or \")\" after a \"signal\" parameter identifier."); return; } } @@ -3952,7 +4035,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { p_class->_signals.push_back(sig); if (!_end_statement()) { - _set_error("Expected end of statement (signal)"); + _set_error("Expected end of statement (\"signal\")."); return; } } break; @@ -4007,12 +4090,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { - ERR_EXPLAIN("Exporting bit flags hint requires string constants."); - WARN_DEPRECATED + WARN_DEPRECATED_MSG("Exporting bit flags hint requires string constants."); break; } if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { - _set_error("Expected ',' in bit flags hint."); + _set_error("Expected \",\" in the bit flags hint."); return; } @@ -4024,7 +4106,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { current_export = PropertyInfo(); - _set_error("Expected a string constant in named bit flags hint."); + _set_error("Expected a string constant in the named bit flags hint."); return; } @@ -4042,7 +4124,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); - _set_error("Expected ')' or ',' in named bit flags hint."); + _set_error("Expected \")\" or \",\" in the named bit flags hint."); return; } tokenizer->advance(); @@ -4051,6 +4133,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 the 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 the 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 the 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 the 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; @@ -4060,7 +4186,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { current_export = PropertyInfo(); - _set_error("Expected a string constant in enumeration hint."); + _set_error("Expected a string constant in the enumeration hint."); return; } @@ -4078,7 +4204,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); - _set_error("Expected ')' or ',' in enumeration hint."); + _set_error("Expected \")\" or \",\" in the enumeration hint."); return; } @@ -4096,7 +4222,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { current_export.hint = PROPERTY_HINT_EXP_EASING; tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { - _set_error("Expected ')' in hint."); + _set_error("Expected \")\" in the hint."); return; } break; @@ -4111,7 +4237,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) break; else if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { - _set_error("Expected ')' or ',' in exponential range hint."); + _set_error("Expected \")\" or \",\" in the exponential range hint."); return; } tokenizer->advance(); @@ -4127,7 +4253,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { current_export = PropertyInfo(); - _set_error("Expected a range in numeric hint."); + _set_error("Expected a range in the numeric hint."); return; } @@ -4142,7 +4268,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); - _set_error("Expected ',' or ')' in numeric range hint."); + _set_error("Expected \",\" or \")\" in the numeric range hint."); return; } @@ -4157,7 +4283,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { current_export = PropertyInfo(); - _set_error("Expected a number as upper bound in numeric range hint."); + _set_error("Expected a number as upper bound in the numeric range hint."); return; } @@ -4170,7 +4296,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); - _set_error("Expected ',' or ')' in numeric range hint."); + _set_error("Expected \",\" or \")\" in the numeric range hint."); return; } @@ -4184,7 +4310,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { current_export = PropertyInfo(); - _set_error("Expected a number as step in numeric range hint."); + _set_error("Expected a number as step in the numeric range hint."); return; } @@ -4203,7 +4329,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { current_export = PropertyInfo(); - _set_error("Expected a string constant in enumeration hint."); + _set_error("Expected a string constant in the enumeration hint."); return; } @@ -4220,7 +4346,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { current_export = PropertyInfo(); - _set_error("Expected ')' or ',' in enumeration hint."); + _set_error("Expected \")\" or \",\" in the enumeration hint."); return; } tokenizer->advance(); @@ -4240,7 +4366,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier() == "GLOBAL")) { - _set_error("Expected 'GLOBAL' after comma in directory hint."); + _set_error("Expected \"GLOBAL\" after comma in the directory hint."); return; } if (!p_class->tool) { @@ -4251,11 +4377,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { - _set_error("Expected ')' in hint."); + _set_error("Expected \")\" in the hint."); return; } } else { - _set_error("Expected ')' or ',' in hint."); + _set_error("Expected \")\" or \",\" in the hint."); return; } break; @@ -4284,7 +4410,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) tokenizer->advance(); else { - _set_error("Expected ')' or ',' in hint."); + _set_error("Expected \")\" or \",\" in the hint."); return; } } @@ -4292,9 +4418,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { if (current_export.hint == PROPERTY_HINT_GLOBAL_FILE) - _set_error("Expected string constant with filter"); + _set_error("Expected string constant with filter."); else - _set_error("Expected 'GLOBAL' or string constant with filter"); + _set_error("Expected \"GLOBAL\" or string constant with filter."); return; } current_export.hint_string = tokenizer->get_token_constant(); @@ -4302,7 +4428,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { - _set_error("Expected ')' in hint."); + _set_error("Expected \")\" in the hint."); return; } break; @@ -4313,7 +4439,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { current_export.hint = PROPERTY_HINT_MULTILINE_TEXT; tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { - _set_error("Expected ')' in hint."); + _set_error("Expected \")\" in the hint."); return; } break; @@ -4324,7 +4450,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_IDENTIFIER) { current_export = PropertyInfo(); - _set_error("Color type hint expects RGB or RGBA as hints"); + _set_error("Color type hint expects RGB or RGBA as hints."); return; } @@ -4335,7 +4461,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { //none } else { current_export = PropertyInfo(); - _set_error("Color type hint expects RGB or RGBA as hints"); + _set_error("Color type hint expects RGB or RGBA as hints."); return; } tokenizer->advance(); @@ -4344,7 +4470,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { default: { current_export = PropertyInfo(); - _set_error("Type '" + Variant::get_type_name(type) + "' can't take hints."); + _set_error("Type \"" + Variant::get_type_name(type) + "\" can't take hints."); return; } break; } @@ -4382,7 +4508,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } else { current_export = PropertyInfo(); - _set_error("Export hint not a resource type."); + _set_error("The export hint isn't a resource type."); } } else if (constant.get_type() == Variant::DICTIONARY) { // Enumeration @@ -4396,7 +4522,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); } else { current_export = PropertyInfo(); - _set_error("Expected 'FLAGS' after comma."); + _set_error("Expected \"FLAGS\" after comma."); } } @@ -4433,7 +4559,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) { current_export = PropertyInfo(); - _set_error("Expected ')' or ',' after export hint."); + _set_error("Expected \")\" or \",\" after the export hint."); return; } @@ -4453,7 +4579,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_ONREADY && tokenizer->get_token() != GDScriptTokenizer::TK_PR_REMOTE && tokenizer->get_token() != GDScriptTokenizer::TK_PR_MASTER && tokenizer->get_token() != GDScriptTokenizer::TK_PR_PUPPET && tokenizer->get_token() != GDScriptTokenizer::TK_PR_SYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_REMOTESYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_MASTERSYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_PUPPETSYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_SLAVE) { current_export = PropertyInfo(); - _set_error("Expected 'var', 'onready', 'remote', 'master', 'puppet', 'sync', 'remotesync', 'mastersync', 'puppetsync'."); + _set_error("Expected \"var\", \"onready\", \"remote\", \"master\", \"puppet\", \"sync\", \"remotesync\", \"mastersync\", \"puppetsync\"."); return; } @@ -4464,7 +4590,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { //may be fallthrough from export, ignore if so tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) { - _set_error("Expected 'var'."); + _set_error("Expected \"var\"."); return; } @@ -4476,13 +4602,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (current_export.type) { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) { - _set_error("Expected 'var'."); + _set_error("Expected \"var\"."); return; } } else { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { - _set_error("Expected 'var' or 'func'."); + _set_error("Expected \"var\" or \"func\"."); return; } } @@ -4496,13 +4622,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (current_export.type) { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) { - _set_error("Expected 'var'."); + _set_error("Expected \"var\"."); return; } } else { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { - _set_error("Expected 'var' or 'func'."); + _set_error("Expected \"var\" or \"func\"."); return; } } @@ -4521,13 +4647,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (current_export.type) { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) { - _set_error("Expected 'var'."); + _set_error("Expected \"var\"."); return; } } else { if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { - _set_error("Expected 'var' or 'func'."); + _set_error("Expected \"var\" or \"func\"."); return; } } @@ -4542,9 +4668,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { if (current_export.type) - _set_error("Expected 'var'."); + _set_error("Expected \"var\"."); else - _set_error("Expected 'var' or 'func'."); + _set_error("Expected \"var\" or \"func\"."); return; } @@ -4557,9 +4683,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { if (current_export.type) - _set_error("Expected 'var'."); + _set_error("Expected \"var\"."); else - _set_error("Expected 'var' or 'func'."); + _set_error("Expected \"var\" or \"func\"."); return; } @@ -4572,9 +4698,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) { if (current_export.type) - _set_error("Expected 'var'."); + _set_error("Expected \"var\"."); else - _set_error("Expected 'var' or 'func'."); + _set_error("Expected \"var\" or \"func\"."); return; } @@ -4597,7 +4723,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (!tokenizer->is_token_literal(0, true)) { - _set_error("Expected identifier for member variable name."); + _set_error("Expected an identifier for the member variable name."); return; } @@ -4613,18 +4739,25 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { #endif if (current_class->constant_expressions.has(member.identifier)) { - _set_error("A constant named '" + String(member.identifier) + "' already exists in this class (at line: " + + _set_error("A constant named \"" + String(member.identifier) + "\" already exists in this class (at line: " + itos(current_class->constant_expressions[member.identifier].expression->line) + ")."); return; } for (int i = 0; i < current_class->variables.size(); i++) { if (current_class->variables[i].identifier == member.identifier) { - _set_error("Variable '" + String(member.identifier) + "' already exists in this class (at line: " + + _set_error("Variable \"" + String(member.identifier) + "\" already exists in this class (at line: " + itos(current_class->variables[i].line) + ")."); return; } } + + for (int i = 0; i < current_class->subclasses.size(); i++) { + if (current_class->subclasses[i]->name == member.identifier) { + _set_error("A class named \"" + String(member.identifier) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ")."); + return; + } + } #ifdef DEBUG_ENABLED for (int i = 0; i < current_class->functions.size(); i++) { if (current_class->functions[i]->name == member.identifier) { @@ -4651,7 +4784,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { #endif tokenizer->advance(); } else if (!_parse_type(member.data_type)) { - _set_error("Expected type for class variable."); + _set_error("Expected a type for the class variable."); return; } } @@ -4679,7 +4812,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { IdentifierNode *id = static_cast<IdentifierNode *>(op->arguments[1]); if (id->name == "get_node") { - _set_error("Use 'onready var " + String(member.identifier) + " = get_node(..)' instead"); + _set_error("Use \"onready var " + String(member.identifier) + " = get_node(...)\" instead."); return; } } @@ -4707,7 +4840,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { Object *obj = cn->value; Resource *res = Object::cast_to<Resource>(obj); if (res == NULL) { - _set_error("Exported constant not a type or resource."); + _set_error("The exported constant isn't a type or resource."); return; } member._export.hint = PROPERTY_HINT_RESOURCE_TYPE; @@ -4725,7 +4858,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { const Variant *args = &cn->value; cn->value = Variant::construct(member._export.type, &args, 1, err); } else { - _set_error("Cannot convert the provided value to the export type."); + _set_error("Can't convert the provided value to the export type."); return; } } @@ -4764,24 +4897,29 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { return; } - if (member._export.type != Variant::NIL) { - IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name = member.identifier; + Node *expr; - ConstantNode *cn = alloc_node<ConstantNode>(); + if (member.data_type.has_type) { + expr = _get_default_value_for_type(member.data_type); + } else { + DataType exported_type; + exported_type.has_type = true; + exported_type.kind = DataType::BUILTIN; + exported_type.builtin_type = member._export.type; + expr = _get_default_value_for_type(exported_type); + } - Variant::CallError ce2; - cn->value = Variant::construct(member._export.type, NULL, 0, ce2); + IdentifierNode *id = alloc_node<IdentifierNode>(); + id->name = member.identifier; - OperatorNode *op = alloc_node<OperatorNode>(); - op->op = OperatorNode::OP_INIT_ASSIGN; - op->arguments.push_back(id); - op->arguments.push_back(cn); + OperatorNode *op = alloc_node<OperatorNode>(); + op->op = OperatorNode::OP_INIT_ASSIGN; + op->arguments.push_back(id); + op->arguments.push_back(expr); - p_class->initializer->statements.push_back(op); + p_class->initializer->statements.push_back(op); - member.initial_assignment = op; - } + member.initial_assignment = op; } if (autoexport && member.data_type.has_type) { @@ -4812,7 +4950,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) { //just comma means using only getter if (!tokenizer->is_token_literal()) { - _set_error("Expected identifier for setter function after 'setget'."); + _set_error("Expected an identifier for the setter function after \"setget\"."); } member.setter = tokenizer->get_token_literal(); @@ -4825,7 +4963,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (!tokenizer->is_token_literal()) { - _set_error("Expected identifier for getter function after ','."); + _set_error("Expected an identifier for the getter function after \",\"."); } member.getter = tokenizer->get_token_literal(); @@ -4836,7 +4974,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { p_class->variables.push_back(member); if (!_end_statement()) { - _set_error("Expected end of statement (continue)"); + _set_error("Expected end of statement (\"continue\")."); return; } } break; @@ -4848,7 +4986,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); if (!tokenizer->is_token_literal(0, true)) { - _set_error("Expected name (identifier) for constant."); + _set_error("Expected an identifier for the constant."); return; } @@ -4856,19 +4994,26 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { int line = tokenizer->get_token_line(); if (current_class->constant_expressions.has(const_id)) { - _set_error("Constant '" + String(const_id) + "' already exists in this class (at line: " + + _set_error("Constant \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->constant_expressions[const_id].expression->line) + ")."); return; } for (int i = 0; i < current_class->variables.size(); i++) { if (current_class->variables[i].identifier == const_id) { - _set_error("A variable named '" + String(const_id) + "' already exists in this class (at line: " + + _set_error("A variable named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->variables[i].line) + ")."); return; } } + for (int i = 0; i < current_class->subclasses.size(); i++) { + if (current_class->subclasses[i]->name == const_id) { + _set_error("A class named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ")."); + return; + } + } + tokenizer->advance(); if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) { @@ -4879,13 +5024,13 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { #endif tokenizer->advance(); } else if (!_parse_type(constant.type)) { - _set_error("Expected type for class constant."); + _set_error("Expected a type for the class constant."); return; } } if (tokenizer->get_token() != GDScriptTokenizer::TK_OP_ASSIGN) { - _set_error("Constant expects assignment."); + _set_error("Constants must be assigned immediately."); return; } @@ -4900,7 +5045,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } if (subexpr->type != Node::TYPE_CONSTANT) { - _set_error("Expected constant expression", line); + _set_error("Expected a constant expression.", line); return; } subexpr->line = line; @@ -4909,7 +5054,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { p_class->constant_expressions.insert(const_id, constant); if (!_end_statement()) { - _set_error("Expected end of statement (constant)", line); + _set_error("Expected end of statement (constant).", line); return; } @@ -4926,23 +5071,30 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { enum_name = tokenizer->get_token_literal(); if (current_class->constant_expressions.has(enum_name)) { - _set_error("A constant named '" + String(enum_name) + "' already exists in this class (at line: " + + _set_error("A constant named \"" + String(enum_name) + "\" already exists in this class (at line " + itos(current_class->constant_expressions[enum_name].expression->line) + ")."); return; } for (int i = 0; i < current_class->variables.size(); i++) { if (current_class->variables[i].identifier == enum_name) { - _set_error("A variable named '" + String(enum_name) + "' already exists in this class (at line: " + + _set_error("A variable named \"" + String(enum_name) + "\" already exists in this class (at line " + itos(current_class->variables[i].line) + ")."); return; } } + for (int i = 0; i < current_class->subclasses.size(); i++) { + if (current_class->subclasses[i]->name == enum_name) { + _set_error("A class named \"" + String(enum_name) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ")."); + return; + } + } + tokenizer->advance(); } if (tokenizer->get_token() != GDScriptTokenizer::TK_CURLY_BRACKET_OPEN) { - _set_error("Expected '{' in enum declaration"); + _set_error("Expected \"{\" in the enum declaration."); return; } tokenizer->advance(); @@ -4960,7 +5112,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) { _set_error("Unexpected end of file."); } else { - _set_error(String("Unexpected ") + GDScriptTokenizer::get_token_name(tokenizer->get_token()) + ", expected identifier"); + _set_error(String("Unexpected ") + GDScriptTokenizer::get_token_name(tokenizer->get_token()) + ", expected an identifier."); } return; @@ -4983,14 +5135,14 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } if (subexpr->type != Node::TYPE_CONSTANT) { - _set_error("Expected constant expression"); + _set_error("Expected a constant expression."); return; } enum_value_expr = static_cast<ConstantNode *>(subexpr); if (enum_value_expr->value.get_type() != Variant::INT) { - _set_error("Expected an int value for enum"); + _set_error("Expected an integer value for \"enum\"."); return; } @@ -5005,25 +5157,35 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) { tokenizer->advance(); + } else if (tokenizer->is_token_literal(0, true)) { + _set_error("Unexpected identifier."); + return; } if (enum_name != "") { enum_dict[const_id] = enum_value_expr->value; } else { if (current_class->constant_expressions.has(const_id)) { - _set_error("A constant named '" + String(const_id) + "' already exists in this class (at line: " + + _set_error("A constant named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->constant_expressions[const_id].expression->line) + ")."); return; } for (int i = 0; i < current_class->variables.size(); i++) { if (current_class->variables[i].identifier == const_id) { - _set_error("A variable named '" + String(const_id) + "' already exists in this class (at line: " + + _set_error("A variable named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->variables[i].line) + ")."); return; } } + for (int i = 0; i < current_class->subclasses.size(); i++) { + if (current_class->subclasses[i]->name == const_id) { + _set_error("A class named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ")."); + return; + } + } + ClassNode::Constant constant; constant.type.has_type = true; constant.type.kind = DataType::BUILTIN; @@ -5046,7 +5208,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } if (!_end_statement()) { - _set_error("Expected end of statement (enum)"); + _set_error("Expected end of statement (\"enum\")."); return; } @@ -5072,9 +5234,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) { } } -void GDScriptParser::_determine_inheritance(ClassNode *p_class) { +void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive) { - if (p_class->extends_used) { + if (p_class->base_type.has_type) { + // Already determined + } else if (p_class->extends_used) { //do inheritance String path = p_class->extends_file; @@ -5090,19 +5254,19 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class) { String base = base_path; if (base == "" || base.is_rel_path()) { - _set_error("Could not resolve relative path for parent class: " + path, p_class->line); + _set_error("Couldn't resolve relative path for the parent class: " + path, p_class->line); return; } path = base.plus_file(path).simplify_path(); } script = ResourceLoader::load(path); if (script.is_null()) { - _set_error("Could not load base class: " + path, p_class->line); + _set_error("Couldn't load the base class: " + path, p_class->line); return; } if (!script->is_valid()) { - _set_error("Script not fully loaded (cyclic preload?): " + path, p_class->line); + _set_error("Script isn't fully loaded (cyclic preload?): " + path, p_class->line); return; } @@ -5117,7 +5281,7 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class) { script = subclass; } else { - _set_error("Could not find subclass: " + sub, p_class->line); + _set_error("Couldn't find the subclass: " + sub, p_class->line); return; } } @@ -5139,10 +5303,35 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class) { if (ScriptServer::is_global_class(base)) { base_script = ResourceLoader::load(ScriptServer::get_global_class_path(base)); if (!base_script.is_valid()) { - _set_error("Class '" + base + "' could not be fully loaded (script error or cyclic dependency).", p_class->line); + _set_error("The class \"" + base + "\" couldn't be fully loaded (script error or cyclic dependency).", p_class->line); return; } p = NULL; + } else { + List<PropertyInfo> props; + ProjectSettings::get_singleton()->get_property_list(&props); + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + String s = E->get().name; + if (!s.begins_with("autoload/")) { + continue; + } + String name = s.get_slice("/", 1); + if (name == base) { + String singleton_path = ProjectSettings::get_singleton()->get(s); + if (singleton_path.begins_with("*")) { + singleton_path = singleton_path.right(1); + } + if (!singleton_path.begins_with("res://")) { + singleton_path = "res://" + singleton_path; + } + base_script = ResourceLoader::load(singleton_path); + if (!base_script.is_valid()) { + _set_error("Class '" + base + "' could not be fully loaded (script error or cyclic inheritance).", p_class->line); + return; + } + p = NULL; + } + } } while (p) { @@ -5180,13 +5369,13 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class) { if (p->constant_expressions.has(base)) { if (p->constant_expressions[base].expression->type != Node::TYPE_CONSTANT) { - _set_error("Could not resolve constant '" + base + "'.", p_class->line); + _set_error("Couldn't resolve the constant \"" + base + "\".", p_class->line); return; } const ConstantNode *cn = static_cast<const ConstantNode *>(p->constant_expressions[base].expression); base_script = cn->value; if (base_script.is_null()) { - _set_error("Constant is not a class: " + base, p_class->line); + _set_error("Constant isn't a class: " + base, p_class->line); return; } break; @@ -5198,6 +5387,7 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class) { if (base_script.is_valid()) { String ident = base; + Ref<GDScript> find_subclass = base_script; for (int i = extend_iter; i < p_class->extends_class.size(); i++) { @@ -5207,35 +5397,35 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class) { if (base_script->get_subclasses().has(subclass)) { - base_script = base_script->get_subclasses()[subclass]; + find_subclass = base_script->get_subclasses()[subclass]; } else if (base_script->get_constants().has(subclass)) { Ref<GDScript> new_base_class = base_script->get_constants()[subclass]; if (new_base_class.is_null()) { - _set_error("Constant is not a class: " + ident, p_class->line); + _set_error("Constant isn't a class: " + ident, p_class->line); return; } - base_script = new_base_class; + find_subclass = new_base_class; } else { - _set_error("Could not find subclass: " + ident, p_class->line); + _set_error("Couldn't find the subclass: " + ident, p_class->line); return; } } - script = base_script; + script = find_subclass; } else if (!base_class) { if (p_class->extends_class.size() > 1) { - _set_error("Invalid inheritance (unknown class + subclasses)", p_class->line); + _set_error("Invalid inheritance (unknown class + subclasses).", p_class->line); return; } //if not found, try engine classes if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) { - _set_error("Unknown class: '" + base + "'", p_class->line); + _set_error("Unknown class: \"" + base + "\"", p_class->line); return; } @@ -5257,7 +5447,7 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class) { p_class->base_type.kind = DataType::NATIVE; p_class->base_type.native_type = native; } else { - _set_error("Could not determine inheritance", p_class->line); + _set_error("Couldn't determine inheritance.", p_class->line); return; } @@ -5268,9 +5458,11 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class) { p_class->base_type.native_type = "Reference"; } - // Recursively determine subclasses - for (int i = 0; i < p_class->subclasses.size(); i++) { - _determine_inheritance(p_class->subclasses[i]); + if (p_recursive) { + // Recursively determine subclasses + for (int i = 0; i < p_class->subclasses.size(); i++) { + _determine_inheritance(p_class->subclasses[i], p_recursive); + } } } @@ -5400,7 +5592,7 @@ bool GDScriptParser::_parse_type(DataType &r_type, bool p_can_be_void) { switch (tokenizer->get_token()) { case GDScriptTokenizer::TK_PERIOD: { if (!can_index) { - _set_error("Unexpected '.'."); + _set_error("Unexpected \".\"."); return false; } can_index = false; @@ -5431,7 +5623,7 @@ bool GDScriptParser::_parse_type(DataType &r_type, bool p_can_be_void) { } if (tokenizer->get_token(-1) == GDScriptTokenizer::TK_PERIOD) { - _set_error("Expected subclass identifier."); + _set_error("Expected a subclass identifier."); return false; } @@ -5469,7 +5661,7 @@ GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source, Ref<GDScript> gds = script; if (gds.is_valid()) { if (!gds->is_valid()) { - _set_error("Class '" + id + "' could not be fully loaded (script error or cyclic dependency).", p_line); + _set_error("The class \"" + id + "\" couldn't be fully loaded (script error or cyclic dependency).", p_line); return DataType(); } result.kind = DataType::GDSCRIPT; @@ -5478,15 +5670,55 @@ GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source, result.kind = DataType::SCRIPT; result.script_type = script; } else { - _set_error("Class '" + id + "' was found in global scope but its script could not be loaded.", p_line); + _set_error("The class \"" + id + "\" was found in global scope, but its script couldn't be loaded.", p_line); return DataType(); } } name_part++; continue; - } else { - p = current_class; } + List<PropertyInfo> props; + ProjectSettings::get_singleton()->get_property_list(&props); + String singleton_path; + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + String s = E->get().name; + if (!s.begins_with("autoload/")) { + continue; + } + String name = s.get_slice("/", 1); + if (name == id) { + singleton_path = ProjectSettings::get_singleton()->get(s); + if (singleton_path.begins_with("*")) { + singleton_path = singleton_path.right(1); + } + if (!singleton_path.begins_with("res://")) { + singleton_path = "res://" + singleton_path; + } + break; + } + } + if (!singleton_path.empty()) { + Ref<Script> script = ResourceLoader::load(singleton_path); + Ref<GDScript> gds = script; + if (gds.is_valid()) { + if (!gds->is_valid()) { + _set_error("Class '" + id + "' could not be fully loaded (script error or cyclic inheritance).", p_line); + return DataType(); + } + result.kind = DataType::GDSCRIPT; + result.script_type = gds; + } else if (script.is_valid()) { + result.kind = DataType::SCRIPT; + result.script_type = script; + } else { + _set_error("Couldn't fully load singleton script '" + id + "' (possible cyclic reference or parse error).", p_line); + return DataType(); + } + name_part++; + continue; + } + + p = current_class; } else if (base_type.kind == DataType::CLASS) { p = base_type.class_type; } @@ -5547,28 +5779,35 @@ GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source, } } - // Still look for class constants in parent script + // Still look for class constants in parent scripts if (!found && (base_type.kind == DataType::GDSCRIPT || base_type.kind == DataType::SCRIPT)) { Ref<Script> scr = base_type.script_type; ERR_FAIL_COND_V(scr.is_null(), result); - Map<StringName, Variant> constants; - scr->get_constants(&constants); + while (scr.is_valid()) { + Map<StringName, Variant> constants; + scr->get_constants(&constants); - if (constants.has(id)) { - Ref<GDScript> gds = constants[id]; + if (constants.has(id)) { + Ref<GDScript> gds = constants[id]; - if (gds.is_valid()) { - result.kind = DataType::GDSCRIPT; - result.script_type = gds; - found = true; - } else { - Ref<Script> scr2 = constants[id]; - if (scr2.is_valid()) { - result.kind = DataType::SCRIPT; - result.script_type = scr2; + if (gds.is_valid()) { + result.kind = DataType::GDSCRIPT; + result.script_type = gds; found = true; + } else { + Ref<Script> scr2 = constants[id]; + if (scr2.is_valid()) { + result.kind = DataType::SCRIPT; + result.script_type = scr2; + found = true; + } } } + if (found) { + break; + } else { + scr = scr->get_base_script(); + } } } @@ -5579,8 +5818,8 @@ GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source, } else { base = result.to_string(); } - _set_error("Identifier '" + String(id) + "' is not a valid type (not a script or class), or could not be found on base '" + - base + "'.", + _set_error("The identifier \"" + String(id) + "\" isn't a valid type (not a script or class), or couldn't be found on base \"" + + base + "\".", p_line); return DataType(); } @@ -5658,7 +5897,7 @@ GDScriptParser::DataType GDScriptParser::_type_from_gdtype(const GDScriptDataTyp switch (p_gdtype.kind) { case GDScriptDataType::UNINITIALIZED: { - ERR_EXPLAIN("Uninitialized datatype. Please report a bug."); + ERR_PRINT("Uninitialized datatype. Please report a bug."); } break; case GDScriptDataType::BUILTIN: { result.kind = DataType::BUILTIN; @@ -5844,11 +6083,8 @@ bool GDScriptParser::_is_type_compatible(const DataType &p_container, const Data if (p_container.kind == DataType::BUILTIN && p_container.builtin_type == Variant::OBJECT) { // Object built-in is a special case, it's compatible with any object and with null - if (p_expression.kind == DataType::BUILTIN && p_expression.builtin_type == Variant::NIL) { - return true; - } if (p_expression.kind == DataType::BUILTIN) { - return false; + return p_expression.builtin_type == Variant::NIL; } // If it's not a built-in, must be an object return true; @@ -5914,12 +6150,18 @@ bool GDScriptParser::_is_type_compatible(const DataType &p_container, const Data break; } + // Some classes are prefixed with `_` internally + if (!ClassDB::class_exists(expr_native)) { + expr_native = "_" + expr_native; + } + switch (p_container.kind) { case DataType::NATIVE: { if (p_container.is_meta_type) { return ClassDB::is_parent_class(expr_native, GDScriptNativeClass::get_class_static()); } else { - return ClassDB::is_parent_class(expr_native, p_container.native_type); + StringName container_native = ClassDB::class_exists(p_container.native_type) ? p_container.native_type : StringName("_" + p_container.native_type); + return ClassDB::is_parent_class(expr_native, container_native); } } break; case DataType::SCRIPT: @@ -5963,8 +6205,37 @@ bool GDScriptParser::_is_type_compatible(const DataType &p_container, const Data return false; } +GDScriptParser::Node *GDScriptParser::_get_default_value_for_type(const DataType &p_type, int p_line) { + Node *result; + + if (p_type.has_type && p_type.kind == DataType::BUILTIN && p_type.builtin_type != Variant::NIL && p_type.builtin_type != Variant::OBJECT) { + if (p_type.builtin_type == Variant::ARRAY) { + result = alloc_node<ArrayNode>(); + } else if (p_type.builtin_type == Variant::DICTIONARY) { + result = alloc_node<DictionaryNode>(); + } else { + ConstantNode *c = alloc_node<ConstantNode>(); + Variant::CallError err; + c->value = Variant::construct(p_type.builtin_type, NULL, 0, err); + result = c; + } + } else { + ConstantNode *c = alloc_node<ConstantNode>(); + c->value = Variant(); + result = c; + } + + result->line = p_line; + + return result; +} + GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { +#ifdef DEBUG_ENABLED + if (p_node->get_datatype().has_type && p_node->type != Node::TYPE_ARRAY && p_node->type != Node::TYPE_DICTIONARY) { +#else if (p_node->get_datatype().has_type) { +#endif return p_node->get_datatype(); } @@ -6043,8 +6314,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { } if (!valid) { - _set_error("Invalid cast. Cannot convert from '" + source_type.to_string() + - "' to '" + cn->cast_type.to_string() + "'.", + _set_error("Invalid cast. Cannot convert from \"" + source_type.to_string() + + "\" to \"" + cn->cast_type.to_string() + "\".", cn->line); return DataType(); } @@ -6073,11 +6344,11 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { DataType signal_type = _reduce_node_type(op->arguments[1]); // TODO: Check if signal exists when it's a constant if (base_type.has_type && base_type.kind == DataType::BUILTIN && base_type.builtin_type != Variant::NIL && base_type.builtin_type != Variant::OBJECT) { - _set_error("First argument of 'yield()' must be an object.", op->line); + _set_error("The first argument of \"yield()\" must be an object.", op->line); return DataType(); } if (signal_type.has_type && (signal_type.kind != DataType::BUILTIN || signal_type.builtin_type != Variant::STRING)) { - _set_error("Second argument of 'yield()' must be a string.", op->line); + _set_error("The second argument of \"yield()\" must be a string.", op->line); return DataType(); } } @@ -6097,15 +6368,15 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { if (check_types && type_type.has_type) { if (!type_type.is_meta_type && (type_type.kind != DataType::NATIVE || !ClassDB::is_parent_class(type_type.native_type, "Script"))) { - _set_error("Invalid 'is' test: right operand is not a type (not a native type nor a script).", op->line); + _set_error("Invalid \"is\" test: the right operand isn't a type (neither a native type nor a script).", op->line); return DataType(); } type_type.is_meta_type = false; // Test the actual type if (!_is_type_compatible(type_type, value_type) && !_is_type_compatible(value_type, type_type)) { if (op->op == OperatorNode::OP_IS) { - _set_error("A value of type '" + value_type.to_string() + "' will never be an instance of '" + type_type.to_string() + "'.", op->line); + _set_error("A value of type \"" + value_type.to_string() + "\" will never be an instance of \"" + type_type.to_string() + "\".", op->line); } else { - _set_error("A value of type '" + value_type.to_string() + "' will never be of type '" + type_type.to_string() + "'.", op->line); + _set_error("A value of type \"" + value_type.to_string() + "\" will never be of type \"" + type_type.to_string() + "\".", op->line); } return DataType(); } @@ -6133,8 +6404,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { node_type = _get_operation_type(var_op, argument_type, argument_type, valid); if (check_types && !valid) { - _set_error("Invalid operand type ('" + argument_type.to_string() + - "') to unary operator '" + Variant::get_operator_name(var_op) + "'.", + _set_error("Invalid operand type (\"" + argument_type.to_string() + + "\") to unary operator \"" + Variant::get_operator_name(var_op) + "\".", op->line, op->column); return DataType(); } @@ -6178,14 +6449,14 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { node_type = _get_operation_type(var_op, argument_a_type, argument_b_type, valid); if (check_types && !valid) { - _set_error("Invalid operand types ('" + argument_a_type.to_string() + "' and '" + - argument_b_type.to_string() + "') to operator '" + Variant::get_operator_name(var_op) + "'.", + _set_error("Invalid operand types (\"" + argument_a_type.to_string() + "\" and \"" + + argument_b_type.to_string() + "\") to operator \"" + Variant::get_operator_name(var_op) + "\".", op->line, op->column); return DataType(); } #ifdef DEBUG_ENABLED - if (var_op == Variant::OP_DIVIDE && argument_a_type.has_type && argument_a_type.kind == DataType::BUILTIN && argument_a_type.builtin_type == Variant::INT && - argument_b_type.has_type && argument_b_type.kind == DataType::BUILTIN && argument_b_type.builtin_type == Variant::INT) { + if (var_op == Variant::OP_DIVIDE && argument_a_type.kind == DataType::BUILTIN && argument_a_type.builtin_type == Variant::INT && + argument_b_type.kind == DataType::BUILTIN && argument_b_type.builtin_type == Variant::INT) { _add_warning(GDScriptWarning::INTEGER_DIVISION, op->line); } #endif // DEBUG_ENABLED @@ -6194,12 +6465,14 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { // Ternary operators case OperatorNode::OP_TERNARY_IF: { if (op->arguments.size() != 3) { - _set_error("Parser bug: ternary operation without 3 arguments"); + _set_error("Parser bug: ternary operation without 3 arguments."); ERR_FAIL_V(DataType()); } DataType true_type = _reduce_node_type(op->arguments[1]); DataType false_type = _reduce_node_type(op->arguments[2]); + // Check arguments[0] errors. + _reduce_node_type(op->arguments[0]); // If types are equal, then the expression is of the same type // If they are compatible, return the broader type @@ -6227,7 +6500,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { case OperatorNode::OP_ASSIGN_BIT_XOR: case OperatorNode::OP_INIT_ASSIGN: { - _set_error("Assignment inside expression is not allowed (parser bug?).", op->line); + _set_error("Assignment inside an expression isn't allowed (parser bug?).", op->line); return DataType(); } break; @@ -6263,8 +6536,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { if (valid) { result = _type_from_variant(res); } else if (check_types) { - _set_error("Can't get index '" + String(member_id->name.operator String()) + "' on base '" + - base_type.to_string() + "'.", + _set_error("Can't get index \"" + String(member_id->name.operator String()) + "\" on base \"" + + base_type.to_string() + "\".", op->line); return DataType(); } @@ -6351,11 +6624,12 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { case Variant::COLOR: { error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING; } break; - default: {} + default: { + } } } if (error) { - _set_error("Invalid index type (" + index_type.to_string() + ") for base '" + base_type.to_string() + "'.", + _set_error("Invalid index type (" + index_type.to_string() + ") for base \"" + base_type.to_string() + "\".", op->line); return DataType(); } @@ -6388,8 +6662,8 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { node_type = _type_from_variant(res); node_type.is_constant = false; } else if (check_types) { - _set_error("Can't get index '" + String(cn->value) + "' on base '" + - base_type.to_string() + "'.", + _set_error("Can't get index \"" + String(cn->value) + "\" on base \"" + + base_type.to_string() + "\".", op->line); return DataType(); } @@ -6399,11 +6673,11 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { _mark_line_as_unsafe(op->line); } } else if (!for_completion && (index_type.kind != DataType::BUILTIN || index_type.builtin_type != Variant::STRING)) { - _set_error("Only strings can be used as index in the base type '" + base_type.to_string() + "'.", op->line); + _set_error("Only strings can be used as an index in the base type \"" + base_type.to_string() + "\".", op->line); return DataType(); } } - if (check_types && !node_type.has_type) { + if (check_types && !node_type.has_type && base_type.kind == DataType::BUILTIN) { // Can infer indexing type for some variant types DataType result; result.has_type = true; @@ -6416,7 +6690,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { case Variant::REAL: case Variant::NODE_PATH: case Variant::_RID: { - _set_error("Can't index on a value of type '" + base_type.to_string() + "'.", op->line); + _set_error("Can't index on a value of type \"" + base_type.to_string() + "\".", op->line); return DataType(); } break; // Return int @@ -6469,10 +6743,12 @@ GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) { } } } break; - default: {} + default: { + } } - p_node->set_datatype(_resolve_type(node_type, p_node->line)); + node_type = _resolve_type(node_type, p_node->line); + p_node->set_datatype(node_type); return node_type; } @@ -6589,8 +6865,7 @@ bool GDScriptParser::_get_function_signature(DataType &p_base_type, const String } if (!ClassDB::class_exists(native)) { if (!check_types) return false; - ERR_EXPLAIN("Parser bug: Class '" + String(native) + "' not found."); - ERR_FAIL_V(false); + ERR_FAIL_V_MSG(false, "Parser bug: Class '" + String(native) + "' not found."); } MethodBind *method = ClassDB::get_method(native, p_function); @@ -6814,7 +7089,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat if (check_types) { if (!tmp.has_method(callee_name)) { - _set_error("Method '" + callee_name + "' is not declared on base '" + base_type.to_string() + "'.", p_call->line); + _set_error("The method \"" + callee_name + "\" isn't declared on base \"" + base_type.to_string() + "\".", p_call->line); return DataType(); } @@ -6874,7 +7149,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat if (!valid) { #ifdef DEBUG_ENABLED if (p_call->arguments[0]->type == Node::TYPE_SELF) { - _set_error("Method '" + callee_name + "' is not declared in the current class.", p_call->line); + _set_error("The method \"" + callee_name + "\" isn't declared in the current class.", p_call->line); return DataType(); } DataType tmp_type; @@ -6894,14 +7169,12 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat #ifdef DEBUG_ENABLED if (current_function && !for_completion && !is_static && p_call->arguments[0]->type == Node::TYPE_SELF && current_function->_static) { - if (current_function && current_function->_static && p_call->arguments[0]->type == Node::TYPE_SELF) { - _set_error("Can't call non-static function from a static function.", p_call->line); - return DataType(); - } + _set_error("Can't call non-static function from a static function.", p_call->line); + return DataType(); } if (check_types && !is_static && !is_initializer && base_type.is_meta_type) { - _set_error("Non-static function '" + String(callee_name) + "' can only be called from an instance.", p_call->line); + _set_error("Non-static function \"" + String(callee_name) + "\" can only be called from an instance.", p_call->line); return DataType(); } @@ -6926,11 +7199,11 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat } if (arg_count < arg_types.size() - default_args_count) { - _set_error("Too few arguments for '" + callee_name + "()' call. Expected at least " + itos(arg_types.size() - default_args_count) + ".", p_call->line); + _set_error("Too few arguments for \"" + callee_name + "()\" call. Expected at least " + itos(arg_types.size() - default_args_count) + ".", p_call->line); return return_type; } if (!is_vararg && arg_count > arg_types.size()) { - _set_error("Too many arguments for '" + callee_name + "()' call. Expected at most " + itos(arg_types.size()) + ".", p_call->line); + _set_error("Too many arguments for \"" + callee_name + "()\" call. Expected at most " + itos(arg_types.size()) + ".", p_call->line); return return_type; } @@ -6952,7 +7225,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const Operat } else if (!_is_type_compatible(arg_types[i - arg_diff], par_type, true)) { // Supertypes are acceptable for dynamic compliance if (!_is_type_compatible(par_type, arg_types[i - arg_diff])) { - _set_error("At '" + callee_name + "()' call, argument " + itos(i - arg_diff + 1) + ". Assigned type (" + + _set_error("At \"" + callee_name + "()\" call, argument " + itos(i - arg_diff + 1) + ". Assigned type (" + par_type.to_string() + ") doesn't match the function argument's type (" + arg_types[i - arg_diff].to_string() + ").", p_call->line); @@ -7100,8 +7373,7 @@ bool GDScriptParser::_get_member_type(const DataType &p_base_type, const StringN } if (!ClassDB::class_exists(native)) { if (!check_types) return false; - ERR_EXPLAIN("Parser bug: Class '" + String(native) + "' not found."); - ERR_FAIL_V(false); + ERR_FAIL_V_MSG(false, "Parser bug: Class \"" + String(native) + "\" not found."); } bool valid = false; @@ -7271,7 +7543,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType Ref<GDScript> gds = scr; if (gds.is_valid()) { if (!gds->is_valid()) { - _set_error("Class '" + p_identifier + "' could not be fully loaded (script error or cyclic dependency)."); + _set_error("The class \"" + p_identifier + "\" couldn't be fully loaded (script error or cyclic dependency)."); return DataType(); } result.kind = DataType::GDSCRIPT; @@ -7280,7 +7552,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType } return result; } - _set_error("Class '" + p_identifier + "' was found in global scope but its script could not be loaded."); + _set_error("The class \"" + p_identifier + "\" was found in global scope, but its script couldn't be loaded."); return DataType(); } @@ -7323,7 +7595,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType Ref<GDScript> gds = singleton; if (gds.is_valid()) { if (!gds->is_valid()) { - _set_error("Couldn't fully load singleton script '" + p_identifier + "' (possible cyclic reference or parse error).", p_line); + _set_error("Couldn't fully load the singleton script \"" + p_identifier + "\" (possible cyclic reference or parse error).", p_line); return DataType(); } result.kind = DataType::GDSCRIPT; @@ -7335,7 +7607,7 @@ GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType } // This means looking in the current class, which type is always known - _set_error("Identifier '" + p_identifier.operator String() + "' is not declared in the current scope.", p_line); + _set_error("The identifier \"" + p_identifier.operator String() + "\" isn't declared in the current scope.", p_line); } #ifdef DEBUG_ENABLED @@ -7367,7 +7639,7 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) { DataType expr = _resolve_type(c.expression->get_datatype(), c.expression->line); if (check_types && !_is_type_compatible(cont, expr)) { - _set_error("Constant value type (" + expr.to_string() + ") is not compatible with declared type (" + cont.to_string() + ").", + _set_error("The constant value type (" + expr.to_string() + ") isn't compatible with declared type (" + cont.to_string() + ").", c.expression->line); return; } @@ -7378,7 +7650,7 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) { DataType tmp; if (_get_member_type(p_class->base_type, E->key(), tmp)) { - _set_error("Member '" + String(E->key()) + "' already exists in parent class.", c.expression->line); + _set_error("The member \"" + String(E->key()) + "\" already exists in a parent class.", c.expression->line); return; } } @@ -7400,7 +7672,7 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) { DataType tmp; if (_get_member_type(p_class->base_type, v.identifier, tmp)) { - _set_error("Member '" + String(v.identifier) + "' already exists in parent class.", v.line); + _set_error("The member \"" + String(v.identifier) + "\" already exists in a parent class.", v.line); return; } @@ -7417,13 +7689,13 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) { } else { // Try with implicit conversion if (v.data_type.kind != DataType::BUILTIN || !_is_type_compatible(v.data_type, expr_type, true)) { - _set_error("Assigned expression type (" + expr_type.to_string() + ") doesn't match the variable's type (" + + _set_error("The assigned expression's type (" + expr_type.to_string() + ") doesn't match the variable's type (" + v.data_type.to_string() + ").", v.line); return; } - // Replace assignment with implict conversion + // Replace assignment with implicit conversion BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>(); convert->line = v.line; convert->function = GDScriptFunctions::TYPE_CONVERT; @@ -7446,43 +7718,19 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) { if (v.data_type.infer_type) { if (!expr_type.has_type) { - _set_error("Assigned value does not have a set type, variable type cannot be inferred.", v.line); + _set_error("The assigned value doesn't have a set type; the variable type can't be inferred.", v.line); return; } v.data_type = expr_type; v.data_type.is_constant = false; } - } else if (v.data_type.has_type && v.data_type.kind == DataType::BUILTIN) { - // Create default value based on the type - IdentifierNode *id = alloc_node<IdentifierNode>(); - id->line = v.line; - id->name = v.identifier; - - ConstantNode *init = alloc_node<ConstantNode>(); - init->line = v.line; - Variant::CallError err; - init->value = Variant::construct(v.data_type.builtin_type, NULL, 0, err); - - OperatorNode *op = alloc_node<OperatorNode>(); - op->line = v.line; - op->op = OperatorNode::OP_INIT_ASSIGN; - op->arguments.push_back(id); - op->arguments.push_back(init); - - p_class->initializer->statements.push_front(op); - v.initial_assignment = op; -#ifdef DEBUG_ENABLED - NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line = v.line - 1; - p_class->initializer->statements.push_front(nl); -#endif } // Check export hint if (v.data_type.has_type && v._export.type != Variant::NIL) { DataType export_type = _type_from_property(v._export); if (!_is_type_compatible(v.data_type, export_type, true)) { - _set_error("Export hint type (" + export_type.to_string() + ") doesn't match the variable's type (" + + _set_error("The export hint's type (" + export_type.to_string() + ") doesn't match the variable's type (" + v.data_type.to_string() + ").", v.line); return; @@ -7501,15 +7749,15 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) { if (setter->get_required_argument_count() != 1 && !(setter->get_required_argument_count() == 0 && setter->default_values.size() > 0)) { - _set_error("Setter function needs to receive exactly 1 argument. See '" + setter->name + - "()' definition at line " + itos(setter->line) + ".", + _set_error("The setter function needs to receive exactly 1 argument. See \"" + setter->name + + "()\" definition at line " + itos(setter->line) + ".", v.line); return; } if (!_is_type_compatible(v.data_type, setter->argument_types[0])) { - _set_error("Setter argument type (" + setter->argument_types[0].to_string() + - ") doesn't match the variable's type (" + v.data_type.to_string() + "). See '" + - setter->name + "()' definition at line " + itos(setter->line) + ".", + _set_error("The setter argument's type (" + setter->argument_types[0].to_string() + + ") doesn't match the variable's type (" + v.data_type.to_string() + "). See \"" + + setter->name + "()\" definition at line " + itos(setter->line) + ".", v.line); return; } @@ -7520,15 +7768,15 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) { FunctionNode *getter = p_class->functions[j]; if (getter->get_required_argument_count() != 0) { - _set_error("Getter function can't receive arguments. See '" + getter->name + - "()' definition at line " + itos(getter->line) + ".", + _set_error("The getter function can't receive arguments. See \"" + getter->name + + "()\" definition at line " + itos(getter->line) + ".", v.line); return; } if (!_is_type_compatible(v.data_type, getter->get_datatype())) { - _set_error("Getter return type (" + getter->get_datatype().to_string() + + _set_error("The getter return type (" + getter->get_datatype().to_string() + ") doesn't match the variable's type (" + v.data_type.to_string() + - "). See '" + getter->name + "()' definition at line " + itos(getter->line) + ".", + "). See \"" + getter->name + "()\" definition at line " + itos(getter->line) + ".", v.line); return; } @@ -7542,23 +7790,23 @@ void GDScriptParser::_check_class_level_types(ClassNode *p_class) { for (int j = 0; j < p_class->static_functions.size(); j++) { if (v.setter == p_class->static_functions[j]->name) { FunctionNode *setter = p_class->static_functions[j]; - _set_error("Setter can't be a static function. See '" + setter->name + "()' definition at line " + itos(setter->line) + ".", v.line); + _set_error("The setter can't be a static function. See \"" + setter->name + "()\" definition at line " + itos(setter->line) + ".", v.line); return; } if (v.getter == p_class->static_functions[j]->name) { FunctionNode *getter = p_class->static_functions[j]; - _set_error("Getter can't be a static function. See '" + getter->name + "()' definition at line " + itos(getter->line) + ".", v.line); + _set_error("The getter can't be a static function. See \"" + getter->name + "()\" definition at line " + itos(getter->line) + ".", v.line); return; } } if (!found_setter && v.setter != StringName()) { - _set_error("Setter function is not defined.", v.line); + _set_error("The setter function isn't defined.", v.line); return; } if (!found_getter && v.getter != StringName()) { - _set_error("Getter function is not defined.", v.line); + _set_error("The getter function isn't defined.", v.line); return; } } @@ -7605,7 +7853,7 @@ void GDScriptParser::_check_function_types(FunctionNode *p_function) { if (!_is_type_compatible(p_function->argument_types[i], def_type, true)) { String arg_name = p_function->arguments[i]; _set_error("Value type (" + def_type.to_string() + ") doesn't match the type of argument '" + - arg_name + "' (" + p_function->arguments[i] + ")", + arg_name + "' (" + p_function->arguments[i] + ").", p_function->line); } } @@ -7614,6 +7862,11 @@ void GDScriptParser::_check_function_types(FunctionNode *p_function) { if (p_function->arguments_usage[i] == 0 && !p_function->arguments[i].operator String().begins_with("_")) { _add_warning(GDScriptWarning::UNUSED_ARGUMENT, p_function->line, p_function->name, p_function->arguments[i].operator String()); } + for (int j = 0; j < current_class->variables.size(); j++) { + if (current_class->variables[j].identifier == p_function->arguments[i]) { + _add_warning(GDScriptWarning::SHADOWED_VARIABLE, p_function->line, p_function->arguments[i], itos(current_class->variables[j].line)); + } + } #endif // DEBUG_ENABLED } @@ -7663,21 +7916,21 @@ void GDScriptParser::_check_function_types(FunctionNode *p_function) { } } parent_signature += ")"; - _set_error("Function signature doesn't match the parent. Parent signature is: '" + parent_signature + "'.", p_function->line); + _set_error("The function signature doesn't match the parent. Parent signature is: \"" + parent_signature + "\".", p_function->line); return; } } #endif // DEBUG_ENABLED } else { if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) { - _set_error("Constructor cannot return a value.", p_function->line); + _set_error("The constructor can't return a value.", p_function->line); return; } } if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) { if (!p_function->body->has_return) { - _set_error("Non-void function must return a value in all possible paths.", p_function->line); + _set_error("A non-void function must return a value in all possible paths.", p_function->line); return; } } @@ -7687,6 +7940,17 @@ void GDScriptParser::_check_function_types(FunctionNode *p_function) { p_function->return_type.has_type = false; p_function->return_type.may_yield = true; } + +#ifdef DEBUG_ENABLED + for (Map<StringName, LocalVarNode *>::Element *E = p_function->body->variables.front(); E; E = E->next()) { + LocalVarNode *lv = E->get(); + for (int i = 0; i < current_class->variables.size(); i++) { + if (current_class->variables[i].identifier == lv->name) { + _add_warning(GDScriptWarning::SHADOWED_VARIABLE, lv->line, lv->name, itos(current_class->variables[i].line)); + } + } + } +#endif // DEBUG_ENABLED } void GDScriptParser::_check_class_blocks_types(ClassNode *p_class) { @@ -7795,14 +8059,14 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) { if (_is_type_compatible(assign_type, lv->datatype)) { _mark_line_as_unsafe(lv->line); } else { - // Try implict conversion + // Try implicit conversion if (lv->datatype.kind != DataType::BUILTIN || !_is_type_compatible(lv->datatype, assign_type, true)) { - _set_error("Assigned value type (" + assign_type.to_string() + ") doesn't match the variable's type (" + + _set_error("The assigned value type (" + assign_type.to_string() + ") doesn't match the variable's type (" + lv->datatype.to_string() + ").", lv->line); return; } - // Replace assignment with implict conversion + // Replace assignment with implicit conversion BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>(); convert->line = lv->line; convert->function = GDScriptFunctions::TYPE_CONVERT; @@ -7829,7 +8093,7 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) { } if (lv->datatype.infer_type) { if (!assign_type.has_type) { - _set_error("Assigned value does not have a set type, variable type cannot be inferred.", lv->line); + _set_error("The assigned value doesn't have a set type; the variable type can't be inferred.", lv->line); return; } lv->datatype = assign_type; @@ -7880,7 +8144,7 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) { } } if (lh_type.is_constant) { - _set_error("Cannot assign a new value to a constant.", op->line); + _set_error("Can't assign a new value to a constant.", op->line); return; } } @@ -7899,8 +8163,8 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) { rh_type = _get_operation_type(oper, lh_type, arg_type, valid); if (check_types && !valid) { - _set_error("Invalid operand types ('" + lh_type.to_string() + "' and '" + arg_type.to_string() + - "') to assignment operator '" + Variant::get_operator_name(oper) + "'.", + _set_error("Invalid operand types (\"" + lh_type.to_string() + "\" and \"" + arg_type.to_string() + + "\") to assignment operator \"" + Variant::get_operator_name(oper) + "\".", op->line); return; } @@ -7926,14 +8190,14 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) { if (_is_type_compatible(rh_type, lh_type)) { _mark_line_as_unsafe(op->line); } else { - // Try implict conversion + // Try implicit conversion if (lh_type.kind != DataType::BUILTIN || !_is_type_compatible(lh_type, rh_type, true)) { - _set_error("Assigned value type (" + rh_type.to_string() + ") doesn't match the variable's type (" + + _set_error("The assigned value's type (" + rh_type.to_string() + ") doesn't match the variable's type (" + lh_type.to_string() + ").", op->line); return; } - // Replace assignment with implict conversion + // Replace assignment with implicit conversion BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>(); convert->line = op->line; convert->function = GDScriptFunctions::TYPE_CONVERT; @@ -8013,18 +8277,18 @@ void GDScriptParser::_check_block_types(BlockNode *p_block) { if (function_type.kind == DataType::BUILTIN && function_type.builtin_type == Variant::NIL) { // Return void, should not have arguments if (cf->arguments.size() > 0) { - _set_error("Void function cannot return a value.", cf->line, cf->column); + _set_error("A void function cannot return a value.", cf->line, cf->column); return; } } else { // Return something, cannot be empty if (cf->arguments.size() == 0) { - _set_error("Non-void function must return a value.", cf->line, cf->column); + _set_error("A non-void function must return a value.", cf->line, cf->column); return; } if (!_is_type_compatible(function_type, ret_type)) { - _set_error("Returned value type (" + ret_type.to_string() + ") doesn't match the function return type (" + + _set_error("The returned value type (" + ret_type.to_string() + ") doesn't match the function return type (" + function_type.to_string() + ").", cf->line, cf->column); return; @@ -8116,6 +8380,9 @@ void GDScriptParser::_add_warning(int p_code, int p_line, const String &p_symbol } void GDScriptParser::_add_warning(int p_code, int p_line, const Vector<String> &p_symbols) { + if (GLOBAL_GET("debug/gdscript/warnings/exclude_addons").booleanize() && base_path.begins_with("res://addons/")) { + return; + } if (tokenizer->is_ignoring_warnings() || !GLOBAL_GET("debug/gdscript/warnings/enable").booleanize()) { return; } @@ -8161,6 +8428,10 @@ int GDScriptParser::get_error_column() const { return error_column; } +bool GDScriptParser::has_error() const { + return error_set; +} + Error GDScriptParser::_parse(const String &p_base_path) { base_path = p_base_path; @@ -8177,7 +8448,7 @@ Error GDScriptParser::_parse(const String &p_base_path) { if (tokenizer->get_token() == GDScriptTokenizer::TK_ERROR) { error_set = false; - _set_error("Parse Error: " + tokenizer->get_token_error()); + _set_error("Parse error: " + tokenizer->get_token_error()); } if (error_set && !for_completion) { @@ -8325,8 +8596,8 @@ void GDScriptParser::clear() { validating = false; for_completion = false; error_set = false; - tab_level.clear(); - tab_level.push_back(0); + indent_level.clear(); + indent_level.push_back(IndentLevel(0, 0)); error_line = 0; error_column = 0; pending_newline = -1; diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h index 809bff8f20..93557d745d 100644 --- a/modules/gdscript/gdscript_parser.h +++ b/modules/gdscript/gdscript_parser.h @@ -149,6 +149,7 @@ public: bool tool; StringName name; bool extends_used; + bool classname_used; StringName extends_file; Vector<StringName> extends_class; DataType base_type; @@ -198,6 +199,7 @@ public: tool = false; type = TYPE_CLASS; extends_used = false; + classname_used = false; end_line = -1; owner = NULL; } @@ -479,7 +481,12 @@ public: struct AssertNode : public Node { Node *condition; - AssertNode() { type = TYPE_ASSERT; } + Node *message; + AssertNode() : + condition(0), + message(0) { + type = TYPE_ASSERT; + } }; struct BreakpointNode : public Node { @@ -545,7 +552,27 @@ private: int pending_newline; - List<int> tab_level; + struct IndentLevel { + int indent; + int tabs; + + bool is_mixed(IndentLevel other) { + return ( + (indent == other.indent && tabs != other.tabs) || + (indent > other.indent && tabs < other.tabs) || + (indent < other.indent && tabs > other.tabs)); + } + + IndentLevel() : + indent(0), + tabs(0) {} + + IndentLevel(int p_indent, int p_tabs) : + indent(p_indent), + tabs(p_tabs) {} + }; + + List<IndentLevel> indent_level; String base_path; String self_path; @@ -580,7 +607,7 @@ private: #endif // DEBUG_ENABLED bool _recover_from_completion(); - bool _parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete = false); + bool _parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete = false, bool p_parsing_constant = false); bool _enter_indent_block(BlockNode *p_block = NULL); bool _parse_newline(); Node *_parse_expression(Node *p_parent, bool p_static, bool p_allow_assign = false, bool p_parsing_constant = false); @@ -597,7 +624,7 @@ private: void _parse_class(ClassNode *p_class); bool _end_statement(); - void _determine_inheritance(ClassNode *p_class); + void _determine_inheritance(ClassNode *p_class, bool p_recursive = true); bool _parse_type(DataType &r_type, bool p_can_be_void = false); DataType _resolve_type(const DataType &p_source, int p_line); DataType _type_from_variant(const Variant &p_value) const; @@ -608,6 +635,7 @@ private: bool _get_function_signature(DataType &p_base_type, const StringName &p_function, DataType &r_return_type, List<DataType> &r_arg_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) const; bool _get_member_type(const DataType &p_base_type, const StringName &p_member, DataType &r_member_type) const; bool _is_type_compatible(const DataType &p_container, const DataType &p_expression, bool p_allow_implicit_conversion = false) const; + Node *_get_default_value_for_type(const DataType &p_type, int p_line = -1); DataType _reduce_node_type(Node *p_node); DataType _reduce_function_call_type(const OperatorNode *p_call); @@ -630,6 +658,7 @@ private: Error _parse(const String &p_base_path); public: + bool has_error() const; String get_error() const; int get_error_line() const; int get_error_column() const; diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp index abc739d645..761a3de37c 100644 --- a/modules/gdscript/gdscript_tokenizer.cpp +++ b/modules/gdscript/gdscript_tokenizer.cpp @@ -339,7 +339,8 @@ StringName GDScriptTokenizer::get_token_literal(int p_offset) const { return "null"; case Variant::BOOL: return value ? "true" : "false"; - default: {} + default: { + } } } case TK_OP_AND: @@ -356,8 +357,7 @@ StringName GDScriptTokenizer::get_token_literal(int p_offset) const { } } } - ERR_EXPLAIN("Failed to get token literal"); - ERR_FAIL_V(""); + ERR_FAIL_V_MSG("", "Failed to get token literal."); } static bool _is_text_char(CharType c) { @@ -375,6 +375,11 @@ static bool _is_hex(CharType c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } +static bool _is_bin(CharType c) { + + return (c == '0' || c == '1'); +} + void GDScriptTokenizerText::_make_token(Token p_type) { TokenData &tk = tk_rb[tk_rb_pos]; @@ -445,11 +450,11 @@ void GDScriptTokenizerText::_make_error(const String &p_error) { tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } -void GDScriptTokenizerText::_make_newline(int p_spaces) { +void GDScriptTokenizerText::_make_newline(int p_indentation, int p_tabs) { TokenData &tk = tk_rb[tk_rb_pos]; tk.type = TK_NEWLINE; - tk.constant = p_spaces; + tk.constant = Vector2(p_indentation, p_tabs); tk.line = line; tk.col = column; tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; @@ -506,18 +511,6 @@ void GDScriptTokenizerText::_advance() { case ' ': INCPOS(1); continue; - case '\n': { - line++; - INCPOS(1); - column = 1; - int i = 0; - while (GETCHAR(i) == ' ' || GETCHAR(i) == '\t') { - i++; - } - - _make_newline(i); - return; - } case '#': { // line comment skip #ifdef DEBUG_ENABLED String comment; @@ -534,27 +527,45 @@ void GDScriptTokenizerText::_advance() { } } #ifdef DEBUG_ENABLED - if (comment.begins_with("#warning-ignore:")) { - String code = comment.get_slice(":", 1); + String comment_content = comment.trim_prefix("#").trim_prefix(" "); + if (comment_content.begins_with("warning-ignore:")) { + String code = comment_content.get_slice(":", 1); warning_skips.push_back(Pair<int, String>(line, code.strip_edges().to_lower())); - } else if (comment.begins_with("#warning-ignore-all:")) { - String code = comment.get_slice(":", 1); + } else if (comment_content.begins_with("warning-ignore-all:")) { + String code = comment_content.get_slice(":", 1); warning_global_skips.insert(code.strip_edges().to_lower()); - } else if (comment.strip_edges() == "#warnings-disable") { + } else if (comment_content.strip_edges() == "warnings-disable") { ignore_warnings = true; } #endif // DEBUG_ENABLED + FALLTHROUGH; + } + case '\n': { + line++; INCPOS(1); + bool used_spaces = false; + int tabs = 0; column = 1; - line++; int i = 0; - while (GETCHAR(i) == ' ' || GETCHAR(i) == '\t') { - i++; + while (true) { + if (GETCHAR(i) == ' ') { + i++; + used_spaces = true; + } else if (GETCHAR(i) == '\t') { + if (used_spaces) { + _make_error("Spaces used before tabs on a line"); + return; + } + i++; + tabs++; + } else { + break; // not indentation anymore + } } - _make_newline(i); - return; - } break; + _make_newline(i, tabs); + return; + } case '/': { switch (GETCHAR(1)) { @@ -812,12 +823,8 @@ void GDScriptTokenizerText::_advance() { _make_error("Unterminated String"); return; } - if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) { - _make_error("Malformed hex constant in string"); - return; - } - CharType v; + CharType v = 0; if (c >= '0' && c <= '9') { v = c - '0'; } else if (c >= 'a' && c <= 'f') { @@ -827,8 +834,8 @@ void GDScriptTokenizerText::_advance() { v = c - 'A'; v += 10; } else { - ERR_PRINT("BUG"); - v = 0; + _make_error("Malformed hex constant in string"); + return; } res <<= 4; @@ -875,6 +882,7 @@ void GDScriptTokenizerText::_advance() { bool period_found = false; bool exponent_found = false; bool hexa_found = false; + bool bin_found = false; bool sign_found = false; String str; @@ -885,23 +893,38 @@ void GDScriptTokenizerText::_advance() { if (period_found || exponent_found) { _make_error("Invalid numeric constant at '.'"); return; + } else if (bin_found) { + _make_error("Invalid binary constant at '.'"); + return; + } else if (hexa_found) { + _make_error("Invalid hexadecimal constant at '.'"); + return; } period_found = true; } else if (GETCHAR(i) == 'x') { - if (hexa_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) { + if (hexa_found || bin_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) { _make_error("Invalid numeric constant at 'x'"); return; } hexa_found = true; + } else if (hexa_found && _is_hex(GETCHAR(i))) { + + } else if (!hexa_found && GETCHAR(i) == 'b') { + if (bin_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) { + _make_error("Invalid numeric constant at 'b'"); + return; + } + bin_found = true; } else if (!hexa_found && GETCHAR(i) == 'e') { - if (hexa_found || exponent_found) { + if (exponent_found || bin_found) { _make_error("Invalid numeric constant at 'e'"); return; } exponent_found = true; } else if (_is_number(GETCHAR(i))) { //all ok - } else if (hexa_found && _is_hex(GETCHAR(i))) { + + } else if (bin_found && _is_bin(GETCHAR(i))) { } else if ((GETCHAR(i) == '-' || GETCHAR(i) == '+') && exponent_found) { if (sign_found) { @@ -928,6 +951,9 @@ void GDScriptTokenizerText::_advance() { if (hexa_found) { int64_t val = str.hex_to_int64(); _make_constant(val); + } else if (bin_found) { + int64_t val = str.bin_to_int64(); + _make_constant(val); } else if (period_found || exponent_found) { double val = str.to_double(); _make_constant(val); @@ -1131,7 +1157,17 @@ int GDScriptTokenizerText::get_token_line_indent(int p_offset) const { int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; ERR_FAIL_COND_V(tk_rb[ofs].type != TK_NEWLINE, 0); - return tk_rb[ofs].constant; + return tk_rb[ofs].constant.operator Vector2().x; +} + +int GDScriptTokenizerText::get_token_line_tab_indent(int p_offset) const { + + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, 0); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, 0); + + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_NEWLINE, 0); + return tk_rb[ofs].constant.operator Vector2().y; } String GDScriptTokenizerText::get_token_error(int p_offset) const { @@ -1162,10 +1198,8 @@ Error GDScriptTokenizerBuffer::set_code_buffer(const Vector<uint8_t> &p_buffer) ERR_FAIL_COND_V(p_buffer.size() < 24 || p_buffer[0] != 'G' || p_buffer[1] != 'D' || p_buffer[2] != 'S' || p_buffer[3] != 'C', ERR_INVALID_DATA); int version = decode_uint32(&buf[4]); - if (version > BYTECODE_VERSION) { - ERR_EXPLAIN("Bytecode is too New! Please use a newer engine version."); - ERR_FAIL_COND_V(version > BYTECODE_VERSION, ERR_INVALID_DATA); - } + ERR_FAIL_COND_V_MSG(version > BYTECODE_VERSION, ERR_INVALID_DATA, "Bytecode is too recent! Please use a newer engine version."); + int identifier_count = decode_uint32(&buf[8]); int constant_count = decode_uint32(&buf[12]); int line_count = decode_uint32(&buf[16]); @@ -1278,7 +1312,7 @@ Vector<uint8_t> GDScriptTokenizerBuffer::parse_code_string(const String &p_code) } break; case TK_CONSTANT: { - Variant c = tt.get_token_constant(); + const Variant &c = tt.get_token_constant(); if (!constant_map.has(c)) { int idx = constant_map.size(); constant_map[c] = idx; @@ -1302,7 +1336,8 @@ Vector<uint8_t> GDScriptTokenizerBuffer::parse_code_string(const String &p_code) ERR_FAIL_V(Vector<uint8_t>()); } break; - default: {} + default: { + } }; token_array.push_back(token); @@ -1370,7 +1405,7 @@ Vector<uint8_t> GDScriptTokenizerBuffer::parse_code_string(const String &p_code) int len; // Objects cannot be constant, never encode objects Error err = encode_variant(E->get(), NULL, len, false); - ERR_FAIL_COND_V(err != OK, Vector<uint8_t>()); + ERR_FAIL_COND_V_MSG(err != OK, Vector<uint8_t>(), "Error when trying to encode Variant."); int pos = buf.size(); buf.resize(pos + len); encode_variant(E->get(), &buf.write[pos], len, false); diff --git a/modules/gdscript/gdscript_tokenizer.h b/modules/gdscript/gdscript_tokenizer.h index 7b977ff67c..58749012b7 100644 --- a/modules/gdscript/gdscript_tokenizer.h +++ b/modules/gdscript/gdscript_tokenizer.h @@ -168,6 +168,7 @@ public: virtual int get_token_line(int p_offset = 0) const = 0; virtual int get_token_column(int p_offset = 0) const = 0; virtual int get_token_line_indent(int p_offset = 0) const = 0; + virtual int get_token_line_tab_indent(int p_offset = 0) const = 0; virtual String get_token_error(int p_offset = 0) const = 0; virtual void advance(int p_amount = 1) = 0; #ifdef DEBUG_ENABLED @@ -205,7 +206,7 @@ class GDScriptTokenizerText : public GDScriptTokenizer { }; void _make_token(Token p_type); - void _make_newline(int p_spaces = 0); + void _make_newline(int p_indentation = 0, int p_tabs = 0); void _make_identifier(const StringName &p_identifier); void _make_built_in_func(GDScriptFunctions::Function p_func); void _make_constant(const Variant &p_constant); @@ -222,6 +223,7 @@ class GDScriptTokenizerText : public GDScriptTokenizer { int tk_rb_pos; String last_error; bool error_flag; + #ifdef DEBUG_ENABLED Vector<Pair<int, String> > warning_skips; Set<String> warning_global_skips; @@ -239,6 +241,7 @@ public: virtual int get_token_line(int p_offset = 0) const; virtual int get_token_column(int p_offset = 0) const; virtual int get_token_line_indent(int p_offset = 0) const; + virtual int get_token_line_tab_indent(int p_offset = 0) const; virtual const Variant &get_token_constant(int p_offset = 0) const; virtual String get_token_error(int p_offset = 0) const; virtual void advance(int p_amount = 1); @@ -277,6 +280,7 @@ public: virtual int get_token_line(int p_offset = 0) const; virtual int get_token_column(int p_offset = 0) const; virtual int get_token_line_indent(int p_offset = 0) const; + virtual int get_token_line_tab_indent(int p_offset = 0) const { return 0; } virtual const Variant &get_token_constant(int p_offset = 0) const; virtual String get_token_error(int p_offset = 0) const; virtual void advance(int p_amount = 1); diff --git a/modules/gdscript/icons/icon_g_d_script.svg b/modules/gdscript/icons/icon_g_d_script.svg new file mode 100644 index 0000000000..953bb9ae9e --- /dev/null +++ b/modules/gdscript/icons/icon_g_d_script.svg @@ -0,0 +1,5 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<path transform="translate(0 1036.4)" d="m7 1l-0.56445 2.2578a5 5 0 0 0 -0.68945 0.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -0.28516 0.68555l-2.2539 0.5625v2l2.2578 0.56445a5 5 0 0 0 0.2793 0.6875l-1.1934 1.9902 1.4141 1.4141 1.9941-1.1953a5 5 0 0 0 0.68555 0.28516l0.5625 2.2539h2l0.56445-2.2578a5 5 0 0 0 0.6875 -0.2793l1.9902 1.1934 1.4141-1.4141-1.1953-1.9941a5 5 0 0 0 0.28516 -0.68555l2.2539-0.5625v-2l-2.2578-0.56445a5 5 0 0 0 -0.2793 -0.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -0.68555 -0.28516l-0.5625-2.2539h-2zm1 5a2 2 0 0 1 2 2 2 2 0 0 1 -2 2 2 2 0 0 1 -2 -2 2 2 0 0 1 2 -2z" fill="#e0e0e0"/> +</g> +</svg> diff --git a/modules/gdscript/language_server/gdscript_extend_parser.cpp b/modules/gdscript/language_server/gdscript_extend_parser.cpp new file mode 100644 index 0000000000..d63f786fcb --- /dev/null +++ b/modules/gdscript/language_server/gdscript_extend_parser.cpp @@ -0,0 +1,740 @@ +/*************************************************************************/ +/* gdscript_extend_parser.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 "gdscript_extend_parser.h" +#include "../gdscript.h" +#include "core/io/json.h" +#include "gdscript_language_protocol.h" +#include "gdscript_workspace.h" + +void ExtendGDScriptParser::update_diagnostics() { + + diagnostics.clear(); + + if (has_error()) { + lsp::Diagnostic diagnostic; + diagnostic.severity = lsp::DiagnosticSeverity::Error; + diagnostic.message = get_error(); + diagnostic.source = "gdscript"; + diagnostic.code = -1; + lsp::Range range; + lsp::Position pos; + int line = LINE_NUMBER_TO_INDEX(get_error_line()); + const String &line_text = get_lines()[line]; + pos.line = line; + pos.character = line_text.length() - line_text.strip_edges(true, false).length(); + range.start = pos; + range.end = range.start; + range.end.character = line_text.strip_edges(false).length(); + diagnostic.range = range; + diagnostics.push_back(diagnostic); + } + + const List<GDScriptWarning> &warnings = get_warnings(); + for (const List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) { + const GDScriptWarning &warning = E->get(); + lsp::Diagnostic diagnostic; + diagnostic.severity = lsp::DiagnosticSeverity::Warning; + diagnostic.message = warning.get_message(); + diagnostic.source = "gdscript"; + diagnostic.code = warning.code; + lsp::Range range; + lsp::Position pos; + int line = LINE_NUMBER_TO_INDEX(warning.line); + const String &line_text = get_lines()[line]; + pos.line = line; + pos.character = line_text.length() - line_text.strip_edges(true, false).length(); + range.start = pos; + range.end = pos; + range.end.character = line_text.strip_edges(false).length(); + diagnostic.range = range; + diagnostics.push_back(diagnostic); + } +} + +void ExtendGDScriptParser::update_symbols() { + + members.clear(); + + const GDScriptParser::Node *head = get_parse_tree(); + if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) { + + parse_class_symbol(gdclass, class_symbol); + + for (int i = 0; i < class_symbol.children.size(); i++) { + const lsp::DocumentSymbol &symbol = class_symbol.children[i]; + members.set(symbol.name, &symbol); + + // cache level one inner classes + if (symbol.kind == lsp::SymbolKind::Class) { + ClassMembers inner_class; + for (int j = 0; j < symbol.children.size(); j++) { + const lsp::DocumentSymbol &s = symbol.children[j]; + inner_class.set(s.name, &s); + } + inner_classes.set(symbol.name, inner_class); + } + } + } +} + +void ExtendGDScriptParser::update_document_links(const String &p_code) { + document_links.clear(); + + GDScriptTokenizerText tokenizer; + FileAccessRef fs = FileAccess::create(FileAccess::ACCESS_RESOURCES); + tokenizer.set_code(p_code); + while (true) { + if (tokenizer.get_token() == GDScriptTokenizer::TK_EOF) { + break; + } else if (tokenizer.get_token() == GDScriptTokenizer::TK_CONSTANT) { + const Variant &const_val = tokenizer.get_token_constant(); + if (const_val.get_type() == Variant::STRING) { + String path = const_val; + bool exists = fs->file_exists(path); + if (!exists) { + path = get_path().get_base_dir() + "/" + path; + exists = fs->file_exists(path); + } + if (exists) { + String value = const_val; + lsp::DocumentLink link; + link.target = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path); + link.range.start.line = LINE_NUMBER_TO_INDEX(tokenizer.get_token_line()); + link.range.end.line = link.range.start.line; + link.range.end.character = LINE_NUMBER_TO_INDEX(tokenizer.get_token_column()); + link.range.start.character = link.range.end.character - value.length(); + document_links.push_back(link); + } + } + } + tokenizer.advance(); + } +} + +void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p_class, lsp::DocumentSymbol &r_symbol) { + + const String uri = get_uri(); + + r_symbol.uri = uri; + r_symbol.script_path = path; + r_symbol.children.clear(); + r_symbol.name = p_class->name; + if (r_symbol.name.empty()) + r_symbol.name = path.get_file(); + r_symbol.kind = lsp::SymbolKind::Class; + r_symbol.deprecated = false; + r_symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_class->line); + r_symbol.range.start.character = p_class->column; + r_symbol.range.end.line = LINE_NUMBER_TO_INDEX(p_class->end_line); + r_symbol.selectionRange.start.line = r_symbol.range.start.line; + r_symbol.detail = "class " + r_symbol.name; + bool is_root_class = &r_symbol == &class_symbol; + r_symbol.documentation = parse_documentation(is_root_class ? 0 : LINE_NUMBER_TO_INDEX(p_class->line), is_root_class); + + for (int i = 0; i < p_class->variables.size(); ++i) { + + const GDScriptParser::ClassNode::Member &m = p_class->variables[i]; + + lsp::DocumentSymbol symbol; + symbol.name = m.identifier; + symbol.kind = lsp::SymbolKind::Variable; + symbol.deprecated = false; + const int line = LINE_NUMBER_TO_INDEX(m.line); + symbol.range.start.line = line; + symbol.range.start.character = lines[line].length() - lines[line].strip_edges(true, false).length(); + symbol.range.end.line = line; + symbol.range.end.character = lines[line].length(); + symbol.selectionRange.start.line = symbol.range.start.line; + if (m._export.type != Variant::NIL) { + symbol.detail += "export "; + } + symbol.detail += "var " + m.identifier; + if (m.data_type.kind != GDScriptParser::DataType::UNRESOLVED) { + symbol.detail += ": " + m.data_type.to_string(); + } + if (m.default_value.get_type() != Variant::NIL) { + symbol.detail += " = " + JSON::print(m.default_value); + } + + symbol.documentation = parse_documentation(line); + symbol.uri = uri; + symbol.script_path = path; + + r_symbol.children.push_back(symbol); + } + + for (int i = 0; i < p_class->_signals.size(); ++i) { + const GDScriptParser::ClassNode::Signal &signal = p_class->_signals[i]; + + lsp::DocumentSymbol symbol; + symbol.name = signal.name; + symbol.kind = lsp::SymbolKind::Event; + symbol.deprecated = false; + const int line = LINE_NUMBER_TO_INDEX(signal.line); + symbol.range.start.line = line; + symbol.range.start.character = lines[line].length() - lines[line].strip_edges(true, false).length(); + symbol.range.end.line = symbol.range.start.line; + symbol.range.end.character = lines[line].length(); + symbol.selectionRange.start.line = symbol.range.start.line; + symbol.documentation = parse_documentation(line); + symbol.uri = uri; + symbol.script_path = path; + symbol.detail = "signal " + signal.name + "("; + for (int j = 0; j < signal.arguments.size(); j++) { + if (j > 0) { + symbol.detail += ", "; + } + symbol.detail += signal.arguments[j]; + } + symbol.detail += ")"; + + r_symbol.children.push_back(symbol); + } + + for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) { + lsp::DocumentSymbol symbol; + const GDScriptParser::ClassNode::Constant &c = E->value(); + const GDScriptParser::ConstantNode *node = dynamic_cast<const GDScriptParser::ConstantNode *>(c.expression); + ERR_FAIL_COND(!node); + symbol.name = E->key(); + symbol.kind = lsp::SymbolKind::Constant; + symbol.deprecated = false; + const int line = LINE_NUMBER_TO_INDEX(E->get().expression->line); + symbol.range.start.line = line; + symbol.range.start.character = E->get().expression->column; + symbol.range.end.line = symbol.range.start.line; + symbol.range.end.character = lines[line].length(); + symbol.selectionRange.start.line = symbol.range.start.line; + symbol.documentation = parse_documentation(line); + symbol.uri = uri; + symbol.script_path = path; + + symbol.detail = "const " + symbol.name; + if (c.type.kind != GDScriptParser::DataType::UNRESOLVED) { + symbol.detail += ": " + c.type.to_string(); + } + + String value_text; + if (node->value.get_type() == Variant::OBJECT) { + RES res = node->value; + if (res.is_valid() && !res->get_path().empty()) { + value_text = "preload(\"" + res->get_path() + "\")"; + if (symbol.documentation.empty()) { + if (Map<String, ExtendGDScriptParser *>::Element *S = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(res->get_path())) { + symbol.documentation = S->get()->class_symbol.documentation; + } + } + } else { + value_text = JSON::print(node->value); + } + } else { + value_text = JSON::print(node->value); + } + if (!value_text.empty()) { + symbol.detail += " = " + value_text; + } + + r_symbol.children.push_back(symbol); + } + + for (int i = 0; i < p_class->functions.size(); ++i) { + const GDScriptParser::FunctionNode *func = p_class->functions[i]; + lsp::DocumentSymbol symbol; + parse_function_symbol(func, symbol); + r_symbol.children.push_back(symbol); + } + + for (int i = 0; i < p_class->static_functions.size(); ++i) { + const GDScriptParser::FunctionNode *func = p_class->static_functions[i]; + lsp::DocumentSymbol symbol; + parse_function_symbol(func, symbol); + r_symbol.children.push_back(symbol); + } + + for (int i = 0; i < p_class->subclasses.size(); ++i) { + const GDScriptParser::ClassNode *subclass = p_class->subclasses[i]; + lsp::DocumentSymbol symbol; + parse_class_symbol(subclass, symbol); + r_symbol.children.push_back(symbol); + } +} + +void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionNode *p_func, lsp::DocumentSymbol &r_symbol) { + + const String uri = get_uri(); + + r_symbol.name = p_func->name; + r_symbol.kind = lsp::SymbolKind::Function; + r_symbol.detail = "func " + p_func->name + "("; + r_symbol.deprecated = false; + const int line = LINE_NUMBER_TO_INDEX(p_func->line); + r_symbol.range.start.line = line; + r_symbol.range.start.character = p_func->column; + r_symbol.range.end.line = MAX(p_func->body->end_line - 2, r_symbol.range.start.line); + r_symbol.range.end.character = lines[r_symbol.range.end.line].length(); + r_symbol.selectionRange.start.line = r_symbol.range.start.line; + r_symbol.documentation = parse_documentation(line); + r_symbol.uri = uri; + r_symbol.script_path = path; + + String arguments; + for (int i = 0; i < p_func->arguments.size(); i++) { + lsp::DocumentSymbol symbol; + symbol.kind = lsp::SymbolKind::Variable; + symbol.name = p_func->arguments[i]; + symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_func->body->line); + symbol.range.start.character = p_func->body->column; + symbol.range.end = symbol.range.start; + symbol.uri = uri; + symbol.script_path = path; + r_symbol.children.push_back(symbol); + if (i > 0) { + arguments += ", "; + } + arguments += String(p_func->arguments[i]); + if (p_func->argument_types[i].kind != GDScriptParser::DataType::UNRESOLVED) { + arguments += ": " + p_func->argument_types[i].to_string(); + } + int default_value_idx = i - (p_func->arguments.size() - p_func->default_values.size()); + if (default_value_idx >= 0) { + const GDScriptParser::ConstantNode *const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(p_func->default_values[default_value_idx]); + if (const_node == NULL) { + const GDScriptParser::OperatorNode *operator_node = dynamic_cast<const GDScriptParser::OperatorNode *>(p_func->default_values[default_value_idx]); + if (operator_node) { + const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(operator_node->next); + } + } + + if (const_node) { + String value = JSON::print(const_node->value); + arguments += " = " + value; + } + } + } + r_symbol.detail += arguments + ")"; + if (p_func->return_type.kind != GDScriptParser::DataType::UNRESOLVED) { + r_symbol.detail += " -> " + p_func->return_type.to_string(); + } + + for (const Map<StringName, LocalVarNode *>::Element *E = p_func->body->variables.front(); E; E = E->next()) { + lsp::DocumentSymbol symbol; + const GDScriptParser::LocalVarNode *var = E->value(); + symbol.name = E->key(); + symbol.kind = lsp::SymbolKind::Variable; + symbol.range.start.line = LINE_NUMBER_TO_INDEX(E->get()->line); + symbol.range.start.character = E->get()->column; + symbol.range.end.line = symbol.range.start.line; + symbol.range.end.character = lines[symbol.range.end.line].length(); + symbol.uri = uri; + symbol.script_path = path; + symbol.detail = "var " + symbol.name; + if (var->datatype.kind != GDScriptParser::DataType::UNRESOLVED) { + symbol.detail += ": " + var->datatype.to_string(); + } + symbol.documentation = parse_documentation(line); + r_symbol.children.push_back(symbol); + } +} + +String ExtendGDScriptParser::parse_documentation(int p_line, bool p_docs_down) { + ERR_FAIL_INDEX_V(p_line, lines.size(), String()); + + List<String> doc_lines; + + if (!p_docs_down) { // inline comment + String inline_comment = lines[p_line]; + int comment_start = inline_comment.find("#"); + if (comment_start != -1) { + inline_comment = inline_comment.substr(comment_start, inline_comment.length()).strip_edges(); + if (inline_comment.length() > 1) { + doc_lines.push_back(inline_comment.substr(1, inline_comment.length())); + } + } + } + + int step = p_docs_down ? 1 : -1; + int start_line = p_docs_down ? p_line : p_line - 1; + for (int i = start_line; true; i += step) { + + if (i < 0 || i >= lines.size()) break; + + String line_comment = lines[i].strip_edges(true, false); + if (line_comment.begins_with("#")) { + line_comment = line_comment.substr(1, line_comment.length()); + if (p_docs_down) { + doc_lines.push_back(line_comment); + } else { + doc_lines.push_front(line_comment); + } + } else { + break; + } + } + + String doc; + for (List<String>::Element *E = doc_lines.front(); E; E = E->next()) { + doc += E->get() + "\n"; + } + return doc; +} + +String ExtendGDScriptParser::get_text_for_completion(const lsp::Position &p_cursor) const { + + String longthing; + int len = lines.size(); + for (int i = 0; i < len; i++) { + + if (i == p_cursor.line) { + longthing += lines[i].substr(0, p_cursor.character); + longthing += String::chr(0xFFFF); //not unicode, represents the cursor + longthing += lines[i].substr(p_cursor.character, lines[i].size()); + } else { + + longthing += lines[i]; + } + + if (i != len - 1) + longthing += "\n"; + } + + return longthing; +} + +String ExtendGDScriptParser::get_text_for_lookup_symbol(const lsp::Position &p_cursor, const String &p_symbol, bool p_func_requred) const { + String longthing; + int len = lines.size(); + for (int i = 0; i < len; i++) { + + if (i == p_cursor.line) { + String line = lines[i]; + String first_part = line.substr(0, p_cursor.character); + String last_part = line.substr(p_cursor.character + 1, lines[i].length()); + if (!p_symbol.empty()) { + String left_cursor_text; + for (int c = p_cursor.character - 1; c >= 0; c--) { + left_cursor_text = line.substr(c, p_cursor.character - c); + if (p_symbol.begins_with(left_cursor_text)) { + first_part = line.substr(0, c); + first_part += p_symbol; + break; + } + } + } + + longthing += first_part; + longthing += String::chr(0xFFFF); //not unicode, represents the cursor + if (p_func_requred) { + longthing += "("; // tell the parser this is a function call + } + longthing += last_part; + } else { + + longthing += lines[i]; + } + + if (i != len - 1) + longthing += "\n"; + } + + return longthing; +} + +String ExtendGDScriptParser::get_identifier_under_position(const lsp::Position &p_position, Vector2i &p_offset) const { + + ERR_FAIL_INDEX_V(p_position.line, lines.size(), ""); + String line = lines[p_position.line]; + ERR_FAIL_INDEX_V(p_position.character, line.size(), ""); + + int start_pos = p_position.character; + for (int c = p_position.character; c >= 0; c--) { + start_pos = c; + CharType ch = line[c]; + bool valid_char = (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_'; + if (!valid_char) { + break; + } + } + + int end_pos = p_position.character; + for (int c = p_position.character; c < line.length(); c++) { + CharType ch = line[c]; + bool valid_char = (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_'; + if (!valid_char) { + break; + } + end_pos = c; + } + if (start_pos < end_pos) { + p_offset.x = start_pos - p_position.character; + p_offset.y = end_pos - p_position.character; + return line.substr(start_pos + 1, end_pos - start_pos); + } + + return ""; +} + +String ExtendGDScriptParser::get_uri() const { + return GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path); +} + +const lsp::DocumentSymbol *ExtendGDScriptParser::search_symbol_defined_at_line(int p_line, const lsp::DocumentSymbol &p_parent) const { + const lsp::DocumentSymbol *ret = NULL; + if (p_line < p_parent.range.start.line) { + return ret; + } else if (p_parent.range.start.line == p_line) { + return &p_parent; + } else { + for (int i = 0; i < p_parent.children.size(); i++) { + ret = search_symbol_defined_at_line(p_line, p_parent.children[i]); + if (ret) { + break; + } + } + } + return ret; +} + +const lsp::DocumentSymbol *ExtendGDScriptParser::get_symbol_defined_at_line(int p_line) const { + if (p_line <= 0) { + return &class_symbol; + } + return search_symbol_defined_at_line(p_line, class_symbol); +} + +const lsp::DocumentSymbol *ExtendGDScriptParser::get_member_symbol(const String &p_name, const String &p_subclass) const { + + if (p_subclass.empty()) { + const lsp::DocumentSymbol *const *ptr = members.getptr(p_name); + if (ptr) { + return *ptr; + } + } else { + if (const ClassMembers *_class = inner_classes.getptr(p_subclass)) { + const lsp::DocumentSymbol *const *ptr = _class->getptr(p_name); + if (ptr) { + return *ptr; + } + } + } + + return NULL; +} + +const List<lsp::DocumentLink> &ExtendGDScriptParser::get_document_links() const { + return document_links; +} + +const Array &ExtendGDScriptParser::get_member_completions() { + + if (member_completions.empty()) { + + const String *name = members.next(NULL); + while (name) { + + const lsp::DocumentSymbol *symbol = members.get(*name); + lsp::CompletionItem item = symbol->make_completion_item(); + item.data = JOIN_SYMBOLS(path, *name); + member_completions.push_back(item.to_json()); + + name = members.next(name); + } + + const String *_class = inner_classes.next(NULL); + while (_class) { + + const ClassMembers *inner_class = inner_classes.getptr(*_class); + const String *member_name = inner_class->next(NULL); + while (member_name) { + const lsp::DocumentSymbol *symbol = inner_class->get(*member_name); + lsp::CompletionItem item = symbol->make_completion_item(); + item.data = JOIN_SYMBOLS(path, JOIN_SYMBOLS(*_class, *member_name)); + member_completions.push_back(item.to_json()); + + member_name = inner_class->next(member_name); + } + + _class = inner_classes.next(_class); + } + } + + return member_completions; +} + +Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::FunctionNode *p_func) const { + Dictionary func; + ERR_FAIL_NULL_V(p_func, func); + func["name"] = p_func->name; + func["return_type"] = p_func->return_type.to_string(); + func["rpc_mode"] = p_func->rpc_mode; + Array arguments; + for (int i = 0; i < p_func->arguments.size(); i++) { + Dictionary arg; + arg["name"] = p_func->arguments[i]; + arg["type"] = p_func->argument_types[i].to_string(); + int default_value_idx = i - (p_func->arguments.size() - p_func->default_values.size()); + if (default_value_idx >= 0) { + const GDScriptParser::ConstantNode *const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(p_func->default_values[default_value_idx]); + if (const_node == NULL) { + const GDScriptParser::OperatorNode *operator_node = dynamic_cast<const GDScriptParser::OperatorNode *>(p_func->default_values[default_value_idx]); + if (operator_node) { + const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(operator_node->next); + } + } + if (const_node) { + arg["default_value"] = const_node->value; + } + } + arguments.push_back(arg); + } + if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_func->line))) { + func["signature"] = symbol->detail; + func["description"] = symbol->documentation; + } + func["arguments"] = arguments; + return func; +} + +Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode *p_class) const { + Dictionary class_api; + + ERR_FAIL_NULL_V(p_class, class_api); + + class_api["name"] = String(p_class->name); + class_api["path"] = path; + Array extends_class; + for (int i = 0; i < p_class->extends_class.size(); i++) { + extends_class.append(String(p_class->extends_class[i])); + } + class_api["extends_class"] = extends_class; + class_api["extends_file"] = String(p_class->extends_file); + class_api["icon"] = String(p_class->icon_path); + + if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_class->line))) { + class_api["signature"] = symbol->detail; + class_api["description"] = symbol->documentation; + } + + Array subclasses; + for (int i = 0; i < p_class->subclasses.size(); i++) { + subclasses.push_back(dump_class_api(p_class->subclasses[i])); + } + class_api["sub_classes"] = subclasses; + + Array constants; + for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) { + + const GDScriptParser::ClassNode::Constant &c = E->value(); + const GDScriptParser::ConstantNode *node = dynamic_cast<const GDScriptParser::ConstantNode *>(c.expression); + ERR_FAIL_COND_V(!node, class_api); + + Dictionary api; + api["name"] = E->key(); + api["value"] = node->value; + api["data_type"] = node->datatype.to_string(); + if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(node->line))) { + api["signature"] = symbol->detail; + api["description"] = symbol->documentation; + } + constants.push_back(api); + } + class_api["constants"] = constants; + + Array members; + for (int i = 0; i < p_class->variables.size(); ++i) { + const GDScriptParser::ClassNode::Member &m = p_class->variables[i]; + Dictionary api; + api["name"] = m.identifier; + api["data_type"] = m.data_type.to_string(); + api["default_value"] = m.default_value; + api["setter"] = String(m.setter); + api["getter"] = String(m.getter); + api["export"] = m._export.type != Variant::NIL; + if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.line))) { + api["signature"] = symbol->detail; + api["description"] = symbol->documentation; + } + members.push_back(api); + } + class_api["members"] = members; + + Array signals; + for (int i = 0; i < p_class->_signals.size(); ++i) { + const GDScriptParser::ClassNode::Signal &signal = p_class->_signals[i]; + Dictionary api; + api["name"] = signal.name; + Array args; + for (int j = 0; j < signal.arguments.size(); j++) { + args.append(signal.arguments[j]); + } + api["arguments"] = args; + if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(signal.line))) { + api["signature"] = symbol->detail; + api["description"] = symbol->documentation; + } + signals.push_back(api); + } + class_api["signals"] = signals; + + Array methods; + for (int i = 0; i < p_class->functions.size(); ++i) { + methods.append(dump_function_api(p_class->functions[i])); + } + class_api["methods"] = methods; + + Array static_functions; + for (int i = 0; i < p_class->static_functions.size(); ++i) { + static_functions.append(dump_function_api(p_class->functions[i])); + } + class_api["static_functions"] = static_functions; + + return class_api; +} + +Dictionary ExtendGDScriptParser::generate_api() const { + + Dictionary api; + const GDScriptParser::Node *head = get_parse_tree(); + if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) { + api = dump_class_api(gdclass); + } + return api; +} + +Error ExtendGDScriptParser::parse(const String &p_code, const String &p_path) { + path = p_path; + lines = p_code.split("\n"); + + Error err = GDScriptParser::parse(p_code, p_path.get_base_dir(), false, p_path, false, NULL, false); + update_diagnostics(); + update_symbols(); + update_document_links(p_code); + return err; +} diff --git a/modules/gdscript/language_server/gdscript_extend_parser.h b/modules/gdscript/language_server/gdscript_extend_parser.h new file mode 100644 index 0000000000..a6e0ca5534 --- /dev/null +++ b/modules/gdscript/language_server/gdscript_extend_parser.h @@ -0,0 +1,101 @@ +/*************************************************************************/ +/* gdscript_extend_parser.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 GDSCRIPT_EXTEND_PARSER_H +#define GDSCRIPT_EXTEND_PARSER_H + +#include "../gdscript_parser.h" +#include "core/variant.h" +#include "lsp.hpp" + +#ifndef LINE_NUMBER_TO_INDEX +#define LINE_NUMBER_TO_INDEX(p_line) ((p_line)-1) +#endif + +#ifndef SYMBOL_SEPERATOR +#define SYMBOL_SEPERATOR "::" +#endif + +#ifndef JOIN_SYMBOLS +#define JOIN_SYMBOLS(p_path, name) ((p_path) + SYMBOL_SEPERATOR + (name)) +#endif + +typedef HashMap<String, const lsp::DocumentSymbol *> ClassMembers; + +class ExtendGDScriptParser : public GDScriptParser { + + String path; + Vector<String> lines; + + lsp::DocumentSymbol class_symbol; + Vector<lsp::Diagnostic> diagnostics; + List<lsp::DocumentLink> document_links; + ClassMembers members; + HashMap<String, ClassMembers> inner_classes; + + void update_diagnostics(); + + void update_symbols(); + void update_document_links(const String &p_code); + void parse_class_symbol(const GDScriptParser::ClassNode *p_class, lsp::DocumentSymbol &r_symbol); + void parse_function_symbol(const GDScriptParser::FunctionNode *p_func, lsp::DocumentSymbol &r_symbol); + + Dictionary dump_function_api(const GDScriptParser::FunctionNode *p_func) const; + Dictionary dump_class_api(const GDScriptParser::ClassNode *p_class) const; + + String parse_documentation(int p_line, bool p_docs_down = false); + const lsp::DocumentSymbol *search_symbol_defined_at_line(int p_line, const lsp::DocumentSymbol &p_parent) const; + + Array member_completions; + +public: + _FORCE_INLINE_ const String &get_path() const { return path; } + _FORCE_INLINE_ const Vector<String> &get_lines() const { return lines; } + _FORCE_INLINE_ const lsp::DocumentSymbol &get_symbols() const { return class_symbol; } + _FORCE_INLINE_ const Vector<lsp::Diagnostic> &get_diagnostics() const { return diagnostics; } + _FORCE_INLINE_ const ClassMembers &get_members() const { return members; } + _FORCE_INLINE_ const HashMap<String, ClassMembers> &get_inner_classes() const { return inner_classes; } + + String get_text_for_completion(const lsp::Position &p_cursor) const; + String get_text_for_lookup_symbol(const lsp::Position &p_cursor, const String &p_symbol = "", bool p_func_requred = false) const; + String get_identifier_under_position(const lsp::Position &p_position, Vector2i &p_offset) const; + String get_uri() const; + + const lsp::DocumentSymbol *get_symbol_defined_at_line(int p_line) const; + const lsp::DocumentSymbol *get_member_symbol(const String &p_name, const String &p_subclass = "") const; + const List<lsp::DocumentLink> &get_document_links() const; + + const Array &get_member_completions(); + Dictionary generate_api() const; + + Error parse(const String &p_code, const String &p_path); +}; + +#endif diff --git a/modules/gdscript/language_server/gdscript_language_protocol.cpp b/modules/gdscript/language_server/gdscript_language_protocol.cpp new file mode 100644 index 0000000000..90646f73ba --- /dev/null +++ b/modules/gdscript/language_server/gdscript_language_protocol.cpp @@ -0,0 +1,235 @@ +/*************************************************************************/ +/* gdscript_language_protocol.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 "gdscript_language_protocol.h" +#include "core/io/json.h" +#include "core/os/copymem.h" +#include "core/project_settings.h" +#include "editor/editor_node.h" + +GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = NULL; + +void GDScriptLanguageProtocol::on_data_received(int p_id) { + lastest_client_id = p_id; + Ref<WebSocketPeer> peer = server->get_peer(p_id); + PoolByteArray data; + if (OK == peer->get_packet_buffer(data)) { + String message; + message.parse_utf8((const char *)data.read().ptr(), data.size()); + if (message.begins_with("Content-Length:")) return; + String output = process_message(message); + if (!output.empty()) { + CharString charstr = output.utf8(); + peer->put_packet((const uint8_t *)charstr.ptr(), charstr.length()); + } + } +} + +void GDScriptLanguageProtocol::on_client_connected(int p_id, const String &p_protocal) { + clients.set(p_id, server->get_peer(p_id)); +} + +void GDScriptLanguageProtocol::on_client_disconnected(int p_id, bool p_was_clean_close) { + clients.erase(p_id); +} + +String GDScriptLanguageProtocol::process_message(const String &p_text) { + String ret = process_string(p_text); + if (ret.empty()) { + return ret; + } else { + return format_output(ret); + } +} + +String GDScriptLanguageProtocol::format_output(const String &p_text) { + + String header = "Content-Length: "; + CharString charstr = p_text.utf8(); + size_t len = charstr.length(); + header += itos(len); + header += "\r\n\r\n"; + + return header + p_text; +} + +void GDScriptLanguageProtocol::_bind_methods() { + ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize); + ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized); + ClassDB::bind_method(D_METHOD("on_data_received"), &GDScriptLanguageProtocol::on_data_received); + ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected); + ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected); + ClassDB::bind_method(D_METHOD("notify_all_clients", "p_method", "p_params"), &GDScriptLanguageProtocol::notify_all_clients, DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("notify_client", "p_method", "p_params", "p_client"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled); + ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document); + ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace); + ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized); +} + +Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) { + + lsp::InitializeResult ret; + + String root_uri = p_params["rootUri"]; + String root = p_params["rootPath"]; + bool is_same_workspace; +#ifndef WINDOWS_ENABLED + is_same_workspace = root.to_lower() == workspace->root.to_lower(); +#else + is_same_workspace = root.replace("\\", "/").to_lower() == workspace->root.to_lower(); +#endif + + if (root_uri.length() && is_same_workspace) { + workspace->root_uri = root_uri; + } else { + + workspace->root_uri = "file://" + workspace->root; + + Dictionary params; + params["path"] = workspace->root; + Dictionary request = make_notification("gdscrip_client/changeWorkspace", params); + if (Ref<WebSocketPeer> *peer = clients.getptr(lastest_client_id)) { + String msg = JSON::print(request); + msg = format_output(msg); + CharString charstr = msg.utf8(); + (*peer)->put_packet((const uint8_t *)charstr.ptr(), charstr.length()); + } + } + + if (!_initialized) { + workspace->initialize(); + text_document->initialize(); + _initialized = true; + } + + return ret.to_json(); +} + +void GDScriptLanguageProtocol::initialized(const Variant &p_params) { + + lsp::GodotCapabilities capabilities; + + DocData *doc = EditorHelp::get_doc_data(); + for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) { + + lsp::GodotNativeClassInfo gdclass; + gdclass.name = E->get().name; + gdclass.class_doc = &(E->get()); + if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E->get().name))) { + gdclass.class_info = ptr; + } + capabilities.native_classes.push_back(gdclass); + } + + notify_client("gdscript/capabilities", capabilities.to_json()); +} + +void GDScriptLanguageProtocol::poll() { + server->poll(); +} + +Error GDScriptLanguageProtocol::start(int p_port) { + if (server == NULL) { + server = dynamic_cast<WebSocketServer *>(ClassDB::instance("WebSocketServer")); + ERR_FAIL_COND_V(!server, FAILED); + server->set_buffers(8192, 1024, 8192, 1024); // 8mb should be way more than enough + server->connect("data_received", this, "on_data_received"); + server->connect("client_connected", this, "on_client_connected"); + server->connect("client_disconnected", this, "on_client_disconnected"); + } + return server->listen(p_port); +} + +void GDScriptLanguageProtocol::stop() { + const int *ptr = clients.next(NULL); + while (ptr) { + clients.get(*ptr)->close(); + ptr = clients.next(ptr); + } + server->stop(); + clients.clear(); +} + +void GDScriptLanguageProtocol::notify_all_clients(const String &p_method, const Variant &p_params) { + + Dictionary message = make_notification(p_method, p_params); + String msg = JSON::print(message); + msg = format_output(msg); + CharString charstr = msg.utf8(); + const int *p_id = clients.next(NULL); + while (p_id != NULL) { + Ref<WebSocketPeer> peer = clients.get(*p_id); + (*peer)->put_packet((const uint8_t *)charstr.ptr(), charstr.length()); + p_id = clients.next(p_id); + } +} + +void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client) { + + if (p_client == -1) { + p_client = lastest_client_id; + } + + Ref<WebSocketPeer> *peer = clients.getptr(p_client); + ERR_FAIL_COND(peer == NULL); + + Dictionary message = make_notification(p_method, p_params); + String msg = JSON::print(message); + msg = format_output(msg); + CharString charstr = msg.utf8(); + + (*peer)->put_packet((const uint8_t *)charstr.ptr(), charstr.length()); +} + +bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const { + return bool(_EDITOR_GET("network/language_server/enable_smart_resolve")); +} + +bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const { + return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor")); +} + +GDScriptLanguageProtocol::GDScriptLanguageProtocol() { + server = NULL; + singleton = this; + _initialized = false; + workspace.instance(); + text_document.instance(); + set_scope("textDocument", text_document.ptr()); + set_scope("completionItem", text_document.ptr()); + set_scope("workspace", workspace.ptr()); + workspace->root = ProjectSettings::get_singleton()->get_resource_path(); +} + +GDScriptLanguageProtocol::~GDScriptLanguageProtocol() { + memdelete(server); + server = NULL; +} diff --git a/modules/gdscript/language_server/gdscript_language_protocol.h b/modules/gdscript/language_server/gdscript_language_protocol.h new file mode 100644 index 0000000000..136b45fd78 --- /dev/null +++ b/modules/gdscript/language_server/gdscript_language_protocol.h @@ -0,0 +1,93 @@ +/*************************************************************************/ +/* gdscript_language_protocol.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 GDSCRIPT_PROTOCAL_SERVER_H +#define GDSCRIPT_PROTOCAL_SERVER_H + +#include "gdscript_text_document.h" +#include "gdscript_workspace.h" +#include "lsp.hpp" +#include "modules/jsonrpc/jsonrpc.h" +#include "modules/websocket/websocket_peer.h" +#include "modules/websocket/websocket_server.h" + +class GDScriptLanguageProtocol : public JSONRPC { + GDCLASS(GDScriptLanguageProtocol, JSONRPC) + + enum LSPErrorCode { + RequestCancelled = -32800, + ContentModified = -32801, + }; + + static GDScriptLanguageProtocol *singleton; + + HashMap<int, Ref<WebSocketPeer> > clients; + WebSocketServer *server; + int lastest_client_id; + + Ref<GDScriptTextDocument> text_document; + Ref<GDScriptWorkspace> workspace; + + void on_data_received(int p_id); + void on_client_connected(int p_id, const String &p_protocal); + void on_client_disconnected(int p_id, bool p_was_clean_close); + + String process_message(const String &p_text); + String format_output(const String &p_text); + + bool _initialized; + +protected: + static void _bind_methods(); + + Dictionary initialize(const Dictionary &p_params); + void initialized(const Variant &p_params); + +public: + _FORCE_INLINE_ static GDScriptLanguageProtocol *get_singleton() { return singleton; } + _FORCE_INLINE_ Ref<GDScriptWorkspace> get_workspace() { return workspace; } + _FORCE_INLINE_ Ref<GDScriptTextDocument> get_text_document() { return text_document; } + _FORCE_INLINE_ bool is_initialized() const { return _initialized; } + + void poll(); + Error start(int p_port); + void stop(); + + void notify_all_clients(const String &p_method, const Variant &p_params = Variant()); + void notify_client(const String &p_method, const Variant &p_params = Variant(), int p_client = -1); + + bool is_smart_resolve_enabled() const; + bool is_goto_native_symbols_enabled() const; + + GDScriptLanguageProtocol(); + ~GDScriptLanguageProtocol(); +}; + +#endif diff --git a/modules/gdscript/language_server/gdscript_language_server.cpp b/modules/gdscript/language_server/gdscript_language_server.cpp new file mode 100644 index 0000000000..8d58b99e02 --- /dev/null +++ b/modules/gdscript/language_server/gdscript_language_server.cpp @@ -0,0 +1,89 @@ +/*************************************************************************/ +/* gdscript_language_server.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 "gdscript_language_server.h" +#include "core/os/file_access.h" +#include "core/os/os.h" +#include "editor/editor_node.h" + +GDScriptLanguageServer::GDScriptLanguageServer() { + thread = NULL; + thread_exit = false; + _EDITOR_DEF("network/language_server/remote_port", 6008); + _EDITOR_DEF("network/language_server/enable_smart_resolve", false); + _EDITOR_DEF("network/language_server/show_native_symbols_in_editor", false); +} + +void GDScriptLanguageServer::_notification(int p_what) { + + switch (p_what) { + case NOTIFICATION_ENTER_TREE: + start(); + break; + case NOTIFICATION_EXIT_TREE: + stop(); + break; + } +} + +void GDScriptLanguageServer::thread_main(void *p_userdata) { + GDScriptLanguageServer *self = static_cast<GDScriptLanguageServer *>(p_userdata); + while (!self->thread_exit) { + // Poll 20 times per second + self->protocol.poll(); + OS::get_singleton()->delay_usec(50000); + } +} + +void GDScriptLanguageServer::start() { + int port = (int)_EDITOR_GET("network/language_server/remote_port"); + if (protocol.start(port) == OK) { + EditorNode::get_log()->add_message("--- GDScript language server started ---", EditorLog::MSG_TYPE_EDITOR); + ERR_FAIL_COND(thread != NULL || thread_exit); + thread_exit = false; + thread = Thread::create(GDScriptLanguageServer::thread_main, this); + } +} + +void GDScriptLanguageServer::stop() { + ERR_FAIL_COND(NULL == thread || thread_exit); + thread_exit = true; + Thread::wait_to_finish(thread); + memdelete(thread); + thread = NULL; + protocol.stop(); + EditorNode::get_log()->add_message("--- GDScript language server stopped ---", EditorLog::MSG_TYPE_EDITOR); +} + +void register_lsp_types() { + ClassDB::register_class<GDScriptLanguageProtocol>(); + ClassDB::register_class<GDScriptTextDocument>(); + ClassDB::register_class<GDScriptWorkspace>(); +} diff --git a/modules/gdscript/language_server/gdscript_language_server.h b/modules/gdscript/language_server/gdscript_language_server.h new file mode 100644 index 0000000000..83c2320d98 --- /dev/null +++ b/modules/gdscript/language_server/gdscript_language_server.h @@ -0,0 +1,60 @@ +/*************************************************************************/ +/* gdscript_language_server.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 GDSCRIPT_LANGUAGE_SERVER_H +#define GDSCRIPT_LANGUAGE_SERVER_H + +#include "../gdscript_parser.h" +#include "editor/editor_plugin.h" +#include "gdscript_language_protocol.h" + +class GDScriptLanguageServer : public EditorPlugin { + GDCLASS(GDScriptLanguageServer, EditorPlugin); + + GDScriptLanguageProtocol protocol; + + Thread *thread; + bool thread_exit; + static void thread_main(void *p_userdata); + +private: + void _notification(int p_what); + void _iteration(); + +public: + Error parse_script_file(const String &p_path); + GDScriptLanguageServer(); + void start(); + void stop(); +}; + +void register_lsp_types(); + +#endif // GDSCRIPT_LANGUAGE_SERVER_H diff --git a/modules/gdscript/language_server/gdscript_text_document.cpp b/modules/gdscript/language_server/gdscript_text_document.cpp new file mode 100644 index 0000000000..1ca2a50c21 --- /dev/null +++ b/modules/gdscript/language_server/gdscript_text_document.cpp @@ -0,0 +1,423 @@ +/*************************************************************************/ +/* gdscript_text_document.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 "gdscript_text_document.h" +#include "../gdscript.h" +#include "core/os/os.h" +#include "editor/editor_settings.h" +#include "editor/plugins/script_text_editor.h" +#include "gdscript_extend_parser.h" +#include "gdscript_language_protocol.h" + +void GDScriptTextDocument::_bind_methods() { + ClassDB::bind_method(D_METHOD("didOpen"), &GDScriptTextDocument::didOpen); + ClassDB::bind_method(D_METHOD("didChange"), &GDScriptTextDocument::didChange); + ClassDB::bind_method(D_METHOD("nativeSymbol"), &GDScriptTextDocument::nativeSymbol); + ClassDB::bind_method(D_METHOD("documentSymbol"), &GDScriptTextDocument::documentSymbol); + ClassDB::bind_method(D_METHOD("completion"), &GDScriptTextDocument::completion); + ClassDB::bind_method(D_METHOD("resolve"), &GDScriptTextDocument::resolve); + ClassDB::bind_method(D_METHOD("foldingRange"), &GDScriptTextDocument::foldingRange); + ClassDB::bind_method(D_METHOD("codeLens"), &GDScriptTextDocument::codeLens); + ClassDB::bind_method(D_METHOD("documentLink"), &GDScriptTextDocument::documentLink); + ClassDB::bind_method(D_METHOD("colorPresentation"), &GDScriptTextDocument::colorPresentation); + ClassDB::bind_method(D_METHOD("hover"), &GDScriptTextDocument::hover); + ClassDB::bind_method(D_METHOD("definition"), &GDScriptTextDocument::definition); + ClassDB::bind_method(D_METHOD("show_native_symbol_in_editor"), &GDScriptTextDocument::show_native_symbol_in_editor); +} + +void GDScriptTextDocument::didOpen(const Variant &p_param) { + lsp::TextDocumentItem doc = load_document_item(p_param); + sync_script_content(doc.uri, doc.text); +} + +void GDScriptTextDocument::didChange(const Variant &p_param) { + lsp::TextDocumentItem doc = load_document_item(p_param); + Dictionary dict = p_param; + Array contentChanges = dict["contentChanges"]; + for (int i = 0; i < contentChanges.size(); ++i) { + lsp::TextDocumentContentChangeEvent evt; + evt.load(contentChanges[i]); + doc.text = evt.text; + } + sync_script_content(doc.uri, doc.text); +} + +lsp::TextDocumentItem GDScriptTextDocument::load_document_item(const Variant &p_param) { + lsp::TextDocumentItem doc; + Dictionary params = p_param; + doc.load(params["textDocument"]); + return doc; +} + +void GDScriptTextDocument::notify_client_show_symbol(const lsp::DocumentSymbol *symbol) { + ERR_FAIL_NULL(symbol); + GDScriptLanguageProtocol::get_singleton()->notify_client("gdscript/show_native_symbol", symbol->to_json(true)); +} + +void GDScriptTextDocument::initialize() { + + if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) { + + const HashMap<StringName, ClassMembers> &native_members = GDScriptLanguageProtocol::get_singleton()->get_workspace()->native_members; + + const StringName *class_ptr = native_members.next(NULL); + while (class_ptr) { + + const ClassMembers &members = native_members.get(*class_ptr); + + const String *name = members.next(NULL); + while (name) { + + const lsp::DocumentSymbol *symbol = members.get(*name); + lsp::CompletionItem item = symbol->make_completion_item(); + item.data = JOIN_SYMBOLS(String(*class_ptr), *name); + native_member_completions.push_back(item.to_json()); + + name = members.next(name); + } + + class_ptr = native_members.next(class_ptr); + } + } +} + +Variant GDScriptTextDocument::nativeSymbol(const Dictionary &p_params) { + + Variant ret; + + lsp::NativeSymbolInspectParams params; + params.load(p_params); + + if (const lsp::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_native_symbol(params)) { + ret = symbol->to_json(true); + notify_client_show_symbol(symbol); + } + + return ret; +} + +Array GDScriptTextDocument::documentSymbol(const Dictionary &p_params) { + Dictionary params = p_params["textDocument"]; + String uri = params["uri"]; + String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(uri); + Array arr; + if (const Map<String, ExtendGDScriptParser *>::Element *parser = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(path)) { + Vector<lsp::DocumentedSymbolInformation> list; + parser->get()->get_symbols().symbol_tree_as_list(uri, list); + for (int i = 0; i < list.size(); i++) { + arr.push_back(list[i].to_json()); + } + } + return arr; +} + +Array GDScriptTextDocument::completion(const Dictionary &p_params) { + + Array arr; + + lsp::CompletionParams params; + params.load(p_params); + Dictionary request_data = params.to_json(); + + List<ScriptCodeCompletionOption> options; + GDScriptLanguageProtocol::get_singleton()->get_workspace()->completion(params, &options); + + if (!options.empty()) { + + int i = 0; + arr.resize(options.size()); + + for (const List<ScriptCodeCompletionOption>::Element *E = options.front(); E; E = E->next()) { + + const ScriptCodeCompletionOption &option = E->get(); + lsp::CompletionItem item; + item.label = option.display; + item.data = request_data; + + switch (option.kind) { + case ScriptCodeCompletionOption::KIND_ENUM: + item.kind = lsp::CompletionItemKind::Enum; + break; + case ScriptCodeCompletionOption::KIND_CLASS: + item.kind = lsp::CompletionItemKind::Class; + break; + case ScriptCodeCompletionOption::KIND_MEMBER: + item.kind = lsp::CompletionItemKind::Property; + break; + case ScriptCodeCompletionOption::KIND_FUNCTION: + item.kind = lsp::CompletionItemKind::Method; + break; + case ScriptCodeCompletionOption::KIND_SIGNAL: + item.kind = lsp::CompletionItemKind::Event; + break; + case ScriptCodeCompletionOption::KIND_CONSTANT: + item.kind = lsp::CompletionItemKind::Constant; + break; + case ScriptCodeCompletionOption::KIND_VARIABLE: + item.kind = lsp::CompletionItemKind::Variable; + break; + case ScriptCodeCompletionOption::KIND_FILE_PATH: + item.kind = lsp::CompletionItemKind::File; + break; + case ScriptCodeCompletionOption::KIND_NODE_PATH: + item.kind = lsp::CompletionItemKind::Snippet; + break; + case ScriptCodeCompletionOption::KIND_PLAIN_TEXT: + item.kind = lsp::CompletionItemKind::Text; + break; + } + + arr[i] = item.to_json(); + i++; + } + } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) { + + arr = native_member_completions.duplicate(); + + for (Map<String, ExtendGDScriptParser *>::Element *E = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.front(); E; E = E->next()) { + + ExtendGDScriptParser *script = E->get(); + const Array &items = script->get_member_completions(); + + const int start_size = arr.size(); + arr.resize(start_size + items.size()); + for (int i = start_size; i < arr.size(); i++) { + arr[i] = items[i - start_size]; + } + } + } + return arr; +} + +Dictionary GDScriptTextDocument::resolve(const Dictionary &p_params) { + + lsp::CompletionItem item; + item.load(p_params); + + lsp::CompletionParams params; + Variant data = p_params["data"]; + + const lsp::DocumentSymbol *symbol = NULL; + + if (data.get_type() == Variant::DICTIONARY) { + + params.load(p_params["data"]); + symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params, item.label, item.kind == lsp::CompletionItemKind::Method || item.kind == lsp::CompletionItemKind::Function); + + } else if (data.get_type() == Variant::STRING) { + + String query = data; + + Vector<String> param_symbols = query.split(SYMBOL_SEPERATOR, false); + + if (param_symbols.size() >= 2) { + + String class_ = param_symbols[0]; + StringName class_name = class_; + String member_name = param_symbols[param_symbols.size() - 1]; + String inner_class_name; + if (param_symbols.size() >= 3) { + inner_class_name = param_symbols[1]; + } + + if (const ClassMembers *members = GDScriptLanguageProtocol::get_singleton()->get_workspace()->native_members.getptr(class_name)) { + if (const lsp::DocumentSymbol *const *member = members->getptr(member_name)) { + symbol = *member; + } + } + + if (!symbol) { + if (const Map<String, ExtendGDScriptParser *>::Element *E = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(class_name)) { + symbol = E->get()->get_member_symbol(member_name, inner_class_name); + } + } + } + } + + if (symbol) { + item.documentation = symbol->render(); + } + + if ((item.kind == lsp::CompletionItemKind::Method || item.kind == lsp::CompletionItemKind::Function) && !item.label.ends_with("):")) { + item.insertText = item.label + "("; + if (symbol && symbol->detail.find(",") == -1) { + item.insertText += ")"; + } + } else if (item.kind == lsp::CompletionItemKind::Event) { + if (params.context.triggerKind == lsp::CompletionTriggerKind::TriggerCharacter && (params.context.triggerCharacter == "(")) { + const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\""; + item.insertText = quote_style + item.label + quote_style; + } + } + + return item.to_json(true); +} + +Array GDScriptTextDocument::foldingRange(const Dictionary &p_params) { + Array arr; + return arr; +} + +Array GDScriptTextDocument::codeLens(const Dictionary &p_params) { + Array arr; + return arr; +} + +Array GDScriptTextDocument::documentLink(const Dictionary &p_params) { + Array ret; + + lsp::DocumentLinkParams params; + params.load(p_params); + + List<lsp::DocumentLink> links; + GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_document_links(params.textDocument.uri, links); + for (const List<lsp::DocumentLink>::Element *E = links.front(); E; E = E->next()) { + ret.push_back(E->get().to_json()); + } + return ret; +} + +Array GDScriptTextDocument::colorPresentation(const Dictionary &p_params) { + Array arr; + return arr; +} + +Variant GDScriptTextDocument::hover(const Dictionary &p_params) { + + lsp::TextDocumentPositionParams params; + params.load(p_params); + + const lsp::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params); + if (symbol) { + + lsp::Hover hover; + hover.contents = symbol->render(); + return hover.to_json(); + + } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) { + + Dictionary ret; + Array contents; + List<const lsp::DocumentSymbol *> list; + GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(params, list); + for (List<const lsp::DocumentSymbol *>::Element *E = list.front(); E; E = E->next()) { + if (const lsp::DocumentSymbol *s = E->get()) { + contents.push_back(s->render().value); + } + } + ret["contents"] = contents; + return ret; + } + + return Variant(); +} + +Array GDScriptTextDocument::definition(const Dictionary &p_params) { + Array arr; + + lsp::TextDocumentPositionParams params; + params.load(p_params); + + const lsp::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params); + if (symbol) { + lsp::Location location; + location.uri = symbol->uri; + location.range = symbol->range; + + const String &path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(symbol->uri); + if (file_checker->file_exists(path)) { + arr.push_back(location.to_json()); + } else if (!symbol->native_class.empty()) { + if (GDScriptLanguageProtocol::get_singleton()->is_goto_native_symbols_enabled()) { + String id; + switch (symbol->kind) { + case lsp::SymbolKind::Class: + id = "class_name:" + symbol->name; + break; + case lsp::SymbolKind::Constant: + id = "class_constant:" + symbol->native_class + ":" + symbol->name; + break; + case lsp::SymbolKind::Property: + case lsp::SymbolKind::Variable: + id = "class_property:" + symbol->native_class + ":" + symbol->name; + break; + case lsp::SymbolKind::Enum: + id = "class_enum:" + symbol->native_class + ":" + symbol->name; + break; + case lsp::SymbolKind::Method: + case lsp::SymbolKind::Function: + id = "class_method:" + symbol->native_class + ":" + symbol->name; + break; + default: + id = "class_global:" + symbol->native_class + ":" + symbol->name; + break; + } + call_deferred("show_native_symbol_in_editor", id); + } else { + notify_client_show_symbol(symbol); + } + } + } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) { + + List<const lsp::DocumentSymbol *> list; + GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(params, list); + for (List<const lsp::DocumentSymbol *>::Element *E = list.front(); E; E = E->next()) { + + if (const lsp::DocumentSymbol *s = E->get()) { + if (!s->uri.empty()) { + lsp::Location location; + location.uri = s->uri; + location.range = s->range; + arr.push_back(location.to_json()); + } + } + } + } + + return arr; +} + +GDScriptTextDocument::GDScriptTextDocument() { + file_checker = FileAccess::create(FileAccess::ACCESS_RESOURCES); +} + +GDScriptTextDocument::~GDScriptTextDocument() { + memdelete(file_checker); +} + +void GDScriptTextDocument::sync_script_content(const String &p_path, const String &p_content) { + String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(p_path); + GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_script(path, p_content); +} + +void GDScriptTextDocument::show_native_symbol_in_editor(const String &p_symbol_id) { + ScriptEditor::get_singleton()->call_deferred("_help_class_goto", p_symbol_id); + OS::get_singleton()->move_window_to_foreground(); +} diff --git a/modules/gdscript/language_server/gdscript_text_document.h b/modules/gdscript/language_server/gdscript_text_document.h new file mode 100644 index 0000000000..235e2c3f6e --- /dev/null +++ b/modules/gdscript/language_server/gdscript_text_document.h @@ -0,0 +1,75 @@ +/*************************************************************************/ +/* gdscript_text_document.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 GDSCRIPT_TEXT_DOCUMENT_H +#define GDSCRIPT_TEXT_DOCUMENT_H + +#include "core/os/file_access.h" +#include "core/reference.h" +#include "lsp.hpp" + +class GDScriptTextDocument : public Reference { + GDCLASS(GDScriptTextDocument, Reference) +protected: + static void _bind_methods(); + + FileAccess *file_checker; + + void didOpen(const Variant &p_param); + void didChange(const Variant &p_param); + + void sync_script_content(const String &p_path, const String &p_content); + void show_native_symbol_in_editor(const String &p_symbol_id); + + Array native_member_completions; + +private: + lsp::TextDocumentItem load_document_item(const Variant &p_param); + void notify_client_show_symbol(const lsp::DocumentSymbol *symbol); + +public: + Variant nativeSymbol(const Dictionary &p_params); + Array documentSymbol(const Dictionary &p_params); + Array completion(const Dictionary &p_params); + Dictionary resolve(const Dictionary &p_params); + Array foldingRange(const Dictionary &p_params); + Array codeLens(const Dictionary &p_params); + Array documentLink(const Dictionary &p_params); + Array colorPresentation(const Dictionary &p_params); + Variant hover(const Dictionary &p_params); + Array definition(const Dictionary &p_params); + + void initialize(); + + GDScriptTextDocument(); + virtual ~GDScriptTextDocument(); +}; + +#endif diff --git a/modules/gdscript/language_server/gdscript_workspace.cpp b/modules/gdscript/language_server/gdscript_workspace.cpp new file mode 100644 index 0000000000..f9a974bad3 --- /dev/null +++ b/modules/gdscript/language_server/gdscript_workspace.cpp @@ -0,0 +1,534 @@ +/*************************************************************************/ +/* gdscript_workspace.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 "gdscript_workspace.h" +#include "../gdscript.h" +#include "../gdscript_parser.h" +#include "core/project_settings.h" +#include "core/script_language.h" +#include "editor/editor_help.h" +#include "gdscript_language_protocol.h" + +void GDScriptWorkspace::_bind_methods() { + ClassDB::bind_method(D_METHOD("symbol"), &GDScriptWorkspace::symbol); + ClassDB::bind_method(D_METHOD("parse_script", "p_path", "p_content"), &GDScriptWorkspace::parse_script); + ClassDB::bind_method(D_METHOD("parse_local_script", "p_path"), &GDScriptWorkspace::parse_local_script); + ClassDB::bind_method(D_METHOD("get_file_path", "p_uri"), &GDScriptWorkspace::get_file_path); + ClassDB::bind_method(D_METHOD("get_file_uri", "p_path"), &GDScriptWorkspace::get_file_uri); + ClassDB::bind_method(D_METHOD("publish_diagnostics", "p_path"), &GDScriptWorkspace::publish_diagnostics); + ClassDB::bind_method(D_METHOD("generate_script_api", "p_path"), &GDScriptWorkspace::generate_script_api); +} + +void GDScriptWorkspace::remove_cache_parser(const String &p_path) { + Map<String, ExtendGDScriptParser *>::Element *parser = parse_results.find(p_path); + Map<String, ExtendGDScriptParser *>::Element *script = scripts.find(p_path); + if (parser && script) { + if (script->get() && script->get() == script->get()) { + memdelete(script->get()); + } else { + memdelete(script->get()); + memdelete(parser->get()); + } + parse_results.erase(p_path); + scripts.erase(p_path); + } else if (parser) { + memdelete(parser->get()); + parse_results.erase(p_path); + } else if (script) { + memdelete(script->get()); + scripts.erase(p_path); + } +} + +const lsp::DocumentSymbol *GDScriptWorkspace::get_native_symbol(const String &p_class, const String &p_member) const { + + StringName class_name = p_class; + StringName empty; + + while (class_name != empty) { + if (const Map<StringName, lsp::DocumentSymbol>::Element *E = native_symbols.find(class_name)) { + const lsp::DocumentSymbol &class_symbol = E->value(); + + if (p_member.empty()) { + return &class_symbol; + } else { + for (int i = 0; i < class_symbol.children.size(); i++) { + const lsp::DocumentSymbol &symbol = class_symbol.children[i]; + if (symbol.name == p_member) { + return &symbol; + } + } + } + } + class_name = ClassDB::get_parent_class(class_name); + } + + return NULL; +} + +const lsp::DocumentSymbol *GDScriptWorkspace::get_script_symbol(const String &p_path) const { + const Map<String, ExtendGDScriptParser *>::Element *S = scripts.find(p_path); + if (S) { + return &(S->get()->get_symbols()); + } + return NULL; +} + +void GDScriptWorkspace::reload_all_workspace_scripts() { + List<String> paths; + list_script_files("res://", paths); + for (List<String>::Element *E = paths.front(); E; E = E->next()) { + const String &path = E->get(); + Error err; + String content = FileAccess::get_file_as_string(path, &err); + ERR_CONTINUE(err != OK); + err = parse_script(path, content); + + if (err != OK) { + Map<String, ExtendGDScriptParser *>::Element *S = parse_results.find(path); + String err_msg = "Failed parse script " + path; + if (S) { + err_msg += "\n" + S->get()->get_error(); + } + ERR_CONTINUE_MSG(err != OK, err_msg); + } + } +} + +void GDScriptWorkspace::list_script_files(const String &p_root_dir, List<String> &r_files) { + Error err; + DirAccessRef dir = DirAccess::open(p_root_dir, &err); + if (OK == err) { + dir->list_dir_begin(); + String file_name = dir->get_next(); + while (file_name.length()) { + if (dir->current_is_dir() && file_name != "." && file_name != ".." && file_name != "./") { + list_script_files(p_root_dir.plus_file(file_name), r_files); + } else if (file_name.ends_with(".gd")) { + String script_file = p_root_dir.plus_file(file_name); + r_files.push_back(script_file); + } + file_name = dir->get_next(); + } + } +} + +ExtendGDScriptParser *GDScriptWorkspace::get_parse_successed_script(const String &p_path) { + const Map<String, ExtendGDScriptParser *>::Element *S = scripts.find(p_path); + if (!S) { + parse_local_script(p_path); + S = scripts.find(p_path); + } + if (S) { + return S->get(); + } + return NULL; +} + +ExtendGDScriptParser *GDScriptWorkspace::get_parse_result(const String &p_path) { + const Map<String, ExtendGDScriptParser *>::Element *S = parse_results.find(p_path); + if (!S) { + parse_local_script(p_path); + S = parse_results.find(p_path); + } + if (S) { + return S->get(); + } + return NULL; +} + +Array GDScriptWorkspace::symbol(const Dictionary &p_params) { + String query = p_params["query"]; + Array arr; + if (!query.empty()) { + for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) { + Vector<lsp::DocumentedSymbolInformation> script_symbols; + E->get()->get_symbols().symbol_tree_as_list(E->key(), script_symbols); + for (int i = 0; i < script_symbols.size(); ++i) { + if (query.is_subsequence_ofi(script_symbols[i].name)) { + arr.push_back(script_symbols[i].to_json()); + } + } + } + } + return arr; +} + +Error GDScriptWorkspace::initialize() { + if (initialized) return OK; + + DocData *doc = EditorHelp::get_doc_data(); + for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) { + + const DocData::ClassDoc &class_data = E->value(); + lsp::DocumentSymbol class_symbol; + String class_name = E->key(); + class_symbol.name = class_name; + class_symbol.native_class = class_name; + class_symbol.kind = lsp::SymbolKind::Class; + class_symbol.detail = String("<Native> class ") + class_name; + if (!class_data.inherits.empty()) { + class_symbol.detail += " extends " + class_data.inherits; + } + class_symbol.documentation = class_data.brief_description + "\n" + class_data.description; + + for (int i = 0; i < class_data.constants.size(); i++) { + const DocData::ConstantDoc &const_data = class_data.constants[i]; + lsp::DocumentSymbol symbol; + symbol.name = const_data.name; + symbol.native_class = class_name; + symbol.kind = lsp::SymbolKind::Constant; + symbol.detail = "const " + class_name + "." + const_data.name; + if (const_data.enumeration.length()) { + symbol.detail += ": " + const_data.enumeration; + } + symbol.detail += " = " + const_data.value; + symbol.documentation = const_data.description; + class_symbol.children.push_back(symbol); + } + + Vector<DocData::PropertyDoc> properties; + properties.append_array(class_data.properties); + const int theme_prop_start_idx = properties.size(); + properties.append_array(class_data.theme_properties); + + for (int i = 0; i < class_data.properties.size(); i++) { + const DocData::PropertyDoc &data = class_data.properties[i]; + lsp::DocumentSymbol symbol; + symbol.name = data.name; + symbol.native_class = class_name; + symbol.kind = lsp::SymbolKind::Property; + symbol.detail = String(i >= theme_prop_start_idx ? "<Theme> var" : "var") + " " + class_name + "." + data.name; + if (data.enumeration.length()) { + symbol.detail += ": " + data.enumeration; + } else { + symbol.detail += ": " + data.type; + } + symbol.documentation = data.description; + class_symbol.children.push_back(symbol); + } + + Vector<DocData::MethodDoc> methods_signals; + methods_signals.append_array(class_data.methods); + const int signal_start_idx = methods_signals.size(); + methods_signals.append_array(class_data.signals); + + for (int i = 0; i < methods_signals.size(); i++) { + const DocData::MethodDoc &data = methods_signals[i]; + + lsp::DocumentSymbol symbol; + symbol.name = data.name; + symbol.native_class = class_name; + symbol.kind = i >= signal_start_idx ? lsp::SymbolKind::Event : lsp::SymbolKind::Method; + + String params = ""; + bool arg_default_value_started = false; + for (int j = 0; j < data.arguments.size(); j++) { + const DocData::ArgumentDoc &arg = data.arguments[j]; + if (!arg_default_value_started && !arg.default_value.empty()) { + arg_default_value_started = true; + } + String arg_str = arg.name + ": " + arg.type; + if (arg_default_value_started) { + arg_str += " = " + arg.default_value; + } + if (j < data.arguments.size() - 1) { + arg_str += ", "; + } + params += arg_str; + } + if (data.qualifiers.find("vararg") != -1) { + params += params.empty() ? "..." : ", ..."; + } + + String return_type = data.return_type; + if (return_type.empty()) { + return_type = "void"; + } + symbol.detail = "func " + class_name + "." + data.name + "(" + params + ") -> " + return_type; + symbol.documentation = data.description; + class_symbol.children.push_back(symbol); + } + + native_symbols.insert(class_name, class_symbol); + } + + reload_all_workspace_scripts(); + + if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) { + for (Map<StringName, lsp::DocumentSymbol>::Element *E = native_symbols.front(); E; E = E->next()) { + ClassMembers members; + const lsp::DocumentSymbol &class_symbol = E->get(); + for (int i = 0; i < class_symbol.children.size(); i++) { + const lsp::DocumentSymbol &symbol = class_symbol.children[i]; + members.set(symbol.name, &symbol); + } + native_members.set(E->key(), members); + } + + // cache member completions + for (Map<String, ExtendGDScriptParser *>::Element *S = scripts.front(); S; S = S->next()) { + S->get()->get_member_completions(); + } + } + + return OK; +} + +Error GDScriptWorkspace::parse_script(const String &p_path, const String &p_content) { + + ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser); + Error err = parser->parse(p_content, p_path); + Map<String, ExtendGDScriptParser *>::Element *last_parser = parse_results.find(p_path); + Map<String, ExtendGDScriptParser *>::Element *last_script = scripts.find(p_path); + + if (err == OK) { + + remove_cache_parser(p_path); + parse_results[p_path] = parser; + scripts[p_path] = parser; + + } else { + if (last_parser && last_script && last_parser->get() != last_script->get()) { + memdelete(last_parser->get()); + } + parse_results[p_path] = parser; + } + + publish_diagnostics(p_path); + + return err; +} + +Error GDScriptWorkspace::parse_local_script(const String &p_path) { + Error err; + String content = FileAccess::get_file_as_string(p_path, &err); + if (err == OK) { + err = parse_script(p_path, content); + } + return err; +} + +String GDScriptWorkspace::get_file_path(const String &p_uri) const { + String path = p_uri; + path = path.replace(root_uri + "/", "res://"); + path = path.http_unescape(); + return path; +} + +String GDScriptWorkspace::get_file_uri(const String &p_path) const { + String uri = p_path; + uri = uri.replace("res://", root_uri + "/"); + return uri; +} + +void GDScriptWorkspace::publish_diagnostics(const String &p_path) { + Dictionary params; + Array errors; + const Map<String, ExtendGDScriptParser *>::Element *ele = parse_results.find(p_path); + if (ele) { + const Vector<lsp::Diagnostic> &list = ele->get()->get_diagnostics(); + errors.resize(list.size()); + for (int i = 0; i < list.size(); ++i) { + errors[i] = list[i].to_json(); + } + } + params["diagnostics"] = errors; + params["uri"] = get_file_uri(p_path); + GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params); +} + +void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<ScriptCodeCompletionOption> *r_options) { + + String path = get_file_path(p_params.textDocument.uri); + String call_hint; + bool forced = false; + + if (const ExtendGDScriptParser *parser = get_parse_result(path)) { + String code = parser->get_text_for_completion(p_params.position); + GDScriptLanguage::get_singleton()->complete_code(code, path, NULL, r_options, forced, call_hint); + } +} + +const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_requred) { + + const lsp::DocumentSymbol *symbol = NULL; + + String path = get_file_path(p_doc_pos.textDocument.uri); + if (const ExtendGDScriptParser *parser = get_parse_result(path)) { + + String symbol_identifier = p_symbol_name; + Vector<String> identifier_parts = symbol_identifier.split("("); + if (identifier_parts.size()) { + symbol_identifier = identifier_parts[0]; + } + + lsp::Position pos = p_doc_pos.position; + if (symbol_identifier.empty()) { + Vector2i offset; + symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, offset); + pos.character += offset.y; + } + + if (!symbol_identifier.empty()) { + + if (ScriptServer::is_global_class(symbol_identifier)) { + + String class_path = ScriptServer::get_global_class_path(symbol_identifier); + symbol = get_script_symbol(class_path); + + } else { + + ScriptLanguage::LookupResult ret; + if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_requred), symbol_identifier, path, NULL, ret)) { + + if (ret.type == ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION) { + + String target_script_path = path; + if (!ret.script.is_null()) { + target_script_path = ret.script->get_path(); + } + + if (const ExtendGDScriptParser *target_parser = get_parse_result(target_script_path)) { + symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location)); + } + + } else { + + String member = ret.class_member; + if (member.empty() && symbol_identifier != ret.class_name) { + member = symbol_identifier; + } + symbol = get_native_symbol(ret.class_name, member); + } + } else { + symbol = parser->get_member_symbol(symbol_identifier); + } + } + } + } + + return symbol; +} + +void GDScriptWorkspace::resolve_related_symbols(const lsp::TextDocumentPositionParams &p_doc_pos, List<const lsp::DocumentSymbol *> &r_list) { + + String path = get_file_path(p_doc_pos.textDocument.uri); + if (const ExtendGDScriptParser *parser = get_parse_result(path)) { + + String symbol_identifier; + Vector2i offset; + symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, offset); + + const StringName *class_ptr = native_members.next(NULL); + while (class_ptr) { + const ClassMembers &members = native_members.get(*class_ptr); + if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) { + r_list.push_back(*symbol); + } + class_ptr = native_members.next(class_ptr); + } + + for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) { + const ExtendGDScriptParser *script = E->get(); + const ClassMembers &members = script->get_members(); + if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) { + r_list.push_back(*symbol); + } + + const HashMap<String, ClassMembers> &inner_classes = script->get_inner_classes(); + const String *_class = inner_classes.next(NULL); + while (_class) { + + const ClassMembers *inner_class = inner_classes.getptr(*_class); + if (const lsp::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) { + r_list.push_back(*symbol); + } + + _class = inner_classes.next(_class); + } + } + } +} + +const lsp::DocumentSymbol *GDScriptWorkspace::resolve_native_symbol(const lsp::NativeSymbolInspectParams &p_params) { + + if (Map<StringName, lsp::DocumentSymbol>::Element *E = native_symbols.find(p_params.native_class)) { + const lsp::DocumentSymbol &symbol = E->get(); + if (p_params.symbol_name.empty() || p_params.symbol_name == symbol.name) { + return &symbol; + } + + for (int i = 0; i < symbol.children.size(); ++i) { + if (symbol.children[i].name == p_params.symbol_name) { + return &(symbol.children[i]); + } + } + } + + return NULL; +} + +void GDScriptWorkspace::resolve_document_links(const String &p_uri, List<lsp::DocumentLink> &r_list) { + if (const ExtendGDScriptParser *parser = get_parse_successed_script(get_file_path(p_uri))) { + const List<lsp::DocumentLink> &links = parser->get_document_links(); + for (const List<lsp::DocumentLink>::Element *E = links.front(); E; E = E->next()) { + r_list.push_back(E->get()); + } + } +} + +Dictionary GDScriptWorkspace::generate_script_api(const String &p_path) { + Dictionary api; + if (const ExtendGDScriptParser *parser = get_parse_successed_script(p_path)) { + api = parser->generate_api(); + } + return api; +} + +GDScriptWorkspace::GDScriptWorkspace() { + ProjectSettings::get_singleton()->get_resource_path(); +} + +GDScriptWorkspace::~GDScriptWorkspace() { + Set<String> cached_parsers; + + for (Map<String, ExtendGDScriptParser *>::Element *E = parse_results.front(); E; E = E->next()) { + cached_parsers.insert(E->key()); + } + + for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) { + cached_parsers.insert(E->key()); + } + + for (Set<String>::Element *E = cached_parsers.front(); E; E = E->next()) { + remove_cache_parser(E->get()); + } +} diff --git a/modules/mono/editor/godotsharp_editor.h b/modules/gdscript/language_server/gdscript_workspace.h index cf0d2aec84..a416ae1075 100644 --- a/modules/mono/editor/godotsharp_editor.h +++ b/modules/gdscript/language_server/gdscript_workspace.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* godotsharp_editor.h */ +/* gdscript_workspace.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,107 +28,64 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GODOTSHARP_EDITOR_H -#define GODOTSHARP_EDITOR_H +#ifndef GDSCRIPT_WORKSPACE_H +#define GDSCRIPT_WORKSPACE_H -#include "godotsharp_builds.h" -#include "monodevelop_instance.h" +#include "../gdscript_parser.h" +#include "core/variant.h" +#include "gdscript_extend_parser.h" +#include "lsp.hpp" -class GodotSharpEditor : public Node { - GDCLASS(GodotSharpEditor, Object) - - EditorNode *editor; - - MenuButton *menu_button; - PopupMenu *menu_popup; - - AcceptDialog *error_dialog; - AcceptDialog *about_dialog; - CheckBox *about_dialog_checkbox; - - ToolButton *bottom_panel_btn; - - GodotSharpBuilds *godotsharp_builds; - - MonoDevelopInstance *monodevelop_instance; -#ifdef OSX_ENABLED - MonoDevelopInstance *visualstudio_mac_instance; -#endif - - bool _create_project_solution(); - void _make_api_solutions_if_needed(); - void _make_api_solutions_if_needed_impl(); - - void _remove_create_sln_menu_option(); - void _show_about_dialog(); - void _toggle_about_dialog_on_start(bool p_enabled); - - void _menu_option_pressed(int p_id); - - void _build_solution_pressed(); - - static GodotSharpEditor *singleton; +class GDScriptWorkspace : public Reference { + GDCLASS(GDScriptWorkspace, Reference); protected: - void _notification(int p_notification); static void _bind_methods(); + void remove_cache_parser(const String &p_path); + bool initialized = false; + Map<StringName, lsp::DocumentSymbol> native_symbols; -public: - enum MenuOptions { - MENU_CREATE_SLN, - MENU_ABOUT_CSHARP, - }; - - enum ExternalEditor { - EDITOR_NONE, -#ifdef WINDOWS_ENABLED - //EDITOR_VISUALSTUDIO, // TODO - EDITOR_MONODEVELOP, - EDITOR_VSCODE -#elif OSX_ENABLED - EDITOR_VISUALSTUDIO_MAC, - EDITOR_MONODEVELOP, - EDITOR_VSCODE -#elif UNIX_ENABLED - EDITOR_MONODEVELOP, - EDITOR_VSCODE -#endif - }; - - _FORCE_INLINE_ static GodotSharpEditor *get_singleton() { return singleton; } + const lsp::DocumentSymbol *get_native_symbol(const String &p_class, const String &p_member = "") const; + const lsp::DocumentSymbol *get_script_symbol(const String &p_path) const; - static void register_internal_calls(); + void reload_all_workspace_scripts(); - void show_error_dialog(const String &p_message, const String &p_title = "Error"); + ExtendGDScriptParser *get_parse_successed_script(const String &p_path); + ExtendGDScriptParser *get_parse_result(const String &p_path); - Error open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col); - bool overrides_external_editor(); + void list_script_files(const String &p_root_dir, List<String> &r_files); - GodotSharpEditor(EditorNode *p_editor); - ~GodotSharpEditor(); -}; - -class MonoReloadNode : public Node { - GDCLASS(MonoReloadNode, Node) +public: + String root; + String root_uri; - Timer *reload_timer; + Map<String, ExtendGDScriptParser *> scripts; + Map<String, ExtendGDScriptParser *> parse_results; + HashMap<StringName, ClassMembers> native_members; - void _reload_timer_timeout(); +public: + Array symbol(const Dictionary &p_params); - static MonoReloadNode *singleton; +public: + Error initialize(); -protected: - static void _bind_methods(); + Error parse_script(const String &p_path, const String &p_content); + Error parse_local_script(const String &p_path); - void _notification(int p_what); + String get_file_path(const String &p_uri) const; + String get_file_uri(const String &p_path) const; -public: - _FORCE_INLINE_ static MonoReloadNode *get_singleton() { return singleton; } + void publish_diagnostics(const String &p_path); + void completion(const lsp::CompletionParams &p_params, List<ScriptCodeCompletionOption> *r_options); - void restart_reload_timer(); + const lsp::DocumentSymbol *resolve_symbol(const lsp::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name = "", bool p_func_requred = false); + void resolve_related_symbols(const lsp::TextDocumentPositionParams &p_doc_pos, List<const lsp::DocumentSymbol *> &r_list); + const lsp::DocumentSymbol *resolve_native_symbol(const lsp::NativeSymbolInspectParams &p_params); + void resolve_document_links(const String &p_uri, List<lsp::DocumentLink> &r_list); + Dictionary generate_script_api(const String &p_path); - MonoReloadNode(); - ~MonoReloadNode(); + GDScriptWorkspace(); + ~GDScriptWorkspace(); }; -#endif // GODOTSHARP_EDITOR_H +#endif diff --git a/modules/gdscript/language_server/lsp.hpp b/modules/gdscript/language_server/lsp.hpp new file mode 100644 index 0000000000..35471d63d6 --- /dev/null +++ b/modules/gdscript/language_server/lsp.hpp @@ -0,0 +1,1662 @@ +/*************************************************************************/ +/* lsp.hpp */ +/*************************************************************************/ +/* 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 GODOT_LSP_H +#define GODOT_LSP_H + +#include "core/class_db.h" +#include "core/list.h" +#include "editor/doc/doc_data.h" + +namespace lsp { + +typedef String DocumentUri; + +/** Format BBCode documentation from DocData to markdown */ +static String marked_documentation(const String &p_bbcode); + +/** + * Text documents are identified using a URI. On the protocol level, URIs are passed as strings. + */ +struct TextDocumentIdentifier { + /** + * The text document's URI. + */ + DocumentUri uri; + + _FORCE_INLINE_ void load(const Dictionary &p_params) { + uri = p_params["uri"]; + } + + _FORCE_INLINE_ Dictionary to_json() const { + Dictionary dict; + dict["uri"] = uri; + return dict; + } +}; + +/** + * Position in a text document expressed as zero-based line and zero-based character offset. + * A position is between two characters like an ‘insert’ cursor in a editor. + * Special values like for example -1 to denote the end of a line are not supported. + */ +struct Position { + /** + * Line position in a document (zero-based). + */ + int line = 0; + + /** + * Character offset on a line in a document (zero-based). Assuming that the line is + * represented as a string, the `character` value represents the gap between the + * `character` and `character + 1`. + * + * If the character value is greater than the line length it defaults back to the + * line length. + */ + int character = 0; + + _FORCE_INLINE_ void load(const Dictionary &p_params) { + line = p_params["line"]; + character = p_params["character"]; + } + + _FORCE_INLINE_ Dictionary to_json() const { + Dictionary dict; + dict["line"] = line; + dict["character"] = character; + return dict; + } +}; + +/** + * A range in a text document expressed as (zero-based) start and end positions. + * A range is comparable to a selection in an editor. Therefore the end position is exclusive. + * If you want to specify a range that contains a line including the line ending character(s) then use an end position denoting the start of the next line. + */ +struct Range { + /** + * The range's start position. + */ + Position start; + + /** + * The range's end position. + */ + Position end; + + _FORCE_INLINE_ void load(const Dictionary &p_params) { + start.load(p_params["start"]); + end.load(p_params["end"]); + } + + _FORCE_INLINE_ Dictionary to_json() const { + Dictionary dict; + dict["start"] = start.to_json(); + dict["end"] = end.to_json(); + return dict; + } +}; + +/** + * Represents a location inside a resource, such as a line inside a text file. + */ +struct Location { + DocumentUri uri; + Range range; + + _FORCE_INLINE_ void load(const Dictionary &p_params) { + uri = p_params["uri"]; + range.load(p_params["range"]); + } + + _FORCE_INLINE_ Dictionary to_json() const { + Dictionary dict; + dict["uri"] = uri; + dict["range"] = range.to_json(); + return dict; + } +}; + +/** + * Represents a link between a source and a target location. + */ +struct LocationLink { + + /** + * Span of the origin of this link. + * + * Used as the underlined span for mouse interaction. Defaults to the word range at + * the mouse position. + */ + Range *originSelectionRange = NULL; + + /** + * The target resource identifier of this link. + */ + String targetUri; + + /** + * The full target range of this link. If the target for example is a symbol then target range is the + * range enclosing this symbol not including leading/trailing whitespace but everything else + * like comments. This information is typically used to highlight the range in the editor. + */ + Range targetRange; + + /** + * The range that should be selected and revealed when this link is being followed, e.g the name of a function. + * Must be contained by the the `targetRange`. See also `DocumentSymbol#range` + */ + Range targetSelectionRange; +}; + +/** + * A parameter literal used in requests to pass a text document and a position inside that document. + */ +struct TextDocumentPositionParams { + /** + * The text document. + */ + TextDocumentIdentifier textDocument; + + /** + * The position inside the text document. + */ + Position position; + + _FORCE_INLINE_ void load(const Dictionary &p_params) { + textDocument.load(p_params["textDocument"]); + position.load(p_params["position"]); + } + + _FORCE_INLINE_ Dictionary to_json() const { + Dictionary dict; + dict["textDocument"] = textDocument.to_json(); + dict["position"] = position.to_json(); + return dict; + } +}; + +struct DocumentLinkParams { + /** + * The document to provide document links for. + */ + TextDocumentIdentifier textDocument; + + _FORCE_INLINE_ void load(const Dictionary &p_params) { + textDocument.load(p_params["textDocument"]); + } +}; + +/** + * A document link is a range in a text document that links to an internal or external resource, like another + * text document or a web site. + */ +struct DocumentLink { + + /** + * The range this link applies to. + */ + Range range; + + /** + * The uri this link points to. If missing a resolve request is sent later. + */ + DocumentUri target; + + Dictionary to_json() const { + Dictionary dict; + dict["range"] = range.to_json(); + dict["target"] = target; + return dict; + } +}; + +/** + * A textual edit applicable to a text document. + */ +struct TextEdit { + /** + * The range of the text document to be manipulated. To insert + * text into a document create a range where start === end. + */ + Range range; + + /** + * The string to be inserted. For delete operations use an + * empty string. + */ + String newText; +}; + +/** + * Represents a reference to a command. + * Provides a title which will be used to represent a command in the UI. + * Commands are identified by a string identifier. + * The recommended way to handle commands is to implement their execution on the server side if the client and server provides the corresponding capabilities. + * Alternatively the tool extension code could handle the command. The protocol currently doesn’t specify a set of well-known commands. + */ +struct Command { + /** + * Title of the command, like `save`. + */ + String title; + /** + * The identifier of the actual command handler. + */ + String command; + /** + * Arguments that the command handler should be + * invoked with. + */ + Array arguments; + + Dictionary to_json() const { + Dictionary dict; + dict["title"] = title; + dict["command"] = command; + if (arguments.size()) dict["arguments"] = arguments; + return dict; + } +}; + +// Use namespace instead of enumeration to follow the LSP specifications +// lsp::EnumName::EnumValue is OK but lsp::EnumValue is not + +namespace TextDocumentSyncKind { +/** + * Documents should not be synced at all. + */ +static const int None = 0; + +/** + * Documents are synced by always sending the full content + * of the document. + */ +static const int Full = 1; + +/** + * Documents are synced by sending the full content on open. + * After that only incremental updates to the document are + * send. + */ +static const int Incremental = 2; +}; // namespace TextDocumentSyncKind + +/** + * Completion options. + */ +struct CompletionOptions { + /** + * The server provides support to resolve additional + * information for a completion item. + */ + bool resolveProvider = true; + + /** + * The characters that trigger completion automatically. + */ + Vector<String> triggerCharacters; + + CompletionOptions() { + triggerCharacters.push_back("."); + triggerCharacters.push_back("$"); + triggerCharacters.push_back("'"); + triggerCharacters.push_back("\""); + triggerCharacters.push_back("("); + triggerCharacters.push_back(","); + } + + Dictionary to_json() const { + Dictionary dict; + dict["resolveProvider"] = resolveProvider; + dict["triggerCharacters"] = triggerCharacters; + return dict; + } +}; + +/** + * Signature help options. + */ +struct SignatureHelpOptions { + /** + * The characters that trigger signature help + * automatically. + */ + Vector<String> triggerCharacters; + + Dictionary to_json() { + Dictionary dict; + dict["triggerCharacters"] = triggerCharacters; + return dict; + } +}; + +/** + * Code Lens options. + */ +struct CodeLensOptions { + /** + * Code lens has a resolve provider as well. + */ + bool resolveProvider = false; + + Dictionary to_json() { + Dictionary dict; + dict["resolveProvider"] = resolveProvider; + return dict; + } +}; + +/** + * Rename options + */ +struct RenameOptions { + /** + * Renames should be checked and tested before being executed. + */ + bool prepareProvider = false; + + Dictionary to_json() { + Dictionary dict; + dict["prepareProvider"] = prepareProvider; + return dict; + } +}; + +/** + * Document link options. + */ +struct DocumentLinkOptions { + /** + * Document links have a resolve provider as well. + */ + bool resolveProvider = false; + + Dictionary to_json() { + Dictionary dict; + dict["resolveProvider"] = resolveProvider; + return dict; + } +}; + +/** + * Execute command options. + */ +struct ExecuteCommandOptions { + /** + * The commands to be executed on the server + */ + Vector<String> commands; + + Dictionary to_json() { + Dictionary dict; + dict["commands"] = commands; + return dict; + } +}; + +/** + * Save options. + */ +struct SaveOptions { + /** + * The client is supposed to include the content on save. + */ + bool includeText = true; + + Dictionary to_json() { + Dictionary dict; + dict["includeText"] = includeText; + return dict; + } +}; + +/** + * Color provider options. + */ +struct ColorProviderOptions { + Dictionary to_json() { + Dictionary dict; + return dict; + } +}; + +/** + * Folding range provider options. + */ +struct FoldingRangeProviderOptions { + Dictionary to_json() { + Dictionary dict; + return dict; + } +}; + +struct TextDocumentSyncOptions { + /** + * Open and close notifications are sent to the server. If omitted open close notification should not + * be sent. + */ + bool openClose = true; + + /** + * Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full + * and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None. + */ + int change = TextDocumentSyncKind::Full; + + /** + * If present will save notifications are sent to the server. If omitted the notification should not be + * sent. + */ + bool willSave = false; + + /** + * If present will save wait until requests are sent to the server. If omitted the request should not be + * sent. + */ + bool willSaveWaitUntil = false; + + /** + * If present save notifications are sent to the server. If omitted the notification should not be + * sent. + */ + SaveOptions save; + + Dictionary to_json() { + Dictionary dict; + dict["willSaveWaitUntil"] = willSaveWaitUntil; + dict["willSave"] = willSave; + dict["openClose"] = openClose; + dict["change"] = change; + dict["save"] = save.to_json(); + return dict; + } +}; + +/** + * Static registration options to be returned in the initialize request. + */ +struct StaticRegistrationOptions { + /** + * The id used to register the request. The id can be used to deregister + * the request again. See also Registration#id. + */ + String id; +}; + +/** + * Format document on type options. + */ +struct DocumentOnTypeFormattingOptions { + /** + * A character on which formatting should be triggered, like `}`. + */ + String firstTriggerCharacter; + + /** + * More trigger characters. + */ + Vector<String> moreTriggerCharacter; + + Dictionary to_json() { + Dictionary dict; + dict["firstTriggerCharacter"] = firstTriggerCharacter; + dict["moreTriggerCharacter"] = moreTriggerCharacter; + return dict; + } +}; + +struct TextDocumentItem { + /** + * The text document's URI. + */ + DocumentUri uri; + + /** + * The text document's language identifier. + */ + String languageId; + + /** + * The version number of this document (it will increase after each + * change, including undo/redo). + */ + int version; + + /** + * The content of the opened text document. + */ + String text; + + void load(const Dictionary &p_dict) { + uri = p_dict["uri"]; + languageId = p_dict["languageId"]; + version = p_dict["version"]; + text = p_dict["text"]; + } + + Dictionary to_json() const { + Dictionary dict; + dict["uri"] = uri; + dict["languageId"] = languageId; + dict["version"] = version; + dict["text"] = text; + return dict; + } +}; + +/** + * An event describing a change to a text document. If range and rangeLength are omitted + * the new text is considered to be the full content of the document. + */ +struct TextDocumentContentChangeEvent { + /** + * The range of the document that changed. + */ + Range range; + + /** + * The length of the range that got replaced. + */ + int rangeLength; + + /** + * The new text of the range/document. + */ + String text; + + void load(const Dictionary &p_params) { + text = p_params["text"]; + rangeLength = p_params["rangeLength"]; + range.load(p_params["range"]); + } +}; + +// Use namespace instead of enumeration to follow the LSP specifications +namespace DiagnosticSeverity { +/** + * Reports an error. + */ +static const int Error = 1; +/** + * Reports a warning. + */ +static const int Warning = 2; +/** + * Reports an information. + */ +static const int Information = 3; +/** + * Reports a hint. + */ +static const int Hint = 4; +}; // namespace DiagnosticSeverity + +/** + * Represents a related message and source code location for a diagnostic. This should be + * used to point to code locations that cause or related to a diagnostics, e.g when duplicating + * a symbol in a scope. + */ +struct DiagnosticRelatedInformation { + /** + * The location of this related diagnostic information. + */ + Location location; + + /** + * The message of this related diagnostic information. + */ + String message; + + Dictionary to_json() const { + Dictionary dict; + dict["location"] = location.to_json(), + dict["message"] = message; + return dict; + } +}; + +/** + * Represents a diagnostic, such as a compiler error or warning. + * Diagnostic objects are only valid in the scope of a resource. + */ +struct Diagnostic { + /** + * The range at which the message applies. + */ + Range range; + + /** + * The diagnostic's severity. Can be omitted. If omitted it is up to the + * client to interpret diagnostics as error, warning, info or hint. + */ + int severity; + + /** + * The diagnostic's code, which might appear in the user interface. + */ + int code; + + /** + * A human-readable string describing the source of this + * diagnostic, e.g. 'typescript' or 'super lint'. + */ + String source; + + /** + * The diagnostic's message. + */ + String message; + + /** + * An array of related diagnostic information, e.g. when symbol-names within + * a scope collide all definitions can be marked via this property. + */ + Vector<DiagnosticRelatedInformation> relatedInformation; + + Dictionary to_json() const { + Dictionary dict; + dict["range"] = range.to_json(); + dict["code"] = code; + dict["severity"] = severity; + dict["message"] = message; + dict["source"] = source; + if (!relatedInformation.empty()) { + Array arr; + arr.resize(relatedInformation.size()); + for (int i = 0; i < relatedInformation.size(); i++) { + arr[i] = relatedInformation[i].to_json(); + } + dict["relatedInformation"] = arr; + } + return dict; + } +}; + +// Use namespace instead of enumeration to follow the LSP specifications +/** + * Describes the content type that a client supports in various + * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. + * + * Please note that `MarkupKinds` must not start with a `$`. This kinds + * are reserved for internal usage. + */ +namespace MarkupKind { +static const String PlainText = "plaintext"; +static const String Markdown = "markdown"; +}; // namespace MarkupKind + +/** + * A `MarkupContent` literal represents a string value which content is interpreted base on its + * kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. + * + * If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. + * See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting + * + * Here is an example how such a string can be constructed using JavaScript / TypeScript: + * ```typescript + * let markdown: MarkdownContent = { + * kind: MarkupKind.Markdown, + * value: [ + * '# Header', + * 'Some text', + * '```typescript', + * 'someCode();', + * '```' + * ].join('\n') + * }; + * ``` + * + * *Please Note* that clients might sanitize the return markdown. A client could decide to + * remove HTML from the markdown to avoid script execution. + */ +struct MarkupContent { + /** + * The type of the Markup + */ + String kind; + + /** + * The content itself + */ + String value; + + MarkupContent() { + kind = MarkupKind::Markdown; + } + + MarkupContent(const String &p_value) { + value = p_value; + kind = MarkupKind::Markdown; + } + + Dictionary to_json() const { + Dictionary dict; + dict["kind"] = kind; + dict["value"] = value; + return dict; + } +}; + +// Use namespace instead of enumeration to follow the LSP specifications +// lsp::EnumName::EnumValue is OK but lsp::EnumValue is not +// And here C++ compilers are unhappy with our enumeration name like Color, File, Reference etc. +/** + * The kind of a completion entry. + */ +namespace CompletionItemKind { +static const int Text = 1; +static const int Method = 2; +static const int Function = 3; +static const int Constructor = 4; +static const int Field = 5; +static const int Variable = 6; +static const int Class = 7; +static const int Interface = 8; +static const int Module = 9; +static const int Property = 10; +static const int Unit = 11; +static const int Value = 12; +static const int Enum = 13; +static const int Keyword = 14; +static const int Snippet = 15; +static const int Color = 16; +static const int File = 17; +static const int Reference = 18; +static const int Folder = 19; +static const int EnumMember = 20; +static const int Constant = 21; +static const int Struct = 22; +static const int Event = 23; +static const int Operator = 24; +static const int TypeParameter = 25; +}; // namespace CompletionItemKind + +// Use namespace instead of enumeration to follow the LSP specifications +/** + * Defines whether the insert text in a completion item should be interpreted as + * plain text or a snippet. + */ +namespace InsertTextFormat { +/** + * The primary text to be inserted is treated as a plain string. + */ +static const int PlainText = 1; + +/** + * The primary text to be inserted is treated as a snippet. + * + * A snippet can define tab stops and placeholders with `$1`, `$2` + * and `${3:foo}`. `$0` defines the final tab stop, it defaults to + * the end of the snippet. Placeholders with equal identifiers are linked, + * that is typing in one will update others too. + */ +static const int Snippet = 2; +}; // namespace InsertTextFormat + +struct CompletionItem { + /** + * The label of this completion item. By default + * also the text that is inserted when selecting + * this completion. + */ + String label; + + /** + * The kind of this completion item. Based of the kind + * an icon is chosen by the editor. The standardized set + * of available values is defined in `CompletionItemKind`. + */ + int kind; + + /** + * A human-readable string with additional information + * about this item, like type or symbol information. + */ + String detail; + + /** + * A human-readable string that represents a doc-comment. + */ + MarkupContent documentation; + + /** + * Indicates if this item is deprecated. + */ + bool deprecated = false; + + /** + * Select this item when showing. + * + * *Note* that only one completion item can be selected and that the + * tool / client decides which item that is. The rule is that the *first* + * item of those that match best is selected. + */ + bool preselect = false; + + /** + * A string that should be used when comparing this item + * with other items. When `falsy` the label is used. + */ + String sortText; + + /** + * A string that should be used when filtering a set of + * completion items. When `falsy` the label is used. + */ + String filterText; + + /** + * A string that should be inserted into a document when selecting + * this completion. When `falsy` the label is used. + * + * The `insertText` is subject to interpretation by the client side. + * Some tools might not take the string literally. For example + * VS Code when code complete is requested in this example `con<cursor position>` + * and a completion item with an `insertText` of `console` is provided it + * will only insert `sole`. Therefore it is recommended to use `textEdit` instead + * since it avoids additional client side interpretation. + * + * @deprecated Use textEdit instead. + */ + String insertText; + + /** + * The format of the insert text. The format applies to both the `insertText` property + * and the `newText` property of a provided `textEdit`. + */ + int insertTextFormat; + + /** + * An edit which is applied to a document when selecting this completion. When an edit is provided the value of + * `insertText` is ignored. + * + * *Note:* The range of the edit must be a single line range and it must contain the position at which completion + * has been requested. + */ + TextEdit textEdit; + + /** + * An optional array of additional text edits that are applied when + * selecting this completion. Edits must not overlap (including the same insert position) + * with the main edit nor with themselves. + * + * Additional text edits should be used to change text unrelated to the current cursor position + * (for example adding an import statement at the top of the file if the completion item will + * insert an unqualified type). + */ + Vector<TextEdit> additionalTextEdits; + + /** + * An optional set of characters that when pressed while this completion is active will accept it first and + * then type that character. *Note* that all commit characters should have `length=1` and that superfluous + * characters will be ignored. + */ + Vector<String> commitCharacters; + + /** + * An optional command that is executed *after* inserting this completion. *Note* that + * additional modifications to the current document should be described with the + * additionalTextEdits-property. + */ + Command command; + + /** + * A data entry field that is preserved on a completion item between + * a completion and a completion resolve request. + */ + Variant data; + + _FORCE_INLINE_ Dictionary to_json(bool resolved = false) const { + Dictionary dict; + dict["label"] = label; + dict["kind"] = kind; + dict["data"] = data; + if (resolved) { + dict["insertText"] = insertText; + dict["detail"] = detail; + dict["documentation"] = documentation.to_json(); + dict["deprecated"] = deprecated; + dict["preselect"] = preselect; + dict["sortText"] = sortText; + dict["filterText"] = filterText; + if (commitCharacters.size()) dict["commitCharacters"] = commitCharacters; + dict["command"] = command.to_json(); + } + return dict; + } + + void load(const Dictionary &p_dict) { + if (p_dict.has("label")) label = p_dict["label"]; + if (p_dict.has("kind")) kind = p_dict["kind"]; + if (p_dict.has("detail")) detail = p_dict["detail"]; + if (p_dict.has("documentation")) { + Variant doc = p_dict["documentation"]; + if (doc.get_type() == Variant::STRING) { + documentation.value = doc; + } else if (doc.get_type() == Variant::DICTIONARY) { + Dictionary v = doc; + documentation.value = v["value"]; + } + } + if (p_dict.has("deprecated")) deprecated = p_dict["deprecated"]; + if (p_dict.has("preselect")) preselect = p_dict["preselect"]; + if (p_dict.has("sortText")) sortText = p_dict["sortText"]; + if (p_dict.has("filterText")) filterText = p_dict["filterText"]; + if (p_dict.has("insertText")) insertText = p_dict["insertText"]; + if (p_dict.has("data")) data = p_dict["data"]; + } +}; + +/** + * Represents a collection of [completion items](#CompletionItem) to be presented + * in the editor. + */ +struct CompletionList { + /** + * This list it not complete. Further typing should result in recomputing + * this list. + */ + bool isIncomplete; + + /** + * The completion items. + */ + Vector<CompletionItem> items; +}; + +// Use namespace instead of enumeration to follow the LSP specifications +// lsp::EnumName::EnumValue is OK but lsp::EnumValue is not +// And here C++ compilers are unhappy with our enumeration name like String, Array, Object etc +/** + * A symbol kind. + */ +namespace SymbolKind { +static const int File = 0; +static const int Module = 1; +static const int Namespace = 2; +static const int Package = 3; +static const int Class = 4; +static const int Method = 5; +static const int Property = 6; +static const int Field = 7; +static const int Constructor = 8; +static const int Enum = 9; +static const int Interface = 10; +static const int Function = 11; +static const int Variable = 12; +static const int Constant = 13; +static const int String = 14; +static const int Number = 15; +static const int Boolean = 16; +static const int Array = 17; +static const int Object = 18; +static const int Key = 19; +static const int Null = 20; +static const int EnumMember = 21; +static const int Struct = 22; +static const int Event = 23; +static const int Operator = 24; +static const int TypeParameter = 25; +}; // namespace SymbolKind + +/** + * Represents information about programming constructs like variables, classes, + * interfaces etc. + */ +struct SymbolInformation { + /** + * The name of this symbol. + */ + String name; + + /** + * The kind of this symbol. + */ + int kind = SymbolKind::File; + + /** + * Indicates if this symbol is deprecated. + */ + bool deprecated = false; + + /** + * The location of this symbol. The location's range is used by a tool + * to reveal the location in the editor. If the symbol is selected in the + * tool the range's start information is used to position the cursor. So + * the range usually spans more then the actual symbol's name and does + * normally include things like visibility modifiers. + * + * The range doesn't have to denote a node range in the sense of a abstract + * syntax tree. It can therefore not be used to re-construct a hierarchy of + * the symbols. + */ + Location location; + + /** + * The name of the symbol containing this symbol. This information is for + * user interface purposes (e.g. to render a qualifier in the user interface + * if necessary). It can't be used to re-infer a hierarchy for the document + * symbols. + */ + String containerName; + + _FORCE_INLINE_ Dictionary to_json() const { + Dictionary dict; + dict["name"] = name; + dict["kind"] = kind; + dict["deprecated"] = deprecated; + dict["location"] = location.to_json(); + dict["containerName"] = containerName; + return dict; + } +}; + +struct DocumentedSymbolInformation : public SymbolInformation { + /** + * A human-readable string with additional information + */ + String detail; + + /** + * A human-readable string that represents a doc-comment. + */ + String documentation; +}; + +/** + * Represents programming constructs like variables, classes, interfaces etc. that appear in a document. Document symbols can be + * hierarchical and they have two ranges: one that encloses its definition and one that points to its most interesting range, + * e.g. the range of an identifier. + */ +struct DocumentSymbol { + + /** + * The name of this symbol. Will be displayed in the user interface and therefore must not be + * an empty string or a string only consisting of white spaces. + */ + String name; + + /** + * More detail for this symbol, e.g the signature of a function. + */ + String detail; + + /** + * Documentation for this symbol + */ + String documentation; + + /** + * Class name for the native symbols + */ + String native_class; + + /** + * The kind of this symbol. + */ + int kind = SymbolKind::File; + + /** + * Indicates if this symbol is deprecated. + */ + bool deprecated = false; + + /** + * The range enclosing this symbol not including leading/trailing whitespace but everything else + * like comments. This information is typically used to determine if the clients cursor is + * inside the symbol to reveal in the symbol in the UI. + */ + Range range; + + /** + * The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. + * Must be contained by the `range`. + */ + Range selectionRange; + + DocumentUri uri; + String script_path; + + /** + * Children of this symbol, e.g. properties of a class. + */ + Vector<DocumentSymbol> children; + + Dictionary to_json(bool with_doc = false) const { + Dictionary dict; + dict["name"] = name; + dict["detail"] = detail; + dict["kind"] = kind; + dict["deprecated"] = deprecated; + dict["range"] = range.to_json(); + dict["selectionRange"] = selectionRange.to_json(); + if (with_doc) { + dict["documentation"] = documentation; + dict["native_class"] = native_class; + } + Array arr; + arr.resize(children.size()); + for (int i = 0; i < children.size(); i++) { + arr[i] = children[i].to_json(with_doc); + } + dict["children"] = arr; + return dict; + } + + void symbol_tree_as_list(const String &p_uri, Vector<DocumentedSymbolInformation> &r_list, const String &p_container = "", bool p_join_name = false) const { + DocumentedSymbolInformation si; + if (p_join_name && !p_container.empty()) { + si.name = p_container + ">" + name; + } else { + si.name = name; + } + si.kind = kind; + si.containerName = p_container; + si.deprecated = deprecated; + si.location.uri = p_uri; + si.location.range = range; + si.detail = detail; + si.documentation = documentation; + r_list.push_back(si); + for (int i = 0; i < children.size(); i++) { + children[i].symbol_tree_as_list(p_uri, r_list, si.name, p_join_name); + } + } + + _FORCE_INLINE_ MarkupContent render() const { + MarkupContent markdown; + if (detail.length()) { + markdown.value = "\t" + detail + "\n\n"; + } + if (documentation.length()) { + markdown.value += marked_documentation(documentation) + "\n\n"; + } + if (script_path.length()) { + markdown.value += "Defined in [" + script_path + "](" + uri + ")"; + } + return markdown; + } + + _FORCE_INLINE_ CompletionItem make_completion_item(bool resolved = false) const { + + lsp::CompletionItem item; + item.label = name; + + if (resolved) { + item.documentation = render(); + } + + switch (kind) { + case lsp::SymbolKind::Enum: + item.kind = lsp::CompletionItemKind::Enum; + break; + case lsp::SymbolKind::Class: + item.kind = lsp::CompletionItemKind::Class; + break; + case lsp::SymbolKind::Property: + item.kind = lsp::CompletionItemKind::Property; + break; + case lsp::SymbolKind::Method: + case lsp::SymbolKind::Function: + item.kind = lsp::CompletionItemKind::Method; + break; + case lsp::SymbolKind::Event: + item.kind = lsp::CompletionItemKind::Event; + break; + case lsp::SymbolKind::Constant: + item.kind = lsp::CompletionItemKind::Constant; + break; + case lsp::SymbolKind::Variable: + item.kind = lsp::CompletionItemKind::Variable; + break; + case lsp::SymbolKind::File: + item.kind = lsp::CompletionItemKind::File; + break; + default: + item.kind = lsp::CompletionItemKind::Text; + break; + } + + return item; + } +}; + +struct NativeSymbolInspectParams { + + String native_class; + String symbol_name; + + void load(const Dictionary &p_params) { + native_class = p_params["native_class"]; + symbol_name = p_params["symbol_name"]; + } +}; + +/** + * Enum of known range kinds + */ +namespace FoldingRangeKind { +/** + * Folding range for a comment + */ +static const String Comment = "comment"; +/** + * Folding range for a imports or includes + */ +static const String Imports = "imports"; +/** + * Folding range for a region (e.g. `#region`) + */ +static const String Region = "region"; +} // namespace FoldingRangeKind + +/** + * Represents a folding range. + */ +struct FoldingRange { + + /** + * The zero-based line number from where the folded range starts. + */ + int startLine = 0; + + /** + * The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. + */ + int startCharacter = 0; + + /** + * The zero-based line number where the folded range ends. + */ + int endLine = 0; + + /** + * The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. + */ + int endCharacter = 0; + + /** + * Describes the kind of the folding range such as `comment' or 'region'. The kind + * is used to categorize folding ranges and used by commands like 'Fold all comments'. See + * [FoldingRangeKind](#FoldingRangeKind) for an enumeration of standardized kinds. + */ + String kind = FoldingRangeKind::Region; + + _FORCE_INLINE_ Dictionary to_json() const { + Dictionary dict; + dict["startLine"] = startLine; + dict["startCharacter"] = startCharacter; + dict["endLine"] = endLine; + dict["endCharacter"] = endCharacter; + return dict; + } +}; + +// Use namespace instead of enumeration to follow the LSP specifications +/** + * How a completion was triggered + */ +namespace CompletionTriggerKind { +/** + * Completion was triggered by typing an identifier (24x7 code + * complete), manual invocation (e.g Ctrl+Space) or via API. + */ +static const int Invoked = 1; + +/** + * Completion was triggered by a trigger character specified by + * the `triggerCharacters` properties of the `CompletionRegistrationOptions`. + */ +static const int TriggerCharacter = 2; + +/** + * Completion was re-triggered as the current completion list is incomplete. + */ +static const int TriggerForIncompleteCompletions = 3; +} // namespace CompletionTriggerKind + +/** + * Contains additional information about the context in which a completion request is triggered. + */ +struct CompletionContext { + /** + * How the completion was triggered. + */ + int triggerKind = CompletionTriggerKind::TriggerCharacter; + + /** + * The trigger character (a single character) that has trigger code complete. + * Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` + */ + String triggerCharacter; + + void load(const Dictionary &p_params) { + triggerKind = int(p_params["triggerKind"]); + triggerCharacter = p_params["triggerCharacter"]; + } +}; + +struct CompletionParams : public TextDocumentPositionParams { + + /** + * The completion context. This is only available if the client specifies + * to send this using `ClientCapabilities.textDocument.completion.contextSupport === true` + */ + CompletionContext context; + + void load(const Dictionary &p_params) { + TextDocumentPositionParams::load(p_params); + context.load(p_params["context"]); + } +}; + +/** + * The result of a hover request. + */ +struct Hover { + /** + * The hover's content + */ + MarkupContent contents; + + /** + * An optional range is a range inside a text document + * that is used to visualize a hover, e.g. by changing the background color. + */ + Range range; + + _FORCE_INLINE_ Dictionary to_json() const { + Dictionary dict; + dict["range"] = range.to_json(); + dict["contents"] = contents.to_json(); + return dict; + } +}; + +struct ServerCapabilities { + /** + * Defines how text documents are synced. Is either a detailed structure defining each notification or + * for backwards compatibility the TextDocumentSyncKind number. If omitted it defaults to `TextDocumentSyncKind.None`. + */ + TextDocumentSyncOptions textDocumentSync; + + /** + * The server provides hover support. + */ + bool hoverProvider = true; + + /** + * The server provides completion support. + */ + CompletionOptions completionProvider; + + /** + * The server provides signature help support. + */ + SignatureHelpOptions signatureHelpProvider; + + /** + * The server provides goto definition support. + */ + bool definitionProvider = true; + + /** + * The server provides Goto Type Definition support. + * + * Since 3.6.0 + */ + bool typeDefinitionProvider = false; + + /** + * The server provides Goto Implementation support. + * + * Since 3.6.0 + */ + bool implementationProvider = false; + + /** + * The server provides find references support. + */ + bool referencesProvider = false; + + /** + * The server provides document highlight support. + */ + bool documentHighlightProvider = false; + + /** + * The server provides document symbol support. + */ + bool documentSymbolProvider = true; + + /** + * The server provides workspace symbol support. + */ + bool workspaceSymbolProvider = true; + + /** + * The server provides code actions. The `CodeActionOptions` return type is only + * valid if the client signals code action literal support via the property + * `textDocument.codeAction.codeActionLiteralSupport`. + */ + bool codeActionProvider = false; + + /** + * The server provides code lens. + */ + CodeLensOptions codeLensProvider; + + /** + * The server provides document formatting. + */ + bool documentFormattingProvider = false; + + /** + * The server provides document range formatting. + */ + bool documentRangeFormattingProvider = false; + + /** + * The server provides document formatting on typing. + */ + DocumentOnTypeFormattingOptions documentOnTypeFormattingProvider; + + /** + * The server provides rename support. RenameOptions may only be + * specified if the client states that it supports + * `prepareSupport` in its initial `initialize` request. + */ + RenameOptions renameProvider; + + /** + * The server provides document link support. + */ + DocumentLinkOptions documentLinkProvider; + + /** + * The server provides color provider support. + * + * Since 3.6.0 + */ + ColorProviderOptions colorProvider; + + /** + * The server provides folding provider support. + * + * Since 3.10.0 + */ + FoldingRangeProviderOptions foldingRangeProvider; + + /** + * The server provides go to declaration support. + * + * Since 3.14.0 + */ + bool declarationProvider = true; + + /** + * The server provides execute command support. + */ + ExecuteCommandOptions executeCommandProvider; + + _FORCE_INLINE_ Dictionary to_json() { + Dictionary dict; + dict["textDocumentSync"] = (int)textDocumentSync.change; + dict["completionProvider"] = completionProvider.to_json(); + dict["signatureHelpProvider"] = signatureHelpProvider.to_json(); + dict["codeLensProvider"] = false; // codeLensProvider.to_json(); + dict["documentOnTypeFormattingProvider"] = documentOnTypeFormattingProvider.to_json(); + dict["renameProvider"] = renameProvider.to_json(); + dict["documentLinkProvider"] = documentLinkProvider.to_json(); + dict["colorProvider"] = false; // colorProvider.to_json(); + dict["foldingRangeProvider"] = false; //foldingRangeProvider.to_json(); + dict["executeCommandProvider"] = executeCommandProvider.to_json(); + dict["hoverProvider"] = hoverProvider; + dict["definitionProvider"] = definitionProvider; + dict["typeDefinitionProvider"] = typeDefinitionProvider; + dict["implementationProvider"] = implementationProvider; + dict["referencesProvider"] = referencesProvider; + dict["documentHighlightProvider"] = documentHighlightProvider; + dict["documentSymbolProvider"] = documentSymbolProvider; + dict["workspaceSymbolProvider"] = workspaceSymbolProvider; + dict["codeActionProvider"] = codeActionProvider; + dict["documentFormattingProvider"] = documentFormattingProvider; + dict["documentRangeFormattingProvider"] = documentRangeFormattingProvider; + dict["declarationProvider"] = declarationProvider; + return dict; + } +}; + +struct InitializeResult { + /** + * The capabilities the language server provides. + */ + ServerCapabilities capabilities; + + _FORCE_INLINE_ Dictionary to_json() { + Dictionary dict; + dict["capabilities"] = capabilities.to_json(); + return dict; + } +}; + +struct GodotNativeClassInfo { + + String name; + const DocData::ClassDoc *class_doc = NULL; + const ClassDB::ClassInfo *class_info = NULL; + + Dictionary to_json() { + Dictionary dict; + dict["name"] = name; + dict["inherits"] = class_doc->inherits; + return dict; + } +}; + +/** Features not included in the standard lsp specifications */ +struct GodotCapabilities { + + /** + * Native class list + */ + List<GodotNativeClassInfo> native_classes; + + Dictionary to_json() { + Dictionary dict; + Array classes; + for (List<GodotNativeClassInfo>::Element *E = native_classes.front(); E; E = E->next()) { + classes.push_back(E->get().to_json()); + } + dict["native_classes"] = classes; + return dict; + } +}; + +/** Format BBCode documentation from DocData to markdown */ +static String marked_documentation(const String &p_bbcode) { + + String markdown = p_bbcode.strip_edges(); + + Vector<String> lines = markdown.split("\n"); + bool in_code_block = false; + int code_block_indent = -1; + + markdown = ""; + for (int i = 0; i < lines.size(); i++) { + String line = lines[i]; + int block_start = line.find("[codeblock]"); + if (block_start != -1) { + code_block_indent = block_start; + in_code_block = true; + line = "\n"; + } else if (in_code_block) { + line = "\t" + line.substr(code_block_indent, line.length()); + } + + if (in_code_block && line.find("[/codeblock]") != -1) { + line = "\n"; + in_code_block = false; + } + + if (!in_code_block) { + line = line.strip_edges(); + line = line.replace("[code]", "`"); + line = line.replace("[/code]", "`"); + line = line.replace("[i]", "*"); + line = line.replace("[/i]", "*"); + line = line.replace("[b]", "**"); + line = line.replace("[/b]", "**"); + line = line.replace("[u]", "__"); + line = line.replace("[/u]", "__"); + line = line.replace("[method ", "`"); + line = line.replace("[member ", "`"); + line = line.replace("[signal ", "`"); + line = line.replace("[enum ", "`"); + line = line.replace("[constant ", "`"); + line = line.replace("[", "`"); + line = line.replace("]", "`"); + } + + if (!in_code_block && i < lines.size() - 1) { + line += "\n\n"; + } else if (i < lines.size() - 1) { + line += "\n"; + } + markdown += line; + } + return markdown; +} + +} // namespace lsp + +#endif diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp index b8a13ed91b..94b9e8c2d9 100644 --- a/modules/gdscript/register_types.cpp +++ b/modules/gdscript/register_types.cpp @@ -32,8 +32,8 @@ #include "core/io/file_access_encrypted.h" #include "core/io/resource_loader.h" +#include "core/os/dir_access.h" #include "core/os/file_access.h" -#include "editor/gdscript_highlighter.h" #include "gdscript.h" #include "gdscript_tokenizer.h" @@ -46,6 +46,12 @@ Ref<ResourceFormatSaverGDScript> resource_saver_gd; #include "editor/editor_export.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" +#include "editor/gdscript_highlighter.h" + +#ifndef GDSCRIPT_NO_LSP +#include "core/engine.h" +#include "language_server/gdscript_language_server.h" +#endif // !GDSCRIPT_NO_LSP class EditorExportGDScript : public EditorExportPlugin { @@ -117,6 +123,9 @@ public: file = FileAccess::get_file_as_array(tmp_path); add_file(p_path.get_basename() + ".gde", file, true); + // Clean up temporary file. + DirAccess::remove_file_or_error(tmp_path); + } else { add_file(p_path.get_basename() + ".gdc", file, true); @@ -130,9 +139,16 @@ static void _editor_init() { Ref<EditorExportGDScript> gd_export; gd_export.instance(); EditorExport::get_singleton()->add_export_plugin(gd_export); + +#ifndef GDSCRIPT_NO_LSP + register_lsp_types(); + GDScriptLanguageServer *lsp_plugin = memnew(GDScriptLanguageServer); + EditorNode::get_singleton()->add_editor_plugin(lsp_plugin); + Engine::get_singleton()->add_singleton(Engine::Singleton("GDScriptLanguageProtocol", GDScriptLanguageProtocol::get_singleton())); +#endif // !GDSCRIPT_NO_LSP } -#endif +#endif // TOOLS_ENABLED void register_gdscript_types() { @@ -151,7 +167,7 @@ void register_gdscript_types() { #ifdef TOOLS_ENABLED ScriptEditor::register_create_syntax_highlighter_function(GDScriptSyntaxHighlighter::create); EditorNode::add_init_callback(_editor_init); -#endif +#endif // TOOLS_ENABLED } void unregister_gdscript_types() { diff --git a/modules/gridmap/doc_classes/GridMap.xml b/modules/gridmap/doc_classes/GridMap.xml index 655be4eb20..3de971db6d 100644 --- a/modules/gridmap/doc_classes/GridMap.xml +++ b/modules/gridmap/doc_classes/GridMap.xml @@ -4,16 +4,14 @@ Node for 3D tile-based maps. </brief_description> <description> - GridMap lets you place meshes on a grid interactively. It works both from the editor and can help you create in-game level editors. - GridMaps use a [MeshLibrary] which contain a list of tiles: meshes with materials plus optional collisions and extra elements. - A GridMap contains a collection of cells. Each grid cell refers to a [MeshLibrary] item. All cells in the map have the same dimensions. - A GridMap is split into a sparse collection of octants for efficient rendering and physics processing. Every octant has the same dimensions and can contain several cells. + GridMap lets you place meshes on a grid interactively. It works both from the editor and from scripts, which can help you create in-game level editors. + GridMaps use a [MeshLibrary] which contains a list of tiles. Each tile is a mesh with materials plus optional collision and navigation shapes. + A GridMap contains a collection of cells. Each grid cell refers to a tile in the [MeshLibrary]. All cells in the map have the same dimensions. + Internally, a GridMap is split into a sparse collection of octants for efficient rendering and physics processing. Every octant has the same dimensions and can contain several cells. </description> <tutorials> <link>https://docs.godotengine.org/en/latest/tutorials/3d/using_gridmaps.html</link> </tutorials> - <demos> - </demos> <methods> <method name="clear"> <return type="void"> @@ -74,6 +72,7 @@ <argument index="0" name="bit" type="int"> </argument> <description> + Returns an individual bit on the [member collision_layer]. </description> </method> <method name="get_collision_mask_bit" qualifiers="const"> @@ -82,20 +81,21 @@ <argument index="0" name="bit" type="int"> </argument> <description> + Returns an individual bit on the [member collision_mask]. </description> </method> <method name="get_meshes"> <return type="Array"> </return> <description> - Array of [Transform] and [Mesh] references corresponding to the non empty cells in the grid. The transforms are specified in world space. + Returns an array of [Transform] and [Mesh] references corresponding to the non-empty cells in the grid. The transforms are specified in world space. </description> </method> <method name="get_used_cells" qualifiers="const"> <return type="Array"> </return> <description> - Array of [Vector3] with the non empty cell coordinates in the grid map. + Returns an array of [Vector3] with the non-empty cell coordinates in the grid map. </description> </method> <method name="make_baked_meshes"> @@ -118,6 +118,7 @@ <argument index="2" name="z" type="int"> </argument> <description> + Returns the position of a grid cell in the GridMap's local coordinate space. </description> </method> <method name="resource_changed"> @@ -142,9 +143,9 @@ <argument index="4" name="orientation" type="int" default="0"> </argument> <description> - Set the mesh index for the cell referenced by its grid-based X, Y and Z coordinates. - A negative item index will clear the cell. - Optionally, the item's orientation can be passed. + Sets the mesh index for the cell referenced by its grid-based X, Y and Z coordinates. + A negative item index such as [constant INVALID_CELL_ITEM] will clear the cell. + Optionally, the item's orientation can be passed. For valid orientation values, see [method Basis.get_orthogonal_index]. </description> </method> <method name="set_clip"> @@ -169,6 +170,7 @@ <argument index="1" name="value" type="bool"> </argument> <description> + Sets an individual bit on the [member collision_layer]. </description> </method> <method name="set_collision_mask_bit"> @@ -179,6 +181,7 @@ <argument index="1" name="value" type="bool"> </argument> <description> + Sets an individual bit on the [member collision_mask]. </description> </method> <method name="world_to_map" qualifiers="const"> @@ -187,38 +190,52 @@ <argument index="0" name="pos" type="Vector3"> </argument> <description> + Returns the coordinates of the grid cell containing the given point. + [code]pos[/code] should be in the GridMap's local coordinate space. </description> </method> </methods> <members> - <member name="cell_center_x" type="bool" setter="set_center_x" getter="get_center_x"> + <member name="cell_center_x" type="bool" setter="set_center_x" getter="get_center_x" default="true"> If [code]true[/code], grid items are centered on the X axis. </member> - <member name="cell_center_y" type="bool" setter="set_center_y" getter="get_center_y"> + <member name="cell_center_y" type="bool" setter="set_center_y" getter="get_center_y" default="true"> If [code]true[/code], grid items are centered on the Y axis. </member> - <member name="cell_center_z" type="bool" setter="set_center_z" getter="get_center_z"> + <member name="cell_center_z" type="bool" setter="set_center_z" getter="get_center_z" default="true"> If [code]true[/code], grid items are centered on the Z axis. </member> - <member name="cell_octant_size" type="int" setter="set_octant_size" getter="get_octant_size"> + <member name="cell_octant_size" type="int" setter="set_octant_size" getter="get_octant_size" default="8"> The size of each octant measured in number of cells. This applies to all three axis. </member> - <member name="cell_scale" type="float" setter="set_cell_scale" getter="get_cell_scale"> + <member name="cell_scale" type="float" setter="set_cell_scale" getter="get_cell_scale" default="1.0"> + The scale of the cell items. + This does not affect the size of the grid cells themselves, only the items in them. This can be used to make cell items overlap their neighbors. </member> - <member name="cell_size" type="Vector3" setter="set_cell_size" getter="get_cell_size"> + <member name="cell_size" type="Vector3" setter="set_cell_size" getter="get_cell_size" default="Vector3( 2, 2, 2 )"> The dimensions of the grid's cells. + This does not affect the size of the meshes. See [member cell_scale]. </member> - <member name="collision_layer" type="int" setter="set_collision_layer" getter="get_collision_layer"> + <member name="collision_layer" type="int" setter="set_collision_layer" getter="get_collision_layer" default="1"> + The physics layers this GridMap is in. + GridMaps act as static bodies, meaning they aren't affected by gravity or other forces. They only affect other physics bodies that collide with them. </member> - <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask"> + <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask" default="1"> + The physics layers this GridMap detects collisions in. </member> <member name="mesh_library" type="MeshLibrary" setter="set_mesh_library" getter="get_mesh_library"> The assigned [MeshLibrary]. </member> - <member name="theme" type="MeshLibrary" setter="set_theme" getter="get_theme"> - Deprecated, use [member mesh_library] instead. - </member> </members> + <signals> + <signal name="cell_size_changed"> + <argument index="0" name="cell_size" type="Vector3"> + </argument> + <description> + Emitted when [member cell_size] changes. + </description> + </signal> + </signals> <constants> <constant name="INVALID_CELL_ITEM" value="-1"> Invalid cell item that can be used in [method set_cell_item] to clear cells (or represent an empty cell in [method get_cell_item]). diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp index 32a014e76d..d69e60ced3 100644 --- a/modules/gridmap/grid_map.cpp +++ b/modules/gridmap/grid_map.cpp @@ -193,24 +193,6 @@ bool GridMap::get_collision_layer_bit(int p_bit) const { return get_collision_layer() & (1 << p_bit); } -#ifndef DISABLE_DEPRECATED -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 - - set_mesh_library(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 - - return get_mesh_library(); -} -#endif // DISABLE_DEPRECATED - void GridMap::set_mesh_library(const Ref<MeshLibrary> &p_mesh_library) { if (!mesh_library.is_null()) @@ -229,10 +211,10 @@ Ref<MeshLibrary> GridMap::get_mesh_library() const { } void GridMap::set_cell_size(const Vector3 &p_size) { - ERR_FAIL_COND(p_size.x < 0.001 || p_size.y < 0.001 || p_size.z < 0.001); cell_size = p_size; _recreate_octant_data(); + emit_signal("cell_size_changed", cell_size); } Vector3 GridMap::get_cell_size() const { @@ -241,6 +223,7 @@ Vector3 GridMap::get_cell_size() const { void GridMap::set_octant_size(int p_size) { + ERR_FAIL_COND(p_size == 0); octant_size = p_size; _recreate_octant_data(); } @@ -480,11 +463,6 @@ bool GridMap::_octant_update(const OctantKey &p_key) { Transform xform; - if (clip && ((clip_above && cellpos[clip_axis] > clip_floor) || (!clip_above && cellpos[clip_axis] < clip_floor))) { - - } else { - } - xform.basis.set_orthogonal_index(c.rot); xform.set_origin(cellpos * cell_size + ofs); xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale)); @@ -844,11 +822,6 @@ void GridMap::_bind_methods() { ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &GridMap::set_collision_layer_bit); ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &GridMap::get_collision_layer_bit); -#ifndef DISABLE_DEPRECATED - ClassDB::bind_method(D_METHOD("set_theme", "theme"), &GridMap::set_theme); - ClassDB::bind_method(D_METHOD("get_theme"), &GridMap::get_theme); -#endif // DISABLE_DEPRECATED - ClassDB::bind_method(D_METHOD("set_mesh_library", "mesh_library"), &GridMap::set_mesh_library); ClassDB::bind_method(D_METHOD("get_mesh_library"), &GridMap::get_mesh_library); @@ -891,10 +864,6 @@ void GridMap::_bind_methods() { ClassDB::bind_method(D_METHOD("clear_baked_meshes"), &GridMap::clear_baked_meshes); ClassDB::bind_method(D_METHOD("make_baked_meshes", "gen_lightmap_uv", "lightmap_uv_texel_size"), &GridMap::make_baked_meshes, DEFVAL(false), DEFVAL(0.1)); -#ifndef DISABLE_DEPRECATED - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "theme", PROPERTY_HINT_RESOURCE_TYPE, "MeshLibrary", 0), "set_theme", "get_theme"); -#endif // DISABLE_DEPRECATED - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh_library", PROPERTY_HINT_RESOURCE_TYPE, "MeshLibrary"), "set_mesh_library", "get_mesh_library"); ADD_GROUP("Cell", "cell_"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "cell_size"), "set_cell_size", "get_cell_size"); @@ -908,6 +877,8 @@ void GridMap::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask"); BIND_CONSTANT(INVALID_CELL_ITEM); + + ADD_SIGNAL(MethodInfo("cell_size_changed", PropertyInfo(Variant::VECTOR3, "cell_size"))); } void GridMap::set_clip(bool p_enabled, bool p_clip_above, int p_floor, Vector3::Axis p_axis) { diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h index f4407099f5..10c96956b7 100644 --- a/modules/gridmap/grid_map.h +++ b/modules/gridmap/grid_map.h @@ -227,11 +227,6 @@ public: void set_collision_mask_bit(int p_bit, bool p_value); bool get_collision_mask_bit(int p_bit) const; -#ifndef DISABLE_DEPRECATED - void set_theme(const Ref<MeshLibrary> &p_theme); - Ref<MeshLibrary> get_theme() const; -#endif // DISABLE_DEPRECATED - void set_mesh_library(const Ref<MeshLibrary> &p_mesh_library); Ref<MeshLibrary> get_mesh_library() const; diff --git a/modules/gridmap/grid_map_editor_plugin.cpp b/modules/gridmap/grid_map_editor_plugin.cpp index 17eb6f674c..1bd570c55f 100644 --- a/modules/gridmap/grid_map_editor_plugin.cpp +++ b/modules/gridmap/grid_map_editor_plugin.cpp @@ -40,11 +40,8 @@ void GridMapEditor::_node_removed(Node *p_node) { - if (p_node == node) { + if (p_node == node) node = NULL; - hide(); - mesh_library_palette->hide(); - } } void GridMapEditor::_configure() { @@ -67,9 +64,6 @@ void GridMapEditor::_menu_option(int p_option) { floor->set_value(floor->get_value() + 1); } break; - case MENU_OPTION_CONFIGURE: { - - } break; case MENU_OPTION_LOCK_VIEW: { int index = options->get_popup()->get_item_index(MENU_OPTION_LOCK_VIEW); @@ -121,14 +115,15 @@ void GridMapEditor::_menu_option(int p_option) { case MENU_OPTION_CURSOR_ROTATE_Y: { Basis r; - if (input_action == INPUT_DUPLICATE) { + if (input_action == INPUT_PASTE) { - r.set_orthogonal_index(selection.duplicate_rot); + r.set_orthogonal_index(paste_indicator.orientation); r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0); - selection.duplicate_rot = r.get_orthogonal_index(); - _update_duplicate_indicator(); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); break; } + r.set_orthogonal_index(cursor_rot); r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0); cursor_rot = r.get_orthogonal_index(); @@ -137,12 +132,12 @@ void GridMapEditor::_menu_option(int p_option) { case MENU_OPTION_CURSOR_ROTATE_X: { Basis r; - if (input_action == INPUT_DUPLICATE) { + if (input_action == INPUT_PASTE) { - r.set_orthogonal_index(selection.duplicate_rot); + r.set_orthogonal_index(paste_indicator.orientation); r.rotate(Vector3(1, 0, 0), -Math_PI / 2.0); - selection.duplicate_rot = r.get_orthogonal_index(); - _update_duplicate_indicator(); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); break; } @@ -154,12 +149,12 @@ void GridMapEditor::_menu_option(int p_option) { case MENU_OPTION_CURSOR_ROTATE_Z: { Basis r; - if (input_action == INPUT_DUPLICATE) { + if (input_action == INPUT_PASTE) { - r.set_orthogonal_index(selection.duplicate_rot); + r.set_orthogonal_index(paste_indicator.orientation); r.rotate(Vector3(0, 0, 1), -Math_PI / 2.0); - selection.duplicate_rot = r.get_orthogonal_index(); - _update_duplicate_indicator(); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); break; } @@ -171,6 +166,15 @@ void GridMapEditor::_menu_option(int p_option) { case MENU_OPTION_CURSOR_BACK_ROTATE_Y: { Basis r; + if (input_action == INPUT_PASTE) { + + r.set_orthogonal_index(paste_indicator.orientation); + r.rotate(Vector3(0, 1, 0), Math_PI / 2.0); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); + break; + } + r.set_orthogonal_index(cursor_rot); r.rotate(Vector3(0, 1, 0), Math_PI / 2.0); cursor_rot = r.get_orthogonal_index(); @@ -179,6 +183,15 @@ void GridMapEditor::_menu_option(int p_option) { case MENU_OPTION_CURSOR_BACK_ROTATE_X: { Basis r; + if (input_action == INPUT_PASTE) { + + r.set_orthogonal_index(paste_indicator.orientation); + r.rotate(Vector3(1, 0, 0), Math_PI / 2.0); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); + break; + } + r.set_orthogonal_index(cursor_rot); r.rotate(Vector3(1, 0, 0), Math_PI / 2.0); cursor_rot = r.get_orthogonal_index(); @@ -187,6 +200,15 @@ void GridMapEditor::_menu_option(int p_option) { case MENU_OPTION_CURSOR_BACK_ROTATE_Z: { Basis r; + if (input_action == INPUT_PASTE) { + + r.set_orthogonal_index(paste_indicator.orientation); + r.rotate(Vector3(0, 0, 1), Math_PI / 2.0); + paste_indicator.orientation = r.get_orthogonal_index(); + _update_paste_indicator(); + break; + } + r.set_orthogonal_index(cursor_rot); r.rotate(Vector3(0, 0, 1), Math_PI / 2.0); cursor_rot = r.get_orthogonal_index(); @@ -194,10 +216,10 @@ void GridMapEditor::_menu_option(int p_option) { } break; case MENU_OPTION_CURSOR_CLEAR_ROTATION: { - if (input_action == INPUT_DUPLICATE) { + if (input_action == INPUT_PASTE) { - selection.duplicate_rot = 0; - _update_duplicate_indicator(); + paste_indicator.orientation = 0; + _update_paste_indicator(); break; } @@ -205,28 +227,33 @@ void GridMapEditor::_menu_option(int p_option) { _update_cursor_transform(); } break; - case MENU_OPTION_DUPLICATE_SELECTS: { - int idx = options->get_popup()->get_item_index(MENU_OPTION_DUPLICATE_SELECTS); + case MENU_OPTION_PASTE_SELECTS: { + int idx = options->get_popup()->get_item_index(MENU_OPTION_PASTE_SELECTS); options->get_popup()->set_item_checked(idx, !options->get_popup()->is_item_checked(idx)); } break; + case MENU_OPTION_SELECTION_DUPLICATE: + case MENU_OPTION_SELECTION_CUT: { if (!(selection.active && input_action == INPUT_NONE)) - return; - if (last_mouseover == Vector3(-1, -1, -1)) //nono mouseovering anythin break; - last_mouseover = selection.begin; - VS::get_singleton()->instance_set_transform(grid_instance[edit_axis], Transform(Basis(), grid_ofs)); + _set_clipboard_data(); + + if (p_option == MENU_OPTION_SELECTION_CUT) { + _delete_selection(); + } - input_action = INPUT_DUPLICATE; - selection.click = last_mouseover; - selection.current = last_mouseover; - selection.duplicate_rot = 0; - _update_duplicate_indicator(); - break; + input_action = INPUT_PASTE; + paste_indicator.click = selection.begin; + paste_indicator.current = selection.begin; + paste_indicator.begin = selection.begin; + paste_indicator.end = selection.end; + paste_indicator.orientation = 0; + _update_paste_indicator(); + } break; case MENU_OPTION_SELECTION_CLEAR: { if (!selection.active) - return; + break; _delete_selection(); @@ -249,7 +276,8 @@ void GridMapEditor::_update_cursor_transform() { cursor_transform = Transform(); cursor_transform.origin = cursor_origin; cursor_transform.basis.set_orthogonal_index(cursor_rot); - cursor_transform = node->get_transform() * cursor_transform; + cursor_transform.basis *= node->get_cell_scale(); + cursor_transform = node->get_global_transform() * cursor_transform; if (cursor_instance.is_valid()) { VisualServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform); @@ -271,7 +299,7 @@ void GridMapEditor::_update_selection_transform() { } Transform xf; - xf.scale(Vector3(1, 1, 1) * (Vector3(1, 1, 1) + (selection.end - selection.begin)) * node->get_cell_size()); + xf.scale((Vector3(1, 1, 1) + (selection.end - selection.begin)) * node->get_cell_size()); xf.origin = selection.begin * node->get_cell_size(); VisualServer::get_singleton()->instance_set_transform(selection_instance, node->get_global_transform() * xf); @@ -315,17 +343,35 @@ void GridMapEditor::_validate_selection() { _update_selection_transform(); } +void GridMapEditor::_set_selection(bool p_active, const Vector3 &p_begin, const Vector3 &p_end) { + + selection.active = p_active; + selection.begin = p_begin; + selection.end = p_end; + selection.click = p_begin; + selection.current = p_end; + + if (is_visible_in_tree()) { + _update_selection_transform(); + } + + options->get_popup()->set_item_disabled(options->get_popup()->get_item_index(MENU_OPTION_SELECTION_CLEAR), !selection.active); + options->get_popup()->set_item_disabled(options->get_popup()->get_item_index(MENU_OPTION_SELECTION_CUT), !selection.active); + options->get_popup()->set_item_disabled(options->get_popup()->get_item_index(MENU_OPTION_SELECTION_DUPLICATE), !selection.active); + options->get_popup()->set_item_disabled(options->get_popup()->get_item_index(MENU_OPTION_SELECTION_FILL), !selection.active); +} + bool GridMapEditor::do_input_action(Camera *p_camera, const Point2 &p_point, bool p_click) { if (!spatial_editor) return false; - if (selected_palette < 0 && input_action != INPUT_COPY && input_action != INPUT_SELECT && input_action != INPUT_DUPLICATE) + if (selected_palette < 0 && input_action != INPUT_PICK && input_action != INPUT_SELECT && input_action != INPUT_PASTE) return false; Ref<MeshLibrary> mesh_library = node->get_mesh_library(); if (mesh_library.is_null()) return false; - if (input_action != INPUT_COPY && input_action != INPUT_SELECT && input_action != INPUT_DUPLICATE && !mesh_library->has_item(selected_palette)) + if (input_action != INPUT_PICK && input_action != INPUT_SELECT && input_action != INPUT_PASTE && !mesh_library->has_item(selected_palette)) return false; Camera *camera = p_camera; @@ -344,8 +390,8 @@ bool GridMapEditor::do_input_action(Camera *p_camera, const Point2 &p_point, boo if (!p.intersects_segment(from, from + normal * settings_pick_distance->get_value(), &inters)) return false; - //make sure the intersection is inside the frustum planes, to avoid - //painting on invisible regions + // Make sure the intersection is inside the frustum planes, to avoid + // Painting on invisible regions. for (int i = 0; i < planes.size(); i++) { Plane fp = local_xform.xform(planes[i]); @@ -356,8 +402,6 @@ bool GridMapEditor::do_input_action(Camera *p_camera, const Point2 &p_point, boo int cell[3]; float cell_size[3] = { node->get_cell_size().x, node->get_cell_size().y, node->get_cell_size().z }; - last_mouseover = Vector3(-1, -1, -1); - for (int i = 0; i < 3; i++) { if (i == edit_axis) @@ -366,33 +410,29 @@ bool GridMapEditor::do_input_action(Camera *p_camera, const Point2 &p_point, boo cell[i] = inters[i] / node->get_cell_size()[i]; if (inters[i] < 0) - cell[i] -= 1; //compensate negative + cell[i] -= 1; // Compensate negative. grid_ofs[i] = cell[i] * cell_size[i]; } - - /*if (cell[i]<0 || cell[i]>=grid_size[i]) { - - cursor_visible=false; - _update_cursor_transform(); - return false; - }*/ } - last_mouseover = Vector3(cell[0], cell[1], cell[2]); - VS::get_singleton()->instance_set_transform(grid_instance[edit_axis], Transform(Basis(), grid_ofs)); + VS::get_singleton()->instance_set_transform(grid_instance[edit_axis], node->get_global_transform() * edit_grid_xform); if (cursor_instance.is_valid()) { cursor_origin = (Vector3(cell[0], cell[1], cell[2]) + Vector3(0.5 * node->get_center_x(), 0.5 * node->get_center_y(), 0.5 * node->get_center_z())) * node->get_cell_size(); cursor_visible = true; + if (input_action == INPUT_SELECT || input_action == INPUT_PASTE) { + cursor_visible = false; + } + _update_cursor_transform(); } - if (input_action == INPUT_DUPLICATE) { + if (input_action == INPUT_PASTE) { - selection.current = Vector3(cell[0], cell[1], cell[2]); - _update_duplicate_indicator(); + paste_indicator.current = Vector3(cell[0], cell[1], cell[2]); + _update_paste_indicator(); } else if (input_action == INPUT_SELECT) { @@ -403,7 +443,7 @@ bool GridMapEditor::do_input_action(Camera *p_camera, const Point2 &p_point, boo _validate_selection(); return true; - } else if (input_action == INPUT_COPY) { + } else if (input_action == INPUT_PICK) { int item = node->get_cell_item(cell[0], cell[1], cell[2]); if (item >= 0) { @@ -456,10 +496,9 @@ void GridMapEditor::_delete_selection() { } } } + undo_redo->add_do_method(this, "_set_selection", !selection.active, selection.begin, selection.end); + undo_redo->add_undo_method(this, "_set_selection", selection.active, selection.begin, selection.end); undo_redo->commit_action(); - - selection.active = false; - _validate_selection(); } void GridMapEditor::_fill_selection() { @@ -479,97 +518,124 @@ void GridMapEditor::_fill_selection() { } } } + undo_redo->add_do_method(this, "_set_selection", !selection.active, selection.begin, selection.end); + undo_redo->add_undo_method(this, "_set_selection", selection.active, selection.begin, selection.end); undo_redo->commit_action(); +} - selection.active = false; - _validate_selection(); +void GridMapEditor::_clear_clipboard_data() { + + for (List<ClipboardItem>::Element *E = clipboard_items.front(); E; E = E->next()) { + + VisualServer::get_singleton()->free(E->get().instance); + } + + clipboard_items.clear(); +} + +void GridMapEditor::_set_clipboard_data() { + + _clear_clipboard_data(); + + Ref<MeshLibrary> meshLibrary = node->get_mesh_library(); + + for (int i = selection.begin.x; i <= selection.end.x; i++) { + + for (int j = selection.begin.y; j <= selection.end.y; j++) { + + for (int k = selection.begin.z; k <= selection.end.z; k++) { + + int itm = node->get_cell_item(i, j, k); + if (itm == GridMap::INVALID_CELL_ITEM) + continue; + + Ref<Mesh> mesh = meshLibrary->get_item_mesh(itm); + + ClipboardItem item; + item.cell_item = itm; + item.grid_offset = Vector3(i, j, k) - selection.begin; + item.orientation = node->get_cell_item_orientation(i, j, k); + item.instance = VisualServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world()->get_scenario()); + + clipboard_items.push_back(item); + } + } + } } -void GridMapEditor::_update_duplicate_indicator() { +void GridMapEditor::_update_paste_indicator() { - if (!selection.active || input_action != INPUT_DUPLICATE) { + if (input_action != INPUT_PASTE) { Transform xf; xf.basis.set_zero(); - VisualServer::get_singleton()->instance_set_transform(duplicate_instance, xf); + VisualServer::get_singleton()->instance_set_transform(paste_instance, xf); return; } + Vector3 center = 0.5 * Vector3(float(node->get_center_x()), float(node->get_center_y()), float(node->get_center_z())); + Vector3 scale = (Vector3(1, 1, 1) + (paste_indicator.end - paste_indicator.begin)) * node->get_cell_size(); Transform xf; - xf.scale(Vector3(1, 1, 1) * (Vector3(1, 1, 1) + (selection.end - selection.begin)) * node->get_cell_size()); - xf.origin = (selection.begin + (selection.current - selection.click)) * node->get_cell_size(); + xf.scale(scale); + xf.origin = (paste_indicator.begin + (paste_indicator.current - paste_indicator.click) + center) * node->get_cell_size(); Basis rot; - rot.set_orthogonal_index(selection.duplicate_rot); + rot.set_orthogonal_index(paste_indicator.orientation); xf.basis = rot * xf.basis; + xf.translate((-center * node->get_cell_size()) / scale); - VisualServer::get_singleton()->instance_set_transform(duplicate_instance, node->get_global_transform() * xf); -} + VisualServer::get_singleton()->instance_set_transform(paste_instance, node->get_global_transform() * xf); -struct __Item { - Vector3 pos; - int rot; - int item; -}; -void GridMapEditor::_duplicate_paste() { + for (List<ClipboardItem>::Element *E = clipboard_items.front(); E; E = E->next()) { - if (!selection.active) - return; + ClipboardItem &item = E->get(); - int idx = options->get_popup()->get_item_index(MENU_OPTION_DUPLICATE_SELECTS); - bool reselect = options->get_popup()->is_item_checked(idx); + xf = Transform(); + xf.origin = (paste_indicator.begin + (paste_indicator.current - paste_indicator.click) + center) * node->get_cell_size(); + xf.basis = rot * xf.basis; + xf.translate(item.grid_offset * node->get_cell_size()); - List<__Item> items; + Basis item_rot; + item_rot.set_orthogonal_index(item.orientation); + xf.basis = item_rot * xf.basis * node->get_cell_scale(); + + VisualServer::get_singleton()->instance_set_transform(item.instance, node->get_global_transform() * xf); + } +} + +void GridMapEditor::_do_paste() { + + int idx = options->get_popup()->get_item_index(MENU_OPTION_PASTE_SELECTS); + bool reselect = options->get_popup()->is_item_checked(idx); Basis rot; - rot.set_orthogonal_index(selection.duplicate_rot); + rot.set_orthogonal_index(paste_indicator.orientation); - for (int i = selection.begin.x; i <= selection.end.x; i++) { + Vector3 ofs = paste_indicator.current - paste_indicator.click; + undo_redo->create_action(TTR("GridMap Paste Selection")); - for (int j = selection.begin.y; j <= selection.end.y; j++) { + for (List<ClipboardItem>::Element *E = clipboard_items.front(); E; E = E->next()) { - for (int k = selection.begin.z; k <= selection.end.z; k++) { + ClipboardItem &item = E->get(); - int itm = node->get_cell_item(i, j, k); - if (itm == GridMap::INVALID_CELL_ITEM) - continue; - int orientation = node->get_cell_item_orientation(i, j, k); - __Item item; - Vector3 rel = Vector3(i, j, k) - selection.begin; - rel = rot.xform(rel); - - Basis orm; - orm.set_orthogonal_index(orientation); - orm = rot * orm; - - item.pos = selection.begin + rel; - item.item = itm; - item.rot = orm.get_orthogonal_index(); - items.push_back(item); - } - } - } + Vector3 pos = rot.xform(item.grid_offset) + paste_indicator.begin + ofs; - Vector3 ofs = selection.current - selection.click; - if (items.size()) { - undo_redo->create_action(TTR("GridMap Duplicate Selection")); - for (List<__Item>::Element *E = items.front(); E; E = E->next()) { - __Item &it = E->get(); - Vector3 pos = it.pos + ofs; + Basis orm; + orm.set_orthogonal_index(item.orientation); + orm = rot * orm; - undo_redo->add_do_method(node, "set_cell_item", pos.x, pos.y, pos.z, it.item, it.rot); - undo_redo->add_undo_method(node, "set_cell_item", pos.x, pos.y, pos.z, node->get_cell_item(pos.x, pos.y, pos.z), node->get_cell_item_orientation(pos.x, pos.y, pos.z)); - } - undo_redo->commit_action(); + undo_redo->add_do_method(node, "set_cell_item", pos.x, pos.y, pos.z, item.cell_item, orm.get_orthogonal_index()); + undo_redo->add_undo_method(node, "set_cell_item", pos.x, pos.y, pos.z, node->get_cell_item(pos.x, pos.y, pos.z), node->get_cell_item_orientation(pos.x, pos.y, pos.z)); } if (reselect) { - selection.begin += ofs; - selection.end += ofs; - selection.click = selection.begin; - selection.current = selection.end; - _validate_selection(); + undo_redo->add_do_method(this, "_set_selection", true, paste_indicator.begin + ofs, paste_indicator.end + ofs); + undo_redo->add_undo_method(this, "_set_selection", selection.active, selection.begin, selection.end); } + + undo_redo->commit_action(); + + _clear_clipboard_data(); } bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const Ref<InputEvent> &p_event) { @@ -585,7 +651,7 @@ bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const Ref<Inpu if (mb->is_pressed()) floor->set_value(floor->get_value() + mb->get_factor()); - return true; //eaten + return true; // Eaten. } else if (mb->get_button_index() == BUTTON_WHEEL_DOWN && (mb->get_command() || mb->get_shift())) { if (mb->is_pressed()) floor->set_value(floor->get_value() - mb->get_factor()); @@ -593,31 +659,36 @@ bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const Ref<Inpu } if (mb->is_pressed()) { + SpatialEditorViewport::NavigationScheme nav_scheme = (SpatialEditorViewport::NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int(); + if ((nav_scheme == SpatialEditorViewport::NAVIGATION_MAYA || nav_scheme == SpatialEditorViewport::NAVIGATION_MODO) && mb->get_alt()) { + input_action = INPUT_NONE; + } else if (mb->get_button_index() == BUTTON_LEFT) { - if (mb->get_button_index() == BUTTON_LEFT) { - - if (input_action == INPUT_DUPLICATE) { - //paste - _duplicate_paste(); + if (input_action == INPUT_PASTE) { + _do_paste(); input_action = INPUT_NONE; - _update_duplicate_indicator(); + _update_paste_indicator(); } else if (mb->get_shift()) { input_action = INPUT_SELECT; + last_selection = selection; } else if (mb->get_command()) { - input_action = INPUT_COPY; + input_action = INPUT_PICK; } else { input_action = INPUT_PAINT; set_items.clear(); } } else if (mb->get_button_index() == BUTTON_RIGHT) { - if (input_action == INPUT_DUPLICATE) { + if (input_action == INPUT_PASTE) { + _clear_clipboard_data(); input_action = INPUT_NONE; - _update_duplicate_indicator(); - } else if (mb->get_shift()) { + _update_paste_indicator(); + return true; + } else if (selection.active) { + _set_selection(false); + return true; + } else { input_action = INPUT_ERASE; set_items.clear(); - } else { - return false; } } else { return false; @@ -626,9 +697,7 @@ bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const Ref<Inpu return do_input_action(p_camera, Point2(mb->get_position().x, mb->get_position().y), true); } else { - if ( - (mb->get_button_index() == BUTTON_RIGHT && input_action == INPUT_ERASE) || - (mb->get_button_index() == BUTTON_LEFT && input_action == INPUT_PAINT)) { + if ((mb->get_button_index() == BUTTON_RIGHT && input_action == INPUT_ERASE) || (mb->get_button_index() == BUTTON_LEFT && input_action == INPUT_PAINT)) { if (set_items.size()) { undo_redo->create_action(TTR("GridMap Paint")); @@ -650,13 +719,21 @@ bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const Ref<Inpu return set_items.size() > 0; } + if (mb->get_button_index() == BUTTON_LEFT && input_action == INPUT_SELECT) { + + undo_redo->create_action("GridMap Selection"); + undo_redo->add_do_method(this, "_set_selection", selection.active, selection.begin, selection.end); + undo_redo->add_undo_method(this, "_set_selection", last_selection.active, last_selection.begin, last_selection.end); + undo_redo->commit_action(); + } + if (mb->get_button_index() == BUTTON_LEFT && input_action != INPUT_NONE) { set_items.clear(); input_action = INPUT_NONE; return true; } - if (mb->get_button_index() == BUTTON_RIGHT && (input_action == INPUT_ERASE || input_action == INPUT_DUPLICATE)) { + if (mb->get_button_index() == BUTTON_RIGHT && (input_action == INPUT_ERASE || input_action == INPUT_PASTE)) { input_action = INPUT_NONE; return true; } @@ -670,6 +747,45 @@ bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const Ref<Inpu return do_input_action(p_camera, mm->get_position(), false); } + Ref<InputEventKey> k = p_event; + + if (k.is_valid()) { + if (k->is_pressed()) { + if (k->get_scancode() == KEY_ESCAPE) { + + if (input_action == INPUT_PASTE) { + _clear_clipboard_data(); + input_action = INPUT_NONE; + _update_paste_indicator(); + return true; + } else if (selection.active) { + _set_selection(false); + return true; + } else { + selected_palette = -1; + mesh_library_palette->unselect_all(); + update_palette(); + _update_cursor_instance(); + return true; + } + } + + if (k->get_shift() && selection.active && input_action != INPUT_PASTE) { + + if (k->get_scancode() == options->get_popup()->get_item_accelerator(options->get_popup()->get_item_index(MENU_OPTION_PREV_LEVEL))) { + selection.click[edit_axis]--; + _validate_selection(); + return true; + } + if (k->get_scancode() == options->get_popup()->get_item_accelerator(options->get_popup()->get_item_index(MENU_OPTION_NEXT_LEVEL))) { + selection.click[edit_axis]++; + _validate_selection(); + return true; + } + } + } + } + Ref<InputEventPanGesture> pan_gesture = p_event; if (pan_gesture.is_valid()) { @@ -740,28 +856,36 @@ void GridMapEditor::_icon_size_changed(float p_value) { void GridMapEditor::update_palette() { int selected = mesh_library_palette->get_current(); + float min_size = EDITOR_DEF("editors/grid_map/preview_size", 64); + min_size *= EDSCALE; + mesh_library_palette->clear(); if (display_mode == DISPLAY_THUMBNAIL) { mesh_library_palette->set_max_columns(0); mesh_library_palette->set_icon_mode(ItemList::ICON_MODE_TOP); + mesh_library_palette->set_fixed_column_width(min_size * MAX(size_slider->get_value(), 1.5)); } else if (display_mode == DISPLAY_LIST) { mesh_library_palette->set_max_columns(1); mesh_library_palette->set_icon_mode(ItemList::ICON_MODE_LEFT); + mesh_library_palette->set_fixed_column_width(0); } - float min_size = EDITOR_DEF("editors/grid_map/preview_size", 64); - min_size *= EDSCALE; mesh_library_palette->set_fixed_icon_size(Size2(min_size, min_size)); - mesh_library_palette->set_fixed_column_width(min_size * MAX(size_slider->get_value(), 1.5)); mesh_library_palette->set_max_text_lines(2); Ref<MeshLibrary> mesh_library = node->get_mesh_library(); if (mesh_library.is_null()) { last_mesh_library = NULL; + search_box->set_text(""); + search_box->set_editable(false); + info_message->show(); return; } + search_box->set_editable(true); + info_message->hide(); + Vector<int> ids; ids = mesh_library->get_item_list(); @@ -802,7 +926,7 @@ void GridMapEditor::update_palette() { item++; } - if (selected != -1) { + if (selected != -1 && mesh_library_palette->get_item_count() > 0) { mesh_library_palette->select(selected); } @@ -810,15 +934,15 @@ void GridMapEditor::update_palette() { } void GridMapEditor::edit(GridMap *p_gridmap) { + if (!p_gridmap && node) + node->disconnect("cell_size_changed", this, "_draw_grids"); node = p_gridmap; - VS *vs = VS::get_singleton(); - last_mouseover = Vector3(-1, -1, -1); input_action = INPUT_NONE; selection.active = false; _update_selection_transform(); - _update_duplicate_indicator(); + _update_paste_indicator(); spatial_editor = Object::cast_to<SpatialEditorPlugin>(editor->get_editor_plugin_screen()); @@ -839,75 +963,13 @@ void GridMapEditor::edit(GridMap *p_gridmap) { set_process(true); - Vector3 edited_floor = p_gridmap->has_meta("_editor_floor_") ? p_gridmap->get_meta("_editor_floor_") : Variant(); clip_mode = p_gridmap->has_meta("_editor_clip_") ? ClipMode(p_gridmap->get_meta("_editor_clip_").operator int()) : CLIP_DISABLED; - for (int i = 0; i < 3; i++) { - if (vs->mesh_get_surface_count(grid[i]) > 0) - vs->mesh_remove_surface(grid[i], 0); - edit_floor[i] = edited_floor[i]; - } - - { - - //update grids - indicator_mat.instance(); - indicator_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); - indicator_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); - indicator_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); - indicator_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); - indicator_mat->set_albedo(Color(0.8, 0.5, 0.1)); - - Vector<Vector3> grid_points[3]; - Vector<Color> grid_colors[3]; - - float cell_size[3] = { p_gridmap->get_cell_size().x, p_gridmap->get_cell_size().y, p_gridmap->get_cell_size().z }; - - for (int i = 0; i < 3; i++) { - - Vector3 axis; - axis[i] = 1; - Vector3 axis_n1; - axis_n1[(i + 1) % 3] = cell_size[(i + 1) % 3]; - Vector3 axis_n2; - axis_n2[(i + 2) % 3] = cell_size[(i + 2) % 3]; - - for (int j = -GRID_CURSOR_SIZE; j <= GRID_CURSOR_SIZE; j++) { - - for (int k = -GRID_CURSOR_SIZE; k <= GRID_CURSOR_SIZE; k++) { - - Vector3 p = axis_n1 * j + axis_n2 * k; - float trans = Math::pow(MAX(0, 1.0 - (Vector2(j, k).length() / GRID_CURSOR_SIZE)), 2); - - Vector3 pj = axis_n1 * (j + 1) + axis_n2 * k; - float transj = Math::pow(MAX(0, 1.0 - (Vector2(j + 1, k).length() / GRID_CURSOR_SIZE)), 2); - - Vector3 pk = axis_n1 * j + axis_n2 * (k + 1); - float transk = Math::pow(MAX(0, 1.0 - (Vector2(j, k + 1).length() / GRID_CURSOR_SIZE)), 2); - - grid_points[i].push_back(p); - grid_points[i].push_back(pk); - grid_colors[i].push_back(Color(1, 1, 1, trans)); - grid_colors[i].push_back(Color(1, 1, 1, transk)); - - grid_points[i].push_back(p); - grid_points[i].push_back(pj); - grid_colors[i].push_back(Color(1, 1, 1, trans)); - grid_colors[i].push_back(Color(1, 1, 1, transj)); - } - } - - Array d; - d.resize(VS::ARRAY_MAX); - d[VS::ARRAY_VERTEX] = grid_points[i]; - d[VS::ARRAY_COLOR] = grid_colors[i]; - VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[i], VisualServer::PRIMITIVE_LINES, d); - VisualServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat->get_rid()); - } - } - + _draw_grids(node->get_cell_size()); update_grid(); _update_clip(); + + node->connect("cell_size_changed", this, "_draw_grids"); } void GridMapEditor::_update_clip() { @@ -921,9 +983,7 @@ void GridMapEditor::_update_clip() { void GridMapEditor::update_grid() { - grid_xform.origin.x -= 1; //force update in hackish way.. what do i care - - //VS *vs = VS::get_singleton(); + grid_xform.origin.x -= 1; // Force update in hackish way. grid_ofs[edit_axis] = edit_floor[edit_axis] * node->get_cell_size()[edit_axis]; @@ -939,11 +999,67 @@ void GridMapEditor::update_grid() { updating = false; } +void GridMapEditor::_draw_grids(const Vector3 &cell_size) { + Vector3 edited_floor = node->has_meta("_editor_floor_") ? node->get_meta("_editor_floor_") : Variant(); + + for (int i = 0; i < 3; i++) { + if (VS::get_singleton()->mesh_get_surface_count(grid[i]) > 0) + VS::get_singleton()->mesh_remove_surface(grid[i], 0); + edit_floor[i] = edited_floor[i]; + } + + Vector<Vector3> grid_points[3]; + Vector<Color> grid_colors[3]; + + for (int i = 0; i < 3; i++) { + + Vector3 axis; + axis[i] = 1; + Vector3 axis_n1; + axis_n1[(i + 1) % 3] = cell_size[(i + 1) % 3]; + Vector3 axis_n2; + axis_n2[(i + 2) % 3] = cell_size[(i + 2) % 3]; + + for (int j = -GRID_CURSOR_SIZE; j <= GRID_CURSOR_SIZE; j++) { + + for (int k = -GRID_CURSOR_SIZE; k <= GRID_CURSOR_SIZE; k++) { + + Vector3 p = axis_n1 * j + axis_n2 * k; + float trans = Math::pow(MAX(0, 1.0 - (Vector2(j, k).length() / GRID_CURSOR_SIZE)), 2); + + Vector3 pj = axis_n1 * (j + 1) + axis_n2 * k; + float transj = Math::pow(MAX(0, 1.0 - (Vector2(j + 1, k).length() / GRID_CURSOR_SIZE)), 2); + + Vector3 pk = axis_n1 * j + axis_n2 * (k + 1); + float transk = Math::pow(MAX(0, 1.0 - (Vector2(j, k + 1).length() / GRID_CURSOR_SIZE)), 2); + + grid_points[i].push_back(p); + grid_points[i].push_back(pk); + grid_colors[i].push_back(Color(1, 1, 1, trans)); + grid_colors[i].push_back(Color(1, 1, 1, transk)); + + grid_points[i].push_back(p); + grid_points[i].push_back(pj); + grid_colors[i].push_back(Color(1, 1, 1, trans)); + grid_colors[i].push_back(Color(1, 1, 1, transj)); + } + } + + Array d; + d.resize(VS::ARRAY_MAX); + d[VS::ARRAY_VERTEX] = grid_points[i]; + d[VS::ARRAY_COLOR] = grid_colors[i]; + VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[i], VisualServer::PRIMITIVE_LINES, d); + VisualServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat->get_rid()); + } +} + void GridMapEditor::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { + get_tree()->connect("node_removed", this, "_node_removed"); mesh_library_palette->connect("item_selected", this, "_item_selected_cbk"); for (int i = 0; i < 3; i++) { @@ -953,13 +1069,16 @@ void GridMapEditor::_notification(int p_what) { } selection_instance = VisualServer::get_singleton()->instance_create2(selection_mesh, get_tree()->get_root()->get_world()->get_scenario()); - duplicate_instance = VisualServer::get_singleton()->instance_create2(duplicate_mesh, get_tree()->get_root()->get_world()->get_scenario()); + paste_instance = VisualServer::get_singleton()->instance_create2(paste_mesh, get_tree()->get_root()->get_world()->get_scenario()); _update_selection_transform(); - _update_duplicate_indicator(); + _update_paste_indicator(); } break; case NOTIFICATION_EXIT_TREE: { + get_tree()->disconnect("node_removed", this, "_node_removed"); + _clear_clipboard_data(); + for (int i = 0; i < 3; i++) { VS::get_singleton()->free(grid_instance[i]); @@ -970,9 +1089,9 @@ void GridMapEditor::_notification(int p_what) { } VisualServer::get_singleton()->free(selection_instance); - VisualServer::get_singleton()->free(duplicate_instance); + VisualServer::get_singleton()->free(paste_instance); selection_instance = RID(); - duplicate_instance = RID(); + paste_instance = RID(); } break; case NOTIFICATION_PROCESS: { @@ -1005,7 +1124,6 @@ void GridMapEditor::_notification(int p_what) { SpatialEditorPlugin *sep = Object::cast_to<SpatialEditorPlugin>(editor->get_editor_plugin_screen()); if (sep) sep->snap_cursor_to_plane(p); - //editor->get_editor_plugin_screen()->call("snap_cursor_to_plane",p); } } break; @@ -1056,6 +1174,10 @@ void GridMapEditor::_floor_changed(float p_value) { _update_selection_transform(); } +void GridMapEditor::_floor_mouse_exited() { + floor->get_line_edit()->release_focus(); +} + void GridMapEditor::_bind_methods() { ClassDB::bind_method("_text_changed", &GridMapEditor::_text_changed); @@ -1065,8 +1187,12 @@ void GridMapEditor::_bind_methods() { ClassDB::bind_method("_configure", &GridMapEditor::_configure); ClassDB::bind_method("_item_selected_cbk", &GridMapEditor::_item_selected_cbk); ClassDB::bind_method("_floor_changed", &GridMapEditor::_floor_changed); + ClassDB::bind_method("_floor_mouse_exited", &GridMapEditor::_floor_mouse_exited); + ClassDB::bind_method("_set_selection", &GridMapEditor::_set_selection); + ClassDB::bind_method("_node_removed", &GridMapEditor::_node_removed); ClassDB::bind_method(D_METHOD("_set_display_mode", "mode"), &GridMapEditor::_set_display_mode); + ClassDB::bind_method("_draw_grids", &GridMapEditor::_draw_grids); } GridMapEditor::GridMapEditor(EditorNode *p_editor) { @@ -1097,6 +1223,8 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { spatial_editor_hb->add_child(floor); floor->connect("value_changed", this, "_floor_changed"); + floor->connect("mouse_exited", this, "_floor_mouse_exited"); + floor->get_line_edit()->connect("mouse_exited", this, "_floor_mouse_exited"); spatial_editor_hb->add_child(memnew(VSeparator)); @@ -1128,18 +1256,15 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { options->get_popup()->add_item(TTR("Cursor Back Rotate Z"), MENU_OPTION_CURSOR_BACK_ROTATE_Z, KEY_MASK_SHIFT + KEY_D); options->get_popup()->add_item(TTR("Cursor Clear Rotation"), MENU_OPTION_CURSOR_CLEAR_ROTATION, KEY_W); options->get_popup()->add_separator(); - options->get_popup()->add_check_item("Duplicate Selects", MENU_OPTION_DUPLICATE_SELECTS); + options->get_popup()->add_check_item("Paste Selects", MENU_OPTION_PASTE_SELECTS); options->get_popup()->add_separator(); - options->get_popup()->add_item(TTR("Create Area"), MENU_OPTION_SELECTION_MAKE_AREA, KEY_CONTROL + KEY_C); - options->get_popup()->add_item(TTR("Create Exterior Connector"), MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR); - options->get_popup()->add_item(TTR("Erase Area"), MENU_OPTION_REMOVE_AREA); - options->get_popup()->add_separator(); - options->get_popup()->add_item(TTR("Duplicate Selection"), MENU_OPTION_SELECTION_DUPLICATE, KEY_MASK_SHIFT + KEY_C); - options->get_popup()->add_item(TTR("Clear Selection"), MENU_OPTION_SELECTION_CLEAR, KEY_MASK_SHIFT + KEY_X); - options->get_popup()->add_item(TTR("Fill Selection"), MENU_OPTION_SELECTION_FILL, KEY_MASK_SHIFT + KEY_F); + options->get_popup()->add_item(TTR("Duplicate Selection"), MENU_OPTION_SELECTION_DUPLICATE, KEY_MASK_CTRL + KEY_C); + options->get_popup()->add_item(TTR("Cut Selection"), MENU_OPTION_SELECTION_CUT, KEY_MASK_CTRL + KEY_X); + options->get_popup()->add_item(TTR("Clear Selection"), MENU_OPTION_SELECTION_CLEAR, KEY_DELETE); + options->get_popup()->add_item(TTR("Fill Selection"), MENU_OPTION_SELECTION_FILL, KEY_MASK_CTRL + KEY_F); options->get_popup()->add_separator(); - options->get_popup()->add_item(TTR("Settings"), MENU_OPTION_GRIDMAP_SETTINGS); + options->get_popup()->add_item(TTR("Settings..."), MENU_OPTION_GRIDMAP_SETTINGS); settings_dialog = memnew(ConfirmationDialog); settings_dialog->set_title(TTR("GridMap Settings")); @@ -1164,6 +1289,7 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { search_box = memnew(LineEdit); search_box->set_h_size_flags(SIZE_EXPAND_FILL); + search_box->set_placeholder(TTR("Filter meshes")); hb->add_child(search_box); search_box->connect("text_changed", this, "_text_changed"); search_box->connect("gui_input", this, "_sbox_input"); @@ -1199,6 +1325,15 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { add_child(mesh_library_palette); mesh_library_palette->set_v_size_flags(SIZE_EXPAND_FILL); + info_message = memnew(Label); + info_message->set_text(TTR("Give a MeshLibrary resource to this GridMap to use its meshes.")); + info_message->set_valign(Label::VALIGN_CENTER); + info_message->set_align(Label::ALIGN_CENTER); + info_message->set_autowrap(true); + info_message->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + info_message->set_anchors_and_margins_preset(PRESET_WIDE, PRESET_MODE_KEEP_SIZE, 8 * EDSCALE); + mesh_library_palette->add_child(info_message); + edit_axis = Vector3::AXIS_Y; edit_floor[0] = -1; edit_floor[1] = -1; @@ -1208,13 +1343,12 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { selected_palette = -1; lock_view = false; cursor_rot = 0; - last_mouseover = Vector3(-1, -1, -1); selection_mesh = VisualServer::get_singleton()->mesh_create(); - duplicate_mesh = VisualServer::get_singleton()->mesh_create(); + paste_mesh = VisualServer::get_singleton()->mesh_create(); { - //selection mesh create + // Selection mesh create. PoolVector<Vector3> lines; PoolVector<Vector3> triangles; @@ -1292,7 +1426,6 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { inner_mat.instance(); inner_mat->set_albedo(Color(0.7, 0.7, 1.0, 0.2)); - //inner_mat->set_flag(SpatialMaterial::FLAG_ONTOP, true); inner_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); inner_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); @@ -1312,19 +1445,18 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { selection_floor_mat->set_on_top_of_alpha(); selection_floor_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); selection_floor_mat->set_line_width(3.0); - //selection_floor_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); d[VS::ARRAY_VERTEX] = lines; VisualServer::get_singleton()->mesh_add_surface_from_arrays(selection_mesh, VS::PRIMITIVE_LINES, d); VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh, 1, outer_mat->get_rid()); d[VS::ARRAY_VERTEX] = triangles; - VisualServer::get_singleton()->mesh_add_surface_from_arrays(duplicate_mesh, VS::PRIMITIVE_TRIANGLES, d); - VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh, 0, inner_mat->get_rid()); + VisualServer::get_singleton()->mesh_add_surface_from_arrays(paste_mesh, VS::PRIMITIVE_TRIANGLES, d); + VisualServer::get_singleton()->mesh_surface_set_material(paste_mesh, 0, inner_mat->get_rid()); d[VS::ARRAY_VERTEX] = lines; - VisualServer::get_singleton()->mesh_add_surface_from_arrays(duplicate_mesh, VS::PRIMITIVE_LINES, d); - VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh, 1, outer_mat->get_rid()); + VisualServer::get_singleton()->mesh_add_surface_from_arrays(paste_mesh, VS::PRIMITIVE_LINES, d); + VisualServer::get_singleton()->mesh_surface_set_material(paste_mesh, 1, outer_mat->get_rid()); for (int i = 0; i < 3; i++) { d[VS::ARRAY_VERTEX] = square[i]; @@ -1334,13 +1466,22 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { } } - selection.active = false; + _set_selection(false); updating = false; accumulated_floor_delta = 0.0; + + indicator_mat.instance(); + indicator_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); + indicator_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); + indicator_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); + indicator_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); + indicator_mat->set_albedo(Color(0.8, 0.5, 0.1)); } GridMapEditor::~GridMapEditor() { + _clear_clipboard_data(); + for (int i = 0; i < 3; i++) { if (grid[i].is_valid()) @@ -1359,9 +1500,9 @@ GridMapEditor::~GridMapEditor() { if (selection_instance.is_valid()) VisualServer::get_singleton()->free(selection_instance); - VisualServer::get_singleton()->free(duplicate_mesh); - if (duplicate_instance.is_valid()) - VisualServer::get_singleton()->free(duplicate_instance); + VisualServer::get_singleton()->free(paste_mesh); + if (paste_instance.is_valid()) + VisualServer::get_singleton()->free(paste_instance); } void GridMapEditorPlugin::_notification(int p_what) { diff --git a/modules/gridmap/grid_map_editor_plugin.h b/modules/gridmap/grid_map_editor_plugin.h index 59b8ac13da..42e62f2842 100644 --- a/modules/gridmap/grid_map_editor_plugin.h +++ b/modules/gridmap/grid_map_editor_plugin.h @@ -35,9 +35,6 @@ #include "editor/editor_plugin.h" #include "editor/pane_drag.h" #include "grid_map.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ class SpatialEditorPlugin; @@ -54,9 +51,9 @@ class GridMapEditor : public VBoxContainer { INPUT_NONE, INPUT_PAINT, INPUT_ERASE, - INPUT_COPY, + INPUT_PICK, INPUT_SELECT, - INPUT_DUPLICATE, + INPUT_PASTE, }; enum ClipMode { @@ -116,8 +113,17 @@ class GridMapEditor : public VBoxContainer { RID selection_instance; RID selection_level_mesh[3]; RID selection_level_instance[3]; - RID duplicate_mesh; - RID duplicate_instance; + RID paste_mesh; + RID paste_instance; + + struct ClipboardItem { + int cell_item; + Vector3 grid_offset; + int orientation; + RID instance; + }; + + List<ClipboardItem> clipboard_items; Ref<SpatialMaterial> indicator_mat; Ref<SpatialMaterial> inner_mat; @@ -132,15 +138,24 @@ class GridMapEditor : public VBoxContainer { Vector3 current; Vector3 begin; Vector3 end; - int duplicate_rot; bool active; } selection; + Selection last_selection; + + struct PasteIndicator { + + Vector3 click; + Vector3 current; + Vector3 begin; + Vector3 end; + int orientation; + }; + PasteIndicator paste_indicator; bool cursor_visible; Transform cursor_transform; Vector3 cursor_origin; - Vector3 last_mouseover; int display_mode; int selected_palette; @@ -148,7 +163,6 @@ class GridMapEditor : public VBoxContainer { enum Menu { - MENU_OPTION_CONFIGURE, MENU_OPTION_NEXT_LEVEL, MENU_OPTION_PREV_LEVEL, MENU_OPTION_LOCK_VIEW, @@ -165,13 +179,11 @@ class GridMapEditor : public VBoxContainer { MENU_OPTION_CURSOR_BACK_ROTATE_X, MENU_OPTION_CURSOR_BACK_ROTATE_Z, MENU_OPTION_CURSOR_CLEAR_ROTATION, - MENU_OPTION_DUPLICATE_SELECTS, - MENU_OPTION_SELECTION_MAKE_AREA, - MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR, + MENU_OPTION_PASTE_SELECTS, MENU_OPTION_SELECTION_DUPLICATE, + MENU_OPTION_SELECTION_CUT, MENU_OPTION_SELECTION_CLEAR, MENU_OPTION_SELECTION_FILL, - MENU_OPTION_REMOVE_AREA, MENU_OPTION_GRIDMAP_SETTINGS }; @@ -184,12 +196,17 @@ class GridMapEditor : public VBoxContainer { RID instance; }; - void update_grid(); + ItemList *mesh_library_palette; + Label *info_message; + + EditorNode *editor; + + void update_grid(); // Change which and where the grid is displayed + void _draw_grids(const Vector3 &cell_size); void _configure(); void _menu_option(int); void update_palette(); void _set_display_mode(int p_mode); - ItemList *mesh_library_palette; void _item_selected_cbk(int idx); void _update_cursor_transform(); void _update_cursor_instance(); @@ -200,17 +217,20 @@ class GridMapEditor : public VBoxContainer { void _icon_size_changed(float p_value); - void _update_duplicate_indicator(); - void _duplicate_paste(); + void _clear_clipboard_data(); + void _set_clipboard_data(); + void _update_paste_indicator(); + void _do_paste(); void _update_selection_transform(); void _validate_selection(); + void _set_selection(bool p_active, const Vector3 &p_begin = Vector3(), const Vector3 &p_end = Vector3()); void _floor_changed(float p_value); + void _floor_mouse_exited(); void _delete_selection(); void _fill_selection(); - EditorNode *editor; bool do_input_action(Camera *p_camera, const Point2 &p_point, bool p_click); friend class GridMapEditorPlugin; diff --git a/modules/gridmap/icons/icon_grid_map.svg b/modules/gridmap/icons/icon_grid_map.svg new file mode 100644 index 0000000000..eafe1211f2 --- /dev/null +++ b/modules/gridmap/icons/icon_grid_map.svg @@ -0,0 +1,5 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<path transform="translate(0 1036.4)" d="m8 1-6 3v8l6 3 6-3v-2l-2-1-4 2-2-1v-4l2-1v-2l2-1zm4 2-2 1v2l2 1 2-1v-2z" fill="#fc9c9c" fill-opacity=".99608"/> +</g> +</svg> diff --git a/modules/hdr/image_loader_hdr.cpp b/modules/hdr/image_loader_hdr.cpp index f75a4a926a..1abf26bfee 100644 --- a/modules/hdr/image_loader_hdr.cpp +++ b/modules/hdr/image_loader_hdr.cpp @@ -37,7 +37,7 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force String header = f->get_token(); - ERR_FAIL_COND_V(header != "#?RADIANCE" && header != "#?RGBE", ERR_FILE_UNRECOGNIZED); + ERR_FAIL_COND_V_MSG(header != "#?RADIANCE" && header != "#?RGBE", ERR_FILE_UNRECOGNIZED, "Unsupported header information in HDR: " + header + "."); while (true) { String line = f->get_line(); @@ -45,12 +45,9 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force if (line == "") // empty line indicates end of header break; if (line.begins_with("FORMAT=")) { // leave option to implement other commands - if (line != "FORMAT=32-bit_rle_rgbe") { - ERR_EXPLAIN("Only 32-bit_rle_rgbe is supported for HDR files."); - return ERR_FILE_UNRECOGNIZED; - } + ERR_FAIL_COND_V_MSG(line != "FORMAT=32-bit_rle_rgbe", ERR_FILE_UNRECOGNIZED, "Only 32-bit_rle_rgbe is supported for HDR files."); } else if (!line.begins_with("#")) { // not comment - WARN_PRINTS("Ignoring unsupported header information in HDR : " + line); + WARN_PRINTS("Ignoring unsupported header information in HDR: " + line + "."); } } @@ -102,10 +99,7 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force len <<= 8; len |= f->get_8(); - if (len != width) { - ERR_EXPLAIN("invalid decoded scanline length, corrupt HDR"); - ERR_FAIL_V(ERR_FILE_CORRUPT); - } + ERR_FAIL_COND_V_MSG(len != width, ERR_FILE_CORRUPT, "Invalid decoded scanline length, corrupt HDR."); for (int k = 0; k < 4; ++k) { int i = 0; diff --git a/modules/hdr/image_loader_hdr.h b/modules/hdr/image_loader_hdr.h index 8ebf52def7..e9575ee4fb 100644 --- a/modules/hdr/image_loader_hdr.h +++ b/modules/hdr/image_loader_hdr.h @@ -33,9 +33,6 @@ #include "core/io/image_loader.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ class ImageLoaderHDR : public ImageFormatLoader { public: diff --git a/modules/jpg/SCsub b/modules/jpg/SCsub index d5f87905eb..96e8e704dd 100644 --- a/modules/jpg/SCsub +++ b/modules/jpg/SCsub @@ -13,7 +13,7 @@ thirdparty_sources = [ ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] -env_jpg.Append(CPPPATH=[thirdparty_dir]) +env_jpg.Prepend(CPPPATH=[thirdparty_dir]) env_thirdparty = env_jpg.Clone() env_thirdparty.disable_warnings() diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp index 5493223cb0..dcd8b8aebd 100644 --- a/modules/jpg/image_loader_jpegd.cpp +++ b/modules/jpg/image_loader_jpegd.cpp @@ -96,7 +96,7 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p else fmt = Image::FORMAT_RGB8; - dw = PoolVector<uint8_t>::Write(); + dw.release(); p_image->create(image_width, image_height, 0, fmt, data); return OK; @@ -117,8 +117,6 @@ Error ImageLoaderJPG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force Error err = jpeg_load_image_from_buffer(p_image.ptr(), w.ptr(), src_image_len); - w = PoolVector<uint8_t>::Write(); - return err; } diff --git a/modules/jpg/image_loader_jpegd.h b/modules/jpg/image_loader_jpegd.h index 9a96fe008d..e9016ce43e 100644 --- a/modules/jpg/image_loader_jpegd.h +++ b/modules/jpg/image_loader_jpegd.h @@ -33,9 +33,6 @@ #include "core/io/image_loader.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ class ImageLoaderJPG : public ImageFormatLoader { public: diff --git a/modules/jsonrpc/SCsub b/modules/jsonrpc/SCsub new file mode 100644 index 0000000000..13c9ffb253 --- /dev/null +++ b/modules/jsonrpc/SCsub @@ -0,0 +1,7 @@ +#!/usr/bin/env python + +Import('env') +Import('env_modules') + +env_jsonrpc = env_modules.Clone() +env_jsonrpc.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/jsonrpc/config.py b/modules/jsonrpc/config.py new file mode 100644 index 0000000000..53bc827027 --- /dev/null +++ b/modules/jsonrpc/config.py @@ -0,0 +1,5 @@ +def can_build(env, platform): + return True + +def configure(env): + pass diff --git a/modules/jsonrpc/jsonrpc.cpp b/modules/jsonrpc/jsonrpc.cpp new file mode 100644 index 0000000000..ea90cce83d --- /dev/null +++ b/modules/jsonrpc/jsonrpc.cpp @@ -0,0 +1,171 @@ +/*************************************************************************/ +/* jsonrpc.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 "jsonrpc.h" +#include "core/io/json.h" + +JSONRPC::JSONRPC() { +} + +JSONRPC::~JSONRPC() { +} + +void JSONRPC::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_scope", "scope", "target"), &JSONRPC::set_scope); + ClassDB::bind_method(D_METHOD("process_action", "action", "recurse"), &JSONRPC::process_action, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("process_string", "action"), &JSONRPC::process_string); + + ClassDB::bind_method(D_METHOD("make_request", "method", "params", "id"), &JSONRPC::make_request); + ClassDB::bind_method(D_METHOD("make_response", "result", "id"), &JSONRPC::make_response); + ClassDB::bind_method(D_METHOD("make_notification", "method", "params"), &JSONRPC::make_notification); + ClassDB::bind_method(D_METHOD("make_response_error", "code", "message", "id"), &JSONRPC::make_response_error, DEFVAL(Variant())); + + BIND_ENUM_CONSTANT(PARSE_ERROR); + BIND_ENUM_CONSTANT(INVALID_REQUEST); + BIND_ENUM_CONSTANT(METHOD_NOT_FOUND); + BIND_ENUM_CONSTANT(INVALID_PARAMS); + BIND_ENUM_CONSTANT(INTERNAL_ERROR); +} + +Dictionary JSONRPC::make_response_error(int p_code, const String &p_message, const Variant &p_id) const { + Dictionary dict; + dict["jsonrpc"] = "2.0"; + + Dictionary err; + err["code"] = p_code; + err["message"] = p_message; + + dict["error"] = err; + dict["id"] = p_id; + + return dict; +} + +Dictionary JSONRPC::make_response(const Variant &p_value, const Variant &p_id) { + Dictionary dict; + dict["jsonrpc"] = "2.0"; + dict["id"] = p_id; + dict["result"] = p_value; + return dict; +} + +Dictionary JSONRPC::make_notification(const String &p_method, const Variant &p_params) { + Dictionary dict; + dict["jsonrpc"] = "2.0"; + dict["method"] = p_method; + dict["params"] = p_params; + return dict; +} + +Dictionary JSONRPC::make_request(const String &p_method, const Variant &p_params, const Variant &p_id) { + Dictionary dict; + dict["jsonrpc"] = "2.0"; + dict["method"] = p_method; + dict["params"] = p_params; + dict["id"] = p_id; + return dict; +} + +Variant JSONRPC::process_action(const Variant &p_action, bool p_process_arr_elements) { + Variant ret; + if (p_action.get_type() == Variant::DICTIONARY) { + Dictionary dict = p_action; + String method = dict.get("method", ""); + Array args; + if (dict.has("params")) { + Variant params = dict.get("params", Variant()); + if (params.get_type() == Variant::ARRAY) { + args = params; + } else { + args.push_back(params); + } + } + + Object *object = this; + if (method_scopes.has(method.get_base_dir())) { + object = method_scopes[method.get_base_dir()]; + method = method.get_file(); + } + + Variant id; + if (dict.has("id")) { + id = dict["id"]; + } + + if (object == NULL || !object->has_method(method)) { + ret = make_response_error(JSONRPC::METHOD_NOT_FOUND, "Method not found", id); + } else { + Variant call_ret = object->callv(method, args); + if (id.get_type() != Variant::NIL) { + ret = make_response(call_ret, id); + } + } + } else if (p_action.get_type() == Variant::ARRAY && p_process_arr_elements) { + Array arr = p_action; + int size = arr.size(); + if (size) { + Array arr_ret; + for (int i = 0; i < size; i++) { + const Variant &var = arr.get(i); + arr_ret.push_back(process_action(var)); + } + ret = arr_ret; + } else { + ret = make_response_error(JSONRPC::INVALID_REQUEST, "Invalid Request"); + } + } else { + ret = make_response_error(JSONRPC::INVALID_REQUEST, "Invalid Request"); + } + return ret; +} + +String JSONRPC::process_string(const String &p_input) { + + if (p_input.empty()) return String(); + + Variant ret; + Variant input; + String err_message; + int err_line; + if (OK != JSON::parse(p_input, input, err_message, err_line)) { + ret = make_response_error(JSONRPC::PARSE_ERROR, "Parse error"); + } else { + ret = process_action(input, true); + } + + if (ret.get_type() == Variant::NIL) { + return ""; + } + return JSON::print(ret); +} + +void JSONRPC::set_scope(const String &p_scope, Object *p_obj) { + method_scopes[p_scope] = p_obj; +} diff --git a/modules/jsonrpc/jsonrpc.h b/modules/jsonrpc/jsonrpc.h new file mode 100644 index 0000000000..91897d0b55 --- /dev/null +++ b/modules/jsonrpc/jsonrpc.h @@ -0,0 +1,70 @@ +/*************************************************************************/ +/* jsonrpc.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 GODOT_JSON_RPC_H +#define GODOT_JSON_RPC_H + +#include "core/object.h" +#include "core/variant.h" + +class JSONRPC : public Object { + GDCLASS(JSONRPC, Object) + + Map<String, Object *> method_scopes; + +protected: + static void _bind_methods(); + +public: + JSONRPC(); + ~JSONRPC(); + + enum ErrorCode { + PARSE_ERROR = -32700, + INVALID_REQUEST = -32600, + METHOD_NOT_FOUND = -32601, + INVALID_PARAMS = -32602, + INTERNAL_ERROR = -32603, + }; + + Dictionary make_response_error(int p_code, const String &p_message, const Variant &p_id = Variant()) const; + Dictionary make_response(const Variant &p_value, const Variant &p_id); + Dictionary make_notification(const String &p_method, const Variant &p_params); + Dictionary make_request(const String &p_method, const Variant &p_params, const Variant &p_id); + + Variant process_action(const Variant &p_action, bool p_process_arr_elements = false); + String process_string(const String &p_input); + + void set_scope(const String &p_scope, Object *p_obj); +}; + +VARIANT_ENUM_CAST(JSONRPC::ErrorCode); + +#endif diff --git a/modules/jsonrpc/register_types.cpp b/modules/jsonrpc/register_types.cpp new file mode 100644 index 0000000000..242b0e9df4 --- /dev/null +++ b/modules/jsonrpc/register_types.cpp @@ -0,0 +1,40 @@ +/*************************************************************************/ +/* register_types.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 "register_types.h" +#include "core/class_db.h" +#include "jsonrpc.h" + +void register_jsonrpc_types() { + ClassDB::register_class<JSONRPC>(); +} + +void unregister_jsonrpc_types() { +} diff --git a/modules/jsonrpc/register_types.h b/modules/jsonrpc/register_types.h new file mode 100644 index 0000000000..e4648b901f --- /dev/null +++ b/modules/jsonrpc/register_types.h @@ -0,0 +1,32 @@ +/*************************************************************************/ +/* register_types.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. */ +/*************************************************************************/ + +void register_jsonrpc_types(); +void unregister_jsonrpc_types(); diff --git a/modules/mbedtls/crypto_mbedtls.cpp b/modules/mbedtls/crypto_mbedtls.cpp new file mode 100644 index 0000000000..62912d1459 --- /dev/null +++ b/modules/mbedtls/crypto_mbedtls.cpp @@ -0,0 +1,284 @@ +/*************************************************************************/ +/* crypto_mbedtls.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 "crypto_mbedtls.h" + +#include "core/os/file_access.h" + +#include "core/engine.h" +#include "core/io/certs_compressed.gen.h" +#include "core/io/compression.h" +#include "core/project_settings.h" + +#ifdef TOOLS_ENABLED +#include "editor/editor_settings.h" +#endif +#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n" +#define PEM_END_CRT "-----END CERTIFICATE-----\n" + +#include "mbedtls/pem.h" +#include <mbedtls/debug.h> + +CryptoKey *CryptoKeyMbedTLS::create() { + return memnew(CryptoKeyMbedTLS); +} + +Error CryptoKeyMbedTLS::load(String p_path) { + ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use"); + + PoolByteArray out; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open CryptoKeyMbedTLS file '" + p_path + "'."); + + int flen = f->get_len(); + out.resize(flen + 1); + { + PoolByteArray::Write w = out.write(); + f->get_buffer(w.ptr(), flen); + w[flen] = 0; //end f string + } + memdelete(f); + + int ret = mbedtls_pk_parse_key(&pkey, out.read().ptr(), out.size(), NULL, 0); + // We MUST zeroize the memory for safety! + mbedtls_platform_zeroize(out.write().ptr(), out.size()); + ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing private key '" + itos(ret) + "'."); + + return OK; +} + +Error CryptoKeyMbedTLS::save(String p_path) { + FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot save CryptoKeyMbedTLS file '" + p_path + "'."); + + unsigned char w[16000]; + memset(w, 0, sizeof(w)); + + int ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w)); + if (ret != 0) { + memdelete(f); + memset(w, 0, sizeof(w)); // Zeroize anything we might have written. + ERR_FAIL_V_MSG(FAILED, "Error writing key '" + itos(ret) + "'."); + } + + size_t len = strlen((char *)w); + f->store_buffer(w, len); + memdelete(f); + memset(w, 0, sizeof(w)); // Zeroize temporary buffer. + return OK; +} + +X509Certificate *X509CertificateMbedTLS::create() { + return memnew(X509CertificateMbedTLS); +} + +Error X509CertificateMbedTLS::load(String p_path) { + ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use"); + + PoolByteArray out; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open X509CertificateMbedTLS file '" + p_path + "'."); + + int flen = f->get_len(); + out.resize(flen + 1); + { + PoolByteArray::Write w = out.write(); + f->get_buffer(w.ptr(), flen); + w[flen] = 0; //end f string + } + memdelete(f); + + int ret = mbedtls_x509_crt_parse(&cert, out.read().ptr(), out.size()); + ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing some certificates: " + itos(ret)); + + return OK; +} + +Error X509CertificateMbedTLS::load_from_memory(const uint8_t *p_buffer, int p_len) { + ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use"); + + int ret = mbedtls_x509_crt_parse(&cert, p_buffer, p_len); + ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing certificates: " + itos(ret)); + return OK; +} + +Error X509CertificateMbedTLS::save(String p_path) { + FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot save X509CertificateMbedTLS file '" + p_path + "'."); + + mbedtls_x509_crt *crt = &cert; + while (crt) { + unsigned char w[4096]; + size_t wrote = 0; + int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote); + if (ret != 0 || wrote == 0) { + memdelete(f); + ERR_FAIL_V_MSG(FAILED, "Error writing certificate '" + itos(ret) + "'."); + } + + f->store_buffer(w, wrote - 1); // don't write the string terminator + crt = crt->next; + } + memdelete(f); + return OK; +} + +Crypto *CryptoMbedTLS::create() { + return memnew(CryptoMbedTLS); +} + +void CryptoMbedTLS::initialize_crypto() { + +#ifdef DEBUG_ENABLED + mbedtls_debug_set_threshold(1); +#endif + + Crypto::_create = create; + Crypto::_load_default_certificates = load_default_certificates; + X509CertificateMbedTLS::make_default(); + CryptoKeyMbedTLS::make_default(); +} + +void CryptoMbedTLS::finalize_crypto() { + Crypto::_create = NULL; + Crypto::_load_default_certificates = NULL; + if (default_certs) { + memdelete(default_certs); + default_certs = NULL; + } + X509CertificateMbedTLS::finalize(); + CryptoKeyMbedTLS::finalize(); +} + +CryptoMbedTLS::CryptoMbedTLS() { + mbedtls_ctr_drbg_init(&ctr_drbg); + mbedtls_entropy_init(&entropy); + int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0); + if (ret != 0) { + ERR_PRINTS(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret)); + } +} + +CryptoMbedTLS::~CryptoMbedTLS() { + mbedtls_ctr_drbg_free(&ctr_drbg); + mbedtls_entropy_free(&entropy); +} + +X509CertificateMbedTLS *CryptoMbedTLS::default_certs = NULL; + +X509CertificateMbedTLS *CryptoMbedTLS::get_default_certificates() { + return default_certs; +} + +void CryptoMbedTLS::load_default_certificates(String p_path) { + ERR_FAIL_COND(default_certs != NULL); + + default_certs = memnew(X509CertificateMbedTLS); + ERR_FAIL_COND(default_certs == NULL); + + if (p_path != "") { + // Use certs defined in project settings. + default_certs->load(p_path); + } +#ifdef BUILTIN_CERTS_ENABLED + else { + // Use builtin certs only if user did not override it in project settings. + PoolByteArray out; + out.resize(_certs_uncompressed_size + 1); + PoolByteArray::Write w = out.write(); + Compression::decompress(w.ptr(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE); + w[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator +#ifdef DEBUG_ENABLED + print_verbose("Loaded builtin certs"); +#endif + default_certs->load_from_memory(out.read().ptr(), out.size()); + } +#endif +} + +Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) { + Ref<CryptoKeyMbedTLS> out; + out.instance(); + int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)); + ERR_FAIL_COND_V(ret != 0, NULL); + ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537); + ERR_FAIL_COND_V(ret != 0, NULL); + return out; +} + +Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after) { + Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS> >(p_key); + ERR_FAIL_COND_V_MSG(key.is_null(), NULL, "Invalid private key argument."); + mbedtls_x509write_cert crt; + mbedtls_x509write_crt_init(&crt); + + mbedtls_x509write_crt_set_subject_key(&crt, &(key->pkey)); + mbedtls_x509write_crt_set_issuer_key(&crt, &(key->pkey)); + mbedtls_x509write_crt_set_subject_name(&crt, p_issuer_name.utf8().get_data()); + mbedtls_x509write_crt_set_issuer_name(&crt, p_issuer_name.utf8().get_data()); + mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3); + mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256); + + mbedtls_mpi serial; + mbedtls_mpi_init(&serial); + uint8_t rand_serial[20]; + mbedtls_ctr_drbg_random(&ctr_drbg, rand_serial, 20); + ERR_FAIL_COND_V(mbedtls_mpi_read_binary(&serial, rand_serial, 20), NULL); + mbedtls_x509write_crt_set_serial(&crt, &serial); + + mbedtls_x509write_crt_set_validity(&crt, p_not_before.utf8().get_data(), p_not_after.utf8().get_data()); + mbedtls_x509write_crt_set_basic_constraints(&crt, 1, -1); + mbedtls_x509write_crt_set_basic_constraints(&crt, 1, 0); + + unsigned char buf[4096]; + memset(buf, 0, 4096); + Ref<X509CertificateMbedTLS> out; + out.instance(); + mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg); + + int err = mbedtls_x509_crt_parse(&(out->cert), buf, 4096); + if (err != 0) { + mbedtls_mpi_free(&serial); + mbedtls_x509write_crt_free(&crt); + ERR_PRINTS("Generated invalid certificate: " + itos(err)); + return NULL; + } + + mbedtls_mpi_free(&serial); + mbedtls_x509write_crt_free(&crt); + return out; +} + +PoolByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) { + PoolByteArray out; + out.resize(p_bytes); + mbedtls_ctr_drbg_random(&ctr_drbg, out.write().ptr(), p_bytes); + return out; +} diff --git a/modules/mbedtls/crypto_mbedtls.h b/modules/mbedtls/crypto_mbedtls.h new file mode 100644 index 0000000000..06b3ecd234 --- /dev/null +++ b/modules/mbedtls/crypto_mbedtls.h @@ -0,0 +1,124 @@ +/*************************************************************************/ +/* crypto_mbedtls.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 CRYPTO_MBEDTLS_H +#define CRYPTO_MBEDTLS_H + +#include "core/crypto/crypto.h" +#include "core/resource.h" + +#include <mbedtls/ctr_drbg.h> +#include <mbedtls/entropy.h> +#include <mbedtls/ssl.h> + +class CryptoMbedTLS; +class SSLContextMbedTLS; +class CryptoKeyMbedTLS : public CryptoKey { + +private: + mbedtls_pk_context pkey; + int locks; + +public: + static CryptoKey *create(); + static void make_default() { CryptoKey::_create = create; } + static void finalize() { CryptoKey::_create = NULL; } + + virtual Error load(String p_path); + virtual Error save(String p_path); + + CryptoKeyMbedTLS() { + mbedtls_pk_init(&pkey); + locks = 0; + } + ~CryptoKeyMbedTLS() { + mbedtls_pk_free(&pkey); + } + + _FORCE_INLINE_ void lock() { locks++; } + _FORCE_INLINE_ void unlock() { locks--; } + + friend class CryptoMbedTLS; + friend class SSLContextMbedTLS; +}; + +class X509CertificateMbedTLS : public X509Certificate { + +private: + mbedtls_x509_crt cert; + int locks; + +public: + static X509Certificate *create(); + static void make_default() { X509Certificate::_create = create; } + static void finalize() { X509Certificate::_create = NULL; } + + virtual Error load(String p_path); + virtual Error load_from_memory(const uint8_t *p_buffer, int p_len); + virtual Error save(String p_path); + + X509CertificateMbedTLS() { + mbedtls_x509_crt_init(&cert); + locks = 0; + } + ~X509CertificateMbedTLS() { + mbedtls_x509_crt_free(&cert); + } + + _FORCE_INLINE_ void lock() { locks++; } + _FORCE_INLINE_ void unlock() { locks--; } + + friend class CryptoMbedTLS; + friend class SSLContextMbedTLS; +}; + +class CryptoMbedTLS : public Crypto { + +private: + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + static X509CertificateMbedTLS *default_certs; + +public: + static Crypto *create(); + static void initialize_crypto(); + static void finalize_crypto(); + static X509CertificateMbedTLS *get_default_certificates(); + static void load_default_certificates(String p_path); + + virtual PoolByteArray generate_random_bytes(int p_bytes); + virtual Ref<CryptoKey> generate_rsa(int p_bytes); + virtual Ref<X509Certificate> generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after); + + CryptoMbedTLS(); + ~CryptoMbedTLS(); +}; + +#endif // CRYPTO_MBEDTLS_H diff --git a/modules/mbedtls/register_types.cpp b/modules/mbedtls/register_types.cpp index 121ed5eb02..f7dc6c785f 100755 --- a/modules/mbedtls/register_types.cpp +++ b/modules/mbedtls/register_types.cpp @@ -30,15 +30,17 @@ #include "register_types.h" -#include "stream_peer_mbed_tls.h" +#include "crypto_mbedtls.h" +#include "stream_peer_mbedtls.h" void register_mbedtls_types() { - ClassDB::register_class<StreamPeerMbedTLS>(); + CryptoMbedTLS::initialize_crypto(); StreamPeerMbedTLS::initialize_ssl(); } void unregister_mbedtls_types() { StreamPeerMbedTLS::finalize_ssl(); + CryptoMbedTLS::finalize_crypto(); } diff --git a/modules/mbedtls/ssl_context_mbedtls.cpp b/modules/mbedtls/ssl_context_mbedtls.cpp new file mode 100644 index 0000000000..eeaf831b4a --- /dev/null +++ b/modules/mbedtls/ssl_context_mbedtls.cpp @@ -0,0 +1,151 @@ +/*************************************************************************/ +/* ssl_context_mbedtls.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 "ssl_context_mbedtls.h" + +static void my_debug(void *ctx, int level, + const char *file, int line, + const char *str) { + + printf("%s:%04d: %s", file, line, str); + fflush(stdout); +} + +Error SSLContextMbedTLS::_setup(int p_endpoint, int p_transport, int p_authmode) { + ERR_FAIL_COND_V_MSG(inited, ERR_ALREADY_IN_USE, "This SSL context is already active"); + + mbedtls_ssl_init(&ssl); + mbedtls_ssl_config_init(&conf); + mbedtls_ctr_drbg_init(&ctr_drbg); + mbedtls_entropy_init(&entropy); + inited = true; + + int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0); + if (ret != 0) { + clear(); // Never leave unusable resources around. + ERR_FAIL_V_MSG(FAILED, "mbedtls_ctr_drbg_seed returned an error" + itos(ret)); + } + + ret = mbedtls_ssl_config_defaults(&conf, p_endpoint, p_transport, MBEDTLS_SSL_PRESET_DEFAULT); + if (ret != 0) { + clear(); + ERR_FAIL_V_MSG(FAILED, "mbedtls_ssl_config_defaults returned an error" + itos(ret)); + } + mbedtls_ssl_conf_authmode(&conf, p_authmode); + mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg); + mbedtls_ssl_conf_dbg(&conf, my_debug, stdout); + return OK; +} + +Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert) { + ERR_FAIL_COND_V(!p_pkey.is_valid(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(!p_cert.is_valid(), ERR_INVALID_PARAMETER); + + Error err = _setup(MBEDTLS_SSL_IS_SERVER, p_transport, p_authmode); + ERR_FAIL_COND_V(err != OK, err); + + // Locking key and certificate(s) + pkey = p_pkey; + certs = p_cert; + if (pkey.is_valid()) + pkey->lock(); + if (certs.is_valid()) + certs->lock(); + + // Adding key and certificate + int ret = mbedtls_ssl_conf_own_cert(&conf, &(certs->cert), &(pkey->pkey)); + if (ret != 0) { + clear(); + ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Invalid cert/key combination " + itos(ret)); + } + // Adding CA chain if available. + if (certs->cert.next) { + mbedtls_ssl_conf_ca_chain(&conf, certs->cert.next, NULL); + } + mbedtls_ssl_setup(&ssl, &conf); + return OK; +} + +Error SSLContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas) { + Error err = _setup(MBEDTLS_SSL_IS_CLIENT, p_transport, p_authmode); + ERR_FAIL_COND_V(err != OK, err); + + X509CertificateMbedTLS *cas = NULL; + + if (p_valid_cas.is_valid()) { + // Locking CA certificates + certs = p_valid_cas; + certs->lock(); + cas = certs.ptr(); + } else { + // Fall back to default certificates (no need to lock those). + cas = CryptoMbedTLS::get_default_certificates(); + if (cas == NULL) { + clear(); + ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "SSL module failed to initialize!"); + } + } + + // Set valid CAs + mbedtls_ssl_conf_ca_chain(&conf, &(cas->cert), NULL); + mbedtls_ssl_setup(&ssl, &conf); + return OK; +} + +void SSLContextMbedTLS::clear() { + if (!inited) + return; + mbedtls_ssl_free(&ssl); + mbedtls_ssl_config_free(&conf); + mbedtls_ctr_drbg_free(&ctr_drbg); + mbedtls_entropy_free(&entropy); + + // Unlock and key and certificates + if (certs.is_valid()) + certs->unlock(); + certs = Ref<X509Certificate>(); + if (pkey.is_valid()) + pkey->unlock(); + pkey = Ref<CryptoKeyMbedTLS>(); + inited = false; +} + +mbedtls_ssl_context *SSLContextMbedTLS::get_context() { + ERR_FAIL_COND_V(!inited, NULL); + return &ssl; +} + +SSLContextMbedTLS::SSLContextMbedTLS() { + inited = false; +} + +SSLContextMbedTLS::~SSLContextMbedTLS() { + clear(); +} diff --git a/modules/mbedtls/ssl_context_mbedtls.h b/modules/mbedtls/ssl_context_mbedtls.h new file mode 100644 index 0000000000..e49d532912 --- /dev/null +++ b/modules/mbedtls/ssl_context_mbedtls.h @@ -0,0 +1,73 @@ +/*************************************************************************/ +/* ssl_context_mbedtls.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 SSL_CONTEXT_MBED_TLS_H +#define SSL_CONTEXT_MBED_TLS_H + +#include "crypto_mbedtls.h" + +#include "core/os/file_access.h" +#include "core/pool_vector.h" +#include "core/reference.h" + +#include <mbedtls/config.h> +#include <mbedtls/ctr_drbg.h> +#include <mbedtls/debug.h> +#include <mbedtls/entropy.h> +#include <mbedtls/ssl.h> + +class SSLContextMbedTLS : public Reference { + +protected: + bool inited; + + static PoolByteArray _read_file(String p_path); + +public: + Ref<X509CertificateMbedTLS> certs; + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_ssl_context ssl; + mbedtls_ssl_config conf; + + Ref<CryptoKeyMbedTLS> pkey; + + Error _setup(int p_endpoint, int p_transport, int p_authmode); + Error init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert); + Error init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas); + void clear(); + + mbedtls_ssl_context *get_context(); + + SSLContextMbedTLS(); + ~SSLContextMbedTLS(); +}; + +#endif // SSL_CONTEXT_MBED_TLS_H diff --git a/modules/mbedtls/stream_peer_mbed_tls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp index 45d3b86919..78e99a3a65 100755 --- a/modules/mbedtls/stream_peer_mbed_tls.cpp +++ b/modules/mbedtls/stream_peer_mbedtls.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* stream_peer_mbed_tls.cpp */ +/* stream_peer_mbedtls.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,21 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "stream_peer_mbed_tls.h" +#include "stream_peer_mbedtls.h" #include "core/io/stream_peer_tcp.h" #include "core/os/file_access.h" -#include <mbedtls/platform_util.h> - -static void my_debug(void *ctx, int level, - const char *file, int line, - const char *str) { - - printf("%s:%04d: %s", file, line, str); - fflush(stdout); -} - void _print_error(int ret) { printf("mbedtls error: returned -0x%x\n\n", -ret); fflush(stdout); @@ -88,18 +78,14 @@ int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { void StreamPeerMbedTLS::_cleanup() { - mbedtls_ssl_free(&ssl); - mbedtls_ssl_config_free(&conf); - mbedtls_ctr_drbg_free(&ctr_drbg); - mbedtls_entropy_free(&entropy); - + ssl_ctx->clear(); base = Ref<StreamPeer>(); status = STATUS_DISCONNECTED; } Error StreamPeerMbedTLS::_do_handshake() { int ret = 0; - while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) { + while ((ret = mbedtls_ssl_handshake(ssl_ctx->get_context())) != 0) { if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { // An error occurred. ERR_PRINTS("TLS handshake error: " + itos(ret)); @@ -120,41 +106,22 @@ Error StreamPeerMbedTLS::_do_handshake() { return OK; } -Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname) { +Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname, Ref<X509Certificate> p_ca_certs) { + + ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER); base = p_base; - int ret = 0; int authmode = p_validate_certs ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE; - mbedtls_ssl_init(&ssl); - mbedtls_ssl_config_init(&conf); - mbedtls_ctr_drbg_init(&ctr_drbg); - mbedtls_entropy_init(&entropy); + Error err = ssl_ctx->init_client(MBEDTLS_SSL_TRANSPORT_STREAM, authmode, p_ca_certs); + ERR_FAIL_COND_V(err != OK, err); - ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0); - if (ret != 0) { - ERR_PRINTS(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret)); - _cleanup(); - return FAILED; - } - - mbedtls_ssl_config_defaults(&conf, - MBEDTLS_SSL_IS_CLIENT, - MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT); - - mbedtls_ssl_conf_authmode(&conf, authmode); - mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL); - mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg); - mbedtls_ssl_conf_dbg(&conf, my_debug, stdout); - mbedtls_ssl_setup(&ssl, &conf); - mbedtls_ssl_set_hostname(&ssl, p_for_hostname.utf8().get_data()); - - mbedtls_ssl_set_bio(&ssl, this, bio_send, bio_recv, NULL); + mbedtls_ssl_set_hostname(ssl_ctx->get_context(), p_for_hostname.utf8().get_data()); + mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, NULL); status = STATUS_HANDSHAKING; - if ((ret = _do_handshake()) != OK) { + if (_do_handshake() != OK) { status = STATUS_ERROR_HOSTNAME_MISMATCH; return FAILED; } @@ -162,11 +129,26 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida return OK; } -Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base) { +Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain) { + + ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER); + + Error err = ssl_ctx->init_server(MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert); + ERR_FAIL_COND_V(err != OK, err); + + base = p_base; + + mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, NULL); + + status = STATUS_HANDSHAKING; + if (_do_handshake() != OK) { + return FAILED; + } + + status = STATUS_CONNECTED; return OK; } - Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) { ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED); @@ -197,7 +179,7 @@ Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, in if (p_bytes == 0) return OK; - int ret = mbedtls_ssl_write(&ssl, p_data, p_bytes); + int ret = mbedtls_ssl_write(ssl_ctx->get_context(), p_data, p_bytes); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { // Non blocking IO ret = 0; @@ -243,7 +225,7 @@ Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r r_received = 0; - int ret = mbedtls_ssl_read(&ssl, p_buffer, p_bytes); + int ret = mbedtls_ssl_read(ssl_ctx->get_context(), p_buffer, p_bytes); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { ret = 0; // non blocking io } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { @@ -273,7 +255,7 @@ void StreamPeerMbedTLS::poll() { // We could pass NULL as second parameter, but some behaviour sanitizers doesn't seem to like that. // Passing a 1 byte buffer to workaround it. uint8_t byte; - int ret = mbedtls_ssl_read(&ssl, &byte, 0); + int ret = mbedtls_ssl_read(ssl_ctx->get_context(), &byte, 0); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { // Nothing to read/write (non blocking IO) @@ -298,10 +280,11 @@ int StreamPeerMbedTLS::get_available_bytes() const { ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0); - return mbedtls_ssl_get_bytes_avail(&ssl); + return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl)); } StreamPeerMbedTLS::StreamPeerMbedTLS() { + ssl_ctx.instance(); status = STATUS_DISCONNECTED; } @@ -317,7 +300,7 @@ void StreamPeerMbedTLS::disconnect_from_stream() { Ref<StreamPeerTCP> tcp = base; if (tcp.is_valid() && tcp->get_status() == StreamPeerTCP::STATUS_CONNECTED) { // We are still connected on the socket, try to send close notify. - mbedtls_ssl_close_notify(&ssl); + mbedtls_ssl_close_notify(ssl_ctx->get_context()); } _cleanup(); @@ -333,28 +316,9 @@ StreamPeerSSL *StreamPeerMbedTLS::_create_func() { return memnew(StreamPeerMbedTLS); } -mbedtls_x509_crt StreamPeerMbedTLS::cacert; - -void StreamPeerMbedTLS::_load_certs(const PoolByteArray &p_array) { - int arr_len = p_array.size(); - PoolByteArray::Read r = p_array.read(); - int err = mbedtls_x509_crt_parse(&cacert, &r[0], arr_len); - if (err != 0) { - WARN_PRINTS("Error parsing some certificates: " + itos(err)); - } -} - void StreamPeerMbedTLS::initialize_ssl() { _create = _create_func; - load_certs_func = _load_certs; - - mbedtls_x509_crt_init(&cacert); - -#ifdef DEBUG_ENABLED - mbedtls_debug_set_threshold(1); -#endif - available = true; } @@ -362,6 +326,4 @@ void StreamPeerMbedTLS::finalize_ssl() { available = false; _create = NULL; - load_certs_func = NULL; - mbedtls_x509_crt_free(&cacert); } diff --git a/modules/mbedtls/stream_peer_mbed_tls.h b/modules/mbedtls/stream_peer_mbedtls.h index 3ddbea3ce4..eec7eab631 100755 --- a/modules/mbedtls/stream_peer_mbed_tls.h +++ b/modules/mbedtls/stream_peer_mbedtls.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* stream_peer_mbed_tls.h */ +/* stream_peer_mbedtls.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -32,16 +32,7 @@ #define STREAM_PEER_OPEN_SSL_H #include "core/io/stream_peer_ssl.h" - -#include <mbedtls/config.h> -#include <mbedtls/ctr_drbg.h> -#include <mbedtls/debug.h> -#include <mbedtls/entropy.h> -#include <mbedtls/net.h> -#include <mbedtls/ssl.h> - -#include <stdio.h> -#include <stdlib.h> +#include "ssl_context_mbedtls.h" class StreamPeerMbedTLS : public StreamPeerSSL { private: @@ -51,19 +42,13 @@ private: Ref<StreamPeer> base; static StreamPeerSSL *_create_func(); - static void _load_certs(const PoolByteArray &p_array); static int bio_recv(void *ctx, unsigned char *buf, size_t len); static int bio_send(void *ctx, const unsigned char *buf, size_t len); void _cleanup(); protected: - static mbedtls_x509_crt cacert; - - mbedtls_entropy_context entropy; - mbedtls_ctr_drbg_context ctr_drbg; - mbedtls_ssl_context ssl; - mbedtls_ssl_config conf; + Ref<SSLContextMbedTLS> ssl_ctx; static void _bind_methods(); @@ -71,8 +56,8 @@ protected: public: virtual void poll(); - virtual Error accept_stream(Ref<StreamPeer> p_base); - virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String()); + virtual Error accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain = Ref<X509Certificate>()); + virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String(), Ref<X509Certificate> p_valid_cert = Ref<X509Certificate>()); virtual Status get_status() const; virtual void disconnect_from_stream(); diff --git a/modules/mobile_vr/doc_classes/MobileVRInterface.xml b/modules/mobile_vr/doc_classes/MobileVRInterface.xml index 0a75ad4784..a132333a87 100644 --- a/modules/mobile_vr/doc_classes/MobileVRInterface.xml +++ b/modules/mobile_vr/doc_classes/MobileVRInterface.xml @@ -1,35 +1,42 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="MobileVRInterface" inherits="ARVRInterface" category="Core" version="3.2"> <brief_description> - Generic mobile VR implementation + Generic mobile VR implementation. </brief_description> <description> - This is a generic mobile VR implementation where you need to provide details about the phone and HMD used. It does not rely on any existing framework. This is the most basic interface we have. For the best effect you do need a mobile phone with a gyroscope and accelerometer. - Note that even though there is no positional tracking the camera will assume the headset is at a height of 1.85 meters. + This is a generic mobile VR implementation where you need to provide details about the phone and HMD used. It does not rely on any existing framework. This is the most basic interface we have. For the best effect, you need a mobile phone with a gyroscope and accelerometer. + Note that even though there is no positional tracking, the camera will assume the headset is at a height of 1.85 meters. You can change this by setting [member eye_height]. + You can initialise this interface as follows: + [codeblock] + var interface = ARVRServer.find_interface("Native mobile") + if interface and interface.initialize(): + get_viewport().arvr = true + [/codeblock] </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="display_to_lens" type="float" setter="set_display_to_lens" getter="get_display_to_lens"> + <member name="display_to_lens" type="float" setter="set_display_to_lens" getter="get_display_to_lens" default="4.0"> The distance between the display and the lenses inside of the device in centimeters. </member> - <member name="display_width" type="float" setter="set_display_width" getter="get_display_width"> + <member name="display_width" type="float" setter="set_display_width" getter="get_display_width" default="14.5"> The width of the display in centimeters. </member> - <member name="iod" type="float" setter="set_iod" getter="get_iod"> + <member name="eye_height" type="float" setter="set_eye_height" getter="get_eye_height" default="1.85"> + The height at which the camera is placed in relation to the ground (i.e. [ARVROrigin] node). + </member> + <member name="iod" type="float" setter="set_iod" getter="get_iod" default="6.0"> The interocular distance, also known as the interpupillary distance. The distance between the pupils of the left and right eye. </member> - <member name="k1" type="float" setter="set_k1" getter="get_k1"> + <member name="k1" type="float" setter="set_k1" getter="get_k1" default="0.215"> The k1 lens factor is one of the two constants that define the strength of the lens used and directly influences the lens distortion effect. </member> - <member name="k2" type="float" setter="set_k2" getter="get_k2"> + <member name="k2" type="float" setter="set_k2" getter="get_k2" default="0.215"> The k2 lens factor, see k1. </member> - <member name="oversample" type="float" setter="set_oversample" getter="get_oversample"> + <member name="oversample" type="float" setter="set_oversample" getter="get_oversample" default="1.5"> The oversample setting. Because of the lens distortion we have to render our buffers at a higher resolution then the screen can natively handle. A value between 1.5 and 2.0 often provides good results but at the cost of performance. </member> </members> diff --git a/modules/mobile_vr/mobile_vr_interface.cpp b/modules/mobile_vr/mobile_vr_interface.cpp index b4fbd417d7..fe107d3683 100644 --- a/modules/mobile_vr/mobile_vr_interface.cpp +++ b/modules/mobile_vr/mobile_vr_interface.cpp @@ -200,6 +200,9 @@ void MobileVRInterface::set_position_from_sensors() { }; void MobileVRInterface::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_eye_height", "eye_height"), &MobileVRInterface::set_eye_height); + ClassDB::bind_method(D_METHOD("get_eye_height"), &MobileVRInterface::get_eye_height); + ClassDB::bind_method(D_METHOD("set_iod", "iod"), &MobileVRInterface::set_iod); ClassDB::bind_method(D_METHOD("get_iod"), &MobileVRInterface::get_iod); @@ -218,6 +221,7 @@ void MobileVRInterface::_bind_methods() { ClassDB::bind_method(D_METHOD("set_k2", "k"), &MobileVRInterface::set_k2); ClassDB::bind_method(D_METHOD("get_k2"), &MobileVRInterface::get_k2); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "eye_height", PROPERTY_HINT_RANGE, "0.0,3.0,0.1"), "set_eye_height", "get_eye_height"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "iod", PROPERTY_HINT_RANGE, "4.0,10.0,0.1"), "set_iod", "get_iod"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "display_width", PROPERTY_HINT_RANGE, "5.0,25.0,0.1"), "set_display_width", "get_display_width"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "display_to_lens", PROPERTY_HINT_RANGE, "5.0,25.0,0.1"), "set_display_to_lens", "get_display_to_lens"); @@ -226,6 +230,14 @@ void MobileVRInterface::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::REAL, "k2", PROPERTY_HINT_RANGE, "0.1,10.0,0.0001"), "set_k2", "get_k2"); } +void MobileVRInterface::set_eye_height(const real_t p_eye_height) { + eye_height = p_eye_height; +} + +real_t MobileVRInterface::get_eye_height() const { + return eye_height; +} + void MobileVRInterface::set_iod(const real_t p_iod) { intraocular_dist = p_iod; }; @@ -328,6 +340,7 @@ Size2 MobileVRInterface::get_render_targetsize() { // we use half our window size Size2 target_size = OS::get_singleton()->get_window_size(); + target_size.x *= 0.5 * oversample; target_size.y *= oversample; @@ -427,6 +440,12 @@ void MobileVRInterface::process() { }; }; +void MobileVRInterface::notification(int p_what){ + _THREAD_SAFE_METHOD_ + + // nothing to do here, I guess we could pauze our sensors... +} + MobileVRInterface::MobileVRInterface() { initialized = false; diff --git a/modules/mobile_vr/mobile_vr_interface.h b/modules/mobile_vr/mobile_vr_interface.h index adc420ea5f..7fa51eecb7 100644 --- a/modules/mobile_vr/mobile_vr_interface.h +++ b/modules/mobile_vr/mobile_vr_interface.h @@ -107,6 +107,9 @@ protected: static void _bind_methods(); public: + void set_eye_height(const real_t p_eye_height); + real_t get_eye_height() const; + void set_iod(const real_t p_iod); real_t get_iod() const; @@ -139,6 +142,7 @@ public: virtual void commit_for_eye(ARVRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect); virtual void process(); + virtual void notification(int p_what); MobileVRInterface(); ~MobileVRInterface(); diff --git a/modules/mono/.gitignore b/modules/mono/.gitignore new file mode 100644 index 0000000000..fa6d00cbbb --- /dev/null +++ b/modules/mono/.gitignore @@ -0,0 +1,2 @@ +# Do not ignore solution files inside the mono module. Overrides Godot's global gitignore. +!*.sln diff --git a/modules/mono/SCsub b/modules/mono/SCsub index b6ba9b1c23..457edfaeed 100644 --- a/modules/mono/SCsub +++ b/modules/mono/SCsub @@ -1,359 +1,68 @@ #!/usr/bin/env python +import build_scripts.tls_configure as tls_configure +import build_scripts.mono_configure as mono_configure + Import('env') Import('env_modules') env_mono = env_modules.Clone() -# TODO move functions to their own modules - -def make_cs_files_header(src, dst, version_dst): - from compat import byte_to_str - - with open(dst, 'w') as header: - header.write('/* THIS FILE IS GENERATED DO NOT EDIT */\n') - header.write('#ifndef CS_COMPRESSED_H\n') - header.write('#define CS_COMPRESSED_H\n\n') - header.write('#ifdef TOOLS_ENABLED\n\n') - header.write('#include "core/map.h"\n') - header.write('#include "core/ustring.h"\n') - inserted_files = '' - import os - latest_mtime = 0 - cs_file_count = 0 - for root, _, files in os.walk(src): - files = [f for f in files if f.endswith('.cs')] - for file in files: - cs_file_count += 1 - filepath = os.path.join(root, file) - filepath_src_rel = os.path.relpath(filepath, src) - mtime = os.path.getmtime(filepath) - latest_mtime = mtime if mtime > latest_mtime else latest_mtime - with open(filepath, 'rb') as f: - buf = f.read() - decomp_size = len(buf) - import zlib - buf = zlib.compress(buf) - name = str(cs_file_count) - header.write('\n') - header.write('// ' + filepath_src_rel + '\n') - header.write('static const int _cs_' + name + '_compressed_size = ' + str(len(buf)) + ';\n') - header.write('static const int _cs_' + name + '_uncompressed_size = ' + str(decomp_size) + ';\n') - header.write('static const unsigned char _cs_' + name + '_compressed[] = { ') - for i, buf_idx in enumerate(range(len(buf))): - if i > 0: - header.write(', ') - header.write(byte_to_str(buf[buf_idx])) - inserted_files += '\tr_files.insert("' + filepath_src_rel.replace('\\', '\\\\') + '", ' \ - 'CompressedFile(_cs_' + name + '_compressed_size, ' \ - '_cs_' + name + '_uncompressed_size, ' \ - '_cs_' + name + '_compressed));\n' - header.write(' };\n') - header.write('\nstruct CompressedFile\n' '{\n' - '\tint compressed_size;\n' '\tint uncompressed_size;\n' '\tconst unsigned char* data;\n' - '\n\tCompressedFile(int p_comp_size, int p_uncomp_size, const unsigned char* p_data)\n' - '\t{\n' '\t\tcompressed_size = p_comp_size;\n' '\t\tuncompressed_size = p_uncomp_size;\n' - '\t\tdata = p_data;\n' '\t}\n' '\n\tCompressedFile() {}\n' '};\n' - '\nvoid get_compressed_files(Map<String, CompressedFile>& r_files)\n' '{\n' + inserted_files + '}\n' - ) - header.write('\n#endif // TOOLS_ENABLED\n') - header.write('\n#endif // CS_COMPRESSED_H\n') - - glue_version = int(latest_mtime) # The latest modified time will do for now - - with open(version_dst, 'w') as version_header: - version_header.write('/* THIS FILE IS GENERATED DO NOT EDIT */\n') - version_header.write('#ifndef CS_GLUE_VERSION_H\n') - version_header.write('#define CS_GLUE_VERSION_H\n\n') - version_header.write('#define CS_GLUE_VERSION UINT32_C(' + str(glue_version) + ')\n') - version_header.write('\n#endif // CS_GLUE_VERSION_H\n') - - -env_mono.add_source_files(env.modules_sources, '*.cpp') -env_mono.add_source_files(env.modules_sources, 'glue/*.cpp') -env_mono.add_source_files(env.modules_sources, 'mono_gd/*.cpp') -env_mono.add_source_files(env.modules_sources, 'utils/*.cpp') - if env['tools']: - env_mono.add_source_files(env.modules_sources, 'editor/*.cpp') # NOTE: It is safe to generate this file here, since this is still executed serially - make_cs_files_header('glue/Managed/Files', 'glue/cs_compressed.gen.h', '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) + import build_scripts.make_cs_compressed_header as make_cs_compressed_header + make_cs_compressed_header.generate_header( + 'glue/Managed/Files', + 'glue/cs_compressed.gen.h', + 'glue/cs_glue_version.gen.h' + ) # Glue sources if env_mono['mono_glue']: env_mono.Append(CPPDEFINES=['MONO_GLUE_ENABLED']) + import os.path + if not os.path.isfile('glue/mono_glue.gen.cpp'): + raise RuntimeError("Mono glue sources not found. Did you forget to run '--generate-mono-glue'?") + if env_mono['tools'] or env_mono['target'] != 'release': env_mono.Append(CPPDEFINES=['GD_MONO_HOT_RELOAD']) -# Configure TLS checks +# Configure Thread Local Storage -import tls_configure conf = Configure(env_mono) tls_configure.configure(conf) env_mono = conf.Finish() +# Configure Mono -# Build GodotSharpTools solution - - -import os - - -def find_nuget_unix(): - import os - - if 'NUGET_PATH' in os.environ: - hint_path = os.environ['NUGET_PATH'] - if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): - return hint_path - hint_path = os.path.join(hint_path, 'nuget') - if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): - return hint_path - - import os.path - import sys - - hint_dirs = ['/opt/novell/mono/bin'] - if sys.platform == 'darwin': - hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current/bin', '/usr/local/var/homebrew/linked/mono/bin'] + hint_dirs - - for hint_dir in hint_dirs: - hint_path = os.path.join(hint_dir, 'nuget') - if os.path.isfile(hint_path): - return hint_path - elif os.path.isfile(hint_path + '.exe'): - return hint_path + '.exe' - - for hint_dir in os.environ['PATH'].split(os.pathsep): - hint_dir = hint_dir.strip('"') - hint_path = os.path.join(hint_dir, 'nuget') - if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): - return hint_path - if os.path.isfile(hint_path + '.exe') and os.access(hint_path + '.exe', os.X_OK): - return hint_path + '.exe' - - return None - - -def find_nuget_windows(): - import os - - if 'NUGET_PATH' in os.environ: - hint_path = os.environ['NUGET_PATH'] - if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): - return hint_path - hint_path = os.path.join(hint_path, 'nuget.exe') - if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): - return hint_path - - import mono_reg_utils as monoreg - - mono_root = '' - bits = env['bits'] - - if bits == '32': - if os.getenv('MONO32_PREFIX'): - mono_root = os.getenv('MONO32_PREFIX') - else: - mono_root = monoreg.find_mono_root_dir(bits) - else: - if os.getenv('MONO64_PREFIX'): - mono_root = os.getenv('MONO64_PREFIX') - else: - mono_root = monoreg.find_mono_root_dir(bits) - - if mono_root: - mono_bin_dir = os.path.join(mono_root, 'bin') - nuget_mono = os.path.join(mono_bin_dir, 'nuget.bat') - - if os.path.isfile(nuget_mono): - return nuget_mono - - # Standalone NuGet - - for hint_dir in os.environ['PATH'].split(os.pathsep): - hint_dir = hint_dir.strip('"') - hint_path = os.path.join(hint_dir, 'nuget.exe') - if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): - return hint_path - - return None - - -def find_msbuild_unix(filename): - import os.path - import sys - - hint_dirs = ['/opt/novell/mono/bin'] - if sys.platform == 'darwin': - hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current/bin', '/usr/local/var/homebrew/linked/mono/bin'] + hint_dirs - - for hint_dir in hint_dirs: - hint_path = os.path.join(hint_dir, filename) - if os.path.isfile(hint_path): - return hint_path - elif os.path.isfile(hint_path + '.exe'): - return hint_path + '.exe' +mono_configure.configure(env, env_mono) - for hint_dir in os.environ['PATH'].split(os.pathsep): - hint_dir = hint_dir.strip('"') - hint_path = os.path.join(hint_dir, filename) - if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): - return hint_path - if os.path.isfile(hint_path + '.exe') and os.access(hint_path + '.exe', os.X_OK): - return hint_path + '.exe' +# Build Godot API solution - return None +if env_mono['tools'] and env_mono['mono_glue']: + import build_scripts.api_solution_build as api_solution_build + api_sln_cmd = api_solution_build.build(env_mono) +# Build GodotTools -def find_msbuild_windows(): - import mono_reg_utils as monoreg - - mono_root = '' - bits = env['bits'] - - if bits == '32': - if os.getenv('MONO32_PREFIX'): - mono_root = os.getenv('MONO32_PREFIX') - else: - mono_root = monoreg.find_mono_root_dir(bits) +if env_mono['tools']: + import build_scripts.godot_tools_build as godot_tools_build + if env_mono['mono_glue']: + godot_tools_build.build(env_mono, api_sln_cmd) else: - if os.getenv('MONO64_PREFIX'): - mono_root = os.getenv('MONO64_PREFIX') - else: - mono_root = monoreg.find_mono_root_dir(bits) - - if not mono_root: - raise RuntimeError('Cannot find mono root directory') - - framework_path = os.path.join(mono_root, 'lib', 'mono', '4.5') - mono_bin_dir = os.path.join(mono_root, 'bin') - msbuild_mono = os.path.join(mono_bin_dir, 'msbuild.bat') - - if os.path.isfile(msbuild_mono): - # The (Csc/Vbc/Fsc)ToolExe environment variables are required when - # building with Mono's MSBuild. They must point to the batch files - # in Mono's bin directory to make sure they are executed with Mono. - mono_msbuild_env = { - 'CscToolExe': os.path.join(mono_bin_dir, 'csc.bat'), - 'VbcToolExe': os.path.join(mono_bin_dir, 'vbc.bat'), - 'FscToolExe': os.path.join(mono_bin_dir, 'fsharpc.bat') - } - return (msbuild_mono, framework_path, mono_msbuild_env) - - msbuild_tools_path = monoreg.find_msbuild_tools_path_reg() - - if msbuild_tools_path: - return (os.path.join(msbuild_tools_path, 'MSBuild.exe'), framework_path, {}) - - return None - - -def mono_build_solution(source, target, env): - import subprocess - from shutil import copyfile - - sln_path = os.path.abspath(str(source[0])) - target_path = os.path.abspath(str(target[0])) - - framework_path = '' - msbuild_env = os.environ.copy() - - # Needed when running from Developer Command Prompt for VS - if 'PLATFORM' in msbuild_env: - del msbuild_env['PLATFORM'] - - # Find MSBuild - if os.name == 'nt': - msbuild_info = find_msbuild_windows() - if msbuild_info is None: - raise RuntimeError('Cannot find MSBuild executable') - msbuild_path = msbuild_info[0] - framework_path = msbuild_info[1] - msbuild_env.update(msbuild_info[2]) - else: - msbuild_path = find_msbuild_unix('msbuild') - if msbuild_path is None: - xbuild_fallback = env['xbuild_fallback'] - - if xbuild_fallback and os.name == 'nt': - print('Option \'xbuild_fallback\' not supported on Windows') - xbuild_fallback = False - - if xbuild_fallback: - print('Cannot find MSBuild executable, trying with xbuild') - print('Warning: xbuild is deprecated') - - msbuild_path = find_msbuild_unix('xbuild') + # Building without the glue sources so the Godot API solution may be missing. + # GodotTools depends on the Godot API solution. As such, we will only build + # GodotTools.ProjectEditor which doesn't depend on the Godot API solution and + # is required by the bindings generator in order to be able to generated it. + godot_tools_build.build_project_editor_only(env_mono) - if msbuild_path is None: - raise RuntimeError('Cannot find xbuild executable') - else: - raise RuntimeError('Cannot find MSBuild executable') +# Add sources - print('MSBuild path: ' + msbuild_path) - - # Find NuGet - nuget_path = find_nuget_windows() if os.name == 'nt' else find_nuget_unix() - if nuget_path is None: - raise RuntimeError('Cannot find NuGet executable') - - print('NuGet path: ' + nuget_path) - - # Do NuGet restore - - try: - subprocess.check_call([nuget_path, 'restore', sln_path]) - except subprocess.CalledProcessError: - raise RuntimeError('GodotSharpTools: NuGet restore failed') - - # Build solution - - build_config = 'Release' - - msbuild_args = [ - msbuild_path, - sln_path, - '/p:Configuration=' + build_config, - ] - - if framework_path: - msbuild_args += ['/p:FrameworkPathOverride=' + framework_path] - - try: - subprocess.check_call(msbuild_args, env=msbuild_env) - except subprocess.CalledProcessError: - raise RuntimeError('GodotSharpTools: Build failed') - - # Copy files - - src_dir = os.path.abspath(os.path.join(sln_path, os.pardir, 'bin', build_config)) - dst_dir = os.path.abspath(os.path.join(target_path, os.pardir)) - asm_file = 'GodotSharpTools.dll' - - if not os.path.isdir(dst_dir): - if os.path.exists(dst_dir): - raise RuntimeError('Target directory is a file') - os.makedirs(dst_dir) - - copyfile(os.path.join(src_dir, asm_file), os.path.join(dst_dir, asm_file)) - - # Dependencies - copyfile(os.path.join(src_dir, "DotNet.Glob.dll"), os.path.join(dst_dir, "DotNet.Glob.dll")) +env_mono.add_source_files(env.modules_sources, '*.cpp') +env_mono.add_source_files(env.modules_sources, 'glue/*.cpp') +env_mono.add_source_files(env.modules_sources, 'mono_gd/*.cpp') +env_mono.add_source_files(env.modules_sources, 'utils/*.cpp') if env['tools']: - output_dir = Dir('#bin').abspath - editor_tools_dir = os.path.join(output_dir, 'GodotSharp', 'Tools') - - mono_sln_builder = Builder(action=mono_build_solution) - env_mono.Append(BUILDERS={'MonoBuildSolution': mono_sln_builder}) - env_mono.MonoBuildSolution( - os.path.join(editor_tools_dir, 'GodotSharpTools.dll'), - 'editor/GodotSharpTools/GodotSharpTools.sln' - ) + env_mono.add_source_files(env.modules_sources, 'editor/*.cpp') diff --git a/modules/mono/__init__.py b/modules/mono/__init__.py new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/modules/mono/__init__.py diff --git a/modules/mono/build_scripts/__init__.py b/modules/mono/build_scripts/__init__.py new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/modules/mono/build_scripts/__init__.py diff --git a/modules/mono/build_scripts/api_solution_build.py b/modules/mono/build_scripts/api_solution_build.py new file mode 100644 index 0000000000..be54d0a679 --- /dev/null +++ b/modules/mono/build_scripts/api_solution_build.py @@ -0,0 +1,76 @@ +# Build the Godot API solution + +import os + +from SCons.Script import Dir + + +def build_api_solution(source, target, env): + # source and target elements are of type SCons.Node.FS.File, hence why we convert them to str + + module_dir = env['module_dir'] + + solution_path = os.path.join(module_dir, 'glue/Managed/Generated/GodotSharp.sln') + + if not os.path.isfile(solution_path): + raise RuntimeError("Godot API solution not found. Did you forget to run '--generate-mono-glue'?") + + build_config = env['solution_build_config'] + + extra_msbuild_args = ['/p:NoWarn=1591'] # Ignore missing documentation warnings + + from .solution_builder import build_solution + build_solution(env, solution_path, build_config, extra_msbuild_args=extra_msbuild_args) + + # Copy targets + + core_src_dir = os.path.abspath(os.path.join(solution_path, os.pardir, 'GodotSharp', 'bin', build_config)) + editor_src_dir = os.path.abspath(os.path.join(solution_path, os.pardir, 'GodotSharpEditor', 'bin', build_config)) + + dst_dir = os.path.abspath(os.path.join(str(target[0]), os.pardir)) + + if not os.path.isdir(dst_dir): + assert not os.path.isfile(dst_dir) + os.makedirs(dst_dir) + + def copy_target(target_path): + from shutil import copy + filename = os.path.basename(target_path) + + src_path = os.path.join(core_src_dir, filename) + if not os.path.isfile(src_path): + src_path = os.path.join(editor_src_dir, filename) + + copy(src_path, target_path) + + for scons_target in target: + copy_target(str(scons_target)) + + +def build(env_mono): + assert env_mono['tools'] + + target_filenames = [ + 'GodotSharp.dll', 'GodotSharp.pdb', 'GodotSharp.xml', + 'GodotSharpEditor.dll', 'GodotSharpEditor.pdb', 'GodotSharpEditor.xml' + ] + + depend_cmd = [] + + for build_config in ['Debug', 'Release']: + output_dir = Dir('#bin').abspath + editor_api_dir = os.path.join(output_dir, 'GodotSharp', 'Api', build_config) + + targets = [os.path.join(editor_api_dir, filename) for filename in target_filenames] + + cmd = env_mono.CommandNoCache(targets, depend_cmd, build_api_solution, + module_dir=os.getcwd(), solution_build_config=build_config) + env_mono.AlwaysBuild(cmd) + + # Make the Release build of the API solution depend on the Debug build. + # We do this in order to prevent SCons from building them in parallel, + # which can freak out MSBuild. In many cases, one of the builds would + # hang indefinitely requiring a key to be pressed for it to continue. + depend_cmd = cmd + + return depend_cmd diff --git a/modules/mono/build_scripts/godot_tools_build.py b/modules/mono/build_scripts/godot_tools_build.py new file mode 100644 index 0000000000..6e5273f5e0 --- /dev/null +++ b/modules/mono/build_scripts/godot_tools_build.py @@ -0,0 +1,115 @@ +# Build GodotTools solution + +import os + +from SCons.Script import Dir + + +def build_godot_tools(source, target, env): + # source and target elements are of type SCons.Node.FS.File, hence why we convert them to str + + module_dir = env['module_dir'] + + solution_path = os.path.join(module_dir, 'editor/GodotTools/GodotTools.sln') + build_config = 'Debug' if env['target'] == 'debug' else 'Release' + + from . solution_builder import build_solution, nuget_restore + nuget_restore(env, solution_path) + build_solution(env, solution_path, build_config) + + # Copy targets + + solution_dir = os.path.abspath(os.path.join(solution_path, os.pardir)) + + src_dir = os.path.join(solution_dir, 'GodotTools', 'bin', build_config) + dst_dir = os.path.abspath(os.path.join(str(target[0]), os.pardir)) + + if not os.path.isdir(dst_dir): + assert not os.path.isfile(dst_dir) + os.makedirs(dst_dir) + + def copy_target(target_path): + from shutil import copy + filename = os.path.basename(target_path) + copy(os.path.join(src_dir, filename), target_path) + + for scons_target in target: + copy_target(str(scons_target)) + + +def build_godot_tools_project_editor(source, target, env): + # source and target elements are of type SCons.Node.FS.File, hence why we convert them to str + + module_dir = env['module_dir'] + + project_name = 'GodotTools.ProjectEditor' + + csproj_dir = os.path.join(module_dir, 'editor/GodotTools', project_name) + csproj_path = os.path.join(csproj_dir, project_name + '.csproj') + build_config = 'Debug' if env['target'] == 'debug' else 'Release' + + from . solution_builder import build_solution, nuget_restore + + # Make sure to restore NuGet packages in the project directory for the project to find it + nuget_restore(env, os.path.join(csproj_dir, 'packages.config'), '-PackagesDirectory', + os.path.join(csproj_dir, 'packages')) + + build_solution(env, csproj_path, build_config) + + # Copy targets + + src_dir = os.path.join(csproj_dir, 'bin', build_config) + dst_dir = os.path.abspath(os.path.join(str(target[0]), os.pardir)) + + if not os.path.isdir(dst_dir): + assert not os.path.isfile(dst_dir) + os.makedirs(dst_dir) + + def copy_target(target_path): + from shutil import copy + filename = os.path.basename(target_path) + copy(os.path.join(src_dir, filename), target_path) + + for scons_target in target: + copy_target(str(scons_target)) + + +def build(env_mono, api_sln_cmd): + assert env_mono['tools'] + + output_dir = Dir('#bin').abspath + editor_tools_dir = os.path.join(output_dir, 'GodotSharp', 'Tools') + + target_filenames = [ + 'GodotTools.dll', 'GodotTools.IdeConnection.dll', 'GodotTools.BuildLogger.dll', + 'GodotTools.ProjectEditor.dll', 'DotNet.Glob.dll', 'GodotTools.Core.dll', + 'JetBrains.Annotations.dll', 'Newtonsoft.Json.dll' + ] + + if env_mono['target'] == 'debug': + target_filenames += [ + 'GodotTools.pdb', 'GodotTools.IdeConnection.pdb', 'GodotTools.BuildLogger.pdb', + 'GodotTools.ProjectEditor.pdb', 'GodotTools.Core.pdb' + ] + + targets = [os.path.join(editor_tools_dir, filename) for filename in target_filenames] + + cmd = env_mono.CommandNoCache(targets, api_sln_cmd, build_godot_tools, module_dir=os.getcwd()) + env_mono.AlwaysBuild(cmd) + + +def build_project_editor_only(env_mono): + assert env_mono['tools'] + + output_dir = Dir('#bin').abspath + editor_tools_dir = os.path.join(output_dir, 'GodotSharp', 'Tools') + + target_filenames = ['GodotTools.ProjectEditor.dll', 'DotNet.Glob.dll', 'GodotTools.Core.dll'] + + if env_mono['target'] == 'debug': + target_filenames += ['GodotTools.ProjectEditor.pdb', 'GodotTools.Core.pdb'] + + targets = [os.path.join(editor_tools_dir, filename) for filename in target_filenames] + + cmd = env_mono.CommandNoCache(targets, [], build_godot_tools_project_editor, module_dir=os.getcwd()) + env_mono.AlwaysBuild(cmd) diff --git a/modules/mono/build_scripts/make_android_mono_config.py b/modules/mono/build_scripts/make_android_mono_config.py new file mode 100644 index 0000000000..8cad204d7b --- /dev/null +++ b/modules/mono/build_scripts/make_android_mono_config.py @@ -0,0 +1,52 @@ + +def generate_compressed_config(config_src, output_dir): + import os.path + from compat import byte_to_str + + # Source file + with open(os.path.join(output_dir, 'android_mono_config.gen.cpp'), 'w') as cpp: + with open(config_src, 'rb') as f: + buf = f.read() + decompr_size = len(buf) + import zlib + buf = zlib.compress(buf) + compr_size = len(buf) + + bytes_seq_str = '' + for i, buf_idx in enumerate(range(compr_size)): + if i > 0: + bytes_seq_str += ', ' + bytes_seq_str += byte_to_str(buf[buf_idx]) + + cpp.write('''/* THIS FILE IS GENERATED DO NOT EDIT */ +#include "android_mono_config.h" + +#ifdef ANDROID_ENABLED + +#include "core/io/compression.h" +#include "core/pool_vector.h" + +namespace { + +// config +static const int config_compressed_size = %d; +static const int config_uncompressed_size = %d; +static const unsigned char config_compressed_data[] = { %s }; + +} // namespace + +String get_godot_android_mono_config() { + PoolVector<uint8_t> data; + data.resize(config_uncompressed_size); + PoolVector<uint8_t>::Write w = data.write(); + Compression::decompress(w.ptr(), config_uncompressed_size, config_compressed_data, + config_compressed_size, Compression::MODE_DEFLATE); + String s; + if (s.parse_utf8((const char *)w.ptr(), data.size())) { + ERR_FAIL_V(String()); + } + return s; +} + +#endif // ANDROID_ENABLED +''' % (compr_size, decompr_size, bytes_seq_str)) diff --git a/modules/mono/build_scripts/make_cs_compressed_header.py b/modules/mono/build_scripts/make_cs_compressed_header.py new file mode 100644 index 0000000000..ed49db5bb2 --- /dev/null +++ b/modules/mono/build_scripts/make_cs_compressed_header.py @@ -0,0 +1,62 @@ + +def generate_header(src, dst, version_dst): + from compat import byte_to_str + + with open(dst, 'w') as header: + header.write('/* THIS FILE IS GENERATED DO NOT EDIT */\n') + header.write('#ifndef CS_COMPRESSED_H\n') + header.write('#define CS_COMPRESSED_H\n\n') + header.write('#ifdef TOOLS_ENABLED\n\n') + header.write('#include "core/map.h"\n') + header.write('#include "core/ustring.h"\n') + inserted_files = '' + import os + latest_mtime = 0 + cs_file_count = 0 + for root, _, files in os.walk(src): + files = [f for f in files if f.endswith('.cs')] + for file in files: + cs_file_count += 1 + filepath = os.path.join(root, file) + filepath_src_rel = os.path.relpath(filepath, src) + mtime = os.path.getmtime(filepath) + latest_mtime = mtime if mtime > latest_mtime else latest_mtime + with open(filepath, 'rb') as f: + buf = f.read() + decompr_size = len(buf) + import zlib + buf = zlib.compress(buf) + compr_size = len(buf) + name = str(cs_file_count) + header.write('\n') + header.write('// ' + filepath_src_rel + '\n') + header.write('static const int _cs_' + name + '_compressed_size = ' + str(compr_size) + ';\n') + header.write('static const int _cs_' + name + '_uncompressed_size = ' + str(decompr_size) + ';\n') + header.write('static const unsigned char _cs_' + name + '_compressed[] = { ') + for i, buf_idx in enumerate(range(compr_size)): + if i > 0: + header.write(', ') + header.write(byte_to_str(buf[buf_idx])) + header.write(' };\n') + inserted_files += '\tr_files.insert("' + filepath_src_rel.replace('\\', '\\\\') + '", ' \ + 'GodotCsCompressedFile(_cs_' + name + '_compressed_size, ' \ + '_cs_' + name + '_uncompressed_size, ' \ + '_cs_' + name + '_compressed));\n' + header.write('\nstruct GodotCsCompressedFile\n' '{\n' + '\tint compressed_size;\n' '\tint uncompressed_size;\n' '\tconst unsigned char* data;\n' + '\n\tGodotCsCompressedFile(int p_comp_size, int p_uncomp_size, const unsigned char* p_data)\n' + '\t{\n' '\t\tcompressed_size = p_comp_size;\n' '\t\tuncompressed_size = p_uncomp_size;\n' + '\t\tdata = p_data;\n' '\t}\n' '\n\tGodotCsCompressedFile() {}\n' '};\n' + '\nvoid get_compressed_files(Map<String, GodotCsCompressedFile>& r_files)\n' '{\n' + inserted_files + '}\n' + ) + header.write('\n#endif // TOOLS_ENABLED\n') + header.write('\n#endif // CS_COMPRESSED_H\n') + + glue_version = int(latest_mtime) # The latest modified time will do for now + + with open(version_dst, 'w') as version_header: + version_header.write('/* THIS FILE IS GENERATED DO NOT EDIT */\n') + version_header.write('#ifndef CS_GLUE_VERSION_H\n') + version_header.write('#define CS_GLUE_VERSION_H\n\n') + version_header.write('#define CS_GLUE_VERSION UINT32_C(' + str(glue_version) + ')\n') + version_header.write('\n#endif // CS_GLUE_VERSION_H\n') diff --git a/modules/mono/build_scripts/mono_android_config.xml b/modules/mono/build_scripts/mono_android_config.xml new file mode 100644 index 0000000000..e79670afd2 --- /dev/null +++ b/modules/mono/build_scripts/mono_android_config.xml @@ -0,0 +1,28 @@ +<configuration> + <dllmap wordsize="32" dll="i:cygwin1.dll" target="/system/lib/libc.so" /> + <dllmap wordsize="64" dll="i:cygwin1.dll" target="/system/lib64/libc.so" /> + <dllmap wordsize="32" dll="libc" target="/system/lib/libc.so" /> + <dllmap wordsize="64" dll="libc" target="/system/lib64/libc.so" /> + <dllmap wordsize="32" dll="intl" target="/system/lib/libc.so" /> + <dllmap wordsize="64" dll="intl" target="/system/lib64/libc.so" /> + <dllmap wordsize="32" dll="libintl" target="/system/lib/libc.so" /> + <dllmap wordsize="64" dll="libintl" target="/system/lib64/libc.so" /> + <dllmap dll="MonoPosixHelper" target="libMonoPosixHelper.so" /> + <dllmap dll="System.Native" target="libmono-native.so" /> + <dllmap wordsize="32" dll="i:msvcrt" target="/system/lib/libc.so" /> + <dllmap wordsize="64" dll="i:msvcrt" target="/system/lib64/libc.so" /> + <dllmap wordsize="32" dll="i:msvcrt.dll" target="/system/lib/libc.so" /> + <dllmap wordsize="64" dll="i:msvcrt.dll" target="/system/lib64/libc.so" /> + <dllmap wordsize="32" dll="sqlite" target="/system/lib/libsqlite.so" /> + <dllmap wordsize="64" dll="sqlite" target="/system/lib64/libsqlite.so" /> + <dllmap wordsize="32" dll="sqlite3" target="/system/lib/libsqlite.so" /> + <dllmap wordsize="64" dll="sqlite3" target="/system/lib64/libsqlite.so" /> + <dllmap wordsize="32" dll="liblog" target="/system/lib/liblog.so" /> + <dllmap wordsize="64" dll="liblog" target="/system/lib64/liblog.so" /> + <dllmap dll="i:kernel32.dll"> + <dllentry dll="__Internal" name="CopyMemory" target="mono_win32_compat_CopyMemory"/> + <dllentry dll="__Internal" name="FillMemory" target="mono_win32_compat_FillMemory"/> + <dllentry dll="__Internal" name="MoveMemory" target="mono_win32_compat_MoveMemory"/> + <dllentry dll="__Internal" name="ZeroMemory" target="mono_win32_compat_ZeroMemory"/> + </dllmap> +</configuration> diff --git a/modules/mono/build_scripts/mono_configure.py b/modules/mono/build_scripts/mono_configure.py new file mode 100644 index 0000000000..89d56def7d --- /dev/null +++ b/modules/mono/build_scripts/mono_configure.py @@ -0,0 +1,470 @@ +import os +import os.path +import sys +import subprocess + +from SCons.Script import Dir, Environment + +if os.name == 'nt': + from . import mono_reg_utils as monoreg + + +android_arch_dirs = { + 'armv7': 'armeabi-v7a', + 'arm64v8': 'arm64-v8a', + 'x86': 'x86', + 'x86_64': 'x86_64' +} + + +def get_android_out_dir(env): + return os.path.join(Dir('#platform/android/java/lib/libs').abspath, + 'release' if env['target'] == 'release' else 'debug', + android_arch_dirs[env['android_arch']]) + + +def find_file_in_dir(directory, files, prefix='', extension=''): + if not extension.startswith('.'): + extension = '.' + extension + for curfile in files: + if os.path.isfile(os.path.join(directory, prefix + curfile + extension)): + return curfile + return '' + + +def copy_file(src_dir, dst_dir, name): + from shutil import copy + + src_path = os.path.join(Dir(src_dir).abspath, name) + dst_dir = Dir(dst_dir).abspath + + if not os.path.isdir(dst_dir): + os.makedirs(dst_dir) + + copy(src_path, dst_dir) + + +def is_desktop(platform): + return platform in ['windows', 'osx', 'x11', 'server', 'uwp', 'haiku'] + + +def is_unix_like(platform): + return platform in ['osx', 'x11', 'server', 'android', 'haiku'] + + +def module_supports_tools_on(platform): + return platform not in ['android', 'javascript'] + + +def find_wasm_src_dir(mono_root): + hint_dirs = [ + os.path.join(mono_root, 'src'), + os.path.join(mono_root, '../src'), + ] + for hint_dir in hint_dirs: + if os.path.isfile(os.path.join(hint_dir, 'driver.c')): + return hint_dir + return '' + + +def configure(env, env_mono): + bits = env['bits'] + is_android = env['platform'] == 'android' + is_javascript = env['platform'] == 'javascript' + + tools_enabled = env['tools'] + mono_static = env['mono_static'] + copy_mono_root = env['copy_mono_root'] + + mono_prefix = env['mono_prefix'] + + mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0'] + + is_travis = os.environ.get('TRAVIS') == 'true' + + if is_travis: + # Travis CI may have a Mono version lower than 5.12 + env_mono.Append(CPPDEFINES=['NO_PENDING_EXCEPTIONS']) + + if is_android and not env['android_arch'] in android_arch_dirs: + raise RuntimeError('This module does not support the specified \'android_arch\': ' + env['android_arch']) + + if tools_enabled and not module_supports_tools_on(env['platform']): + # TODO: + # Android: We have to add the data directory to the apk, concretely the Api and Tools folders. + raise RuntimeError('This module does not currently support building for this platform with tools enabled') + + if is_android and mono_static: + # Android: When static linking and doing something that requires libmono-native, we get a dlopen error as libmono-native seems to depend on libmonosgen-2.0 + raise RuntimeError('Statically linking Mono is not currently supported on this platform') + + if is_javascript: + mono_static = True + + if not mono_prefix and (os.getenv('MONO32_PREFIX') or os.getenv('MONO64_PREFIX')): + print("WARNING: The environment variables 'MONO32_PREFIX' and 'MONO64_PREFIX' are deprecated; use the 'mono_prefix' SCons parameter instead") + + if env['platform'] == 'windows': + mono_root = mono_prefix + + if not mono_root and os.name == 'nt': + mono_root = monoreg.find_mono_root_dir(bits) + + if not mono_root: + raise RuntimeError("Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter") + + print('Found Mono root directory: ' + mono_root) + + mono_lib_path = os.path.join(mono_root, 'lib') + + env.Append(LIBPATH=mono_lib_path) + env_mono.Prepend(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0')) + + lib_suffix = Environment()['LIBSUFFIX'] + + if mono_static: + if env.msvc: + mono_static_lib_name = 'libmono-static-sgen' + else: + mono_static_lib_name = 'libmonosgen-2.0' + + if not os.path.isfile(os.path.join(mono_lib_path, mono_static_lib_name + lib_suffix)): + raise RuntimeError('Could not find static mono library in: ' + mono_lib_path) + + if env.msvc: + env.Append(LINKFLAGS=mono_static_lib_name + lib_suffix) + + env.Append(LINKFLAGS='Mincore' + lib_suffix) + env.Append(LINKFLAGS='msvcrt' + lib_suffix) + env.Append(LINKFLAGS='LIBCMT' + lib_suffix) + env.Append(LINKFLAGS='Psapi' + lib_suffix) + else: + env.Append(LINKFLAGS=os.path.join(mono_lib_path, mono_static_lib_name + lib_suffix)) + + env.Append(LIBS=['psapi']) + env.Append(LIBS=['version']) + else: + mono_lib_name = find_file_in_dir(mono_lib_path, mono_lib_names, extension=lib_suffix) + + if not mono_lib_name: + raise RuntimeError('Could not find mono library in: ' + mono_lib_path) + + if env.msvc: + env.Append(LINKFLAGS=mono_lib_name + lib_suffix) + else: + env.Append(LIBS=[mono_lib_name]) + + mono_bin_path = os.path.join(mono_root, 'bin') + + mono_dll_name = find_file_in_dir(mono_bin_path, mono_lib_names, extension='.dll') + + if not mono_dll_name: + raise RuntimeError('Could not find mono shared library in: ' + mono_bin_path) + + copy_file(mono_bin_path, '#bin', mono_dll_name + '.dll') + else: + is_apple = (sys.platform == 'darwin' or "osxcross" in env) + + sharedlib_ext = '.dylib' if is_apple else '.so' + + mono_root = mono_prefix + mono_lib_path = '' + mono_so_name = '' + + if not mono_root and (is_android or is_javascript): + raise RuntimeError("Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter") + + if not mono_root and is_apple: + # Try with some known directories under OSX + hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current', '/usr/local/var/homebrew/linked/mono'] + for hint_dir in hint_dirs: + if os.path.isdir(hint_dir): + mono_root = hint_dir + break + + # We can't use pkg-config to link mono statically, + # but we can still use it to find the mono root directory + if not mono_root and mono_static: + mono_root = pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext) + if not mono_root: + raise RuntimeError("Building with mono_static=yes, but failed to find the mono prefix with pkg-config; " + \ + "specify one manually with the 'mono_prefix' SCons parameter") + + if mono_root: + print('Found Mono root directory: ' + mono_root) + + mono_lib_path = os.path.join(mono_root, 'lib') + + env.Append(LIBPATH=[mono_lib_path]) + env_mono.Prepend(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0')) + + mono_lib = find_file_in_dir(mono_lib_path, mono_lib_names, prefix='lib', extension='.a') + + if not mono_lib: + raise RuntimeError('Could not find mono library in: ' + mono_lib_path) + + env_mono.Append(CPPDEFINES=['_REENTRANT']) + + if mono_static: + env.Append(LINKFLAGS=['-rdynamic']) + + mono_lib_file = os.path.join(mono_lib_path, 'lib' + mono_lib + '.a') + + if is_apple: + env.Append(LINKFLAGS=['-Wl,-force_load,' + mono_lib_file]) + else: + assert is_desktop(env['platform']) or is_android or is_javascript + env.Append(LINKFLAGS=['-Wl,-whole-archive', mono_lib_file, '-Wl,-no-whole-archive']) + + if is_javascript: + env.Append(LIBS=['mono-icall-table', 'mono-native', 'mono-ilgen', 'mono-ee-interp']) + + wasm_src_dir = os.path.join(mono_root, 'src') + if not os.path.isdir(wasm_src_dir): + raise RuntimeError('Could not find mono wasm src directory') + + # Ideally this should be defined only for 'driver.c', but I can't fight scons for another 2 hours + env_mono.Append(CPPDEFINES=['CORE_BINDINGS']) + + env_mono.add_source_files(env.modules_sources, [ + os.path.join(wasm_src_dir, 'driver.c'), + os.path.join(wasm_src_dir, 'zlib-helper.c'), + os.path.join(wasm_src_dir, 'corebindings.c') + ]) + + env.Append(LINKFLAGS=[ + '--js-library', os.path.join(wasm_src_dir, 'library_mono.js'), + '--js-library', os.path.join(wasm_src_dir, 'binding_support.js'), + '--js-library', os.path.join(wasm_src_dir, 'dotnet_support.js') + ]) + else: + env.Append(LIBS=[mono_lib]) + + if is_apple: + env.Append(LIBS=['iconv', 'pthread']) + elif is_android: + pass # Nothing + elif is_javascript: + env.Append(LIBS=['m', 'rt', 'dl', 'pthread']) + else: + env.Append(LIBS=['m', 'rt', 'dl', 'pthread']) + + if not mono_static: + mono_so_name = find_file_in_dir(mono_lib_path, mono_lib_names, prefix='lib', extension=sharedlib_ext) + + if not mono_so_name: + raise RuntimeError('Could not find mono shared library in: ' + mono_lib_path) + + copy_file(mono_lib_path, '#bin', 'lib' + mono_so_name + sharedlib_ext) + else: + assert not mono_static + + # TODO: Add option to force using pkg-config + print('Mono root directory not found. Using pkg-config instead') + + env.ParseConfig('pkg-config monosgen-2 --libs') + env_mono.ParseConfig('pkg-config monosgen-2 --cflags') + + tmpenv = Environment() + tmpenv.AppendENVPath('PKG_CONFIG_PATH', os.getenv('PKG_CONFIG_PATH')) + tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L') + + for hint_dir in tmpenv['LIBPATH']: + name_found = find_file_in_dir(hint_dir, mono_lib_names, prefix='lib', extension=sharedlib_ext) + if name_found: + mono_lib_path = hint_dir + mono_so_name = name_found + break + + if not mono_so_name: + raise RuntimeError('Could not find mono shared library in: ' + str(tmpenv['LIBPATH'])) + + if not mono_static: + libs_output_dir = get_android_out_dir(env) if is_android else '#bin' + copy_file(mono_lib_path, libs_output_dir, 'lib' + mono_so_name + sharedlib_ext) + + if not tools_enabled: + if is_desktop(env['platform']): + if not mono_root: + mono_root = subprocess.check_output(['pkg-config', 'mono-2', '--variable=prefix']).decode('utf8').strip() + + make_template_dir(env, mono_root) + elif is_android: + # Compress Android Mono Config + from . import make_android_mono_config + module_dir = os.getcwd() + config_file_path = os.path.join(module_dir, 'build_scripts', 'mono_android_config.xml') + make_android_mono_config.generate_compressed_config(config_file_path, 'mono_gd/') + + # Copy the required shared libraries + copy_mono_shared_libs(env, mono_root, None) + elif is_javascript: + pass # No data directory for this platform + + if copy_mono_root: + if not mono_root: + mono_root = subprocess.check_output(['pkg-config', 'mono-2', '--variable=prefix']).decode('utf8').strip() + + if tools_enabled: + copy_mono_root_files(env, mono_root) + else: + print("Ignoring option: 'copy_mono_root'; only available for builds with 'tools' enabled.") + + +def make_template_dir(env, mono_root): + from shutil import rmtree + + platform = env['platform'] + target = env['target'] + + template_dir_name = '' + + assert is_desktop(platform) + + template_dir_name = 'data.mono.%s.%s.%s' % (platform, env['bits'], target) + + output_dir = Dir('#bin').abspath + template_dir = os.path.join(output_dir, template_dir_name) + + template_mono_root_dir = os.path.join(template_dir, 'Mono') + + if os.path.isdir(template_mono_root_dir): + rmtree(template_mono_root_dir) # Clean first + + # Copy etc/mono/ + + template_mono_config_dir = os.path.join(template_mono_root_dir, 'etc', 'mono') + copy_mono_etc_dir(mono_root, template_mono_config_dir, platform) + + # Copy the required shared libraries + + copy_mono_shared_libs(env, mono_root, template_mono_root_dir) + + +def copy_mono_root_files(env, mono_root): + from glob import glob + from shutil import copy + from shutil import rmtree + + if not mono_root: + raise RuntimeError('Mono installation directory not found') + + output_dir = Dir('#bin').abspath + editor_mono_root_dir = os.path.join(output_dir, 'GodotSharp', 'Mono') + + if os.path.isdir(editor_mono_root_dir): + rmtree(editor_mono_root_dir) # Clean first + + # Copy etc/mono/ + + editor_mono_config_dir = os.path.join(editor_mono_root_dir, 'etc', 'mono') + copy_mono_etc_dir(mono_root, editor_mono_config_dir, env['platform']) + + # Copy the required shared libraries + + copy_mono_shared_libs(env, mono_root, editor_mono_root_dir) + + # Copy framework assemblies + + mono_framework_dir = os.path.join(mono_root, 'lib', 'mono', '4.5') + mono_framework_facades_dir = os.path.join(mono_framework_dir, 'Facades') + + editor_mono_framework_dir = os.path.join(editor_mono_root_dir, 'lib', 'mono', '4.5') + editor_mono_framework_facades_dir = os.path.join(editor_mono_framework_dir, 'Facades') + + if not os.path.isdir(editor_mono_framework_dir): + os.makedirs(editor_mono_framework_dir) + if not os.path.isdir(editor_mono_framework_facades_dir): + os.makedirs(editor_mono_framework_facades_dir) + + for assembly in glob(os.path.join(mono_framework_dir, '*.dll')): + copy(assembly, editor_mono_framework_dir) + for assembly in glob(os.path.join(mono_framework_facades_dir, '*.dll')): + copy(assembly, editor_mono_framework_facades_dir) + + +def copy_mono_etc_dir(mono_root, target_mono_config_dir, platform): + from distutils.dir_util import copy_tree + from glob import glob + from shutil import copy + + if not os.path.isdir(target_mono_config_dir): + os.makedirs(target_mono_config_dir) + + mono_etc_dir = os.path.join(mono_root, 'etc', 'mono') + if not os.path.isdir(mono_etc_dir): + mono_etc_dir = '' + etc_hint_dirs = [] + if platform != 'windows': + etc_hint_dirs += ['/etc/mono', '/usr/local/etc/mono'] + if 'MONO_CFG_DIR' in os.environ: + etc_hint_dirs += [os.path.join(os.environ['MONO_CFG_DIR'], 'mono')] + for etc_hint_dir in etc_hint_dirs: + if os.path.isdir(etc_hint_dir): + mono_etc_dir = etc_hint_dir + break + if not mono_etc_dir: + raise RuntimeError('Mono installation etc directory not found') + + copy_tree(os.path.join(mono_etc_dir, '2.0'), os.path.join(target_mono_config_dir, '2.0')) + copy_tree(os.path.join(mono_etc_dir, '4.0'), os.path.join(target_mono_config_dir, '4.0')) + copy_tree(os.path.join(mono_etc_dir, '4.5'), os.path.join(target_mono_config_dir, '4.5')) + if os.path.isdir(os.path.join(mono_etc_dir, 'mconfig')): + copy_tree(os.path.join(mono_etc_dir, 'mconfig'), os.path.join(target_mono_config_dir, 'mconfig')) + + for file in glob(os.path.join(mono_etc_dir, '*')): + if os.path.isfile(file): + copy(file, target_mono_config_dir) + + +def copy_mono_shared_libs(env, mono_root, target_mono_root_dir): + from shutil import copy + + def copy_if_exists(src, dst): + if os.path.isfile(src): + copy(src, dst) + + platform = env['platform'] + + if platform == 'windows': + src_mono_bin_dir = os.path.join(mono_root, 'bin') + target_mono_bin_dir = os.path.join(target_mono_root_dir, 'bin') + + if not os.path.isdir(target_mono_bin_dir): + os.makedirs(target_mono_bin_dir) + + mono_posix_helper_name = find_file_in_dir(src_mono_bin_dir, ['MonoPosixHelper', 'libMonoPosixHelper'], extension='.dll') + copy(os.path.join(src_mono_bin_dir, mono_posix_helper_name + '.dll'), os.path.join(target_mono_bin_dir, 'MonoPosixHelper.dll')) + + # For newer versions + btls_dll_path = os.path.join(src_mono_bin_dir, 'libmono-btls-shared.dll') + if os.path.isfile(btls_dll_path): + copy(btls_dll_path, target_mono_bin_dir) + else: + target_mono_lib_dir = get_android_out_dir(env) if platform == 'android' else os.path.join(target_mono_root_dir, 'lib') + + if not os.path.isdir(target_mono_lib_dir): + os.makedirs(target_mono_lib_dir) + + if platform == 'osx': + # TODO: Make sure nothing is missing + copy(os.path.join(mono_root, 'lib', 'libMonoPosixHelper.dylib'), target_mono_lib_dir) + elif is_unix_like(platform): + lib_file_names = [lib_name + '.so' for lib_name in [ + 'libmono-btls-shared', 'libmono-ee-interp', 'libmono-native', 'libMonoPosixHelper', + 'libmono-profiler-aot', 'libmono-profiler-coverage', 'libmono-profiler-log', 'libMonoSupportW' + ]] + + for lib_file_name in lib_file_names: + copy_if_exists(os.path.join(mono_root, 'lib', lib_file_name), target_mono_lib_dir) + + +def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext): + tmpenv = Environment() + tmpenv.AppendENVPath('PKG_CONFIG_PATH', os.getenv('PKG_CONFIG_PATH')) + tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L') + for hint_dir in tmpenv['LIBPATH']: + name_found = find_file_in_dir(hint_dir, mono_lib_names, prefix='lib', extension=sharedlib_ext) + if name_found and os.path.isdir(os.path.join(hint_dir, '..', 'include', 'mono-2.0')): + return os.path.join(hint_dir, '..') + return '' diff --git a/modules/mono/mono_reg_utils.py b/modules/mono/build_scripts/mono_reg_utils.py index 583708bf07..b2c48f0a61 100644 --- a/modules/mono/mono_reg_utils.py +++ b/modules/mono/build_scripts/mono_reg_utils.py @@ -116,5 +116,3 @@ def find_msbuild_tools_path_reg(): return value except (WindowsError, OSError): return '' - - return '' diff --git a/modules/mono/build_scripts/solution_builder.py b/modules/mono/build_scripts/solution_builder.py new file mode 100644 index 0000000000..d1529a64d2 --- /dev/null +++ b/modules/mono/build_scripts/solution_builder.py @@ -0,0 +1,214 @@ + +import os + + +verbose = False + + +def find_nuget_unix(): + import os + + if 'NUGET_PATH' in os.environ: + hint_path = os.environ['NUGET_PATH'] + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + hint_path = os.path.join(hint_path, 'nuget') + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + + import os.path + import sys + + hint_dirs = ['/opt/novell/mono/bin'] + if sys.platform == 'darwin': + hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current/bin', '/usr/local/var/homebrew/linked/mono/bin'] + hint_dirs + + for hint_dir in hint_dirs: + hint_path = os.path.join(hint_dir, 'nuget') + if os.path.isfile(hint_path): + return hint_path + elif os.path.isfile(hint_path + '.exe'): + return hint_path + '.exe' + + for hint_dir in os.environ['PATH'].split(os.pathsep): + hint_dir = hint_dir.strip('"') + hint_path = os.path.join(hint_dir, 'nuget') + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + if os.path.isfile(hint_path + '.exe') and os.access(hint_path + '.exe', os.X_OK): + return hint_path + '.exe' + + return None + + +def find_nuget_windows(env): + import os + + if 'NUGET_PATH' in os.environ: + hint_path = os.environ['NUGET_PATH'] + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + hint_path = os.path.join(hint_path, 'nuget.exe') + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + + from . mono_reg_utils import find_mono_root_dir + + mono_root = env['mono_prefix'] or find_mono_root_dir(env['bits']) + + if mono_root: + mono_bin_dir = os.path.join(mono_root, 'bin') + nuget_mono = os.path.join(mono_bin_dir, 'nuget.bat') + + if os.path.isfile(nuget_mono): + return nuget_mono + + # Standalone NuGet + + for hint_dir in os.environ['PATH'].split(os.pathsep): + hint_dir = hint_dir.strip('"') + hint_path = os.path.join(hint_dir, 'nuget.exe') + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + + return None + + +def find_msbuild_unix(filename): + import os.path + import sys + + hint_dirs = ['/opt/novell/mono/bin'] + if sys.platform == 'darwin': + hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current/bin', '/usr/local/var/homebrew/linked/mono/bin'] + hint_dirs + + for hint_dir in hint_dirs: + hint_path = os.path.join(hint_dir, filename) + if os.path.isfile(hint_path): + return hint_path + elif os.path.isfile(hint_path + '.exe'): + return hint_path + '.exe' + + for hint_dir in os.environ['PATH'].split(os.pathsep): + hint_dir = hint_dir.strip('"') + hint_path = os.path.join(hint_dir, filename) + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + if os.path.isfile(hint_path + '.exe') and os.access(hint_path + '.exe', os.X_OK): + return hint_path + '.exe' + + return None + + +def find_msbuild_windows(env): + from . mono_reg_utils import find_mono_root_dir, find_msbuild_tools_path_reg + + mono_root = env['mono_prefix'] or find_mono_root_dir(env['bits']) + + if not mono_root: + raise RuntimeError('Cannot find mono root directory') + + mono_bin_dir = os.path.join(mono_root, 'bin') + msbuild_mono = os.path.join(mono_bin_dir, 'msbuild.bat') + + msbuild_tools_path = find_msbuild_tools_path_reg() + + if msbuild_tools_path: + return (os.path.join(msbuild_tools_path, 'MSBuild.exe'), {}) + + if os.path.isfile(msbuild_mono): + # The (Csc/Vbc/Fsc)ToolExe environment variables are required when + # building with Mono's MSBuild. They must point to the batch files + # in Mono's bin directory to make sure they are executed with Mono. + mono_msbuild_env = { + 'CscToolExe': os.path.join(mono_bin_dir, 'csc.bat'), + 'VbcToolExe': os.path.join(mono_bin_dir, 'vbc.bat'), + 'FscToolExe': os.path.join(mono_bin_dir, 'fsharpc.bat') + } + return (msbuild_mono, mono_msbuild_env) + + return None + + +def run_command(command, args, env_override=None, name=None): + def cmd_args_to_str(cmd_args): + return ' '.join([arg if not ' ' in arg else '"%s"' % arg for arg in cmd_args]) + + args = [command] + args + + if name is None: + name = os.path.basename(command) + + if verbose: + print("Running '%s': %s" % (name, cmd_args_to_str(args))) + + import subprocess + try: + if env_override is None: + subprocess.check_call(args) + else: + subprocess.check_call(args, env=env_override) + except subprocess.CalledProcessError as e: + raise RuntimeError("'%s' exited with error code: %s" % (name, e.returncode)) + + +def nuget_restore(env, *args): + global verbose + verbose = env['verbose'] + + # Find NuGet + nuget_path = find_nuget_windows(env) if os.name == 'nt' else find_nuget_unix() + if nuget_path is None: + raise RuntimeError('Cannot find NuGet executable') + + print('NuGet path: ' + nuget_path) + + # Do NuGet restore + run_command(nuget_path, ['restore'] + list(args), name='nuget restore') + + +def build_solution(env, solution_path, build_config, extra_msbuild_args=[]): + global verbose + verbose = env['verbose'] + + msbuild_env = os.environ.copy() + + # Needed when running from Developer Command Prompt for VS + if 'PLATFORM' in msbuild_env: + del msbuild_env['PLATFORM'] + + # Find MSBuild + if os.name == 'nt': + msbuild_info = find_msbuild_windows(env) + if msbuild_info is None: + raise RuntimeError('Cannot find MSBuild executable') + msbuild_path = msbuild_info[0] + msbuild_env.update(msbuild_info[1]) + else: + msbuild_path = find_msbuild_unix('msbuild') + if msbuild_path is None: + xbuild_fallback = env['xbuild_fallback'] + + if xbuild_fallback and os.name == 'nt': + print('Option \'xbuild_fallback\' not supported on Windows') + xbuild_fallback = False + + if xbuild_fallback: + print('Cannot find MSBuild executable, trying with xbuild') + print('Warning: xbuild is deprecated') + + msbuild_path = find_msbuild_unix('xbuild') + + if msbuild_path is None: + raise RuntimeError('Cannot find xbuild executable') + else: + raise RuntimeError('Cannot find MSBuild executable') + + print('MSBuild path: ' + msbuild_path) + + # Build solution + + msbuild_args = [solution_path, '/p:Configuration=' + build_config] + msbuild_args += extra_msbuild_args + + run_command(msbuild_path, msbuild_args, env_override=msbuild_env, name='msbuild') diff --git a/modules/mono/tls_configure.py b/modules/mono/build_scripts/tls_configure.py index 622280b00b..622280b00b 100644 --- a/modules/mono/tls_configure.py +++ b/modules/mono/build_scripts/tls_configure.py diff --git a/modules/mono/class_db_api_json.cpp b/modules/mono/class_db_api_json.cpp new file mode 100644 index 0000000000..bbc779601e --- /dev/null +++ b/modules/mono/class_db_api_json.cpp @@ -0,0 +1,246 @@ +/*************************************************************************/ +/* class_db_api_json.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 "class_db_api_json.h" + +#ifdef DEBUG_METHODS_ENABLED + +#include "core/io/json.h" +#include "core/os/file_access.h" +#include "core/project_settings.h" +#include "core/version.h" + +void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { + Dictionary classes_dict; + + List<StringName> names; + + const StringName *k = NULL; + + while ((k = ClassDB::classes.next(k))) { + + names.push_back(*k); + } + //must be alphabetically sorted for hash to compute + names.sort_custom<StringName::AlphCompare>(); + + for (List<StringName>::Element *E = names.front(); E; E = E->next()) { + + ClassDB::ClassInfo *t = ClassDB::classes.getptr(E->get()); + ERR_FAIL_COND(!t); + if (t->api != p_api || !t->exposed) + continue; + + Dictionary class_dict; + classes_dict[t->name] = class_dict; + + class_dict["inherits"] = t->inherits; + + { //methods + + List<StringName> snames; + + k = NULL; + + while ((k = t->method_map.next(k))) { + + snames.push_back(*k); + } + + snames.sort_custom<StringName::AlphCompare>(); + + Array methods; + + for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { + Dictionary method_dict; + methods.push_back(method_dict); + + MethodBind *mb = t->method_map[F->get()]; + method_dict["name"] = mb->get_name(); + method_dict["argument_count"] = mb->get_argument_count(); + method_dict["return_type"] = mb->get_argument_type(-1); + + Array arguments; + method_dict["arguments"] = arguments; + + for (int i = 0; i < mb->get_argument_count(); i++) { + Dictionary argument_dict; + arguments.push_back(argument_dict); + const PropertyInfo info = mb->get_argument_info(i); + argument_dict["type"] = info.type; + argument_dict["name"] = info.name; + argument_dict["hint"] = info.hint; + argument_dict["hint_string"] = info.hint_string; + } + + method_dict["default_argument_count"] = mb->get_default_argument_count(); + + Array default_arguments; + method_dict["default_arguments"] = default_arguments; + + for (int i = 0; i < mb->get_default_argument_count(); i++) { + Dictionary default_argument_dict; + default_arguments.push_back(default_argument_dict); + //hash should not change, i hope for tis + Variant da = mb->get_default_argument(i); + default_argument_dict["value"] = da; + } + + method_dict["hint_flags"] = mb->get_hint_flags(); + } + + if (!methods.empty()) { + class_dict["methods"] = methods; + } + } + + { //constants + + List<StringName> snames; + + k = NULL; + + while ((k = t->constant_map.next(k))) { + + snames.push_back(*k); + } + + snames.sort_custom<StringName::AlphCompare>(); + + Array constants; + + for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { + Dictionary constant_dict; + constants.push_back(constant_dict); + + constant_dict["name"] = F->get(); + constant_dict["value"] = t->constant_map[F->get()]; + } + + if (!constants.empty()) { + class_dict["constants"] = constants; + } + } + + { //signals + + List<StringName> snames; + + k = NULL; + + while ((k = t->signal_map.next(k))) { + + snames.push_back(*k); + } + + snames.sort_custom<StringName::AlphCompare>(); + + Array signals; + + for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { + Dictionary signal_dict; + signals.push_back(signal_dict); + + MethodInfo &mi = t->signal_map[F->get()]; + signal_dict["name"] = F->get(); + + Array arguments; + signal_dict["arguments"] = arguments; + for (int i = 0; i < mi.arguments.size(); i++) { + Dictionary argument_dict; + arguments.push_back(argument_dict); + argument_dict["type"] = mi.arguments[i].type; + } + } + + if (!signals.empty()) { + class_dict["signals"] = signals; + } + } + + { //properties + + List<StringName> snames; + + k = NULL; + + while ((k = t->property_setget.next(k))) { + + snames.push_back(*k); + } + + snames.sort_custom<StringName::AlphCompare>(); + + Array properties; + + for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { + Dictionary property_dict; + properties.push_back(property_dict); + + ClassDB::PropertySetGet *psg = t->property_setget.getptr(F->get()); + + property_dict["name"] = F->get(); + property_dict["setter"] = psg->setter; + property_dict["getter"] = psg->getter; + } + + if (!properties.empty()) { + class_dict["property_setget"] = properties; + } + } + + Array property_list; + + //property list + for (List<PropertyInfo>::Element *F = t->property_list.front(); F; F = F->next()) { + Dictionary property_dict; + property_list.push_back(property_dict); + + property_dict["name"] = F->get().name; + property_dict["type"] = F->get().type; + property_dict["hint"] = F->get().hint; + property_dict["hint_string"] = F->get().hint_string; + property_dict["usage"] = F->get().usage; + } + + if (!property_list.empty()) { + class_dict["property_list"] = property_list; + } + } + + FileAccessRef f = FileAccess::open(p_output_file, FileAccess::WRITE); + ERR_FAIL_COND_MSG(!f, "Cannot open file '" + p_output_file + "'."); + f->store_string(JSON::print(classes_dict, /*indent: */ "\t")); + f->close(); + + print_line(String() + "ClassDB API JSON written to: " + ProjectSettings::get_singleton()->globalize_path(p_output_file)); +} + +#endif // DEBUG_METHODS_ENABLED diff --git a/modules/mono/editor/dotnet_solution.h b/modules/mono/class_db_api_json.h index 18933364fa..9888ecfb55 100644 --- a/modules/mono/editor/dotnet_solution.h +++ b/modules/mono/class_db_api_json.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* dotnet_solution.h */ +/* class_db_api_json.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,36 +28,19 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef NET_SOLUTION_H -#define NET_SOLUTION_H +#ifndef CLASS_DB_API_JSON_H +#define CLASS_DB_API_JSON_H -#include "core/map.h" -#include "core/ustring.h" - -struct DotNetSolution { - String name; - - struct ProjectInfo { - String guid; - String relpath; // Must be relative to the solution directory - Vector<String> configs; - }; +// 'core/method_bind.h' defines DEBUG_METHODS_ENABLED, but it looks like we +// cannot include it here. That's why we include it through 'core/class_db.h'. +#include "core/class_db.h" - void add_new_project(const String &p_name, const ProjectInfo &p_project_info); - bool has_project(const String &p_name) const; - const ProjectInfo &get_project_info(const String &p_name) const; - bool remove_project(const String &p_name); +#ifdef DEBUG_METHODS_ENABLED - Error save(); - - bool set_path(const String &p_existing_path); - String get_path(); +#include "core/ustring.h" - DotNetSolution(const String &p_name); +void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api); -private: - String path; - Map<String, ProjectInfo> projects; -}; +#endif // DEBUG_METHODS_ENABLED -#endif // NET_SOLUTION_H +#endif // CLASS_DB_API_JSON_H diff --git a/modules/mono/config.py b/modules/mono/config.py index 6b88600c56..70cb464c7a 100644 --- a/modules/mono/config.py +++ b/modules/mono/config.py @@ -1,25 +1,30 @@ - -import imp -import os -import sys -import subprocess - -from distutils.version import LooseVersion -from SCons.Script import BoolVariable, Dir, Environment, Variables +def can_build(env, platform): + return True -monoreg = imp.load_source('mono_reg_utils', 'modules/mono/mono_reg_utils.py') +def configure(env): + if env['platform'] not in ['windows', 'osx', 'x11', 'server', 'android', 'haiku', 'javascript']: + raise RuntimeError('This module does not currently support building for this platform') + env.use_ptrcall = True + env.add_module_version_string('mono') -def can_build(env, platform): - if platform in ['javascript']: - return False # Not yet supported - return True + 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 is_enabled(): - # The module is disabled by default. Use module_mono_enabled=yes to enable it. - return False + if env['platform'] == 'javascript': + # Mono wasm already has zlib builtin, so we need this workaround to avoid symbol collisions + print('Compiling with Mono wasm disables \'builtin_zlib\'') + env['builtin_zlib'] = False + thirdparty_zlib_dir = "#thirdparty/zlib/" + env.Prepend(CPPPATH=[thirdparty_zlib_dir]) def get_doc_classes(): @@ -34,407 +39,6 @@ def get_doc_path(): return 'doc_classes' -def find_file_in_dir(directory, files, prefix='', extension=''): - if not extension.startswith('.'): - extension = '.' + extension - for curfile in files: - if os.path.isfile(os.path.join(directory, prefix + curfile + extension)): - return curfile - return '' - - -def copy_file(src_dir, dst_dir, name): - from shutil import copyfile - - src_path = os.path.join(src_dir, name) - dst_path = os.path.join(dst_dir, name) - - if not os.path.isdir(dst_dir): - os.mkdir(dst_dir) - - copyfile(src_path, dst_path) - - -def configure(env): - env.use_ptrcall = True - env.add_module_version_string('mono') - - envvars = Variables() - 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'] - - tools_enabled = env['tools'] - mono_static = env['mono_static'] - copy_mono_root = env['copy_mono_root'] - - mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0'] - - if env['platform'] == 'windows': - mono_root = '' - - if bits == '32': - if os.getenv('MONO32_PREFIX'): - mono_root = os.getenv('MONO32_PREFIX') - elif os.name == 'nt': - mono_root = monoreg.find_mono_root_dir(bits) - else: - if os.getenv('MONO64_PREFIX'): - mono_root = os.getenv('MONO64_PREFIX') - elif os.name == 'nt': - mono_root = monoreg.find_mono_root_dir(bits) - - if not mono_root: - raise RuntimeError('Mono installation directory not found') - - print('Found Mono root directory: ' + mono_root) - - mono_version = mono_root_try_find_mono_version(mono_root) - configure_for_mono_version(env, mono_version) - - mono_lib_path = os.path.join(mono_root, 'lib') - - env.Append(LIBPATH=mono_lib_path) - env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0')) - - if mono_static: - lib_suffix = Environment()['LIBSUFFIX'] - - if env.msvc: - mono_static_lib_name = 'libmono-static-sgen' - else: - mono_static_lib_name = 'libmonosgen-2.0' - - if not os.path.isfile(os.path.join(mono_lib_path, mono_static_lib_name + lib_suffix)): - raise RuntimeError('Could not find static mono library in: ' + mono_lib_path) - - if env.msvc: - env.Append(LINKFLAGS=mono_static_lib_name + lib_suffix) - - env.Append(LINKFLAGS='Mincore' + lib_suffix) - env.Append(LINKFLAGS='msvcrt' + lib_suffix) - env.Append(LINKFLAGS='LIBCMT' + lib_suffix) - env.Append(LINKFLAGS='Psapi' + lib_suffix) - else: - env.Append(LINKFLAGS=os.path.join(mono_lib_path, mono_static_lib_name + lib_suffix)) - - env.Append(LIBS='psapi') - env.Append(LIBS='version') - else: - mono_lib_name = find_file_in_dir(mono_lib_path, mono_lib_names, extension='.lib') - - if not mono_lib_name: - raise RuntimeError('Could not find mono library in: ' + mono_lib_path) - - if env.msvc: - env.Append(LINKFLAGS=mono_lib_name + Environment()['LIBSUFFIX']) - else: - env.Append(LIBS=mono_lib_name) - - mono_bin_path = os.path.join(mono_root, 'bin') - - mono_dll_name = find_file_in_dir(mono_bin_path, mono_lib_names, extension='.dll') - - if not mono_dll_name: - raise RuntimeError('Could not find mono shared library in: ' + mono_bin_path) - - copy_file(mono_bin_path, 'bin', mono_dll_name + '.dll') - else: - is_apple = (sys.platform == 'darwin' or "osxcross" in env) - - sharedlib_ext = '.dylib' if is_apple else '.so' - - mono_root = '' - mono_lib_path = '' - - if bits == '32': - if os.getenv('MONO32_PREFIX'): - mono_root = os.getenv('MONO32_PREFIX') - else: - if os.getenv('MONO64_PREFIX'): - mono_root = os.getenv('MONO64_PREFIX') - - if not mono_root and is_apple: - # Try with some known directories under OSX - hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current', '/usr/local/var/homebrew/linked/mono'] - for hint_dir in hint_dirs: - if os.path.isdir(hint_dir): - mono_root = hint_dir - break - - # We can't use pkg-config to link mono statically, - # but we can still use it to find the mono root directory - if not mono_root and mono_static: - mono_root = pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext) - if not mono_root: - raise RuntimeError('Building with mono_static=yes, but failed to find the mono prefix with pkg-config. Specify one manually') - - if mono_root: - print('Found Mono root directory: ' + mono_root) - - mono_version = mono_root_try_find_mono_version(mono_root) - configure_for_mono_version(env, mono_version) - - mono_lib_path = os.path.join(mono_root, 'lib') - - env.Append(LIBPATH=mono_lib_path) - env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0')) - - mono_lib = find_file_in_dir(mono_lib_path, mono_lib_names, prefix='lib', extension='.a') - - if not mono_lib: - raise RuntimeError('Could not find mono library in: ' + mono_lib_path) - - env.Append(CPPFLAGS=['-D_REENTRANT']) - - if mono_static: - mono_lib_file = os.path.join(mono_lib_path, 'lib' + mono_lib + '.a') - - if is_apple: - env.Append(LINKFLAGS=['-Wl,-force_load,' + mono_lib_file]) - else: - env.Append(LINKFLAGS=['-Wl,-whole-archive', mono_lib_file, '-Wl,-no-whole-archive']) - else: - env.Append(LIBS=[mono_lib]) - - if is_apple: - env.Append(LIBS=['iconv', 'pthread']) - else: - env.Append(LIBS=['m', 'rt', 'dl', 'pthread']) - - if not mono_static: - mono_so_name = find_file_in_dir(mono_lib_path, mono_lib_names, prefix='lib', extension=sharedlib_ext) - - if not mono_so_name: - raise RuntimeError('Could not find mono shared library in: ' + mono_lib_path) - - copy_file(mono_lib_path, 'bin', 'lib' + mono_so_name + sharedlib_ext) - else: - assert not mono_static - - # TODO: Add option to force using pkg-config - print('Mono root directory not found. Using pkg-config instead') - - mono_version = pkgconfig_try_find_mono_version() - configure_for_mono_version(env, mono_version) - - env.ParseConfig('pkg-config monosgen-2 --cflags --libs') - - mono_lib_path = '' - mono_so_name = '' - - tmpenv = Environment() - tmpenv.AppendENVPath('PKG_CONFIG_PATH', os.getenv('PKG_CONFIG_PATH')) - tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L') - - for hint_dir in tmpenv['LIBPATH']: - name_found = find_file_in_dir(hint_dir, mono_lib_names, prefix='lib', extension=sharedlib_ext) - if name_found: - mono_lib_path = hint_dir - mono_so_name = name_found - break - - if not mono_so_name: - raise RuntimeError('Could not find mono shared library in: ' + str(tmpenv['LIBPATH'])) - - copy_file(mono_lib_path, 'bin', 'lib' + mono_so_name + sharedlib_ext) - - env.Append(LINKFLAGS='-rdynamic') - - if not tools_enabled: - if not mono_root: - mono_root = subprocess.check_output(['pkg-config', 'mono-2', '--variable=prefix']).decode('utf8').strip() - - make_template_dir(env, mono_root) - - if copy_mono_root: - if not mono_root: - mono_root = subprocess.check_output(['pkg-config', 'mono-2', '--variable=prefix']).decode('utf8').strip() - - if tools_enabled: - copy_mono_root_files(env, mono_root) - else: - print("Ignoring option: 'copy_mono_root'. Only available for builds with 'tools' enabled.") - - -def make_template_dir(env, mono_root): - from shutil import rmtree - - platform = env['platform'] - target = env['target'] - - template_dir_name = '' - - if platform in ['windows', 'osx', 'x11']: - template_dir_name = 'data.mono.%s.%s.%s' % (platform, env['bits'], target) - else: - assert False - - output_dir = Dir('#bin').abspath - template_dir = os.path.join(output_dir, template_dir_name) - - template_mono_root_dir = os.path.join(template_dir, 'Mono') - - if os.path.isdir(template_mono_root_dir): - rmtree(template_mono_root_dir) # Clean first - - # Copy etc/mono/ - - template_mono_config_dir = os.path.join(template_mono_root_dir, 'etc', 'mono') - copy_mono_etc_dir(mono_root, template_mono_config_dir, env['platform']) - - # Copy the required shared libraries - - copy_mono_shared_libs(mono_root, template_mono_root_dir, env['platform']) - - -def copy_mono_root_files(env, mono_root): - from glob import glob - from shutil import copy - from shutil import rmtree - - if not mono_root: - raise RuntimeError('Mono installation directory not found') - - output_dir = Dir('#bin').abspath - editor_mono_root_dir = os.path.join(output_dir, 'GodotSharp', 'Mono') - - if os.path.isdir(editor_mono_root_dir): - rmtree(editor_mono_root_dir) # Clean first - - # Copy etc/mono/ - - editor_mono_config_dir = os.path.join(editor_mono_root_dir, 'etc', 'mono') - copy_mono_etc_dir(mono_root, editor_mono_config_dir, env['platform']) - - # Copy the required shared libraries - - copy_mono_shared_libs(mono_root, editor_mono_root_dir, env['platform']) - - # Copy framework assemblies - - mono_framework_dir = os.path.join(mono_root, 'lib', 'mono', '4.5') - mono_framework_facades_dir = os.path.join(mono_framework_dir, 'Facades') - - editor_mono_framework_dir = os.path.join(editor_mono_root_dir, 'lib', 'mono', '4.5') - editor_mono_framework_facades_dir = os.path.join(editor_mono_framework_dir, 'Facades') - - if not os.path.isdir(editor_mono_framework_dir): - os.makedirs(editor_mono_framework_dir) - if not os.path.isdir(editor_mono_framework_facades_dir): - os.makedirs(editor_mono_framework_facades_dir) - - for assembly in glob(os.path.join(mono_framework_dir, '*.dll')): - copy(assembly, editor_mono_framework_dir) - for assembly in glob(os.path.join(mono_framework_facades_dir, '*.dll')): - copy(assembly, editor_mono_framework_facades_dir) - - -def copy_mono_etc_dir(mono_root, target_mono_config_dir, platform): - from distutils.dir_util import copy_tree - from glob import glob - from shutil import copy - - if not os.path.isdir(target_mono_config_dir): - os.makedirs(target_mono_config_dir) - - mono_etc_dir = os.path.join(mono_root, 'etc', 'mono') - if not os.path.isdir(mono_etc_dir): - mono_etc_dir = '' - etc_hint_dirs = [] - if platform != 'windows': - etc_hint_dirs += ['/etc/mono', '/usr/local/etc/mono'] - if 'MONO_CFG_DIR' in os.environ: - etc_hint_dirs += [os.path.join(os.environ['MONO_CFG_DIR'], 'mono')] - for etc_hint_dir in etc_hint_dirs: - if os.path.isdir(etc_hint_dir): - mono_etc_dir = etc_hint_dir - break - if not mono_etc_dir: - raise RuntimeError('Mono installation etc directory not found') - - copy_tree(os.path.join(mono_etc_dir, '2.0'), os.path.join(target_mono_config_dir, '2.0')) - copy_tree(os.path.join(mono_etc_dir, '4.0'), os.path.join(target_mono_config_dir, '4.0')) - copy_tree(os.path.join(mono_etc_dir, '4.5'), os.path.join(target_mono_config_dir, '4.5')) - copy_tree(os.path.join(mono_etc_dir, 'mconfig'), os.path.join(target_mono_config_dir, 'mconfig')) - - for file in glob(os.path.join(mono_etc_dir, '*')): - if os.path.isfile(file): - copy(file, target_mono_config_dir) - - -def copy_mono_shared_libs(mono_root, target_mono_root_dir, platform): - from shutil import copy - - if platform == 'windows': - target_mono_bin_dir = os.path.join(target_mono_root_dir, 'bin') - - if not os.path.isdir(target_mono_bin_dir): - os.makedirs(target_mono_bin_dir) - - copy(os.path.join(mono_root, 'bin', 'MonoPosixHelper.dll'), os.path.join(target_mono_bin_dir, 'MonoPosixHelper.dll')) - else: - target_mono_lib_dir = os.path.join(target_mono_root_dir, 'lib') - - if not os.path.isdir(target_mono_lib_dir): - os.makedirs(target_mono_lib_dir) - - if platform == 'osx': - copy(os.path.join(mono_root, 'lib', 'libMonoPosixHelper.dylib'), os.path.join(target_mono_lib_dir, 'libMonoPosixHelper.dylib')) - elif platform == 'x11': - copy(os.path.join(mono_root, 'lib', 'libmono-btls-shared.so'), os.path.join(target_mono_lib_dir, 'libmono-btls-shared.so')) - copy(os.path.join(mono_root, 'lib', 'libMonoPosixHelper.so'), os.path.join(target_mono_lib_dir, 'libMonoPosixHelper.so')) - - -def configure_for_mono_version(env, mono_version): - if mono_version is None: - raise RuntimeError('Mono JIT compiler version not found') - print('Found Mono JIT compiler version: ' + str(mono_version)) - if mono_version >= LooseVersion('5.12.0'): - env.Append(CPPFLAGS=['-DHAS_PENDING_EXCEPTIONS']) - - -def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext): - tmpenv = Environment() - tmpenv.AppendENVPath('PKG_CONFIG_PATH', os.getenv('PKG_CONFIG_PATH')) - tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L') - for hint_dir in tmpenv['LIBPATH']: - name_found = find_file_in_dir(hint_dir, mono_lib_names, prefix='lib', extension=sharedlib_ext) - if name_found and os.path.isdir(os.path.join(hint_dir, '..', 'include', 'mono-2.0')): - return os.path.join(hint_dir, '..') - return '' - - -def pkgconfig_try_find_mono_version(): - from compat import decode_utf8 - - lines = subprocess.check_output(['pkg-config', 'monosgen-2', '--modversion']).splitlines() - greater_version = None - for line in lines: - try: - version = LooseVersion(decode_utf8(line)) - if greater_version is None or version > greater_version: - greater_version = version - except ValueError: - pass - return greater_version - - -def mono_root_try_find_mono_version(mono_root): - from compat import decode_utf8 - - mono_bin = os.path.join(mono_root, 'bin') - if os.path.isfile(os.path.join(mono_bin, 'mono')): - mono_binary = os.path.join(mono_bin, 'mono') - elif os.path.isfile(os.path.join(mono_bin, 'mono.exe')): - mono_binary = os.path.join(mono_bin, 'mono.exe') - else: - return None - output = subprocess.check_output([mono_binary, '--version']) - first_line = decode_utf8(output.splitlines()[0]) - try: - return LooseVersion(first_line.split()[len('Mono JIT compiler version'.split())]) - except (ValueError, IndexError): - return None +def is_enabled(): + # The module is disabled by default. Use module_mono_enabled=yes to enable it. + return False diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index 5f97069485..4536614379 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -42,12 +42,18 @@ #include "editor/bindings_generator.h" #include "editor/csharp_project.h" #include "editor/editor_node.h" -#include "editor/godotsharp_editor.h" #endif +#ifdef DEBUG_METHODS_ENABLED +#include "class_db_api_json.h" +#endif + +#include "editor/editor_internal_calls.h" #include "godotsharp_dirs.h" +#include "mono_gd/gd_mono_cache.h" #include "mono_gd/gd_mono_class.h" #include "mono_gd/gd_mono_marshal.h" +#include "mono_gd/gd_mono_utils.h" #include "signal_awaiter_utils.h" #include "utils/macros.h" #include "utils/mutex_utils.h" @@ -65,8 +71,8 @@ static bool _create_project_solution_if_needed() { if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) { // A solution does not yet exist, create a new one - CRASH_COND(GodotSharpEditor::get_singleton() == NULL); - return GodotSharpEditor::get_singleton()->call("_create_project_solution"); + CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == NULL); + return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolution"); } return true; @@ -96,34 +102,37 @@ Error CSharpLanguage::execute_file(const String &p_path) { return OK; } -#ifdef TOOLS_ENABLED -void gdsharp_editor_init_callback() { +void CSharpLanguage::init() { - EditorNode *editor = EditorNode::get_singleton(); - editor->add_child(memnew(GodotSharpEditor(editor))); -} +#ifdef DEBUG_METHODS_ENABLED + if (OS::get_singleton()->get_cmdline_args().find("--class_db_to_json")) { + class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE); +#ifdef TOOLS_ENABLED + class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR); +#endif + } #endif - -void CSharpLanguage::init() { gdmono = memnew(GDMono); gdmono->initialize(); -#ifndef MONO_GLUE_ENABLED - WARN_PRINT("This binary is built with `mono_glue=no` and cannot be used for scripting"); +#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED) + // Generate bindings here, before loading assemblies. 'initialize_load_assemblies' aborts + // the applications if the api assemblies or the main tools assembly is missing, but this + // is not a problem for BindingsGenerator as it only needs the tools project editor assembly. + List<String> cmdline_args = OS::get_singleton()->get_cmdline_args(); + BindingsGenerator::handle_cmdline_args(cmdline_args); #endif -#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED) - if (gdmono->get_editor_tools_assembly() != NULL) { - List<String> cmdline_args = OS::get_singleton()->get_cmdline_args(); - BindingsGenerator::handle_cmdline_args(cmdline_args); - } +#ifndef MONO_GLUE_ENABLED + print_line("Run this binary with '--generate-mono-glue path/to/modules/mono/glue'"); #endif -#ifdef TOOLS_ENABLED - EditorNode::add_init_callback(&gdsharp_editor_init_callback); + if (gdmono->is_runtime_initialized()) + gdmono->initialize_load_assemblies(); - GLOBAL_DEF("mono/export/include_scripts_content", false); +#ifdef TOOLS_ENABLED + EditorNode::add_init_callback(&_editor_init_callback); #endif } @@ -131,14 +140,6 @@ void CSharpLanguage::finish() { finalizing = true; -#ifdef TOOLS_ENABLED - // Must be here, to avoid StringName leaks - if (BindingsGenerator::singleton) { - memdelete(BindingsGenerator::singleton); - BindingsGenerator::singleton = NULL; - } -#endif - // Make sure all script binding gchandles are released before finalizing GDMono for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) { CSharpScriptBinding &script_binding = E->value(); @@ -545,7 +546,7 @@ Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() #ifdef DEBUG_ENABLED _TLS_RECURSION_GUARD_V_(Vector<StackInfo>()); - if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoUtils::mono_cache.corlib_cache_updated) + if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoCache::cached_data.corlib_cache_updated) return Vector<StackInfo>(); MonoObject *stack_trace = mono_object_new(mono_domain_get(), CACHED_CLASS(System_Diagnostics_StackTrace)->get_mono_ptr()); @@ -571,7 +572,7 @@ Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObjec MonoException *exc = NULL; - MonoArray *frames = invoke_method_thunk(CACHED_METHOD_THUNK(System_Diagnostics_StackTrace, GetFrames), p_stack_trace, &exc); + MonoArray *frames = CACHED_METHOD_THUNK(System_Diagnostics_StackTrace, GetFrames).invoke(p_stack_trace, &exc); if (exc) { GDMonoUtils::debug_print_unhandled_exception(exc); @@ -583,8 +584,6 @@ Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObjec if (frame_count <= 0) return Vector<StackInfo>(); - GDMonoUtils::DebugUtils_StackFrameInfo get_sf_info = CACHED_METHOD_THUNK(DebuggingUtils, GetStackFrameInfo); - Vector<StackInfo> si; si.resize(frame_count); @@ -595,7 +594,7 @@ Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObjec MonoString *file_name; int file_line_num; MonoString *method_decl; - invoke_method_thunk(get_sf_info, frame, &file_name, &file_line_num, &method_decl, &exc); + CACHED_METHOD_THUNK(DebuggingUtils, GetStackFrameInfo).invoke(frame, &file_name, &file_line_num, &method_decl, &exc); if (exc) { GDMonoUtils::debug_print_unhandled_exception(exc); @@ -618,18 +617,17 @@ Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObjec void CSharpLanguage::frame() { if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != NULL) { - const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoUtils::mono_cache.task_scheduler_handle; + const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoCache::cached_data.task_scheduler_handle; if (task_scheduler_handle.is_valid()) { MonoObject *task_scheduler = task_scheduler_handle->get_target(); if (task_scheduler) { MonoException *exc = NULL; - invoke_method_thunk(CACHED_METHOD_THUNK(GodotTaskScheduler, Activate), task_scheduler, &exc); + CACHED_METHOD_THUNK(GodotTaskScheduler, Activate).invoke(task_scheduler, &exc); if (exc) { GDMonoUtils::debug_unhandled_exception(exc); - GD_UNREACHABLE(); } } } @@ -672,7 +670,7 @@ void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft CRASH_COND(!Engine::get_singleton()->is_editor_hint()); #ifdef TOOLS_ENABLED - MonoReloadNode::get_singleton()->restart_reload_timer(); + get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer"); #endif #ifdef GD_MONO_HOT_RELOAD @@ -690,19 +688,20 @@ bool CSharpLanguage::is_assembly_reloading_needed() { GDMonoAssembly *proj_assembly = gdmono->get_project_assembly(); - String name = ProjectSettings::get_singleton()->get("application/config/name"); - if (name.empty()) { - name = "UnnamedProject"; + String appname = ProjectSettings::get_singleton()->get("application/config/name"); + String appname_safe = OS::get_singleton()->get_safe_dir_name(appname); + if (appname_safe.empty()) { + appname_safe = "UnnamedProject"; } - name += ".dll"; + appname_safe += ".dll"; if (proj_assembly) { String proj_asm_path = proj_assembly->get_path(); if (!FileAccess::exists(proj_assembly->get_path())) { // Maybe it wasn't loaded from the default path, so check this as well - proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name); + proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe); if (!FileAccess::exists(proj_asm_path)) return false; // No assembly to load } @@ -710,18 +709,10 @@ bool CSharpLanguage::is_assembly_reloading_needed() { if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time()) return false; // Already up to date } else { - if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name))) + if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe))) return false; // No assembly to load } -#ifdef TOOLS_ENABLED - if (!gdmono->get_core_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_CORE)) - return false; // The core API assembly to load is invalidated - - if (!gdmono->get_editor_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR)) - return false; // The editor API assembly to load is invalidated -#endif - return true; } @@ -738,58 +729,93 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { SCOPED_MUTEX_LOCK(script_instances_mutex); for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) { - if (elem->self()->get_path().is_resource_file()) { - // Cast to CSharpScript to avoid being erased by accident - scripts.push_back(Ref<CSharpScript>(elem->self())); - } + // Cast to CSharpScript to avoid being erased by accident + scripts.push_back(Ref<CSharpScript>(elem->self())); } } List<Ref<CSharpScript> > to_reload; + // We need to keep reference instances alive during reloading + List<Ref<Reference> > ref_instances; + + for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) { + CSharpScriptBinding &script_binding = E->value(); + Reference *ref = Object::cast_to<Reference>(script_binding.owner); + if (ref) { + ref_instances.push_back(Ref<Reference>(ref)); + } + } + // As scripts are going to be reloaded, must proceed without locking here scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) { - Ref<CSharpScript> &script = E->get(); to_reload.push_back(script); + if (script->get_path().empty()) { + script->tied_class_name_for_reload = script->script_class->get_name(); + script->tied_class_namespace_for_reload = script->script_class->get_namespace(); + } + // Script::instances are deleted during managed object disposal, which happens on domain finalize. // Only placeholders are kept. Therefore we need to keep a copy before that happens. for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) { - script->pending_reload_instances.insert(F->get()->get_instance_id()); + Object *obj = F->get(); + script->pending_reload_instances.insert(obj->get_instance_id()); + + Reference *ref = Object::cast_to<Reference>(obj); + if (ref) { + ref_instances.push_back(Ref<Reference>(ref)); + } } #ifdef TOOLS_ENABLED for (Set<PlaceHolderScriptInstance *>::Element *F = script->placeholders.front(); F; F = F->next()) { - script->pending_reload_instances.insert(F->get()->get_owner()->get_instance_id()); + Object *obj = F->get()->get_owner(); + script->pending_reload_instances.insert(obj->get_instance_id()); + + Reference *ref = Object::cast_to<Reference>(obj); + if (ref) { + ref_instances.push_back(Ref<Reference>(ref)); + } } #endif - // FIXME: What about references? Need to keep them alive if only managed code references them. - // Save state and remove script from instances Map<ObjectID, CSharpScript::StateBackup> &owners_map = script->pending_reload_state; - while (script->instances.front()) { - Object *obj = script->instances.front()->get(); - // Save instance info - CSharpScript::StateBackup state; + for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) { + Object *obj = F->get(); ERR_CONTINUE(!obj->get_script_instance()); - // TODO: Proper state backup (Not only variants, serialize managed state of scripts) - obj->get_script_instance()->get_property_state(state.properties); + CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance()); - Ref<MonoGCHandle> gchandle = CAST_CSHARP_INSTANCE(obj->get_script_instance())->gchandle; - if (gchandle.is_valid()) - gchandle->release(); + // Call OnBeforeSerialize + if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener))) + obj->get_script_instance()->call_multilevel(string_names.on_before_serialize); + + // Save instance info + CSharpScript::StateBackup state; + + // TODO: Proper state backup (Not only variants, serialize managed state of scripts) + csi->get_properties_state_for_reloading(state.properties); owners_map[obj->get_instance_id()] = state; + } + } + + // After the state of all instances is saved, clear scripts and script instances + for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) { + Ref<CSharpScript> &script = E->get(); + + while (script->instances.front()) { + Object *obj = script->instances.front()->get(); obj->set_script(RefPtr()); // Remove script and existing script instances (placeholder are not removed before domain reload) } @@ -832,26 +858,80 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { scr->pending_reload_state.erase(obj_id); } } + return; } + List<Ref<CSharpScript> > to_reload_state; + for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) { + Ref<CSharpScript> script = E->get(); + + if (!script->get_path().empty()) { +#ifdef TOOLS_ENABLED + script->exports_invalidated = true; +#endif + script->signals_invalidated = true; + + script->reload(p_soft_reload); + script->update_exports(); + + if (!script->valid) { + script->pending_reload_instances.clear(); + continue; + } + } else { + const StringName &class_namespace = script->tied_class_namespace_for_reload; + const StringName &class_name = script->tied_class_name_for_reload; + GDMonoAssembly *project_assembly = gdmono->get_project_assembly(); + + // Search in project and tools assemblies first as those are the most likely to have the class + GDMonoClass *script_class = (project_assembly ? project_assembly->get_class(class_namespace, class_name) : NULL); - Ref<CSharpScript> scr = E->get(); #ifdef TOOLS_ENABLED - scr->exports_invalidated = true; + if (!script_class) { + GDMonoAssembly *tools_assembly = gdmono->get_tools_assembly(); + script_class = (tools_assembly ? tools_assembly->get_class(class_namespace, class_name) : NULL); + } #endif - scr->signals_invalidated = true; - scr->reload(p_soft_reload); - scr->update_exports(); + + if (!script_class) { + script_class = gdmono->get_class(class_namespace, class_name); + } + + if (!script_class) { + // The class was removed, can't reload + script->pending_reload_instances.clear(); + continue; + } + + bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(script_class); + if (!obj_type) { + // The class no longer inherits Godot.Object, can't reload + script->pending_reload_instances.clear(); + continue; + } + + GDMonoClass *native = GDMonoUtils::get_class_native_base(script_class); + + CSharpScript::initialize_for_managed_type(script, script_class, native); + } + + String native_name = NATIVE_GDMONOCLASS_NAME(script->native); { - for (Set<ObjectID>::Element *F = scr->pending_reload_instances.front(); F; F = F->next()) { + for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) { ObjectID obj_id = F->get(); Object *obj = ObjectDB::get_instance(obj_id); if (!obj) { - scr->pending_reload_state.erase(obj_id); + script->pending_reload_state.erase(obj_id); + continue; + } + + if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) { + // No longer inherits the same compatible type, can't reload + script->pending_reload_state.erase(obj_id); continue; } @@ -863,28 +943,20 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { // Non-placeholder script instances are removed in godot_icall_Object_Disposed. CRASH_COND(!si->is_placeholder()); - if (scr->is_tool() || ScriptServer::is_scripting_enabled()) { + if (script->is_tool() || ScriptServer::is_scripting_enabled()) { // Replace placeholder with a script instance - CSharpScript::StateBackup &state_backup = scr->pending_reload_state[obj_id]; + CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id]; // Backup placeholder script instance state before replacing it with a script instance si->get_property_state(state_backup.properties); - ScriptInstance *script_instance = scr->instance_create(obj); + ScriptInstance *script_instance = script->instance_create(obj); if (script_instance) { - scr->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si)); + script->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si)); obj->set_script_instance(script_instance); } - - // TODO: Restore serialized state - - for (List<Pair<StringName, Variant> >::Element *G = state_backup.properties.front(); G; G = G->next()) { - script_instance->set(G->get().first, G->get().second); - } - - scr->pending_reload_state.erase(obj_id); } continue; @@ -893,20 +965,42 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { CRASH_COND(si != NULL); #endif // Re-create script instance + obj->set_script(script.get_ref_ptr()); // will create the script instance as well + } + } - obj->set_script(scr.get_ref_ptr()); // will create the script instance as well + to_reload_state.push_back(script); + } - // TODO: Restore serialized state + for (List<Ref<CSharpScript> >::Element *E = to_reload_state.front(); E; E = E->next()) { + Ref<CSharpScript> script = E->get(); - for (List<Pair<StringName, Variant> >::Element *G = scr->pending_reload_state[obj_id].properties.front(); G; G = G->next()) { - obj->get_script_instance()->set(G->get().first, G->get().second); - } + for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) { + ObjectID obj_id = F->get(); + Object *obj = ObjectDB::get_instance(obj_id); - scr->pending_reload_state.erase(obj_id); + if (!obj) { + script->pending_reload_state.erase(obj_id); + continue; } - scr->pending_reload_instances.clear(); + ERR_CONTINUE(!obj->get_script_instance()); + + // TODO: Restore serialized state + + CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id]; + + for (List<Pair<StringName, Variant> >::Element *G = state_backup.properties.front(); G; G = G->next()) { + obj->get_script_instance()->set(G->get().first, G->get().second); + } + + // Call OnAfterDeserialization + CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance()); + if (csi && csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener))) + obj->get_script_instance()->call_multilevel(string_names.on_after_deserialize); } + + script->pending_reload_instances.clear(); } #ifdef TOOLS_ENABLED @@ -919,7 +1013,7 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { } #endif -void CSharpLanguage::project_assembly_loaded() { +void CSharpLanguage::_load_scripts_metadata() { scripts_metadata.clear(); @@ -941,6 +1035,7 @@ void CSharpLanguage::project_assembly_loaded() { String old_json; Error ferr = read_all_file_utf8(scripts_metadata_path, old_json); + ERR_FAIL_COND(ferr != OK); Variant old_dict_var; @@ -948,16 +1043,17 @@ void CSharpLanguage::project_assembly_loaded() { int err_line; Error json_err = JSON::parse(old_json, old_dict_var, err_str, err_line); if (json_err != OK) { - ERR_PRINTS("Failed to parse metadata file: '" + err_str + "' (" + String::num_int64(err_line) + ")"); + ERR_PRINTS("Failed to parse metadata file: '" + err_str + "' (" + String::num_int64(err_line) + ")."); return; } scripts_metadata = old_dict_var.operator Dictionary(); + scripts_metadata_invalidated = false; print_verbose("Successfully loaded scripts metadata"); } else { if (!Engine::get_singleton()->is_editor_hint()) { - ERR_PRINT("Missing scripts metadata file"); + ERR_PRINT("Missing scripts metadata file."); } } } @@ -970,19 +1066,19 @@ void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const #ifdef TOOLS_ENABLED Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) { - return GodotSharpEditor::get_singleton()->open_in_external_editor(p_script, p_line, p_col); + return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col); } bool CSharpLanguage::overrides_external_editor() { - return GodotSharpEditor::get_singleton()->overrides_external_editor(); + return get_godotsharp_editor()->call("OverridesExternalEditor"); } #endif void CSharpLanguage::thread_enter() { #if 0 - if (mono->is_runtime_initialized()) { + if (gdmono->is_runtime_initialized()) { GDMonoUtils::attach_current_thread(); } #endif @@ -991,7 +1087,7 @@ void CSharpLanguage::thread_enter() { void CSharpLanguage::thread_exit() { #if 0 - if (mono->is_runtime_initialized()) { + if (gdmono->is_runtime_initialized()) { GDMonoUtils::detach_current_thread(); } #endif @@ -1004,7 +1100,7 @@ bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const S _debug_parse_err_line = p_line; _debug_parse_err_file = p_file; _debug_error = p_error; - ScriptDebugger::get_singleton()->debug(this, false); + ScriptDebugger::get_singleton()->debug(this, false, true); return true; } else { return false; @@ -1024,12 +1120,42 @@ bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) { } } -void CSharpLanguage::_uninitialize_script_bindings() { +void CSharpLanguage::_on_scripts_domain_unloaded() { for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) { CSharpScriptBinding &script_binding = E->value(); script_binding.inited = false; } + + scripts_metadata_invalidated = true; +} + +#ifdef TOOLS_ENABLED +void CSharpLanguage::_editor_init_callback() { + + register_editor_internal_calls(); + + // Initialize GodotSharpEditor + + GDMonoClass *editor_klass = GDMono::get_singleton()->get_tools_assembly()->get_class("GodotTools", "GodotSharpEditor"); + CRASH_COND(editor_klass == NULL); + + MonoObject *mono_object = mono_object_new(mono_domain_get(), editor_klass->get_mono_ptr()); + CRASH_COND(mono_object == NULL); + + MonoException *exc = NULL; + GDMonoUtils::runtime_object_init(mono_object, editor_klass, &exc); + UNHANDLED_EXCEPTION(exc); + + EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(GDMonoMarshal::mono_object_to_variant(mono_object)); + CRASH_COND(godotsharp_editor == NULL); + + // Enable it as a plugin + EditorNode::add_editor_plugin(godotsharp_editor); + godotsharp_editor->enable_plugin(); + + get_singleton()->godotsharp_editor = godotsharp_editor; } +#endif void CSharpLanguage::set_language_index(int p_idx) { @@ -1068,7 +1194,7 @@ void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, Ref<Mon CSharpLanguage::CSharpLanguage() { - ERR_FAIL_COND(singleton); + ERR_FAIL_COND_MSG(singleton, "C# singleton already exist."); singleton = this; finalizing = false; @@ -1086,6 +1212,12 @@ CSharpLanguage::CSharpLanguage() { #endif lang_idx = -1; + + scripts_metadata_invalidated = true; + +#ifdef TOOLS_ENABLED + godotsharp_editor = NULL; +#endif } CSharpLanguage::~CSharpLanguage() { @@ -1141,6 +1273,7 @@ bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_b r_script_binding.type_name = type_name; r_script_binding.wrapper_class = type_class; // cache r_script_binding.gchandle = MonoGCHandle::create_strong(mono_object); + r_script_binding.owner = p_object; // Tie managed to unmanaged Reference *ref = Object::cast_to<Reference>(p_object); @@ -1225,6 +1358,9 @@ void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) { CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); Ref<MonoGCHandle> &gchandle = script_binding.gchandle; + if (!script_binding.inited) + return; + if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 // The reference count was increased after the managed side was the only one referencing our owner. // This means the owner is being referenced again by the unmanaged side, @@ -1249,14 +1385,17 @@ bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) { CRASH_COND(!ref_owner); #endif - int refcount = ref_owner->reference_get_count(); - void *data = p_object->get_script_instance_binding(get_language_index()); CRASH_COND(!data); CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); Ref<MonoGCHandle> &gchandle = script_binding.gchandle; + int refcount = ref_owner->reference_get_count(); + + if (!script_binding.inited) + return refcount == 0; + if (refcount == 1 && gchandle.is_valid() && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 // If owner owner is no longer referenced by the unmanaged side, // the managed instance takes responsibility of deleting the owner when GCed. @@ -1419,11 +1558,64 @@ bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const { return false; } +void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant> > &r_state) { + + List<PropertyInfo> pinfo; + get_property_list(&pinfo); + + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + Pair<StringName, Variant> state_pair; + state_pair.first = E->get().name; + + ManagedType managedType; + + GDMonoField *field = script->script_class->get_field(state_pair.first); + if (!field) + continue; // Properties ignored. We get the property baking fields instead. + + managedType = field->get_type(); + + if (GDMonoMarshal::managed_to_variant_type(managedType) != Variant::NIL) { // If we can marshal it + if (get(state_pair.first, state_pair.second)) { + r_state.push_back(state_pair); + } + } + } +} + void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const { for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) { p_properties->push_back(E->value()); } + + // Call _get_property_list + + ERR_FAIL_COND(!script.is_valid()); + + MonoObject *mono_object = get_mono_object(); + ERR_FAIL_NULL(mono_object); + + GDMonoClass *top = script->script_class; + + while (top && top != script->native) { + GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get_property_list), 0); + + if (method) { + MonoObject *ret = method->invoke(mono_object); + + if (ret) { + Array array = Array(GDMonoMarshal::mono_object_to_variant(ret)); + for (int i = 0, size = array.size(); i < size; i++) + p_properties->push_back(PropertyInfo::from_dict(array.get(i))); + return; + } + + break; + } + + top = top->get_parent_class(); + } } Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const { @@ -1576,31 +1768,27 @@ MonoObject *CSharpInstance::_internal_new_managed() { // Search the constructor first, to fail with an error if it's not found before allocating anything else. GDMonoMethod *ctor = script->script_class->get_method(CACHED_STRING_NAME(dotctor), 0); - if (ctor == NULL) { - ERR_PRINTS("Cannot create script instance because the class does not define a parameterless constructor: " + script->get_path()); - - ERR_EXPLAIN("Constructor not found"); - ERR_FAIL_V(NULL); - } + ERR_FAIL_NULL_V_MSG(ctor, NULL, + "Cannot create script instance because the class does not define a parameterless constructor: '" + script->get_path() + "'."); CSharpLanguage::get_singleton()->release_script_gchandle(gchandle); ERR_FAIL_NULL_V(owner, NULL); ERR_FAIL_COND_V(script.is_null(), NULL); - MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script->script_class->get_mono_ptr()); + MonoObject *mono_object = mono_object_new(mono_domain_get(), script->script_class->get_mono_ptr()); if (!mono_object) { // Important to clear this before destroying the script instance here script = Ref<CSharpScript>(); - owner = NULL; bool die = _unreference_owner_unsafe(); // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug. CRASH_COND(die == true); - ERR_EXPLAIN("Failed to allocate memory for the object"); - ERR_FAIL_V(NULL); + owner = NULL; + + ERR_FAIL_V_MSG(NULL, "Failed to allocate memory for the object."); } // Tie managed to unmanaged @@ -1830,6 +2018,34 @@ void CSharpInstance::_call_notification(int p_notification) { } } +String CSharpInstance::to_string(bool *r_valid) { + MonoObject *mono_object = get_mono_object(); + + if (mono_object == NULL) { + if (r_valid) + *r_valid = false; + return String(); + } + + MonoException *exc = NULL; + MonoString *result = GDMonoUtils::object_to_string(mono_object, &exc); + + if (exc) { + GDMonoUtils::set_pending_exception(exc); + if (r_valid) + *r_valid = false; + return String(); + } + + if (result == NULL) { + if (r_valid) + *r_valid = false; + return String(); + } + + return GDMonoMarshal::mono_string_to_godot(result); +} + Ref<Script> CSharpInstance::get_script() const { return script; @@ -1886,7 +2102,16 @@ CSharpInstance::~CSharpInstance() { CRASH_COND(data == NULL); CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); - CRASH_COND(!script_binding.inited); + + if (!script_binding.inited) { + SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->get_language_bind_mutex()); + + if (!script_binding.inited) { // Other thread may have set it up + // Already had a binding that needs to be setup + CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, owner); + CRASH_COND(!script_binding.inited); + } + } bool die = _unreference_owner_unsafe(); CRASH_COND(die == true); // The "instance binding" should be holding a reference @@ -1928,6 +2153,52 @@ void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List propnames.push_back(E->get()); } } + +void CSharpScript::_update_member_info_no_exports() { + + if (exports_invalidated) { + exports_invalidated = false; + + member_info.clear(); + + GDMonoClass *top = script_class; + + while (top && top != native) { + PropertyInfo prop_info; + bool exported; + + const Vector<GDMonoField *> &fields = top->get_all_fields(); + + for (int i = fields.size() - 1; i >= 0; i--) { + GDMonoField *field = fields[i]; + + if (_get_member_export(field, /* inspect export: */ false, prop_info, exported)) { + StringName member_name = field->get_name(); + + member_info[member_name] = prop_info; + exported_members_cache.push_front(prop_info); + exported_members_defval_cache[member_name] = Variant(); + } + } + + const Vector<GDMonoProperty *> &properties = top->get_all_properties(); + + for (int i = properties.size() - 1; i >= 0; i--) { + GDMonoProperty *property = properties[i]; + + if (_get_member_export(property, /* inspect export: */ false, prop_info, exported)) { + StringName member_name = property->get_name(); + + member_info[member_name] = prop_info; + exported_members_cache.push_front(prop_info); + exported_members_defval_cache[member_name] = Variant(); + } + } + + top = top->get_parent_class(); + } + } +} #endif bool CSharpScript::_update_exports() { @@ -1954,10 +2225,10 @@ bool CSharpScript::_update_exports() { // Here we create a temporary managed instance of the class to get the initial values - MonoObject *tmp_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr()); + MonoObject *tmp_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr()); if (!tmp_object) { - ERR_PRINT("Failed to allocate temporary MonoObject"); + ERR_PRINT("Failed to allocate temporary MonoObject."); return false; } @@ -1965,12 +2236,8 @@ bool CSharpScript::_update_exports() { GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0); - if (ctor == NULL) { - ERR_PRINTS("Cannot construct temporary MonoObject because the class does not define a parameterless constructor: " + get_path()); - - ERR_EXPLAIN("Constructor not found"); - ERR_FAIL_V(NULL); - } + ERR_FAIL_NULL_V_MSG(ctor, NULL, + "Cannot construct temporary MonoObject because the class does not define a parameterless constructor: '" + get_path() + "'."); MonoException *ctor_exc = NULL; ctor->invoke(tmp_object, NULL, &ctor_exc); @@ -1995,18 +2262,18 @@ bool CSharpScript::_update_exports() { for (int i = fields.size() - 1; i >= 0; i--) { GDMonoField *field = fields[i]; - if (_get_member_export(top, field, prop_info, exported)) { - StringName name = field->get_name(); + if (_get_member_export(field, /* inspect export: */ true, prop_info, exported)) { + StringName member_name = field->get_name(); if (exported) { - member_info[name] = prop_info; + member_info[member_name] = prop_info; exported_members_cache.push_front(prop_info); if (tmp_object) { - exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object)); + exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object)); } } else { - member_info[name] = prop_info; + member_info[member_name] = prop_info; } } } @@ -2016,25 +2283,25 @@ bool CSharpScript::_update_exports() { for (int i = properties.size() - 1; i >= 0; i--) { GDMonoProperty *property = properties[i]; - if (_get_member_export(top, property, prop_info, exported)) { - StringName name = property->get_name(); + if (_get_member_export(property, /* inspect export: */ true, prop_info, exported)) { + StringName member_name = property->get_name(); if (exported) { - member_info[name] = prop_info; + member_info[member_name] = prop_info; exported_members_cache.push_front(prop_info); if (tmp_object) { MonoException *exc = NULL; MonoObject *ret = property->get_value(tmp_object, &exc); if (exc) { - exported_members_defval_cache[name] = Variant(); + exported_members_defval_cache[member_name] = Variant(); GDMonoUtils::debug_print_unhandled_exception(exc); } else { - exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(ret); + exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret); } } } else { - member_info[name] = prop_info; + member_info[member_name] = prop_info; } } } @@ -2123,7 +2390,7 @@ bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoClass *p_delegate, Ve arg.type = GDMonoMarshal::managed_to_variant_type(types[i]); if (arg.type == Variant::NIL) { - ERR_PRINTS("Unknown type of signal parameter: " + arg.name + " in " + p_class->get_full_name()); + ERR_PRINTS("Unknown type of signal parameter: '" + arg.name + "' in '" + p_class->get_full_name() + "'."); return false; } @@ -2143,17 +2410,19 @@ bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoClass *p_delegate, Ve * Returns false if there was an error, otherwise true. * If there was an error, r_prop_info and r_exported are not assigned any value. */ -bool CSharpScript::_get_member_export(GDMonoClass *p_class, IMonoClassMember *p_member, PropertyInfo &r_prop_info, bool &r_exported) { +bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported) { - StringName name = p_member->get_name(); + // Goddammit, C++. All I wanted was some nested functions. +#define MEMBER_FULL_QUALIFIED_NAME(m_member) \ + (m_member->get_enclosing_class()->get_full_name() + "." + (String)m_member->get_name()) if (p_member->is_static()) { if (p_member->has_attribute(CACHED_CLASS(ExportAttribute))) - ERR_PRINTS("Cannot export member because it is static: " + p_class->get_full_name() + "." + name.operator String()); + ERR_PRINTS("Cannot export member because it is static: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'."); return false; } - if (member_info.has(name)) + if (member_info.has(p_member->get_name())) return false; ManagedType type; @@ -2166,39 +2435,67 @@ bool CSharpScript::_get_member_export(GDMonoClass *p_class, IMonoClassMember *p_ CRASH_NOW(); } - GDMonoMarshal::ExportInfo export_info; - Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type, &export_info); - - if (!p_member->has_attribute(CACHED_CLASS(ExportAttribute))) { - r_prop_info = PropertyInfo(variant_type, name.operator String(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE); - r_exported = false; - return true; - } + bool exported = p_member->has_attribute(CACHED_CLASS(ExportAttribute)); if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) { GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member); - if (!property->has_getter() || !property->has_setter()) { - ERR_PRINTS("Cannot export property because it does not provide a getter or a setter: " + p_class->get_full_name() + "." + name.operator String()); + if (!property->has_getter()) { + if (exported) + ERR_PRINTS("Read-only property cannot be exported: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'."); + return false; + } + if (!property->has_setter()) { + if (exported) + ERR_PRINTS("Write-only property (without getter) cannot be exported: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'."); return false; } } + Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type); + + if (!p_inspect_export || !exported) { + r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE); + r_exported = false; + return true; + } + MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute)); PropertyHint hint = PROPERTY_HINT_NONE; String hint_string; if (variant_type == Variant::NIL) { - ERR_PRINTS("Unknown type of exported member: " + p_class->get_full_name() + "." + name.operator String()); + ERR_PRINTS("Unknown exported member type: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'."); return false; - } else if (variant_type == Variant::INT && type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(type.type_class->get_mono_ptr())) { - // TODO: Move to ExportInfo? - variant_type = Variant::INT; - hint = PROPERTY_HINT_ENUM; + } + + int hint_res = _try_get_member_export_hint(p_member, type, variant_type, /* allow_generics: */ true, hint, hint_string); - Vector<MonoClassField *> fields = type.type_class->get_enum_fields(); + ERR_FAIL_COND_V_MSG(hint_res == -1, false, + "Error while trying to determine information about the exported member: '" + + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'."); - MonoType *enum_basetype = mono_class_enum_basetype(type.type_class->get_mono_ptr()); + if (hint_res == 0) { + hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr)); + hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr); + } + + r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE); + r_exported = true; + + return true; + +#undef MEMBER_FULL_QUALIFIED_NAME +} + +int CSharpScript::_try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string) { + + if (p_variant_type == Variant::INT && p_type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(p_type.type_class->get_mono_ptr())) { + r_hint = PROPERTY_HINT_ENUM; + + Vector<MonoClassField *> fields = p_type.type_class->get_enum_fields(); + + MonoType *enum_basetype = mono_class_enum_basetype(p_type.type_class->get_mono_ptr()); String name_only_hint_string; @@ -2211,12 +2508,12 @@ bool CSharpScript::_get_member_export(GDMonoClass *p_class, IMonoClassMember *p_ MonoClassField *field = fields[i]; if (i > 0) { - hint_string += ","; + r_hint_string += ","; name_only_hint_string += ","; } String enum_field_name = mono_field_get_name(field); - hint_string += enum_field_name; + r_hint_string += enum_field_name; name_only_hint_string += enum_field_name; // TODO: @@ -2225,54 +2522,62 @@ bool CSharpScript::_get_member_export(GDMonoClass *p_class, IMonoClassMember *p_ MonoObject *val_obj = mono_field_get_value_object(mono_domain_get(), field, NULL); - if (val_obj == NULL) { - ERR_PRINTS("Failed to get '" + enum_field_name + "' constant enum value of exported member: " + - p_class->get_full_name() + "." + name.operator String()); - return false; - } + ERR_FAIL_NULL_V_MSG(val_obj, -1, "Failed to get '" + enum_field_name + "' constant enum value."); bool r_error; uint64_t val = GDMonoUtils::unbox_enum_value(val_obj, enum_basetype, r_error); - if (r_error) { - ERR_PRINTS("Failed to unbox '" + enum_field_name + "' constant enum value of exported member: " + - p_class->get_full_name() + "." + name.operator String()); - return false; - } + ERR_FAIL_COND_V_MSG(r_error, -1, "Failed to unbox '" + enum_field_name + "' constant enum value."); if (val != (unsigned int)i) { uses_default_values = false; } - hint_string += ":"; - hint_string += String::num_uint64(val); + r_hint_string += ":"; + r_hint_string += String::num_uint64(val); } if (uses_default_values) { // If we use the format NAME:VAL, that's what the editor displays. // That's annoying if the user is not using custom values for the enum constants. // This may not be needed in the future if the editor is changed to not display values. - hint_string = name_only_hint_string; + r_hint_string = name_only_hint_string; } - } else if (variant_type == Variant::OBJECT && CACHED_CLASS(GodotReference)->is_assignable_from(type.type_class)) { - GDMonoClass *field_native_class = GDMonoUtils::get_class_native_base(type.type_class); + } else if (p_variant_type == Variant::OBJECT && CACHED_CLASS(GodotResource)->is_assignable_from(p_type.type_class)) { + GDMonoClass *field_native_class = GDMonoUtils::get_class_native_base(p_type.type_class); CRASH_COND(field_native_class == NULL); - hint = PROPERTY_HINT_RESOURCE_TYPE; - hint_string = NATIVE_GDMONOCLASS_NAME(field_native_class); - } else if (variant_type == Variant::ARRAY && export_info.array.element_type != Variant::NIL) { - hint = PROPERTY_HINT_TYPE_STRING; - hint_string = itos(export_info.array.element_type) + ":"; - } else if (variant_type == Variant::DICTIONARY && export_info.dictionary.key_type != Variant::NIL && export_info.dictionary.value_type != Variant::NIL) { - // TODO: There is no hint for this yet + r_hint = PROPERTY_HINT_RESOURCE_TYPE; + r_hint_string = NATIVE_GDMONOCLASS_NAME(field_native_class); + } else if (p_allow_generics && p_variant_type == Variant::ARRAY) { + // Nested arrays are not supported in the inspector + + ManagedType elem_type; + + if (!GDMonoMarshal::try_get_array_element_type(p_type, elem_type)) + return 0; + + Variant::Type elem_variant_type = GDMonoMarshal::managed_to_variant_type(elem_type); + + PropertyHint elem_hint = PROPERTY_HINT_NONE; + String elem_hint_string; + + ERR_FAIL_COND_V_MSG(elem_variant_type == Variant::NIL, -1, "Unknown array element type."); + + int hint_res = _try_get_member_export_hint(p_member, elem_type, elem_variant_type, /* allow_generics: */ false, elem_hint, elem_hint_string); + + ERR_FAIL_COND_V_MSG(hint_res == -1, -1, "Error while trying to determine information about the array element type."); + + // Format: type/hint:hint_string + r_hint_string = itos(elem_variant_type) + "/" + itos(elem_hint) + ":" + elem_hint_string; + r_hint = PROPERTY_HINT_TYPE_STRING; + + } else if (p_allow_generics && p_variant_type == Variant::DICTIONARY) { + // TODO: Dictionaries are not supported in the inspector } else { - hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr)); - hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr); + return 0; } - r_prop_info = PropertyInfo(variant_type, name.operator String(), hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE); - r_exported = true; - - return true; + return 1; } #endif @@ -2355,38 +2660,63 @@ void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const { void CSharpScript::_bind_methods() { - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo(Variant::OBJECT, "new")); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new")); } Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) { - // This method should not fail + // This method should not fail, only assertions allowed - CRASH_COND(!p_class); + CRASH_COND(p_class == NULL); - // TODO: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time + // TODO OPTIMIZE: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time Ref<CSharpScript> script = memnew(CSharpScript); - script->name = p_class->get_name(); - script->script_class = p_class; - script->native = p_native; + initialize_for_managed_type(script, p_class, p_native); + + return script; +} + +void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native) { - CRASH_COND(script->native == NULL); + // This method should not fail, only assertions allowed - GDMonoClass *base = script->script_class->get_parent_class(); + CRASH_COND(p_class == NULL); - if (base != script->native) - script->base = base; + p_script->name = p_class->get_name(); + p_script->script_class = p_class; + p_script->native = p_native; + + CRASH_COND(p_script->native == NULL); + + GDMonoClass *base = p_script->script_class->get_parent_class(); + + if (base != p_script->native) + p_script->base = base; + + p_script->valid = true; + p_script->tool = p_script->script_class->has_attribute(CACHED_CLASS(ToolAttribute)); + + if (!p_script->tool) { + GDMonoClass *nesting_class = p_script->script_class->get_nesting_class(); + p_script->tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute)); + } + +#if TOOLS_ENABLED + if (!p_script->tool) { + p_script->tool = p_script->script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly(); + } +#endif #ifdef DEBUG_ENABLED // For debug builds, we must fetch from all native base methods as well. // Native base methods must be fetched before the current class. // Not needed if the script class itself is a native class. - if (script->script_class != script->native) { - GDMonoClass *native_top = script->native; + if (p_script->script_class != p_script->native) { + GDMonoClass *native_top = p_script->native; while (native_top) { - native_top->fetch_methods_with_godot_api_checks(script->native); + native_top->fetch_methods_with_godot_api_checks(p_script->native); if (native_top == CACHED_CLASS(GodotObject)) break; @@ -2396,18 +2726,19 @@ Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GD } #endif - script->script_class->fetch_methods_with_godot_api_checks(script->native); + p_script->script_class->fetch_methods_with_godot_api_checks(p_script->native); // Need to fetch method from base classes as well - GDMonoClass *top = script->script_class; - while (top && top != script->native) { - top->fetch_methods_with_godot_api_checks(script->native); + GDMonoClass *top = p_script->script_class; + while (top && top != p_script->native) { + top->fetch_methods_with_godot_api_checks(p_script->native); top = top->get_parent_class(); } - script->load_script_signals(script->script_class, script->native); - - return script; + p_script->load_script_signals(p_script->script_class, p_script->native); +#ifdef TOOLS_ENABLED + p_script->_update_member_info_no_exports(); +#endif } bool CSharpScript::can_instance() const { @@ -2415,13 +2746,14 @@ bool CSharpScript::can_instance() const { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { - if (get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted... + // Hack to lower the risk of attached scripts not being added to the C# project + if (!get_path().empty() && get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted... if (_create_project_solution_if_needed()) { CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(), "Compile", ProjectSettings::get_singleton()->globalize_path(get_path())); } else { - ERR_PRINTS("Cannot add " + get_path() + " to the C# project because it could not be created."); + ERR_PRINTS("C# project could not be created; cannot add file: '" + get_path() + "'."); } } } @@ -2439,12 +2771,10 @@ bool CSharpScript::can_instance() const { if (extra_cond && !script_class) { if (GDMono::get_singleton()->get_project_assembly() == NULL) { // The project assembly is not loaded - ERR_EXPLAIN("Cannot instance script because the project assembly is not loaded. Script: " + get_path()); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Cannot instance script because the project assembly is not loaded. Script: '" + get_path() + "'."); } else { // The project assembly is loaded, but the class could not found - ERR_EXPLAIN("Cannot instance script because the class '" + name + "' could not be found. Script: " + get_path()); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Cannot instance script because the class '" + name + "' could not be found. Script: '" + get_path() + "'."); } } @@ -2466,12 +2796,12 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg // Search the constructor first, to fail with an error if it's not found before allocating anything else. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount); if (ctor == NULL) { - if (p_argcount == 0) { - ERR_PRINTS("Cannot create script instance because the class does not define a parameterless constructor: " + get_path()); - } + ERR_FAIL_COND_V_MSG(p_argcount == 0, NULL, + "Cannot create script instance. The class '" + script_class->get_full_name() + + "' does not define a parameterless constructor." + + (get_path().empty() ? String() : " Path: '" + get_path() + "'.")); - ERR_EXPLAIN("Constructor not found"); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Constructor not found."); } Ref<Reference> ref; @@ -2509,7 +2839,7 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg /* STEP 2, INITIALIZE AND CONSTRUCT */ - MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr()); + MonoObject *mono_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr()); if (!mono_object) { // Important to clear this before destroying the script instance here @@ -2522,8 +2852,7 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg p_owner->set_script_instance(NULL); r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL; - ERR_EXPLAIN("Failed to allocate memory for the object"); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Failed to allocate memory for the object."); } // Tie managed to unmanaged @@ -2557,11 +2886,10 @@ Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Variant::Call r_error.error = Variant::CallError::CALL_OK; REF ref; - Object *owner = NULL; ERR_FAIL_NULL_V(native, Variant()); - owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native)); + Object *owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native)); Reference *r = Object::cast_to<Reference>(owner); if (r) { @@ -2590,18 +2918,18 @@ ScriptInstance *CSharpScript::instance_create(Object *p_this) { #endif if (native) { - String native_name = native->get_name(); + String native_name = NATIVE_GDMONOCLASS_NAME(native); if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) { if (ScriptDebugger::get_singleton()) { CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'"); } - ERR_EXPLAIN("Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'"); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Script inherits from native type '" + native_name + + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'."); } } Variant::CallError unchecked_error; - return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error); + return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this) != NULL, unchecked_error); } PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) { @@ -2716,11 +3044,22 @@ Error CSharpScript::reload(bool p_keep_state) { if (script_class) { #ifdef DEBUG_ENABLED - print_verbose("Found class " + script_class->get_namespace() + "." + script_class->get_name() + " for script " + get_path()); + print_verbose("Found class " + script_class->get_full_name() + " for script " + get_path()); #endif tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute)); + if (!tool) { + GDMonoClass *nesting_class = script_class->get_nesting_class(); + tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute)); + } + +#if TOOLS_ENABLED + if (!tool) { + tool = script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly(); + } +#endif + native = GDMonoUtils::get_class_native_base(script_class); CRASH_COND(native == NULL); @@ -2798,10 +3137,7 @@ void CSharpScript::update_exports() { } bool CSharpScript::has_script_signal(const StringName &p_signal) const { - if (_signals.has(p_signal)) - return true; - - return false; + return _signals.has(p_signal); } void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const { @@ -2840,12 +3176,12 @@ int CSharpScript::get_member_line(const StringName &p_member) const { Error CSharpScript::load_source_code(const String &p_path) { Error ferr = read_all_file_utf8(p_path, source); - if (ferr != OK) { - if (ferr == ERR_INVALID_DATA) { - ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); - } - ERR_FAIL_V(ferr); - } + + ERR_FAIL_COND_V_MSG(ferr != OK, ferr, + ferr == ERR_INVALID_DATA ? + "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded." + " Please ensure that scripts are saved in valid UTF-8 unicode." : + "Failed to read file: '" + p_path + "'."); #ifdef TOOLS_ENABLED source_changed_cache = true; @@ -2905,7 +3241,7 @@ RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED) Error err = script->load_source_code(p_path); - ERR_FAIL_COND_V(err != OK, RES()); + ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot load C# script file '" + p_path + "'."); #endif script->set_path(p_original_path); @@ -2914,14 +3250,14 @@ RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p #ifdef DEBUG_ENABLED // User is responsible for thread attach/detach - ERR_EXPLAIN("Thread is not attached"); - CRASH_COND(mono_domain_get() == NULL); + CRASH_COND_MSG(mono_domain_get() == NULL, "Thread is not attached."); #endif #endif #ifdef TOOLS_ENABLED - if (Engine::get_singleton()->is_editor_hint() && mono_domain_get() == NULL) { + MonoDomain *domain = mono_domain_get(); + if (Engine::get_singleton()->is_editor_hint() && domain == NULL) { CRASH_COND(Thread::get_caller_id() == Thread::get_main_id()); @@ -2929,8 +3265,8 @@ RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p // because this may be called by one of the editor's worker threads. // Attach this thread temporarily to reload the script. - if (SCRIPTS_DOMAIN) { - MonoThread *mono_thread = mono_thread_attach(SCRIPTS_DOMAIN); + if (domain) { + MonoThread *mono_thread = mono_thread_attach(domain); CRASH_COND(mono_thread == NULL); script->reload(); mono_thread_detach(mono_thread); @@ -2981,15 +3317,14 @@ Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_r "Compile", ProjectSettings::get_singleton()->globalize_path(p_path)); } else { - ERR_PRINTS("Failed to create C# project"); - ERR_PRINTS("Cannot add " + p_path + " to the C# project"); + ERR_PRINTS("C# project could not be created; cannot add file: '" + p_path + "'."); } } #endif Error err; FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); - ERR_FAIL_COND_V(err, err); + ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'."); file->store_string(source); @@ -3027,7 +3362,10 @@ CSharpLanguage::StringNameCache::StringNameCache() { _signal_callback = StaticCString::create("_signal_callback"); _set = StaticCString::create("_set"); _get = StaticCString::create("_get"); + _get_property_list = StaticCString::create("_get_property_list"); _notification = StaticCString::create("_notification"); _script_source = StaticCString::create("script/source"); + on_before_serialize = StaticCString::create("OnBeforeSerialize"); + on_after_deserialize = StaticCString::create("OnAfterDeserialize"); dotctor = StaticCString::create(".ctor"); } diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index 99877a4379..eb168f344d 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -41,6 +41,10 @@ #include "mono_gd/gd_mono_header.h" #include "mono_gd/gd_mono_internals.h" +#ifdef TOOLS_ENABLED +#include "editor/editor_plugin.h" +#endif + class CSharpScript; class CSharpInstance; class CSharpLanguage; @@ -63,7 +67,7 @@ TScriptInstance *cast_script_instance(ScriptInstance *p_inst) { class CSharpScript : public Script { - GDCLASS(CSharpScript, Script) + GDCLASS(CSharpScript, Script); friend class CSharpInstance; friend class CSharpLanguage; @@ -92,6 +96,8 @@ class CSharpScript : public Script { Set<ObjectID> pending_reload_instances; Map<ObjectID, StateBackup> pending_reload_state; + StringName tied_class_name_for_reload; + StringName tied_class_namespace_for_reload; #endif String source; @@ -115,6 +121,7 @@ class CSharpScript : public Script { bool placeholder_fallback_enabled; bool exports_invalidated; void _update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames); + void _update_member_info_no_exports(); virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder); #endif @@ -127,7 +134,8 @@ class CSharpScript : public Script { bool _update_exports(); #ifdef TOOLS_ENABLED - bool _get_member_export(GDMonoClass *p_class, IMonoClassMember *p_member, PropertyInfo &r_prop_info, bool &r_exported); + bool _get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported); + static int _try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string); #endif CSharpInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error); @@ -136,6 +144,7 @@ class CSharpScript : public Script { // Do not use unless you know what you are doing friend void GDMonoInternals::tie_managed_to_unmanaged(MonoObject *, Object *); static Ref<CSharpScript> create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native); + static void initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native); protected: static void _bind_methods(); @@ -225,6 +234,8 @@ class CSharpInstance : public ScriptInstance { MultiplayerAPI::RPCMode _member_get_rpc_mode(IMonoClassMember *p_member) const; + void get_properties_state_for_reloading(List<Pair<StringName, Variant> > &r_state); + public: MonoObject *get_mono_object() const; @@ -260,6 +271,8 @@ public: virtual void notification(int p_notification); void _call_notification(int p_notification); + virtual String to_string(bool *r_valid); + virtual Ref<Script> get_script() const; virtual ScriptLanguage *get_language(); @@ -273,6 +286,7 @@ struct CSharpScriptBinding { StringName type_name; GDMonoClass *wrapper_class; Ref<MonoGCHandle> gchandle; + Object *owner; }; class CSharpLanguage : public ScriptLanguage { @@ -298,9 +312,12 @@ class CSharpLanguage : public ScriptLanguage { StringName _signal_callback; StringName _set; StringName _get; + StringName _get_property_list; StringName _notification; StringName _script_source; StringName dotctor; // .ctor + StringName on_before_serialize; // OnBeforeSerialize + StringName on_after_deserialize; // OnAfterDeserialize StringNameCache(); }; @@ -308,14 +325,23 @@ class CSharpLanguage : public ScriptLanguage { int lang_idx; Dictionary scripts_metadata; + bool scripts_metadata_invalidated; // For debug_break and debug_break_parse int _debug_parse_err_line; String _debug_parse_err_file; String _debug_error; + void _load_scripts_metadata(); + friend class GDMono; - void _uninitialize_script_bindings(); + void _on_scripts_domain_unloaded(); + +#ifdef TOOLS_ENABLED + EditorPlugin *godotsharp_editor; + + static void _editor_init_callback(); +#endif public: StringNameCache string_names; @@ -329,8 +355,12 @@ public: _FORCE_INLINE_ static CSharpLanguage *get_singleton() { return singleton; } +#ifdef TOOLS_ENABLED + _FORCE_INLINE_ EditorPlugin *get_godotsharp_editor() const { return godotsharp_editor; } +#endif + static void release_script_gchandle(Ref<MonoGCHandle> &p_gchandle); - static void release_script_gchandle(MonoObject *p_pinned_expected_obj, Ref<MonoGCHandle> &p_gchandle); + static void release_script_gchandle(MonoObject *p_expected_obj, Ref<MonoGCHandle> &p_gchandle); bool debug_break(const String &p_error, bool p_allow_continue = true); bool debug_break_parse(const String &p_file, int p_line, const String &p_error); @@ -340,9 +370,15 @@ public: void reload_assemblies(bool p_soft_reload); #endif - void project_assembly_loaded(); + _FORCE_INLINE_ Dictionary get_scripts_metadata_or_nothing() { + return scripts_metadata_invalidated ? Dictionary() : scripts_metadata; + } - _FORCE_INLINE_ const Dictionary &get_scripts_metadata() { return scripts_metadata; } + _FORCE_INLINE_ const Dictionary &get_scripts_metadata() { + if (scripts_metadata_invalidated) + _load_scripts_metadata(); + return scripts_metadata; + } virtual String get_name() const; @@ -367,7 +403,6 @@ public: virtual bool supports_builtin_mode() const; /* TODO? */ virtual int find_function(const String &p_function, const String &p_code) const { return -1; } virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const; - /* TODO? */ Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) { return ERR_UNAVAILABLE; } virtual String _get_indentation() const; /* TODO? */ virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const {} /* TODO */ virtual void add_global_constant(const StringName &p_variable, const Variant &p_value) {} @@ -428,7 +463,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; @@ -437,7 +471,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/doc_classes/@C#.xml b/modules/mono/doc_classes/@C#.xml index a821713d0d..826c106d7e 100644 --- a/modules/mono/doc_classes/@C#.xml +++ b/modules/mono/doc_classes/@C#.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/mono/doc_classes/CSharpScript.xml b/modules/mono/doc_classes/CSharpScript.xml index 7f22388132..de2e246ea9 100644 --- a/modules/mono/doc_classes/CSharpScript.xml +++ b/modules/mono/doc_classes/CSharpScript.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="new" qualifiers="vararg"> <return type="Object"> diff --git a/modules/mono/doc_classes/GodotSharp.xml b/modules/mono/doc_classes/GodotSharp.xml index 21835e639c..18556a84ba 100644 --- a/modules/mono/doc_classes/GodotSharp.xml +++ b/modules/mono/doc_classes/GodotSharp.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="attach_thread"> <return type="void"> diff --git a/modules/mono/editor/GodotSharpTools/.gitignore b/modules/mono/editor/GodotSharpTools/.gitignore deleted file mode 100644 index 296ad48834..0000000000 --- a/modules/mono/editor/GodotSharpTools/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# nuget packages -packages
\ No newline at end of file diff --git a/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs b/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs deleted file mode 100644 index 967e3bcc19..0000000000 --- a/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs +++ /dev/null @@ -1,425 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Diagnostics; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Security; -using Microsoft.Build.Framework; - -namespace GodotSharpTools.Build -{ - public class BuildInstance : IDisposable - { - [MethodImpl(MethodImplOptions.InternalCall)] - private extern static void godot_icall_BuildInstance_ExitCallback(string solution, string config, int exitCode); - - [MethodImpl(MethodImplOptions.InternalCall)] - private extern static string godot_icall_BuildInstance_get_MSBuildPath(); - [MethodImpl(MethodImplOptions.InternalCall)] - private extern static string godot_icall_BuildInstance_get_MonoWindowsBinDir(); - [MethodImpl(MethodImplOptions.InternalCall)] - private extern static bool godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows(); - [MethodImpl(MethodImplOptions.InternalCall)] - private extern static bool godot_icall_BuildInstance_get_PrintBuildOutput(); - - private static string GetMSBuildPath() - { - string msbuildPath = godot_icall_BuildInstance_get_MSBuildPath(); - - if (msbuildPath == null) - throw new FileNotFoundException("Cannot find the MSBuild executable."); - - return msbuildPath; - } - - private static string MonoWindowsBinDir - { - get - { - string monoWinBinDir = godot_icall_BuildInstance_get_MonoWindowsBinDir(); - - if (monoWinBinDir == null) - throw new FileNotFoundException("Cannot find the Windows Mono binaries directory."); - - return monoWinBinDir; - } - } - - private static bool UsingMonoMSBuildOnWindows - { - get - { - return godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows(); - } - } - - private static bool PrintBuildOutput - { - get - { - return godot_icall_BuildInstance_get_PrintBuildOutput(); - } - } - - private string solution; - private string config; - - private Process process; - - private int exitCode; - public int ExitCode { get { return exitCode; } } - - public bool IsRunning { get { return process != null && !process.HasExited; } } - - public BuildInstance(string solution, string config) - { - this.solution = solution; - this.config = config; - } - - public bool Build(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null) - { - List<string> customPropertiesList = new List<string>(); - - if (customProperties != null) - customPropertiesList.AddRange(customProperties); - - string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList); - - ProcessStartInfo startInfo = new ProcessStartInfo(GetMSBuildPath(), compilerArgs); - - bool redirectOutput = !IsDebugMSBuildRequested() && !PrintBuildOutput; - - if (!redirectOutput) // TODO: or if stdout verbose - Console.WriteLine($"Running: \"{startInfo.FileName}\" {startInfo.Arguments}"); - - startInfo.RedirectStandardOutput = redirectOutput; - startInfo.RedirectStandardError = redirectOutput; - startInfo.UseShellExecute = false; - - if (UsingMonoMSBuildOnWindows) - { - // These environment variables are required for Mono's MSBuild to find the compilers. - // We use the batch files in Mono's bin directory to make sure the compilers are executed with mono. - string monoWinBinDir = MonoWindowsBinDir; - startInfo.EnvironmentVariables.Add("CscToolExe", Path.Combine(monoWinBinDir, "csc.bat")); - startInfo.EnvironmentVariables.Add("VbcToolExe", Path.Combine(monoWinBinDir, "vbc.bat")); - startInfo.EnvironmentVariables.Add("FscToolExe", Path.Combine(monoWinBinDir, "fsharpc.bat")); - } - - // Needed when running from Developer Command Prompt for VS - RemovePlatformVariable(startInfo.EnvironmentVariables); - - using (Process process = new Process()) - { - process.StartInfo = startInfo; - - process.Start(); - - if (redirectOutput) - { - process.BeginOutputReadLine(); - process.BeginErrorReadLine(); - } - - process.WaitForExit(); - - exitCode = process.ExitCode; - } - - return true; - } - - public bool BuildAsync(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null) - { - if (process != null) - throw new InvalidOperationException("Already in use"); - - List<string> customPropertiesList = new List<string>(); - - if (customProperties != null) - customPropertiesList.AddRange(customProperties); - - string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList); - - ProcessStartInfo startInfo = new ProcessStartInfo(GetMSBuildPath(), compilerArgs); - - bool redirectOutput = !IsDebugMSBuildRequested() && !PrintBuildOutput; - - if (!redirectOutput) // TODO: or if stdout verbose - Console.WriteLine($"Running: \"{startInfo.FileName}\" {startInfo.Arguments}"); - - startInfo.RedirectStandardOutput = redirectOutput; - startInfo.RedirectStandardError = redirectOutput; - startInfo.UseShellExecute = false; - - if (UsingMonoMSBuildOnWindows) - { - // These environment variables are required for Mono's MSBuild to find the compilers. - // We use the batch files in Mono's bin directory to make sure the compilers are executed with mono. - string monoWinBinDir = MonoWindowsBinDir; - startInfo.EnvironmentVariables.Add("CscToolExe", Path.Combine(monoWinBinDir, "csc.bat")); - startInfo.EnvironmentVariables.Add("VbcToolExe", Path.Combine(monoWinBinDir, "vbc.bat")); - startInfo.EnvironmentVariables.Add("FscToolExe", Path.Combine(monoWinBinDir, "fsharpc.bat")); - } - - // Needed when running from Developer Command Prompt for VS - RemovePlatformVariable(startInfo.EnvironmentVariables); - - process = new Process(); - process.StartInfo = startInfo; - process.EnableRaisingEvents = true; - process.Exited += new EventHandler(BuildProcess_Exited); - - process.Start(); - - if (redirectOutput) - { - process.BeginOutputReadLine(); - process.BeginErrorReadLine(); - } - - return true; - } - - private string BuildArguments(string loggerAssemblyPath, string loggerOutputDir, List<string> customProperties) - { - string arguments = string.Format(@"""{0}"" /v:normal /t:Build ""/p:{1}"" ""/l:{2},{3};{4}""", - solution, - "Configuration=" + config, - typeof(GodotBuildLogger).FullName, - loggerAssemblyPath, - loggerOutputDir - ); - - foreach (string customProperty in customProperties) - { - arguments += " \"/p:" + customProperty + "\""; - } - - return arguments; - } - - private void RemovePlatformVariable(StringDictionary environmentVariables) - { - // EnvironmentVariables is case sensitive? Seriously? - - List<string> platformEnvironmentVariables = new List<string>(); - - foreach (string env in environmentVariables.Keys) - { - if (env.ToUpper() == "PLATFORM") - platformEnvironmentVariables.Add(env); - } - - foreach (string env in platformEnvironmentVariables) - environmentVariables.Remove(env); - } - - private void BuildProcess_Exited(object sender, System.EventArgs e) - { - exitCode = process.ExitCode; - - godot_icall_BuildInstance_ExitCallback(solution, config, exitCode); - - Dispose(); - } - - private static bool IsDebugMSBuildRequested() - { - return Environment.GetEnvironmentVariable("GODOT_DEBUG_MSBUILD")?.Trim() == "1"; - } - - public void Dispose() - { - if (process != null) - { - process.Dispose(); - process = null; - } - } - } - - public class GodotBuildLogger : ILogger - { - public string Parameters { get; set; } - public LoggerVerbosity Verbosity { get; set; } - - public void Initialize(IEventSource eventSource) - { - if (null == Parameters) - throw new LoggerException("Log directory was not set."); - - string[] parameters = Parameters.Split(new[] { ';' }); - - string logDir = parameters[0]; - - if (String.IsNullOrEmpty(logDir)) - throw new LoggerException("Log directory was not set."); - - if (parameters.Length > 1) - throw new LoggerException("Too many parameters passed."); - - string logFile = Path.Combine(logDir, "msbuild_log.txt"); - string issuesFile = Path.Combine(logDir, "msbuild_issues.csv"); - - try - { - if (!Directory.Exists(logDir)) - Directory.CreateDirectory(logDir); - - this.logStreamWriter = new StreamWriter(logFile); - this.issuesStreamWriter = new StreamWriter(issuesFile); - } - catch (Exception ex) - { - if - ( - ex is UnauthorizedAccessException - || ex is ArgumentNullException - || ex is PathTooLongException - || ex is DirectoryNotFoundException - || ex is NotSupportedException - || ex is ArgumentException - || ex is SecurityException - || ex is IOException - ) - { - throw new LoggerException("Failed to create log file: " + ex.Message); - } - else - { - // Unexpected failure - throw; - } - } - - eventSource.ProjectStarted += new ProjectStartedEventHandler(eventSource_ProjectStarted); - eventSource.TaskStarted += new TaskStartedEventHandler(eventSource_TaskStarted); - eventSource.MessageRaised += new BuildMessageEventHandler(eventSource_MessageRaised); - eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised); - eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised); - eventSource.ProjectFinished += new ProjectFinishedEventHandler(eventSource_ProjectFinished); - } - - void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e) - { - string line = String.Format("{0}({1},{2}): error {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message); - - if (e.ProjectFile.Length > 0) - line += string.Format(" [{0}]", e.ProjectFile); - - WriteLine(line); - - string errorLine = String.Format(@"error,{0},{1},{2},{3},{4},{5}", - e.File.CsvEscape(), e.LineNumber, e.ColumnNumber, - e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile.CsvEscape()); - issuesStreamWriter.WriteLine(errorLine); - } - - void eventSource_WarningRaised(object sender, BuildWarningEventArgs e) - { - string line = String.Format("{0}({1},{2}): warning {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message, e.ProjectFile); - - if (e.ProjectFile != null && e.ProjectFile.Length > 0) - line += string.Format(" [{0}]", e.ProjectFile); - - WriteLine(line); - - string warningLine = String.Format(@"warning,{0},{1},{2},{3},{4},{5}", - e.File.CsvEscape(), e.LineNumber, e.ColumnNumber, - e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile != null ? e.ProjectFile.CsvEscape() : string.Empty); - issuesStreamWriter.WriteLine(warningLine); - } - - void eventSource_MessageRaised(object sender, BuildMessageEventArgs e) - { - // BuildMessageEventArgs adds Importance to BuildEventArgs - // Let's take account of the verbosity setting we've been passed in deciding whether to log the message - if ((e.Importance == MessageImportance.High && IsVerbosityAtLeast(LoggerVerbosity.Minimal)) - || (e.Importance == MessageImportance.Normal && IsVerbosityAtLeast(LoggerVerbosity.Normal)) - || (e.Importance == MessageImportance.Low && IsVerbosityAtLeast(LoggerVerbosity.Detailed)) - ) - { - WriteLineWithSenderAndMessage(String.Empty, e); - } - } - - void eventSource_TaskStarted(object sender, TaskStartedEventArgs e) - { - // TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName - // To keep this log clean, this logger will ignore these events. - } - - void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e) - { - WriteLine(e.Message); - indent++; - } - - void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e) - { - indent--; - WriteLine(e.Message); - } - - /// <summary> - /// Write a line to the log, adding the SenderName - /// </summary> - private void WriteLineWithSender(string line, BuildEventArgs e) - { - if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/)) - { - // Well, if the sender name is MSBuild, let's leave it out for prettiness - WriteLine(line); - } - else - { - WriteLine(e.SenderName + ": " + line); - } - } - - /// <summary> - /// Write a line to the log, adding the SenderName and Message - /// (these parameters are on all MSBuild event argument objects) - /// </summary> - private void WriteLineWithSenderAndMessage(string line, BuildEventArgs e) - { - if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/)) - { - // Well, if the sender name is MSBuild, let's leave it out for prettiness - WriteLine(line + e.Message); - } - else - { - WriteLine(e.SenderName + ": " + line + e.Message); - } - } - - private void WriteLine(string line) - { - for (int i = indent; i > 0; i--) - { - logStreamWriter.Write("\t"); - } - logStreamWriter.WriteLine(line); - } - - public void Shutdown() - { - logStreamWriter.Close(); - issuesStreamWriter.Close(); - } - - public bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity) - { - return this.Verbosity >= checkVerbosity; - } - - private StreamWriter logStreamWriter; - private StreamWriter issuesStreamWriter; - private int indent; - } -} diff --git a/modules/mono/editor/GodotSharpTools/Editor/GodotSharpExport.cs b/modules/mono/editor/GodotSharpTools/Editor/GodotSharpExport.cs deleted file mode 100644 index e45dd2025b..0000000000 --- a/modules/mono/editor/GodotSharpTools/Editor/GodotSharpExport.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.CompilerServices; - -namespace GodotSharpTools.Editor -{ - public static class GodotSharpExport - { - public static void _ExportBegin(string[] features, bool debug, string path, int flags) - { - var featureSet = new HashSet<string>(features); - - if (PlatformHasTemplateDir(featureSet)) - { - string templateDirName = "data.mono"; - - if (featureSet.Contains("Windows")) - { - templateDirName += ".windows"; - templateDirName += featureSet.Contains("64") ? ".64" : ".32"; - } - else if (featureSet.Contains("X11")) - { - templateDirName += ".x11"; - templateDirName += featureSet.Contains("64") ? ".64" : ".32"; - } - else - { - throw new NotSupportedException("Target platform not supported"); - } - - templateDirName += debug ? ".release_debug" : ".release"; - - string templateDirPath = Path.Combine(GetTemplatesDir(), templateDirName); - - if (!Directory.Exists(templateDirPath)) - throw new FileNotFoundException("Data template directory not found"); - - string outputDir = new FileInfo(path).Directory.FullName; - - string outputDataDir = Path.Combine(outputDir, GetDataDirName()); - - if (Directory.Exists(outputDataDir)) - Directory.Delete(outputDataDir, recursive: true); // Clean first - - Directory.CreateDirectory(outputDataDir); - - foreach (string dir in Directory.GetDirectories(templateDirPath, "*", SearchOption.AllDirectories)) - { - Directory.CreateDirectory(Path.Combine(outputDataDir, dir.Substring(templateDirPath.Length + 1))); - } - - foreach (string file in Directory.GetFiles(templateDirPath, "*", SearchOption.AllDirectories)) - { - File.Copy(file, Path.Combine(outputDataDir, file.Substring(templateDirPath.Length + 1))); - } - } - } - - public static bool PlatformHasTemplateDir(HashSet<string> featureSet) - { - // OSX export templates are contained in a zip, so we place - // our custom template inside it and let Godot do the rest. - return !featureSet.Contains("OSX"); - } - - [MethodImpl(MethodImplOptions.InternalCall)] - extern static string GetTemplatesDir(); - - [MethodImpl(MethodImplOptions.InternalCall)] - extern static string GetDataDirName(); - } -} diff --git a/modules/mono/editor/GodotSharpTools/Editor/MonoDevelopInstance.cs b/modules/mono/editor/GodotSharpTools/Editor/MonoDevelopInstance.cs deleted file mode 100644 index fba4a8f65c..0000000000 --- a/modules/mono/editor/GodotSharpTools/Editor/MonoDevelopInstance.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.IO; -using System.Collections.Generic; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -namespace GodotSharpTools.Editor -{ - public class MonoDevelopInstance - { - public enum EditorId - { - MonoDevelop = 0, - VisualStudioForMac = 1 - } - - readonly string solutionFile; - readonly EditorId editorId; - - Process process; - - public void Execute(string[] files) - { - bool newWindow = process == null || process.HasExited; - - List<string> args = new List<string>(); - - string command; - - if (Utils.OS.IsOSX()) - { - string bundleId = codeEditorBundleIds[editorId]; - - if (IsApplicationBundleInstalled(bundleId)) - { - command = "open"; - - args.Add("-b"); - args.Add(bundleId); - - // The 'open' process must wait until the application finishes - if (newWindow) - args.Add("--wait-apps"); - - args.Add("--args"); - } - else - { - command = codeEditorPaths[editorId]; - } - } - else - { - command = codeEditorPaths[editorId]; - } - - args.Add("--ipc-tcp"); - - if (newWindow) - args.Add("\"" + Path.GetFullPath(solutionFile) + "\""); - - foreach (var file in files) - { - int semicolonIndex = file.IndexOf(';'); - - string filePath = semicolonIndex < 0 ? file : file.Substring(0, semicolonIndex); - string cursor = semicolonIndex < 0 ? string.Empty : file.Substring(semicolonIndex); - - args.Add("\"" + Path.GetFullPath(filePath.NormalizePath()) + cursor + "\""); - } - - if (newWindow) - { - process = Process.Start(new ProcessStartInfo() - { - FileName = command, - Arguments = string.Join(" ", args), - UseShellExecute = false - }); - } - else - { - Process.Start(new ProcessStartInfo() - { - FileName = command, - Arguments = string.Join(" ", args), - UseShellExecute = false - }); - } - } - - public MonoDevelopInstance(string solutionFile, EditorId editorId) - { - if (editorId == EditorId.VisualStudioForMac && !Utils.OS.IsOSX()) - throw new InvalidOperationException($"{nameof(EditorId.VisualStudioForMac)} not supported on this platform"); - - this.solutionFile = solutionFile; - this.editorId = editorId; - } - - [MethodImpl(MethodImplOptions.InternalCall)] - private extern static bool IsApplicationBundleInstalled(string bundleId); - - static readonly IReadOnlyDictionary<EditorId, string> codeEditorPaths; - static readonly IReadOnlyDictionary<EditorId, string> codeEditorBundleIds; - - static MonoDevelopInstance() - { - if (Utils.OS.IsOSX()) - { - codeEditorPaths = new Dictionary<EditorId, string> - { - // Rely on PATH - { EditorId.MonoDevelop, "monodevelop" }, - { EditorId.VisualStudioForMac, "VisualStudio" } - }; - codeEditorBundleIds = new Dictionary<EditorId, string> - { - // TODO EditorId.MonoDevelop - { EditorId.VisualStudioForMac, "com.microsoft.visual-studio" } - }; - } - else if (Utils.OS.IsWindows()) - { - codeEditorPaths = new Dictionary<EditorId, string> - { - // XamarinStudio is no longer a thing, and the latest version is quite old - // MonoDevelop is available from source only on Windows. The recommendation - // is to use Visual Studio instead. Since there are no official builds, we - // will rely on custom MonoDevelop builds being added to PATH. - { EditorId.MonoDevelop, "MonoDevelop.exe" } - }; - } - else if (Utils.OS.IsUnix()) - { - codeEditorPaths = new Dictionary<EditorId, string> - { - // Rely on PATH - { EditorId.MonoDevelop, "monodevelop" } - }; - } - } - } -} diff --git a/modules/mono/editor/GodotSharpTools/GodotSharpTools.sln b/modules/mono/editor/GodotSharpTools/GodotSharpTools.sln deleted file mode 100644 index 5f7d0e8a39..0000000000 --- a/modules/mono/editor/GodotSharpTools/GodotSharpTools.sln +++ /dev/null @@ -1,17 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotSharpTools", "GodotSharpTools.csproj", "{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal diff --git a/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs b/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs deleted file mode 100644 index a13f4fd6ef..0000000000 --- a/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using DotNet.Globbing; -using Microsoft.Build.Construction; - -namespace GodotSharpTools.Project -{ - public static class ProjectUtils - { - public static void AddItemToProjectChecked(string projectPath, string itemType, string include) - { - var dir = Directory.GetParent(projectPath).FullName; - var root = ProjectRootElement.Open(projectPath); - var normalizedInclude = include.RelativeToPath(dir).Replace("/", "\\"); - - if (root.AddItemChecked(itemType, normalizedInclude)) - root.Save(); - } - - private static string[] GetAllFilesRecursive(string rootDirectory, string mask) - { - string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories); - - // We want relative paths - for (int i = 0; i < files.Length; i++) { - files[i] = files[i].RelativeToPath(rootDirectory); - } - - return files; - } - - public static string[] GetIncludeFiles(string projectPath, string itemType) - { - var result = new List<string>(); - var existingFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs"); - - GlobOptions globOptions = new GlobOptions(); - globOptions.Evaluation.CaseInsensitive = false; - - var root = ProjectRootElement.Open(projectPath); - - foreach (var itemGroup in root.ItemGroups) - { - if (itemGroup.Condition.Length != 0) - continue; - - foreach (var item in itemGroup.Items) - { - if (item.ItemType != itemType) - continue; - - string normalizedInclude = item.Include.NormalizePath(); - - var glob = Glob.Parse(normalizedInclude, globOptions); - - // TODO Check somehow if path has no blog to avoid the following loop... - - foreach (var existingFile in existingFiles) - { - if (glob.IsMatch(existingFile)) - { - result.Add(existingFile); - } - } - } - } - - return result.ToArray(); - } - } -} diff --git a/modules/mono/editor/GodotSharpTools/Utils/OS.cs b/modules/mono/editor/GodotSharpTools/Utils/OS.cs deleted file mode 100644 index 148e954e77..0000000000 --- a/modules/mono/editor/GodotSharpTools/Utils/OS.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace GodotSharpTools.Utils -{ - public static class OS - { - [MethodImpl(MethodImplOptions.InternalCall)] - extern static string GetPlatformName(); - - const string HaikuName = "Haiku"; - const string OSXName = "OSX"; - const string ServerName = "Server"; - const string UWPName = "UWP"; - const string WindowsName = "Windows"; - const string X11Name = "X11"; - - public static bool IsHaiku() - { - return HaikuName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase); - } - - public static bool IsOSX() - { - return OSXName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase); - } - - public static bool IsServer() - { - return ServerName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase); - } - - public static bool IsUWP() - { - return UWPName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase); - } - - public static bool IsWindows() - { - return WindowsName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase); - } - - public static bool IsX11() - { - return X11Name.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase); - } - - static bool? IsUnixCache = null; - static readonly string[] UnixPlatforms = new string[] { HaikuName, OSXName, ServerName, X11Name }; - - public static bool IsUnix() - { - if (IsUnixCache.HasValue) - return IsUnixCache.Value; - - string osName = GetPlatformName(); - IsUnixCache = UnixPlatforms.Any(p => p.Equals(osName, StringComparison.OrdinalIgnoreCase)); - return IsUnixCache.Value; - } - } -} diff --git a/modules/mono/editor/GodotTools/.gitignore b/modules/mono/editor/GodotTools/.gitignore new file mode 100644 index 0000000000..48e2f914d8 --- /dev/null +++ b/modules/mono/editor/GodotTools/.gitignore @@ -0,0 +1,356 @@ +# Rider +.idea/ + +# Visual Studio Code +.vscode/ + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs new file mode 100644 index 0000000000..a0f6f1ff32 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs @@ -0,0 +1,186 @@ +using System; +using System.IO; +using System.Security; +using Microsoft.Build.Framework; +using GodotTools.Core; + +namespace GodotTools.BuildLogger +{ + public class GodotBuildLogger : ILogger + { + public static readonly string AssemblyPath = Path.GetFullPath(typeof(GodotBuildLogger).Assembly.Location); + + public string Parameters { get; set; } + public LoggerVerbosity Verbosity { get; set; } + + public void Initialize(IEventSource eventSource) + { + if (null == Parameters) + throw new LoggerException("Log directory was not set."); + + var parameters = Parameters.Split(new[] {';'}); + + string logDir = parameters[0]; + + if (string.IsNullOrEmpty(logDir)) + throw new LoggerException("Log directory was not set."); + + if (parameters.Length > 1) + throw new LoggerException("Too many parameters passed."); + + string logFile = Path.Combine(logDir, "msbuild_log.txt"); + string issuesFile = Path.Combine(logDir, "msbuild_issues.csv"); + + try + { + if (!Directory.Exists(logDir)) + Directory.CreateDirectory(logDir); + + logStreamWriter = new StreamWriter(logFile); + issuesStreamWriter = new StreamWriter(issuesFile); + } + catch (Exception ex) + { + if (ex is UnauthorizedAccessException + || ex is ArgumentNullException + || ex is PathTooLongException + || ex is DirectoryNotFoundException + || ex is NotSupportedException + || ex is ArgumentException + || ex is SecurityException + || ex is IOException) + { + throw new LoggerException("Failed to create log file: " + ex.Message); + } + else + { + // Unexpected failure + throw; + } + } + + eventSource.ProjectStarted += eventSource_ProjectStarted; + eventSource.TaskStarted += eventSource_TaskStarted; + eventSource.MessageRaised += eventSource_MessageRaised; + eventSource.WarningRaised += eventSource_WarningRaised; + eventSource.ErrorRaised += eventSource_ErrorRaised; + eventSource.ProjectFinished += eventSource_ProjectFinished; + } + + void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e) + { + string line = $"{e.File}({e.LineNumber},{e.ColumnNumber}): error {e.Code}: {e.Message}"; + + if (e.ProjectFile.Length > 0) + line += $" [{e.ProjectFile}]"; + + WriteLine(line); + + string errorLine = $@"error,{e.File.CsvEscape()},{e.LineNumber},{e.ColumnNumber}," + + $@"{e.Code.CsvEscape()},{e.Message.CsvEscape()},{e.ProjectFile.CsvEscape()}"; + issuesStreamWriter.WriteLine(errorLine); + } + + void eventSource_WarningRaised(object sender, BuildWarningEventArgs e) + { + string line = $"{e.File}({e.LineNumber},{e.ColumnNumber}): warning {e.Code}: {e.Message}"; + + if (!string.IsNullOrEmpty(e.ProjectFile)) + line += $" [{e.ProjectFile}]"; + + WriteLine(line); + + string warningLine = $@"warning,{e.File.CsvEscape()},{e.LineNumber},{e.ColumnNumber},{e.Code.CsvEscape()}," + + $@"{e.Message.CsvEscape()},{(e.ProjectFile != null ? e.ProjectFile.CsvEscape() : string.Empty)}"; + issuesStreamWriter.WriteLine(warningLine); + } + + private void eventSource_MessageRaised(object sender, BuildMessageEventArgs e) + { + // BuildMessageEventArgs adds Importance to BuildEventArgs + // Let's take account of the verbosity setting we've been passed in deciding whether to log the message + if (e.Importance == MessageImportance.High && IsVerbosityAtLeast(LoggerVerbosity.Minimal) + || e.Importance == MessageImportance.Normal && IsVerbosityAtLeast(LoggerVerbosity.Normal) + || e.Importance == MessageImportance.Low && IsVerbosityAtLeast(LoggerVerbosity.Detailed)) + { + WriteLineWithSenderAndMessage(string.Empty, e); + } + } + + private void eventSource_TaskStarted(object sender, TaskStartedEventArgs e) + { + // TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName + // To keep this log clean, this logger will ignore these events. + } + + private void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e) + { + WriteLine(e.Message); + indent++; + } + + private void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e) + { + indent--; + WriteLine(e.Message); + } + + /// <summary> + /// Write a line to the log, adding the SenderName + /// </summary> + private void WriteLineWithSender(string line, BuildEventArgs e) + { + if (0 == string.Compare(e.SenderName, "MSBuild", StringComparison.OrdinalIgnoreCase)) + { + // Well, if the sender name is MSBuild, let's leave it out for prettiness + WriteLine(line); + } + else + { + WriteLine(e.SenderName + ": " + line); + } + } + + /// <summary> + /// Write a line to the log, adding the SenderName and Message + /// (these parameters are on all MSBuild event argument objects) + /// </summary> + private void WriteLineWithSenderAndMessage(string line, BuildEventArgs e) + { + if (0 == string.Compare(e.SenderName, "MSBuild", StringComparison.OrdinalIgnoreCase)) + { + // Well, if the sender name is MSBuild, let's leave it out for prettiness + WriteLine(line + e.Message); + } + else + { + WriteLine(e.SenderName + ": " + line + e.Message); + } + } + + private void WriteLine(string line) + { + for (int i = indent; i > 0; i--) + { + logStreamWriter.Write("\t"); + } + + logStreamWriter.WriteLine(line); + } + + public void Shutdown() + { + logStreamWriter.Close(); + issuesStreamWriter.Close(); + } + + private bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity) + { + return Verbosity >= checkVerbosity; + } + + private StreamWriter logStreamWriter; + private StreamWriter issuesStreamWriter; + private int indent; + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj new file mode 100644 index 0000000000..dcfdd83831 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{6CE9A984-37B1-4F8A-8FE9-609F05F071B3}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>GodotTools.BuildLogger</RootNamespace> + <AssemblyName>GodotTools.BuildLogger</AssemblyName> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + <LangVersion>7</LangVersion> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugSymbols>true</DebugSymbols> + <DebugType>portable</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugType>portable</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="Microsoft.Build.Framework" /> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="GodotBuildLogger.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj"> + <Project>{639e48bd-44e5-4091-8edd-22d36dc0768d}</Project> + <Name>GodotTools.Core</Name> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project>
\ No newline at end of file diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..8717c4901e --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("GodotTools.BuildLogger")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("Godot Engine contributors")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("6CE9A984-37B1-4F8A-8FE9-609F05F071B3")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/modules/mono/editor/GodotSharpTools/GodotSharpTools.csproj b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj index 2871c041f5..24c7cb1573 100644 --- a/modules/mono/editor/GodotSharpTools/GodotSharpTools.csproj +++ b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj @@ -1,18 +1,18 @@ -<?xml version="1.0" encoding="utf-8"?> +<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProjectGuid>{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}</ProjectGuid> + <ProjectGuid>{639E48BD-44E5-4091-8EDD-22D36DC0768D}</ProjectGuid> <OutputType>Library</OutputType> - <RootNamespace>GodotSharpTools</RootNamespace> - <AssemblyName>GodotSharpTools</AssemblyName> + <RootNamespace>GodotTools.Core</RootNamespace> + <AssemblyName>GodotTools.Core</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> - <BaseIntermediateOutputPath>obj</BaseIntermediateOutputPath> + <LangVersion>7</LangVersion> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> - <DebugType>portable</DebugType> + <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug</OutputPath> <DefineConstants>DEBUG;</DefineConstants> @@ -21,7 +21,6 @@ <ConsolePause>false</ConsolePause> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> - <DebugType>portable</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release</OutputPath> <ErrorReport>prompt</ErrorReport> @@ -30,26 +29,11 @@ </PropertyGroup> <ItemGroup> <Reference Include="System" /> - <Reference Include="Microsoft.Build" /> - <Reference Include="Microsoft.Build.Framework" /> - <Reference Include="DotNet.Glob, Version=2.1.1.0, Culture=neutral, PublicKeyToken=b68cc888b4f632d1, processorArchitecture=MSIL"> - <HintPath>packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll</HintPath> - </Reference> </ItemGroup> <ItemGroup> - <Compile Include="StringExtensions.cs" /> - <Compile Include="Build\BuildSystem.cs" /> - <Compile Include="Editor\MonoDevelopInstance.cs" /> - <Compile Include="Project\ProjectExtensions.cs" /> - <Compile Include="Project\IdentifierUtils.cs" /> - <Compile Include="Project\ProjectGenerator.cs" /> - <Compile Include="Project\ProjectUtils.cs" /> + <Compile Include="ProcessExtensions.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="Utils\OS.cs" /> - <Compile Include="Editor\GodotSharpExport.cs" /> - </ItemGroup> - <ItemGroup> - <None Include="packages.config" /> + <Compile Include="StringExtensions.cs" /> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> </Project>
\ No newline at end of file diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/ProcessExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.Core/ProcessExtensions.cs new file mode 100644 index 0000000000..43d40f2ad9 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.Core/ProcessExtensions.cs @@ -0,0 +1,38 @@ +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; + +namespace GodotTools.Core +{ + public static class ProcessExtensions + { + public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken)) + { + var tcs = new TaskCompletionSource<bool>(); + + void ProcessExited(object sender, EventArgs e) + { + tcs.TrySetResult(true); + } + + process.EnableRaisingEvents = true; + process.Exited += ProcessExited; + + try + { + if (process.HasExited) + return; + + using (cancellationToken.Register(() => tcs.TrySetCanceled())) + { + await tcs.Task; + } + } + finally + { + process.Exited -= ProcessExited; + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..699ae6e741 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs @@ -0,0 +1,26 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +// Information about this assembly is defined by the following attributes. +// Change them to the values specific to your project. + +[assembly: AssemblyTitle("GodotTools.Core")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("Godot Engine contributors")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". +// The form "{Major}.{Minor}.*" will automatically update the build and revision, +// and "{Major}.{Minor}.{Build}.*" will update just the revision. + +[assembly: AssemblyVersion("1.0.*")] + +// The following attributes are used to specify the signing key for the assembly, +// if desired. See the Mono documentation for more information about signing. + +//[assembly: AssemblyDelaySign(false)] +//[assembly: AssemblyKeyFile("")] diff --git a/modules/mono/editor/GodotSharpTools/StringExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs index b0436d2f18..8cd7e76303 100644 --- a/modules/mono/editor/GodotSharpTools/StringExtensions.cs +++ b/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs @@ -1,7 +1,8 @@ using System; +using System.Collections.Generic; using System.IO; -namespace GodotSharpTools +namespace GodotTools.Core { public static class StringExtensions { @@ -25,7 +26,7 @@ namespace GodotSharpTools path = path.Replace('\\', '/'); - string[] parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + string[] parts = path.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries); path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim(); @@ -37,18 +38,40 @@ namespace GodotSharpTools public static bool IsAbsolutePath(this string path) { return path.StartsWith("/", StringComparison.Ordinal) || - path.StartsWith("\\", StringComparison.Ordinal) || - path.StartsWith(driveRoot, StringComparison.Ordinal); + path.StartsWith("\\", StringComparison.Ordinal) || + path.StartsWith(driveRoot, StringComparison.Ordinal); } public static string CsvEscape(this string value, char delimiter = ',') { - bool hasSpecialChar = value.IndexOfAny(new char[] { '\"', '\n', '\r', delimiter }) != -1; + bool hasSpecialChar = value.IndexOfAny(new char[] {'\"', '\n', '\r', delimiter}) != -1; if (hasSpecialChar) return "\"" + value.Replace("\"", "\"\"") + "\""; return value; } + + public static string ToSafeDirName(this string dirName, bool allowDirSeparator) + { + var invalidChars = new List<string> {":", "*", "?", "\"", "<", ">", "|"}; + + if (allowDirSeparator) + { + // Directory separators are allowed, but disallow ".." to avoid going up the filesystem + invalidChars.Add(".."); + } + else + { + invalidChars.Add("/"); + } + + string safeDirName = dirName.Replace("\\", "/").Trim(); + + foreach (string invalidChar in invalidChars) + safeDirName = safeDirName.Replace(invalidChar, "-"); + + return safeDirName; + } } } diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ConsoleLogger.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ConsoleLogger.cs new file mode 100644 index 0000000000..7a2ff2ca56 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ConsoleLogger.cs @@ -0,0 +1,33 @@ +using System; + +namespace GodotTools.IdeConnection +{ + public class ConsoleLogger : ILogger + { + public void LogDebug(string message) + { + Console.WriteLine("DEBUG: " + message); + } + + public void LogInfo(string message) + { + Console.WriteLine("INFO: " + message); + } + + public void LogWarning(string message) + { + Console.WriteLine("WARN: " + message); + } + + public void LogError(string message) + { + Console.WriteLine("ERROR: " + message); + } + + public void LogError(string message, Exception e) + { + Console.WriteLine("EXCEPTION: " + message); + Console.WriteLine(e); + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeBase.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeBase.cs new file mode 100644 index 0000000000..be89638241 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeBase.cs @@ -0,0 +1,94 @@ +using System; +using Path = System.IO.Path; + +namespace GodotTools.IdeConnection +{ + public class GodotIdeBase : IDisposable + { + private ILogger logger; + + public ILogger Logger + { + get => logger ?? (logger = new ConsoleLogger()); + set => logger = value; + } + + private readonly string projectMetadataDir; + + protected const string MetaFileName = "ide_server_meta.txt"; + protected string MetaFilePath => Path.Combine(projectMetadataDir, MetaFileName); + + private GodotIdeConnection connection; + protected readonly object ConnectionLock = new object(); + + public bool IsDisposed { get; private set; } = false; + + public bool IsConnected => connection != null && !connection.IsDisposed && connection.IsConnected; + + public event Action Connected + { + add + { + if (connection != null && !connection.IsDisposed) + connection.Connected += value; + } + remove + { + if (connection != null && !connection.IsDisposed) + connection.Connected -= value; + } + } + + protected GodotIdeConnection Connection + { + get => connection; + set + { + connection?.Dispose(); + connection = value; + } + } + + protected GodotIdeBase(string projectMetadataDir) + { + this.projectMetadataDir = projectMetadataDir; + } + + protected void DisposeConnection() + { + lock (ConnectionLock) + { + connection?.Dispose(); + } + } + + ~GodotIdeBase() + { + Dispose(disposing: false); + } + + public void Dispose() + { + if (IsDisposed) + return; + + lock (ConnectionLock) + { + if (IsDisposed) // lock may not be fair + return; + IsDisposed = true; + } + + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + connection?.Dispose(); + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeClient.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeClient.cs new file mode 100644 index 0000000000..4f56a8d71b --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeClient.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace GodotTools.IdeConnection +{ + public abstract class GodotIdeClient : GodotIdeBase + { + protected GodotIdeMetadata GodotIdeMetadata; + + private readonly FileSystemWatcher fsWatcher; + + protected GodotIdeClient(string projectMetadataDir) : base(projectMetadataDir) + { + messageHandlers = InitializeMessageHandlers(); + + // FileSystemWatcher requires an existing directory + if (!File.Exists(projectMetadataDir)) + Directory.CreateDirectory(projectMetadataDir); + + fsWatcher = new FileSystemWatcher(projectMetadataDir, MetaFileName); + } + + private void OnMetaFileChanged(object sender, FileSystemEventArgs e) + { + if (IsDisposed) + return; + + lock (ConnectionLock) + { + if (IsDisposed) + return; + + if (!File.Exists(MetaFilePath)) + return; + + var metadata = ReadMetadataFile(); + + if (metadata != null && metadata != GodotIdeMetadata) + { + GodotIdeMetadata = metadata.Value; + ConnectToServer(); + } + } + } + + private void OnMetaFileDeleted(object sender, FileSystemEventArgs e) + { + if (IsDisposed) + return; + + if (IsConnected) + DisposeConnection(); + + // The file may have been re-created + + lock (ConnectionLock) + { + if (IsDisposed) + return; + + if (IsConnected || !File.Exists(MetaFilePath)) + return; + + var metadata = ReadMetadataFile(); + + if (metadata != null) + { + GodotIdeMetadata = metadata.Value; + ConnectToServer(); + } + } + } + + private GodotIdeMetadata? ReadMetadataFile() + { + using (var reader = File.OpenText(MetaFilePath)) + { + string portStr = reader.ReadLine(); + + if (portStr == null) + return null; + + string editorExecutablePath = reader.ReadLine(); + + if (editorExecutablePath == null) + return null; + + if (!int.TryParse(portStr, out int port)) + return null; + + return new GodotIdeMetadata(port, editorExecutablePath); + } + } + + private void ConnectToServer() + { + var tcpClient = new TcpClient(); + + Connection = new GodotIdeConnectionClient(tcpClient, HandleMessage); + Connection.Logger = Logger; + + try + { + Logger.LogInfo("Connecting to Godot Ide Server"); + + tcpClient.Connect(IPAddress.Loopback, GodotIdeMetadata.Port); + + Logger.LogInfo("Connection open with Godot Ide Server"); + + var clientThread = new Thread(Connection.Start) + { + IsBackground = true, + Name = "Godot Ide Connection Client" + }; + clientThread.Start(); + } + catch (SocketException e) + { + if (e.SocketErrorCode == SocketError.ConnectionRefused) + Logger.LogError("The connection to the Godot Ide Server was refused"); + else + throw; + } + } + + public void Start() + { + Logger.LogInfo("Starting Godot Ide Client"); + + fsWatcher.Changed += OnMetaFileChanged; + fsWatcher.Deleted += OnMetaFileDeleted; + fsWatcher.EnableRaisingEvents = true; + + lock (ConnectionLock) + { + if (IsDisposed) + return; + + if (!File.Exists(MetaFilePath)) + { + Logger.LogInfo("There is no Godot Ide Server running"); + return; + } + + var metadata = ReadMetadataFile(); + + if (metadata != null) + { + GodotIdeMetadata = metadata.Value; + ConnectToServer(); + } + else + { + Logger.LogError("Failed to read Godot Ide metadata file"); + } + } + } + + public bool WriteMessage(Message message) + { + return Connection.WriteMessage(message); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (disposing) + { + fsWatcher?.Dispose(); + } + } + + protected virtual bool HandleMessage(Message message) + { + if (messageHandlers.TryGetValue(message.Id, out var action)) + { + action(message.Arguments); + return true; + } + + return false; + } + + private readonly Dictionary<string, Action<string[]>> messageHandlers; + + private Dictionary<string, Action<string[]>> InitializeMessageHandlers() + { + return new Dictionary<string, Action<string[]>> + { + ["OpenFile"] = args => + { + switch (args.Length) + { + case 1: + OpenFile(file: args[0]); + return; + case 2: + OpenFile(file: args[0], line: int.Parse(args[1])); + return; + case 3: + OpenFile(file: args[0], line: int.Parse(args[1]), column: int.Parse(args[2])); + return; + default: + throw new ArgumentException(); + } + } + }; + } + + protected abstract void OpenFile(string file); + protected abstract void OpenFile(string file, int line); + protected abstract void OpenFile(string file, int line, int column); + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnection.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnection.cs new file mode 100644 index 0000000000..e7e81f175e --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnection.cs @@ -0,0 +1,207 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Net.Sockets; +using System.Text; + +namespace GodotTools.IdeConnection +{ + public abstract class GodotIdeConnection : IDisposable + { + protected const string Version = "1.0"; + + protected static readonly string ClientHandshake = $"Godot Ide Client Version {Version}"; + protected static readonly string ServerHandshake = $"Godot Ide Server Version {Version}"; + + private const int ClientWriteTimeout = 8000; + private readonly TcpClient tcpClient; + + private TextReader clientReader; + private TextWriter clientWriter; + + private readonly object writeLock = new object(); + + private readonly Func<Message, bool> messageHandler; + + public event Action Connected; + + private ILogger logger; + + public ILogger Logger + { + get => logger ?? (logger = new ConsoleLogger()); + set => logger = value; + } + + public bool IsDisposed { get; private set; } = false; + + public bool IsConnected => tcpClient.Client != null && tcpClient.Client.Connected; + + protected GodotIdeConnection(TcpClient tcpClient, Func<Message, bool> messageHandler) + { + this.tcpClient = tcpClient; + this.messageHandler = messageHandler; + } + + public void Start() + { + try + { + if (!StartConnection()) + return; + + string messageLine; + while ((messageLine = ReadLine()) != null) + { + if (!MessageParser.TryParse(messageLine, out Message msg)) + { + Logger.LogError($"Received message with invalid format: {messageLine}"); + continue; + } + + Logger.LogDebug($"Received message: {msg}"); + + if (msg.Id == "close") + { + Logger.LogInfo("Closing connection"); + return; + } + + try + { + try + { + Debug.Assert(messageHandler != null); + + if (!messageHandler(msg)) + Logger.LogError($"Received unknown message: {msg}"); + } + catch (Exception e) + { + Logger.LogError($"Message handler for '{msg}' failed with exception", e); + } + } + catch (Exception e) + { + Logger.LogError($"Exception thrown from message handler. Message: {msg}", e); + } + } + } + catch (Exception e) + { + Logger.LogError($"Unhandled exception in the Godot Ide Connection thread", e); + } + finally + { + Dispose(); + } + } + + private bool StartConnection() + { + NetworkStream clientStream = tcpClient.GetStream(); + + clientReader = new StreamReader(clientStream, Encoding.UTF8); + + lock (writeLock) + clientWriter = new StreamWriter(clientStream, Encoding.UTF8); + + clientStream.WriteTimeout = ClientWriteTimeout; + + if (!WriteHandshake()) + { + Logger.LogError("Could not write handshake"); + return false; + } + + if (!IsValidResponseHandshake(ReadLine())) + { + Logger.LogError("Received invalid handshake"); + return false; + } + + Connected?.Invoke(); + + Logger.LogInfo("Godot Ide connection started"); + + return true; + } + + private string ReadLine() + { + try + { + return clientReader?.ReadLine(); + } + catch (Exception e) + { + if (IsDisposed) + { + var se = e as SocketException ?? e.InnerException as SocketException; + if (se != null && se.SocketErrorCode == SocketError.Interrupted) + return null; + } + + throw; + } + } + + public bool WriteMessage(Message message) + { + Logger.LogDebug($"Sending message {message}"); + + var messageComposer = new MessageComposer(); + + messageComposer.AddArgument(message.Id); + foreach (string argument in message.Arguments) + messageComposer.AddArgument(argument); + + return WriteLine(messageComposer.ToString()); + } + + protected bool WriteLine(string text) + { + if (clientWriter == null || IsDisposed || !IsConnected) + return false; + + lock (writeLock) + { + try + { + clientWriter.WriteLine(text); + clientWriter.Flush(); + } + catch (Exception e) + { + if (!IsDisposed) + { + var se = e as SocketException ?? e.InnerException as SocketException; + if (se != null && se.SocketErrorCode == SocketError.Shutdown) + Logger.LogInfo("Client disconnected ungracefully"); + else + Logger.LogError("Exception thrown when trying to write to client", e); + + Dispose(); + } + } + } + + return true; + } + + protected abstract bool WriteHandshake(); + protected abstract bool IsValidResponseHandshake(string handshakeLine); + + public void Dispose() + { + if (IsDisposed) + return; + + IsDisposed = true; + + clientReader?.Dispose(); + clientWriter?.Dispose(); + ((IDisposable) tcpClient)?.Dispose(); + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionClient.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionClient.cs new file mode 100644 index 0000000000..1b11a14358 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionClient.cs @@ -0,0 +1,24 @@ +using System; +using System.Net.Sockets; +using System.Threading.Tasks; + +namespace GodotTools.IdeConnection +{ + public class GodotIdeConnectionClient : GodotIdeConnection + { + public GodotIdeConnectionClient(TcpClient tcpClient, Func<Message, bool> messageHandler) + : base(tcpClient, messageHandler) + { + } + + protected override bool WriteHandshake() + { + return WriteLine(ClientHandshake); + } + + protected override bool IsValidResponseHandshake(string handshakeLine) + { + return handshakeLine == ServerHandshake; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionServer.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionServer.cs new file mode 100644 index 0000000000..aa98dc7ca3 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionServer.cs @@ -0,0 +1,24 @@ +using System; +using System.Net.Sockets; +using System.Threading.Tasks; + +namespace GodotTools.IdeConnection +{ + public class GodotIdeConnectionServer : GodotIdeConnection + { + public GodotIdeConnectionServer(TcpClient tcpClient, Func<Message, bool> messageHandler) + : base(tcpClient, messageHandler) + { + } + + protected override bool WriteHandshake() + { + return WriteLine(ServerHandshake); + } + + protected override bool IsValidResponseHandshake(string handshakeLine) + { + return handshakeLine == ClientHandshake; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeMetadata.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeMetadata.cs new file mode 100644 index 0000000000..d16daba0e2 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeMetadata.cs @@ -0,0 +1,45 @@ +namespace GodotTools.IdeConnection +{ + public struct GodotIdeMetadata + { + public int Port { get; } + public string EditorExecutablePath { get; } + + public GodotIdeMetadata(int port, string editorExecutablePath) + { + Port = port; + EditorExecutablePath = editorExecutablePath; + } + + public static bool operator ==(GodotIdeMetadata a, GodotIdeMetadata b) + { + return a.Port == b.Port && a.EditorExecutablePath == b.EditorExecutablePath; + } + + public static bool operator !=(GodotIdeMetadata a, GodotIdeMetadata b) + { + return !(a == b); + } + + public override bool Equals(object obj) + { + if (obj is GodotIdeMetadata metadata) + return metadata == this; + + return false; + } + + public bool Equals(GodotIdeMetadata other) + { + return Port == other.Port && EditorExecutablePath == other.EditorExecutablePath; + } + + public override int GetHashCode() + { + unchecked + { + return (Port * 397) ^ (EditorExecutablePath != null ? EditorExecutablePath.GetHashCode() : 0); + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj new file mode 100644 index 0000000000..94e525715b --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj @@ -0,0 +1,53 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{92600954-25F0-4291-8E11-1FEE9FC4BE20}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>GodotTools.IdeConnection</RootNamespace> + <AssemblyName>GodotTools.IdeConnection</AssemblyName> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + <LangVersion>7</LangVersion> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugSymbols>true</DebugSymbols> + <DebugType>portable</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugType>portable</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="System" /> + </ItemGroup> + <ItemGroup> + <Compile Include="ConsoleLogger.cs" /> + <Compile Include="GodotIdeMetadata.cs" /> + <Compile Include="GodotIdeBase.cs" /> + <Compile Include="GodotIdeClient.cs" /> + <Compile Include="GodotIdeConnection.cs" /> + <Compile Include="GodotIdeConnectionClient.cs" /> + <Compile Include="GodotIdeConnectionServer.cs" /> + <Compile Include="ILogger.cs" /> + <Compile Include="Message.cs" /> + <Compile Include="MessageComposer.cs" /> + <Compile Include="MessageParser.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> +</Project>
\ No newline at end of file diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ILogger.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ILogger.cs new file mode 100644 index 0000000000..614bb30271 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ILogger.cs @@ -0,0 +1,13 @@ +using System; + +namespace GodotTools.IdeConnection +{ + public interface ILogger + { + void LogDebug(string message); + void LogInfo(string message); + void LogWarning(string message); + void LogError(string message); + void LogError(string message, Exception e); + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Message.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Message.cs new file mode 100644 index 0000000000..f24d324ae3 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Message.cs @@ -0,0 +1,21 @@ +using System.Linq; + +namespace GodotTools.IdeConnection +{ + public struct Message + { + public string Id { get; set; } + public string[] Arguments { get; set; } + + public Message(string id, params string[] arguments) + { + Id = id; + Arguments = arguments; + } + + public override string ToString() + { + return $"(Id: '{Id}', Arguments: '{string.Join(",", Arguments)}')"; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageComposer.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageComposer.cs new file mode 100644 index 0000000000..9e4cd6ec1a --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageComposer.cs @@ -0,0 +1,46 @@ +using System.Linq; +using System.Text; + +namespace GodotTools.IdeConnection +{ + public class MessageComposer + { + private readonly StringBuilder stringBuilder = new StringBuilder(); + + private static readonly char[] CharsToEscape = { '\\', '"' }; + + public void AddArgument(string argument) + { + AddArgument(argument, quoted: argument.Contains(",")); + } + + public void AddArgument(string argument, bool quoted) + { + if (stringBuilder.Length > 0) + stringBuilder.Append(','); + + if (quoted) + { + stringBuilder.Append('"'); + + foreach (char @char in argument) + { + if (CharsToEscape.Contains(@char)) + stringBuilder.Append('\\'); + stringBuilder.Append(@char); + } + + stringBuilder.Append('"'); + } + else + { + stringBuilder.Append(argument); + } + } + + public override string ToString() + { + return stringBuilder.ToString(); + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageParser.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageParser.cs new file mode 100644 index 0000000000..ed691e481f --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageParser.cs @@ -0,0 +1,88 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace GodotTools.IdeConnection +{ + public static class MessageParser + { + public static bool TryParse(string messageLine, out Message message) + { + var arguments = new List<string>(); + var stringBuilder = new StringBuilder(); + + bool expectingArgument = true; + + for (int i = 0; i < messageLine.Length; i++) + { + char @char = messageLine[i]; + + if (@char == ',') + { + if (expectingArgument) + arguments.Add(string.Empty); + + expectingArgument = true; + continue; + } + + bool quoted = false; + + if (messageLine[i] == '"') + { + quoted = true; + i++; + } + + while (i < messageLine.Length) + { + @char = messageLine[i]; + + if (quoted && @char == '"') + { + i++; + break; + } + + if (@char == '\\') + { + i++; + if (i < messageLine.Length) + break; + + stringBuilder.Append(messageLine[i]); + } + else if (!quoted && @char == ',') + { + break; // We don't increment the counter to allow the colon to be parsed after this + } + else + { + stringBuilder.Append(@char); + } + + i++; + } + + arguments.Add(stringBuilder.ToString()); + stringBuilder.Clear(); + + expectingArgument = false; + } + + if (arguments.Count == 0) + { + message = new Message(); + return false; + } + + message = new Message + { + Id = arguments[0], + Arguments = arguments.Skip(1).ToArray() + }; + + return true; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..c7c00e66a2 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("GodotTools.IdeConnection")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("Godot Engine contributors")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("92600954-25F0-4291-8E11-1FEE9FC4BE20")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiAssembliesInfo.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiAssembliesInfo.cs new file mode 100644 index 0000000000..345a472185 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiAssembliesInfo.cs @@ -0,0 +1,15 @@ +namespace GodotTools +{ + public static class ApiAssemblyNames + { + public const string SolutionName = "GodotSharp"; + public const string Core = "GodotSharp"; + public const string Editor = "GodotSharpEditor"; + } + + public enum ApiAssemblyType + { + Core, + Editor + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiSolutionGenerator.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiSolutionGenerator.cs new file mode 100644 index 0000000000..bfae2afc13 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiSolutionGenerator.cs @@ -0,0 +1,52 @@ +using System.Collections.Generic; +using System.IO; + +namespace GodotTools.ProjectEditor +{ + public static class ApiSolutionGenerator + { + public static void GenerateApiSolution(string solutionDir, + string coreProjDir, IEnumerable<string> coreCompileItems, + string editorProjDir, IEnumerable<string> editorCompileItems) + { + var solution = new DotNetSolution(ApiAssemblyNames.SolutionName); + + solution.DirectoryPath = solutionDir; + + // GodotSharp project + + const string coreApiAssemblyName = ApiAssemblyNames.Core; + + string coreGuid = ProjectGenerator.GenCoreApiProject(coreProjDir, coreCompileItems); + + var coreProjInfo = new DotNetSolution.ProjectInfo + { + Guid = coreGuid, + PathRelativeToSolution = Path.Combine(coreApiAssemblyName, $"{coreApiAssemblyName}.csproj") + }; + coreProjInfo.Configs.Add("Debug"); + coreProjInfo.Configs.Add("Release"); + + solution.AddNewProject(coreApiAssemblyName, coreProjInfo); + + // GodotSharpEditor project + + const string editorApiAssemblyName = ApiAssemblyNames.Editor; + + string editorGuid = ProjectGenerator.GenEditorApiProject(editorProjDir, + $"../{coreApiAssemblyName}/{coreApiAssemblyName}.csproj", editorCompileItems); + + var editorProjInfo = new DotNetSolution.ProjectInfo(); + editorProjInfo.Guid = editorGuid; + editorProjInfo.PathRelativeToSolution = Path.Combine(editorApiAssemblyName, $"{editorApiAssemblyName}.csproj"); + editorProjInfo.Configs.Add("Debug"); + editorProjInfo.Configs.Add("Release"); + + solution.AddNewProject(editorApiAssemblyName, editorProjInfo); + + // Save solution + + solution.Save(); + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs new file mode 100644 index 0000000000..76cb249acf --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs @@ -0,0 +1,122 @@ +using GodotTools.Core; +using System.Collections.Generic; +using System.IO; + +namespace GodotTools.ProjectEditor +{ + public class DotNetSolution + { + private string directoryPath; + private readonly Dictionary<string, ProjectInfo> projects = new Dictionary<string, ProjectInfo>(); + + public string Name { get; } + + public string DirectoryPath + { + get => directoryPath; + set => directoryPath = value.IsAbsolutePath() ? value : Path.GetFullPath(value); + } + + public class ProjectInfo + { + public string Guid; + public string PathRelativeToSolution; + public List<string> Configs = new List<string>(); + } + + public void AddNewProject(string name, ProjectInfo projectInfo) + { + projects[name] = projectInfo; + } + + public bool HasProject(string name) + { + return projects.ContainsKey(name); + } + + public ProjectInfo GetProjectInfo(string name) + { + return projects[name]; + } + + public bool RemoveProject(string name) + { + return projects.Remove(name); + } + + public void Save() + { + if (!Directory.Exists(DirectoryPath)) + throw new FileNotFoundException("The solution directory does not exist."); + + string projectsDecl = string.Empty; + string slnPlatformsCfg = string.Empty; + string projPlatformsCfg = string.Empty; + + bool isFirstProject = true; + + foreach (var pair in projects) + { + string name = pair.Key; + ProjectInfo projectInfo = pair.Value; + + if (!isFirstProject) + projectsDecl += "\n"; + + projectsDecl += string.Format(ProjectDeclaration, + name, projectInfo.PathRelativeToSolution.Replace("/", "\\"), projectInfo.Guid); + + for (int i = 0; i < projectInfo.Configs.Count; i++) + { + string config = projectInfo.Configs[i]; + + if (i != 0 || !isFirstProject) + { + slnPlatformsCfg += "\n"; + projPlatformsCfg += "\n"; + } + + slnPlatformsCfg += string.Format(SolutionPlatformsConfig, config); + projPlatformsCfg += string.Format(ProjectPlatformsConfig, projectInfo.Guid, config); + } + + isFirstProject = false; + } + + string solutionPath = Path.Combine(DirectoryPath, Name + ".sln"); + string content = string.Format(SolutionTemplate, projectsDecl, slnPlatformsCfg, projPlatformsCfg); + + File.WriteAllText(solutionPath, content); + } + + public DotNetSolution(string name) + { + Name = name; + } + + const string SolutionTemplate = +@"Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +{0} +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution +{1} + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution +{2} + EndGlobalSection +EndGlobal +"; + + const string ProjectDeclaration = +@"Project(""{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}"") = ""{0}"", ""{1}"", ""{{{2}}}"" +EndProject"; + + const string SolutionPlatformsConfig = +@" {0}|Any CPU = {0}|Any CPU"; + + const string ProjectPlatformsConfig = +@" {{{0}}}.{1}|Any CPU.ActiveCfg = {1}|Any CPU + {{{0}}}.{1}|Any CPU.Build.0 = {1}|Any CPU"; + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj new file mode 100644 index 0000000000..ab3a5d1aea --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}</ProjectGuid> + <OutputType>Library</OutputType> + <RootNamespace>GodotTools.ProjectEditor</RootNamespace> + <AssemblyName>GodotTools.ProjectEditor</AssemblyName> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <BaseIntermediateOutputPath>obj</BaseIntermediateOutputPath> + <LangVersion>7</LangVersion> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>portable</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug</OutputPath> + <DefineConstants>DEBUG;</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <ConsolePause>false</ConsolePause> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <Optimize>true</Optimize> + <OutputPath>bin\Release</OutputPath> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <ConsolePause>false</ConsolePause> + </PropertyGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="Microsoft.Build" /> + <Reference Include="DotNet.Glob, Version=2.1.1.0, Culture=neutral, PublicKeyToken=b68cc888b4f632d1, processorArchitecture=MSIL"> + <!-- + When building Godot with 'mono_glue=no' SCons will build this project alone instead of the + entire solution. $(SolutionDir) is not defined in that case, so we need to workaround that. + We make SCons restore the NuGet packages in the project directory instead in this case. + --> + <HintPath Condition=" '$(SolutionDir)' != '' And Exists('$(SolutionDir)\packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll') ">$(SolutionDir)\packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll</HintPath> + <HintPath Condition=" '$(SolutionDir)' == '' Or !Exists('$(SolutionDir)\packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll') ">$(ProjectDir)\packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll</HintPath> + </Reference> + </ItemGroup> + <ItemGroup> + <Compile Include="ApiAssembliesInfo.cs" /> + <Compile Include="ApiSolutionGenerator.cs" /> + <Compile Include="DotNetSolution.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="IdentifierUtils.cs" /> + <Compile Include="ProjectExtensions.cs" /> + <Compile Include="ProjectGenerator.cs" /> + <Compile Include="ProjectUtils.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="packages.config" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj"> + <Project>{639E48BD-44E5-4091-8EDD-22D36DC0768D}</Project> + <Name>GodotTools.Core</Name> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> +</Project> diff --git a/modules/mono/editor/GodotSharpTools/Project/IdentifierUtils.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs index 83e2d2cf8d..f93eb9a1fa 100644 --- a/modules/mono/editor/GodotSharpTools/Project/IdentifierUtils.cs +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.Text; -namespace GodotSharpTools.Project +namespace GodotTools.ProjectEditor { public static class IdentifierUtils { @@ -12,7 +12,7 @@ namespace GodotSharpTools.Project if (string.IsNullOrEmpty(qualifiedIdentifier)) throw new ArgumentException($"{nameof(qualifiedIdentifier)} cannot be empty", nameof(qualifiedIdentifier)); - string[] identifiers = qualifiedIdentifier.Split(new[] { '.' }); + string[] identifiers = qualifiedIdentifier.Split('.'); for (int i = 0; i < identifiers.Length; i++) { @@ -66,8 +66,6 @@ namespace GodotSharpTools.Project if (identifierBuilder.Length > startIndex || @char == '_') identifierBuilder.Append(@char); break; - default: - break; } } @@ -97,14 +95,14 @@ namespace GodotSharpTools.Project } else { - if (_doubleUnderscoreKeywords.Contains(value)) + if (DoubleUnderscoreKeywords.Contains(value)) return true; } - return _keywords.Contains(value); + return Keywords.Contains(value); } - static HashSet<string> _doubleUnderscoreKeywords = new HashSet<string> + private static readonly HashSet<string> DoubleUnderscoreKeywords = new HashSet<string> { "__arglist", "__makeref", @@ -112,7 +110,7 @@ namespace GodotSharpTools.Project "__refvalue", }; - static HashSet<string> _keywords = new HashSet<string> + private static readonly HashSet<string> Keywords = new HashSet<string> { "as", "do", diff --git a/modules/mono/editor/GodotSharpTools/Project/ProjectExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs index 647d9ac81d..36961eb45e 100644 --- a/modules/mono/editor/GodotSharpTools/Project/ProjectExtensions.cs +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs @@ -1,8 +1,9 @@ +using GodotTools.Core; using System; using DotNet.Globbing; using Microsoft.Build.Construction; -namespace GodotSharpTools.Project +namespace GodotTools.ProjectEditor { public static class ProjectExtensions { diff --git a/modules/mono/editor/GodotSharpTools/Project/ProjectGenerator.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs index 89279c69a6..4f21871f1a 100644 --- a/modules/mono/editor/GodotSharpTools/Project/ProjectGenerator.cs +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs @@ -1,17 +1,19 @@ +using GodotTools.Core; using System; +using System.Collections.Generic; using System.IO; using Microsoft.Build.Construction; -namespace GodotSharpTools.Project +namespace GodotTools.ProjectEditor { public static class ProjectGenerator { - public const string CoreApiProjectName = "GodotSharp"; - public const string EditorApiProjectName = "GodotSharpEditor"; - const string CoreApiProjectGuid = "{AEBF0036-DA76-4341-B651-A3F2856AB2FA}"; - const string EditorApiProjectGuid = "{8FBEC238-D944-4074-8548-B3B524305905}"; + private const string CoreApiProjectName = "GodotSharp"; + private const string EditorApiProjectName = "GodotSharpEditor"; + private const string CoreApiProjectGuid = "{AEBF0036-DA76-4341-B651-A3F2856AB2FA}"; + private const string EditorApiProjectGuid = "{8FBEC238-D944-4074-8548-B3B524305905}"; - public static string GenCoreApiProject(string dir, string[] compileItems) + public static string GenCoreApiProject(string dir, IEnumerable<string> compileItems) { string path = Path.Combine(dir, CoreApiProjectName + ".csproj"); @@ -24,8 +26,8 @@ namespace GodotSharpTools.Project mainGroup.SetProperty("BaseIntermediateOutputPath", "obj"); GenAssemblyInfoFile(root, dir, CoreApiProjectName, - new string[] { "[assembly: InternalsVisibleTo(\"" + EditorApiProjectName + "\")]" }, - new string[] { "System.Runtime.CompilerServices" }); + new[] {"[assembly: InternalsVisibleTo(\"" + EditorApiProjectName + "\")]"}, + new[] {"System.Runtime.CompilerServices"}); foreach (var item in compileItems) { @@ -37,7 +39,7 @@ namespace GodotSharpTools.Project return CoreApiProjectGuid; } - public static string GenEditorApiProject(string dir, string coreApiProjPath, string[] compileItems) + public static string GenEditorApiProject(string dir, string coreApiProjPath, IEnumerable<string> compileItems) { string path = Path.Combine(dir, EditorApiProjectName + ".csproj"); @@ -64,7 +66,7 @@ namespace GodotSharpTools.Project return EditorApiProjectGuid; } - public static string GenGameProject(string dir, string name, string[] compileItems) + public static string GenGameProject(string dir, string name, IEnumerable<string> compileItems) { string path = Path.Combine(dir, name + ".csproj"); @@ -74,24 +76,26 @@ namespace GodotSharpTools.Project mainGroup.SetProperty("OutputPath", Path.Combine(".mono", "temp", "bin", "$(Configuration)")); mainGroup.SetProperty("BaseIntermediateOutputPath", Path.Combine(".mono", "temp", "obj")); mainGroup.SetProperty("IntermediateOutputPath", Path.Combine("$(BaseIntermediateOutputPath)", "$(Configuration)")); + mainGroup.SetProperty("ApiConfiguration", "Debug").Condition = " '$(Configuration)' != 'Release' "; + mainGroup.SetProperty("ApiConfiguration", "Release").Condition = " '$(Configuration)' == 'Release' "; var toolsGroup = root.AddPropertyGroup(); toolsGroup.Condition = " '$(Configuration)|$(Platform)' == 'Tools|AnyCPU' "; toolsGroup.AddProperty("DebugSymbols", "true"); toolsGroup.AddProperty("DebugType", "portable"); toolsGroup.AddProperty("Optimize", "false"); - toolsGroup.AddProperty("DefineConstants", "DEBUG;TOOLS;"); + toolsGroup.AddProperty("DefineConstants", "$(GodotDefineConstants);GODOT;DEBUG;TOOLS;"); toolsGroup.AddProperty("ErrorReport", "prompt"); toolsGroup.AddProperty("WarningLevel", "4"); toolsGroup.AddProperty("ConsolePause", "false"); var coreApiRef = root.AddItem("Reference", CoreApiProjectName); - coreApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", CoreApiProjectName + ".dll")); + coreApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", "$(ApiConfiguration)", CoreApiProjectName + ".dll")); coreApiRef.AddMetadata("Private", "False"); var editorApiRef = root.AddItem("Reference", EditorApiProjectName); editorApiRef.Condition = " '$(Configuration)' == 'Tools' "; - editorApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", EditorApiProjectName + ".dll")); + editorApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", "$(ApiConfiguration)", EditorApiProjectName + ".dll")); editorApiRef.AddMetadata("Private", "False"); GenAssemblyInfoFile(root, dir, name); @@ -108,7 +112,6 @@ namespace GodotSharpTools.Project public static void GenAssemblyInfoFile(ProjectRootElement root, string dir, string name, string[] assemblyLines = null, string[] usingDirectives = null) { - string propertiesDir = Path.Combine(dir, "Properties"); if (!Directory.Exists(propertiesDir)) Directory.CreateDirectory(propertiesDir); @@ -124,12 +127,9 @@ namespace GodotSharpTools.Project string assemblyLinesText = string.Empty; if (assemblyLines != null) - { - foreach (var assemblyLine in assemblyLines) - assemblyLinesText += string.Join("\n", assemblyLines) + "\n"; - } + assemblyLinesText += string.Join("\n", assemblyLines) + "\n"; - string content = string.Format(assemblyInfoTemplate, usingDirectivesText, name, assemblyLinesText); + string content = string.Format(AssemblyInfoTemplate, usingDirectivesText, name, assemblyLinesText); string assemblyInfoFile = Path.Combine(propertiesDir, "AssemblyInfo.cs"); @@ -161,7 +161,7 @@ namespace GodotSharpTools.Project debugGroup.AddProperty("DebugSymbols", "true"); debugGroup.AddProperty("DebugType", "portable"); debugGroup.AddProperty("Optimize", "false"); - debugGroup.AddProperty("DefineConstants", "DEBUG;"); + debugGroup.AddProperty("DefineConstants", "$(GodotDefineConstants);GODOT;DEBUG;"); debugGroup.AddProperty("ErrorReport", "prompt"); debugGroup.AddProperty("WarningLevel", "4"); debugGroup.AddProperty("ConsolePause", "false"); @@ -170,6 +170,7 @@ namespace GodotSharpTools.Project releaseGroup.Condition = " '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "; releaseGroup.AddProperty("DebugType", "portable"); releaseGroup.AddProperty("Optimize", "true"); + releaseGroup.AddProperty("DefineConstants", "$(GodotDefineConstants);GODOT;"); releaseGroup.AddProperty("ErrorReport", "prompt"); releaseGroup.AddProperty("WarningLevel", "4"); releaseGroup.AddProperty("ConsolePause", "false"); @@ -193,8 +194,8 @@ namespace GodotSharpTools.Project } } - private const string assemblyInfoTemplate = -@"using System.Reflection;{0} + private const string AssemblyInfoTemplate = + @"using System.Reflection;{0} // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs new file mode 100644 index 0000000000..233aab45b3 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs @@ -0,0 +1,175 @@ +using GodotTools.Core; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using DotNet.Globbing; +using Microsoft.Build.Construction; + +namespace GodotTools.ProjectEditor +{ + public static class ProjectUtils + { + public static void AddItemToProjectChecked(string projectPath, string itemType, string include) + { + var dir = Directory.GetParent(projectPath).FullName; + var root = ProjectRootElement.Open(projectPath); + Debug.Assert(root != null); + + var normalizedInclude = include.RelativeToPath(dir).Replace("/", "\\"); + + if (root.AddItemChecked(itemType, normalizedInclude)) + root.Save(); + } + + private static string[] GetAllFilesRecursive(string rootDirectory, string mask) + { + string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories); + + // We want relative paths + for (int i = 0; i < files.Length; i++) + { + files[i] = files[i].RelativeToPath(rootDirectory); + } + + return files; + } + + public static string[] GetIncludeFiles(string projectPath, string itemType) + { + var result = new List<string>(); + var existingFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs"); + + var globOptions = new GlobOptions(); + globOptions.Evaluation.CaseInsensitive = false; + + var root = ProjectRootElement.Open(projectPath); + + foreach (var itemGroup in root.ItemGroups) + { + if (itemGroup.Condition.Length != 0) + continue; + + foreach (var item in itemGroup.Items) + { + if (item.ItemType != itemType) + continue; + + string normalizedInclude = item.Include.NormalizePath(); + + var glob = Glob.Parse(normalizedInclude, globOptions); + + // TODO Check somehow if path has no blob to avoid the following loop... + + foreach (var existingFile in existingFiles) + { + if (glob.IsMatch(existingFile)) + { + result.Add(existingFile); + } + } + } + } + + return result.ToArray(); + } + + /// Simple function to make sure the Api assembly references are configured correctly + public static void FixApiHintPath(string projectPath) + { + var root = ProjectRootElement.Open(projectPath); + Debug.Assert(root != null); + + bool dirty = false; + + void AddPropertyIfNotPresent(string name, string condition, string value) + { + if (root.PropertyGroups + .Any(g => (g.Condition == string.Empty || g.Condition == condition) && + g.Properties + .Any(p => p.Name == name && + p.Value == value && + (p.Condition == condition || g.Condition == condition)))) + { + return; + } + + root.AddProperty(name, value).Condition = condition; + dirty = true; + } + + AddPropertyIfNotPresent(name: "ApiConfiguration", + condition: " '$(Configuration)' != 'Release' ", + value: "Debug"); + AddPropertyIfNotPresent(name: "ApiConfiguration", + condition: " '$(Configuration)' == 'Release' ", + value: "Release"); + + void SetReferenceHintPath(string referenceName, string condition, string hintPath) + { + foreach (var itemGroup in root.ItemGroups.Where(g => + g.Condition == string.Empty || g.Condition == condition)) + { + var references = itemGroup.Items.Where(item => + item.ItemType == "Reference" && + item.Include == referenceName && + (item.Condition == condition || itemGroup.Condition == condition)); + + var referencesWithHintPath = references.Where(reference => + reference.Metadata.Any(m => m.Name == "HintPath")); + + if (referencesWithHintPath.Any(reference => reference.Metadata + .Any(m => m.Name == "HintPath" && m.Value == hintPath))) + { + // Found a Reference item with the right HintPath + return; + } + + var referenceWithHintPath = referencesWithHintPath.FirstOrDefault(); + if (referenceWithHintPath != null) + { + // Found a Reference item with a wrong HintPath + foreach (var metadata in referenceWithHintPath.Metadata.ToList() + .Where(m => m.Name == "HintPath")) + { + // Safe to remove as we duplicate with ToList() to loop + referenceWithHintPath.RemoveChild(metadata); + } + + referenceWithHintPath.AddMetadata("HintPath", hintPath); + dirty = true; + return; + } + + var referenceWithoutHintPath = references.FirstOrDefault(); + if (referenceWithoutHintPath != null) + { + // Found a Reference item without a HintPath + referenceWithoutHintPath.AddMetadata("HintPath", hintPath); + dirty = true; + return; + } + } + + // Found no Reference item at all. Add it. + root.AddItem("Reference", referenceName).Condition = condition; + dirty = true; + } + + const string coreProjectName = "GodotSharp"; + const string editorProjectName = "GodotSharpEditor"; + + const string coreCondition = ""; + const string editorCondition = " '$(Configuration)' == 'Tools' "; + + var coreHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{coreProjectName}.dll"; + var editorHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{editorProjectName}.dll"; + + SetReferenceHintPath(coreProjectName, coreCondition, coreHintPath); + SetReferenceHintPath(editorProjectName, editorCondition, editorHintPath); + + if (dirty) + root.Save(); + } + } +} diff --git a/modules/mono/editor/GodotSharpTools/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/Properties/AssemblyInfo.cs index 7115d8fc71..09333850fc 100644 --- a/modules/mono/editor/GodotSharpTools/Properties/AssemblyInfo.cs +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/Properties/AssemblyInfo.cs @@ -4,12 +4,12 @@ using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. -[assembly: AssemblyTitle("GodotSharpTools")] +[assembly: AssemblyTitle("GodotTools.ProjectEditor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("ignacio")] +[assembly: AssemblyCopyright("Godot Engine contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/modules/mono/editor/GodotSharpTools/packages.config b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/packages.config index 2c7cb0bd4b..13915000e4 100644 --- a/modules/mono/editor/GodotSharpTools/packages.config +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/packages.config @@ -1,4 +1,4 @@ -<?xml version="1.0" encoding="utf-8"?> +<?xml version="1.0" encoding="utf-8"?> <packages> <package id="DotNet.Glob" version="2.1.1" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/modules/mono/editor/GodotTools/GodotTools.sln b/modules/mono/editor/GodotTools/GodotTools.sln new file mode 100644 index 0000000000..a3438ea5f3 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools.sln @@ -0,0 +1,41 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.ProjectEditor", "GodotTools.ProjectEditor\GodotTools.ProjectEditor.csproj", "{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools", "GodotTools\GodotTools.csproj", "{27B00618-A6F2-4828-B922-05CAEB08C286}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.Core", "GodotTools.Core\GodotTools.Core.csproj", "{639E48BD-44E5-4091-8EDD-22D36DC0768D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.BuildLogger", "GodotTools.BuildLogger\GodotTools.BuildLogger.csproj", "{6CE9A984-37B1-4F8A-8FE9-609F05F071B3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.IdeConnection", "GodotTools.IdeConnection\GodotTools.IdeConnection.csproj", "{92600954-25F0-4291-8E11-1FEE9FC4BE20}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Release|Any CPU.Build.0 = Release|Any CPU + {27B00618-A6F2-4828-B922-05CAEB08C286}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {27B00618-A6F2-4828-B922-05CAEB08C286}.Debug|Any CPU.Build.0 = Debug|Any CPU + {27B00618-A6F2-4828-B922-05CAEB08C286}.Release|Any CPU.ActiveCfg = Release|Any CPU + {27B00618-A6F2-4828-B922-05CAEB08C286}.Release|Any CPU.Build.0 = Release|Any CPU + {639E48BD-44E5-4091-8EDD-22D36DC0768D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {639E48BD-44E5-4091-8EDD-22D36DC0768D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {639E48BD-44E5-4091-8EDD-22D36DC0768D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {639E48BD-44E5-4091-8EDD-22D36DC0768D}.Release|Any CPU.Build.0 = Release|Any CPU + {6CE9A984-37B1-4F8A-8FE9-609F05F071B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6CE9A984-37B1-4F8A-8FE9-609F05F071B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6CE9A984-37B1-4F8A-8FE9-609F05F071B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6CE9A984-37B1-4F8A-8FE9-609F05F071B3}.Release|Any CPU.Build.0 = Release|Any CPU + {92600954-25F0-4291-8E11-1FEE9FC4BE20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {92600954-25F0-4291-8E11-1FEE9FC4BE20}.Debug|Any CPU.Build.0 = Debug|Any CPU + {92600954-25F0-4291-8E11-1FEE9FC4BE20}.Release|Any CPU.ActiveCfg = Release|Any CPU + {92600954-25F0-4291-8E11-1FEE9FC4BE20}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/modules/mono/editor/GodotTools/GodotTools/BottomPanel.cs b/modules/mono/editor/GodotTools/GodotTools/BottomPanel.cs new file mode 100644 index 0000000000..44813f962c --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/BottomPanel.cs @@ -0,0 +1,343 @@ +using Godot; +using System; +using System.IO; +using Godot.Collections; +using GodotTools.Internals; +using static GodotTools.Internals.Globals; +using File = GodotTools.Utils.File; +using Path = System.IO.Path; + +namespace GodotTools +{ + public class BottomPanel : VBoxContainer + { + private EditorInterface editorInterface; + + private TabContainer panelTabs; + + private VBoxContainer panelBuildsTab; + + private ItemList buildTabsList; + private TabContainer buildTabs; + + private ToolButton warningsBtn; + private ToolButton errorsBtn; + private Button viewLogBtn; + + private void _UpdateBuildTabsList() + { + buildTabsList.Clear(); + + int currentTab = buildTabs.CurrentTab; + + bool noCurrentTab = currentTab < 0 || currentTab >= buildTabs.GetTabCount(); + + for (int i = 0; i < buildTabs.GetChildCount(); i++) + { + var tab = (BuildTab) buildTabs.GetChild(i); + + if (tab == null) + continue; + + string itemName = Path.GetFileNameWithoutExtension(tab.BuildInfo.Solution); + itemName += " [" + tab.BuildInfo.Configuration + "]"; + + buildTabsList.AddItem(itemName, tab.IconTexture); + + string itemTooltip = "Solution: " + tab.BuildInfo.Solution; + itemTooltip += "\nConfiguration: " + tab.BuildInfo.Configuration; + itemTooltip += "\nStatus: "; + + if (tab.BuildExited) + itemTooltip += tab.BuildResult == BuildTab.BuildResults.Success ? "Succeeded" : "Errored"; + else + itemTooltip += "Running"; + + if (!tab.BuildExited || tab.BuildResult == BuildTab.BuildResults.Error) + itemTooltip += $"\nErrors: {tab.ErrorCount}"; + + itemTooltip += $"\nWarnings: {tab.WarningCount}"; + + buildTabsList.SetItemTooltip(i, itemTooltip); + + if (noCurrentTab || currentTab == i) + { + buildTabsList.Select(i); + _BuildTabsItemSelected(i); + } + } + } + + public BuildTab GetBuildTabFor(BuildInfo buildInfo) + { + foreach (var buildTab in new Array<BuildTab>(buildTabs.GetChildren())) + { + if (buildTab.BuildInfo.Equals(buildInfo)) + return buildTab; + } + + var newBuildTab = new BuildTab(buildInfo); + AddBuildTab(newBuildTab); + + return newBuildTab; + } + + private void _BuildTabsItemSelected(int idx) + { + if (idx < 0 || idx >= buildTabs.GetTabCount()) + throw new IndexOutOfRangeException(); + + buildTabs.CurrentTab = idx; + if (!buildTabs.Visible) + buildTabs.Visible = true; + + warningsBtn.Visible = true; + errorsBtn.Visible = true; + viewLogBtn.Visible = true; + } + + private void _BuildTabsNothingSelected() + { + if (buildTabs.GetTabCount() != 0) + { + // just in case + buildTabs.Visible = false; + + // This callback is called when clicking on the empty space of the list. + // ItemList won't deselect the items automatically, so we must do it ourselves. + buildTabsList.UnselectAll(); + } + + warningsBtn.Visible = false; + errorsBtn.Visible = false; + viewLogBtn.Visible = false; + } + + private void _WarningsToggled(bool pressed) + { + int currentTab = buildTabs.CurrentTab; + + if (currentTab < 0 || currentTab >= buildTabs.GetTabCount()) + throw new InvalidOperationException("No tab selected"); + + var buildTab = (BuildTab) buildTabs.GetChild(currentTab); + buildTab.WarningsVisible = pressed; + buildTab.UpdateIssuesList(); + } + + private void _ErrorsToggled(bool pressed) + { + int currentTab = buildTabs.CurrentTab; + + if (currentTab < 0 || currentTab >= buildTabs.GetTabCount()) + throw new InvalidOperationException("No tab selected"); + + var buildTab = (BuildTab) buildTabs.GetChild(currentTab); + buildTab.ErrorsVisible = pressed; + buildTab.UpdateIssuesList(); + } + + public void BuildProjectPressed() + { + if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) + return; // No solution to build + + string editorScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor"); + string playerScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor_player"); + + CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, editorScriptsMetadataPath); + + if (File.Exists(editorScriptsMetadataPath)) + { + try + { + File.Copy(editorScriptsMetadataPath, playerScriptsMetadataPath); + } + catch (IOException e) + { + GD.PushError($"Failed to copy scripts metadata file. Exception message: {e.Message}"); + return; + } + } + + var godotDefines = new[] + { + OS.GetName(), + Internal.GodotIs32Bits() ? "32" : "64" + }; + + bool buildSuccess = BuildManager.BuildProjectBlocking("Tools", godotDefines); + + if (!buildSuccess) + return; + + // Notify running game for hot-reload + Internal.ScriptEditorDebuggerReloadScripts(); + + // Hot-reload in the editor + GodotSharpEditor.Instance.GetNode<HotReloadAssemblyWatcher>("HotReloadAssemblyWatcher").RestartTimer(); + + if (Internal.IsAssembliesReloadingNeeded()) + Internal.ReloadAssemblies(softReload: false); + } + + private void _ViewLogPressed() + { + if (!buildTabsList.IsAnythingSelected()) + return; + + var selectedItems = buildTabsList.GetSelectedItems(); + + if (selectedItems.Length != 1) + throw new InvalidOperationException($"Expected 1 selected item, got {selectedItems.Length}"); + + int selectedItem = selectedItems[0]; + + var buildTab = (BuildTab) buildTabs.GetTabControl(selectedItem); + + OS.ShellOpen(Path.Combine(buildTab.BuildInfo.LogsDirPath, BuildManager.MsBuildLogFileName)); + } + + public override void _Notification(int what) + { + base._Notification(what); + + if (what == EditorSettings.NotificationEditorSettingsChanged) + { + var editorBaseControl = editorInterface.GetBaseControl(); + panelTabs.AddStyleboxOverride("panel", editorBaseControl.GetStylebox("DebuggerPanel", "EditorStyles")); + panelTabs.AddStyleboxOverride("tab_fg", editorBaseControl.GetStylebox("DebuggerTabFG", "EditorStyles")); + panelTabs.AddStyleboxOverride("tab_bg", editorBaseControl.GetStylebox("DebuggerTabBG", "EditorStyles")); + } + } + + public void AddBuildTab(BuildTab buildTab) + { + buildTabs.AddChild(buildTab); + RaiseBuildTab(buildTab); + } + + public void RaiseBuildTab(BuildTab buildTab) + { + if (buildTab.GetParent() != buildTabs) + throw new InvalidOperationException("Build tab is not in the tabs list"); + + buildTabs.MoveChild(buildTab, 0); + _UpdateBuildTabsList(); + } + + public void ShowBuildTab() + { + for (int i = 0; i < panelTabs.GetTabCount(); i++) + { + if (panelTabs.GetTabControl(i) == panelBuildsTab) + { + panelTabs.CurrentTab = i; + GodotSharpEditor.Instance.MakeBottomPanelItemVisible(this); + return; + } + } + + GD.PushError("Builds tab not found"); + } + + public override void _Ready() + { + base._Ready(); + + editorInterface = GodotSharpEditor.Instance.GetEditorInterface(); + + var editorBaseControl = editorInterface.GetBaseControl(); + + SizeFlagsVertical = (int) SizeFlags.ExpandFill; + SetAnchorsAndMarginsPreset(LayoutPreset.Wide); + + panelTabs = new TabContainer + { + TabAlign = TabContainer.TabAlignEnum.Left, + RectMinSize = new Vector2(0, 228) * EditorScale, + SizeFlagsVertical = (int) SizeFlags.ExpandFill + }; + panelTabs.AddStyleboxOverride("panel", editorBaseControl.GetStylebox("DebuggerPanel", "EditorStyles")); + panelTabs.AddStyleboxOverride("tab_fg", editorBaseControl.GetStylebox("DebuggerTabFG", "EditorStyles")); + panelTabs.AddStyleboxOverride("tab_bg", editorBaseControl.GetStylebox("DebuggerTabBG", "EditorStyles")); + AddChild(panelTabs); + + { + // Builds tab + panelBuildsTab = new VBoxContainer + { + Name = "Builds".TTR(), + SizeFlagsHorizontal = (int) SizeFlags.ExpandFill + }; + panelTabs.AddChild(panelBuildsTab); + + var toolBarHBox = new HBoxContainer {SizeFlagsHorizontal = (int) SizeFlags.ExpandFill}; + panelBuildsTab.AddChild(toolBarHBox); + + var buildProjectBtn = new Button + { + Text = "Build Project".TTR(), + FocusMode = FocusModeEnum.None + }; + buildProjectBtn.Connect("pressed", this, nameof(BuildProjectPressed)); + toolBarHBox.AddChild(buildProjectBtn); + + toolBarHBox.AddSpacer(begin: false); + + warningsBtn = new ToolButton + { + Text = "Warnings".TTR(), + ToggleMode = true, + Pressed = true, + Visible = false, + FocusMode = FocusModeEnum.None + }; + warningsBtn.Connect("toggled", this, nameof(_WarningsToggled)); + toolBarHBox.AddChild(warningsBtn); + + errorsBtn = new ToolButton + { + Text = "Errors".TTR(), + ToggleMode = true, + Pressed = true, + Visible = false, + FocusMode = FocusModeEnum.None + }; + errorsBtn.Connect("toggled", this, nameof(_ErrorsToggled)); + toolBarHBox.AddChild(errorsBtn); + + toolBarHBox.AddSpacer(begin: false); + + viewLogBtn = new Button + { + Text = "View log".TTR(), + FocusMode = FocusModeEnum.None, + Visible = false + }; + viewLogBtn.Connect("pressed", this, nameof(_ViewLogPressed)); + toolBarHBox.AddChild(viewLogBtn); + + var hsc = new HSplitContainer + { + SizeFlagsHorizontal = (int) SizeFlags.ExpandFill, + SizeFlagsVertical = (int) SizeFlags.ExpandFill + }; + panelBuildsTab.AddChild(hsc); + + buildTabsList = new ItemList {SizeFlagsHorizontal = (int) SizeFlags.ExpandFill}; + buildTabsList.Connect("item_selected", this, nameof(_BuildTabsItemSelected)); + buildTabsList.Connect("nothing_selected", this, nameof(_BuildTabsNothingSelected)); + hsc.AddChild(buildTabsList); + + buildTabs = new TabContainer + { + TabAlign = TabContainer.TabAlignEnum.Left, + SizeFlagsHorizontal = (int) SizeFlags.ExpandFill, + TabsVisible = false + }; + hsc.AddChild(buildTabs); + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs new file mode 100644 index 0000000000..da90c960e5 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs @@ -0,0 +1,172 @@ +using GodotTools.Core; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Diagnostics; +using System.IO; +using System.Threading.Tasks; +using GodotTools.BuildLogger; +using GodotTools.Internals; +using GodotTools.Utils; +using Directory = System.IO.Directory; + +namespace GodotTools.Build +{ + public static class BuildSystem + { + private static string GetMsBuildPath() + { + string msbuildPath = MsBuildFinder.FindMsBuild(); + + if (msbuildPath == null) + throw new FileNotFoundException("Cannot find the MSBuild executable."); + + return msbuildPath; + } + + private static string MonoWindowsBinDir + { + get + { + string monoWinBinDir = Path.Combine(Internal.MonoWindowsInstallRoot, "bin"); + + if (!Directory.Exists(monoWinBinDir)) + throw new FileNotFoundException("Cannot find the Windows Mono install bin directory."); + + return monoWinBinDir; + } + } + + private static Godot.EditorSettings EditorSettings => + GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); + + private static bool UsingMonoMsBuildOnWindows + { + get + { + if (OS.IsWindows) + { + return (BuildManager.BuildTool) EditorSettings.GetSetting("mono/builds/build_tool") + == BuildManager.BuildTool.MsBuildMono; + } + + return false; + } + } + + private static bool PrintBuildOutput => + (bool) EditorSettings.GetSetting("mono/builds/print_build_output"); + + private static Process LaunchBuild(string solution, string config, string loggerOutputDir, IEnumerable<string> customProperties = null) + { + var customPropertiesList = new List<string>(); + + if (customProperties != null) + customPropertiesList.AddRange(customProperties); + + string compilerArgs = BuildArguments(solution, config, loggerOutputDir, customPropertiesList); + + var startInfo = new ProcessStartInfo(GetMsBuildPath(), compilerArgs); + + bool redirectOutput = !IsDebugMsBuildRequested() && !PrintBuildOutput; + + if (!redirectOutput || Godot.OS.IsStdoutVerbose()) + Console.WriteLine($"Running: \"{startInfo.FileName}\" {startInfo.Arguments}"); + + startInfo.RedirectStandardOutput = redirectOutput; + startInfo.RedirectStandardError = redirectOutput; + startInfo.UseShellExecute = false; + + if (UsingMonoMsBuildOnWindows) + { + // These environment variables are required for Mono's MSBuild to find the compilers. + // We use the batch files in Mono's bin directory to make sure the compilers are executed with mono. + string monoWinBinDir = MonoWindowsBinDir; + startInfo.EnvironmentVariables.Add("CscToolExe", Path.Combine(monoWinBinDir, "csc.bat")); + startInfo.EnvironmentVariables.Add("VbcToolExe", Path.Combine(monoWinBinDir, "vbc.bat")); + startInfo.EnvironmentVariables.Add("FscToolExe", Path.Combine(monoWinBinDir, "fsharpc.bat")); + } + + // Needed when running from Developer Command Prompt for VS + RemovePlatformVariable(startInfo.EnvironmentVariables); + + var process = new Process {StartInfo = startInfo}; + + process.Start(); + + if (redirectOutput) + { + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + } + + return process; + } + + public static int Build(BuildInfo buildInfo) + { + return Build(buildInfo.Solution, buildInfo.Configuration, + buildInfo.LogsDirPath, buildInfo.CustomProperties); + } + + public static async Task<int> BuildAsync(BuildInfo buildInfo) + { + return await BuildAsync(buildInfo.Solution, buildInfo.Configuration, + buildInfo.LogsDirPath, buildInfo.CustomProperties); + } + + public static int Build(string solution, string config, string loggerOutputDir, IEnumerable<string> customProperties = null) + { + using (var process = LaunchBuild(solution, config, loggerOutputDir, customProperties)) + { + process.WaitForExit(); + + return process.ExitCode; + } + } + + public static async Task<int> BuildAsync(string solution, string config, string loggerOutputDir, IEnumerable<string> customProperties = null) + { + using (var process = LaunchBuild(solution, config, loggerOutputDir, customProperties)) + { + await process.WaitForExitAsync(); + + return process.ExitCode; + } + } + + private static string BuildArguments(string solution, string config, string loggerOutputDir, List<string> customProperties) + { + string arguments = $@"""{solution}"" /v:normal /t:Build ""/p:{"Configuration=" + config}"" " + + $@"""/l:{typeof(GodotBuildLogger).FullName},{GodotBuildLogger.AssemblyPath};{loggerOutputDir}"""; + + foreach (string customProperty in customProperties) + { + arguments += " /p:" + customProperty; + } + + return arguments; + } + + private static void RemovePlatformVariable(StringDictionary environmentVariables) + { + // EnvironmentVariables is case sensitive? Seriously? + + var platformEnvironmentVariables = new List<string>(); + + foreach (string env in environmentVariables.Keys) + { + if (env.ToUpper() == "PLATFORM") + platformEnvironmentVariables.Add(env); + } + + foreach (string env in platformEnvironmentVariables) + environmentVariables.Remove(env); + } + + private static bool IsDebugMsBuildRequested() + { + return Environment.GetEnvironmentVariable("GODOT_DEBUG_MSBUILD")?.Trim() == "1"; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs b/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs new file mode 100644 index 0000000000..ad8a6516ab --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Godot; +using GodotTools.Internals; +using Directory = System.IO.Directory; +using Environment = System.Environment; +using File = System.IO.File; +using Path = System.IO.Path; +using OS = GodotTools.Utils.OS; + +namespace GodotTools.Build +{ + public static class MsBuildFinder + { + private static string _msbuildToolsPath = string.Empty; + private static string _msbuildUnixPath = string.Empty; + + public static string FindMsBuild() + { + var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); + var buildTool = (BuildManager.BuildTool) editorSettings.GetSetting("mono/builds/build_tool"); + + if (OS.IsWindows) + { + switch (buildTool) + { + case BuildManager.BuildTool.MsBuildVs: + { + if (_msbuildToolsPath.Empty() || !File.Exists(_msbuildToolsPath)) + { + // Try to search it again if it wasn't found last time or if it was removed from its location + _msbuildToolsPath = FindMsBuildToolsPathOnWindows(); + + if (_msbuildToolsPath.Empty()) + { + throw new FileNotFoundException($"Cannot find executable for '{BuildManager.PropNameMsbuildVs}'."); + } + } + + if (!_msbuildToolsPath.EndsWith("\\")) + _msbuildToolsPath += "\\"; + + return Path.Combine(_msbuildToolsPath, "MSBuild.exe"); + } + case BuildManager.BuildTool.MsBuildMono: + { + string msbuildPath = Path.Combine(Internal.MonoWindowsInstallRoot, "bin", "msbuild.bat"); + + if (!File.Exists(msbuildPath)) + { + throw new FileNotFoundException($"Cannot find executable for '{BuildManager.PropNameMsbuildMono}'. Tried with path: {msbuildPath}"); + } + + return msbuildPath; + } + default: + throw new IndexOutOfRangeException("Invalid build tool in editor settings"); + } + } + + if (OS.IsUnixLike()) + { + if (buildTool == BuildManager.BuildTool.MsBuildMono) + { + if (_msbuildUnixPath.Empty() || !File.Exists(_msbuildUnixPath)) + { + // Try to search it again if it wasn't found last time or if it was removed from its location + _msbuildUnixPath = FindBuildEngineOnUnix("msbuild"); + } + + if (_msbuildUnixPath.Empty()) + { + throw new FileNotFoundException($"Cannot find binary for '{BuildManager.PropNameMsbuildMono}'"); + } + + return _msbuildUnixPath; + } + else + { + throw new IndexOutOfRangeException("Invalid build tool in editor settings"); + } + } + + throw new PlatformNotSupportedException(); + } + + private static IEnumerable<string> MsBuildHintDirs + { + get + { + var result = new List<string>(); + + if (OS.IsOSX) + { + result.Add("/Library/Frameworks/Mono.framework/Versions/Current/bin/"); + result.Add("/usr/local/var/homebrew/linked/mono/bin/"); + } + + result.Add("/opt/novell/mono/bin/"); + + return result; + } + } + + private static string FindBuildEngineOnUnix(string name) + { + string ret = OS.PathWhich(name); + + if (!ret.Empty()) + return ret; + + string retFallback = OS.PathWhich($"{name}.exe"); + + if (!retFallback.Empty()) + return retFallback; + + foreach (string hintDir in MsBuildHintDirs) + { + string hintPath = Path.Combine(hintDir, name); + + if (File.Exists(hintPath)) + return hintPath; + } + + return string.Empty; + } + + private static string FindMsBuildToolsPathOnWindows() + { + if (!OS.IsWindows) + throw new PlatformNotSupportedException(); + + // Try to find 15.0 with vswhere + + string vsWherePath = Environment.GetEnvironmentVariable(Internal.GodotIs32Bits() ? "ProgramFiles" : "ProgramFiles(x86)"); + vsWherePath += "\\Microsoft Visual Studio\\Installer\\vswhere.exe"; + + var vsWhereArgs = new[] {"-latest", "-products", "*", "-requires", "Microsoft.Component.MSBuild"}; + + var outputArray = new Godot.Collections.Array<string>(); + int exitCode = Godot.OS.Execute(vsWherePath, vsWhereArgs, + blocking: true, output: (Godot.Collections.Array) outputArray); + + if (exitCode != 0) + return string.Empty; + + if (outputArray.Count == 0) + return string.Empty; + + var lines = outputArray[0].Split('\n'); + + foreach (string line in lines) + { + int sepIdx = line.IndexOf(':'); + + if (sepIdx <= 0) + continue; + + string key = line.Substring(0, sepIdx); // No need to trim + + if (key != "installationPath") + continue; + + string value = line.Substring(sepIdx + 1).StripEdges(); + + if (value.Empty()) + throw new FormatException("installationPath value is empty"); + + if (!value.EndsWith("\\")) + value += "\\"; + + // Since VS2019, the directory is simply named "Current" + string msbuildDir = Path.Combine(value, "MSBuild\\Current\\Bin"); + + if (Directory.Exists(msbuildDir)) + return msbuildDir; + + // Directory name "15.0" is used in VS 2017 + return Path.Combine(value, "MSBuild\\15.0\\Bin"); + } + + return string.Empty; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/BuildInfo.cs b/modules/mono/editor/GodotTools/GodotTools/BuildInfo.cs new file mode 100644 index 0000000000..70bd552f2f --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/BuildInfo.cs @@ -0,0 +1,47 @@ +using System; +using Godot; +using Godot.Collections; +using GodotTools.Internals; +using Path = System.IO.Path; + +namespace GodotTools +{ + [Serializable] + public sealed class BuildInfo : Reference // TODO Remove Reference once we have proper serialization + { + public string Solution { get; } + public string Configuration { get; } + public Array<string> CustomProperties { get; } = new Array<string>(); // TODO Use List once we have proper serialization + + public string LogsDirPath => Path.Combine(GodotSharpDirs.BuildLogsDirs, $"{Solution.MD5Text()}_{Configuration}"); + + public override bool Equals(object obj) + { + if (obj is BuildInfo other) + return other.Solution == Solution && other.Configuration == Configuration; + + return false; + } + + public override int GetHashCode() + { + unchecked + { + int hash = 17; + hash = hash * 29 + Solution.GetHashCode(); + hash = hash * 29 + Configuration.GetHashCode(); + return hash; + } + } + + private BuildInfo() + { + } + + public BuildInfo(string solution, string configuration) + { + Solution = solution; + Configuration = configuration; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/BuildManager.cs b/modules/mono/editor/GodotTools/GodotTools/BuildManager.cs new file mode 100644 index 0000000000..217bf5c144 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/BuildManager.cs @@ -0,0 +1,266 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using GodotTools.Build; +using GodotTools.Internals; +using GodotTools.Utils; +using static GodotTools.Internals.Globals; +using File = GodotTools.Utils.File; + +namespace GodotTools +{ + public static class BuildManager + { + private static readonly List<BuildInfo> BuildsInProgress = new List<BuildInfo>(); + + public const string PropNameMsbuildMono = "MSBuild (Mono)"; + public const string PropNameMsbuildVs = "MSBuild (VS Build Tools)"; + + public const string MsBuildIssuesFileName = "msbuild_issues.csv"; + public const string MsBuildLogFileName = "msbuild_log.txt"; + + public enum BuildTool + { + MsBuildMono, + MsBuildVs + } + + private static void RemoveOldIssuesFile(BuildInfo buildInfo) + { + var issuesFile = GetIssuesFilePath(buildInfo); + + if (!File.Exists(issuesFile)) + return; + + File.Delete(issuesFile); + } + + private static void ShowBuildErrorDialog(string message) + { + GodotSharpEditor.Instance.ShowErrorDialog(message, "Build error"); + GodotSharpEditor.Instance.BottomPanel.ShowBuildTab(); + } + + public static void RestartBuild(BuildTab buildTab) => throw new NotImplementedException(); + public static void StopBuild(BuildTab buildTab) => throw new NotImplementedException(); + + private static string GetLogFilePath(BuildInfo buildInfo) + { + return Path.Combine(buildInfo.LogsDirPath, MsBuildLogFileName); + } + + private static string GetIssuesFilePath(BuildInfo buildInfo) + { + return Path.Combine(buildInfo.LogsDirPath, MsBuildIssuesFileName); + } + + private static void PrintVerbose(string text) + { + if (Godot.OS.IsStdoutVerbose()) + Godot.GD.Print(text); + } + + public static bool Build(BuildInfo buildInfo) + { + if (BuildsInProgress.Contains(buildInfo)) + throw new InvalidOperationException("A build is already in progress"); + + BuildsInProgress.Add(buildInfo); + + try + { + BuildTab buildTab = GodotSharpEditor.Instance.BottomPanel.GetBuildTabFor(buildInfo); + buildTab.OnBuildStart(); + + // Required in order to update the build tasks list + Internal.GodotMainIteration(); + + try + { + RemoveOldIssuesFile(buildInfo); + } + catch (IOException e) + { + buildTab.OnBuildExecFailed($"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}"); + Console.Error.WriteLine(e); + } + + try + { + int exitCode = BuildSystem.Build(buildInfo); + + if (exitCode != 0) + PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}"); + + buildTab.OnBuildExit(exitCode == 0 ? BuildTab.BuildResults.Success : BuildTab.BuildResults.Error); + + return exitCode == 0; + } + catch (Exception e) + { + buildTab.OnBuildExecFailed($"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}"); + Console.Error.WriteLine(e); + return false; + } + } + finally + { + BuildsInProgress.Remove(buildInfo); + } + } + + public static async Task<bool> BuildAsync(BuildInfo buildInfo) + { + if (BuildsInProgress.Contains(buildInfo)) + throw new InvalidOperationException("A build is already in progress"); + + BuildsInProgress.Add(buildInfo); + + try + { + BuildTab buildTab = GodotSharpEditor.Instance.BottomPanel.GetBuildTabFor(buildInfo); + + try + { + RemoveOldIssuesFile(buildInfo); + } + catch (IOException e) + { + buildTab.OnBuildExecFailed($"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}"); + Console.Error.WriteLine(e); + } + + try + { + int exitCode = await BuildSystem.BuildAsync(buildInfo); + + if (exitCode != 0) + PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}"); + + buildTab.OnBuildExit(exitCode == 0 ? BuildTab.BuildResults.Success : BuildTab.BuildResults.Error); + + return exitCode == 0; + } + catch (Exception e) + { + buildTab.OnBuildExecFailed($"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}"); + Console.Error.WriteLine(e); + return false; + } + } + finally + { + BuildsInProgress.Remove(buildInfo); + } + } + + public static bool BuildProjectBlocking(string config, IEnumerable<string> godotDefines) + { + if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) + return true; // No solution to build + + // Make sure the API assemblies are up to date before building the project. + // We may not have had the chance to update the release API assemblies, and the debug ones + // may have been deleted by the user at some point after they were loaded by the Godot editor. + string apiAssembliesUpdateError = Internal.UpdateApiAssembliesFromPrebuilt(config == "Release" ? "Release" : "Debug"); + + if (!string.IsNullOrEmpty(apiAssembliesUpdateError)) + { + ShowBuildErrorDialog("Failed to update the Godot API assemblies"); + return false; + } + + var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); + var buildTool = (BuildTool) editorSettings.GetSetting("mono/builds/build_tool"); + + using (var pr = new EditorProgress("mono_project_debug_build", "Building project solution...", 1)) + { + pr.Step("Building project solution", 0); + + var buildInfo = new BuildInfo(GodotSharpDirs.ProjectSlnPath, config); + + // Add Godot defines + string constants = buildTool == BuildTool.MsBuildVs ? "GodotDefineConstants=\"" : "GodotDefineConstants=\\\""; + + foreach (var godotDefine in godotDefines) + constants += $"GODOT_{godotDefine.ToUpper().Replace("-", "_").Replace(" ", "_").Replace(";", "_")};"; + + if (Internal.GodotIsRealTDouble()) + constants += "GODOT_REAL_T_IS_DOUBLE;"; + + constants += buildTool == BuildTool.MsBuildVs ? "\"" : "\\\""; + + buildInfo.CustomProperties.Add(constants); + + if (!Build(buildInfo)) + { + ShowBuildErrorDialog("Failed to build project solution"); + return false; + } + } + + return true; + } + + public static bool EditorBuildCallback() + { + if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) + return true; // No solution to build + + string editorScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor"); + string playerScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor_player"); + + CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, editorScriptsMetadataPath); + + if (File.Exists(editorScriptsMetadataPath)) + File.Copy(editorScriptsMetadataPath, playerScriptsMetadataPath); + + var currentPlayRequest = GodotSharpEditor.Instance.GodotIdeManager.GodotIdeServer.CurrentPlayRequest; + + if (currentPlayRequest != null) + { + if (currentPlayRequest.Value.HasDebugger) + { + // Set the environment variable that will tell the player to connect to the IDE debugger + // TODO: We should probably add a better way to do this + Environment.SetEnvironmentVariable("GODOT_MONO_DEBUGGER_AGENT", + "--debugger-agent=transport=dt_socket" + + $",address={currentPlayRequest.Value.DebuggerHost}:{currentPlayRequest.Value.DebuggerPort}" + + ",server=n"); + } + + return true; // Requested play from an external editor/IDE which already built the project + } + + var godotDefines = new[] + { + Godot.OS.GetName(), + Internal.GodotIs32Bits() ? "32" : "64" + }; + + return BuildProjectBlocking("Tools", godotDefines); + } + + public static void Initialize() + { + // Build tool settings + + EditorDef("mono/builds/build_tool", OS.IsWindows ? BuildTool.MsBuildVs : BuildTool.MsBuildMono); + + var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); + + editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary + { + ["type"] = Godot.Variant.Type.Int, + ["name"] = "mono/builds/build_tool", + ["hint"] = Godot.PropertyHint.Enum, + ["hint_string"] = OS.IsWindows ? + $"{PropNameMsbuildMono},{PropNameMsbuildVs}" : + $"{PropNameMsbuildMono}" + }); + + EditorDef("mono/builds/print_build_output", false); + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/BuildTab.cs b/modules/mono/editor/GodotTools/GodotTools/BuildTab.cs new file mode 100644 index 0000000000..807a20d9a1 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/BuildTab.cs @@ -0,0 +1,267 @@ +using Godot; +using System; +using Godot.Collections; +using GodotTools.Internals; +using File = GodotTools.Utils.File; +using Path = System.IO.Path; + +namespace GodotTools +{ + public class BuildTab : VBoxContainer + { + public enum BuildResults + { + Error, + Success + } + + [Serializable] + private class BuildIssue : Reference // TODO Remove Reference once we have proper serialization + { + public bool Warning { get; set; } + public string File { get; set; } + public int Line { get; set; } + public int Column { get; set; } + public string Code { get; set; } + public string Message { get; set; } + public string ProjectFile { get; set; } + } + + private readonly Array<BuildIssue> issues = new Array<BuildIssue>(); // TODO Use List once we have proper serialization + private ItemList issuesList; + + public bool BuildExited { get; private set; } = false; + + public BuildResults? BuildResult { get; private set; } = null; + + public int ErrorCount { get; private set; } = 0; + + public int WarningCount { get; private set; } = 0; + + public bool ErrorsVisible { get; set; } = true; + public bool WarningsVisible { get; set; } = true; + + public Texture IconTexture + { + get + { + if (!BuildExited) + return GetIcon("Stop", "EditorIcons"); + + if (BuildResult == BuildResults.Error) + return GetIcon("StatusError", "EditorIcons"); + + return GetIcon("StatusSuccess", "EditorIcons"); + } + } + + public BuildInfo BuildInfo { get; private set; } + + private void _LoadIssuesFromFile(string csvFile) + { + using (var file = new Godot.File()) + { + try + { + Error openError = file.Open(csvFile, Godot.File.ModeFlags.Read); + + if (openError != Error.Ok) + return; + + while (!file.EofReached()) + { + string[] csvColumns = file.GetCsvLine(); + + if (csvColumns.Length == 1 && csvColumns[0].Empty()) + return; + + if (csvColumns.Length != 7) + { + GD.PushError($"Expected 7 columns, got {csvColumns.Length}"); + continue; + } + + var issue = new BuildIssue + { + Warning = csvColumns[0] == "warning", + File = csvColumns[1], + Line = int.Parse(csvColumns[2]), + Column = int.Parse(csvColumns[3]), + Code = csvColumns[4], + Message = csvColumns[5], + ProjectFile = csvColumns[6] + }; + + if (issue.Warning) + WarningCount += 1; + else + ErrorCount += 1; + + issues.Add(issue); + } + } + finally + { + file.Close(); // Disposing it is not enough. We need to call Close() + } + } + } + + private void _IssueActivated(int idx) + { + if (idx < 0 || idx >= issuesList.GetItemCount()) + throw new IndexOutOfRangeException("Item list index out of range"); + + // Get correct issue idx from issue list + int issueIndex = (int) issuesList.GetItemMetadata(idx); + + if (idx < 0 || idx >= issues.Count) + throw new IndexOutOfRangeException("Issue index out of range"); + + BuildIssue issue = issues[issueIndex]; + + if (issue.ProjectFile.Empty() && issue.File.Empty()) + return; + + string projectDir = issue.ProjectFile.Length > 0 ? issue.ProjectFile.GetBaseDir() : BuildInfo.Solution.GetBaseDir(); + + string file = Path.Combine(projectDir.SimplifyGodotPath(), issue.File.SimplifyGodotPath()); + + if (!File.Exists(file)) + return; + + file = ProjectSettings.LocalizePath(file); + + if (file.StartsWith("res://")) + { + var script = (Script) ResourceLoader.Load(file, typeHint: Internal.CSharpLanguageType); + + if (script != null && Internal.ScriptEditorEdit(script, issue.Line, issue.Column)) + Internal.EditorNodeShowScriptScreen(); + } + } + + public void UpdateIssuesList() + { + issuesList.Clear(); + + using (var warningIcon = GetIcon("Warning", "EditorIcons")) + using (var errorIcon = GetIcon("Error", "EditorIcons")) + { + for (int i = 0; i < issues.Count; i++) + { + BuildIssue issue = issues[i]; + + if (!(issue.Warning ? WarningsVisible : ErrorsVisible)) + continue; + + string tooltip = string.Empty; + tooltip += $"Message: {issue.Message}"; + + if (!issue.Code.Empty()) + tooltip += $"\nCode: {issue.Code}"; + + tooltip += $"\nType: {(issue.Warning ? "warning" : "error")}"; + + string text = string.Empty; + + if (!issue.File.Empty()) + { + text += $"{issue.File}({issue.Line},{issue.Column}): "; + + tooltip += $"\nFile: {issue.File}"; + tooltip += $"\nLine: {issue.Line}"; + tooltip += $"\nColumn: {issue.Column}"; + } + + if (!issue.ProjectFile.Empty()) + tooltip += $"\nProject: {issue.ProjectFile}"; + + text += issue.Message; + + int lineBreakIdx = text.IndexOf("\n", StringComparison.Ordinal); + string itemText = lineBreakIdx == -1 ? text : text.Substring(0, lineBreakIdx); + issuesList.AddItem(itemText, issue.Warning ? warningIcon : errorIcon); + + int index = issuesList.GetItemCount() - 1; + issuesList.SetItemTooltip(index, tooltip); + issuesList.SetItemMetadata(index, i); + } + } + } + + public void OnBuildStart() + { + BuildExited = false; + + issues.Clear(); + WarningCount = 0; + ErrorCount = 0; + UpdateIssuesList(); + + GodotSharpEditor.Instance.BottomPanel.RaiseBuildTab(this); + } + + public void OnBuildExit(BuildResults result) + { + BuildExited = true; + BuildResult = result; + + _LoadIssuesFromFile(Path.Combine(BuildInfo.LogsDirPath, BuildManager.MsBuildIssuesFileName)); + UpdateIssuesList(); + + GodotSharpEditor.Instance.BottomPanel.RaiseBuildTab(this); + } + + public void OnBuildExecFailed(string cause) + { + BuildExited = true; + BuildResult = BuildResults.Error; + + issuesList.Clear(); + + var issue = new BuildIssue {Message = cause, Warning = false}; + + ErrorCount += 1; + issues.Add(issue); + + UpdateIssuesList(); + + GodotSharpEditor.Instance.BottomPanel.RaiseBuildTab(this); + } + + public void RestartBuild() + { + if (!BuildExited) + throw new InvalidOperationException("Build already started"); + + BuildManager.RestartBuild(this); + } + + public void StopBuild() + { + if (!BuildExited) + throw new InvalidOperationException("Build is not in progress"); + + BuildManager.StopBuild(this); + } + + public override void _Ready() + { + base._Ready(); + + issuesList = new ItemList {SizeFlagsVertical = (int) SizeFlags.ExpandFill}; + issuesList.Connect("item_activated", this, nameof(_IssueActivated)); + AddChild(issuesList); + } + + private BuildTab() + { + } + + public BuildTab(BuildInfo buildInfo) + { + BuildInfo = buildInfo; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/CsProjOperations.cs b/modules/mono/editor/GodotTools/GodotTools/CsProjOperations.cs new file mode 100644 index 0000000000..c021a9051e --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/CsProjOperations.cs @@ -0,0 +1,127 @@ +using Godot; +using System; +using Godot.Collections; +using GodotTools.Internals; +using GodotTools.ProjectEditor; +using static GodotTools.Internals.Globals; +using File = GodotTools.Utils.File; +using Directory = GodotTools.Utils.Directory; + +namespace GodotTools +{ + public static class CsProjOperations + { + public static string GenerateGameProject(string dir, string name) + { + try + { + return ProjectGenerator.GenGameProject(dir, name, compileItems: new string[] { }); + } + catch (Exception e) + { + GD.PushError(e.ToString()); + return string.Empty; + } + } + + public static void AddItem(string projectPath, string itemType, string include) + { + if (!(bool) GlobalDef("mono/project/auto_update_project", true)) + return; + + ProjectUtils.AddItemToProjectChecked(projectPath, itemType, include); + } + + public static void FixApiHintPath(string projectPath) + { + try + { + ProjectUtils.FixApiHintPath(projectPath); + } + catch (Exception e) + { + GD.PushError(e.ToString()); + } + } + + private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + private static ulong ConvertToTimestamp(this DateTime value) + { + TimeSpan elapsedTime = value - Epoch; + return (ulong) elapsedTime.TotalSeconds; + } + + public static void GenerateScriptsMetadata(string projectPath, string outputPath) + { + if (File.Exists(outputPath)) + File.Delete(outputPath); + + var oldDict = Internal.GetScriptsMetadataOrNothing(); + var newDict = new Godot.Collections.Dictionary<string, object>(); + + foreach (var includeFile in ProjectUtils.GetIncludeFiles(projectPath, "Compile")) + { + string projectIncludeFile = ("res://" + includeFile).SimplifyGodotPath(); + + ulong modifiedTime = File.GetLastWriteTime(projectIncludeFile).ConvertToTimestamp(); + + if (oldDict.TryGetValue(projectIncludeFile, out var oldFileVar)) + { + var oldFileDict = (Dictionary) oldFileVar; + + if (ulong.TryParse(oldFileDict["modified_time"] as string, out ulong storedModifiedTime)) + { + if (storedModifiedTime == modifiedTime) + { + // No changes so no need to parse again + newDict[projectIncludeFile] = oldFileDict; + continue; + } + } + } + + ScriptClassParser.ParseFileOrThrow(projectIncludeFile, out var classes); + + string searchName = System.IO.Path.GetFileNameWithoutExtension(projectIncludeFile); + + var classDict = new Dictionary(); + + foreach (var classDecl in classes) + { + if (classDecl.BaseCount == 0) + continue; // Does not inherit nor implement anything, so it can't be a script class + + string classCmp = classDecl.Nested ? + classDecl.Name.Substring(classDecl.Name.LastIndexOf(".", StringComparison.Ordinal) + 1) : + classDecl.Name; + + if (classCmp != searchName) + continue; + + classDict["namespace"] = classDecl.Namespace; + classDict["class_name"] = classDecl.Name; + classDict["nested"] = classDecl.Nested; + break; + } + + if (classDict.Count == 0) + continue; // Not found + + newDict[projectIncludeFile] = new Dictionary {["modified_time"] = $"{modifiedTime}", ["class"] = classDict}; + } + + if (newDict.Count > 0) + { + string json = JSON.Print(newDict); + + string baseDir = outputPath.GetBaseDir(); + + if (!Directory.Exists(baseDir)) + Directory.CreateDirectory(baseDir); + + File.WriteAllText(outputPath, json); + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs new file mode 100644 index 0000000000..c7e8ea511a --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs @@ -0,0 +1,676 @@ +using Godot; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using GodotTools.Core; +using GodotTools.Internals; +using static GodotTools.Internals.Globals; +using Directory = GodotTools.Utils.Directory; +using File = GodotTools.Utils.File; +using OS = GodotTools.Utils.OS; +using Path = System.IO.Path; + +namespace GodotTools.Export +{ + public class ExportPlugin : EditorExportPlugin + { + public void RegisterExportSettings() + { + // TODO: These would be better as export preset options, but that doesn't seem to be supported yet + + GlobalDef("mono/export/include_scripts_content", false); + GlobalDef("mono/export/export_assemblies_inside_pck", true); + + GlobalDef("mono/export/aot/enabled", false); + GlobalDef("mono/export/aot/full_aot", false); + + // --aot or --aot=opt1,opt2 (use 'mono --aot=help AuxAssembly.dll' to list AOT options) + GlobalDef("mono/export/aot/extra_aot_options", new string[] { }); + // --optimize/-O=opt1,opt2 (use 'mono --list-opt'' to list optimize options) + GlobalDef("mono/export/aot/extra_optimizer_options", new string[] { }); + + GlobalDef("mono/export/aot/android_toolchain_path", ""); + } + + private string maybeLastExportError; + + private void AddFile(string srcPath, string dstPath, bool remap = false) + { + AddFile(dstPath, File.ReadAllBytes(srcPath), remap); + } + + public override void _ExportFile(string path, string type, string[] features) + { + base._ExportFile(path, type, features); + + if (type != Internal.CSharpLanguageType) + return; + + if (Path.GetExtension(path) != $".{Internal.CSharpLanguageExtension}") + throw new ArgumentException($"Resource of type {Internal.CSharpLanguageType} has an invalid file extension: {path}", nameof(path)); + + // TODO What if the source file is not part of the game's C# project + + bool includeScriptsContent = (bool) ProjectSettings.GetSetting("mono/export/include_scripts_content"); + + if (!includeScriptsContent) + { + // We don't want to include the source code on exported games. + + // Sadly, Godot prints errors when adding an empty file (nothing goes wrong, it's just noise). + // Because of this, we add a file which contains a line break. + AddFile(path, System.Text.Encoding.UTF8.GetBytes("\n"), remap: false); + Skip(); + } + } + + public override void _ExportBegin(string[] features, bool isDebug, string path, int flags) + { + base._ExportBegin(features, isDebug, path, flags); + + try + { + _ExportBeginImpl(features, isDebug, path, flags); + } + catch (Exception e) + { + maybeLastExportError = e.Message; + GD.PushError($"Failed to export project: {e.Message}"); + Console.Error.WriteLine(e); + // TODO: Do something on error once _ExportBegin supports failing. + } + } + + private void _ExportBeginImpl(string[] features, bool isDebug, string path, int flags) + { + if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) + return; + + string platform = DeterminePlatformFromFeatures(features); + + if (platform == null) + throw new NotSupportedException("Target platform not supported"); + + string outputDir = new FileInfo(path).Directory?.FullName ?? + throw new FileNotFoundException("Base directory not found"); + + string buildConfig = isDebug ? "Debug" : "Release"; + + string scriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, $"scripts_metadata.{(isDebug ? "debug" : "release")}"); + CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, scriptsMetadataPath); + + AddFile(scriptsMetadataPath, scriptsMetadataPath); + + // Turn export features into defines + var godotDefines = features; + + if (!BuildManager.BuildProjectBlocking(buildConfig, godotDefines)) + throw new Exception("Failed to build project"); + + // Add dependency assemblies + + var dependencies = new Godot.Collections.Dictionary<string, string>(); + + var projectDllName = (string) ProjectSettings.GetSetting("application/config/name"); + if (projectDllName.Empty()) + { + projectDllName = "UnnamedProject"; + } + + string projectDllSrcDir = Path.Combine(GodotSharpDirs.ResTempAssembliesBaseDir, buildConfig); + string projectDllSrcPath = Path.Combine(projectDllSrcDir, $"{projectDllName}.dll"); + + dependencies[projectDllName] = projectDllSrcPath; + + if (platform == OS.Platforms.Android) + { + string godotAndroidExtProfileDir = GetBclProfileDir("godot_android_ext"); + string monoAndroidAssemblyPath = Path.Combine(godotAndroidExtProfileDir, "Mono.Android.dll"); + + if (!File.Exists(monoAndroidAssemblyPath)) + throw new FileNotFoundException("Assembly not found: 'Mono.Android'", monoAndroidAssemblyPath); + + dependencies["Mono.Android"] = monoAndroidAssemblyPath; + } + + var initialDependencies = dependencies.Duplicate(); + internal_GetExportedAssemblyDependencies(initialDependencies, buildConfig, DeterminePlatformBclDir(platform), dependencies); + + string outputDataDir = null; + + if (PlatformHasTemplateDir(platform)) + outputDataDir = ExportDataDirectory(features, platform, isDebug, outputDir); + + string apiConfig = isDebug ? "Debug" : "Release"; + string resAssembliesDir = Path.Combine(GodotSharpDirs.ResAssembliesBaseDir, apiConfig); + + bool assembliesInsidePck = (bool) ProjectSettings.GetSetting("mono/export/export_assemblies_inside_pck") || outputDataDir == null; + + if (!assembliesInsidePck) + { + string outputDataGameAssembliesDir = Path.Combine(outputDataDir, "Assemblies"); + if (!Directory.Exists(outputDataGameAssembliesDir)) + Directory.CreateDirectory(outputDataGameAssembliesDir); + } + + foreach (var dependency in dependencies) + { + string dependSrcPath = dependency.Value; + + if (assembliesInsidePck) + { + string dependDstPath = Path.Combine(resAssembliesDir, dependSrcPath.GetFile()); + AddFile(dependSrcPath, dependDstPath); + } + else + { + string dependDstPath = Path.Combine(outputDataDir, "Assemblies", dependSrcPath.GetFile()); + File.Copy(dependSrcPath, dependDstPath); + } + } + + // AOT + + if ((bool) ProjectSettings.GetSetting("mono/export/aot/enabled")) + { + AotCompileDependencies(features, platform, isDebug, outputDir, outputDataDir, dependencies); + } + } + + public override void _ExportEnd() + { + base._ExportEnd(); + + string aotTempDir = Path.Combine(Path.GetTempPath(), $"godot-aot-{Process.GetCurrentProcess().Id}"); + + if (Directory.Exists(aotTempDir)) + Directory.Delete(aotTempDir, recursive: true); + + // TODO: Just a workaround until the export plugins can be made to abort with errors + if (!string.IsNullOrEmpty(maybeLastExportError)) // Check empty as well, because it's set to empty after hot-reloading + { + string lastExportError = maybeLastExportError; + maybeLastExportError = null; + + GodotSharpEditor.Instance.ShowErrorDialog(lastExportError, "Failed to export C# project"); + } + } + + private static string ExportDataDirectory(string[] features, string platform, bool isDebug, string outputDir) + { + string target = isDebug ? "release_debug" : "release"; + + // NOTE: Bits is ok for now as all platforms with a data directory have it, but that may change in the future. + string bits = features.Contains("64") ? "64" : "32"; + + string TemplateDirName() => $"data.mono.{platform}.{bits}.{target}"; + + string templateDirPath = Path.Combine(Internal.FullTemplatesDir, TemplateDirName()); + bool validTemplatePathFound = true; + + if (!Directory.Exists(templateDirPath)) + { + validTemplatePathFound = false; + + if (isDebug) + { + target = "debug"; // Support both 'release_debug' and 'debug' for the template data directory name + templateDirPath = Path.Combine(Internal.FullTemplatesDir, TemplateDirName()); + validTemplatePathFound = true; + + if (!Directory.Exists(templateDirPath)) + validTemplatePathFound = false; + } + } + + if (!validTemplatePathFound) + throw new FileNotFoundException("Data template directory not found", templateDirPath); + + string outputDataDir = Path.Combine(outputDir, DataDirName); + + if (Directory.Exists(outputDataDir)) + Directory.Delete(outputDataDir, recursive: true); // Clean first + + Directory.CreateDirectory(outputDataDir); + + foreach (string dir in Directory.GetDirectories(templateDirPath, "*", SearchOption.AllDirectories)) + { + Directory.CreateDirectory(Path.Combine(outputDataDir, dir.Substring(templateDirPath.Length + 1))); + } + + foreach (string file in Directory.GetFiles(templateDirPath, "*", SearchOption.AllDirectories)) + { + File.Copy(file, Path.Combine(outputDataDir, file.Substring(templateDirPath.Length + 1))); + } + + return outputDataDir; + } + + private void AotCompileDependencies(string[] features, string platform, bool isDebug, string outputDir, string outputDataDir, IDictionary<string, string> dependencies) + { + // TODO: WASM + + string bclDir = DeterminePlatformBclDir(platform) ?? typeof(object).Assembly.Location.GetBaseDir(); + + string aotTempDir = Path.Combine(Path.GetTempPath(), $"godot-aot-{Process.GetCurrentProcess().Id}"); + + if (!Directory.Exists(aotTempDir)) + Directory.CreateDirectory(aotTempDir); + + var assemblies = new Dictionary<string, string>(); + + foreach (var dependency in dependencies) + { + string assemblyName = dependency.Key; + string assemblyPath = dependency.Value; + + string assemblyPathInBcl = Path.Combine(bclDir, assemblyName + ".dll"); + + if (File.Exists(assemblyPathInBcl)) + { + // Don't create teporaries for assemblies from the BCL + assemblies.Add(assemblyName, assemblyPathInBcl); + } + else + { + string tempAssemblyPath = Path.Combine(aotTempDir, assemblyName + ".dll"); + File.Copy(assemblyPath, tempAssemblyPath); + assemblies.Add(assemblyName, tempAssemblyPath); + } + } + + foreach (var assembly in assemblies) + { + string assemblyName = assembly.Key; + string assemblyPath = assembly.Value; + + string sharedLibExtension = platform == OS.Platforms.Windows ? ".dll" : + platform == OS.Platforms.OSX ? ".dylib" : + platform == OS.Platforms.HTML5 ? ".wasm" : + ".so"; + + string outputFileName = assemblyName + ".dll" + sharedLibExtension; + + if (platform == OS.Platforms.Android) + { + // Not sure if the 'lib' prefix is an Android thing or just Godot being picky, + // but we use '-aot-' as well just in case to avoid conflicts with other libs. + outputFileName = "lib-aot-" + outputFileName; + } + + string outputFilePath = null; + string tempOutputFilePath; + + switch (platform) + { + case OS.Platforms.OSX: + tempOutputFilePath = Path.Combine(aotTempDir, outputFileName); + break; + case OS.Platforms.Android: + tempOutputFilePath = Path.Combine(aotTempDir, "%%ANDROID_ABI%%", outputFileName); + break; + case OS.Platforms.HTML5: + tempOutputFilePath = Path.Combine(aotTempDir, outputFileName); + outputFilePath = Path.Combine(outputDir, outputFileName); + break; + default: + tempOutputFilePath = Path.Combine(aotTempDir, outputFileName); + outputFilePath = Path.Combine(outputDataDir, "Mono", platform == OS.Platforms.Windows ? "bin" : "lib", outputFileName); + break; + } + + var data = new Dictionary<string, string>(); + var enabledAndroidAbis = platform == OS.Platforms.Android ? GetEnabledAndroidAbis(features).ToArray() : null; + + if (platform == OS.Platforms.Android) + { + Debug.Assert(enabledAndroidAbis != null); + + foreach (var abi in enabledAndroidAbis) + { + data["abi"] = abi; + var outputFilePathForThisAbi = tempOutputFilePath.Replace("%%ANDROID_ABI%%", abi); + + AotCompileAssembly(platform, isDebug, data, assemblyPath, outputFilePathForThisAbi); + + AddSharedObject(outputFilePathForThisAbi, tags: new[] {abi}); + } + } + else + { + string bits = features.Contains("64") ? "64" : features.Contains("64") ? "32" : null; + + if (bits != null) + data["bits"] = bits; + + AotCompileAssembly(platform, isDebug, data, assemblyPath, tempOutputFilePath); + + if (platform == OS.Platforms.OSX) + { + AddSharedObject(tempOutputFilePath, tags: null); + } + else + { + Debug.Assert(outputFilePath != null); + File.Copy(tempOutputFilePath, outputFilePath); + } + } + } + } + + private static void AotCompileAssembly(string platform, bool isDebug, Dictionary<string, string> data, string assemblyPath, string outputFilePath) + { + // Make sure the output directory exists + Directory.CreateDirectory(outputFilePath.GetBaseDir()); + + string exeExt = OS.IsWindows ? ".exe" : string.Empty; + + string monoCrossDirName = DetermineMonoCrossDirName(platform, data); + string monoCrossRoot = Path.Combine(GodotSharpDirs.DataEditorToolsDir, "aot-compilers", monoCrossDirName); + string monoCrossBin = Path.Combine(monoCrossRoot, "bin"); + + string toolPrefix = DetermineToolPrefix(monoCrossBin); + string monoExeName = System.IO.File.Exists(Path.Combine(monoCrossBin, $"{toolPrefix}mono{exeExt}")) ? "mono" : "mono-sgen"; + + string compilerCommand = Path.Combine(monoCrossBin, $"{toolPrefix}{monoExeName}{exeExt}"); + + bool fullAot = (bool) ProjectSettings.GetSetting("mono/export/aot/full_aot"); + + string EscapeOption(string option) => option.Contains(',') ? $"\"{option}\"" : option; + string OptionsToString(IEnumerable<string> options) => string.Join(",", options.Select(EscapeOption)); + + var aotOptions = new List<string>(); + var optimizerOptions = new List<string>(); + + if (fullAot) + aotOptions.Add("full"); + + aotOptions.Add(isDebug ? "soft-debug" : "nodebug"); + + if (platform == OS.Platforms.Android) + { + string abi = data["abi"]; + + string androidToolchain = (string) ProjectSettings.GetSetting("mono/export/aot/android_toolchain_path"); + + if (string.IsNullOrEmpty(androidToolchain)) + { + androidToolchain = Path.Combine(GodotSharpDirs.DataEditorToolsDir, "android-toolchains", $"{abi}"); // TODO: $"{abi}-{apiLevel}{(clang?"clang":"")}" + + if (!Directory.Exists(androidToolchain)) + throw new FileNotFoundException("Missing android toolchain. Specify one in the AOT export settings."); + } + else if (!Directory.Exists(androidToolchain)) + { + throw new FileNotFoundException("Android toolchain not found: " + androidToolchain); + } + + var androidToolPrefixes = new Dictionary<string, string> + { + ["armeabi-v7a"] = "arm-linux-androideabi-", + ["arm64-v8a"] = "aarch64-linux-android-", + ["x86"] = "i686-linux-android-", + ["x86_64"] = "x86_64-linux-android-" + }; + + aotOptions.Add("tool-prefix=" + Path.Combine(androidToolchain, "bin", androidToolPrefixes[abi])); + + string triple = GetAndroidTriple(abi); + aotOptions.Add ($"mtriple={triple}"); + } + + aotOptions.Add($"outfile={outputFilePath}"); + + var extraAotOptions = (string[]) ProjectSettings.GetSetting("mono/export/aot/extra_aot_options"); + var extraOptimizerOptions = (string[]) ProjectSettings.GetSetting("mono/export/aot/extra_optimizer_options"); + + if (extraAotOptions.Length > 0) + aotOptions.AddRange(extraAotOptions); + + if (extraOptimizerOptions.Length > 0) + optimizerOptions.AddRange(extraOptimizerOptions); + + var compilerArgs = new List<string>(); + + if (isDebug) + compilerArgs.Add("--debug"); // Required for --aot=soft-debug + + compilerArgs.Add(aotOptions.Count > 0 ? $"--aot={OptionsToString(aotOptions)}" : "--aot"); + + if (optimizerOptions.Count > 0) + compilerArgs.Add($"-O={OptionsToString(optimizerOptions)}"); + + compilerArgs.Add(ProjectSettings.GlobalizePath(assemblyPath)); + + // TODO: Once we move to .NET Standard 2.1 we can use ProcessStartInfo.ArgumentList instead + string CmdLineArgsToString(IEnumerable<string> args) + { + // Not perfect, but as long as we are careful... + return string.Join(" ", args.Select(arg => arg.Contains(" ") ? $@"""{arg}""" : arg)); + } + + using (var process = new Process()) + { + process.StartInfo = new ProcessStartInfo(compilerCommand, CmdLineArgsToString(compilerArgs)) + { + UseShellExecute = false + }; + + string platformBclDir = DeterminePlatformBclDir(platform); + process.StartInfo.EnvironmentVariables.Add("MONO_PATH", string.IsNullOrEmpty(platformBclDir) ? + typeof(object).Assembly.Location.GetBaseDir() : + platformBclDir); + + Console.WriteLine($"Running: \"{process.StartInfo.FileName}\" {process.StartInfo.Arguments}"); + + if (!process.Start()) + throw new Exception("Failed to start process for Mono AOT compiler"); + + process.WaitForExit(); + + if (process.ExitCode != 0) + throw new Exception($"Mono AOT compiler exited with error code: {process.ExitCode}"); + + if (!System.IO.File.Exists(outputFilePath)) + throw new Exception("Mono AOT compiler finished successfully but the output file is missing"); + } + } + + private static string DetermineMonoCrossDirName(string platform, IReadOnlyDictionary<string, string> data) + { + switch (platform) + { + case OS.Platforms.Windows: + case OS.Platforms.UWP: + { + string arch = data["bits"] == "64" ? "x86_64" : "i686"; + return $"windows-{arch}"; + } + case OS.Platforms.OSX: + { + string arch = "x86_64"; + return $"{platform}-{arch}"; + } + case OS.Platforms.X11: + case OS.Platforms.Server: + { + string arch = data["bits"] == "64" ? "x86_64" : "i686"; + return $"linux-{arch}"; + } + case OS.Platforms.Haiku: + { + string arch = data["bits"] == "64" ? "x86_64" : "i686"; + return $"{platform}-{arch}"; + } + case OS.Platforms.Android: + { + string abi = data["abi"]; + return $"{platform}-{abi}"; + } + case OS.Platforms.HTML5: + return "wasm-wasm32"; + default: + throw new NotSupportedException(); + } + } + + private static string DetermineToolPrefix(string monoCrossBin) + { + string exeExt = OS.IsWindows ? ".exe" : string.Empty; + + if (System.IO.File.Exists(Path.Combine(monoCrossBin, $"mono{exeExt}"))) + return string.Empty; + + if (System.IO.File.Exists(Path.Combine(monoCrossBin, $"mono-sgen{exeExt}" + exeExt))) + return string.Empty; + + var files = new DirectoryInfo(monoCrossBin).GetFiles($"*mono{exeExt}" + exeExt, SearchOption.TopDirectoryOnly); + if (files.Length > 0) + { + string fileName = files[0].Name; + return fileName.Substring(0, fileName.Length - $"mono{exeExt}".Length); + } + + files = new DirectoryInfo(monoCrossBin).GetFiles($"*mono-sgen{exeExt}" + exeExt, SearchOption.TopDirectoryOnly); + if (files.Length > 0) + { + string fileName = files[0].Name; + return fileName.Substring(0, fileName.Length - $"mono-sgen{exeExt}".Length); + } + + throw new FileNotFoundException($"Cannot find the mono runtime executable in {monoCrossBin}"); + } + + private static IEnumerable<string> GetEnabledAndroidAbis(string[] features) + { + var androidAbis = new[] + { + "armeabi-v7a", + "arm64-v8a", + "x86", + "x86_64" + }; + + return androidAbis.Where(features.Contains); + } + + private static string GetAndroidTriple(string abi) + { + var abiArchs = new Dictionary<string, string> + { + ["armeabi-v7a"] = "armv7", + ["arm64-v8a"] = "aarch64-v8a", + ["x86"] = "i686", + ["x86_64"] = "x86_64" + }; + + string arch = abiArchs[abi]; + + return $"{arch}-linux-android"; + } + + private static bool PlatformHasTemplateDir(string platform) + { + // OSX export templates are contained in a zip, so we place our custom template inside it and let Godot do the rest. + return !new[] {OS.Platforms.OSX, OS.Platforms.Android, OS.Platforms.HTML5}.Contains(platform); + } + + private static string DeterminePlatformFromFeatures(IEnumerable<string> features) + { + foreach (var feature in features) + { + if (OS.PlatformNameMap.TryGetValue(feature, out string platform)) + return platform; + } + + return null; + } + + private static string GetBclProfileDir(string profile) + { + string templatesDir = Internal.FullTemplatesDir; + return Path.Combine(templatesDir, "bcl", profile); + } + + private static string DeterminePlatformBclDir(string platform) + { + string templatesDir = Internal.FullTemplatesDir; + string platformBclDir = Path.Combine(templatesDir, "bcl", platform); + + if (!File.Exists(Path.Combine(platformBclDir, "mscorlib.dll"))) + { + string profile = DeterminePlatformBclProfile(platform); + platformBclDir = Path.Combine(templatesDir, "bcl", profile); + + if (!File.Exists(Path.Combine(platformBclDir, "mscorlib.dll"))) + { + if (PlatformRequiresCustomBcl(platform)) + throw new FileNotFoundException($"Missing BCL (Base Class Library) for platform: {platform}"); + + platformBclDir = null; // Use the one we're running on + } + } + + return platformBclDir; + } + + /// <summary> + /// Determines whether the BCL bundled with the Godot editor can be used for the target platform, + /// or if it requires a custom BCL that must be distributed with the export templates. + /// </summary> + private static bool PlatformRequiresCustomBcl(string platform) + { + if (new[] {OS.Platforms.Android, OS.Platforms.HTML5}.Contains(platform)) + return true; + + // The 'net_4_x' BCL is not compatible between Windows and the other platforms. + // We use the names 'net_4_x_win' and 'net_4_x' to differentiate between the two. + + bool isWinOrUwp = new[] + { + OS.Platforms.Windows, + OS.Platforms.UWP + }.Contains(platform); + + return OS.IsWindows ? !isWinOrUwp : isWinOrUwp; + } + + private static string DeterminePlatformBclProfile(string platform) + { + switch (platform) + { + case OS.Platforms.Windows: + case OS.Platforms.UWP: + return "net_4_x_win"; + case OS.Platforms.OSX: + case OS.Platforms.X11: + case OS.Platforms.Server: + case OS.Platforms.Haiku: + return "net_4_x"; + case OS.Platforms.Android: + return "monodroid"; + case OS.Platforms.HTML5: + return "wasm"; + default: + throw new NotSupportedException(); + } + } + + private static string DataDirName + { + get + { + var appName = (string) ProjectSettings.GetSetting("application/config/name"); + string appNameSafe = appName.ToSafeDirName(allowDirSeparator: false); + return $"data_{appNameSafe}"; + } + } + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_GetExportedAssemblyDependencies(Godot.Collections.Dictionary<string, string> initialDependencies, + string buildConfig, string customBclDir, Godot.Collections.Dictionary<string, string> dependencies); + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/ExternalEditorId.cs b/modules/mono/editor/GodotTools/GodotTools/ExternalEditorId.cs new file mode 100644 index 0000000000..bb218c2f19 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/ExternalEditorId.cs @@ -0,0 +1,12 @@ +namespace GodotTools +{ + public enum ExternalEditorId + { + None, + VisualStudio, // TODO (Windows-only) + VisualStudioForMac, // Mac-only + MonoDevelop, + VsCode, + Rider + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs new file mode 100644 index 0000000000..660971d912 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs @@ -0,0 +1,505 @@ +using Godot; +using GodotTools.Export; +using GodotTools.Utils; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using GodotTools.Ides; +using GodotTools.Ides.Rider; +using GodotTools.Internals; +using GodotTools.ProjectEditor; +using JetBrains.Annotations; +using static GodotTools.Internals.Globals; +using File = GodotTools.Utils.File; +using OS = GodotTools.Utils.OS; + +namespace GodotTools +{ + [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")] + public class GodotSharpEditor : EditorPlugin, ISerializationListener + { + private EditorSettings editorSettings; + + private PopupMenu menuPopup; + + private AcceptDialog errorDialog; + private AcceptDialog aboutDialog; + private CheckBox aboutDialogCheckBox; + + private ToolButton bottomPanelBtn; + + public GodotIdeManager GodotIdeManager { get; private set; } + + private WeakRef exportPluginWeak; // TODO Use WeakReference once we have proper serialization + + public BottomPanel BottomPanel { get; private set; } + + private bool CreateProjectSolution() + { + using (var pr = new EditorProgress("create_csharp_solution", "Generating solution...".TTR(), 3)) + { + pr.Step("Generating C# project...".TTR()); + + string resourceDir = ProjectSettings.GlobalizePath("res://"); + + string path = resourceDir; + string name = (string) ProjectSettings.GetSetting("application/config/name"); + if (name.Empty()) + name = "UnnamedProject"; + + string guid = CsProjOperations.GenerateGameProject(path, name); + + if (guid.Length > 0) + { + var solution = new DotNetSolution(name) + { + DirectoryPath = path + }; + + var projectInfo = new DotNetSolution.ProjectInfo + { + Guid = guid, + PathRelativeToSolution = name + ".csproj", + Configs = new List<string> {"Debug", "Release", "Tools"} + }; + + solution.AddNewProject(name, projectInfo); + + try + { + solution.Save(); + } + catch (IOException e) + { + ShowErrorDialog("Failed to save solution. Exception message: ".TTR() + e.Message); + return false; + } + + pr.Step("Updating Godot API assemblies...".TTR()); + + string debugApiAssembliesError = Internal.UpdateApiAssembliesFromPrebuilt("Debug"); + + if (!string.IsNullOrEmpty(debugApiAssembliesError)) + { + ShowErrorDialog("Failed to update the Godot API assemblies: " + debugApiAssembliesError); + return false; + } + + string releaseApiAssembliesError = Internal.UpdateApiAssembliesFromPrebuilt("Release"); + + if (!string.IsNullOrEmpty(releaseApiAssembliesError)) + { + ShowErrorDialog("Failed to update the Godot API assemblies: " + releaseApiAssembliesError); + return false; + } + + pr.Step("Done".TTR()); + + // Here, after all calls to progress_task_step + CallDeferred(nameof(_RemoveCreateSlnMenuOption)); + } + else + { + ShowErrorDialog("Failed to create C# project.".TTR()); + } + + return true; + } + } + + private void _RemoveCreateSlnMenuOption() + { + menuPopup.RemoveItem(menuPopup.GetItemIndex((int) MenuOptions.CreateSln)); + bottomPanelBtn.Show(); + } + + private void _ShowAboutDialog() + { + bool showOnStart = (bool) editorSettings.GetSetting("mono/editor/show_info_on_start"); + aboutDialogCheckBox.Pressed = showOnStart; + aboutDialog.PopupCenteredMinsize(); + } + + private void _ToggleAboutDialogOnStart(bool enabled) + { + bool showOnStart = (bool) editorSettings.GetSetting("mono/editor/show_info_on_start"); + if (showOnStart != enabled) + editorSettings.SetSetting("mono/editor/show_info_on_start", enabled); + } + + private void _MenuOptionPressed(MenuOptions id) + { + switch (id) + { + case MenuOptions.CreateSln: + CreateProjectSolution(); + break; + case MenuOptions.AboutCSharp: + _ShowAboutDialog(); + break; + default: + throw new ArgumentOutOfRangeException(nameof(id), id, "Invalid menu option"); + } + } + + private void _BuildSolutionPressed() + { + if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) + { + if (!CreateProjectSolution()) + return; // Failed to create solution + } + + Instance.BottomPanel.BuildProjectPressed(); + } + + public override void _Notification(int what) + { + base._Notification(what); + + if (what == NotificationReady) + { + bool showInfoDialog = (bool) editorSettings.GetSetting("mono/editor/show_info_on_start"); + if (showInfoDialog) + { + aboutDialog.PopupExclusive = true; + _ShowAboutDialog(); + // Once shown a first time, it can be seen again via the Mono menu - it doesn't have to be exclusive from that time on. + aboutDialog.PopupExclusive = false; + } + } + } + + private enum MenuOptions + { + CreateSln, + AboutCSharp, + } + + public void ShowErrorDialog(string message, string title = "Error") + { + errorDialog.WindowTitle = title; + errorDialog.DialogText = message; + errorDialog.PopupCenteredMinsize(); + } + + private static string _vsCodePath = string.Empty; + + private static readonly string[] VsCodeNames = + { + "code", "code-oss", "vscode", "vscode-oss", "visual-studio-code", "visual-studio-code-oss" + }; + + [UsedImplicitly] + public Error OpenInExternalEditor(Script script, int line, int col) + { + var editor = (ExternalEditorId) editorSettings.GetSetting("mono/editor/external_editor"); + + switch (editor) + { + case ExternalEditorId.None: + // Tells the caller to fallback to the global external editor settings or the built-in editor + return Error.Unavailable; + case ExternalEditorId.VisualStudio: + throw new NotSupportedException(); + case ExternalEditorId.VisualStudioForMac: + goto case ExternalEditorId.MonoDevelop; + case ExternalEditorId.Rider: + { + string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath); + RiderPathManager.OpenFile(GodotSharpDirs.ProjectSlnPath, scriptPath, line); + return Error.Ok; + } + case ExternalEditorId.MonoDevelop: + { + string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath); + + if (line >= 0) + GodotIdeManager.SendOpenFile(scriptPath, line + 1, col); + else + GodotIdeManager.SendOpenFile(scriptPath); + + break; + } + + case ExternalEditorId.VsCode: + { + if (_vsCodePath.Empty() || !File.Exists(_vsCodePath)) + { + // Try to search it again if it wasn't found last time or if it was removed from its location + _vsCodePath = VsCodeNames.SelectFirstNotNull(OS.PathWhich, orElse: string.Empty); + } + + var args = new List<string>(); + + bool osxAppBundleInstalled = false; + + if (OS.IsOSX) + { + // The package path is '/Applications/Visual Studio Code.app' + const string vscodeBundleId = "com.microsoft.VSCode"; + + osxAppBundleInstalled = Internal.IsOsxAppBundleInstalled(vscodeBundleId); + + if (osxAppBundleInstalled) + { + args.Add("-b"); + args.Add(vscodeBundleId); + + // The reusing of existing windows made by the 'open' command might not choose a wubdiw that is + // editing our folder. It's better to ask for a new window and let VSCode do the window management. + args.Add("-n"); + + // The open process must wait until the application finishes (which is instant in VSCode's case) + args.Add("--wait-apps"); + + args.Add("--args"); + } + } + + var resourcePath = ProjectSettings.GlobalizePath("res://"); + args.Add(resourcePath); + + string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath); + + if (line >= 0) + { + args.Add("-g"); + args.Add($"{scriptPath}:{line + 1}:{col}"); + } + else + { + args.Add(scriptPath); + } + + string command; + + if (OS.IsOSX) + { + if (!osxAppBundleInstalled && _vsCodePath.Empty()) + { + GD.PushError("Cannot find code editor: VSCode"); + return Error.FileNotFound; + } + + command = osxAppBundleInstalled ? "/usr/bin/open" : _vsCodePath; + } + else + { + if (_vsCodePath.Empty()) + { + GD.PushError("Cannot find code editor: VSCode"); + return Error.FileNotFound; + } + + command = _vsCodePath; + } + + try + { + OS.RunProcess(command, args); + } + catch (Exception e) + { + GD.PushError($"Error when trying to run code editor: VSCode. Exception message: '{e.Message}'"); + } + + break; + } + + default: + throw new ArgumentOutOfRangeException(); + } + + return Error.Ok; + } + + [UsedImplicitly] + public bool OverridesExternalEditor() + { + return (ExternalEditorId) editorSettings.GetSetting("mono/editor/external_editor") != ExternalEditorId.None; + } + + public override bool Build() + { + return BuildManager.EditorBuildCallback(); + } + + public override void EnablePlugin() + { + base.EnablePlugin(); + + if (Instance != null) + throw new InvalidOperationException(); + Instance = this; + + var editorInterface = GetEditorInterface(); + var editorBaseControl = editorInterface.GetBaseControl(); + + editorSettings = editorInterface.GetEditorSettings(); + + errorDialog = new AcceptDialog(); + editorBaseControl.AddChild(errorDialog); + + BottomPanel = new BottomPanel(); + + bottomPanelBtn = AddControlToBottomPanel(BottomPanel, "Mono".TTR()); + + AddChild(new HotReloadAssemblyWatcher {Name = "HotReloadAssemblyWatcher"}); + + menuPopup = new PopupMenu(); + menuPopup.Hide(); + menuPopup.SetAsToplevel(true); + + AddToolSubmenuItem("Mono", menuPopup); + + // TODO: Remove or edit this info dialog once Mono support is no longer in alpha + { + menuPopup.AddItem("About C# support".TTR(), (int) MenuOptions.AboutCSharp); + aboutDialog = new AcceptDialog(); + editorBaseControl.AddChild(aboutDialog); + aboutDialog.WindowTitle = "Important: C# support is not feature-complete"; + + // We don't use DialogText as the default AcceptDialog Label doesn't play well with the TextureRect and CheckBox + // we'll add. Instead we add containers and a new autowrapped Label inside. + + // Main VBoxContainer (icon + label on top, checkbox at bottom) + var aboutVBox = new VBoxContainer(); + aboutDialog.AddChild(aboutVBox); + + // HBoxContainer for icon + label + var aboutHBox = new HBoxContainer(); + aboutVBox.AddChild(aboutHBox); + + var aboutIcon = new TextureRect(); + aboutIcon.Texture = aboutIcon.GetIcon("NodeWarning", "EditorIcons"); + aboutHBox.AddChild(aboutIcon); + + var aboutLabel = new Label(); + aboutHBox.AddChild(aboutLabel); + aboutLabel.RectMinSize = new Vector2(600, 150) * EditorScale; + aboutLabel.SizeFlagsVertical = (int) Control.SizeFlags.ExpandFill; + aboutLabel.Autowrap = true; + aboutLabel.Text = + "C# support in Godot Engine is in late alpha stage and, while already usable, " + + "it is not meant for use in production.\n\n" + + "Projects can be exported to Linux, macOS, Windows and Android, but not yet to iOS, HTML5 or UWP. " + + "Bugs and usability issues will be addressed gradually over future releases, " + + "potentially including compatibility breaking changes as new features are implemented for a better overall C# experience.\n\n" + + "If you experience issues with this Mono build, please report them on Godot's issue tracker with details about your system, MSBuild version, IDE, etc.:\n\n" + + " https://github.com/godotengine/godot/issues\n\n" + + "Your critical feedback at this stage will play a great role in shaping the C# support in future releases, so thank you!"; + + EditorDef("mono/editor/show_info_on_start", true); + + // CheckBox in main container + aboutDialogCheckBox = new CheckBox {Text = "Show this warning when starting the editor"}; + aboutDialogCheckBox.Connect("toggled", this, nameof(_ToggleAboutDialogOnStart)); + aboutVBox.AddChild(aboutDialogCheckBox); + } + + if (File.Exists(GodotSharpDirs.ProjectSlnPath) && File.Exists(GodotSharpDirs.ProjectCsProjPath)) + { + // Make sure the existing project has Api assembly references configured correctly + CsProjOperations.FixApiHintPath(GodotSharpDirs.ProjectCsProjPath); + } + else + { + bottomPanelBtn.Hide(); + menuPopup.AddItem("Create C# solution".TTR(), (int) MenuOptions.CreateSln); + } + + menuPopup.Connect("id_pressed", this, nameof(_MenuOptionPressed)); + + var buildButton = new ToolButton + { + Text = "Build", + HintTooltip = "Build solution", + FocusMode = Control.FocusModeEnum.None + }; + buildButton.Connect("pressed", this, nameof(_BuildSolutionPressed)); + AddControlToContainer(CustomControlContainer.Toolbar, buildButton); + + // External editor settings + EditorDef("mono/editor/external_editor", ExternalEditorId.None); + + string settingsHintStr = "Disabled"; + + if (OS.IsWindows) + { + settingsHintStr += $",MonoDevelop:{(int) ExternalEditorId.MonoDevelop}" + + $",Visual Studio Code:{(int) ExternalEditorId.VsCode}" + + $",JetBrains Rider:{(int) ExternalEditorId.Rider}"; + } + else if (OS.IsOSX) + { + settingsHintStr += $",Visual Studio:{(int) ExternalEditorId.VisualStudioForMac}" + + $",MonoDevelop:{(int) ExternalEditorId.MonoDevelop}" + + $",Visual Studio Code:{(int) ExternalEditorId.VsCode}" + + $",JetBrains Rider:{(int) ExternalEditorId.Rider}"; + } + else if (OS.IsUnixLike()) + { + settingsHintStr += $",MonoDevelop:{(int) ExternalEditorId.MonoDevelop}" + + $",Visual Studio Code:{(int) ExternalEditorId.VsCode}" + + $",JetBrains Rider:{(int) ExternalEditorId.Rider}"; + } + + editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary + { + ["type"] = Variant.Type.Int, + ["name"] = "mono/editor/external_editor", + ["hint"] = PropertyHint.Enum, + ["hint_string"] = settingsHintStr + }); + + // Export plugin + var exportPlugin = new ExportPlugin(); + AddExportPlugin(exportPlugin); + exportPlugin.RegisterExportSettings(); + exportPluginWeak = WeakRef(exportPlugin); + + BuildManager.Initialize(); + RiderPathManager.Initialize(); + + GodotIdeManager = new GodotIdeManager(); + AddChild(GodotIdeManager); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (exportPluginWeak != null) + { + // We need to dispose our export plugin before the editor destroys EditorSettings. + // Otherwise, if the GC disposes it at a later time, EditorExportPlatformAndroid + // will be freed after EditorSettings already was, and its device polling thread + // will try to access the EditorSettings singleton, resulting in null dereferencing. + (exportPluginWeak.GetRef() as ExportPlugin)?.Dispose(); + + exportPluginWeak.Dispose(); + } + + GodotIdeManager?.Dispose(); + } + + public void OnBeforeSerialize() + { + } + + public void OnAfterDeserialize() + { + Instance = this; + } + + // Singleton + + public static GodotSharpEditor Instance { get; private set; } + + private GodotSharpEditor() + { + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj new file mode 100644 index 0000000000..be2b70529e --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj @@ -0,0 +1,107 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{27B00618-A6F2-4828-B922-05CAEB08C286}</ProjectGuid> + <OutputType>Library</OutputType> + <RootNamespace>GodotTools</RootNamespace> + <AssemblyName>GodotTools</AssemblyName> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <GodotSourceRootPath>$(SolutionDir)/../../../../</GodotSourceRootPath> + <GodotApiConfiguration>Debug</GodotApiConfiguration> + <LangVersion>7</LangVersion> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>portable</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug</OutputPath> + <DefineConstants>DEBUG;</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <ConsolePause>false</ConsolePause> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <Optimize>true</Optimize> + <OutputPath>bin\Release</OutputPath> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <ConsolePause>false</ConsolePause> + </PropertyGroup> + <ItemGroup> + <Reference Include="JetBrains.Annotations, Version=2019.1.3.0, Culture=neutral, PublicKeyToken=1010a0d8d6380325"> + <HintPath>..\packages\JetBrains.Annotations.2019.1.3\lib\net20\JetBrains.Annotations.dll</HintPath> + <Private>True</Private> + </Reference> + <Reference Include="Mono.Posix" /> + <Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed"> + <HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath> + <Private>True</Private> + </Reference> + <Reference Include="System" /> + <Reference Include="GodotSharp"> + <HintPath>$(GodotSourceRootPath)/bin/GodotSharp/Api/$(GodotApiConfiguration)/GodotSharp.dll</HintPath> + </Reference> + <Reference Include="GodotSharpEditor"> + <HintPath>$(GodotSourceRootPath)/bin/GodotSharp/Api/$(GodotApiConfiguration)/GodotSharpEditor.dll</HintPath> + </Reference> + </ItemGroup> + <ItemGroup> + <Compile Include="Build\MsBuildFinder.cs" /> + <Compile Include="Export\ExportPlugin.cs" /> + <Compile Include="ExternalEditorId.cs" /> + <Compile Include="Ides\GodotIdeManager.cs" /> + <Compile Include="Ides\GodotIdeServer.cs" /> + <Compile Include="Ides\MonoDevelop\EditorId.cs" /> + <Compile Include="Ides\MonoDevelop\Instance.cs" /> + <Compile Include="Ides\Rider\RiderPathLocator.cs" /> + <Compile Include="Ides\Rider\RiderPathManager.cs" /> + <Compile Include="Internals\BindingsGenerator.cs" /> + <Compile Include="Internals\EditorProgress.cs" /> + <Compile Include="Internals\GodotSharpDirs.cs" /> + <Compile Include="Internals\Internal.cs" /> + <Compile Include="Internals\ScriptClassParser.cs" /> + <Compile Include="Internals\Globals.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="Build\BuildSystem.cs" /> + <Compile Include="Utils\Directory.cs" /> + <Compile Include="Utils\File.cs" /> + <Compile Include="Utils\NotifyAwaiter.cs" /> + <Compile Include="Utils\OS.cs" /> + <Compile Include="GodotSharpEditor.cs" /> + <Compile Include="BuildManager.cs" /> + <Compile Include="HotReloadAssemblyWatcher.cs" /> + <Compile Include="BuildInfo.cs" /> + <Compile Include="BuildTab.cs" /> + <Compile Include="BottomPanel.cs" /> + <Compile Include="CsProjOperations.cs" /> + <Compile Include="Utils\CollectionExtensions.cs" /> + <Compile Include="Utils\User32Dll.cs" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\GodotTools.BuildLogger\GodotTools.BuildLogger.csproj"> + <Project>{6ce9a984-37b1-4f8a-8fe9-609f05f071b3}</Project> + <Name>GodotTools.BuildLogger</Name> + </ProjectReference> + <ProjectReference Include="..\GodotTools.IdeConnection\GodotTools.IdeConnection.csproj"> + <Project>{92600954-25f0-4291-8e11-1fee9fc4be20}</Project> + <Name>GodotTools.IdeConnection</Name> + </ProjectReference> + <ProjectReference Include="..\GodotTools.ProjectEditor\GodotTools.ProjectEditor.csproj"> + <Project>{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}</Project> + <Name>GodotTools.ProjectEditor</Name> + </ProjectReference> + <ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj"> + <Project>{639E48BD-44E5-4091-8EDD-22D36DC0768D}</Project> + <Name>GodotTools.Core</Name> + </ProjectReference> + </ItemGroup> + <ItemGroup> + <None Include="packages.config" /> + </ItemGroup> + <ItemGroup> + <Content Include="Ides\Rider\.editorconfig" /> + </ItemGroup> + <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> +</Project>
\ No newline at end of file diff --git a/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs b/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs new file mode 100644 index 0000000000..0f6f5ffadc --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs @@ -0,0 +1,48 @@ +using Godot; +using GodotTools.Internals; +using static GodotTools.Internals.Globals; + +namespace GodotTools +{ + public class HotReloadAssemblyWatcher : Node + { + private Timer watchTimer; + + public override void _Notification(int what) + { + if (what == MainLoop.NotificationWmFocusIn) + { + RestartTimer(); + + if (Internal.IsAssembliesReloadingNeeded()) + Internal.ReloadAssemblies(softReload: false); + } + } + + private void TimerTimeout() + { + if (Internal.IsAssembliesReloadingNeeded()) + Internal.ReloadAssemblies(softReload: false); + } + + public void RestartTimer() + { + watchTimer.Stop(); + watchTimer.Start(); + } + + public override void _Ready() + { + base._Ready(); + + watchTimer = new Timer + { + OneShot = false, + WaitTime = (float) EditorDef("mono/assembly_watch_interval_sec", 0.5) + }; + watchTimer.Connect("timeout", this, nameof(TimerTimeout)); + AddChild(watchTimer); + watchTimer.Start(); + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs new file mode 100644 index 0000000000..3213de0127 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs @@ -0,0 +1,166 @@ +using System; +using System.IO; +using Godot; +using GodotTools.IdeConnection; +using GodotTools.Internals; + +namespace GodotTools.Ides +{ + public class GodotIdeManager : Node, ISerializationListener + { + public GodotIdeServer GodotIdeServer { get; private set; } + + private MonoDevelop.Instance monoDevelInstance; + private MonoDevelop.Instance vsForMacInstance; + + private GodotIdeServer GetRunningServer() + { + if (GodotIdeServer != null && !GodotIdeServer.IsDisposed) + return GodotIdeServer; + StartServer(); + return GodotIdeServer; + } + + public override void _Ready() + { + StartServer(); + } + + public void OnBeforeSerialize() + { + GodotIdeServer?.Dispose(); + } + + public void OnAfterDeserialize() + { + StartServer(); + } + + private ILogger logger; + + protected ILogger Logger + { + get => logger ?? (logger = new GodotLogger()); + } + + private void StartServer() + { + GodotIdeServer?.Dispose(); + GodotIdeServer = new GodotIdeServer(LaunchIde, + OS.GetExecutablePath(), + ProjectSettings.GlobalizePath(GodotSharpDirs.ResMetadataDir)); + + GodotIdeServer.Logger = Logger; + + GodotIdeServer.StartServer(); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + GodotIdeServer?.Dispose(); + } + + private void LaunchIde() + { + var editor = (ExternalEditorId) GodotSharpEditor.Instance.GetEditorInterface() + .GetEditorSettings().GetSetting("mono/editor/external_editor"); + + switch (editor) + { + case ExternalEditorId.None: + case ExternalEditorId.VisualStudio: + case ExternalEditorId.VsCode: + case ExternalEditorId.Rider: + throw new NotSupportedException(); + case ExternalEditorId.VisualStudioForMac: + goto case ExternalEditorId.MonoDevelop; + case ExternalEditorId.MonoDevelop: + { + MonoDevelop.Instance GetMonoDevelopInstance(string solutionPath) + { + if (Utils.OS.IsOSX && editor == ExternalEditorId.VisualStudioForMac) + { + vsForMacInstance = vsForMacInstance ?? + new MonoDevelop.Instance(solutionPath, MonoDevelop.EditorId.VisualStudioForMac); + return vsForMacInstance; + } + + monoDevelInstance = monoDevelInstance ?? + new MonoDevelop.Instance(solutionPath, MonoDevelop.EditorId.MonoDevelop); + return monoDevelInstance; + } + + try + { + var instance = GetMonoDevelopInstance(GodotSharpDirs.ProjectSlnPath); + + if (!instance.IsRunning) + instance.Execute(); + } + catch (FileNotFoundException) + { + string editorName = editor == ExternalEditorId.VisualStudioForMac ? "Visual Studio" : "MonoDevelop"; + GD.PushError($"Cannot find code editor: {editorName}"); + } + + break; + } + + default: + throw new ArgumentOutOfRangeException(); + } + } + + private void WriteMessage(string id, params string[] arguments) + { + GetRunningServer().WriteMessage(new Message(id, arguments)); + } + + public void SendOpenFile(string file) + { + WriteMessage("OpenFile", file); + } + + public void SendOpenFile(string file, int line) + { + WriteMessage("OpenFile", file, line.ToString()); + } + + public void SendOpenFile(string file, int line, int column) + { + WriteMessage("OpenFile", file, line.ToString(), column.ToString()); + } + + private class GodotLogger : ILogger + { + public void LogDebug(string message) + { + if (OS.IsStdoutVerbose()) + Console.WriteLine(message); + } + + public void LogInfo(string message) + { + if (OS.IsStdoutVerbose()) + Console.WriteLine(message); + } + + public void LogWarning(string message) + { + GD.PushWarning(message); + } + + public void LogError(string message) + { + GD.PushError(message); + } + + public void LogError(string message, Exception e) + { + GD.PushError(message + "\n" + e); + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs new file mode 100644 index 0000000000..309b917c71 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using GodotTools.IdeConnection; +using GodotTools.Internals; +using GodotTools.Utils; +using Directory = System.IO.Directory; +using File = System.IO.File; +using Thread = System.Threading.Thread; + +namespace GodotTools.Ides +{ + public class GodotIdeServer : GodotIdeBase + { + private readonly TcpListener listener; + private readonly FileStream metaFile; + private readonly Action launchIdeAction; + private readonly NotifyAwaiter<bool> clientConnectedAwaiter = new NotifyAwaiter<bool>(); + + private async Task<bool> AwaitClientConnected() + { + return await clientConnectedAwaiter.Reset(); + } + + public GodotIdeServer(Action launchIdeAction, string editorExecutablePath, string projectMetadataDir) + : base(projectMetadataDir) + { + messageHandlers = InitializeMessageHandlers(); + + this.launchIdeAction = launchIdeAction; + + // Make sure the directory exists + Directory.CreateDirectory(projectMetadataDir); + + // The Godot editor's file system thread can keep the file open for writing, so we are forced to allow write sharing... + const FileShare metaFileShare = FileShare.ReadWrite; + + metaFile = File.Open(MetaFilePath, FileMode.Create, FileAccess.Write, metaFileShare); + + listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, port: 0)); + listener.Start(); + + int port = ((IPEndPoint) listener.Server.LocalEndPoint).Port; + using (var metaFileWriter = new StreamWriter(metaFile, Encoding.UTF8)) + { + metaFileWriter.WriteLine(port); + metaFileWriter.WriteLine(editorExecutablePath); + } + + StartServer(); + } + + public void StartServer() + { + var serverThread = new Thread(RunServerThread) {Name = "Godot Ide Connection Server"}; + serverThread.Start(); + } + + private void RunServerThread() + { + SynchronizationContext.SetSynchronizationContext(Godot.Dispatcher.SynchronizationContext); + + try + { + while (!IsDisposed) + { + TcpClient tcpClient = listener.AcceptTcpClient(); + + Logger.LogInfo("Connection open with Ide Client"); + + lock (ConnectionLock) + { + Connection = new GodotIdeConnectionServer(tcpClient, HandleMessage); + Connection.Logger = Logger; + } + + Connected += () => clientConnectedAwaiter.SetResult(true); + + Connection.Start(); + } + } + catch (Exception e) + { + if (!IsDisposed && !(e is SocketException se && se.SocketErrorCode == SocketError.Interrupted)) + throw; + } + } + + public async void WriteMessage(Message message) + { + async Task LaunchIde() + { + if (IsConnected) + return; + + launchIdeAction(); + await Task.WhenAny(Task.Delay(10000), AwaitClientConnected()); + } + + await LaunchIde(); + + if (!IsConnected) + { + Logger.LogError("Cannot write message: Godot Ide Server not connected"); + return; + } + + Connection.WriteMessage(message); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (disposing) + { + listener?.Stop(); + + metaFile?.Dispose(); + + File.Delete(MetaFilePath); + } + } + + protected virtual bool HandleMessage(Message message) + { + if (messageHandlers.TryGetValue(message.Id, out var action)) + { + action(message.Arguments); + return true; + } + + return false; + } + + private readonly Dictionary<string, Action<string[]>> messageHandlers; + + private Dictionary<string, Action<string[]>> InitializeMessageHandlers() + { + return new Dictionary<string, Action<string[]>> + { + ["Play"] = args => + { + switch (args.Length) + { + case 0: + Play(); + return; + case 2: + Play(debuggerHost: args[0], debuggerPort: int.Parse(args[1])); + return; + default: + throw new ArgumentException(); + } + }, + ["ReloadScripts"] = args => ReloadScripts() + }; + } + + private void DispatchToMainThread(Action action) + { + var d = new SendOrPostCallback(state => action()); + Godot.Dispatcher.SynchronizationContext.Post(d, null); + } + + private void Play() + { + DispatchToMainThread(() => + { + CurrentPlayRequest = new PlayRequest(); + Internal.EditorRunPlay(); + CurrentPlayRequest = null; + }); + } + + private void Play(string debuggerHost, int debuggerPort) + { + DispatchToMainThread(() => + { + CurrentPlayRequest = new PlayRequest(debuggerHost, debuggerPort); + Internal.EditorRunPlay(); + CurrentPlayRequest = null; + }); + } + + private void ReloadScripts() + { + DispatchToMainThread(Internal.ScriptEditorDebugger_ReloadScripts); + } + + public PlayRequest? CurrentPlayRequest { get; private set; } + + public struct PlayRequest + { + public bool HasDebugger { get; } + public string DebuggerHost { get; } + public int DebuggerPort { get; } + + public PlayRequest(string debuggerHost, int debuggerPort) + { + HasDebugger = true; + DebuggerHost = debuggerHost; + DebuggerPort = debuggerPort; + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/EditorId.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/EditorId.cs new file mode 100644 index 0000000000..1dfc91d6d1 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/EditorId.cs @@ -0,0 +1,8 @@ +namespace GodotTools.Ides.MonoDevelop +{ + public enum EditorId + { + MonoDevelop = 0, + VisualStudioForMac = 1 + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/Instance.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/Instance.cs new file mode 100644 index 0000000000..6026c109ad --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/Instance.cs @@ -0,0 +1,131 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Diagnostics; +using GodotTools.Internals; +using GodotTools.Utils; + +namespace GodotTools.Ides.MonoDevelop +{ + public class Instance + { + private readonly string solutionFile; + private readonly EditorId editorId; + + private Process process; + + public bool IsRunning => process != null && !process.HasExited; + + public void Execute() + { + bool newWindow = process == null || process.HasExited; + + var args = new List<string>(); + + string command; + + if (OS.IsOSX) + { + string bundleId = BundleIds[editorId]; + + if (Internal.IsOsxAppBundleInstalled(bundleId)) + { + command = "open"; + + args.Add("-b"); + args.Add(bundleId); + + // The 'open' process must wait until the application finishes + if (newWindow) + args.Add("--wait-apps"); + + args.Add("--args"); + } + else + { + command = OS.PathWhich(ExecutableNames[editorId]); + } + } + else + { + command = OS.PathWhich(ExecutableNames[editorId]); + } + + args.Add("--ipc-tcp"); + + if (newWindow) + args.Add("\"" + Path.GetFullPath(solutionFile) + "\""); + + if (command == null) + throw new FileNotFoundException(); + + if (newWindow) + { + process = Process.Start(new ProcessStartInfo + { + FileName = command, + Arguments = string.Join(" ", args), + UseShellExecute = true + }); + } + else + { + Process.Start(new ProcessStartInfo + { + FileName = command, + Arguments = string.Join(" ", args), + UseShellExecute = true + })?.Dispose(); + } + } + + public Instance(string solutionFile, EditorId editorId) + { + if (editorId == EditorId.VisualStudioForMac && !OS.IsOSX) + throw new InvalidOperationException($"{nameof(EditorId.VisualStudioForMac)} not supported on this platform"); + + this.solutionFile = solutionFile; + this.editorId = editorId; + } + + private static readonly IReadOnlyDictionary<EditorId, string> ExecutableNames; + private static readonly IReadOnlyDictionary<EditorId, string> BundleIds; + + static Instance() + { + if (OS.IsOSX) + { + ExecutableNames = new Dictionary<EditorId, string> + { + // Rely on PATH + {EditorId.MonoDevelop, "monodevelop"}, + {EditorId.VisualStudioForMac, "VisualStudio"} + }; + BundleIds = new Dictionary<EditorId, string> + { + // TODO EditorId.MonoDevelop + {EditorId.VisualStudioForMac, "com.microsoft.visual-studio"} + }; + } + else if (OS.IsWindows) + { + ExecutableNames = new Dictionary<EditorId, string> + { + // XamarinStudio is no longer a thing, and the latest version is quite old + // MonoDevelop is available from source only on Windows. The recommendation + // is to use Visual Studio instead. Since there are no official builds, we + // will rely on custom MonoDevelop builds being added to PATH. + {EditorId.MonoDevelop, "MonoDevelop.exe"} + }; + } + else if (OS.IsUnixLike()) + { + ExecutableNames = new Dictionary<EditorId, string> + { + // Rely on PATH + {EditorId.MonoDevelop, "monodevelop"} + }; + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/.editorconfig b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/.editorconfig new file mode 100644 index 0000000000..aca19790ca --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/.editorconfig @@ -0,0 +1,6 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf
\ No newline at end of file diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs new file mode 100644 index 0000000000..901ade71e3 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs @@ -0,0 +1,416 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Godot; +using JetBrains.Annotations; +using Microsoft.Win32; +using Newtonsoft.Json; +using Directory = System.IO.Directory; +using Environment = System.Environment; +using File = System.IO.File; +using Path = System.IO.Path; +using OS = GodotTools.Utils.OS; + +namespace GodotTools.Ides.Rider +{ + /// <summary> + /// This code is a modified version of the JetBrains resharper-unity plugin listed under Apache License 2.0 license: + /// https://github.com/JetBrains/resharper-unity/blob/master/unity/JetBrains.Rider.Unity.Editor/EditorPlugin/RiderPathLocator.cs + /// </summary> + public static class RiderPathLocator + { + public static RiderInfo[] GetAllRiderPaths() + { + try + { + if (OS.IsWindows) + { + return CollectRiderInfosWindows(); + } + if (OS.IsOSX) + { + return CollectRiderInfosMac(); + } + if (OS.IsUnixLike()) + { + return CollectAllRiderPathsLinux(); + } + throw new Exception("Unexpected OS."); + } + catch (Exception e) + { + GD.PushWarning(e.Message); + } + + return new RiderInfo[0]; + } + + private static RiderInfo[] CollectAllRiderPathsLinux() + { + var installInfos = new List<RiderInfo>(); + var home = Environment.GetEnvironmentVariable("HOME"); + if (!string.IsNullOrEmpty(home)) + { + var toolboxRiderRootPath = GetToolboxBaseDir(); + installInfos.AddRange(CollectPathsFromToolbox(toolboxRiderRootPath, "bin", "rider.sh", false) + .Select(a => new RiderInfo(a, true)).ToList()); + + //$Home/.local/share/applications/jetbrains-rider.desktop + var shortcut = new FileInfo(Path.Combine(home, @".local/share/applications/jetbrains-rider.desktop")); + + if (shortcut.Exists) + { + var lines = File.ReadAllLines(shortcut.FullName); + foreach (var line in lines) + { + if (!line.StartsWith("Exec=\"")) + continue; + var path = line.Split('"').Where((item, index) => index == 1).SingleOrDefault(); + if (string.IsNullOrEmpty(path)) + continue; + + if (installInfos.Any(a => a.Path == path)) // avoid adding similar build as from toolbox + continue; + installInfos.Add(new RiderInfo(path, false)); + } + } + } + + // snap install + var snapInstallPath = "/snap/rider/current/bin/rider.sh"; + if (new FileInfo(snapInstallPath).Exists) + installInfos.Add(new RiderInfo(snapInstallPath, false)); + + return installInfos.ToArray(); + } + + private static RiderInfo[] CollectRiderInfosMac() + { + var installInfos = new List<RiderInfo>(); + // "/Applications/*Rider*.app" + var folder = new DirectoryInfo("/Applications"); + if (folder.Exists) + { + installInfos.AddRange(folder.GetDirectories("*Rider*.app") + .Select(a => new RiderInfo(a.FullName, false)) + .ToList()); + } + + // /Users/user/Library/Application Support/JetBrains/Toolbox/apps/Rider/ch-1/181.3870.267/Rider EAP.app + var toolboxRiderRootPath = GetToolboxBaseDir(); + var paths = CollectPathsFromToolbox(toolboxRiderRootPath, "", "Rider*.app", true) + .Select(a => new RiderInfo(a, true)); + installInfos.AddRange(paths); + + return installInfos.ToArray(); + } + + private static RiderInfo[] CollectRiderInfosWindows() + { + var installInfos = new List<RiderInfo>(); + var toolboxRiderRootPath = GetToolboxBaseDir(); + var installPathsToolbox = CollectPathsFromToolbox(toolboxRiderRootPath, "bin", "rider64.exe", false).ToList(); + installInfos.AddRange(installPathsToolbox.Select(a => new RiderInfo(a, true)).ToList()); + + var installPaths = new List<string>(); + const string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; + CollectPathsFromRegistry(registryKey, installPaths); + const string wowRegistryKey = @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"; + CollectPathsFromRegistry(wowRegistryKey, installPaths); + + installInfos.AddRange(installPaths.Select(a => new RiderInfo(a, false)).ToList()); + + return installInfos.ToArray(); + } + + private static string GetToolboxBaseDir() + { + if (OS.IsWindows) + { + var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return Path.Combine(localAppData, @"JetBrains\Toolbox\apps\Rider"); + } + + if (OS.IsOSX) + { + var home = Environment.GetEnvironmentVariable("HOME"); + if (!string.IsNullOrEmpty(home)) + { + return Path.Combine(home, @"Library/Application Support/JetBrains/Toolbox/apps/Rider"); + } + } + + if (OS.IsUnixLike()) + { + var home = Environment.GetEnvironmentVariable("HOME"); + if (!string.IsNullOrEmpty(home)) + { + return Path.Combine(home, @".local/share/JetBrains/Toolbox/apps/Rider"); + } + } + + throw new Exception("Unexpected OS."); + } + + internal static ProductInfo GetBuildVersion(string path) + { + var buildTxtFileInfo = new FileInfo(Path.Combine(path, GetRelativePathToBuildTxt())); + var dir = buildTxtFileInfo.DirectoryName; + if (!Directory.Exists(dir)) + return null; + var buildVersionFile = new FileInfo(Path.Combine(dir, "product-info.json")); + if (!buildVersionFile.Exists) + return null; + var json = File.ReadAllText(buildVersionFile.FullName); + return ProductInfo.GetProductInfo(json); + } + + internal static Version GetBuildNumber(string path) + { + var file = new FileInfo(Path.Combine(path, GetRelativePathToBuildTxt())); + if (!file.Exists) + return null; + var text = File.ReadAllText(file.FullName); + if (text.Length <= 3) + return null; + + var versionText = text.Substring(3); + return Version.TryParse(versionText, out var v) ? v : null; + } + + internal static bool IsToolbox(string path) + { + return path.StartsWith(GetToolboxBaseDir()); + } + + private static string GetRelativePathToBuildTxt() + { + if (OS.IsWindows || OS.IsUnixLike()) + return "../../build.txt"; + if (OS.IsOSX) + return "Contents/Resources/build.txt"; + throw new Exception("Unknown OS."); + } + + private static void CollectPathsFromRegistry(string registryKey, List<string> installPaths) + { + using (var key = Registry.LocalMachine.OpenSubKey(registryKey)) + { + if (key == null) return; + foreach (var subkeyName in key.GetSubKeyNames().Where(a => a.Contains("Rider"))) + { + using (var subkey = key.OpenSubKey(subkeyName)) + { + var folderObject = subkey?.GetValue("InstallLocation"); + if (folderObject == null) continue; + var folder = folderObject.ToString(); + var possiblePath = Path.Combine(folder, @"bin\rider64.exe"); + if (File.Exists(possiblePath)) + installPaths.Add(possiblePath); + } + } + } + } + + private static string[] CollectPathsFromToolbox(string toolboxRiderRootPath, string dirName, string searchPattern, + bool isMac) + { + if (!Directory.Exists(toolboxRiderRootPath)) + return new string[0]; + + var channelDirs = Directory.GetDirectories(toolboxRiderRootPath); + var paths = channelDirs.SelectMany(channelDir => + { + try + { + // use history.json - last entry stands for the active build https://jetbrains.slack.com/archives/C07KNP99D/p1547807024066500?thread_ts=1547731708.057700&cid=C07KNP99D + var historyFile = Path.Combine(channelDir, ".history.json"); + if (File.Exists(historyFile)) + { + var json = File.ReadAllText(historyFile); + var build = ToolboxHistory.GetLatestBuildFromJson(json); + if (build != null) + { + var buildDir = Path.Combine(channelDir, build); + var executablePaths = GetExecutablePaths(dirName, searchPattern, isMac, buildDir); + if (executablePaths.Any()) + return executablePaths; + } + } + + var channelFile = Path.Combine(channelDir, ".channel.settings.json"); + if (File.Exists(channelFile)) + { + var json = File.ReadAllText(channelFile).Replace("active-application", "active_application"); + var build = ToolboxInstallData.GetLatestBuildFromJson(json); + if (build != null) + { + var buildDir = Path.Combine(channelDir, build); + var executablePaths = GetExecutablePaths(dirName, searchPattern, isMac, buildDir); + if (executablePaths.Any()) + return executablePaths; + } + } + + // changes in toolbox json files format may brake the logic above, so return all found Rider installations + return Directory.GetDirectories(channelDir) + .SelectMany(buildDir => GetExecutablePaths(dirName, searchPattern, isMac, buildDir)); + } + catch (Exception e) + { + // do not write to Debug.Log, just log it. + Logger.Warn($"Failed to get RiderPath from {channelDir}", e); + } + + return new string[0]; + }) + .Where(c => !string.IsNullOrEmpty(c)) + .ToArray(); + return paths; + } + + private static string[] GetExecutablePaths(string dirName, string searchPattern, bool isMac, string buildDir) + { + var folder = new DirectoryInfo(Path.Combine(buildDir, dirName)); + if (!folder.Exists) + return new string[0]; + + if (!isMac) + return new[] {Path.Combine(folder.FullName, searchPattern)}.Where(File.Exists).ToArray(); + return folder.GetDirectories(searchPattern).Select(f => f.FullName) + .Where(Directory.Exists).ToArray(); + } + + // Disable the "field is never assigned" compiler warning. We never assign it, but Unity does. + // Note that Unity disable this warning in the generated C# projects +#pragma warning disable 0649 + + [Serializable] + class ToolboxHistory + { + public List<ItemNode> history; + + public static string GetLatestBuildFromJson(string json) + { + try + { + return JsonConvert.DeserializeObject<ToolboxHistory>(json).history.LastOrDefault()?.item.build; + } + catch (Exception) + { + Logger.Warn($"Failed to get latest build from json {json}"); + } + + return null; + } + } + + [Serializable] + class ItemNode + { + public BuildNode item; + } + + [Serializable] + class BuildNode + { + public string build; + } + + [Serializable] + public class ProductInfo + { + public string version; + public string versionSuffix; + + [CanBeNull] + internal static ProductInfo GetProductInfo(string json) + { + try + { + var productInfo = JsonConvert.DeserializeObject<ProductInfo>(json); + return productInfo; + } + catch (Exception) + { + Logger.Warn($"Failed to get version from json {json}"); + } + + return null; + } + } + + // ReSharper disable once ClassNeverInstantiated.Global + [Serializable] + class ToolboxInstallData + { + // ReSharper disable once InconsistentNaming + public ActiveApplication active_application; + + [CanBeNull] + public static string GetLatestBuildFromJson(string json) + { + try + { + var toolbox = JsonConvert.DeserializeObject<ToolboxInstallData>(json); + var builds = toolbox.active_application.builds; + if (builds != null && builds.Any()) + return builds.First(); + } + catch (Exception) + { + Logger.Warn($"Failed to get latest build from json {json}"); + } + + return null; + } + } + + [Serializable] + class ActiveApplication + { + // ReSharper disable once InconsistentNaming + public List<string> builds; + } + +#pragma warning restore 0649 + + public struct RiderInfo + { + public bool IsToolbox; + public string Presentation; + public Version BuildNumber; + public ProductInfo ProductInfo; + public string Path; + + public RiderInfo(string path, bool isToolbox) + { + BuildNumber = GetBuildNumber(path); + ProductInfo = GetBuildVersion(path); + Path = new FileInfo(path).FullName; // normalize separators + var presentation = $"Rider {BuildNumber}"; + + if (ProductInfo != null && !string.IsNullOrEmpty(ProductInfo.version)) + { + var suffix = string.IsNullOrEmpty(ProductInfo.versionSuffix) ? "" : $" {ProductInfo.versionSuffix}"; + presentation = $"Rider {ProductInfo.version}{suffix}"; + } + + if (isToolbox) + presentation += " (JetBrains Toolbox)"; + + Presentation = presentation; + IsToolbox = isToolbox; + } + } + + private static class Logger + { + internal static void Warn(string message, Exception e = null) + { + throw new Exception(message, e); + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs new file mode 100644 index 0000000000..b7dba13bbe --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Godot; +using GodotTools.Internals; + +namespace GodotTools.Ides.Rider +{ + public static class RiderPathManager + { + private static readonly string editorPathSettingName= "mono/editor/editor_path_optional"; + + private static string GetRiderPathFromSettings() + { + var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); + if (editorSettings.HasSetting(editorPathSettingName)) + return (string) editorSettings.GetSetting(editorPathSettingName); + return null; + } + + public static void Initialize() + { + var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); + var editor = (ExternalEditorId) editorSettings.GetSetting("mono/editor/external_editor"); + if (editor == ExternalEditorId.Rider) + { + if (!editorSettings.HasSetting(editorPathSettingName)) + { + Globals.EditorDef(editorPathSettingName, "Optional"); + editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary + { + ["type"] = Variant.Type.String, + ["name"] = editorPathSettingName, + ["hint"] = PropertyHint.File, + ["hint_string"] = "" + }); + } + + var riderPath = (string) editorSettings.GetSetting(editorPathSettingName); + if (IsRiderAndExists(riderPath)) + { + Globals.EditorDef(editorPathSettingName, riderPath); + return; + } + + var paths = RiderPathLocator.GetAllRiderPaths(); + + if (!paths.Any()) + return; + + var newPath = paths.Last().Path; + Globals.EditorDef(editorPathSettingName, newPath); + editorSettings.SetSetting(editorPathSettingName, newPath); + } + } + + private static bool IsRider(string path) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } + + var fileInfo = new FileInfo(path); + var filename = fileInfo.Name.ToLowerInvariant(); + return filename.StartsWith("rider", StringComparison.Ordinal); + } + + private static string CheckAndUpdatePath(string riderPath) + { + if (IsRiderAndExists(riderPath)) + { + return riderPath; + } + + var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); + var paths = RiderPathLocator.GetAllRiderPaths(); + + if (!paths.Any()) + return null; + + var newPath = paths.Last().Path; + editorSettings.SetSetting(editorPathSettingName, newPath); + Globals.EditorDef(editorPathSettingName, newPath); + return newPath; + } + + private static bool IsRiderAndExists(string riderPath) + { + return !string.IsNullOrEmpty(riderPath) && IsRider(riderPath) && new FileInfo(riderPath).Exists; + } + + public static void OpenFile(string slnPath, string scriptPath, int line) + { + var pathFromSettings = GetRiderPathFromSettings(); + var path = CheckAndUpdatePath(pathFromSettings); + + var args = new List<string>(); + args.Add(slnPath); + if (line >= 0) + { + args.Add("--line"); + args.Add(line.ToString()); + } + args.Add(scriptPath); + try + { + Utils.OS.RunProcess(path, args); + } + catch (Exception e) + { + GD.PushError($"Error when trying to run code editor: JetBrains Rider. Exception message: '{e.Message}'"); + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/BindingsGenerator.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/BindingsGenerator.cs new file mode 100644 index 0000000000..1daa5e138e --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Internals/BindingsGenerator.cs @@ -0,0 +1,87 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace GodotTools.Internals +{ + public class BindingsGenerator : IDisposable + { + class BindingsGeneratorSafeHandle : SafeHandle + { + public BindingsGeneratorSafeHandle(IntPtr handle) : base(IntPtr.Zero, true) + { + this.handle = handle; + } + + public override bool IsInvalid => handle == IntPtr.Zero; + + protected override bool ReleaseHandle() + { + internal_Dtor(handle); + return true; + } + } + + private BindingsGeneratorSafeHandle safeHandle; + private bool disposed = false; + + public bool LogPrintEnabled + { + get => internal_LogPrintEnabled(GetPtr()); + set => internal_SetLogPrintEnabled(GetPtr(), value); + } + + public static uint Version => internal_Version(); + public static uint CsGlueVersion => internal_CsGlueVersion(); + + public Godot.Error GenerateCsApi(string outputDir) => internal_GenerateCsApi(GetPtr(), outputDir); + + internal IntPtr GetPtr() + { + if (disposed) + throw new ObjectDisposedException(GetType().FullName); + + return safeHandle.DangerousGetHandle(); + } + + public void Dispose() + { + if (disposed) + return; + + if (safeHandle != null && !safeHandle.IsInvalid) + { + safeHandle.Dispose(); + safeHandle = null; + } + + disposed = true; + } + + public BindingsGenerator() + { + safeHandle = new BindingsGeneratorSafeHandle(internal_Ctor()); + } + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern IntPtr internal_Ctor(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_Dtor(IntPtr handle); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool internal_LogPrintEnabled(IntPtr handle); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_SetLogPrintEnabled(IntPtr handle, bool enabled); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Godot.Error internal_GenerateCsApi(IntPtr handle, string outputDir); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern uint internal_Version(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern uint internal_CsGlueVersion(); + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs new file mode 100644 index 0000000000..70ba7c733a --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs @@ -0,0 +1,50 @@ +using System; +using System.Runtime.CompilerServices; +using Godot; + +namespace GodotTools.Internals +{ + public class EditorProgress : IDisposable + { + public string Task { get; } + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_Create(string task, string label, int amount, bool canCancel); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_Dispose(string task); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool internal_Step(string task, string state, int step, bool forceRefresh); + + public EditorProgress(string task, string label, int amount, bool canCancel = false) + { + Task = task; + internal_Create(task, label, amount, canCancel); + } + + ~EditorProgress() + { + // Should never rely on the GC to dispose EditorProgress. + // It should be disposed immediately when the task finishes. + GD.PushError("EditorProgress disposed by the Garbage Collector"); + Dispose(); + } + + public void Dispose() + { + internal_Dispose(Task); + GC.SuppressFinalize(this); + } + + public void Step(string state, int step = -1, bool forceRefresh = true) + { + internal_Step(Task, state, step, forceRefresh); + } + + public bool TryStep(string state, int step = -1, bool forceRefresh = true) + { + return internal_Step(Task, state, step, forceRefresh); + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs new file mode 100644 index 0000000000..793f84fd77 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs @@ -0,0 +1,33 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace GodotTools.Internals +{ + public static class Globals + { + public static float EditorScale => internal_EditorScale(); + + public static object GlobalDef(string setting, object defaultValue, bool restartIfChanged = false) => + internal_GlobalDef(setting, defaultValue, restartIfChanged); + + public static object EditorDef(string setting, object defaultValue, bool restartIfChanged = false) => + internal_EditorDef(setting, defaultValue, restartIfChanged); + + [SuppressMessage("ReSharper", "InconsistentNaming")] + public static string TTR(this string text) => internal_TTR(text); + + // Internal Calls + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float internal_EditorScale(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern object internal_GlobalDef(string setting, object defaultValue, bool restartIfChanged); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern object internal_EditorDef(string setting, object defaultValue, bool restartIfChanged); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_TTR(string text); + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs new file mode 100644 index 0000000000..ddf3b829b5 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs @@ -0,0 +1,91 @@ +using System.Runtime.CompilerServices; + +namespace GodotTools.Internals +{ + public static class GodotSharpDirs + { + public static string ResDataDir => internal_ResDataDir(); + public static string ResMetadataDir => internal_ResMetadataDir(); + public static string ResAssembliesBaseDir => internal_ResAssembliesBaseDir(); + public static string ResAssembliesDir => internal_ResAssembliesDir(); + public static string ResConfigDir => internal_ResConfigDir(); + public static string ResTempDir => internal_ResTempDir(); + public static string ResTempAssembliesBaseDir => internal_ResTempAssembliesBaseDir(); + public static string ResTempAssembliesDir => internal_ResTempAssembliesDir(); + + public static string MonoUserDir => internal_MonoUserDir(); + public static string MonoLogsDir => internal_MonoLogsDir(); + + #region Tools-only + public static string MonoSolutionsDir => internal_MonoSolutionsDir(); + public static string BuildLogsDirs => internal_BuildLogsDirs(); + + public static string ProjectSlnPath => internal_ProjectSlnPath(); + public static string ProjectCsProjPath => internal_ProjectCsProjPath(); + + public static string DataEditorToolsDir => internal_DataEditorToolsDir(); + public static string DataEditorPrebuiltApiDir => internal_DataEditorPrebuiltApiDir(); + #endregion + + public static string DataMonoEtcDir => internal_DataMonoEtcDir(); + public static string DataMonoLibDir => internal_DataMonoLibDir(); + + #region Windows-only + public static string DataMonoBinDir => internal_DataMonoBinDir(); + #endregion + + + #region Internal + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ResDataDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ResMetadataDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ResAssembliesBaseDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ResAssembliesDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ResConfigDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ResTempDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ResTempAssembliesBaseDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ResTempAssembliesDir(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_MonoUserDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_MonoLogsDir(); + + #region Tools-only + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_MonoSolutionsDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_BuildLogsDirs(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ProjectSlnPath(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_ProjectCsProjPath(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_DataEditorToolsDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_DataEditorPrebuiltApiDir(); + #endregion + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_DataMonoEtcDir(); + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_DataMonoLibDir(); + + #region Windows-only + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_DataMonoBinDir(); + #endregion + + #endregion + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs new file mode 100644 index 0000000000..de361ba844 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs @@ -0,0 +1,116 @@ +using System; +using System.Runtime.CompilerServices; +using Godot; +using Godot.Collections; + +namespace GodotTools.Internals +{ + public static class Internal + { + public const string CSharpLanguageType = "CSharpScript"; + public const string CSharpLanguageExtension = "cs"; + + public static string UpdateApiAssembliesFromPrebuilt(string config) => + internal_UpdateApiAssembliesFromPrebuilt(config); + + public static string FullTemplatesDir => + internal_FullTemplatesDir(); + + public static string SimplifyGodotPath(this string path) => internal_SimplifyGodotPath(path); + + public static bool IsOsxAppBundleInstalled(string bundleId) => internal_IsOsxAppBundleInstalled(bundleId); + + public static bool GodotIs32Bits() => internal_GodotIs32Bits(); + + public static bool GodotIsRealTDouble() => internal_GodotIsRealTDouble(); + + public static void GodotMainIteration() => internal_GodotMainIteration(); + + public static ulong GetCoreApiHash() => internal_GetCoreApiHash(); + + public static ulong GetEditorApiHash() => internal_GetEditorApiHash(); + + public static bool IsAssembliesReloadingNeeded() => internal_IsAssembliesReloadingNeeded(); + + public static void ReloadAssemblies(bool softReload) => internal_ReloadAssemblies(softReload); + + public static void ScriptEditorDebuggerReloadScripts() => internal_ScriptEditorDebuggerReloadScripts(); + + public static bool ScriptEditorEdit(Resource resource, int line, int col, bool grabFocus = true) => + internal_ScriptEditorEdit(resource, line, col, grabFocus); + + public static void EditorNodeShowScriptScreen() => internal_EditorNodeShowScriptScreen(); + + public static Dictionary<string, object> GetScriptsMetadataOrNothing() => + internal_GetScriptsMetadataOrNothing(typeof(Dictionary<string, object>)); + + public static string MonoWindowsInstallRoot => internal_MonoWindowsInstallRoot(); + + public static void EditorRunPlay() => internal_EditorRunPlay(); + + public static void EditorRunStop() => internal_EditorRunStop(); + + public static void ScriptEditorDebugger_ReloadScripts() => internal_ScriptEditorDebugger_ReloadScripts(); + + #region Internal + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_UpdateApiAssembliesFromPrebuilt(string config); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_FullTemplatesDir(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_SimplifyGodotPath(this string path); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool internal_IsOsxAppBundleInstalled(string bundleId); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool internal_GodotIs32Bits(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool internal_GodotIsRealTDouble(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_GodotMainIteration(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern ulong internal_GetCoreApiHash(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern ulong internal_GetEditorApiHash(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool internal_IsAssembliesReloadingNeeded(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_ReloadAssemblies(bool softReload); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_ScriptEditorDebuggerReloadScripts(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool internal_ScriptEditorEdit(Resource resource, int line, int col, bool grabFocus); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_EditorNodeShowScriptScreen(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Dictionary<string, object> internal_GetScriptsMetadataOrNothing(Type dictType); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string internal_MonoWindowsInstallRoot(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_EditorRunPlay(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_EditorRunStop(); + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void internal_ScriptEditorDebugger_ReloadScripts(); + + #endregion + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs new file mode 100644 index 0000000000..2497d276a9 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Godot; +using Godot.Collections; + +namespace GodotTools.Internals +{ + public static class ScriptClassParser + { + public class ClassDecl + { + public string Name { get; } + public string Namespace { get; } + public bool Nested { get; } + public int BaseCount { get; } + + public ClassDecl(string name, string @namespace, bool nested, int baseCount) + { + Name = name; + Namespace = @namespace; + Nested = nested; + BaseCount = baseCount; + } + } + + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Error internal_ParseFile(string filePath, Array<Dictionary> classes); + + public static void ParseFileOrThrow(string filePath, out IEnumerable<ClassDecl> classes) + { + var classesArray = new Array<Dictionary>(); + var error = internal_ParseFile(filePath, classesArray); + if (error != Error.Ok) + throw new Exception($"Failed to determine namespace and class for script: {filePath}. Parse error: {error}"); + + var classesList = new List<ClassDecl>(); + + foreach (var classDeclDict in classesArray) + { + classesList.Add(new ClassDecl( + (string) classDeclDict["name"], + (string) classDeclDict["namespace"], + (bool) classDeclDict["nested"], + (int) classDeclDict["base_count"] + )); + } + + classes = classesList; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..f5fe85c722 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs @@ -0,0 +1,26 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +// Information about this assembly is defined by the following attributes. +// Change them to the values specific to your project. + +[assembly: AssemblyTitle("GodotTools")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("Godot Engine contributors")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". +// The form "{Major}.{Minor}.*" will automatically update the build and revision, +// and "{Major}.{Minor}.{Build}.*" will update just the revision. + +[assembly: AssemblyVersion("1.0.*")] + +// The following attributes are used to specify the signing key for the assembly, +// if desired. See the Mono documentation for more information about signing. + +//[assembly: AssemblyDelaySign(false)] +//[assembly: AssemblyKeyFile("")] diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/CollectionExtensions.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/CollectionExtensions.cs new file mode 100644 index 0000000000..e3c2c822a5 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Utils/CollectionExtensions.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace GodotTools.Utils +{ + public static class CollectionExtensions + { + public static T SelectFirstNotNull<T>(this IEnumerable<T> enumerable, Func<T, T> predicate, T orElse = null) + where T : class + { + foreach (T elem in enumerable) + { + T result = predicate(elem); + if (result != null) + return result; + } + + return orElse; + } + + public static IEnumerable<string> EnumerateLines(this TextReader textReader) + { + string line; + while ((line = textReader.ReadLine()) != null) + yield return line; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/Directory.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/Directory.cs new file mode 100644 index 0000000000..c67d48b92a --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Utils/Directory.cs @@ -0,0 +1,40 @@ +using System.IO; +using Godot; + +namespace GodotTools.Utils +{ + public static class Directory + { + private static string GlobalizePath(this string path) + { + return ProjectSettings.GlobalizePath(path); + } + + public static bool Exists(string path) + { + return System.IO.Directory.Exists(path.GlobalizePath()); + } + + /// Create directory recursively + public static DirectoryInfo CreateDirectory(string path) + { + return System.IO.Directory.CreateDirectory(path.GlobalizePath()); + } + + public static void Delete(string path, bool recursive) + { + System.IO.Directory.Delete(path.GlobalizePath(), recursive); + } + + + public static string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) + { + return System.IO.Directory.GetDirectories(path.GlobalizePath(), searchPattern, searchOption); + } + + public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption) + { + return System.IO.Directory.GetFiles(path.GlobalizePath(), searchPattern, searchOption); + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/File.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/File.cs new file mode 100644 index 0000000000..e1e2188edb --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Utils/File.cs @@ -0,0 +1,43 @@ +using System; +using Godot; + +namespace GodotTools.Utils +{ + public static class File + { + private static string GlobalizePath(this string path) + { + return ProjectSettings.GlobalizePath(path); + } + + public static void WriteAllText(string path, string contents) + { + System.IO.File.WriteAllText(path.GlobalizePath(), contents); + } + + public static bool Exists(string path) + { + return System.IO.File.Exists(path.GlobalizePath()); + } + + public static DateTime GetLastWriteTime(string path) + { + return System.IO.File.GetLastWriteTime(path.GlobalizePath()); + } + + public static void Delete(string path) + { + System.IO.File.Delete(path.GlobalizePath()); + } + + public static void Copy(string sourceFileName, string destFileName) + { + System.IO.File.Copy(sourceFileName.GlobalizePath(), destFileName.GlobalizePath(), overwrite: true); + } + + public static byte[] ReadAllBytes(string path) + { + return System.IO.File.ReadAllBytes(path.GlobalizePath()); + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs new file mode 100644 index 0000000000..700b786752 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs @@ -0,0 +1,64 @@ +using System; +using System.Runtime.CompilerServices; + +namespace GodotTools.Utils +{ + public sealed class NotifyAwaiter<T> : INotifyCompletion + { + private Action continuation; + private Exception exception; + private T result; + + public bool IsCompleted { get; private set; } + + public T GetResult() + { + if (exception != null) + throw exception; + return result; + } + + public void OnCompleted(Action continuation) + { + if (this.continuation != null) + throw new InvalidOperationException("This awaiter has already been listened"); + this.continuation = continuation; + } + + public void SetResult(T result) + { + if (IsCompleted) + throw new InvalidOperationException("This awaiter is already completed"); + + IsCompleted = true; + this.result = result; + + continuation?.Invoke(); + } + + public void SetException(Exception exception) + { + if (IsCompleted) + throw new InvalidOperationException("This awaiter is already completed"); + + IsCompleted = true; + this.exception = exception; + + continuation?.Invoke(); + } + + public NotifyAwaiter<T> Reset() + { + continuation = null; + exception = null; + result = default(T); + IsCompleted = false; + return this; + } + + public NotifyAwaiter<T> GetAwaiter() + { + return this; + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs new file mode 100644 index 0000000000..1fe07e0bb6 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using Mono.Unix.Native; + +namespace GodotTools.Utils +{ + [SuppressMessage("ReSharper", "InconsistentNaming")] + public static class OS + { + [MethodImpl(MethodImplOptions.InternalCall)] + static extern string GetPlatformName(); + + public static class Names + { + public const string Windows = "Windows"; + public const string OSX = "OSX"; + public const string X11 = "X11"; + public const string Server = "Server"; + public const string UWP = "UWP"; + public const string Haiku = "Haiku"; + public const string Android = "Android"; + public const string HTML5 = "HTML5"; + } + + public static class Platforms + { + public const string Windows = "windows"; + public const string OSX = "osx"; + public const string X11 = "x11"; + public const string Server = "server"; + public const string UWP = "uwp"; + public const string Haiku = "haiku"; + public const string Android = "android"; + public const string HTML5 = "javascript"; + } + + public static readonly Dictionary<string, string> PlatformNameMap = new Dictionary<string, string> + { + [Names.Windows] = Platforms.Windows, + [Names.OSX] = Platforms.OSX, + [Names.X11] = Platforms.X11, + [Names.Server] = Platforms.Server, + [Names.UWP] = Platforms.UWP, + [Names.Haiku] = Platforms.Haiku, + [Names.Android] = Platforms.Android, + [Names.HTML5] = Platforms.HTML5 + }; + + private static bool IsOS(string name) + { + return name.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase); + } + + private static readonly Lazy<bool> _isWindows = new Lazy<bool>(() => IsOS(Names.Windows)); + private static readonly Lazy<bool> _isOSX = new Lazy<bool>(() => IsOS(Names.OSX)); + private static readonly Lazy<bool> _isX11 = new Lazy<bool>(() => IsOS(Names.X11)); + private static readonly Lazy<bool> _isServer = new Lazy<bool>(() => IsOS(Names.Server)); + private static readonly Lazy<bool> _isUWP = new Lazy<bool>(() => IsOS(Names.UWP)); + private static readonly Lazy<bool> _isHaiku = new Lazy<bool>(() => IsOS(Names.Haiku)); + private static readonly Lazy<bool> _isAndroid = new Lazy<bool>(() => IsOS(Names.Android)); + private static readonly Lazy<bool> _isHTML5 = new Lazy<bool>(() => IsOS(Names.HTML5)); + + public static bool IsWindows => _isWindows.Value || IsUWP; + public static bool IsOSX => _isOSX.Value; + public static bool IsX11 => _isX11.Value; + public static bool IsServer => _isServer.Value; + public static bool IsUWP => _isUWP.Value; + public static bool IsHaiku => _isHaiku.Value; + public static bool IsAndroid => _isAndroid.Value; + public static bool IsHTML5 => _isHTML5.Value; + + private static bool? _isUnixCache; + private static readonly string[] UnixLikePlatforms = {Names.OSX, Names.X11, Names.Server, Names.Haiku, Names.Android}; + + public static bool IsUnixLike() + { + if (_isUnixCache.HasValue) + return _isUnixCache.Value; + + string osName = GetPlatformName(); + _isUnixCache = UnixLikePlatforms.Any(p => p.Equals(osName, StringComparison.OrdinalIgnoreCase)); + return _isUnixCache.Value; + } + + public static char PathSep => IsWindows ? ';' : ':'; + + public static string PathWhich(string name) + { + return IsWindows ? PathWhichWindows(name) : PathWhichUnix(name); + } + + private static string PathWhichWindows(string name) + { + string[] windowsExts = Environment.GetEnvironmentVariable("PATHEXT")?.Split(PathSep) ?? new string[] { }; + string[] pathDirs = Environment.GetEnvironmentVariable("PATH")?.Split(PathSep); + + var searchDirs = new List<string>(); + + if (pathDirs != null) + searchDirs.AddRange(pathDirs); + + string nameExt = Path.GetExtension(name); + bool hasPathExt = string.IsNullOrEmpty(nameExt) || windowsExts.Contains(nameExt, StringComparer.OrdinalIgnoreCase); + + searchDirs.Add(System.IO.Directory.GetCurrentDirectory()); // last in the list + + if (hasPathExt) + return searchDirs.Select(dir => Path.Combine(dir, name)).FirstOrDefault(File.Exists); + + return (from dir in searchDirs + select Path.Combine(dir, name) + into path + from ext in windowsExts + select path + ext).FirstOrDefault(File.Exists); + } + + private static string PathWhichUnix(string name) + { + string[] pathDirs = Environment.GetEnvironmentVariable("PATH")?.Split(PathSep); + + var searchDirs = new List<string>(); + + if (pathDirs != null) + searchDirs.AddRange(pathDirs); + + searchDirs.Add(System.IO.Directory.GetCurrentDirectory()); // last in the list + + return searchDirs.Select(dir => Path.Combine(dir, name)) + .FirstOrDefault(path => File.Exists(path) && Syscall.access(path, AccessModes.X_OK) == 0); + } + + public static void RunProcess(string command, IEnumerable<string> arguments) + { + // TODO: Once we move to .NET Standard 2.1 we can use ProcessStartInfo.ArgumentList instead + string CmdLineArgsToString(IEnumerable<string> args) + { + // Not perfect, but as long as we are careful... + return string.Join(" ", args.Select(arg => arg.Contains(" ") ? $@"""{arg}""" : arg)); + } + + var startInfo = new ProcessStartInfo(command, CmdLineArgsToString(arguments)) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }; + + using (Process process = Process.Start(startInfo)) + { + if (process == null) + throw new Exception("No process was started"); + + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + if (IsWindows && process.Id>0) + User32Dll.AllowSetForegroundWindow(process.Id); // allows application to focus itself + } + } + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/User32Dll.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/User32Dll.cs new file mode 100644 index 0000000000..6810a991b3 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/Utils/User32Dll.cs @@ -0,0 +1,10 @@ +using System.Runtime.InteropServices; + +namespace GodotTools.Utils +{ + public static class User32Dll + { + [DllImport("user32.dll")] + public static extern bool AllowSetForegroundWindow(int dwProcessId); + } +} diff --git a/modules/mono/editor/GodotTools/GodotTools/packages.config b/modules/mono/editor/GodotTools/GodotTools/packages.config new file mode 100644 index 0000000000..2db4b4acc6 --- /dev/null +++ b/modules/mono/editor/GodotTools/GodotTools/packages.config @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="JetBrains.Annotations" version="2019.1.3" targetFramework="net45" /> + <package id="Newtonsoft.Json" version="12.0.3" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index 84e2303cf6..2252f7676d 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -30,7 +30,7 @@ #include "bindings_generator.h" -#ifdef DEBUG_METHODS_ENABLED +#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) #include "core/engine.h" #include "core/global_constants.h" @@ -38,7 +38,6 @@ #include "core/os/dir_access.h" #include "core/os/file_access.h" #include "core/os/os.h" -#include "core/string_builder.h" #include "core/ucaps.h" #include "../glue/cs_compressed.gen.h" @@ -98,13 +97,9 @@ #define C_METHOD_MONOARRAY_TO(m_type) C_NS_MONOMARSHAL "::mono_array_to_" #m_type #define C_METHOD_MONOARRAY_FROM(m_type) C_NS_MONOMARSHAL "::" #m_type "_to_mono_array" -#define BINDINGS_GENERATOR_VERSION UINT32_C(8) +#define BINDINGS_GENERATOR_VERSION UINT32_C(11) -const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN = "\t%0 %1_in = %1;\n"; - -bool BindingsGenerator::verbose_output = false; - -BindingsGenerator *BindingsGenerator::singleton = NULL; +const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN("\t%0 %1_in = %1;\n"); static String fix_doc_description(const String &p_bbcode) { @@ -284,7 +279,7 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf Vector<String> link_target_parts = link_target.split("."); if (link_target_parts.size() <= 0 || link_target_parts.size() > 2) { - ERR_PRINTS("Invalid reference format: " + tag); + ERR_PRINTS("Invalid reference format: '" + tag + "'."); xml_output.append("<c>"); xml_output.append(tag); @@ -380,7 +375,7 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf xml_output.append(target_enum_itype.proxy_name); // Includes nesting class if any xml_output.append("\"/>"); } else { - ERR_PRINTS("Cannot resolve enum reference in documentation: " + link_target); + ERR_PRINTS("Cannot resolve enum reference in documentation: '" + link_target + "'."); xml_output.append("<c>"); xml_output.append(link_target); @@ -429,7 +424,7 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf xml_output.append(target_iconst->proxy_name); xml_output.append("\"/>"); } else { - ERR_PRINTS("Cannot resolve global constant reference in documentation: " + link_target); + ERR_PRINTS("Cannot resolve global constant reference in documentation: '" + link_target + "'."); xml_output.append("<c>"); xml_output.append(link_target); @@ -469,7 +464,7 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf xml_output.append(target_iconst->proxy_name); xml_output.append("\"/>"); } else { - ERR_PRINTS("Cannot resolve constant reference in documentation: " + link_target); + ERR_PRINTS("Cannot resolve constant reference in documentation: '" + link_target + "'."); xml_output.append("<c>"); xml_output.append(link_target); @@ -539,7 +534,7 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf xml_output.append(target_itype->proxy_name); xml_output.append("\"/>"); } else { - ERR_PRINTS("Cannot resolve type reference in documentation: " + tag); + ERR_PRINTS("Cannot resolve type reference in documentation: '" + tag + "'."); xml_output.append("<c>"); xml_output.append(tag); @@ -736,13 +731,26 @@ void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) { i++; } + String im_type_out = return_type->im_type_out; + + if (return_type->ret_as_byref_arg) { + // Doesn't affect the unique signature + im_type_out = "void"; + + im_sig += ", "; + im_sig += return_type->im_type_out; + im_sig += " argRet"; + + i++; + } + // godot_icall_{argc}_{icallcount} String icall_method = ICALL_PREFIX; icall_method += itos(imethod.arguments.size()); icall_method += "_"; icall_method += itos(method_icalls.size()); - InternalCall im_icall = InternalCall(p_itype.api_type, icall_method, return_type->im_type_out, im_sig, im_unique_sig); + InternalCall im_icall = InternalCall(p_itype.api_type, icall_method, im_type_out, im_sig, im_unique_sig); List<InternalCall>::Element *match = method_icalls.find(im_icall); @@ -757,47 +765,47 @@ void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) { } } -void BindingsGenerator::_generate_global_constants(List<String> &p_output) { +void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) { // Constants (in partial GD class) - p_output.push_back("\n#pragma warning disable CS1591 // Disable warning: " - "'Missing XML comment for publicly visible type or member'\n"); + p_output.append("\n#pragma warning disable CS1591 // Disable warning: " + "'Missing XML comment for publicly visible type or member'\n"); - p_output.push_back("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); - p_output.push_back(INDENT1 "public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" INDENT1 "{"); + p_output.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); + p_output.append(INDENT1 "public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" INDENT1 "{"); for (const List<ConstantInterface>::Element *E = global_constants.front(); E; E = E->next()) { const ConstantInterface &iconstant = E->get(); if (iconstant.const_doc && iconstant.const_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), NULL); - Vector<String> summary_lines = xml_summary.split("\n"); + Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); if (summary_lines.size()) { - p_output.push_back(MEMBER_BEGIN "/// <summary>\n"); + p_output.append(MEMBER_BEGIN "/// <summary>\n"); for (int i = 0; i < summary_lines.size(); i++) { - p_output.push_back(INDENT2 "/// "); - p_output.push_back(summary_lines[i]); - p_output.push_back("\n"); + p_output.append(INDENT2 "/// "); + p_output.append(summary_lines[i]); + p_output.append("\n"); } - p_output.push_back(INDENT2 "/// </summary>"); + p_output.append(INDENT2 "/// </summary>"); } } - p_output.push_back(MEMBER_BEGIN "public const int "); - p_output.push_back(iconstant.proxy_name); - p_output.push_back(" = "); - p_output.push_back(itos(iconstant.value)); - p_output.push_back(";"); + p_output.append(MEMBER_BEGIN "public const int "); + p_output.append(iconstant.proxy_name); + p_output.append(" = "); + p_output.append(itos(iconstant.value)); + p_output.append(";"); } if (!global_constants.empty()) - p_output.push_back("\n"); + p_output.append("\n"); - p_output.push_back(INDENT1 CLOSE_BLOCK); // end of GD class + p_output.append(INDENT1 CLOSE_BLOCK); // end of GD class // Enums @@ -817,90 +825,84 @@ void BindingsGenerator::_generate_global_constants(List<String> &p_output) { CRASH_COND(enum_class_name != "Variant"); // Hard-coded... - if (verbose_output) { - WARN_PRINTS("Declaring global enum `" + enum_proxy_name + "` inside static class `" + enum_class_name + "`"); - } + _log("Declaring global enum '%s' inside static class '%s'\n", enum_proxy_name.utf8().get_data(), enum_class_name.utf8().get_data()); - p_output.push_back("\n" INDENT1 "public static partial class "); - p_output.push_back(enum_class_name); - p_output.push_back("\n" INDENT1 OPEN_BLOCK); + p_output.append("\n" INDENT1 "public static partial class "); + p_output.append(enum_class_name); + p_output.append("\n" INDENT1 OPEN_BLOCK); } - p_output.push_back("\n" INDENT1 "public enum "); - p_output.push_back(enum_proxy_name); - p_output.push_back("\n" INDENT1 OPEN_BLOCK); + p_output.append("\n" INDENT1 "public enum "); + p_output.append(enum_proxy_name); + p_output.append("\n" INDENT1 OPEN_BLOCK); for (const List<ConstantInterface>::Element *F = ienum.constants.front(); F; F = F->next()) { const ConstantInterface &iconstant = F->get(); if (iconstant.const_doc && iconstant.const_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), NULL); - Vector<String> summary_lines = xml_summary.split("\n"); + Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); if (summary_lines.size()) { - p_output.push_back(INDENT2 "/// <summary>\n"); + p_output.append(INDENT2 "/// <summary>\n"); for (int i = 0; i < summary_lines.size(); i++) { - p_output.push_back(INDENT2 "/// "); - p_output.push_back(summary_lines[i]); - p_output.push_back("\n"); + p_output.append(INDENT2 "/// "); + p_output.append(summary_lines[i]); + p_output.append("\n"); } - p_output.push_back(INDENT2 "/// </summary>\n"); + p_output.append(INDENT2 "/// </summary>\n"); } } - p_output.push_back(INDENT2); - p_output.push_back(iconstant.proxy_name); - p_output.push_back(" = "); - p_output.push_back(itos(iconstant.value)); - p_output.push_back(F != ienum.constants.back() ? ",\n" : "\n"); + p_output.append(INDENT2); + p_output.append(iconstant.proxy_name); + p_output.append(" = "); + p_output.append(itos(iconstant.value)); + p_output.append(F != ienum.constants.back() ? ",\n" : "\n"); } - p_output.push_back(INDENT1 CLOSE_BLOCK); + p_output.append(INDENT1 CLOSE_BLOCK); if (enum_in_static_class) - p_output.push_back(INDENT1 CLOSE_BLOCK); + p_output.append(INDENT1 CLOSE_BLOCK); } - p_output.push_back(CLOSE_BLOCK); // end of namespace + p_output.append(CLOSE_BLOCK); // end of namespace - p_output.push_back("\n#pragma warning restore CS1591\n"); + p_output.append("\n#pragma warning restore CS1591\n"); } -Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir, DotNetSolution &r_solution, bool p_verbose_output) { +Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir, Vector<String> &r_compile_items) { - verbose_output = p_verbose_output; - - String proj_dir = p_solution_dir.plus_file(CORE_API_ASSEMBLY_NAME); + ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED); DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); ERR_FAIL_COND_V(!da, ERR_CANT_CREATE); - if (!DirAccess::exists(proj_dir)) { - Error err = da->make_dir_recursive(proj_dir); - ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE); + if (!DirAccess::exists(p_proj_dir)) { + Error err = da->make_dir_recursive(p_proj_dir); + ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Cannot create directory '" + p_proj_dir + "'."); } - da->change_dir(proj_dir); + da->change_dir(p_proj_dir); da->make_dir("Core"); da->make_dir("ObjectType"); - String core_dir = path_join(proj_dir, "Core"); - String obj_type_dir = path_join(proj_dir, "ObjectType"); - - Vector<String> compile_items; + String core_dir = path::join(p_proj_dir, "Core"); + String obj_type_dir = path::join(p_proj_dir, "ObjectType"); // Generate source file for global scope constants and enums { - List<String> constants_source; + StringBuilder constants_source; _generate_global_constants(constants_source); - String output_file = path_join(core_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs"); + String output_file = path::join(core_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs"); Error save_err = _save_file(output_file, constants_source); if (save_err != OK) return save_err; - compile_items.push_back(output_file); + r_compile_items.push_back(output_file); } for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) { @@ -909,7 +911,7 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir, if (itype.api_type == ClassDB::API_EDITOR) continue; - String output_file = path_join(obj_type_dir, itype.proxy_name + ".cs"); + String output_file = path::join(obj_type_dir, itype.proxy_name + ".cs"); Error err = _generate_cs_type(itype, output_file); if (err == ERR_SKIP) @@ -918,19 +920,19 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir, if (err != OK) return err; - compile_items.push_back(output_file); + r_compile_items.push_back(output_file); } // Generate sources from compressed files - Map<String, CompressedFile> compressed_files; + Map<String, GodotCsCompressedFile> compressed_files; get_compressed_files(compressed_files); - for (Map<String, CompressedFile>::Element *E = compressed_files.front(); E; E = E->next()) { + for (Map<String, GodotCsCompressedFile>::Element *E = compressed_files.front(); E; E = E->next()) { const String &file_name = E->key(); - const CompressedFile &file_data = E->value(); + const GodotCsCompressedFile &file_data = E->value(); - String output_file = path_join(core_dir, file_name); + String output_file = path::join(core_dir, file_name); Vector<uint8_t> data; data.resize(file_data.uncompressed_size); @@ -948,31 +950,31 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir, file->store_buffer(data.ptr(), data.size()); file->close(); - compile_items.push_back(output_file); + r_compile_items.push_back(output_file); } - List<String> cs_icalls_content; - - cs_icalls_content.push_back("using System;\n" - "using System.Runtime.CompilerServices;\n" - "\n"); - cs_icalls_content.push_back("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); - cs_icalls_content.push_back(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS "\n" INDENT1 OPEN_BLOCK); - - cs_icalls_content.push_back(MEMBER_BEGIN "internal static ulong godot_api_hash = "); - cs_icalls_content.push_back(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + ";\n"); - cs_icalls_content.push_back(MEMBER_BEGIN "internal static uint bindings_version = "); - cs_icalls_content.push_back(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n"); - cs_icalls_content.push_back(MEMBER_BEGIN "internal static uint cs_glue_version = "); - cs_icalls_content.push_back(String::num_uint64(CS_GLUE_VERSION) + ";\n"); - -#define ADD_INTERNAL_CALL(m_icall) \ - if (!m_icall.editor_only) { \ - cs_icalls_content.push_back(MEMBER_BEGIN "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \ - cs_icalls_content.push_back(INDENT2 "internal extern static "); \ - cs_icalls_content.push_back(m_icall.im_type_out + " "); \ - cs_icalls_content.push_back(m_icall.name + "("); \ - cs_icalls_content.push_back(m_icall.im_sig + ");\n"); \ + StringBuilder cs_icalls_content; + + cs_icalls_content.append("using System;\n" + "using System.Runtime.CompilerServices;\n" + "\n"); + cs_icalls_content.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); + cs_icalls_content.append(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS "\n" INDENT1 OPEN_BLOCK); + + cs_icalls_content.append(MEMBER_BEGIN "internal static ulong godot_api_hash = "); + cs_icalls_content.append(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + ";\n"); + cs_icalls_content.append(MEMBER_BEGIN "internal static uint bindings_version = "); + cs_icalls_content.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n"); + cs_icalls_content.append(MEMBER_BEGIN "internal static uint cs_glue_version = "); + cs_icalls_content.append(String::num_uint64(CS_GLUE_VERSION) + ";\n"); + +#define ADD_INTERNAL_CALL(m_icall) \ + if (!m_icall.editor_only) { \ + cs_icalls_content.append(MEMBER_BEGIN "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \ + cs_icalls_content.append(INDENT2 "internal extern static "); \ + cs_icalls_content.append(m_icall.im_type_out + " "); \ + cs_icalls_content.append(m_icall.name + "("); \ + cs_icalls_content.append(m_icall.im_sig + ");\n"); \ } for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next()) @@ -982,54 +984,37 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir, #undef ADD_INTERNAL_CALL - cs_icalls_content.push_back(INDENT1 CLOSE_BLOCK CLOSE_BLOCK); + cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK); - String internal_methods_file = path_join(core_dir, BINDINGS_CLASS_NATIVECALLS ".cs"); + String internal_methods_file = path::join(core_dir, BINDINGS_CLASS_NATIVECALLS ".cs"); Error err = _save_file(internal_methods_file, cs_icalls_content); if (err != OK) return err; - compile_items.push_back(internal_methods_file); - - String guid = CSharpProject::generate_core_api_project(proj_dir, compile_items); - - DotNetSolution::ProjectInfo proj_info; - proj_info.guid = guid; - proj_info.relpath = String(CORE_API_ASSEMBLY_NAME).plus_file(CORE_API_ASSEMBLY_NAME ".csproj"); - proj_info.configs.push_back("Debug"); - proj_info.configs.push_back("Release"); - - r_solution.add_new_project(CORE_API_ASSEMBLY_NAME, proj_info); - - if (verbose_output) - OS::get_singleton()->print("The solution and C# project for the Core API was generated successfully\n"); + r_compile_items.push_back(internal_methods_file); return OK; } -Error BindingsGenerator::generate_cs_editor_project(const String &p_solution_dir, DotNetSolution &r_solution, bool p_verbose_output) { - - verbose_output = p_verbose_output; +Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir, Vector<String> &r_compile_items) { - String proj_dir = p_solution_dir.plus_file(EDITOR_API_ASSEMBLY_NAME); + ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED); DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); ERR_FAIL_COND_V(!da, ERR_CANT_CREATE); - if (!DirAccess::exists(proj_dir)) { - Error err = da->make_dir_recursive(proj_dir); + if (!DirAccess::exists(p_proj_dir)) { + Error err = da->make_dir_recursive(p_proj_dir); ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE); } - da->change_dir(proj_dir); + da->change_dir(p_proj_dir); da->make_dir("Core"); da->make_dir("ObjectType"); - String core_dir = path_join(proj_dir, "Core"); - String obj_type_dir = path_join(proj_dir, "ObjectType"); - - Vector<String> compile_items; + String core_dir = path::join(p_proj_dir, "Core"); + String obj_type_dir = path::join(p_proj_dir, "ObjectType"); for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) { const TypeInterface &itype = E.get(); @@ -1037,7 +1022,7 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_solution_dir if (itype.api_type != ClassDB::API_EDITOR) continue; - String output_file = path_join(obj_type_dir, itype.proxy_name + ".cs"); + String output_file = path::join(obj_type_dir, itype.proxy_name + ".cs"); Error err = _generate_cs_type(itype, output_file); if (err == ERR_SKIP) @@ -1046,32 +1031,32 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_solution_dir if (err != OK) return err; - compile_items.push_back(output_file); + r_compile_items.push_back(output_file); } - List<String> cs_icalls_content; - - cs_icalls_content.push_back("using System;\n" - "using System.Runtime.CompilerServices;\n" - "\n"); - cs_icalls_content.push_back("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); - cs_icalls_content.push_back(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS_EDITOR "\n" INDENT1 OPEN_BLOCK); - - cs_icalls_content.push_back(INDENT2 "internal static ulong godot_api_hash = "); - cs_icalls_content.push_back(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + ";\n"); - cs_icalls_content.push_back(INDENT2 "internal static uint bindings_version = "); - cs_icalls_content.push_back(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n"); - cs_icalls_content.push_back(INDENT2 "internal static uint cs_glue_version = "); - cs_icalls_content.push_back(String::num_uint64(CS_GLUE_VERSION) + ";\n"); - cs_icalls_content.push_back("\n"); - -#define ADD_INTERNAL_CALL(m_icall) \ - if (m_icall.editor_only) { \ - cs_icalls_content.push_back(INDENT2 "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \ - cs_icalls_content.push_back(INDENT2 "internal extern static "); \ - cs_icalls_content.push_back(m_icall.im_type_out + " "); \ - cs_icalls_content.push_back(m_icall.name + "("); \ - cs_icalls_content.push_back(m_icall.im_sig + ");\n"); \ + StringBuilder cs_icalls_content; + + cs_icalls_content.append("using System;\n" + "using System.Runtime.CompilerServices;\n" + "\n"); + cs_icalls_content.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); + cs_icalls_content.append(INDENT1 "internal static class " BINDINGS_CLASS_NATIVECALLS_EDITOR "\n" INDENT1 OPEN_BLOCK); + + cs_icalls_content.append(INDENT2 "internal static ulong godot_api_hash = "); + cs_icalls_content.append(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + ";\n"); + cs_icalls_content.append(INDENT2 "internal static uint bindings_version = "); + cs_icalls_content.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + ";\n"); + cs_icalls_content.append(INDENT2 "internal static uint cs_glue_version = "); + cs_icalls_content.append(String::num_uint64(CS_GLUE_VERSION) + ";\n"); + cs_icalls_content.append("\n"); + +#define ADD_INTERNAL_CALL(m_icall) \ + if (m_icall.editor_only) { \ + cs_icalls_content.append(INDENT2 "[MethodImpl(MethodImplOptions.InternalCall)]\n"); \ + cs_icalls_content.append(INDENT2 "internal extern static "); \ + cs_icalls_content.append(m_icall.im_type_out + " "); \ + cs_icalls_content.append(m_icall.name + "("); \ + cs_icalls_content.append(m_icall.im_sig + ");\n"); \ } for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next()) @@ -1081,73 +1066,72 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_solution_dir #undef ADD_INTERNAL_CALL - cs_icalls_content.push_back(INDENT1 CLOSE_BLOCK CLOSE_BLOCK); + cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK); - String internal_methods_file = path_join(core_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs"); + String internal_methods_file = path::join(core_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs"); Error err = _save_file(internal_methods_file, cs_icalls_content); if (err != OK) return err; - compile_items.push_back(internal_methods_file); - - String guid = CSharpProject::generate_editor_api_project(proj_dir, "../" CORE_API_ASSEMBLY_NAME "/" CORE_API_ASSEMBLY_NAME ".csproj", compile_items); - - DotNetSolution::ProjectInfo proj_info; - proj_info.guid = guid; - proj_info.relpath = String(EDITOR_API_ASSEMBLY_NAME).plus_file(EDITOR_API_ASSEMBLY_NAME ".csproj"); - proj_info.configs.push_back("Debug"); - proj_info.configs.push_back("Release"); - - r_solution.add_new_project(EDITOR_API_ASSEMBLY_NAME, proj_info); - - if (verbose_output) - OS::get_singleton()->print("The solution and C# project for the Editor API was generated successfully\n"); + r_compile_items.push_back(internal_methods_file); return OK; } -Error BindingsGenerator::generate_cs_api(const String &p_output_dir, bool p_verbose_output) { +Error BindingsGenerator::generate_cs_api(const String &p_output_dir) { + + ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED); + + String output_dir = path::abspath(path::realpath(p_output_dir)); DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); ERR_FAIL_COND_V(!da, ERR_CANT_CREATE); - if (!DirAccess::exists(p_output_dir)) { - Error err = da->make_dir_recursive(p_output_dir); + if (!DirAccess::exists(output_dir)) { + Error err = da->make_dir_recursive(output_dir); ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE); } - DotNetSolution solution(API_SOLUTION_NAME); + Error proj_err; - if (!solution.set_path(p_output_dir)) - return ERR_FILE_NOT_FOUND; + // Generate GodotSharp source files - Error proj_err; + String core_proj_dir = output_dir.plus_file(CORE_API_ASSEMBLY_NAME); + Vector<String> core_compile_items; - proj_err = generate_cs_core_project(p_output_dir, solution, p_verbose_output); + proj_err = generate_cs_core_project(core_proj_dir, core_compile_items); if (proj_err != OK) { - ERR_PRINT("Generation of the Core API C# project failed"); + ERR_PRINT("Generation of the Core API C# project failed."); return proj_err; } - proj_err = generate_cs_editor_project(p_output_dir, solution, p_verbose_output); + // Generate GodotSharpEditor source files + + String editor_proj_dir = output_dir.plus_file(EDITOR_API_ASSEMBLY_NAME); + Vector<String> editor_compile_items; + + proj_err = generate_cs_editor_project(editor_proj_dir, editor_compile_items); if (proj_err != OK) { - ERR_PRINT("Generation of the Editor API C# project failed"); + ERR_PRINT("Generation of the Editor API C# project failed."); return proj_err; } - Error sln_error = solution.save(); - if (sln_error != OK) { - ERR_PRINT("Failed to save API solution"); - return sln_error; + // Generate solution + + if (!CSharpProject::generate_api_solution(output_dir, + core_proj_dir, core_compile_items, editor_proj_dir, editor_compile_items)) { + return ERR_CANT_CREATE; } + _log("The solution for the Godot API was generated successfully\n"); + return OK; } // FIXME: There are some members that hide other inherited members. // - In the case of both members being the same kind, the new one must be declared -// explicitly as `new` to avoid the warning (and we must print a message about it). +// explicitly as 'new' to avoid the warning (and we must print a message about it). // - In the case of both members being of a different kind, then the new one must // be renamed to avoid the name collision (and we must print a warning about it). // - Csc warning e.g.: @@ -1169,65 +1153,64 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls; - if (verbose_output) - OS::get_singleton()->print("Generating %s.cs...\n", itype.proxy_name.utf8().get_data()); + _log("Generating %s.cs...\n", itype.proxy_name.utf8().get_data()); String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types - List<String> output; + StringBuilder output; - output.push_back("using System;\n"); // IntPtr - output.push_back("using System.Diagnostics;\n"); // DebuggerBrowsable + output.append("using System;\n"); // IntPtr + output.append("using System.Diagnostics;\n"); // DebuggerBrowsable - output.push_back("\n" - "#pragma warning disable CS1591 // Disable warning: " - "'Missing XML comment for publicly visible type or member'\n" - "#pragma warning disable CS1573 // Disable warning: " - "'Parameter has no matching param tag in the XML comment'\n"); + output.append("\n" + "#pragma warning disable CS1591 // Disable warning: " + "'Missing XML comment for publicly visible type or member'\n" + "#pragma warning disable CS1573 // Disable warning: " + "'Parameter has no matching param tag in the XML comment'\n"); - output.push_back("\nnamespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); + output.append("\nnamespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); const DocData::ClassDoc *class_doc = itype.class_doc; if (class_doc && class_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(class_doc->description), &itype); - Vector<String> summary_lines = xml_summary.split("\n"); + Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); if (summary_lines.size()) { - output.push_back(INDENT1 "/// <summary>\n"); + output.append(INDENT1 "/// <summary>\n"); for (int i = 0; i < summary_lines.size(); i++) { - output.push_back(INDENT1 "/// "); - output.push_back(summary_lines[i]); - output.push_back("\n"); + output.append(INDENT1 "/// "); + output.append(summary_lines[i]); + output.append("\n"); } - output.push_back(INDENT1 "/// </summary>\n"); + output.append(INDENT1 "/// </summary>\n"); } } - output.push_back(INDENT1 "public "); + output.append(INDENT1 "public "); if (itype.is_singleton) { - output.push_back("static partial class "); + output.append("static partial class "); } else { - output.push_back(itype.is_instantiable ? "partial class " : "abstract partial class "); + output.append(itype.is_instantiable ? "partial class " : "abstract partial class "); } - output.push_back(itype.proxy_name); + output.append(itype.proxy_name); if (itype.is_singleton) { - output.push_back("\n"); + output.append("\n"); } else if (is_derived_type) { if (obj_types.has(itype.base_name)) { - output.push_back(" : "); - output.push_back(obj_types[itype.base_name].proxy_name); - output.push_back("\n"); + output.append(" : "); + output.append(obj_types[itype.base_name].proxy_name); + output.append("\n"); } else { - ERR_PRINTS("Base type '" + itype.base_name.operator String() + "' does not exist, for class " + itype.name); + ERR_PRINTS("Base type '" + itype.base_name.operator String() + "' does not exist, for class '" + itype.name + "'."); return ERR_INVALID_DATA; } } - output.push_back(INDENT1 "{"); + output.append(INDENT1 "{"); if (class_doc) { @@ -1238,30 +1221,30 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str if (iconstant.const_doc && iconstant.const_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype); - Vector<String> summary_lines = xml_summary.split("\n"); + Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); if (summary_lines.size()) { - output.push_back(MEMBER_BEGIN "/// <summary>\n"); + output.append(MEMBER_BEGIN "/// <summary>\n"); for (int i = 0; i < summary_lines.size(); i++) { - output.push_back(INDENT2 "/// "); - output.push_back(summary_lines[i]); - output.push_back("\n"); + output.append(INDENT2 "/// "); + output.append(summary_lines[i]); + output.append("\n"); } - output.push_back(INDENT2 "/// </summary>"); + output.append(INDENT2 "/// </summary>"); } } - output.push_back(MEMBER_BEGIN "public const int "); - output.push_back(iconstant.proxy_name); - output.push_back(" = "); - output.push_back(itos(iconstant.value)); - output.push_back(";"); + output.append(MEMBER_BEGIN "public const int "); + output.append(iconstant.proxy_name); + output.append(" = "); + output.append(itos(iconstant.value)); + output.append(";"); } if (itype.constants.size()) - output.push_back("\n"); + output.append("\n"); // Add enums @@ -1270,38 +1253,38 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str ERR_FAIL_COND_V(ienum.constants.empty(), ERR_BUG); - output.push_back(MEMBER_BEGIN "public enum "); - output.push_back(ienum.cname.operator String()); - output.push_back(MEMBER_BEGIN OPEN_BLOCK); + output.append(MEMBER_BEGIN "public enum "); + output.append(ienum.cname.operator String()); + output.append(MEMBER_BEGIN OPEN_BLOCK); for (const List<ConstantInterface>::Element *F = ienum.constants.front(); F; F = F->next()) { const ConstantInterface &iconstant = F->get(); if (iconstant.const_doc && iconstant.const_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype); - Vector<String> summary_lines = xml_summary.split("\n"); + Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); if (summary_lines.size()) { - output.push_back(INDENT3 "/// <summary>\n"); + output.append(INDENT3 "/// <summary>\n"); for (int i = 0; i < summary_lines.size(); i++) { - output.push_back(INDENT3 "/// "); - output.push_back(summary_lines[i]); - output.push_back("\n"); + output.append(INDENT3 "/// "); + output.append(summary_lines[i]); + output.append("\n"); } - output.push_back(INDENT3 "/// </summary>\n"); + output.append(INDENT3 "/// </summary>\n"); } } - output.push_back(INDENT3); - output.push_back(iconstant.proxy_name); - output.push_back(" = "); - output.push_back(itos(iconstant.value)); - output.push_back(F != ienum.constants.back() ? ",\n" : "\n"); + output.append(INDENT3); + output.append(iconstant.proxy_name); + output.append(" = "); + output.append(itos(iconstant.value)); + output.append(F != ienum.constants.back() ? ",\n" : "\n"); } - output.push_back(INDENT2 CLOSE_BLOCK); + output.append(INDENT2 CLOSE_BLOCK); } // Add properties @@ -1309,11 +1292,9 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str for (const List<PropertyInterface>::Element *E = itype.properties.front(); E; E = E->next()) { const PropertyInterface &iprop = E->get(); Error prop_err = _generate_cs_property(itype, iprop, output); - if (prop_err != OK) { - ERR_EXPLAIN("Failed to generate property '" + iprop.cname.operator String() + - "' for class '" + itype.name + "'"); - ERR_FAIL_V(prop_err); - } + ERR_FAIL_COND_V_MSG(prop_err != OK, prop_err, + "Failed to generate property '" + iprop.cname.operator String() + + "' for class '" + itype.name + "'."); } } @@ -1322,63 +1303,62 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str if (itype.is_singleton) { // Add the type name and the singleton pointer as static fields - output.push_back(MEMBER_BEGIN "private static Godot.Object singleton;\n"); - output.push_back(MEMBER_BEGIN "public static Godot.Object Singleton\n" INDENT2 "{\n" INDENT3 - "get\n" INDENT3 "{\n" INDENT4 "if (singleton == null)\n" INDENT5 - "singleton = Engine.GetSingleton(" BINDINGS_NATIVE_NAME_FIELD ");\n" INDENT4 - "return singleton;\n" INDENT3 "}\n" INDENT2 "}\n"); - - output.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \""); - output.push_back(itype.name); - output.push_back("\";\n"); - - output.push_back(INDENT2 "internal static IntPtr " BINDINGS_PTR_FIELD " = "); - output.push_back(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); - output.push_back("." ICALL_PREFIX); - output.push_back(itype.name); - output.push_back(SINGLETON_ICALL_SUFFIX "();\n"); + output.append(MEMBER_BEGIN "private static Godot.Object singleton;\n"); + output.append(MEMBER_BEGIN "public static Godot.Object Singleton\n" INDENT2 "{\n" INDENT3 + "get\n" INDENT3 "{\n" INDENT4 "if (singleton == null)\n" INDENT5 + "singleton = Engine.GetSingleton(typeof("); + output.append(itype.proxy_name); + output.append(").Name);\n" INDENT4 "return singleton;\n" INDENT3 "}\n" INDENT2 "}\n"); + + output.append(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \""); + output.append(itype.name); + output.append("\";\n"); + + output.append(INDENT2 "internal static IntPtr " BINDINGS_PTR_FIELD " = "); + output.append(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); + output.append("." ICALL_PREFIX); + output.append(itype.name); + output.append(SINGLETON_ICALL_SUFFIX "();\n"); } else if (is_derived_type) { // Add member fields - output.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \""); - output.push_back(itype.name); - output.push_back("\";\n"); + output.append(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \""); + output.append(itype.name); + output.append("\";\n"); // Add default constructor if (itype.is_instantiable) { - output.push_back(MEMBER_BEGIN "public "); - output.push_back(itype.proxy_name); - output.push_back("() : this("); - output.push_back(itype.memory_own ? "true" : "false"); + output.append(MEMBER_BEGIN "public "); + output.append(itype.proxy_name); + output.append("() : this("); + output.append(itype.memory_own ? "true" : "false"); // The default constructor may also be called by the engine when instancing existing native objects // The engine will initialize the pointer field of the managed side before calling the constructor // This is why we only allocate a new native object from the constructor if the pointer field is not set - output.push_back(")\n" OPEN_BLOCK_L2 "if (" BINDINGS_PTR_FIELD " == IntPtr.Zero)\n" INDENT4 BINDINGS_PTR_FIELD " = "); - output.push_back(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); - output.push_back("." + ctor_method); - output.push_back("(this);\n" CLOSE_BLOCK_L2); + output.append(")\n" OPEN_BLOCK_L2 "if (" BINDINGS_PTR_FIELD " == IntPtr.Zero)\n" INDENT4 BINDINGS_PTR_FIELD " = "); + output.append(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); + output.append("." + ctor_method); + output.append("(this);\n" CLOSE_BLOCK_L2); } else { // Hide the constructor - output.push_back(MEMBER_BEGIN "internal "); - output.push_back(itype.proxy_name); - output.push_back("() {}\n"); + output.append(MEMBER_BEGIN "internal "); + output.append(itype.proxy_name); + output.append("() {}\n"); } // Add.. em.. trick constructor. Sort of. - output.push_back(MEMBER_BEGIN "internal "); - output.push_back(itype.proxy_name); - output.push_back("(bool " CS_FIELD_MEMORYOWN ") : base(" CS_FIELD_MEMORYOWN ") {}\n"); + output.append(MEMBER_BEGIN "internal "); + output.append(itype.proxy_name); + output.append("(bool " CS_FIELD_MEMORYOWN ") : base(" CS_FIELD_MEMORYOWN ") {}\n"); } int method_bind_count = 0; for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) { const MethodInterface &imethod = E->get(); Error method_err = _generate_cs_method(itype, imethod, method_bind_count, output); - if (method_err != OK) { - ERR_EXPLAIN("Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'"); - ERR_FAIL_V(method_err); - } + ERR_FAIL_COND_V_MSG(method_err != OK, method_err, + "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'."); } if (itype.is_singleton) { @@ -1395,17 +1375,17 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str custom_icalls.push_back(ctor_icall); } - output.push_back(INDENT1 CLOSE_BLOCK /* class */ + output.append(INDENT1 CLOSE_BLOCK /* class */ CLOSE_BLOCK /* namespace */); - output.push_back("\n" - "#pragma warning restore CS1591\n" - "#pragma warning restore CS1573\n"); + output.append("\n" + "#pragma warning restore CS1591\n" + "#pragma warning restore CS1573\n"); return _save_file(p_output_file, output); } -Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInterface &p_itype, const PropertyInterface &p_iprop, List<String> &p_output) { +Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInterface &p_itype, const PropertyInterface &p_iprop, StringBuilder &p_output) { const MethodInterface *setter = p_itype.find_method_by_name(p_iprop.setter); @@ -1452,72 +1432,94 @@ Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInte if (p_iprop.prop_doc && p_iprop.prop_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(p_iprop.prop_doc->description), &p_itype); - Vector<String> summary_lines = xml_summary.split("\n"); + Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); if (summary_lines.size()) { - p_output.push_back(MEMBER_BEGIN "/// <summary>\n"); + p_output.append(MEMBER_BEGIN "/// <summary>\n"); for (int i = 0; i < summary_lines.size(); i++) { - p_output.push_back(INDENT2 "/// "); - p_output.push_back(summary_lines[i]); - p_output.push_back("\n"); + p_output.append(INDENT2 "/// "); + p_output.append(summary_lines[i]); + p_output.append("\n"); } - p_output.push_back(INDENT2 "/// </summary>"); + p_output.append(INDENT2 "/// </summary>"); } } - p_output.push_back(MEMBER_BEGIN "public "); + p_output.append(MEMBER_BEGIN "public "); if (p_itype.is_singleton) - p_output.push_back("static "); + p_output.append("static "); - p_output.push_back(prop_itype->cs_type); - p_output.push_back(" "); - p_output.push_back(p_iprop.proxy_name); - p_output.push_back("\n" INDENT2 OPEN_BLOCK); + p_output.append(prop_itype->cs_type); + p_output.append(" "); + p_output.append(p_iprop.proxy_name); + p_output.append("\n" INDENT2 OPEN_BLOCK); if (getter) { - p_output.push_back(INDENT3 "get\n" OPEN_BLOCK_L3); - p_output.push_back("return "); - p_output.push_back(getter->proxy_name + "("); + p_output.append(INDENT3 "get\n" + + // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that) + "#pragma warning disable CS0618 // Disable warning about obsolete method\n" + + OPEN_BLOCK_L3); + + p_output.append("return "); + p_output.append(getter->proxy_name + "("); if (p_iprop.index != -1) { const ArgumentInterface &idx_arg = getter->arguments.front()->get(); if (idx_arg.type.cname != name_cache.type_int) { // Assume the index parameter is an enum const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type); CRASH_COND(idx_arg_type == NULL); - p_output.push_back("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index)); + p_output.append("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index)); } else { - p_output.push_back(itos(p_iprop.index)); + p_output.append(itos(p_iprop.index)); } } - p_output.push_back(");\n" CLOSE_BLOCK_L3); + p_output.append(");\n" + + CLOSE_BLOCK_L3 + + // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that) + "#pragma warning restore CS0618\n"); } if (setter) { - p_output.push_back(INDENT3 "set\n" OPEN_BLOCK_L3); - p_output.push_back(setter->proxy_name + "("); + p_output.append(INDENT3 "set\n" + + // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that) + "#pragma warning disable CS0618 // Disable warning about obsolete method\n" + + OPEN_BLOCK_L3); + + p_output.append(setter->proxy_name + "("); if (p_iprop.index != -1) { const ArgumentInterface &idx_arg = setter->arguments.front()->get(); if (idx_arg.type.cname != name_cache.type_int) { // Assume the index parameter is an enum const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type); CRASH_COND(idx_arg_type == NULL); - p_output.push_back("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index) + ", "); + p_output.append("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index) + ", "); } else { - p_output.push_back(itos(p_iprop.index) + ", "); + p_output.append(itos(p_iprop.index) + ", "); } } - p_output.push_back("value);\n" CLOSE_BLOCK_L3); + p_output.append("value);\n" + + CLOSE_BLOCK_L3 + + // TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that) + "#pragma warning restore CS0618\n"); } - p_output.push_back(CLOSE_BLOCK_L2); + p_output.append(CLOSE_BLOCK_L2); return OK; } -Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, List<String> &p_output) { +Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, StringBuilder &p_output) { const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type); @@ -1529,7 +1531,7 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf String icall_params = method_bind_field + ", "; icall_params += sformat(p_itype.cs_in, "this"); - List<String> default_args_doc; + StringBuilder default_args_doc; // Retrieve information from the arguments for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) { @@ -1598,7 +1600,7 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf // Apparently the name attribute must not include the @ String param_tag_name = iarg.name.begins_with("@") ? iarg.name.substr(1, iarg.name.length()) : iarg.name; - default_args_doc.push_back(INDENT2 "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is " + def_arg + "</param>\n"); + default_args_doc.append(INDENT2 "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is " + def_arg + "</param>\n"); } else { icall_params += arg_type->cs_in.empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name); } @@ -1607,61 +1609,67 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf // Generate method { if (!p_imethod.is_virtual && !p_imethod.requires_object_call) { - p_output.push_back(MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]" MEMBER_BEGIN "private static IntPtr "); - p_output.push_back(method_bind_field + " = Object." ICALL_GET_METHODBIND "(" BINDINGS_NATIVE_NAME_FIELD ", \""); - p_output.push_back(p_imethod.name); - p_output.push_back("\");\n"); + p_output.append(MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]" MEMBER_BEGIN "private static IntPtr "); + p_output.append(method_bind_field + " = Object." ICALL_GET_METHODBIND "(" BINDINGS_NATIVE_NAME_FIELD ", \""); + p_output.append(p_imethod.name); + p_output.append("\");\n"); } if (p_imethod.method_doc && p_imethod.method_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(p_imethod.method_doc->description), &p_itype); - Vector<String> summary_lines = xml_summary.split("\n"); + Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); - if (summary_lines.size() || default_args_doc.size()) { - p_output.push_back(MEMBER_BEGIN "/// <summary>\n"); + if (summary_lines.size() || default_args_doc.get_string_length()) { + p_output.append(MEMBER_BEGIN "/// <summary>\n"); for (int i = 0; i < summary_lines.size(); i++) { - p_output.push_back(INDENT2 "/// "); - p_output.push_back(summary_lines[i]); - p_output.push_back("\n"); + p_output.append(INDENT2 "/// "); + p_output.append(summary_lines[i]); + p_output.append("\n"); } - for (List<String>::Element *E = default_args_doc.front(); E; E = E->next()) { - p_output.push_back(E->get()); - } - - p_output.push_back(INDENT2 "/// </summary>"); + p_output.append(default_args_doc.as_string()); + p_output.append(INDENT2 "/// </summary>"); } } if (!p_imethod.is_internal) { - p_output.push_back(MEMBER_BEGIN "[GodotMethod(\""); - p_output.push_back(p_imethod.name); - p_output.push_back("\")]"); + p_output.append(MEMBER_BEGIN "[GodotMethod(\""); + p_output.append(p_imethod.name); + p_output.append("\")]"); + } + + if (p_imethod.is_deprecated) { + if (p_imethod.deprecation_message.empty()) + WARN_PRINTS("An empty deprecation message is discouraged. Method: '" + p_imethod.proxy_name + "'."); + + p_output.append(MEMBER_BEGIN "[Obsolete(\""); + p_output.append(p_imethod.deprecation_message); + p_output.append("\")]"); } - p_output.push_back(MEMBER_BEGIN); - p_output.push_back(p_imethod.is_internal ? "internal " : "public "); + p_output.append(MEMBER_BEGIN); + p_output.append(p_imethod.is_internal ? "internal " : "public "); if (p_itype.is_singleton) { - p_output.push_back("static "); + p_output.append("static "); } else if (p_imethod.is_virtual) { - p_output.push_back("virtual "); + p_output.append("virtual "); } - p_output.push_back(return_type->cs_type + " "); - p_output.push_back(p_imethod.proxy_name + "("); - p_output.push_back(arguments_sig + ")\n" OPEN_BLOCK_L2); + p_output.append(return_type->cs_type + " "); + p_output.append(p_imethod.proxy_name + "("); + p_output.append(arguments_sig + ")\n" OPEN_BLOCK_L2); if (p_imethod.is_virtual) { // Godot virtual method must be overridden, therefore we return a default value by default. if (return_type->cname == name_cache.type_void) { - p_output.push_back("return;\n" CLOSE_BLOCK_L2); + p_output.append("return;\n" CLOSE_BLOCK_L2); } else { - p_output.push_back("return default("); - p_output.push_back(return_type->cs_type); - p_output.push_back(");\n" CLOSE_BLOCK_L2); + p_output.append("return default("); + p_output.append(return_type->cs_type); + p_output.append(");\n" CLOSE_BLOCK_L2); } return OK; // Won't increment method bind count @@ -1670,16 +1678,16 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf if (p_imethod.requires_object_call) { // Fallback to Godot's object.Call(string, params) - p_output.push_back(CS_METHOD_CALL "(\""); - p_output.push_back(p_imethod.name); - p_output.push_back("\""); + p_output.append(CS_METHOD_CALL "(\""); + p_output.append(p_imethod.name); + p_output.append("\""); for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) { - p_output.push_back(", "); - p_output.push_back(F->get().name); + p_output.append(", "); + p_output.append(F->get().name); } - p_output.push_back(");\n" CLOSE_BLOCK_L2); + p_output.append(");\n" CLOSE_BLOCK_L2); return OK; // Won't increment method bind count } @@ -1690,40 +1698,41 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf const InternalCall *im_icall = match->value(); String im_call = im_icall->editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS; - im_call += "." + im_icall->name + "(" + icall_params + ")"; + im_call += "."; + im_call += im_icall->name; if (p_imethod.arguments.size()) - p_output.push_back(cs_in_statements); + p_output.append(cs_in_statements); if (return_type->cname == name_cache.type_void) { - p_output.push_back(im_call + ";\n"); + p_output.append(im_call + "(" + icall_params + ");\n"); } else if (return_type->cs_out.empty()) { - p_output.push_back("return " + im_call + ";\n"); + p_output.append("return " + im_call + "(" + icall_params + ");\n"); } else { - p_output.push_back(sformat(return_type->cs_out, im_call, return_type->cs_type, return_type->im_type_out)); - p_output.push_back("\n"); + p_output.append(sformat(return_type->cs_out, im_call, icall_params, return_type->cs_type, return_type->im_type_out)); + p_output.append("\n"); } - p_output.push_back(CLOSE_BLOCK_L2); + p_output.append(CLOSE_BLOCK_L2); } p_method_bind_count++; + return OK; } Error BindingsGenerator::generate_glue(const String &p_output_dir) { - verbose_output = true; + ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED); bool dir_exists = DirAccess::exists(p_output_dir); - ERR_EXPLAIN("The output directory does not exist."); - ERR_FAIL_COND_V(!dir_exists, ERR_FILE_BAD_PATH); + ERR_FAIL_COND_V_MSG(!dir_exists, ERR_FILE_BAD_PATH, "The output directory does not exist."); - List<String> output; + StringBuilder output; - output.push_back("/* THIS FILE IS GENERATED DO NOT EDIT */\n"); - output.push_back("#include \"" GLUE_HEADER_FILE "\"\n"); - output.push_back("\n#ifdef MONO_GLUE_ENABLED\n"); + output.append("/* THIS FILE IS GENERATED DO NOT EDIT */\n"); + output.append("#include \"" GLUE_HEADER_FILE "\"\n"); + output.append("\n#ifdef MONO_GLUE_ENABLED\n"); generated_icall_funcs.clear(); @@ -1750,10 +1759,8 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) { const MethodInterface &imethod = E->get(); Error method_err = _generate_glue_method(itype, imethod, output); - if (method_err != OK) { - ERR_EXPLAIN("Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'"); - ERR_FAIL_V(method_err); - } + ERR_FAIL_COND_V_MSG(method_err != OK, method_err, + "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'."); } if (itype.is_singleton) { @@ -1763,11 +1770,11 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (!find_icall_by_name(singleton_icall.name, custom_icalls)) custom_icalls.push_back(singleton_icall); - output.push_back("Object* "); - output.push_back(singleton_icall_name); - output.push_back("() " OPEN_BLOCK "\treturn Engine::get_singleton()->get_singleton_object(\""); - output.push_back(itype.proxy_name); - output.push_back("\");\n" CLOSE_BLOCK "\n"); + output.append("Object* "); + output.append(singleton_icall_name); + output.append("() " OPEN_BLOCK "\treturn Engine::get_singleton()->get_singleton_object(\""); + output.append(itype.proxy_name); + output.append("\");\n" CLOSE_BLOCK "\n"); } if (is_derived_type && itype.is_instantiable) { @@ -1776,43 +1783,46 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (!find_icall_by_name(ctor_icall.name, custom_icalls)) custom_icalls.push_back(ctor_icall); - output.push_back("Object* "); - output.push_back(ctor_method); - output.push_back("(MonoObject* obj) " OPEN_BLOCK - "\t" C_MACRO_OBJECT_CONSTRUCT "(instance, \""); - output.push_back(itype.name); - output.push_back("\");\n" - "\t" C_METHOD_TIE_MANAGED_TO_UNMANAGED "(obj, instance);\n" - "\treturn instance;\n" CLOSE_BLOCK "\n"); + output.append("Object* "); + output.append(ctor_method); + output.append("(MonoObject* obj) " OPEN_BLOCK + "\t" C_MACRO_OBJECT_CONSTRUCT "(instance, \""); + output.append(itype.name); + output.append("\");\n" + "\t" C_METHOD_TIE_MANAGED_TO_UNMANAGED "(obj, instance);\n" + "\treturn instance;\n" CLOSE_BLOCK "\n"); } } - output.push_back("namespace GodotSharpBindings\n" OPEN_BLOCK "\n"); + output.append("namespace GodotSharpBindings\n" OPEN_BLOCK "\n"); + + output.append("uint64_t get_core_api_hash() { return "); + output.append(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + "U; }\n"); - output.push_back("uint64_t get_core_api_hash() { return "); - output.push_back(String::num_uint64(GDMono::get_singleton()->get_api_core_hash()) + "U; }\n"); + output.append("#ifdef TOOLS_ENABLED\n" + "uint64_t get_editor_api_hash() { return "); + output.append(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + "U; }\n"); + output.append("#endif // TOOLS_ENABLED\n"); - output.push_back("#ifdef TOOLS_ENABLED\n" - "uint64_t get_editor_api_hash() { return "); - output.push_back(String::num_uint64(GDMono::get_singleton()->get_api_editor_hash()) + "U; }\n"); - output.push_back("#endif // TOOLS_ENABLED\n"); + output.append("uint32_t get_bindings_version() { return "); + output.append(String::num_uint64(BINDINGS_GENERATOR_VERSION) + "; }\n"); - output.push_back("uint32_t get_bindings_version() { return "); - output.push_back(String::num_uint64(BINDINGS_GENERATOR_VERSION) + "; }\n"); + output.append("uint32_t get_cs_glue_version() { return "); + output.append(String::num_uint64(CS_GLUE_VERSION) + "; }\n"); - output.push_back("\nvoid register_generated_icalls() " OPEN_BLOCK); - output.push_back("\tgodot_register_glue_header_icalls();\n"); + output.append("\nvoid register_generated_icalls() " OPEN_BLOCK); + output.append("\tgodot_register_glue_header_icalls();\n"); -#define ADD_INTERNAL_CALL_REGISTRATION(m_icall) \ - { \ - output.push_back("\tmono_add_internal_call("); \ - output.push_back("\"" BINDINGS_NAMESPACE "."); \ - output.push_back(m_icall.editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); \ - output.push_back("::"); \ - output.push_back(m_icall.name); \ - output.push_back("\", (void*)"); \ - output.push_back(m_icall.name); \ - output.push_back(");\n"); \ +#define ADD_INTERNAL_CALL_REGISTRATION(m_icall) \ + { \ + output.append("\tmono_add_internal_call("); \ + output.append("\"" BINDINGS_NAMESPACE "."); \ + output.append(m_icall.editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); \ + output.append("::"); \ + output.append(m_icall.name); \ + output.append("\", (void*)"); \ + output.append(m_icall.name); \ + output.append(");\n"); \ } bool tools_sequence = false; @@ -1821,11 +1831,11 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (tools_sequence) { if (!E->get().editor_only) { tools_sequence = false; - output.push_back("#endif\n"); + output.append("#endif\n"); } } else { if (E->get().editor_only) { - output.push_back("#ifdef TOOLS_ENABLED\n"); + output.append("#ifdef TOOLS_ENABLED\n"); tools_sequence = true; } } @@ -1835,23 +1845,23 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (tools_sequence) { tools_sequence = false; - output.push_back("#endif\n"); + output.append("#endif\n"); } - output.push_back("#ifdef TOOLS_ENABLED\n"); + output.append("#ifdef TOOLS_ENABLED\n"); for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next()) ADD_INTERNAL_CALL_REGISTRATION(E->get()); - output.push_back("#endif // TOOLS_ENABLED\n"); + output.append("#endif // TOOLS_ENABLED\n"); for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next()) { if (tools_sequence) { if (!E->get().editor_only) { tools_sequence = false; - output.push_back("#endif\n"); + output.append("#endif\n"); } } else { if (E->get().editor_only) { - output.push_back("#ifdef TOOLS_ENABLED\n"); + output.append("#ifdef TOOLS_ENABLED\n"); tools_sequence = true; } } @@ -1861,16 +1871,16 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (tools_sequence) { tools_sequence = false; - output.push_back("#endif\n"); + output.append("#endif\n"); } #undef ADD_INTERNAL_CALL_REGISTRATION - output.push_back(CLOSE_BLOCK "\n} // namespace GodotSharpBindings\n"); + output.append(CLOSE_BLOCK "\n} // namespace GodotSharpBindings\n"); - output.push_back("\n#endif // MONO_GLUE_ENABLED\n"); + output.append("\n#endif // MONO_GLUE_ENABLED\n"); - Error save_err = _save_file(path_join(p_output_dir, "mono_glue.gen.cpp"), output); + Error save_err = _save_file(path::join(p_output_dir, "mono_glue.gen.cpp"), output); if (save_err != OK) return save_err; @@ -1883,23 +1893,19 @@ uint32_t BindingsGenerator::get_version() { return BINDINGS_GENERATOR_VERSION; } -Error BindingsGenerator::_save_file(const String &p_path, const List<String> &p_content) { +Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p_content) { FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE); - ERR_EXPLAIN("Cannot open file: " + p_path); - ERR_FAIL_COND_V(!file, ERR_FILE_CANT_WRITE); - - for (const List<String>::Element *E = p_content.front(); E; E = E->next()) { - file->store_string(E->get()); - } + ERR_FAIL_COND_V_MSG(!file, ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'."); + file->store_string(p_content.as_string()); file->close(); return OK; } -Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, List<String> &p_output) { +Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, StringBuilder &p_output) { if (p_imethod.is_virtual) return OK; // Ignore @@ -1945,6 +1951,15 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte i++; } + if (return_type->ret_as_byref_arg) { + c_func_sig += ", "; + c_func_sig += return_type->c_type_in; + c_func_sig += " "; + c_func_sig += "arg_ret"; + + i++; + } + const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&p_imethod); ERR_FAIL_NULL_V(match, ERR_BUG); @@ -1955,17 +1970,15 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte generated_icall_funcs.push_back(im_icall); if (im_icall->editor_only) - p_output.push_back("#ifdef TOOLS_ENABLED\n"); + p_output.append("#ifdef TOOLS_ENABLED\n"); // Generate icall function - p_output.push_back(ret_void ? "void " : return_type->c_type_out + " "); - p_output.push_back(icall_method); - p_output.push_back("("); - p_output.push_back(c_func_sig); - p_output.push_back(") " OPEN_BLOCK); - - String fail_ret = ret_void ? "" : ", " + (return_type->c_type_out.ends_with("*") ? "NULL" : return_type->c_type_out + "()"); + p_output.append((ret_void || return_type->ret_as_byref_arg) ? "void " : return_type->c_type_out + " "); + p_output.append(icall_method); + p_output.append("("); + p_output.append(c_func_sig); + p_output.append(") " OPEN_BLOCK); if (!ret_void) { String ptrcall_return_type; @@ -1977,7 +1990,7 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte // the Variant alive until the method returns. Otherwise, if the returned Variant holds a RefPtr, // it could be deleted too early. This is the case with GDScript.new() which returns OBJECT. // Alternatively, we could just return Variant, but that would result in a worse API. - p_output.push_back("\tVariant " C_LOCAL_VARARG_RET ";\n"); + p_output.append("\tVariant " C_LOCAL_VARARG_RET ";\n"); } if (return_type->is_object_type) { @@ -1987,83 +2000,94 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte ptrcall_return_type = return_type->c_type; } - p_output.push_back("\t" + ptrcall_return_type); - p_output.push_back(" " C_LOCAL_RET); - p_output.push_back(initialization + ";\n"); - p_output.push_back("\tERR_FAIL_NULL_V(" CS_PARAM_INSTANCE); - p_output.push_back(fail_ret); - p_output.push_back(");\n"); + p_output.append("\t" + ptrcall_return_type); + p_output.append(" " C_LOCAL_RET); + p_output.append(initialization + ";\n"); + + String fail_ret = return_type->c_type_out.ends_with("*") && !return_type->ret_as_byref_arg ? "NULL" : return_type->c_type_out + "()"; + + if (return_type->ret_as_byref_arg) { + p_output.append("\tif (" CS_PARAM_INSTANCE " == NULL) { *arg_ret = "); + p_output.append(fail_ret); + p_output.append("; ERR_FAIL_MSG(\"Parameter ' arg_ret ' is null.\"); }\n"); + } else { + p_output.append("\tERR_FAIL_NULL_V(" CS_PARAM_INSTANCE ", "); + p_output.append(fail_ret); + p_output.append(");\n"); + } } else { - p_output.push_back("\tERR_FAIL_NULL(" CS_PARAM_INSTANCE ");\n"); + p_output.append("\tERR_FAIL_NULL(" CS_PARAM_INSTANCE ");\n"); } if (p_imethod.arguments.size()) { if (p_imethod.is_vararg) { - String err_fail_macro = ret_void ? "ERR_FAIL_COND" : "ERR_FAIL_COND_V"; String vararg_arg = "arg" + argc_str; String real_argc_str = itos(p_imethod.arguments.size() - 1); // Arguments count without vararg - p_output.push_back("\tint vararg_length = mono_array_length("); - p_output.push_back(vararg_arg); - p_output.push_back(");\n\tint total_length = "); - p_output.push_back(real_argc_str); - p_output.push_back(" + vararg_length;\n" - "\tArgumentsVector<Variant> varargs(vararg_length);\n" - "\tArgumentsVector<const Variant *> " C_LOCAL_PTRCALL_ARGS "(total_length);\n"); - p_output.push_back(c_in_statements); - p_output.push_back("\tfor (int i = 0; i < vararg_length; i++) " OPEN_BLOCK - "\t\tMonoObject* elem = mono_array_get("); - p_output.push_back(vararg_arg); - p_output.push_back(", MonoObject*, i);\n" - "\t\tvarargs.set(i, GDMonoMarshal::mono_object_to_variant(elem));\n" - "\t\t" C_LOCAL_PTRCALL_ARGS ".set("); - p_output.push_back(real_argc_str); - p_output.push_back(" + i, &varargs.get(i));\n\t" CLOSE_BLOCK); + p_output.append("\tint vararg_length = mono_array_length("); + p_output.append(vararg_arg); + p_output.append(");\n\tint total_length = "); + p_output.append(real_argc_str); + p_output.append(" + vararg_length;\n" + "\tArgumentsVector<Variant> varargs(vararg_length);\n" + "\tArgumentsVector<const Variant *> " C_LOCAL_PTRCALL_ARGS "(total_length);\n"); + p_output.append(c_in_statements); + p_output.append("\tfor (int i = 0; i < vararg_length; i++) " OPEN_BLOCK + "\t\tMonoObject* elem = mono_array_get("); + p_output.append(vararg_arg); + p_output.append(", MonoObject*, i);\n" + "\t\tvarargs.set(i, GDMonoMarshal::mono_object_to_variant(elem));\n" + "\t\t" C_LOCAL_PTRCALL_ARGS ".set("); + p_output.append(real_argc_str); + p_output.append(" + i, &varargs.get(i));\n\t" CLOSE_BLOCK); } else { - p_output.push_back(c_in_statements); - p_output.push_back("\tconst void* " C_LOCAL_PTRCALL_ARGS "["); - p_output.push_back(argc_str + "] = { "); - p_output.push_back(c_args_var_content + " };\n"); + p_output.append(c_in_statements); + p_output.append("\tconst void* " C_LOCAL_PTRCALL_ARGS "["); + p_output.append(argc_str + "] = { "); + p_output.append(c_args_var_content + " };\n"); } } if (p_imethod.is_vararg) { - p_output.push_back("\tVariant::CallError vcall_error;\n\t"); + p_output.append("\tVariant::CallError vcall_error;\n\t"); if (!ret_void) { // See the comment on the C_LOCAL_VARARG_RET declaration if (return_type->cname != name_cache.type_Variant) { - p_output.push_back(C_LOCAL_VARARG_RET " = "); + p_output.append(C_LOCAL_VARARG_RET " = "); } else { - p_output.push_back(C_LOCAL_RET " = "); + p_output.append(C_LOCAL_RET " = "); } } - p_output.push_back(CS_PARAM_METHODBIND "->call(" CS_PARAM_INSTANCE ", "); - p_output.push_back(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ".ptr()" : "NULL"); - p_output.push_back(", total_length, vcall_error);\n"); + p_output.append(CS_PARAM_METHODBIND "->call(" CS_PARAM_INSTANCE ", "); + p_output.append(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ".ptr()" : "NULL"); + p_output.append(", total_length, vcall_error);\n"); // See the comment on the C_LOCAL_VARARG_RET declaration if (return_type->cname != name_cache.type_Variant) { - p_output.push_back("\t" C_LOCAL_RET " = " C_LOCAL_VARARG_RET ";\n"); + p_output.append("\t" C_LOCAL_RET " = " C_LOCAL_VARARG_RET ";\n"); } } else { - p_output.push_back("\t" CS_PARAM_METHODBIND "->ptrcall(" CS_PARAM_INSTANCE ", "); - p_output.push_back(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ", " : "NULL, "); - p_output.push_back(!ret_void ? "&" C_LOCAL_RET ");\n" : "NULL);\n"); + p_output.append("\t" CS_PARAM_METHODBIND "->ptrcall(" CS_PARAM_INSTANCE ", "); + p_output.append(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ", " : "NULL, "); + p_output.append(!ret_void ? "&" C_LOCAL_RET ");\n" : "NULL);\n"); } if (!ret_void) { - if (return_type->c_out.empty()) - p_output.push_back("\treturn " C_LOCAL_RET ";\n"); - else - p_output.push_back(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name)); + if (return_type->c_out.empty()) { + p_output.append("\treturn " C_LOCAL_RET ";\n"); + } else if (return_type->ret_as_byref_arg) { + p_output.append(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name, "arg_ret")); + } else { + p_output.append(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name)); + } } - p_output.push_back(CLOSE_BLOCK "\n"); + p_output.append(CLOSE_BLOCK "\n"); if (im_icall->editor_only) - p_output.push_back("#endif // TOOLS_ENABLED\n"); + p_output.append("#endif // TOOLS_ENABLED\n"); } return OK; @@ -2103,7 +2127,7 @@ const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_placehol if (found) return found; - ERR_PRINTS(String() + "Type not found. Creating placeholder: " + p_typeref.cname.operator String()); + ERR_PRINTS(String() + "Type not found. Creating placeholder: '" + p_typeref.cname.operator String() + "'."); const Map<StringName, TypeInterface>::Element *match = placeholder_types.find(p_typeref.cname); @@ -2116,7 +2140,59 @@ const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_placehol return &placeholder_types.insert(placeholder.cname, placeholder)->get(); } -void BindingsGenerator::_populate_object_type_interfaces() { +StringName BindingsGenerator::_get_int_type_name_from_meta(GodotTypeInfo::Metadata p_meta) { + + switch (p_meta) { + case GodotTypeInfo::METADATA_INT_IS_INT8: + return "sbyte"; + break; + case GodotTypeInfo::METADATA_INT_IS_INT16: + return "short"; + break; + case GodotTypeInfo::METADATA_INT_IS_INT32: + return "int"; + break; + case GodotTypeInfo::METADATA_INT_IS_INT64: + return "long"; + break; + case GodotTypeInfo::METADATA_INT_IS_UINT8: + return "byte"; + break; + case GodotTypeInfo::METADATA_INT_IS_UINT16: + return "ushort"; + break; + case GodotTypeInfo::METADATA_INT_IS_UINT32: + return "uint"; + break; + case GodotTypeInfo::METADATA_INT_IS_UINT64: + return "ulong"; + break; + default: + // Assume INT32 + return "int"; + } +} + +StringName BindingsGenerator::_get_float_type_name_from_meta(GodotTypeInfo::Metadata p_meta) { + + switch (p_meta) { + case GodotTypeInfo::METADATA_REAL_IS_FLOAT: + return "float"; + break; + case GodotTypeInfo::METADATA_REAL_IS_DOUBLE: + return "double"; + break; + default: + // Assume real_t (float or double depending of REAL_T_IS_DOUBLE) +#ifdef REAL_T_IS_DOUBLE + return "double"; +#else + return "float"; +#endif + } +} + +bool BindingsGenerator::_populate_object_type_interfaces() { obj_types.clear(); @@ -2135,15 +2211,13 @@ void BindingsGenerator::_populate_object_type_interfaces() { } if (!ClassDB::is_class_exposed(type_cname)) { - if (verbose_output) - WARN_PRINTS("Ignoring type " + type_cname.operator String() + " because it's not exposed"); + _log("Ignoring type '%s' because it's not exposed\n", String(type_cname).utf8().get_data()); class_list.pop_front(); continue; } if (!ClassDB::is_class_enabled(type_cname)) { - if (verbose_output) - WARN_PRINTS("Ignoring type " + type_cname.operator String() + " because it's not enabled"); + _log("Ignoring type '%s' because it's not enabled\n", String(type_cname).utf8().get_data()); class_list.pop_front(); continue; } @@ -2154,7 +2228,7 @@ void BindingsGenerator::_populate_object_type_interfaces() { itype.base_name = ClassDB::get_parent_class(type_cname); itype.is_singleton = Engine::get_singleton()->has_singleton(itype.proxy_name); - itype.is_instantiable = ClassDB::can_instance(type_cname) && !itype.is_singleton; + itype.is_instantiable = class_info->creation_func && !itype.is_singleton; itype.is_reference = ClassDB::is_parent_class(type_cname, name_cache.type_Reference); itype.memory_own = itype.is_reference; @@ -2171,10 +2245,12 @@ void BindingsGenerator::_populate_object_type_interfaces() { itype.im_type_in = "IntPtr"; itype.im_type_out = itype.proxy_name; + // Populate properties + List<PropertyInfo> property_list; ClassDB::get_property_list(type_cname, &property_list, true); - // Populate properties + Map<StringName, StringName> accessor_methods; for (const List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) { const PropertyInfo &property = E->get(); @@ -2187,18 +2263,21 @@ void BindingsGenerator::_populate_object_type_interfaces() { iprop.setter = ClassDB::get_property_setter(type_cname, iprop.cname); iprop.getter = ClassDB::get_property_getter(type_cname, iprop.cname); + if (iprop.setter != StringName()) + accessor_methods[iprop.setter] = iprop.cname; + if (iprop.getter != StringName()) + accessor_methods[iprop.getter] = iprop.cname; + bool valid = false; iprop.index = ClassDB::get_property_index(type_cname, iprop.cname, &valid); - ERR_FAIL_COND(!valid); + ERR_FAIL_COND_V(!valid, false); iprop.proxy_name = escape_csharp_keyword(snake_to_pascal_case(iprop.cname)); - // Prevent property and enclosing type from sharing the same name + // Prevent the property and its enclosing type from sharing the same name if (iprop.proxy_name == itype.proxy_name) { - if (verbose_output) { - WARN_PRINTS("Name of property `" + iprop.proxy_name + "` is ambiguous with the name of its class `" + - itype.proxy_name + "`. Renaming property to `" + iprop.proxy_name + "_`"); - } + _log("Name of property '%s' is ambiguous with the name of its enclosing class '%s'. Renaming property to '%s_'\n", + iprop.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), iprop.proxy_name.utf8().get_data()); iprop.proxy_name += "_"; } @@ -2236,9 +2315,14 @@ void BindingsGenerator::_populate_object_type_interfaces() { if (method_info.name.empty()) continue; + String cname = method_info.name; + + if (blacklisted_methods.find(itype.cname) && blacklisted_methods[itype.cname].find(cname)) + continue; + MethodInterface imethod; imethod.name = method_info.name; - imethod.cname = imethod.name; + imethod.cname = cname; if (method_info.flags & METHOD_FLAG_VIRTUAL) imethod.is_virtual = true; @@ -2250,35 +2334,39 @@ void BindingsGenerator::_populate_object_type_interfaces() { imethod.is_vararg = m && m->is_vararg(); if (!m && !imethod.is_virtual) { - if (virtual_method_list.find(method_info)) { - // A virtual method without the virtual flag. This is a special case. - - // There is no method bind, so let's fallback to Godot's object.Call(string, params) - imethod.requires_object_call = true; - - // The method Object.free is registered as a virtual method, but without the virtual flag. - // This is because this method is not supposed to be overridden, but called. - // We assume the return type is void. - imethod.return_type.cname = name_cache.type_void; - - // Actually, more methods like this may be added in the future, - // which could actually will return something different. - // Let's put this to notify us if that ever happens. - if (itype.cname != name_cache.type_Object || imethod.name != "free") { - if (verbose_output) { - WARN_PRINTS("Notification: New unexpected virtual non-overridable method found.\n" - "We only expected Object.free, but found " + - itype.name + "." + imethod.name); - } - } - } else { - ERR_PRINTS("Missing MethodBind for non-virtual method: " + itype.name + "." + imethod.name); + ERR_FAIL_COND_V_MSG(!virtual_method_list.find(method_info), false, + "Missing MethodBind for non-virtual method: '" + itype.name + "." + imethod.name + "'."); + + // A virtual method without the virtual flag. This is a special case. + + // There is no method bind, so let's fallback to Godot's object.Call(string, params) + imethod.requires_object_call = true; + + // The method Object.free is registered as a virtual method, but without the virtual flag. + // This is because this method is not supposed to be overridden, but called. + // We assume the return type is void. + imethod.return_type.cname = name_cache.type_void; + + // Actually, more methods like this may be added in the future, + // which could actually will return something different. + // Let's put this to notify us if that ever happens. + if (itype.cname != name_cache.type_Object || imethod.name != "free") { + WARN_PRINTS("Notification: New unexpected virtual non-overridable method found." + " We only expected Object.free, but found '" + + itype.name + "." + imethod.name + "'."); } } else if (return_info.type == Variant::INT && return_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) { imethod.return_type.cname = return_info.class_name; imethod.return_type.is_enum = true; } else if (return_info.class_name != StringName()) { imethod.return_type.cname = return_info.class_name; + if (!imethod.is_virtual && ClassDB::is_parent_class(return_info.class_name, name_cache.type_Reference) && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE) { + /* clang-format off */ + ERR_PRINTS("Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." + " Are you returning a reference type by pointer? Method: '" + itype.name + "." + imethod.name + "'."); + /* clang-format on */ + ERR_FAIL_V(false); + } } else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) { imethod.return_type.cname = return_info.hint_string; } else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) { @@ -2286,14 +2374,22 @@ void BindingsGenerator::_populate_object_type_interfaces() { } else if (return_info.type == Variant::NIL) { imethod.return_type.cname = name_cache.type_void; } else { - imethod.return_type.cname = Variant::get_type_name(return_info.type); + if (return_info.type == Variant::INT) { + imethod.return_type.cname = _get_int_type_name_from_meta(m ? m->get_argument_meta(-1) : GodotTypeInfo::METADATA_NONE); + } else if (return_info.type == Variant::REAL) { + imethod.return_type.cname = _get_float_type_name_from_meta(m ? m->get_argument_meta(-1) : GodotTypeInfo::METADATA_NONE); + } else { + imethod.return_type.cname = Variant::get_type_name(return_info.type); + } } for (int i = 0; i < argc; i++) { PropertyInfo arginfo = method_info.arguments[i]; + String orig_arg_name = arginfo.name; + ArgumentInterface iarg; - iarg.name = arginfo.name; + iarg.name = orig_arg_name; if (arginfo.type == Variant::INT && arginfo.usage & PROPERTY_USAGE_CLASS_IS_ENUM) { iarg.type.cname = arginfo.class_name; @@ -2305,13 +2401,21 @@ void BindingsGenerator::_populate_object_type_interfaces() { } else if (arginfo.type == Variant::NIL) { iarg.type.cname = name_cache.type_Variant; } else { - iarg.type.cname = Variant::get_type_name(arginfo.type); + if (arginfo.type == Variant::INT) { + iarg.type.cname = _get_int_type_name_from_meta(m ? m->get_argument_meta(i) : GodotTypeInfo::METADATA_NONE); + } else if (arginfo.type == Variant::REAL) { + iarg.type.cname = _get_float_type_name_from_meta(m ? m->get_argument_meta(i) : GodotTypeInfo::METADATA_NONE); + } else { + iarg.type.cname = Variant::get_type_name(arginfo.type); + } } iarg.name = escape_csharp_keyword(snake_to_camel_case(iarg.name)); if (m && m->has_default_argument(i)) { - _default_argument_from_variant(m->get_default_argument(i), iarg); + bool defval_ok = _arg_default_value_from_variant(m->get_default_argument(i), iarg); + ERR_FAIL_COND_V_MSG(!defval_ok, false, + "Cannot determine default value for argument '" + orig_arg_name + "' of method '" + itype.name + "." + imethod.name + "'."); } imethod.add_argument(iarg); @@ -2326,16 +2430,24 @@ void BindingsGenerator::_populate_object_type_interfaces() { imethod.proxy_name = escape_csharp_keyword(snake_to_pascal_case(imethod.name)); - // Prevent naming the property and its enclosing type from sharing the same name + // Prevent the method and its enclosing type from sharing the same name if (imethod.proxy_name == itype.proxy_name) { - if (verbose_output) { - WARN_PRINTS("Name of method `" + imethod.proxy_name + "` is ambiguous with the name of its class `" + - itype.proxy_name + "`. Renaming method to `" + imethod.proxy_name + "_`"); - } + _log("Name of method '%s' is ambiguous with the name of its enclosing class '%s'. Renaming method to '%s_'\n", + imethod.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), imethod.proxy_name.utf8().get_data()); imethod.proxy_name += "_"; } + Map<StringName, StringName>::Element *accessor = accessor_methods.find(imethod.cname); + if (accessor) { + const PropertyInterface *accessor_property = itype.find_property_by_name(accessor->value()); + + // We only deprecate an accessor method if it's in the same class as the property. It's easier this way, but also + // we don't know if an accessor method in a different class could have other purposes, so better leave those untouched. + imethod.is_deprecated = true; + imethod.deprecation_message = imethod.proxy_name + " is deprecated. Use the " + accessor_property->proxy_name + " property instead."; + } + if (itype.class_doc) { for (int i = 0; i < itype.class_doc->methods.size(); i++) { if (itype.class_doc->methods[i].name == imethod.name) { @@ -2362,8 +2474,8 @@ void BindingsGenerator::_populate_object_type_interfaces() { // Populate enums and constants - List<String> constant_list; - ClassDB::get_integer_constant_list(type_cname, &constant_list, true); + List<String> constants; + ClassDB::get_integer_constant_list(type_cname, &constants, true); const HashMap<StringName, List<StringName> > &enum_map = class_info->enum_map; const StringName *k = NULL; @@ -2378,13 +2490,13 @@ void BindingsGenerator::_populate_object_type_interfaces() { enum_proxy_cname = StringName(enum_proxy_name); } EnumInterface ienum(enum_proxy_cname); - const List<StringName> &constants = enum_map.get(*k); - for (const List<StringName>::Element *E = constants.front(); E; E = E->next()) { + const List<StringName> &enum_constants = enum_map.get(*k); + for (const List<StringName>::Element *E = enum_constants.front(); E; E = E->next()) { const StringName &constant_cname = E->get(); String constant_name = constant_cname.operator String(); int *value = class_info->constant_map.getptr(constant_cname); - ERR_FAIL_NULL(value); - constant_list.erase(constant_name); + ERR_FAIL_NULL_V(value, false); + constants.erase(constant_name); ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value); @@ -2416,10 +2528,10 @@ void BindingsGenerator::_populate_object_type_interfaces() { enum_types.insert(enum_itype.cname, enum_itype); } - for (const List<String>::Element *E = constant_list.front(); E; E = E->next()) { + for (const List<String>::Element *E = constants.front(); E; E = E->next()) { const String &constant_name = E->get(); int *value = class_info->constant_map.getptr(StringName(E->get())); - ERR_FAIL_NULL(value); + ERR_FAIL_NULL_V(value, false); ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value); @@ -2440,21 +2552,18 @@ void BindingsGenerator::_populate_object_type_interfaces() { class_list.pop_front(); } + + return true; } -void BindingsGenerator::_default_argument_from_variant(const Variant &p_val, ArgumentInterface &r_iarg) { +bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, ArgumentInterface &r_iarg) { r_iarg.default_argument = p_val; 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: @@ -2493,16 +2602,24 @@ void BindingsGenerator::_default_argument_from_variant(const Variant &p_val, Arg r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; break; case Variant::OBJECT: - if (p_val.is_zero()) { - r_iarg.default_argument = "null"; - break; - } - FALLTHROUGH; + ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false, + "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value."); + + r_iarg.default_argument = "null"; + break; case Variant::DICTIONARY: - case Variant::_RID: r_iarg.default_argument = "new %s()"; r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF; break; + case Variant::_RID: + ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_RID, false, + "Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_RID) + "'."); + + ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false, + "Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value."); + + r_iarg.default_argument = "null"; + break; case Variant::ARRAY: case Variant::POOL_BYTE_ARRAY: case Variant::POOL_INT_ARRAY: @@ -2520,11 +2637,14 @@ void BindingsGenerator::_default_argument_from_variant(const Variant &p_val, Arg r_iarg.default_argument = Variant::get_type_name(p_val.get_type()) + ".Identity"; r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; break; - default: {} + default: { + } } if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "null") r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF; + + return true; } void BindingsGenerator::_populate_builtin_type_interfaces() { @@ -2533,36 +2653,37 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { TypeInterface itype; -#define INSERT_STRUCT_TYPE(m_type, m_type_in) \ +#define INSERT_STRUCT_TYPE(m_type) \ { \ itype = TypeInterface::create_value_type(String(#m_type)); \ itype.c_in = "\t%0 %1_in = MARSHALLED_IN(" #m_type ", %1);\n"; \ - itype.c_out = "\treturn MARSHALLED_OUT(" #m_type ", %1);\n"; \ + itype.c_out = "\t*%3 = MARSHALLED_OUT(" #m_type ", %1);\n"; \ itype.c_arg_in = "&%s_in"; \ itype.c_type_in = "GDMonoMarshal::M_" #m_type "*"; \ itype.c_type_out = "GDMonoMarshal::M_" #m_type; \ itype.cs_in = "ref %s"; \ - itype.cs_out = "return (%1)%0;"; \ - itype.im_type_out = itype.cs_type; \ + /* in cs_out, im_type_out (%3) includes the 'out ' part */ \ + itype.cs_out = "%0(%1, %3 argRet); return (%2)argRet;"; \ + itype.im_type_out = "out " + itype.cs_type; \ + itype.ret_as_byref_arg = true; \ builtin_types.insert(itype.cname, itype); \ } - INSERT_STRUCT_TYPE(Vector2, "real_t*") - INSERT_STRUCT_TYPE(Rect2, "real_t*") - INSERT_STRUCT_TYPE(Transform2D, "real_t*") - INSERT_STRUCT_TYPE(Vector3, "real_t*") - INSERT_STRUCT_TYPE(Basis, "real_t*") - INSERT_STRUCT_TYPE(Quat, "real_t*") - INSERT_STRUCT_TYPE(Transform, "real_t*") - INSERT_STRUCT_TYPE(AABB, "real_t*") - INSERT_STRUCT_TYPE(Color, "real_t*") - INSERT_STRUCT_TYPE(Plane, "real_t*") + INSERT_STRUCT_TYPE(Vector2) + INSERT_STRUCT_TYPE(Rect2) + INSERT_STRUCT_TYPE(Transform2D) + INSERT_STRUCT_TYPE(Vector3) + INSERT_STRUCT_TYPE(Basis) + INSERT_STRUCT_TYPE(Quat) + INSERT_STRUCT_TYPE(Transform) + INSERT_STRUCT_TYPE(AABB) + INSERT_STRUCT_TYPE(Color) + INSERT_STRUCT_TYPE(Plane) #undef INSERT_STRUCT_TYPE // bool itype = TypeInterface::create_value_type(String("bool")); - { // MonoBoolean <---> bool itype.c_in = "\t%0 %1_in = (%0)%1;\n"; @@ -2576,45 +2697,118 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { itype.im_type_out = itype.name; builtin_types.insert(itype.cname, itype); - // int - // C interface is the same as that of enums. Remember to apply any - // changes done here to TypeInterface::postsetup_enum_type as well - itype = TypeInterface::create_value_type(String("int")); - itype.c_arg_in = "&%s_in"; + // Integer types { - // The expected types for parameters and return value in ptrcall are 'int64_t' or 'uint64_t'. - itype.c_in = "\t%0 %1_in = (%0)%1;\n"; - itype.c_out = "\treturn (%0)%1;\n"; - itype.c_type = "int64_t"; + // C interface for 'uint32_t' is the same as that of enums. Remember to apply + // any of the changes done here to 'TypeInterface::postsetup_enum_type' as well. +#define INSERT_INT_TYPE(m_name, m_c_type_in_out, m_c_type) \ + { \ + itype = TypeInterface::create_value_type(String(m_name)); \ + { \ + itype.c_in = "\t%0 %1_in = (%0)%1;\n"; \ + itype.c_out = "\treturn (%0)%1;\n"; \ + itype.c_type = #m_c_type; \ + itype.c_arg_in = "&%s_in"; \ + } \ + itype.c_type_in = #m_c_type_in_out; \ + itype.c_type_out = itype.c_type_in; \ + itype.im_type_in = itype.name; \ + itype.im_type_out = itype.name; \ + builtin_types.insert(itype.cname, itype); \ } - itype.c_type_in = "int32_t"; - itype.c_type_out = itype.c_type_in; - itype.im_type_in = itype.name; - itype.im_type_out = itype.name; - builtin_types.insert(itype.cname, itype); - // real_t - itype = TypeInterface(); - itype.name = "float"; // The name is always "float" in Variant, even with REAL_T_IS_DOUBLE. - itype.cname = itype.name; -#ifdef REAL_T_IS_DOUBLE - itype.proxy_name = "double"; -#else - itype.proxy_name = "float"; -#endif + // The expected type for all integers in ptrcall is 'int64_t', so that's what we use for 'c_type' + + INSERT_INT_TYPE("sbyte", int8_t, int64_t); + INSERT_INT_TYPE("short", int16_t, int64_t); + INSERT_INT_TYPE("int", int32_t, int64_t); + INSERT_INT_TYPE("byte", uint8_t, int64_t); + INSERT_INT_TYPE("ushort", uint16_t, int64_t); + INSERT_INT_TYPE("uint", uint32_t, int64_t); + + itype = TypeInterface::create_value_type(String("long")); + { + itype.c_out = "\treturn (%0)%1;\n"; + itype.c_in = "\t%0 %1_in = (%0)*%1;\n"; + itype.c_out = "\t*%3 = (%0)%1;\n"; + itype.c_type = "int64_t"; + itype.c_arg_in = "&%s_in"; + } + itype.c_type_in = "int64_t*"; + itype.c_type_out = "int64_t"; + itype.im_type_in = "ref " + itype.name; + itype.im_type_out = "out " + itype.name; + itype.cs_in = "ref %0"; + /* in cs_out, im_type_out (%3) includes the 'out ' part */ + itype.cs_out = "%0(%1, %3 argRet); return (%2)argRet;"; + itype.ret_as_byref_arg = true; + builtin_types.insert(itype.cname, itype); + + itype = TypeInterface::create_value_type(String("ulong")); + { + itype.c_in = "\t%0 %1_in = (%0)*%1;\n"; + itype.c_out = "\t*%3 = (%0)%1;\n"; + itype.c_type = "int64_t"; + itype.c_arg_in = "&%s_in"; + } + itype.c_type_in = "uint64_t*"; + itype.c_type_out = "uint64_t"; + itype.im_type_in = "ref " + itype.name; + itype.im_type_out = "out " + itype.name; + itype.cs_in = "ref %0"; + /* in cs_out, im_type_out (%3) includes the 'out ' part */ + itype.cs_out = "%0(%1, %3 argRet); return (%2)argRet;"; + itype.ret_as_byref_arg = true; + builtin_types.insert(itype.cname, itype); + } + + // Floating point types { - // The expected type for parameters and return value in ptrcall is 'double'. - itype.c_in = "\t%0 %1_in = (%0)%1;\n"; - itype.c_out = "\treturn (%0)%1;\n"; - itype.c_type = "double"; - itype.c_type_in = "real_t"; - itype.c_type_out = "real_t"; - itype.c_arg_in = "&%s_in"; + // float + itype = TypeInterface(); + itype.name = "float"; + itype.cname = itype.name; + itype.proxy_name = "float"; + { + // The expected type for 'float' in ptrcall is 'double' + itype.c_in = "\t%0 %1_in = (%0)*%1;\n"; + itype.c_out = "\t*%3 = (%0)%1;\n"; + itype.c_type = "double"; + itype.c_type_in = "float*"; + itype.c_type_out = "float"; + itype.c_arg_in = "&%s_in"; + } + itype.cs_type = itype.proxy_name; + itype.im_type_in = "ref " + itype.proxy_name; + itype.im_type_out = "out " + itype.proxy_name; + itype.cs_in = "ref %0"; + /* in cs_out, im_type_out (%3) includes the 'out ' part */ + itype.cs_out = "%0(%1, %3 argRet); return (%2)argRet;"; + itype.ret_as_byref_arg = true; + builtin_types.insert(itype.cname, itype); + + // double + itype = TypeInterface(); + itype.name = "double"; + itype.cname = itype.name; + itype.proxy_name = "double"; + { + itype.c_in = "\t%0 %1_in = (%0)*%1;\n"; + itype.c_out = "\t*%3 = (%0)%1;\n"; + itype.c_type = "double"; + itype.c_type_in = "double*"; + itype.c_type_out = "double"; + itype.c_arg_in = "&%s_in"; + } + itype.cs_type = itype.proxy_name; + itype.im_type_in = "ref " + itype.proxy_name; + itype.im_type_out = "out " + itype.proxy_name; + itype.cs_in = "ref %0"; + /* in cs_out, im_type_out (%3) includes the 'out ' part */ + itype.cs_out = "%0(%1, %3 argRet); return (%2)argRet;"; + itype.ret_as_byref_arg = true; + builtin_types.insert(itype.cname, itype); } - itype.cs_type = itype.proxy_name; - itype.im_type_in = itype.proxy_name; - itype.im_type_out = itype.proxy_name; - builtin_types.insert(itype.cname, itype); // String itype = TypeInterface(); @@ -2643,7 +2837,7 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { itype.c_type_out = itype.c_type + "*"; itype.cs_type = itype.proxy_name; itype.cs_in = "NodePath." CS_SMETHOD_GETINSTANCE "(%0)"; - itype.cs_out = "return new %1(%0);"; + itype.cs_out = "return new %2(%0(%1));"; itype.im_type_in = "IntPtr"; itype.im_type_out = "IntPtr"; builtin_types.insert(itype.cname, itype); @@ -2659,7 +2853,7 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { itype.c_type_out = itype.c_type + "*"; itype.cs_type = itype.proxy_name; itype.cs_in = "RID." CS_SMETHOD_GETINSTANCE "(%0)"; - itype.cs_out = "return new %1(%0);"; + itype.cs_out = "return new %2(%0(%1));"; itype.im_type_in = "IntPtr"; itype.im_type_out = "IntPtr"; builtin_types.insert(itype.cname, itype); @@ -2741,7 +2935,7 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { itype.c_type_out = itype.c_type + "*"; itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name; itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()"; - itype.cs_out = "return new " + itype.cs_type + "(%0);"; + itype.cs_out = "return new " + itype.cs_type + "(%0(%1));"; itype.im_type_in = "IntPtr"; itype.im_type_out = "IntPtr"; builtin_types.insert(itype.cname, itype); @@ -2757,7 +2951,7 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { itype.c_type_out = itype.c_type + "*"; itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name; itype.cs_in = "%0." CS_SMETHOD_GETINSTANCE "()"; - itype.cs_out = "return new " + itype.cs_type + "(%0);"; + itype.cs_out = "return new " + itype.cs_type + "(%0(%1));"; itype.im_type_in = "IntPtr"; itype.im_type_out = "IntPtr"; builtin_types.insert(itype.cname, itype); @@ -2783,8 +2977,7 @@ void BindingsGenerator::_populate_global_constants() { if (global_constants_count > 0) { Map<String, DocData::ClassDoc>::Element *match = EditorHelp::get_doc_data()->class_list.find("@GlobalScope"); - ERR_EXPLAIN("Could not find `@GlobalScope` in DocData"); - CRASH_COND(!match); + CRASH_COND_MSG(!match, "Could not find '@GlobalScope' in DocData."); const DocData::ClassDoc &global_scope_doc = match->value(); @@ -2838,7 +3031,7 @@ void BindingsGenerator::_populate_global_constants() { // HARDCODED: The Error enum have the prefix 'ERR_' for everything except 'OK' and 'FAILED'. if (ienum.cname == name_cache.enum_Error) { if (prefix_length > 0) { // Just in case it ever changes - ERR_PRINTS("Prefix for enum 'Error' is not empty"); + ERR_PRINTS("Prefix for enum '" _STR(Error) "' is not empty."); } prefix_length = 1; // 'ERR_' @@ -2864,13 +3057,37 @@ void BindingsGenerator::_populate_global_constants() { } } -void BindingsGenerator::initialize() { +void BindingsGenerator::_initialize_blacklisted_methods() { + + blacklisted_methods["Object"].push_back("to_string"); // there is already ToString + blacklisted_methods["Object"].push_back("_to_string"); // override ToString instead + blacklisted_methods["Object"].push_back("_init"); // never called in C# (TODO: implement it) +} + +void BindingsGenerator::_log(const char *p_format, ...) { + + if (log_print_enabled) { + va_list list; + + va_start(list, p_format); + OS::get_singleton()->print("%s", str_format(p_format, list).utf8().get_data()); + va_end(list); + } +} + +void BindingsGenerator::_initialize() { + + initialized = false; EditorHelp::generate_doc(); enum_types.clear(); - _populate_object_type_interfaces(); + _initialize_blacklisted_methods(); + + bool obj_type_ok = _populate_object_type_interfaces(); + ERR_FAIL_COND_MSG(!obj_type_ok, "Failed to generate object type interfaces"); + _populate_builtin_type_interfaces(); _populate_global_constants(); @@ -2882,46 +3099,56 @@ void BindingsGenerator::initialize() { for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) _generate_method_icalls(E.get()); + + initialized = true; } void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) { const int NUM_OPTIONS = 2; - int options_left = NUM_OPTIONS; + String generate_all_glue_option = "--generate-mono-glue"; + String generate_cs_glue_option = "--generate-mono-cs-glue"; + String generate_cpp_glue_option = "--generate-mono-cpp-glue"; - String mono_glue_option = "--generate-mono-glue"; - String cs_api_option = "--generate-cs-api"; + String glue_dir_path; + String cs_dir_path; + String cpp_dir_path; - verbose_output = true; + int options_left = NUM_OPTIONS; const List<String>::Element *elem = p_cmdline_args.front(); while (elem && options_left) { - - if (elem->get() == mono_glue_option) { - + if (elem->get() == generate_all_glue_option) { const List<String>::Element *path_elem = elem->next(); if (path_elem) { - if (get_singleton()->generate_glue(path_elem->get()) != OK) - ERR_PRINTS(mono_glue_option + ": Failed to generate mono glue"); + glue_dir_path = path_elem->get(); elem = elem->next(); } else { - ERR_PRINTS(mono_glue_option + ": No output directory specified"); + ERR_PRINTS(generate_all_glue_option + ": No output directory specified (expected path to '{GODOT_ROOT}/modules/mono/glue')."); } --options_left; + } else if (elem->get() == generate_cs_glue_option) { + const List<String>::Element *path_elem = elem->next(); - } else if (elem->get() == cs_api_option) { + if (path_elem) { + cs_dir_path = path_elem->get(); + elem = elem->next(); + } else { + ERR_PRINTS(generate_cs_glue_option + ": No output directory specified."); + } + --options_left; + } else if (elem->get() == generate_cpp_glue_option) { const List<String>::Element *path_elem = elem->next(); if (path_elem) { - if (get_singleton()->generate_cs_api(path_elem->get()) != OK) - ERR_PRINTS(cs_api_option + ": Failed to generate the C# API"); + cpp_dir_path = path_elem->get(); elem = elem->next(); } else { - ERR_PRINTS(cs_api_option + ": No output directory specified"); + ERR_PRINTS(generate_cpp_glue_option + ": No output directory specified."); } --options_left; @@ -2930,10 +3157,36 @@ void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) elem = elem->next(); } - verbose_output = false; + if (glue_dir_path.length() || cs_dir_path.length() || cpp_dir_path.length()) { + BindingsGenerator bindings_generator; + bindings_generator.set_log_print_enabled(true); + + if (!bindings_generator.initialized) { + ERR_PRINTS("Failed to initialize the bindings generator"); + ::exit(0); + } + + if (glue_dir_path.length()) { + if (bindings_generator.generate_glue(glue_dir_path) != OK) + ERR_PRINTS(generate_all_glue_option + ": Failed to generate the C++ glue."); + + if (bindings_generator.generate_cs_api(glue_dir_path.plus_file("Managed/Generated")) != OK) + ERR_PRINTS(generate_all_glue_option + ": Failed to generate the C# API."); + } + + if (cs_dir_path.length()) { + if (bindings_generator.generate_cs_api(cs_dir_path) != OK) + ERR_PRINTS(generate_cs_glue_option + ": Failed to generate the C# API."); + } - if (options_left != NUM_OPTIONS) + if (cpp_dir_path.length()) { + if (bindings_generator.generate_glue(cpp_dir_path) != OK) + ERR_PRINTS(generate_cpp_glue_option + ": Failed to generate the C++ glue."); + } + + // Exit once done ::exit(0); + } } #endif diff --git a/modules/mono/editor/bindings_generator.h b/modules/mono/editor/bindings_generator.h index 42071f9c0d..07918a2d03 100644 --- a/modules/mono/editor/bindings_generator.h +++ b/modules/mono/editor/bindings_generator.h @@ -32,11 +32,11 @@ #define BINDINGS_GENERATOR_H #include "core/class_db.h" -#include "dotnet_solution.h" +#include "core/string_builder.h" #include "editor/doc/doc_data.h" #include "editor/editor_help.h" -#ifdef DEBUG_METHODS_ENABLED +#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) #include "core/ustring.h" @@ -147,7 +147,7 @@ class BindingsGenerator { bool requires_object_call; /** - * Determines if the method visibility is `internal` (visible only to files in the same assembly). + * Determines if the method visibility is 'internal' (visible only to files in the same assembly). * Currently, we only use this for methods that are not meant to be exposed, * but are required by properties as getters or setters. * Methods that are not meant to be exposed are those that begin with underscore and are not virtual. @@ -158,17 +158,20 @@ class BindingsGenerator { const DocData::MethodDoc *method_doc; + bool is_deprecated; + String deprecation_message; + void add_argument(const ArgumentInterface &argument) { arguments.push_back(argument); } MethodInterface() { - return_type.cname = BindingsGenerator::get_singleton()->name_cache.type_void; is_vararg = false; is_virtual = false; requires_object_call = false; is_internal = false; method_doc = NULL; + is_deprecated = false; } }; @@ -211,6 +214,14 @@ class BindingsGenerator { */ bool memory_own; + /** + * This must be set to true for any struct bigger than 32-bits. Those cannot be passed/returned by value + * with internal calls, so we must use pointers instead. Returns must be replace with out parameters. + * In this case, [c_out] and [cs_out] must have a different format, explained below. + * The Mono IL interpreter icall trampolines don't support passing structs bigger than 32-bits by value (at least not on WASM). + */ + bool ret_as_byref_arg; + // !! The comments of the following fields make reference to other fields via square brackets, e.g.: [field_name] // !! When renaming those fields, make sure to rename their references in the comments @@ -245,6 +256,14 @@ class BindingsGenerator { * %0: [c_type_out] of the return type * %1: name of the variable to be returned * %2: [name] of the return type + * --------------------------------------- + * If [ret_as_byref_arg] is true, the format is different. Instead of using a return statement, + * the value must be assigned to a parameter. This type of this parameter is a pointer to [c_type_out]. + * Formatting elements: + * %0: [c_type_out] of the return type + * %1: name of the variable to be returned + * %2: [name] of the return type + * %3: name of the parameter that must be assigned the return value */ String c_out; @@ -288,9 +307,10 @@ class BindingsGenerator { * One or more statements that determine how a variable of this type is returned from a method. * It must contain the return statement(s). * Formatting elements: - * %0: internal method call statement - * %1: [cs_type] of the return type - * %2: [im_type_out] of the return type + * %0: internal method name + * %1: internal method call arguments without surrounding parenthesis + * %2: [cs_type] of the return type + * %3: [im_type_out] of the return type */ String cs_out; @@ -399,8 +419,8 @@ class BindingsGenerator { } static void postsetup_enum_type(TypeInterface &r_enum_itype) { - // C interface is the same as that of 'int'. Remember to apply any - // changes done here to the 'int' type interface as well + // C interface for enums is the same as that of 'uint32_t'. Remember to apply + // any of the changes done here to the 'uint32_t' type interface as well. r_enum_itype.c_arg_in = "&%s_in"; { @@ -414,7 +434,7 @@ class BindingsGenerator { r_enum_itype.cs_type = r_enum_itype.proxy_name; r_enum_itype.cs_in = "(int)%s"; - r_enum_itype.cs_out = "return (%1)%0;"; + r_enum_itype.cs_out = "return (%2)%0(%1);"; r_enum_itype.im_type_in = "int"; r_enum_itype.im_type_out = "int"; r_enum_itype.class_doc = &EditorHelp::get_doc_data()->class_list[r_enum_itype.proxy_name]; @@ -432,6 +452,8 @@ class BindingsGenerator { memory_own = false; + ret_as_byref_arg = false; + c_arg_in = "%s"; class_doc = NULL; @@ -468,7 +490,8 @@ class BindingsGenerator { } }; - static bool verbose_output; + bool log_print_enabled; + bool initialized; OrderedHashMap<StringName, TypeInterface> obj_types; @@ -487,33 +510,60 @@ class BindingsGenerator { List<InternalCall> core_custom_icalls; List<InternalCall> editor_custom_icalls; + Map<StringName, List<StringName> > blacklisted_methods; + + void _initialize_blacklisted_methods(); + struct NameCache { StringName type_void; - StringName type_int; StringName type_Array; StringName type_Dictionary; StringName type_Variant; StringName type_VarArg; StringName type_Object; StringName type_Reference; + StringName type_RID; StringName type_String; StringName type_at_GlobalScope; StringName enum_Error; + StringName type_sbyte; + StringName type_short; + StringName type_int; + StringName type_long; + StringName type_byte; + StringName type_ushort; + StringName type_uint; + StringName type_ulong; + StringName type_float; + StringName type_double; + NameCache() { type_void = StaticCString::create("void"); - type_int = StaticCString::create("int"); type_Array = StaticCString::create("Array"); type_Dictionary = StaticCString::create("Dictionary"); type_Variant = StaticCString::create("Variant"); type_VarArg = StaticCString::create("VarArg"); type_Object = StaticCString::create("Object"); type_Reference = StaticCString::create("Reference"); + type_RID = StaticCString::create("RID"); type_String = StaticCString::create("String"); type_at_GlobalScope = StaticCString::create("@GlobalScope"); enum_Error = StaticCString::create("Error"); + + type_sbyte = StaticCString::create("sbyte"); + type_short = StaticCString::create("short"); + type_int = StaticCString::create("int"); + type_long = StaticCString::create("long"); + type_byte = StaticCString::create("byte"); + type_ushort = StaticCString::create("ushort"); + type_uint = StaticCString::create("uint"); + type_ulong = StaticCString::create("ulong"); + type_float = StaticCString::create("float"); + type_double = StaticCString::create("double"); } + private: NameCache(const NameCache &); NameCache &operator=(const NameCache &); }; @@ -559,51 +609,51 @@ class BindingsGenerator { const TypeInterface *_get_type_or_null(const TypeReference &p_typeref); const TypeInterface *_get_type_or_placeholder(const TypeReference &p_typeref); - void _default_argument_from_variant(const Variant &p_val, ArgumentInterface &r_iarg); + StringName _get_int_type_name_from_meta(GodotTypeInfo::Metadata p_meta); + StringName _get_float_type_name_from_meta(GodotTypeInfo::Metadata p_meta); + + bool _arg_default_value_from_variant(const Variant &p_val, ArgumentInterface &r_iarg); - void _populate_object_type_interfaces(); + bool _populate_object_type_interfaces(); void _populate_builtin_type_interfaces(); void _populate_global_constants(); Error _generate_cs_type(const TypeInterface &itype, const String &p_output_file); - Error _generate_cs_property(const TypeInterface &p_itype, const PropertyInterface &p_iprop, List<String> &p_output); - Error _generate_cs_method(const TypeInterface &p_itype, const MethodInterface &p_imethod, int &p_method_bind_count, List<String> &p_output); - - void _generate_global_constants(List<String> &p_output); + Error _generate_cs_property(const TypeInterface &p_itype, const PropertyInterface &p_iprop, StringBuilder &p_output); + Error _generate_cs_method(const TypeInterface &p_itype, const MethodInterface &p_imethod, int &p_method_bind_count, StringBuilder &p_output); - Error _generate_glue_method(const TypeInterface &p_itype, const MethodInterface &p_imethod, List<String> &p_output); + void _generate_global_constants(StringBuilder &p_output); - Error _save_file(const String &p_path, const List<String> &p_content); + Error _generate_glue_method(const TypeInterface &p_itype, const MethodInterface &p_imethod, StringBuilder &p_output); - BindingsGenerator() {} + Error _save_file(const String &p_path, const StringBuilder &p_content); - BindingsGenerator(const BindingsGenerator &); - BindingsGenerator &operator=(const BindingsGenerator &); + void _log(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3; - friend class CSharpLanguage; - static BindingsGenerator *singleton; + void _initialize(); public: - Error generate_cs_core_project(const String &p_solution_dir, DotNetSolution &r_solution, bool p_verbose_output = true); - Error generate_cs_editor_project(const String &p_solution_dir, DotNetSolution &r_solution, bool p_verbose_output = true); - Error generate_cs_api(const String &p_output_dir, bool p_verbose_output = true); + Error generate_cs_core_project(const String &p_proj_dir, Vector<String> &r_compile_files); + Error generate_cs_editor_project(const String &p_proj_dir, Vector<String> &r_compile_items); + Error generate_cs_api(const String &p_output_dir); Error generate_glue(const String &p_output_dir); - static uint32_t get_version(); + _FORCE_INLINE_ bool is_log_print_enabled() { return log_print_enabled; } + _FORCE_INLINE_ void set_log_print_enabled(bool p_enabled) { log_print_enabled = p_enabled; } - void initialize(); + _FORCE_INLINE_ bool is_initialized() { return initialized; } - _FORCE_INLINE_ static BindingsGenerator *get_singleton() { - if (!singleton) { - singleton = memnew(BindingsGenerator); - singleton->initialize(); - } - return singleton; - } + static uint32_t get_version(); static void handle_cmdline_args(const List<String> &p_cmdline_args); + + BindingsGenerator() : + log_print_enabled(true), + initialized(false) { + _initialize(); + } }; #endif diff --git a/modules/mono/editor/csharp_project.cpp b/modules/mono/editor/csharp_project.cpp index beeff51bc2..748447005f 100644 --- a/modules/mono/editor/csharp_project.cpp +++ b/modules/mono/editor/csharp_project.cpp @@ -44,66 +44,52 @@ namespace CSharpProject { -String generate_core_api_project(const String &p_dir, const Vector<String> &p_files) { - - _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN) - - GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectGenerator"); - - Variant dir = p_dir; - Variant compile_items = p_files; - const Variant *args[2] = { &dir, &compile_items }; +bool generate_api_solution_impl(const String &p_solution_dir, const String &p_core_proj_dir, const Vector<String> &p_core_compile_items, + const String &p_editor_proj_dir, const Vector<String> &p_editor_compile_items, + GDMonoAssembly *p_tools_project_editor_assembly) { + + GDMonoClass *klass = p_tools_project_editor_assembly->get_class("GodotTools.ProjectEditor", "ApiSolutionGenerator"); + + Variant solution_dir = p_solution_dir; + Variant core_proj_dir = p_core_proj_dir; + Variant core_compile_items = p_core_compile_items; + Variant editor_proj_dir = p_editor_proj_dir; + Variant editor_compile_items = p_editor_compile_items; + const Variant *args[5] = { &solution_dir, &core_proj_dir, &core_compile_items, &editor_proj_dir, &editor_compile_items }; MonoException *exc = NULL; - MonoObject *ret = klass->get_method("GenCoreApiProject", 2)->invoke(NULL, args, &exc); + klass->get_method("GenerateApiSolution", 5)->invoke(NULL, args, &exc); if (exc) { GDMonoUtils::debug_print_unhandled_exception(exc); - ERR_FAIL_V(String()); + ERR_FAIL_V(false); } - return ret ? GDMonoMarshal::mono_string_to_godot((MonoString *)ret) : String(); + return true; } -String generate_editor_api_project(const String &p_dir, const String &p_core_proj_path, const Vector<String> &p_files) { +bool generate_api_solution(const String &p_solution_dir, const String &p_core_proj_dir, const Vector<String> &p_core_compile_items, + const String &p_editor_proj_dir, const Vector<String> &p_editor_compile_items) { - _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN) + if (GDMono::get_singleton()->get_tools_project_editor_assembly()) { + return generate_api_solution_impl(p_solution_dir, p_core_proj_dir, p_core_compile_items, + p_editor_proj_dir, p_editor_compile_items, + GDMono::get_singleton()->get_tools_project_editor_assembly()); + } else { + MonoDomain *temp_domain = GDMonoUtils::create_domain("GodotEngine.Domain.ApiSolutionGeneration"); + CRASH_COND(temp_domain == NULL); + _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(temp_domain); - GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectGenerator"); + _GDMONO_SCOPE_DOMAIN_(temp_domain); - Variant dir = p_dir; - Variant core_proj_path = p_core_proj_path; - Variant compile_items = p_files; - const Variant *args[3] = { &dir, &core_proj_path, &compile_items }; - MonoException *exc = NULL; - MonoObject *ret = klass->get_method("GenEditorApiProject", 3)->invoke(NULL, args, &exc); + GDMonoAssembly *tools_project_editor_asm = NULL; - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - ERR_FAIL_V(String()); - } + bool assembly_loaded = GDMono::get_singleton()->load_assembly(TOOLS_PROJECT_EDITOR_ASM_NAME, &tools_project_editor_asm); + ERR_FAIL_COND_V_MSG(!assembly_loaded, false, "Failed to load assembly: '" TOOLS_PROJECT_EDITOR_ASM_NAME "'."); - return ret ? GDMonoMarshal::mono_string_to_godot((MonoString *)ret) : String(); -} - -String generate_game_project(const String &p_dir, const String &p_name, const Vector<String> &p_files) { - - _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN) - - GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectGenerator"); - - Variant dir = p_dir; - Variant name = p_name; - Variant compile_items = p_files; - const Variant *args[3] = { &dir, &name, &compile_items }; - MonoException *exc = NULL; - MonoObject *ret = klass->get_method("GenGameProject", 3)->invoke(NULL, args, &exc); - - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - ERR_FAIL_V(String()); + return generate_api_solution_impl(p_solution_dir, p_core_proj_dir, p_core_compile_items, + p_editor_proj_dir, p_editor_compile_items, + tools_project_editor_asm); } - - return ret ? GDMonoMarshal::mono_string_to_godot((MonoString *)ret) : String(); } void add_item(const String &p_project_path, const String &p_item_type, const String &p_include) { @@ -111,9 +97,9 @@ void add_item(const String &p_project_path, const String &p_item_type, const Str if (!GLOBAL_DEF("mono/project/auto_update_project", true)) return; - _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN) + GDMonoAssembly *tools_project_editor_assembly = GDMono::get_singleton()->get_tools_project_editor_assembly(); - GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectUtils"); + GDMonoClass *klass = tools_project_editor_assembly->get_class("GodotTools.ProjectEditor", "ProjectUtils"); Variant project_path = p_project_path; Variant item_type = p_item_type; @@ -128,126 +114,4 @@ void add_item(const String &p_project_path, const String &p_item_type, const Str } } -Error generate_scripts_metadata(const String &p_project_path, const String &p_output_path) { - - _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN) - - if (FileAccess::exists(p_output_path)) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); - Error rm_err = da->remove(p_output_path); - - ERR_EXPLAIN("Failed to remove old scripts metadata file"); - ERR_FAIL_COND_V(rm_err != OK, rm_err); - } - - GDMonoClass *project_utils = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectUtils"); - - void *args[2] = { - GDMonoMarshal::mono_string_from_godot(p_project_path), - GDMonoMarshal::mono_string_from_godot("Compile") - }; - - MonoException *exc = NULL; - MonoArray *ret = (MonoArray *)project_utils->get_method("GetIncludeFiles", 2)->invoke_raw(NULL, args, &exc); - - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - ERR_FAIL_V(FAILED); - } - - PoolStringArray project_files = GDMonoMarshal::mono_array_to_PoolStringArray(ret); - PoolStringArray::Read r = project_files.read(); - - Dictionary old_dict = CSharpLanguage::get_singleton()->get_scripts_metadata(); - Dictionary new_dict; - - for (int i = 0; i < project_files.size(); i++) { - const String &project_file = ("res://" + r[i]).simplify_path(); - - uint64_t modified_time = FileAccess::get_modified_time(project_file); - - const Variant *old_file_var = old_dict.getptr(project_file); - if (old_file_var) { - Dictionary old_file_dict = old_file_var->operator Dictionary(); - - if (old_file_dict["modified_time"].operator uint64_t() == modified_time) { - // No changes so no need to parse again - new_dict[project_file] = old_file_dict; - continue; - } - } - - ScriptClassParser scp; - Error err = scp.parse_file(project_file); - if (err != OK) { - ERR_PRINTS("Parse error: " + scp.get_error()); - ERR_EXPLAIN("Failed to determine namespace and class for script: " + project_file); - ERR_FAIL_V(err); - } - - Vector<ScriptClassParser::ClassDecl> classes = scp.get_classes(); - - bool found = false; - Dictionary class_dict; - - String search_name = project_file.get_file().get_basename(); - - for (int j = 0; j < classes.size(); j++) { - const ScriptClassParser::ClassDecl &class_decl = classes[j]; - - if (class_decl.base.size() == 0) - continue; // Does not inherit nor implement anything, so it can't be a script class - - String class_cmp; - - if (class_decl.nested) { - class_cmp = class_decl.name.get_slice(".", class_decl.name.get_slice_count(".") - 1); - } else { - class_cmp = class_decl.name; - } - - if (class_cmp != search_name) - continue; - - class_dict["namespace"] = class_decl.namespace_; - class_dict["class_name"] = class_decl.name; - class_dict["nested"] = class_decl.nested; - - found = true; - break; - } - - if (found) { - Dictionary file_dict; - file_dict["modified_time"] = modified_time; - file_dict["class"] = class_dict; - new_dict[project_file] = file_dict; - } - } - - if (new_dict.size()) { - String json = JSON::print(new_dict, "", false); - - String base_dir = p_output_path.get_base_dir(); - - if (!DirAccess::exists(base_dir)) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); - - Error err = da->make_dir_recursive(base_dir); - ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE); - } - - Error ferr; - FileAccess *f = FileAccess::open(p_output_path, FileAccess::WRITE, &ferr); - ERR_EXPLAIN("Cannot open file for writing: " + p_output_path); - ERR_FAIL_COND_V(ferr != OK, ferr); - f->store_string(json); - f->flush(); - f->close(); - memdelete(f); - } - - return OK; -} - } // namespace CSharpProject diff --git a/modules/mono/editor/csharp_project.h b/modules/mono/editor/csharp_project.h index 3d5a65f8da..b42762cea2 100644 --- a/modules/mono/editor/csharp_project.h +++ b/modules/mono/editor/csharp_project.h @@ -35,14 +35,11 @@ namespace CSharpProject { -String generate_core_api_project(const String &p_dir, const Vector<String> &p_files = Vector<String>()); -String generate_editor_api_project(const String &p_dir, const String &p_core_dll_path, const Vector<String> &p_files = Vector<String>()); -String generate_game_project(const String &p_dir, const String &p_name, const Vector<String> &p_files = Vector<String>()); +bool generate_api_solution(const String &p_solution_dir, const String &p_core_proj_dir, const Vector<String> &p_core_compile_items, + const String &p_editor_proj_dir, const Vector<String> &p_editor_compile_items); void add_item(const String &p_project_path, const String &p_item_type, const String &p_include); -Error generate_scripts_metadata(const String &p_project_path, const String &p_output_path); - } // namespace CSharpProject #endif // CSHARP_PROJECT_H diff --git a/modules/mono/editor/dotnet_solution.cpp b/modules/mono/editor/dotnet_solution.cpp deleted file mode 100644 index 324752cafc..0000000000 --- a/modules/mono/editor/dotnet_solution.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/*************************************************************************/ -/* dotnet_solution.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 "dotnet_solution.h" - -#include "core/os/dir_access.h" -#include "core/os/file_access.h" - -#include "../utils/path_utils.h" -#include "../utils/string_utils.h" -#include "csharp_project.h" - -#define SOLUTION_TEMPLATE \ - "Microsoft Visual Studio Solution File, Format Version 12.00\n" \ - "# Visual Studio 2012\n" \ - "%0\n" \ - "Global\n" \ - "\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n" \ - "%1\n" \ - "\tEndGlobalSection\n" \ - "\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n" \ - "%2\n" \ - "\tEndGlobalSection\n" \ - "EndGlobal\n" - -#define PROJECT_DECLARATION "Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"%0\", \"%1\", \"{%2}\"\nEndProject" - -#define SOLUTION_PLATFORMS_CONFIG "\t%0|Any CPU = %0|Any CPU" - -#define PROJECT_PLATFORMS_CONFIG \ - "\t\t{%0}.%1|Any CPU.ActiveCfg = %1|Any CPU\n" \ - "\t\t{%0}.%1|Any CPU.Build.0 = %1|Any CPU" - -void DotNetSolution::add_new_project(const String &p_name, const ProjectInfo &p_project_info) { - projects[p_name] = p_project_info; -} - -bool DotNetSolution::has_project(const String &p_name) const { - return projects.find(p_name) != NULL; -} - -const DotNetSolution::ProjectInfo &DotNetSolution::get_project_info(const String &p_name) const { - return projects[p_name]; -} - -bool DotNetSolution::remove_project(const String &p_name) { - return projects.erase(p_name); -} - -Error DotNetSolution::save() { - bool dir_exists = DirAccess::exists(path); - ERR_EXPLAIN("The directory does not exist."); - ERR_FAIL_COND_V(!dir_exists, ERR_FILE_NOT_FOUND); - - String projs_decl; - String sln_platform_cfg; - String proj_platform_cfg; - - for (Map<String, ProjectInfo>::Element *E = projects.front(); E; E = E->next()) { - const String &name = E->key(); - const ProjectInfo &proj_info = E->value(); - - bool is_front = E == projects.front(); - - if (!is_front) - projs_decl += "\n"; - - projs_decl += sformat(PROJECT_DECLARATION, name, proj_info.relpath.replace("/", "\\"), proj_info.guid); - - for (int i = 0; i < proj_info.configs.size(); i++) { - const String &config = proj_info.configs[i]; - - if (i != 0 || !is_front) { - sln_platform_cfg += "\n"; - proj_platform_cfg += "\n"; - } - - sln_platform_cfg += sformat(SOLUTION_PLATFORMS_CONFIG, config); - proj_platform_cfg += sformat(PROJECT_PLATFORMS_CONFIG, proj_info.guid, config); - } - } - - String content = sformat(SOLUTION_TEMPLATE, projs_decl, sln_platform_cfg, proj_platform_cfg); - - FileAccess *file = FileAccess::open(path_join(path, name + ".sln"), FileAccess::WRITE); - ERR_FAIL_NULL_V(file, ERR_FILE_CANT_WRITE); - file->store_string(content); - file->close(); - memdelete(file); - - return OK; -} - -bool DotNetSolution::set_path(const String &p_existing_path) { - if (p_existing_path.is_abs_path()) { - path = p_existing_path; - } else { - String abspath; - if (!rel_path_to_abs(p_existing_path, abspath)) - return false; - path = abspath; - } - - return true; -} - -String DotNetSolution::get_path() { - return path; -} - -DotNetSolution::DotNetSolution(const String &p_name) { - name = p_name; -} diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp new file mode 100644 index 0000000000..443b4ba841 --- /dev/null +++ b/modules/mono/editor/editor_internal_calls.cpp @@ -0,0 +1,445 @@ +/*************************************************************************/ +/* editor_internal_calls.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 "editor_internal_calls.h" + +#include "core/os/os.h" +#include "core/version.h" +#include "editor/editor_node.h" +#include "editor/plugins/script_editor_plugin.h" +#include "editor/script_editor_debugger.h" +#include "main/main.h" + +#include "../csharp_script.h" +#include "../glue/cs_glue_version.gen.h" +#include "../godotsharp_dirs.h" +#include "../mono_gd/gd_mono_marshal.h" +#include "../utils/osx_utils.h" +#include "bindings_generator.h" +#include "godotsharp_export.h" +#include "script_class_parser.h" + +MonoString *godot_icall_GodotSharpDirs_ResDataDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_data_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_ResMetadataDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_metadata_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_ResAssembliesBaseDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_assemblies_base_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_ResAssembliesDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_assemblies_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_ResConfigDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_config_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_ResTempDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_temp_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_ResTempAssembliesBaseDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_temp_assemblies_base_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_ResTempAssembliesDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_temp_assemblies_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_MonoUserDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_mono_user_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_MonoLogsDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_mono_logs_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_MonoSolutionsDir() { +#ifdef TOOLS_ENABLED + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_mono_solutions_dir()); +#else + return NULL; +#endif +} + +MonoString *godot_icall_GodotSharpDirs_BuildLogsDirs() { +#ifdef TOOLS_ENABLED + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_build_logs_dir()); +#else + return NULL; +#endif +} + +MonoString *godot_icall_GodotSharpDirs_ProjectSlnPath() { +#ifdef TOOLS_ENABLED + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_project_sln_path()); +#else + return NULL; +#endif +} + +MonoString *godot_icall_GodotSharpDirs_ProjectCsProjPath() { +#ifdef TOOLS_ENABLED + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_project_csproj_path()); +#else + return NULL; +#endif +} + +MonoString *godot_icall_GodotSharpDirs_DataEditorToolsDir() { +#ifdef TOOLS_ENABLED + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_editor_tools_dir()); +#else + return NULL; +#endif +} + +MonoString *godot_icall_GodotSharpDirs_DataEditorPrebuiltApiDir() { +#ifdef TOOLS_ENABLED + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_editor_prebuilt_api_dir()); +#else + return NULL; +#endif +} + +MonoString *godot_icall_GodotSharpDirs_DataMonoEtcDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_mono_etc_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_DataMonoLibDir() { + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_mono_lib_dir()); +} + +MonoString *godot_icall_GodotSharpDirs_DataMonoBinDir() { +#ifdef WINDOWS_ENABLED + return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_mono_bin_dir()); +#else + return NULL; +#endif +} + +void godot_icall_EditorProgress_Create(MonoString *p_task, MonoString *p_label, int32_t p_amount, MonoBoolean p_can_cancel) { + String task = GDMonoMarshal::mono_string_to_godot(p_task); + String label = GDMonoMarshal::mono_string_to_godot(p_label); + EditorNode::progress_add_task(task, label, p_amount, (bool)p_can_cancel); +} + +void godot_icall_EditorProgress_Dispose(MonoString *p_task) { + String task = GDMonoMarshal::mono_string_to_godot(p_task); + EditorNode::progress_end_task(task); +} + +MonoBoolean godot_icall_EditorProgress_Step(MonoString *p_task, MonoString *p_state, int32_t p_step, MonoBoolean p_force_refresh) { + String task = GDMonoMarshal::mono_string_to_godot(p_task); + String state = GDMonoMarshal::mono_string_to_godot(p_state); + return EditorNode::progress_task_step(task, state, p_step, (bool)p_force_refresh); +} + +BindingsGenerator *godot_icall_BindingsGenerator_Ctor() { + return memnew(BindingsGenerator); +} + +void godot_icall_BindingsGenerator_Dtor(BindingsGenerator *p_handle) { + memdelete(p_handle); +} + +MonoBoolean godot_icall_BindingsGenerator_LogPrintEnabled(BindingsGenerator *p_handle) { + return p_handle->is_log_print_enabled(); +} + +void godot_icall_BindingsGenerator_SetLogPrintEnabled(BindingsGenerator p_handle, MonoBoolean p_enabled) { + p_handle.set_log_print_enabled(p_enabled); +} + +int32_t godot_icall_BindingsGenerator_GenerateCsApi(BindingsGenerator *p_handle, MonoString *p_output_dir) { + String output_dir = GDMonoMarshal::mono_string_to_godot(p_output_dir); + return p_handle->generate_cs_api(output_dir); +} + +uint32_t godot_icall_BindingsGenerator_Version() { + return BindingsGenerator::get_version(); +} + +uint32_t godot_icall_BindingsGenerator_CsGlueVersion() { + return CS_GLUE_VERSION; +} + +int32_t godot_icall_ScriptClassParser_ParseFile(MonoString *p_filepath, MonoObject *p_classes) { + String filepath = GDMonoMarshal::mono_string_to_godot(p_filepath); + + ScriptClassParser scp; + Error err = scp.parse_file(filepath); + if (err == OK) { + Array classes = GDMonoMarshal::mono_object_to_variant(p_classes); + const Vector<ScriptClassParser::ClassDecl> &class_decls = scp.get_classes(); + + for (int i = 0; i < class_decls.size(); i++) { + const ScriptClassParser::ClassDecl &classDecl = class_decls[i]; + + Dictionary classDeclDict; + classDeclDict["name"] = classDecl.name; + classDeclDict["namespace"] = classDecl.namespace_; + classDeclDict["nested"] = classDecl.nested; + classDeclDict["base_count"] = classDecl.base.size(); + classes.push_back(classDeclDict); + } + } + return err; +} + +uint32_t godot_icall_ExportPlugin_GetExportedAssemblyDependencies(MonoObject *p_initial_dependencies, + MonoString *p_build_config, MonoString *p_custom_bcl_dir, MonoObject *r_dependencies) { + Dictionary initial_dependencies = GDMonoMarshal::mono_object_to_variant(p_initial_dependencies); + String build_config = GDMonoMarshal::mono_string_to_godot(p_build_config); + String custom_bcl_dir = GDMonoMarshal::mono_string_to_godot(p_custom_bcl_dir); + Dictionary dependencies = GDMonoMarshal::mono_object_to_variant(r_dependencies); + + return GodotSharpExport::get_exported_assembly_dependencies(initial_dependencies, build_config, custom_bcl_dir, dependencies); +} + +MonoString *godot_icall_Internal_UpdateApiAssembliesFromPrebuilt(MonoString *p_config) { + String config = GDMonoMarshal::mono_string_to_godot(p_config); + String error_str = GDMono::get_singleton()->update_api_assemblies_from_prebuilt(config); + return GDMonoMarshal::mono_string_from_godot(error_str); +} + +MonoString *godot_icall_Internal_FullTemplatesDir() { + String full_templates_dir = EditorSettings::get_singleton()->get_templates_dir().plus_file(VERSION_FULL_CONFIG); + return GDMonoMarshal::mono_string_from_godot(full_templates_dir); +} + +MonoString *godot_icall_Internal_SimplifyGodotPath(MonoString *p_path) { + String path = GDMonoMarshal::mono_string_to_godot(p_path); + return GDMonoMarshal::mono_string_from_godot(path.simplify_path()); +} + +MonoBoolean godot_icall_Internal_IsOsxAppBundleInstalled(MonoString *p_bundle_id) { +#ifdef OSX_ENABLED + String bundle_id = GDMonoMarshal::mono_string_to_godot(p_bundle_id); + return (MonoBoolean)osx_is_app_bundle_installed(bundle_id); +#else + (void)p_bundle_id; // UNUSED + return (MonoBoolean) false; +#endif +} + +MonoBoolean godot_icall_Internal_GodotIs32Bits() { + return sizeof(void *) == 4; +} + +MonoBoolean godot_icall_Internal_GodotIsRealTDouble() { +#ifdef REAL_T_IS_DOUBLE + return (MonoBoolean) true; +#else + return (MonoBoolean) false; +#endif +} + +void godot_icall_Internal_GodotMainIteration() { + Main::iteration(); +} + +uint64_t godot_icall_Internal_GetCoreApiHash() { + return ClassDB::get_api_hash(ClassDB::API_CORE); +} + +uint64_t godot_icall_Internal_GetEditorApiHash() { + return ClassDB::get_api_hash(ClassDB::API_EDITOR); +} + +MonoBoolean godot_icall_Internal_IsAssembliesReloadingNeeded() { +#ifdef GD_MONO_HOT_RELOAD + return (MonoBoolean)CSharpLanguage::get_singleton()->is_assembly_reloading_needed(); +#else + return (MonoBoolean) false; +#endif +} + +void godot_icall_Internal_ReloadAssemblies(MonoBoolean p_soft_reload) { +#ifdef GD_MONO_HOT_RELOAD + _GodotSharp::get_singleton()->call_deferred("_reload_assemblies", (bool)p_soft_reload); +#endif +} + +void godot_icall_Internal_ScriptEditorDebuggerReloadScripts() { + ScriptEditor::get_singleton()->get_debugger()->reload_scripts(); +} + +MonoBoolean godot_icall_Internal_ScriptEditorEdit(MonoObject *p_resource, int32_t p_line, int32_t p_col, MonoBoolean p_grab_focus) { + Ref<Resource> resource = GDMonoMarshal::mono_object_to_variant(p_resource); + return (MonoBoolean)ScriptEditor::get_singleton()->edit(resource, p_line, p_col, (bool)p_grab_focus); +} + +void godot_icall_Internal_EditorNodeShowScriptScreen() { + EditorNode::get_singleton()->call("_editor_select", EditorNode::EDITOR_SCRIPT); +} + +MonoObject *godot_icall_Internal_GetScriptsMetadataOrNothing(MonoReflectionType *p_dict_reftype) { + Dictionary maybe_metadata = CSharpLanguage::get_singleton()->get_scripts_metadata_or_nothing(); + + MonoType *dict_type = mono_reflection_type_get_type(p_dict_reftype); + + uint32_t type_encoding = mono_type_get_type(dict_type); + MonoClass *type_class_raw = mono_class_from_mono_type(dict_type); + GDMonoClass *type_class = GDMono::get_singleton()->get_class(type_class_raw); + + return GDMonoMarshal::variant_to_mono_object(maybe_metadata, ManagedType(type_encoding, type_class)); +} + +MonoString *godot_icall_Internal_MonoWindowsInstallRoot() { +#ifdef WINDOWS_ENABLED + String install_root_dir = GDMono::get_singleton()->get_mono_reg_info().install_root_dir; + return GDMonoMarshal::mono_string_from_godot(install_root_dir); +#else + return NULL; +#endif +} + +void godot_icall_Internal_EditorRunPlay() { + EditorNode::get_singleton()->run_play(); +} + +void godot_icall_Internal_EditorRunStop() { + EditorNode::get_singleton()->run_stop(); +} + +void godot_icall_Internal_ScriptEditorDebugger_ReloadScripts() { + ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); + if (sed) { + sed->reload_scripts(); + } +} + +float godot_icall_Globals_EditorScale() { + return EDSCALE; +} + +MonoObject *godot_icall_Globals_GlobalDef(MonoString *p_setting, MonoObject *p_default_value, MonoBoolean p_restart_if_changed) { + String setting = GDMonoMarshal::mono_string_to_godot(p_setting); + Variant default_value = GDMonoMarshal::mono_object_to_variant(p_default_value); + Variant result = _GLOBAL_DEF(setting, default_value, (bool)p_restart_if_changed); + return GDMonoMarshal::variant_to_mono_object(result); +} + +MonoObject *godot_icall_Globals_EditorDef(MonoString *p_setting, MonoObject *p_default_value, MonoBoolean p_restart_if_changed) { + String setting = GDMonoMarshal::mono_string_to_godot(p_setting); + Variant default_value = GDMonoMarshal::mono_object_to_variant(p_default_value); + Variant result = _EDITOR_DEF(setting, default_value, (bool)p_restart_if_changed); + return GDMonoMarshal::variant_to_mono_object(result); +} + +MonoString *godot_icall_Globals_TTR(MonoString *p_text) { + String text = GDMonoMarshal::mono_string_to_godot(p_text); + return GDMonoMarshal::mono_string_from_godot(TTR(text)); +} + +MonoString *godot_icall_Utils_OS_GetPlatformName() { + String os_name = OS::get_singleton()->get_name(); + return GDMonoMarshal::mono_string_from_godot(os_name); +} + +void register_editor_internal_calls() { + + // GodotSharpDirs + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResDataDir", (void *)godot_icall_GodotSharpDirs_ResDataDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResMetadataDir", (void *)godot_icall_GodotSharpDirs_ResMetadataDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResAssembliesBaseDir", (void *)godot_icall_GodotSharpDirs_ResAssembliesBaseDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResAssembliesDir", (void *)godot_icall_GodotSharpDirs_ResAssembliesDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResConfigDir", (void *)godot_icall_GodotSharpDirs_ResConfigDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempDir", (void *)godot_icall_GodotSharpDirs_ResTempDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempAssembliesBaseDir", (void *)godot_icall_GodotSharpDirs_ResTempAssembliesBaseDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempAssembliesDir", (void *)godot_icall_GodotSharpDirs_ResTempAssembliesDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoUserDir", (void *)godot_icall_GodotSharpDirs_MonoUserDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoLogsDir", (void *)godot_icall_GodotSharpDirs_MonoLogsDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoSolutionsDir", (void *)godot_icall_GodotSharpDirs_MonoSolutionsDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_BuildLogsDirs", (void *)godot_icall_GodotSharpDirs_BuildLogsDirs); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ProjectSlnPath", (void *)godot_icall_GodotSharpDirs_ProjectSlnPath); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ProjectCsProjPath", (void *)godot_icall_GodotSharpDirs_ProjectCsProjPath); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataEditorToolsDir", (void *)godot_icall_GodotSharpDirs_DataEditorToolsDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataEditorPrebuiltApiDir", (void *)godot_icall_GodotSharpDirs_DataEditorPrebuiltApiDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoEtcDir", (void *)godot_icall_GodotSharpDirs_DataMonoEtcDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoLibDir", (void *)godot_icall_GodotSharpDirs_DataMonoLibDir); + mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoBinDir", (void *)godot_icall_GodotSharpDirs_DataMonoBinDir); + + // EditorProgress + mono_add_internal_call("GodotTools.Internals.EditorProgress::internal_Create", (void *)godot_icall_EditorProgress_Create); + mono_add_internal_call("GodotTools.Internals.EditorProgress::internal_Dispose", (void *)godot_icall_EditorProgress_Dispose); + mono_add_internal_call("GodotTools.Internals.EditorProgress::internal_Step", (void *)godot_icall_EditorProgress_Step); + + // BiningsGenerator + mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_Ctor", (void *)godot_icall_BindingsGenerator_Ctor); + mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_Dtor", (void *)godot_icall_BindingsGenerator_Dtor); + mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_LogPrintEnabled", (void *)godot_icall_BindingsGenerator_LogPrintEnabled); + mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_SetLogPrintEnabled", (void *)godot_icall_BindingsGenerator_SetLogPrintEnabled); + mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_GenerateCsApi", (void *)godot_icall_BindingsGenerator_GenerateCsApi); + mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_Version", (void *)godot_icall_BindingsGenerator_Version); + mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_CsGlueVersion", (void *)godot_icall_BindingsGenerator_CsGlueVersion); + + // ScriptClassParser + mono_add_internal_call("GodotTools.Internals.ScriptClassParser::internal_ParseFile", (void *)godot_icall_ScriptClassParser_ParseFile); + + // ExportPlugin + mono_add_internal_call("GodotTools.Export.ExportPlugin::internal_GetExportedAssemblyDependencies", (void *)godot_icall_ExportPlugin_GetExportedAssemblyDependencies); + + // Internals + mono_add_internal_call("GodotTools.Internals.Internal::internal_UpdateApiAssembliesFromPrebuilt", (void *)godot_icall_Internal_UpdateApiAssembliesFromPrebuilt); + mono_add_internal_call("GodotTools.Internals.Internal::internal_FullTemplatesDir", (void *)godot_icall_Internal_FullTemplatesDir); + mono_add_internal_call("GodotTools.Internals.Internal::internal_SimplifyGodotPath", (void *)godot_icall_Internal_SimplifyGodotPath); + mono_add_internal_call("GodotTools.Internals.Internal::internal_IsOsxAppBundleInstalled", (void *)godot_icall_Internal_IsOsxAppBundleInstalled); + mono_add_internal_call("GodotTools.Internals.Internal::internal_GodotIs32Bits", (void *)godot_icall_Internal_GodotIs32Bits); + mono_add_internal_call("GodotTools.Internals.Internal::internal_GodotIsRealTDouble", (void *)godot_icall_Internal_GodotIsRealTDouble); + mono_add_internal_call("GodotTools.Internals.Internal::internal_GodotMainIteration", (void *)godot_icall_Internal_GodotMainIteration); + mono_add_internal_call("GodotTools.Internals.Internal::internal_GetCoreApiHash", (void *)godot_icall_Internal_GetCoreApiHash); + mono_add_internal_call("GodotTools.Internals.Internal::internal_GetEditorApiHash", (void *)godot_icall_Internal_GetEditorApiHash); + mono_add_internal_call("GodotTools.Internals.Internal::internal_IsAssembliesReloadingNeeded", (void *)godot_icall_Internal_IsAssembliesReloadingNeeded); + mono_add_internal_call("GodotTools.Internals.Internal::internal_ReloadAssemblies", (void *)godot_icall_Internal_ReloadAssemblies); + mono_add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorDebuggerReloadScripts", (void *)godot_icall_Internal_ScriptEditorDebuggerReloadScripts); + mono_add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorEdit", (void *)godot_icall_Internal_ScriptEditorEdit); + mono_add_internal_call("GodotTools.Internals.Internal::internal_EditorNodeShowScriptScreen", (void *)godot_icall_Internal_EditorNodeShowScriptScreen); + mono_add_internal_call("GodotTools.Internals.Internal::internal_GetScriptsMetadataOrNothing", (void *)godot_icall_Internal_GetScriptsMetadataOrNothing); + mono_add_internal_call("GodotTools.Internals.Internal::internal_MonoWindowsInstallRoot", (void *)godot_icall_Internal_MonoWindowsInstallRoot); + mono_add_internal_call("GodotTools.Internals.Internal::internal_EditorRunPlay", (void *)godot_icall_Internal_EditorRunPlay); + mono_add_internal_call("GodotTools.Internals.Internal::internal_EditorRunStop", (void *)godot_icall_Internal_EditorRunStop); + mono_add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorDebugger_ReloadScripts", (void *)godot_icall_Internal_ScriptEditorDebugger_ReloadScripts); + + // Globals + mono_add_internal_call("GodotTools.Internals.Globals::internal_EditorScale", (void *)godot_icall_Globals_EditorScale); + mono_add_internal_call("GodotTools.Internals.Globals::internal_GlobalDef", (void *)godot_icall_Globals_GlobalDef); + mono_add_internal_call("GodotTools.Internals.Globals::internal_EditorDef", (void *)godot_icall_Globals_EditorDef); + mono_add_internal_call("GodotTools.Internals.Globals::internal_TTR", (void *)godot_icall_Globals_TTR); + + // Utils.OS + mono_add_internal_call("GodotTools.Utils.OS::GetPlatformName", (void *)godot_icall_Utils_OS_GetPlatformName); +} diff --git a/modules/mono/editor/editor_internal_calls.h b/modules/mono/editor/editor_internal_calls.h new file mode 100644 index 0000000000..1682da66e5 --- /dev/null +++ b/modules/mono/editor/editor_internal_calls.h @@ -0,0 +1,36 @@ +/*************************************************************************/ +/* editor_internal_calls.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 EDITOR_INTERNAL_CALL_H +#define EDITOR_INTERNAL_CALL_H + +void register_editor_internal_calls(); + +#endif // EDITOR_INTERNAL_CALL_H diff --git a/modules/mono/editor/godotsharp_builds.cpp b/modules/mono/editor/godotsharp_builds.cpp deleted file mode 100644 index 00c780d1b7..0000000000 --- a/modules/mono/editor/godotsharp_builds.cpp +++ /dev/null @@ -1,602 +0,0 @@ -/*************************************************************************/ -/* godotsharp_builds.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 "godotsharp_builds.h" - -#include "core/vector.h" -#include "main/main.h" - -#include "../glue/cs_glue_version.gen.h" -#include "../godotsharp_dirs.h" -#include "../mono_gd/gd_mono_class.h" -#include "../mono_gd/gd_mono_marshal.h" -#include "../utils/path_utils.h" -#include "bindings_generator.h" -#include "csharp_project.h" -#include "godotsharp_editor.h" - -#define PROP_NAME_MSBUILD_MONO "MSBuild (Mono)" -#define PROP_NAME_MSBUILD_VS "MSBuild (VS Build Tools)" -#define PROP_NAME_XBUILD "xbuild (Deprecated)" - -void godot_icall_BuildInstance_ExitCallback(MonoString *p_solution, MonoString *p_config, int p_exit_code) { - - String solution = GDMonoMarshal::mono_string_to_godot(p_solution); - String config = GDMonoMarshal::mono_string_to_godot(p_config); - GodotSharpBuilds::get_singleton()->build_exit_callback(MonoBuildInfo(solution, config), p_exit_code); -} - -static Vector<const char *> _get_msbuild_hint_dirs() { - Vector<const char *> ret; -#ifdef OSX_ENABLED - ret.push_back("/Library/Frameworks/Mono.framework/Versions/Current/bin/"); - ret.push_back("/usr/local/var/homebrew/linked/mono/bin/"); -#endif - ret.push_back("/opt/novell/mono/bin/"); - return ret; -} - -#ifdef UNIX_ENABLED -String _find_build_engine_on_unix(const String &p_name) { - String ret = path_which(p_name); - - if (ret.length()) - return ret; - - String ret_fallback = path_which(p_name + ".exe"); - if (ret_fallback.length()) - return ret_fallback; - - static Vector<const char *> locations = _get_msbuild_hint_dirs(); - - for (int i = 0; i < locations.size(); i++) { - String hint_path = locations[i] + p_name; - - if (FileAccess::exists(hint_path)) { - return hint_path; - } - } - - return String(); -} -#endif - -MonoString *godot_icall_BuildInstance_get_MSBuildPath() { - - GodotSharpBuilds::BuildTool build_tool = GodotSharpBuilds::BuildTool(int(EditorSettings::get_singleton()->get("mono/builds/build_tool"))); - -#if defined(WINDOWS_ENABLED) - switch (build_tool) { - case GodotSharpBuilds::MSBUILD_VS: { - static String msbuild_tools_path; - - if (msbuild_tools_path.empty() || !FileAccess::exists(msbuild_tools_path)) { - // Try to search it again if it wasn't found last time or if it was removed from its location - msbuild_tools_path = MonoRegUtils::find_msbuild_tools_path(); - - if (msbuild_tools_path.empty()) { - ERR_PRINTS("Cannot find executable for '" PROP_NAME_MSBUILD_VS "'. Tried with path: " + msbuild_tools_path); - return NULL; - } - } - - if (!msbuild_tools_path.ends_with("\\")) - msbuild_tools_path += "\\"; - - return GDMonoMarshal::mono_string_from_godot(msbuild_tools_path + "MSBuild.exe"); - } break; - case GodotSharpBuilds::MSBUILD_MONO: { - String msbuild_path = GDMono::get_singleton()->get_mono_reg_info().bin_dir.plus_file("msbuild.bat"); - - if (!FileAccess::exists(msbuild_path)) { - ERR_PRINTS("Cannot find executable for '" PROP_NAME_MSBUILD_MONO "'. Tried with path: " + msbuild_path); - return NULL; - } - - return GDMonoMarshal::mono_string_from_godot(msbuild_path); - } break; - case GodotSharpBuilds::XBUILD: { - String xbuild_path = GDMono::get_singleton()->get_mono_reg_info().bin_dir.plus_file("xbuild.bat"); - - if (!FileAccess::exists(xbuild_path)) { - ERR_PRINTS("Cannot find executable for '" PROP_NAME_XBUILD "'. Tried with path: " + xbuild_path); - return NULL; - } - - return GDMonoMarshal::mono_string_from_godot(xbuild_path); - } break; - default: - ERR_EXPLAIN("You don't deserve to live"); - CRASH_NOW(); - } -#elif defined(UNIX_ENABLED) - static String msbuild_path; - static String xbuild_path; - - if (build_tool == GodotSharpBuilds::XBUILD) { - if (xbuild_path.empty() || !FileAccess::exists(xbuild_path)) { - // Try to search it again if it wasn't found last time or if it was removed from its location - xbuild_path = _find_build_engine_on_unix("msbuild"); - } - - if (xbuild_path.empty()) { - ERR_PRINT("Cannot find binary for '" PROP_NAME_XBUILD "'"); - return NULL; - } - } else { - if (msbuild_path.empty() || !FileAccess::exists(msbuild_path)) { - // Try to search it again if it wasn't found last time or if it was removed from its location - msbuild_path = _find_build_engine_on_unix("msbuild"); - } - - if (msbuild_path.empty()) { - ERR_PRINT("Cannot find binary for '" PROP_NAME_MSBUILD_MONO "'"); - return NULL; - } - } - - return GDMonoMarshal::mono_string_from_godot(build_tool != GodotSharpBuilds::XBUILD ? msbuild_path : xbuild_path); -#else - (void)build_tool; // UNUSED - - ERR_EXPLAIN("Not implemented on this platform"); - ERR_FAIL_V(NULL); -#endif -} - -MonoString *godot_icall_BuildInstance_get_MonoWindowsBinDir() { - -#if defined(WINDOWS_ENABLED) - const MonoRegInfo &mono_reg_info = GDMono::get_singleton()->get_mono_reg_info(); - if (mono_reg_info.bin_dir.length()) { - return GDMonoMarshal::mono_string_from_godot(mono_reg_info.bin_dir); - } - - ERR_EXPLAIN("Cannot find Mono's binaries directory in the registry"); - ERR_FAIL_V(NULL); -#else - return NULL; -#endif -} - -MonoBoolean godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows() { - -#if defined(WINDOWS_ENABLED) - return GodotSharpBuilds::BuildTool(int(EditorSettings::get_singleton()->get("mono/builds/build_tool"))) == GodotSharpBuilds::MSBUILD_MONO; -#else - return false; -#endif -} - -MonoBoolean godot_icall_BuildInstance_get_PrintBuildOutput() { - - return (bool)EDITOR_GET("mono/builds/print_build_output"); -} - -void GodotSharpBuilds::register_internal_calls() { - - static bool registered = false; - ERR_FAIL_COND(registered); - registered = true; - - mono_add_internal_call("GodotSharpTools.Build.BuildSystem::godot_icall_BuildInstance_ExitCallback", (void *)godot_icall_BuildInstance_ExitCallback); - mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_MSBuildPath", (void *)godot_icall_BuildInstance_get_MSBuildPath); - mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_MonoWindowsBinDir", (void *)godot_icall_BuildInstance_get_MonoWindowsBinDir); - mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows", (void *)godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows); - mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_PrintBuildOutput", (void *)godot_icall_BuildInstance_get_PrintBuildOutput); -} - -void GodotSharpBuilds::show_build_error_dialog(const String &p_message) { - - GodotSharpEditor::get_singleton()->show_error_dialog(p_message, "Build error"); - MonoBottomPanel::get_singleton()->show_build_tab(); -} - -bool GodotSharpBuilds::build_api_sln(const String &p_api_sln_dir, const String &p_config) { - - String api_sln_file = p_api_sln_dir.plus_file(API_SOLUTION_NAME ".sln"); - - String core_api_assembly_dir = p_api_sln_dir.plus_file(CORE_API_ASSEMBLY_NAME).plus_file("bin").plus_file(p_config); - String core_api_assembly_file = core_api_assembly_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); - - String editor_api_assembly_dir = p_api_sln_dir.plus_file(EDITOR_API_ASSEMBLY_NAME).plus_file("bin").plus_file(p_config); - String editor_api_assembly_file = editor_api_assembly_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); - - if (!FileAccess::exists(core_api_assembly_file) || !FileAccess::exists(editor_api_assembly_file)) { - MonoBuildInfo api_build_info(api_sln_file, p_config); - // TODO Replace this global NoWarn with '#pragma warning' directives on generated files, - // once we start to actively document manually maintained C# classes - api_build_info.custom_props.push_back("NoWarn=1591"); // Ignore missing documentation warnings - - if (!GodotSharpBuilds::get_singleton()->build(api_build_info)) { - show_build_error_dialog("Failed to build " API_SOLUTION_NAME " solution."); - return false; - } - } - - return true; -} - -bool GodotSharpBuilds::copy_api_assembly(const String &p_src_dir, const String &p_dst_dir, const String &p_assembly_name, APIAssembly::Type p_api_type) { - - // Create destination directory if needed - if (!DirAccess::exists(p_dst_dir)) { - DirAccess *da = DirAccess::create_for_path(p_dst_dir); - Error err = da->make_dir_recursive(p_dst_dir); - memdelete(da); - - if (err != OK) { - show_build_error_dialog("Failed to create destination directory for the API assemblies. Error: " + itos(err)); - return false; - } - } - - String assembly_file = p_assembly_name + ".dll"; - String assembly_src = p_src_dir.plus_file(assembly_file); - String assembly_dst = p_dst_dir.plus_file(assembly_file); - - if (!FileAccess::exists(assembly_dst) || - FileAccess::get_modified_time(assembly_src) > FileAccess::get_modified_time(assembly_dst) || - GDMono::get_singleton()->metadata_is_api_assembly_invalidated(p_api_type)) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - - String xml_file = p_assembly_name + ".xml"; - if (da->copy(p_src_dir.plus_file(xml_file), p_dst_dir.plus_file(xml_file)) != OK) - WARN_PRINTS("Failed to copy " + xml_file); - - String pdb_file = p_assembly_name + ".pdb"; - if (da->copy(p_src_dir.plus_file(pdb_file), p_dst_dir.plus_file(pdb_file)) != OK) - WARN_PRINTS("Failed to copy " + pdb_file); - - Error err = da->copy(assembly_src, assembly_dst); - - if (err != OK) { - show_build_error_dialog("Failed to copy " + assembly_file); - return false; - } - - GDMono::get_singleton()->metadata_set_api_assembly_invalidated(p_api_type, false); - } - - return true; -} - -String GodotSharpBuilds::_api_folder_name(APIAssembly::Type p_api_type) { - - uint64_t api_hash = p_api_type == APIAssembly::API_CORE ? - GDMono::get_singleton()->get_api_core_hash() : - GDMono::get_singleton()->get_api_editor_hash(); - return String::num_uint64(api_hash) + - "_" + String::num_uint64(BindingsGenerator::get_version()) + - "_" + String::num_uint64(CS_GLUE_VERSION); -} - -bool GodotSharpBuilds::make_api_assembly(APIAssembly::Type p_api_type) { - - String api_name = p_api_type == APIAssembly::API_CORE ? CORE_API_ASSEMBLY_NAME : EDITOR_API_ASSEMBLY_NAME; - - String editor_prebuilt_api_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir(); - String res_assemblies_dir = GodotSharpDirs::get_res_assemblies_dir(); - - if (FileAccess::exists(editor_prebuilt_api_dir.plus_file(api_name + ".dll"))) { - EditorProgress pr("mono_copy_prebuilt_api_assembly", "Copying prebuilt " + api_name + " assembly...", 1); - pr.step("Copying " + api_name + " assembly", 0); - return GodotSharpBuilds::copy_api_assembly(editor_prebuilt_api_dir, res_assemblies_dir, api_name, p_api_type); - } - - String api_build_config = "Release"; - - EditorProgress pr("mono_build_release_" API_SOLUTION_NAME, "Building " API_SOLUTION_NAME " solution...", 3); - - pr.step("Generating " API_SOLUTION_NAME " solution", 0); - - String api_sln_dir = GodotSharpDirs::get_mono_solutions_dir() - .plus_file(_api_folder_name(APIAssembly::API_CORE)); - - String api_sln_file = api_sln_dir.plus_file(API_SOLUTION_NAME ".sln"); - - if (!DirAccess::exists(api_sln_dir) || !FileAccess::exists(api_sln_file)) { - BindingsGenerator *gen = BindingsGenerator::get_singleton(); - bool gen_verbose = OS::get_singleton()->is_stdout_verbose(); - - Error err = gen->generate_cs_api(api_sln_dir, gen_verbose); - if (err != OK) { - show_build_error_dialog("Failed to generate " API_SOLUTION_NAME " solution. Error: " + itos(err)); - return false; - } - } - - pr.step("Building " API_SOLUTION_NAME " solution", 1); - - if (!GodotSharpBuilds::build_api_sln(api_sln_dir, api_build_config)) - return false; - - pr.step("Copying " + api_name + " assembly", 2); - - // Copy the built assembly to the assemblies directory - String api_assembly_dir = api_sln_dir.plus_file(api_name).plus_file("bin").plus_file(api_build_config); - if (!GodotSharpBuilds::copy_api_assembly(api_assembly_dir, res_assemblies_dir, api_name, p_api_type)) - return false; - - return true; -} - -bool GodotSharpBuilds::build_project_blocking(const String &p_config) { - - if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path())) - return true; // No solution to build - - if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_CORE)) - return false; - - if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_EDITOR)) - return false; - - EditorProgress pr("mono_project_debug_build", "Building project solution...", 1); - pr.step("Building project solution", 0); - - MonoBuildInfo build_info(GodotSharpDirs::get_project_sln_path(), p_config); - if (!GodotSharpBuilds::get_singleton()->build(build_info)) { - GodotSharpBuilds::show_build_error_dialog("Failed to build project solution"); - return false; - } - - return true; -} - -bool GodotSharpBuilds::editor_build_callback() { - - if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path())) - return true; // No solution to build - - String scripts_metadata_path_editor = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor"); - String scripts_metadata_path_player = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor_player"); - - Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path_editor); - ERR_FAIL_COND_V(metadata_err != OK, false); - - if (FileAccess::exists(scripts_metadata_path_editor)) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); - Error copy_err = da->copy(scripts_metadata_path_editor, scripts_metadata_path_player); - - ERR_EXPLAIN("Failed to copy scripts metadata file"); - ERR_FAIL_COND_V(copy_err != OK, false); - } - - return build_project_blocking("Tools"); -} - -GodotSharpBuilds *GodotSharpBuilds::singleton = NULL; - -void GodotSharpBuilds::build_exit_callback(const MonoBuildInfo &p_build_info, int p_exit_code) { - - BuildProcess *match = builds.getptr(p_build_info); - ERR_FAIL_NULL(match); - - BuildProcess &bp = *match; - bp.on_exit(p_exit_code); -} - -void GodotSharpBuilds::restart_build(MonoBuildTab *p_build_tab) { -} - -void GodotSharpBuilds::stop_build(MonoBuildTab *p_build_tab) { -} - -bool GodotSharpBuilds::build(const MonoBuildInfo &p_build_info) { - - BuildProcess *match = builds.getptr(p_build_info); - - if (match) { - BuildProcess &bp = *match; - bp.start(true); - return bp.exit_code == 0; - } else { - BuildProcess bp = BuildProcess(p_build_info); - bp.start(true); - builds.set(p_build_info, bp); - return bp.exit_code == 0; - } -} - -bool GodotSharpBuilds::build_async(const MonoBuildInfo &p_build_info, GodotSharpBuild_ExitCallback p_callback) { - - BuildProcess *match = builds.getptr(p_build_info); - - if (match) { - BuildProcess &bp = *match; - bp.start(); - return !bp.exited; // failed to start - } else { - BuildProcess bp = BuildProcess(p_build_info, p_callback); - bp.start(); - builds.set(p_build_info, bp); - return !bp.exited; // failed to start - } -} - -GodotSharpBuilds::GodotSharpBuilds() { - - singleton = this; - - EditorNode::get_singleton()->add_build_callback(&GodotSharpBuilds::editor_build_callback); - - // Build tool settings - EditorSettings *ed_settings = EditorSettings::get_singleton(); - -#ifdef WINDOWS_ENABLED - EDITOR_DEF("mono/builds/build_tool", MSBUILD_VS); -#else - EDITOR_DEF("mono/builds/build_tool", MSBUILD_MONO); -#endif - - ed_settings->add_property_hint(PropertyInfo(Variant::INT, "mono/builds/build_tool", PROPERTY_HINT_ENUM, - PROP_NAME_MSBUILD_MONO -#ifdef WINDOWS_ENABLED - "," PROP_NAME_MSBUILD_VS -#endif - "," PROP_NAME_XBUILD)); - - EDITOR_DEF("mono/builds/print_build_output", false); -} - -GodotSharpBuilds::~GodotSharpBuilds() { - - singleton = NULL; -} - -void GodotSharpBuilds::BuildProcess::on_exit(int p_exit_code) { - - exited = true; - exit_code = p_exit_code; - build_tab->on_build_exit(p_exit_code == 0 ? MonoBuildTab::RESULT_SUCCESS : MonoBuildTab::RESULT_ERROR); - build_instance.unref(); - - if (exit_callback) - exit_callback(exit_code); -} - -void GodotSharpBuilds::BuildProcess::start(bool p_blocking) { - - _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN) - - exit_code = -1; - - String log_dirpath = build_info.get_log_dirpath(); - - if (build_tab) { - build_tab->on_build_start(); - } else { - build_tab = memnew(MonoBuildTab(build_info, log_dirpath)); - MonoBottomPanel::get_singleton()->add_build_tab(build_tab); - } - - if (p_blocking) { - // Required in order to update the build tasks list - Main::iteration(); - } - - if (!exited) { - exited = true; - String message = "Tried to start build process, but it is already running"; - build_tab->on_build_exec_failed(message); - ERR_EXPLAIN(message); - ERR_FAIL(); - } - - exited = false; - - // Remove old issues file - - String issues_file = get_msbuild_issues_filename(); - DirAccessRef d = DirAccess::create_for_path(log_dirpath); - if (d->file_exists(issues_file)) { - Error err = d->remove(issues_file); - if (err != OK) { - exited = true; - String file_path = ProjectSettings::get_singleton()->localize_path(log_dirpath).plus_file(issues_file); - String message = "Cannot remove issues file: " + file_path; - build_tab->on_build_exec_failed(message); - ERR_EXPLAIN(message); - ERR_FAIL(); - } - } - - GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Build", "BuildInstance"); - - MonoObject *mono_object = mono_object_new(mono_domain_get(), klass->get_mono_ptr()); - - // Construct - - Variant solution = build_info.solution; - Variant config = build_info.configuration; - - const Variant *ctor_args[2] = { &solution, &config }; - - MonoException *exc = NULL; - GDMonoMethod *ctor = klass->get_method(".ctor", 2); - ctor->invoke(mono_object, ctor_args, &exc); - - if (exc) { - exited = true; - GDMonoUtils::debug_unhandled_exception(exc); - String message = "The build constructor threw an exception.\n" + GDMonoUtils::get_exception_name_and_message(exc); - build_tab->on_build_exec_failed(message); - ERR_EXPLAIN(message); - ERR_FAIL(); - } - - // Call Build - - String logger_assembly_path = GDMono::get_singleton()->get_editor_tools_assembly()->get_path(); - Variant logger_assembly = ProjectSettings::get_singleton()->globalize_path(logger_assembly_path); - Variant logger_output_dir = log_dirpath; - Variant custom_props = build_info.custom_props; - - const Variant *args[3] = { &logger_assembly, &logger_output_dir, &custom_props }; - - exc = NULL; - GDMonoMethod *build_method = klass->get_method(p_blocking ? "Build" : "BuildAsync", 3); - build_method->invoke(mono_object, args, &exc); - - if (exc) { - exited = true; - GDMonoUtils::debug_unhandled_exception(exc); - String message = "The build method threw an exception.\n" + GDMonoUtils::get_exception_name_and_message(exc); - build_tab->on_build_exec_failed(message); - ERR_EXPLAIN(message); - ERR_FAIL(); - } - - // Build returned - - if (p_blocking) { - exited = true; - exit_code = klass->get_field("exitCode")->get_int_value(mono_object); - - if (exit_code != 0) { - String log_filepath = build_info.get_log_dirpath().plus_file(get_msbuild_log_filename()); - print_verbose("MSBuild exited with code: " + itos(exit_code) + ". Log file: " + log_filepath); - } - - build_tab->on_build_exit(exit_code == 0 ? MonoBuildTab::RESULT_SUCCESS : MonoBuildTab::RESULT_ERROR); - } else { - build_instance = MonoGCHandle::create_strong(mono_object); - exited = false; - } -} - -GodotSharpBuilds::BuildProcess::BuildProcess(const MonoBuildInfo &p_build_info, GodotSharpBuild_ExitCallback p_callback) : - build_info(p_build_info), - build_tab(NULL), - exit_callback(p_callback), - exited(true), - exit_code(-1) { -} diff --git a/modules/mono/editor/godotsharp_editor.cpp b/modules/mono/editor/godotsharp_editor.cpp deleted file mode 100644 index 921b9f987b..0000000000 --- a/modules/mono/editor/godotsharp_editor.cpp +++ /dev/null @@ -1,581 +0,0 @@ -/*************************************************************************/ -/* godotsharp_editor.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 "godotsharp_editor.h" - -#include "core/message_queue.h" -#include "core/os/os.h" -#include "core/project_settings.h" -#include "scene/gui/control.h" -#include "scene/main/node.h" - -#include "../csharp_script.h" -#include "../godotsharp_dirs.h" -#include "../mono_gd/gd_mono.h" -#include "../mono_gd/gd_mono_marshal.h" -#include "../utils/path_utils.h" -#include "bindings_generator.h" -#include "csharp_project.h" -#include "dotnet_solution.h" -#include "godotsharp_export.h" - -#ifdef OSX_ENABLED -#include "../utils/osx_utils.h" -#endif - -#ifdef WINDOWS_ENABLED -#include "../utils/mono_reg_utils.h" -#endif - -GodotSharpEditor *GodotSharpEditor::singleton = NULL; - -bool GodotSharpEditor::_create_project_solution() { - - EditorProgress pr("create_csharp_solution", TTR("Generating solution..."), 2); - - pr.step(TTR("Generating C# project...")); - - String path = OS::get_singleton()->get_resource_dir(); - String name = ProjectSettings::get_singleton()->get("application/config/name"); - if (name.empty()) { - name = "UnnamedProject"; - } - - String guid = CSharpProject::generate_game_project(path, name); - - if (guid.length()) { - - DotNetSolution solution(name); - - if (!solution.set_path(path)) { - show_error_dialog(TTR("Failed to create solution.")); - return false; - } - - DotNetSolution::ProjectInfo proj_info; - proj_info.guid = guid; - proj_info.relpath = name + ".csproj"; - proj_info.configs.push_back("Debug"); - proj_info.configs.push_back("Release"); - proj_info.configs.push_back("Tools"); - - solution.add_new_project(name, proj_info); - - Error sln_error = solution.save(); - - if (sln_error != OK) { - show_error_dialog(TTR("Failed to save solution.")); - return false; - } - - if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_CORE)) - return false; - - if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_EDITOR)) - return false; - - pr.step(TTR("Done")); - - // Here, after all calls to progress_task_step - call_deferred("_remove_create_sln_menu_option"); - - } else { - show_error_dialog(TTR("Failed to create C# project.")); - } - - return true; -} - -void GodotSharpEditor::_make_api_solutions_if_needed() { - // I'm sick entirely of ProgressDialog - - static int attempts_left = 100; - - if (MessageQueue::get_singleton()->is_flushing() || !SceneTree::get_singleton()) { - ERR_FAIL_COND(attempts_left == 0); // You've got to be kidding - - if (SceneTree::get_singleton()) { - SceneTree::get_singleton()->connect("idle_frame", this, "_make_api_solutions_if_needed", Vector<Variant>()); - } else { - call_deferred("_make_api_solutions_if_needed"); - } - - attempts_left--; - return; - } - - // Recursion guard needed because signals don't play well with ProgressDialog either, but unlike - // the message queue, with signals the collateral damage should be minimal in the worst case. - static bool recursion_guard = false; - if (!recursion_guard) { - recursion_guard = true; - - // Oneshot signals don't play well with ProgressDialog either, so we do it this way instead - SceneTree::get_singleton()->disconnect("idle_frame", this, "_make_api_solutions_if_needed"); - - _make_api_solutions_if_needed_impl(); - - recursion_guard = false; - } -} - -void GodotSharpEditor::_make_api_solutions_if_needed_impl() { - // If the project has a solution and C# project make sure the API assemblies are present and up to date - String res_assemblies_dir = GodotSharpDirs::get_res_assemblies_dir(); - - if (!FileAccess::exists(res_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll")) || - GDMono::get_singleton()->metadata_is_api_assembly_invalidated(APIAssembly::API_CORE)) { - if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_CORE)) - return; - } - - if (!FileAccess::exists(res_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll")) || - GDMono::get_singleton()->metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR)) { - if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_EDITOR)) - return; // Redundant? I don't think so - } -} - -void GodotSharpEditor::_remove_create_sln_menu_option() { - - menu_popup->remove_item(menu_popup->get_item_index(MENU_CREATE_SLN)); - - bottom_panel_btn->show(); -} - -void GodotSharpEditor::_show_about_dialog() { - - bool show_on_start = EDITOR_GET("mono/editor/show_info_on_start"); - about_dialog_checkbox->set_pressed(show_on_start); - about_dialog->popup_centered_minsize(); -} - -void GodotSharpEditor::_toggle_about_dialog_on_start(bool p_enabled) { - - bool show_on_start = EDITOR_GET("mono/editor/show_info_on_start"); - if (show_on_start != p_enabled) { - EditorSettings::get_singleton()->set_setting("mono/editor/show_info_on_start", p_enabled); - } -} - -void GodotSharpEditor::_build_solution_pressed() { - - if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path())) { - if (!_create_project_solution()) - return; // Failed to create solution - } - - MonoBottomPanel::get_singleton()->call("_build_project_pressed"); -} - -void GodotSharpEditor::_menu_option_pressed(int p_id) { - - switch (p_id) { - case MENU_CREATE_SLN: { - - _create_project_solution(); - } break; - case MENU_ABOUT_CSHARP: { - - _show_about_dialog(); - } break; - default: - ERR_FAIL(); - } -} - -void GodotSharpEditor::_notification(int p_notification) { - - switch (p_notification) { - - case NOTIFICATION_READY: { - - bool show_info_dialog = EDITOR_GET("mono/editor/show_info_on_start"); - if (show_info_dialog) { - about_dialog->set_exclusive(true); - _show_about_dialog(); - // Once shown a first time, it can be seen again via the Mono menu - it doesn't have to be exclusive then. - about_dialog->set_exclusive(false); - } - } - } -} - -void GodotSharpEditor::_bind_methods() { - - ClassDB::bind_method(D_METHOD("_build_solution_pressed"), &GodotSharpEditor::_build_solution_pressed); - ClassDB::bind_method(D_METHOD("_create_project_solution"), &GodotSharpEditor::_create_project_solution); - ClassDB::bind_method(D_METHOD("_make_api_solutions_if_needed"), &GodotSharpEditor::_make_api_solutions_if_needed); - ClassDB::bind_method(D_METHOD("_remove_create_sln_menu_option"), &GodotSharpEditor::_remove_create_sln_menu_option); - ClassDB::bind_method(D_METHOD("_toggle_about_dialog_on_start"), &GodotSharpEditor::_toggle_about_dialog_on_start); - ClassDB::bind_method(D_METHOD("_menu_option_pressed", "id"), &GodotSharpEditor::_menu_option_pressed); -} - -MonoBoolean godot_icall_MonoDevelopInstance_IsApplicationBundleInstalled(MonoString *p_bundle_id) { -#ifdef OSX_ENABLED - return (MonoBoolean)osx_is_app_bundle_installed(GDMonoMarshal::mono_string_to_godot(p_bundle_id)); -#else - (void)p_bundle_id; // UNUSED - ERR_FAIL_V(false); -#endif -} - -MonoString *godot_icall_Utils_OS_GetPlatformName() { - return GDMonoMarshal::mono_string_from_godot(OS::get_singleton()->get_name()); -} - -void GodotSharpEditor::register_internal_calls() { - - static bool registered = false; - ERR_FAIL_COND(registered); - registered = true; - - mono_add_internal_call("GodotSharpTools.Editor.MonoDevelopInstance::IsApplicationBundleInstalled", (void *)godot_icall_MonoDevelopInstance_IsApplicationBundleInstalled); - mono_add_internal_call("GodotSharpTools.Utils.OS::GetPlatformName", (void *)godot_icall_Utils_OS_GetPlatformName); - - GodotSharpBuilds::register_internal_calls(); - GodotSharpExport::register_internal_calls(); -} - -void GodotSharpEditor::show_error_dialog(const String &p_message, const String &p_title) { - - error_dialog->set_title(p_title); - error_dialog->set_text(p_message); - error_dialog->popup_centered_minsize(); -} - -Error GodotSharpEditor::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) { - - ExternalEditor editor = ExternalEditor(int(EditorSettings::get_singleton()->get("mono/editor/external_editor"))); - - switch (editor) { - case EDITOR_VSCODE: { - static String vscode_path; - - if (vscode_path.empty() || !FileAccess::exists(vscode_path)) { - // Try to search it again if it wasn't found last time or if it was removed from its location - bool found = false; - - // TODO: Use initializer lists once C++11 is allowed - - static Vector<String> vscode_names; - if (vscode_names.empty()) { - vscode_names.push_back("code"); - vscode_names.push_back("code-oss"); - vscode_names.push_back("vscode"); - vscode_names.push_back("vscode-oss"); - vscode_names.push_back("visual-studio-code"); - vscode_names.push_back("visual-studio-code-oss"); - } - for (int i = 0; i < vscode_names.size(); i++) { - vscode_path = path_which(vscode_names[i]); - if (!vscode_path.empty()) { - found = true; - break; - } - } - - if (!found) - vscode_path.clear(); // Not found, clear so next time the empty() check is enough - } - - List<String> args; - -#ifdef OSX_ENABLED - // The package path is '/Applications/Visual Studio Code.app' - static const String vscode_bundle_id = "com.microsoft.VSCode"; - static bool osx_app_bundle_installed = osx_is_app_bundle_installed(vscode_bundle_id); - - if (osx_app_bundle_installed) { - args.push_back("-b"); - args.push_back(vscode_bundle_id); - - // The reusing of existing windows made by the 'open' command might not choose a wubdiw that is - // editing our folder. It's better to ask for a new window and let VSCode do the window management. - args.push_back("-n"); - - // The open process must wait until the application finishes (which is instant in VSCode's case) - args.push_back("--wait-apps"); - - args.push_back("--args"); - } -#endif - - args.push_back(ProjectSettings::get_singleton()->get_resource_path()); - - String script_path = ProjectSettings::get_singleton()->globalize_path(p_script->get_path()); - - if (p_line >= 0) { - args.push_back("-g"); - args.push_back(script_path + ":" + itos(p_line + 1) + ":" + itos(p_col)); - } else { - args.push_back(script_path); - } - -#ifdef OSX_ENABLED - ERR_EXPLAIN("Cannot find code editor: VSCode"); - ERR_FAIL_COND_V(!osx_app_bundle_installed && vscode_path.empty(), ERR_FILE_NOT_FOUND); - - String command = osx_app_bundle_installed ? "/usr/bin/open" : vscode_path; -#else - ERR_EXPLAIN("Cannot find code editor: VSCode"); - ERR_FAIL_COND_V(vscode_path.empty(), ERR_FILE_NOT_FOUND); - - String command = vscode_path; -#endif - - Error err = OS::get_singleton()->execute(command, args, false); - - if (err != OK) { - ERR_PRINT("Error when trying to execute code editor: VSCode"); - return err; - } - } break; -#ifdef OSX_ENABLED - case EDITOR_VISUALSTUDIO_MAC: - // [[fallthrough]]; -#endif - case EDITOR_MONODEVELOP: { -#ifdef OSX_ENABLED - bool is_visualstudio = editor == EDITOR_VISUALSTUDIO_MAC; - - MonoDevelopInstance **instance = is_visualstudio ? - &visualstudio_mac_instance : - &monodevelop_instance; - - MonoDevelopInstance::EditorId editor_id = is_visualstudio ? - MonoDevelopInstance::VISUALSTUDIO_FOR_MAC : - MonoDevelopInstance::MONODEVELOP; -#else - MonoDevelopInstance **instance = &monodevelop_instance; - MonoDevelopInstance::EditorId editor_id = MonoDevelopInstance::MONODEVELOP; -#endif - - if (!*instance) - *instance = memnew(MonoDevelopInstance(GodotSharpDirs::get_project_sln_path(), editor_id)); - - String script_path = ProjectSettings::get_singleton()->globalize_path(p_script->get_path()); - - if (p_line >= 0) { - script_path += ";" + itos(p_line + 1) + ";" + itos(p_col); - } - - (*instance)->execute(script_path); - } break; - default: - return ERR_UNAVAILABLE; - } - - return OK; -} - -bool GodotSharpEditor::overrides_external_editor() { - - return ExternalEditor(int(EditorSettings::get_singleton()->get("mono/editor/external_editor"))) != EDITOR_NONE; -} - -GodotSharpEditor::GodotSharpEditor(EditorNode *p_editor) { - - singleton = this; - - monodevelop_instance = NULL; -#ifdef OSX_ENABLED - visualstudio_mac_instance = NULL; -#endif - - editor = p_editor; - - error_dialog = memnew(AcceptDialog); - editor->get_gui_base()->add_child(error_dialog); - - bottom_panel_btn = editor->add_bottom_panel_item(TTR("Mono"), memnew(MonoBottomPanel(editor))); - - godotsharp_builds = memnew(GodotSharpBuilds); - - editor->add_child(memnew(MonoReloadNode)); - - menu_popup = memnew(PopupMenu); - menu_popup->hide(); - menu_popup->set_as_toplevel(true); - menu_popup->set_pass_on_modal_close_click(false); - - editor->add_tool_submenu_item("Mono", menu_popup); - - // TODO: Remove or edit this info dialog once Mono support is no longer in alpha - { - menu_popup->add_item(TTR("About C# support"), MENU_ABOUT_CSHARP); - about_dialog = memnew(AcceptDialog); - editor->get_gui_base()->add_child(about_dialog); - about_dialog->set_title("Important: C# support is not feature-complete"); - - // We don't use set_text() as the default AcceptDialog Label doesn't play well with the TextureRect and CheckBox - // we'll add. Instead we add containers and a new autowrapped Label inside. - - // Main VBoxContainer (icon + label on top, checkbox at bottom) - VBoxContainer *about_vbc = memnew(VBoxContainer); - about_dialog->add_child(about_vbc); - - // HBoxContainer for icon + label - HBoxContainer *about_hbc = memnew(HBoxContainer); - about_vbc->add_child(about_hbc); - - TextureRect *about_icon = memnew(TextureRect); - about_hbc->add_child(about_icon); - Ref<Texture> about_icon_tex = about_icon->get_icon("NodeWarning", "EditorIcons"); - about_icon->set_texture(about_icon_tex); - - Label *about_label = memnew(Label); - about_hbc->add_child(about_label); - about_label->set_custom_minimum_size(Size2(600, 150) * EDSCALE); - about_label->set_v_size_flags(Control::SIZE_EXPAND_FILL); - about_label->set_autowrap(true); - String about_text = - String("C# support in Godot Engine is in late alpha stage and, while already usable, ") + - "it is not meant for use in production.\n\n" + - "Projects can be exported to Linux, macOS and Windows, but not yet to mobile or web platforms. " + - "Bugs and usability issues will be addressed gradually over future releases, " + - "potentially including compatibility breaking changes as new features are implemented for a better overall C# experience.\n\n" + - "If you experience issues with this Mono build, please report them on Godot's issue tracker with details about your system, MSBuild version, IDE, etc.:\n\n" + - " https://github.com/godotengine/godot/issues\n\n" + - "Your critical feedback at this stage will play a great role in shaping the C# support in future releases, so thank you!"; - about_label->set_text(about_text); - - EDITOR_DEF("mono/editor/show_info_on_start", true); - - // CheckBox in main container - about_dialog_checkbox = memnew(CheckBox); - about_vbc->add_child(about_dialog_checkbox); - about_dialog_checkbox->set_text("Show this warning when starting the editor"); - about_dialog_checkbox->connect("toggled", this, "_toggle_about_dialog_on_start"); - } - - String sln_path = GodotSharpDirs::get_project_sln_path(); - String csproj_path = GodotSharpDirs::get_project_csproj_path(); - - if (FileAccess::exists(sln_path) && FileAccess::exists(csproj_path)) { - // Defer this task because EditorProgress calls Main::iterarion() and the main loop is not yet initialized. - call_deferred("_make_api_solutions_if_needed"); - } else { - bottom_panel_btn->hide(); - menu_popup->add_item(TTR("Create C# solution"), MENU_CREATE_SLN); - } - - menu_popup->connect("id_pressed", this, "_menu_option_pressed"); - - ToolButton *build_button = memnew(ToolButton); - build_button->set_text("Build"); - build_button->set_tooltip("Build solution"); - build_button->set_focus_mode(Control::FOCUS_NONE); - build_button->connect("pressed", this, "_build_solution_pressed"); - editor->get_menu_hb()->add_child(build_button); - - // External editor settings - EditorSettings *ed_settings = EditorSettings::get_singleton(); - EDITOR_DEF("mono/editor/external_editor", EDITOR_NONE); - - String settings_hint_str = "Disabled"; - -#ifdef WINDOWS_ENABLED - settings_hint_str += ",MonoDevelop,Visual Studio Code"; -#elif OSX_ENABLED - settings_hint_str += ",Visual Studio,MonoDevelop,Visual Studio Code"; -#elif UNIX_ENABLED - settings_hint_str += ",MonoDevelop,Visual Studio Code"; -#endif - - ed_settings->add_property_hint(PropertyInfo(Variant::INT, "mono/editor/external_editor", PROPERTY_HINT_ENUM, settings_hint_str)); - - // Export plugin - Ref<GodotSharpExport> godotsharp_export; - godotsharp_export.instance(); - EditorExport::get_singleton()->add_export_plugin(godotsharp_export); -} - -GodotSharpEditor::~GodotSharpEditor() { - - singleton = NULL; - - memdelete(godotsharp_builds); - - if (monodevelop_instance) { - memdelete(monodevelop_instance); - monodevelop_instance = NULL; - } -} - -MonoReloadNode *MonoReloadNode::singleton = NULL; - -void MonoReloadNode::_reload_timer_timeout() { - - if (CSharpLanguage::get_singleton()->is_assembly_reloading_needed()) { - CSharpLanguage::get_singleton()->reload_assemblies(false); - } -} - -void MonoReloadNode::restart_reload_timer() { - - reload_timer->stop(); - reload_timer->start(); -} - -void MonoReloadNode::_bind_methods() { - - ClassDB::bind_method(D_METHOD("_reload_timer_timeout"), &MonoReloadNode::_reload_timer_timeout); -} - -void MonoReloadNode::_notification(int p_what) { - switch (p_what) { - case MainLoop::NOTIFICATION_WM_FOCUS_IN: { - restart_reload_timer(); - if (CSharpLanguage::get_singleton()->is_assembly_reloading_needed()) { - CSharpLanguage::get_singleton()->reload_assemblies(false); - } - } break; - default: { - } break; - }; -} - -MonoReloadNode::MonoReloadNode() { - - singleton = this; - - reload_timer = memnew(Timer); - add_child(reload_timer); - reload_timer->set_one_shot(false); - reload_timer->set_wait_time(EDITOR_DEF("mono/assembly_watch_interval_sec", 0.5)); - reload_timer->connect("timeout", this, "_reload_timer_timeout"); - reload_timer->start(); -} - -MonoReloadNode::~MonoReloadNode() { - - singleton = NULL; -} diff --git a/modules/mono/editor/godotsharp_export.cpp b/modules/mono/editor/godotsharp_export.cpp index ee5fed1a0c..e02bd3be58 100644 --- a/modules/mono/editor/godotsharp_export.cpp +++ b/modules/mono/editor/godotsharp_export.cpp @@ -30,164 +30,33 @@ #include "godotsharp_export.h" -#include "core/version.h" - -#include "../csharp_script.h" -#include "../godotsharp_defs.h" -#include "../godotsharp_dirs.h" -#include "../mono_gd/gd_mono_class.h" -#include "../mono_gd/gd_mono_marshal.h" -#include "csharp_project.h" -#include "godotsharp_builds.h" - -static MonoString *godot_icall_GodotSharpExport_GetTemplatesDir() { - String current_version = VERSION_FULL_CONFIG; - String templates_dir = EditorSettings::get_singleton()->get_templates_dir().plus_file(current_version); - return GDMonoMarshal::mono_string_from_godot(ProjectSettings::get_singleton()->globalize_path(templates_dir)); -} - -static MonoString *godot_icall_GodotSharpExport_GetDataDirName() { - String appname = ProjectSettings::get_singleton()->get("application/config/name"); - String appname_safe = OS::get_singleton()->get_safe_dir_name(appname); - return GDMonoMarshal::mono_string_from_godot("data_" + appname_safe); -} - -void GodotSharpExport::register_internal_calls() { - static bool registered = false; - ERR_FAIL_COND(registered); - registered = true; - - mono_add_internal_call("GodotSharpTools.Editor.GodotSharpExport::GetTemplatesDir", (void *)godot_icall_GodotSharpExport_GetTemplatesDir); - mono_add_internal_call("GodotSharpTools.Editor.GodotSharpExport::GetDataDirName", (void *)godot_icall_GodotSharpExport_GetDataDirName); -} - -void GodotSharpExport::_export_file(const String &p_path, const String &p_type, const Set<String> &) { - - if (p_type != CSharpLanguage::get_singleton()->get_type()) - return; - - ERR_FAIL_COND(p_path.get_extension() != CSharpLanguage::get_singleton()->get_extension()); - - // TODO what if the source file is not part of the game's C# project - - if (!GLOBAL_GET("mono/export/include_scripts_content")) { - // We don't want to include the source code on exported games - add_file(p_path, Vector<uint8_t>(), false); - skip(); - } -} - -void GodotSharpExport::_export_begin(const Set<String> &p_features, bool p_debug, const String &p_path, int p_flags) { - - // TODO right now there is no way to stop the export process with an error - - ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized()); - ERR_FAIL_NULL(TOOLS_DOMAIN); - ERR_FAIL_NULL(GDMono::get_singleton()->get_editor_tools_assembly()); - - if (FileAccess::exists(GodotSharpDirs::get_project_sln_path())) { - String build_config = p_debug ? "Debug" : "Release"; - - String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata." + String(p_debug ? "debug" : "release")); - Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path); - ERR_FAIL_COND(metadata_err != OK); - - ERR_FAIL_COND(!_add_file(scripts_metadata_path, scripts_metadata_path)); - - ERR_FAIL_COND(!GodotSharpBuilds::build_project_blocking(build_config)); - - // Add dependency assemblies - - Map<String, String> dependencies; - - String project_dll_name = ProjectSettings::get_singleton()->get("application/config/name"); - if (project_dll_name.empty()) { - project_dll_name = "UnnamedProject"; - } - - String project_dll_src_dir = GodotSharpDirs::get_res_temp_assemblies_base_dir().plus_file(build_config); - String project_dll_src_path = project_dll_src_dir.plus_file(project_dll_name + ".dll"); - dependencies.insert(project_dll_name, project_dll_src_path); - - { - MonoDomain *export_domain = GDMonoUtils::create_domain("GodotEngine.ProjectExportDomain"); - ERR_FAIL_NULL(export_domain); - _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(export_domain); - - _GDMONO_SCOPE_DOMAIN_(export_domain); - - GDMonoAssembly *scripts_assembly = NULL; - bool load_success = GDMono::get_singleton()->load_assembly_from(project_dll_name, - project_dll_src_path, &scripts_assembly, /* refonly: */ true); +#include <mono/metadata/image.h> - ERR_EXPLAIN("Cannot load refonly assembly: " + project_dll_name); - ERR_FAIL_COND(!load_success); +#include "core/os/os.h" - Vector<String> search_dirs; - GDMonoAssembly::fill_search_dirs(search_dirs, build_config); - Error depend_error = _get_assembly_dependencies(scripts_assembly, search_dirs, dependencies); - ERR_FAIL_COND(depend_error != OK); - } - - for (Map<String, String>::Element *E = dependencies.front(); E; E = E->next()) { - String depend_src_path = E->value(); - String depend_dst_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(depend_src_path.get_file()); - ERR_FAIL_COND(!_add_file(depend_src_path, depend_dst_path)); - } - } - - // Mono specific export template extras (data dir) - - GDMonoClass *export_class = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Editor", "GodotSharpExport"); - ERR_FAIL_NULL(export_class); - GDMonoMethod *export_begin_method = export_class->get_method("_ExportBegin", 4); - ERR_FAIL_NULL(export_begin_method); - - MonoArray *features = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(String), p_features.size()); - int i = 0; - for (const Set<String>::Element *E = p_features.front(); E; E = E->next()) { - MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E->get()); - mono_array_set(features, MonoString *, i, boxed); - i++; - } - - MonoBoolean debug = p_debug; - MonoString *path = GDMonoMarshal::mono_string_from_godot(p_path); - uint32_t flags = p_flags; - void *args[4] = { features, &debug, path, &flags }; - MonoException *exc = NULL; - export_begin_method->invoke_raw(NULL, args, &exc); +#include "../mono_gd/gd_mono.h" +#include "../mono_gd/gd_mono_assembly.h" +#include "../mono_gd/gd_mono_cache.h" - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - ERR_FAIL(); - } -} +namespace GodotSharpExport { -bool GodotSharpExport::_add_file(const String &p_src_path, const String &p_dst_path, bool p_remap) { +String get_assemblyref_name(MonoImage *p_image, int index) { + const MonoTableInfo *table_info = mono_image_get_table_info(p_image, MONO_TABLE_ASSEMBLYREF); - FileAccessRef f = FileAccess::open(p_src_path, FileAccess::READ); - ERR_FAIL_COND_V(!f, false); + uint32_t cols[MONO_ASSEMBLYREF_SIZE]; - Vector<uint8_t> data; - data.resize(f->get_len()); - f->get_buffer(data.ptrw(), data.size()); + mono_metadata_decode_row(table_info, index, cols, MONO_ASSEMBLYREF_SIZE); - add_file(p_dst_path, data, p_remap); - - return true; + return String::utf8(mono_metadata_string_heap(p_image, cols[MONO_ASSEMBLYREF_NAME])); } -Error GodotSharpExport::_get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Map<String, String> &r_dependencies) { - +Error get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Dictionary &r_dependencies) { MonoImage *image = p_assembly->get_image(); for (int i = 0; i < mono_image_get_table_rows(image, MONO_TABLE_ASSEMBLYREF); i++) { - MonoAssemblyName *ref_aname = aname_prealloc; - mono_assembly_get_assemblyref(image, i, ref_aname); - String ref_name = mono_assembly_name_get_name(ref_aname); + String ref_name = get_assemblyref_name(image, i); - if (r_dependencies.find(ref_name)) + if (r_dependencies.has(ref_name)) continue; GDMonoAssembly *ref_assembly = NULL; @@ -221,29 +90,43 @@ Error GodotSharpExport::_get_assembly_dependencies(GDMonoAssembly *p_assembly, c } } - if (!ref_assembly) { - ERR_EXPLAIN("Cannot load assembly (refonly): " + ref_name); - ERR_FAIL_V(ERR_CANT_RESOLVE); - } + ERR_FAIL_COND_V_MSG(!ref_assembly, ERR_CANT_RESOLVE, "Cannot load assembly (refonly): '" + ref_name + "'."); - r_dependencies.insert(ref_name, ref_assembly->get_path()); + r_dependencies[ref_name] = ref_assembly->get_path(); - Error err = _get_assembly_dependencies(ref_assembly, p_search_dirs, r_dependencies); - if (err != OK) - return err; + Error err = get_assembly_dependencies(ref_assembly, p_search_dirs, r_dependencies); + ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot load one of the dependencies for the assembly: '" + ref_name + "'."); } return OK; } -GodotSharpExport::GodotSharpExport() { - // MonoAssemblyName is an incomplete type (internal to mono), so we can't allocate it ourselves. - // There isn't any api to allocate an empty one either, so we need to do it this way. - aname_prealloc = mono_assembly_name_new("whatever"); - mono_assembly_name_free(aname_prealloc); // "it does not frees the object itself, only the name members" (typo included) -} +Error get_exported_assembly_dependencies(const Dictionary &p_initial_dependencies, + const String &p_build_config, const String &p_custom_bcl_dir, Dictionary &r_dependencies) { + MonoDomain *export_domain = GDMonoUtils::create_domain("GodotEngine.Domain.ProjectExport"); + ERR_FAIL_NULL_V(export_domain, FAILED); + _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(export_domain); + + _GDMONO_SCOPE_DOMAIN_(export_domain); + + Vector<String> search_dirs; + GDMonoAssembly::fill_search_dirs(search_dirs, p_build_config, p_custom_bcl_dir); + + for (const Variant *key = p_initial_dependencies.next(); key; key = p_initial_dependencies.next(key)) { + String assembly_name = *key; + String assembly_path = p_initial_dependencies[*key]; + + GDMonoAssembly *assembly = NULL; + bool load_success = GDMono::get_singleton()->load_assembly_from(assembly_name, assembly_path, &assembly, /* refonly: */ true); -GodotSharpExport::~GodotSharpExport() { - if (aname_prealloc) - mono_free(aname_prealloc); + ERR_FAIL_COND_V_MSG(!load_success, ERR_CANT_RESOLVE, "Cannot load assembly (refonly): '" + assembly_name + "'."); + + Error err = get_assembly_dependencies(assembly, search_dirs, r_dependencies); + if (err != OK) + return err; + } + + return OK; } + +} // namespace GodotSharpExport diff --git a/modules/mono/editor/godotsharp_export.h b/modules/mono/editor/godotsharp_export.h index 4dc8ea75d5..8eb5a4d9dc 100644 --- a/modules/mono/editor/godotsharp_export.h +++ b/modules/mono/editor/godotsharp_export.h @@ -31,29 +31,19 @@ #ifndef GODOTSHARP_EXPORT_H #define GODOTSHARP_EXPORT_H -#include <mono/metadata/image.h> - -#include "editor/editor_export.h" +#include "core/dictionary.h" +#include "core/error_list.h" +#include "core/ustring.h" #include "../mono_gd/gd_mono_header.h" -class GodotSharpExport : public EditorExportPlugin { - - MonoAssemblyName *aname_prealloc; - - bool _add_file(const String &p_src_path, const String &p_dst_path, bool p_remap = false); - - Error _get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Map<String, String> &r_dependencies); +namespace GodotSharpExport { -protected: - virtual void _export_file(const String &p_path, const String &p_type, const Set<String> &p_features); - virtual void _export_begin(const Set<String> &p_features, bool p_debug, const String &p_path, int p_flags); +Error get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Dictionary &r_dependencies); -public: - static void register_internal_calls(); +Error get_exported_assembly_dependencies(const Dictionary &p_initial_dependencies, + const String &p_build_config, const String &p_custom_lib_dir, Dictionary &r_dependencies); - GodotSharpExport(); - ~GodotSharpExport(); -}; +} // namespace GodotSharpExport #endif // GODOTSHARP_EXPORT_H diff --git a/modules/mono/editor/mono_bottom_panel.cpp b/modules/mono/editor/mono_bottom_panel.cpp deleted file mode 100644 index 21ce9ca5c4..0000000000 --- a/modules/mono/editor/mono_bottom_panel.cpp +++ /dev/null @@ -1,525 +0,0 @@ -/*************************************************************************/ -/* mono_bottom_panel.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 "mono_bottom_panel.h" - -#include "editor/plugins/script_editor_plugin.h" -#include "editor/script_editor_debugger.h" - -#include "../csharp_script.h" -#include "../godotsharp_dirs.h" -#include "csharp_project.h" -#include "godotsharp_editor.h" - -MonoBottomPanel *MonoBottomPanel::singleton = NULL; - -void MonoBottomPanel::_update_build_tabs_list() { - - build_tabs_list->clear(); - - int current_tab = build_tabs->get_current_tab(); - - bool no_current_tab = current_tab < 0 || current_tab >= build_tabs->get_tab_count(); - - for (int i = 0; i < build_tabs->get_child_count(); i++) { - - MonoBuildTab *tab = Object::cast_to<MonoBuildTab>(build_tabs->get_child(i)); - - if (tab) { - String item_name = tab->build_info.solution.get_file().get_basename(); - item_name += " [" + tab->build_info.configuration + "]"; - - build_tabs_list->add_item(item_name, tab->get_icon_texture()); - - String item_tooltip = "Solution: " + tab->build_info.solution; - item_tooltip += "\nConfiguration: " + tab->build_info.configuration; - item_tooltip += "\nStatus: "; - - if (tab->build_exited) { - item_tooltip += tab->build_result == MonoBuildTab::RESULT_SUCCESS ? "Succeeded" : "Errored"; - } else { - item_tooltip += "Running"; - } - - if (!tab->build_exited || tab->build_result == MonoBuildTab::RESULT_ERROR) { - item_tooltip += "\nErrors: " + itos(tab->error_count); - } - - item_tooltip += "\nWarnings: " + itos(tab->warning_count); - - build_tabs_list->set_item_tooltip(i, item_tooltip); - - if (no_current_tab || current_tab == i) { - build_tabs_list->select(i); - _build_tabs_item_selected(i); - } - } - } -} - -void MonoBottomPanel::add_build_tab(MonoBuildTab *p_build_tab) { - - build_tabs->add_child(p_build_tab); - raise_build_tab(p_build_tab); -} - -void MonoBottomPanel::raise_build_tab(MonoBuildTab *p_build_tab) { - - ERR_FAIL_COND(p_build_tab->get_parent() != build_tabs); - build_tabs->move_child(p_build_tab, 0); - _update_build_tabs_list(); -} - -void MonoBottomPanel::show_build_tab() { - - for (int i = 0; i < panel_tabs->get_tab_count(); i++) { - if (panel_tabs->get_tab_control(i) == panel_builds_tab) { - panel_tabs->set_current_tab(i); - editor->make_bottom_panel_item_visible(this); - return; - } - } - - ERR_PRINT("Builds tab not found"); -} - -void MonoBottomPanel::_build_tabs_item_selected(int p_idx) { - - ERR_FAIL_INDEX(p_idx, build_tabs->get_tab_count()); - - build_tabs->set_current_tab(p_idx); - if (!build_tabs->is_visible()) - build_tabs->set_visible(true); - - warnings_btn->set_visible(true); - errors_btn->set_visible(true); - view_log_btn->set_visible(true); -} - -void MonoBottomPanel::_build_tabs_nothing_selected() { - - if (build_tabs->get_tab_count() != 0) { // just in case - build_tabs->set_visible(false); - - // This callback is called when clicking on the empty space of the list. - // ItemList won't deselect the items automatically, so we must do it ourselves. - build_tabs_list->unselect_all(); - } - - warnings_btn->set_visible(false); - errors_btn->set_visible(false); - view_log_btn->set_visible(false); -} - -void MonoBottomPanel::_warnings_toggled(bool p_pressed) { - - int current_tab = build_tabs->get_current_tab(); - ERR_FAIL_INDEX(current_tab, build_tabs->get_tab_count()); - MonoBuildTab *build_tab = Object::cast_to<MonoBuildTab>(build_tabs->get_child(current_tab)); - build_tab->warnings_visible = p_pressed; - build_tab->_update_issues_list(); -} - -void MonoBottomPanel::_errors_toggled(bool p_pressed) { - - int current_tab = build_tabs->get_current_tab(); - ERR_FAIL_INDEX(current_tab, build_tabs->get_tab_count()); - MonoBuildTab *build_tab = Object::cast_to<MonoBuildTab>(build_tabs->get_child(current_tab)); - build_tab->errors_visible = p_pressed; - build_tab->_update_issues_list(); -} - -void MonoBottomPanel::_build_project_pressed() { - - if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path())) - return; // No solution to build - - String scripts_metadata_path_editor = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor"); - String scripts_metadata_path_player = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor_player"); - - Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path_editor); - ERR_FAIL_COND(metadata_err != OK); - - if (FileAccess::exists(scripts_metadata_path_editor)) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); - Error copy_err = da->copy(scripts_metadata_path_editor, scripts_metadata_path_player); - - ERR_EXPLAIN("Failed to copy scripts metadata file"); - ERR_FAIL_COND(copy_err != OK); - } - - bool build_success = GodotSharpBuilds::get_singleton()->build_project_blocking("Tools"); - - if (build_success) { - // Notify running game for hot-reload - ScriptEditor::get_singleton()->get_debugger()->reload_scripts(); - - // Hot-reload in the editor - MonoReloadNode::get_singleton()->restart_reload_timer(); - - if (CSharpLanguage::get_singleton()->is_assembly_reloading_needed()) { - CSharpLanguage::get_singleton()->reload_assemblies(false); - } - } -} - -void MonoBottomPanel::_view_log_pressed() { - - if (build_tabs_list->is_anything_selected()) { - Vector<int> selected_items = build_tabs_list->get_selected_items(); - CRASH_COND(selected_items.size() != 1); - int selected_item = selected_items[0]; - - MonoBuildTab *build_tab = Object::cast_to<MonoBuildTab>(build_tabs->get_tab_control(selected_item)); - ERR_FAIL_NULL(build_tab); - - String log_dirpath = build_tab->get_build_info().get_log_dirpath(); - - OS::get_singleton()->shell_open(log_dirpath.plus_file(GodotSharpBuilds::get_msbuild_log_filename())); - } -} - -void MonoBottomPanel::_notification(int p_what) { - - switch (p_what) { - - case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { - panel_tabs->add_style_override("panel", editor->get_gui_base()->get_stylebox("DebuggerPanel", "EditorStyles")); - panel_tabs->add_style_override("tab_fg", editor->get_gui_base()->get_stylebox("DebuggerTabFG", "EditorStyles")); - panel_tabs->add_style_override("tab_bg", editor->get_gui_base()->get_stylebox("DebuggerTabBG", "EditorStyles")); - } break; - } -} - -void MonoBottomPanel::_bind_methods() { - - ClassDB::bind_method(D_METHOD("_build_project_pressed"), &MonoBottomPanel::_build_project_pressed); - ClassDB::bind_method(D_METHOD("_view_log_pressed"), &MonoBottomPanel::_view_log_pressed); - ClassDB::bind_method(D_METHOD("_warnings_toggled", "pressed"), &MonoBottomPanel::_warnings_toggled); - ClassDB::bind_method(D_METHOD("_errors_toggled", "pressed"), &MonoBottomPanel::_errors_toggled); - ClassDB::bind_method(D_METHOD("_build_tabs_item_selected", "idx"), &MonoBottomPanel::_build_tabs_item_selected); - ClassDB::bind_method(D_METHOD("_build_tabs_nothing_selected"), &MonoBottomPanel::_build_tabs_nothing_selected); -} - -MonoBottomPanel::MonoBottomPanel(EditorNode *p_editor) { - - singleton = this; - - editor = p_editor; - - set_v_size_flags(SIZE_EXPAND_FILL); - set_anchors_and_margins_preset(Control::PRESET_WIDE); - - panel_tabs = memnew(TabContainer); - panel_tabs->set_tab_align(TabContainer::ALIGN_LEFT); - panel_tabs->add_style_override("panel", editor->get_gui_base()->get_stylebox("DebuggerPanel", "EditorStyles")); - panel_tabs->add_style_override("tab_fg", editor->get_gui_base()->get_stylebox("DebuggerTabFG", "EditorStyles")); - panel_tabs->add_style_override("tab_bg", editor->get_gui_base()->get_stylebox("DebuggerTabBG", "EditorStyles")); - panel_tabs->set_custom_minimum_size(Size2(0, 228) * EDSCALE); - panel_tabs->set_v_size_flags(SIZE_EXPAND_FILL); - add_child(panel_tabs); - - { // Builds - panel_builds_tab = memnew(VBoxContainer); - panel_builds_tab->set_name(TTR("Builds")); - panel_builds_tab->set_h_size_flags(SIZE_EXPAND_FILL); - panel_tabs->add_child(panel_builds_tab); - - HBoxContainer *toolbar_hbc = memnew(HBoxContainer); - toolbar_hbc->set_h_size_flags(SIZE_EXPAND_FILL); - panel_builds_tab->add_child(toolbar_hbc); - - Button *build_project_btn = memnew(Button); - build_project_btn->set_text(TTR("Build Project")); - build_project_btn->set_focus_mode(FOCUS_NONE); - build_project_btn->connect("pressed", this, "_build_project_pressed"); - toolbar_hbc->add_child(build_project_btn); - - toolbar_hbc->add_spacer(); - - warnings_btn = memnew(ToolButton); - warnings_btn->set_text(TTR("Warnings")); - warnings_btn->set_toggle_mode(true); - warnings_btn->set_pressed(true); - warnings_btn->set_visible(false); - warnings_btn->set_focus_mode(FOCUS_NONE); - warnings_btn->connect("toggled", this, "_warnings_toggled"); - toolbar_hbc->add_child(warnings_btn); - - errors_btn = memnew(ToolButton); - errors_btn->set_text(TTR("Errors")); - errors_btn->set_toggle_mode(true); - errors_btn->set_pressed(true); - errors_btn->set_visible(false); - errors_btn->set_focus_mode(FOCUS_NONE); - errors_btn->connect("toggled", this, "_errors_toggled"); - toolbar_hbc->add_child(errors_btn); - - toolbar_hbc->add_spacer(); - - view_log_btn = memnew(Button); - view_log_btn->set_text(TTR("View log")); - view_log_btn->set_focus_mode(FOCUS_NONE); - view_log_btn->set_visible(false); - view_log_btn->connect("pressed", this, "_view_log_pressed"); - toolbar_hbc->add_child(view_log_btn); - - HSplitContainer *hsc = memnew(HSplitContainer); - hsc->set_h_size_flags(SIZE_EXPAND_FILL); - hsc->set_v_size_flags(SIZE_EXPAND_FILL); - panel_builds_tab->add_child(hsc); - - build_tabs_list = memnew(ItemList); - build_tabs_list->set_h_size_flags(SIZE_EXPAND_FILL); - build_tabs_list->connect("item_selected", this, "_build_tabs_item_selected"); - build_tabs_list->connect("nothing_selected", this, "_build_tabs_nothing_selected"); - hsc->add_child(build_tabs_list); - - build_tabs = memnew(TabContainer); - build_tabs->set_tab_align(TabContainer::ALIGN_LEFT); - build_tabs->set_h_size_flags(SIZE_EXPAND_FILL); - build_tabs->set_tabs_visible(false); - hsc->add_child(build_tabs); - } -} - -MonoBottomPanel::~MonoBottomPanel() { - - singleton = NULL; -} - -void MonoBuildTab::_load_issues_from_file(const String &p_csv_file) { - - FileAccessRef f = FileAccess::open(p_csv_file, FileAccess::READ); - - if (!f) - return; - - while (!f->eof_reached()) { - Vector<String> csv_line = f->get_csv_line(); - - if (csv_line.size() == 1 && csv_line[0].empty()) - return; - - ERR_CONTINUE(csv_line.size() != 7); - - BuildIssue issue; - issue.warning = csv_line[0] == "warning"; - issue.file = csv_line[1]; - issue.line = csv_line[2].to_int(); - issue.column = csv_line[3].to_int(); - issue.code = csv_line[4]; - issue.message = csv_line[5]; - issue.project_file = csv_line[6]; - - if (issue.warning) - warning_count += 1; - else - error_count += 1; - - issues.push_back(issue); - } -} - -void MonoBuildTab::_update_issues_list() { - - issues_list->clear(); - - Ref<Texture> warning_icon = get_icon("Warning", "EditorIcons"); - Ref<Texture> error_icon = get_icon("Error", "EditorIcons"); - - for (int i = 0; i < issues.size(); i++) { - - const BuildIssue &issue = issues[i]; - - if (!(issue.warning ? warnings_visible : errors_visible)) - continue; - - String tooltip; - tooltip += String("Message: ") + issue.message; - - if (issue.code.length()) { - tooltip += String("\nCode: ") + issue.code; - } - - tooltip += String("\nType: ") + (issue.warning ? "warning" : "error"); - - String text; - - if (issue.file.length()) { - String sline = String::num_int64(issue.line); - String scolumn = String::num_int64(issue.column); - - text += issue.file + "("; - text += sline + ","; - text += scolumn + "): "; - - tooltip += "\nFile: " + issue.file; - tooltip += "\nLine: " + sline; - tooltip += "\nColumn: " + scolumn; - } - - if (issue.project_file.length()) { - tooltip += "\nProject: " + issue.project_file; - } - - text += issue.message; - - int line_break_idx = text.find("\n"); - issues_list->add_item(line_break_idx == -1 ? text : text.substr(0, line_break_idx), - issue.warning ? warning_icon : error_icon); - int index = issues_list->get_item_count() - 1; - issues_list->set_item_tooltip(index, tooltip); - issues_list->set_item_metadata(index, i); - } -} - -Ref<Texture> MonoBuildTab::get_icon_texture() const { - - if (build_exited) { - if (build_result == RESULT_ERROR) { - return get_icon("StatusError", "EditorIcons"); - } else { - return get_icon("StatusSuccess", "EditorIcons"); - } - } else { - return get_icon("Stop", "EditorIcons"); - } -} - -MonoBuildInfo MonoBuildTab::get_build_info() { - - return build_info; -} - -void MonoBuildTab::on_build_start() { - - build_exited = false; - - issues.clear(); - warning_count = 0; - error_count = 0; - _update_issues_list(); - - MonoBottomPanel::get_singleton()->raise_build_tab(this); -} - -void MonoBuildTab::on_build_exit(BuildResult result) { - - build_exited = true; - build_result = result; - - _load_issues_from_file(logs_dir.plus_file(GodotSharpBuilds::get_msbuild_issues_filename())); - _update_issues_list(); - - MonoBottomPanel::get_singleton()->raise_build_tab(this); -} - -void MonoBuildTab::on_build_exec_failed(const String &p_cause) { - - build_exited = true; - build_result = RESULT_ERROR; - - issues_list->clear(); - - BuildIssue issue; - issue.message = p_cause; - issue.warning = false; - - error_count += 1; - issues.push_back(issue); - - _update_issues_list(); - - MonoBottomPanel::get_singleton()->raise_build_tab(this); -} - -void MonoBuildTab::restart_build() { - - ERR_FAIL_COND(!build_exited); - GodotSharpBuilds::get_singleton()->restart_build(this); -} - -void MonoBuildTab::stop_build() { - - ERR_FAIL_COND(build_exited); - GodotSharpBuilds::get_singleton()->stop_build(this); -} - -void MonoBuildTab::_issue_activated(int p_idx) { - - ERR_FAIL_INDEX(p_idx, issues_list->get_item_count()); - - // Get correct issue idx from issue list - int issue_idx = this->issues_list->get_item_metadata(p_idx); - - ERR_FAIL_INDEX(issue_idx, issues.size()); - - const BuildIssue &issue = issues[issue_idx]; - - if (issue.project_file.empty() && issue.file.empty()) - return; - - String project_dir = issue.project_file.length() ? issue.project_file.get_base_dir() : build_info.solution.get_base_dir(); - - String file = project_dir.simplify_path().plus_file(issue.file.simplify_path()); - - if (!FileAccess::exists(file)) - return; - - file = ProjectSettings::get_singleton()->localize_path(file); - - if (file.begins_with("res://")) { - Ref<Script> script = ResourceLoader::load(file, CSharpLanguage::get_singleton()->get_type()); - - if (script.is_valid() && ScriptEditor::get_singleton()->edit(script, issue.line, issue.column)) { - EditorNode::get_singleton()->call("_editor_select", EditorNode::EDITOR_SCRIPT); - } - } -} - -void MonoBuildTab::_bind_methods() { - - ClassDB::bind_method("_issue_activated", &MonoBuildTab::_issue_activated); -} - -MonoBuildTab::MonoBuildTab(const MonoBuildInfo &p_build_info, const String &p_logs_dir) : - build_exited(false), - issues_list(memnew(ItemList)), - error_count(0), - warning_count(0), - errors_visible(true), - warnings_visible(true), - logs_dir(p_logs_dir), - build_info(p_build_info) { - issues_list->set_v_size_flags(SIZE_EXPAND_FILL); - issues_list->connect("item_activated", this, "_issue_activated"); - add_child(issues_list); -} diff --git a/modules/mono/editor/mono_bottom_panel.h b/modules/mono/editor/mono_bottom_panel.h deleted file mode 100644 index 406e46f7ce..0000000000 --- a/modules/mono/editor/mono_bottom_panel.h +++ /dev/null @@ -1,150 +0,0 @@ -/*************************************************************************/ -/* mono_bottom_panel.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 MONO_BOTTOM_PANEL_H -#define MONO_BOTTOM_PANEL_H - -#include "editor/editor_node.h" -#include "scene/gui/control.h" - -#include "mono_build_info.h" - -class MonoBuildTab; - -class MonoBottomPanel : public VBoxContainer { - - GDCLASS(MonoBottomPanel, VBoxContainer) - - EditorNode *editor; - - TabContainer *panel_tabs; - - VBoxContainer *panel_builds_tab; - - ItemList *build_tabs_list; - TabContainer *build_tabs; - - ToolButton *warnings_btn; - ToolButton *errors_btn; - Button *view_log_btn; - - void _update_build_tabs_list(); - - void _build_tabs_item_selected(int p_idx); - void _build_tabs_nothing_selected(); - - void _warnings_toggled(bool p_pressed); - void _errors_toggled(bool p_pressed); - - void _build_project_pressed(); - void _view_log_pressed(); - - static MonoBottomPanel *singleton; - -protected: - void _notification(int p_what); - - static void _bind_methods(); - -public: - _FORCE_INLINE_ static MonoBottomPanel *get_singleton() { return singleton; } - - void add_build_tab(MonoBuildTab *p_build_tab); - void raise_build_tab(MonoBuildTab *p_build_tab); - - void show_build_tab(); - - MonoBottomPanel(EditorNode *p_editor = NULL); - ~MonoBottomPanel(); -}; - -class MonoBuildTab : public VBoxContainer { - - GDCLASS(MonoBuildTab, VBoxContainer) - -public: - enum BuildResult { - RESULT_ERROR, - RESULT_SUCCESS - }; - - struct BuildIssue { - bool warning; - String file; - int line; - int column; - String code; - String message; - String project_file; - }; - -private: - friend class MonoBottomPanel; - - bool build_exited; - BuildResult build_result; - - Vector<BuildIssue> issues; - ItemList *issues_list; - - int error_count; - int warning_count; - - bool errors_visible; - bool warnings_visible; - - String logs_dir; - - MonoBuildInfo build_info; - - void _load_issues_from_file(const String &p_csv_file); - void _update_issues_list(); - - void _issue_activated(int p_idx); - -protected: - static void _bind_methods(); - -public: - Ref<Texture> get_icon_texture() const; - - MonoBuildInfo get_build_info(); - - void on_build_start(); - void on_build_exit(BuildResult result); - void on_build_exec_failed(const String &p_cause); - - void restart_build(); - void stop_build(); - - MonoBuildTab(const MonoBuildInfo &p_build_info, const String &p_logs_dir); -}; - -#endif // MONO_BOTTOM_PANEL_H diff --git a/modules/mono/editor/script_class_parser.cpp b/modules/mono/editor/script_class_parser.cpp index dfb652a7aa..dcb0ca5a80 100644 --- a/modules/mono/editor/script_class_parser.cpp +++ b/modules/mono/editor/script_class_parser.cpp @@ -162,8 +162,8 @@ ScriptClassParser::Token ScriptClassParser::get_token() { error = true; return TK_ERROR; } else if (code[idx] == begin_str) { - if (verbatim && code[idx + 1] == '"') { // `""` is verbatim string's `\"` - idx += 2; // skip next `"` as well + if (verbatim && code[idx + 1] == '"') { // '""' is verbatim string's '\"' + idx += 2; // skip next '"' as well continue; } @@ -590,7 +590,7 @@ Error ScriptClassParser::parse(const String &p_code) { name = String(value); } else if (tk == TK_CURLY_BRACKET_OPEN) { if (name.empty()) { - error_str = "Expected " + get_token_name(TK_IDENTIFIER) + " after keyword `struct`, found " + get_token_name(TK_CURLY_BRACKET_OPEN); + error_str = "Expected " + get_token_name(TK_IDENTIFIER) + " after keyword 'struct', found " + get_token_name(TK_CURLY_BRACKET_OPEN); error = true; return ERR_PARSE_ERROR; } @@ -657,12 +657,12 @@ Error ScriptClassParser::parse_file(const String &p_filepath) { String source; Error ferr = read_all_file_utf8(p_filepath, source); - if (ferr != OK) { - if (ferr == ERR_INVALID_DATA) { - ERR_EXPLAIN("File '" + p_filepath + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); - } - ERR_FAIL_V(ferr); - } + + ERR_FAIL_COND_V_MSG(ferr != OK, ferr, + ferr == ERR_INVALID_DATA ? + "File '" + p_filepath + "' contains invalid unicode (UTF-8), so it was not loaded." + " Please ensure that scripts are saved in valid UTF-8 unicode." : + "Failed to read file: '" + p_filepath + "'."); return parse(source); } diff --git a/modules/mono/glue/Managed/.gitignore b/modules/mono/glue/Managed/.gitignore new file mode 100644 index 0000000000..146421cac8 --- /dev/null +++ b/modules/mono/glue/Managed/.gitignore @@ -0,0 +1,2 @@ +# Generated Godot API solution folder +Generated diff --git a/modules/mono/glue/Managed/Files/AABB.cs b/modules/mono/glue/Managed/Files/AABB.cs index 33b2b46712..6a4f785551 100644 --- a/modules/mono/glue/Managed/Files/AABB.cs +++ b/modules/mono/glue/Managed/Files/AABB.cs @@ -5,6 +5,7 @@ // file: core/variant_call.cpp // commit: 5ad9be4c24e9d7dc5672fdc42cea896622fe5685 using System; +using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else @@ -13,6 +14,8 @@ using real_t = System.Single; namespace Godot { + [Serializable] + [StructLayout(LayoutKind.Sequential)] public struct AABB : IEquatable<AABB> { private Vector3 _position; @@ -414,6 +417,21 @@ namespace Godot _position = position; _size = size; } + public AABB(Vector3 position, real_t width, real_t height, real_t depth) + { + _position = position; + _size = new Vector3(width, height, depth); + } + public AABB(real_t x, real_t y, real_t z, Vector3 size) + { + _position = new Vector3(x, y, z); + _size = size; + } + public AABB(real_t x, real_t y, real_t z, real_t width, real_t height, real_t depth) + { + _position = new Vector3(x, y, z); + _size = new Vector3(width, height, depth); + } public static bool operator ==(AABB left, AABB right) { @@ -440,6 +458,11 @@ namespace Godot return _position == other._position && _size == other._size; } + public bool IsEqualApprox(AABB other) + { + return _position.IsEqualApprox(other._position) && _size.IsEqualApprox(other._size); + } + public override int GetHashCode() { return _position.GetHashCode() ^ _size.GetHashCode(); diff --git a/modules/mono/glue/Managed/Files/Array.cs b/modules/mono/glue/Managed/Files/Array.cs index 2277c7bf18..aba1065498 100644 --- a/modules/mono/glue/Managed/Files/Array.cs +++ b/modules/mono/glue/Managed/Files/Array.cs @@ -64,6 +64,11 @@ namespace Godot.Collections return safeHandle.DangerousGetHandle(); } + public Array Duplicate(bool deep = false) + { + return new Array(godot_icall_Array_Duplicate(GetPtr(), deep)); + } + public Error Resize(int newSize) { return godot_icall_Array_Resize(GetPtr(), newSize); @@ -143,6 +148,11 @@ namespace Godot.Collections } } + public override string ToString() + { + return godot_icall_Array_ToString(GetPtr()); + } + [MethodImpl(MethodImplOptions.InternalCall)] internal extern static IntPtr godot_icall_Array_Ctor(); @@ -174,6 +184,9 @@ namespace Godot.Collections internal extern static void godot_icall_Array_CopyTo(IntPtr ptr, System.Array array, int arrayIndex); [MethodImpl(MethodImplOptions.InternalCall)] + internal extern static IntPtr godot_icall_Array_Duplicate(IntPtr ptr, bool deep); + + [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_Array_IndexOf(IntPtr ptr, object item); [MethodImpl(MethodImplOptions.InternalCall)] @@ -190,6 +203,9 @@ namespace Godot.Collections [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Array_Generic_GetElementTypeInfo(Type elemType, out int elemTypeEncoding, out IntPtr elemTypeClass); + + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern static string godot_icall_Array_ToString(IntPtr ptr); } public class Array<T> : IList<T>, ICollection<T>, IEnumerable<T> @@ -242,6 +258,11 @@ namespace Godot.Collections return from.objectArray; } + public Array<T> Duplicate(bool deep = false) + { + return new Array<T>(objectArray.Duplicate(deep)); + } + public Error Resize(int newSize) { return objectArray.Resize(newSize); @@ -353,5 +374,7 @@ namespace Godot.Collections { return GetEnumerator(); } + + public override string ToString() => objectArray.ToString(); } } diff --git a/modules/mono/glue/Managed/Files/Attributes/RPCAttributes.cs b/modules/mono/glue/Managed/Files/Attributes/RPCAttributes.cs index 2398e10135..1bf6d5199a 100644 --- a/modules/mono/glue/Managed/Files/Attributes/RPCAttributes.cs +++ b/modules/mono/glue/Managed/Files/Attributes/RPCAttributes.cs @@ -2,27 +2,27 @@ using System; namespace Godot { - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] public class RemoteAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] public class SyncAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] public class MasterAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] public class PuppetAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] public class SlaveAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] public class RemoteSyncAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] public class MasterSyncAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] public class PuppetSyncAttribute : Attribute {} } diff --git a/modules/mono/glue/Managed/Files/Basis.cs b/modules/mono/glue/Managed/Files/Basis.cs index ac9576cebd..c5e62b77c8 100644 --- a/modules/mono/glue/Managed/Files/Basis.cs +++ b/modules/mono/glue/Managed/Files/Basis.cs @@ -8,43 +8,10 @@ using real_t = System.Single; namespace Godot { + [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Basis : IEquatable<Basis> { - private static readonly Basis identity = new Basis - ( - 1f, 0f, 0f, - 0f, 1f, 0f, - 0f, 0f, 1f - ); - - private static readonly Basis[] orthoBases = { - new Basis(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f), - new Basis(0f, -1f, 0f, 1f, 0f, 0f, 0f, 0f, 1f), - new Basis(-1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, 1f), - new Basis(0f, 1f, 0f, -1f, 0f, 0f, 0f, 0f, 1f), - new Basis(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f), - new Basis(0f, 0f, 1f, 1f, 0f, 0f, 0f, 1f, 0f), - new Basis(-1f, 0f, 0f, 0f, 0f, 1f, 0f, 1f, 0f), - new Basis(0f, 0f, -1f, -1f, 0f, 0f, 0f, 1f, 0f), - new Basis(1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, -1f), - new Basis(0f, 1f, 0f, 1f, 0f, 0f, 0f, 0f, -1f), - new Basis(-1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, -1f), - new Basis(0f, -1f, 0f, -1f, 0f, 0f, 0f, 0f, -1f), - new Basis(1f, 0f, 0f, 0f, 0f, 1f, 0f, -1f, 0f), - new Basis(0f, 0f, -1f, 1f, 0f, 0f, 0f, -1f, 0f), - new Basis(-1f, 0f, 0f, 0f, 0f, -1f, 0f, -1f, 0f), - new Basis(0f, 0f, 1f, -1f, 0f, 0f, 0f, -1f, 0f), - new Basis(0f, 0f, 1f, 0f, 1f, 0f, -1f, 0f, 0f), - new Basis(0f, -1f, 0f, 0f, 0f, 1f, -1f, 0f, 0f), - new Basis(0f, 0f, -1f, 0f, -1f, 0f, -1f, 0f, 0f), - new Basis(0f, 1f, 0f, 0f, 0f, -1f, -1f, 0f, 0f), - new Basis(0f, 0f, 1f, 0f, -1f, 0f, 1f, 0f, 0f), - new Basis(0f, 1f, 0f, 0f, 0f, 1f, 1f, 0f, 0f), - new Basis(0f, 0f, -1f, 0f, 1f, 0f, 1f, 0f, 0f), - new Basis(0f, -1f, 0f, 0f, 0f, -1f, 1f, 0f, 0f) - }; - // NOTE: x, y and z are public-only. Use Column0, Column1 and Column2 internally. /// <summary> @@ -63,7 +30,6 @@ namespace Godot /// </summary> public Vector3 y { - get => Column1; set => Column1 = value; } @@ -74,7 +40,6 @@ namespace Godot /// </summary> public Vector3 z { - get => Column2; set => Column2 = value; } @@ -114,8 +79,6 @@ namespace Godot } } - public static Basis Identity => identity; - public Vector3 Scale { get @@ -225,7 +188,7 @@ namespace Godot return orthonormalizedBasis.Quat(); } - internal void SetQuantScale(Quat quat, Vector3 scale) + internal void SetQuatScale(Quat quat, Vector3 scale) { SetDiagonal(scale); Rotate(quat); @@ -241,7 +204,6 @@ namespace Godot Row0 = new Vector3(diagonal.x, 0, 0); Row1 = new Vector3(0, diagonal.y, 0); Row2 = new Vector3(0, 0, diagonal.z); - } public real_t Determinant() @@ -260,13 +222,13 @@ namespace Godot Vector3 euler; euler.z = 0.0f; - real_t mxy = m.Row1[2]; + real_t mzy = m.Row1[2]; - if (mxy < 1.0f) + if (mzy < 1.0f) { - if (mxy > -1.0f) + if (mzy > -1.0f) { - euler.x = Mathf.Asin(-mxy); + euler.x = Mathf.Asin(-mzy); euler.y = Mathf.Atan2(m.Row0[2], m.Row2[2]); euler.z = Mathf.Atan2(m.Row1[0], m.Row1[1]); } @@ -361,7 +323,7 @@ namespace Godot for (int i = 0; i < 24; i++) { - if (orthoBases[i] == orth) + if (orth == _orthoBases[i]) return i; } @@ -418,19 +380,11 @@ namespace Godot public Basis Scaled(Vector3 scale) { - var m = this; - - m.Row0[0] *= scale.x; - m.Row0[1] *= scale.x; - m.Row0[2] *= scale.x; - m.Row1[0] *= scale.y; - m.Row1[1] *= scale.y; - m.Row1[2] *= scale.y; - m.Row2[0] *= scale.z; - m.Row2[1] *= scale.z; - m.Row2[2] *= scale.z; - - return m; + var b = this; + b.Row0 *= scale.x; + b.Row1 *= scale.y; + b.Row2 *= scale.z; + return b; } public real_t Tdotx(Vector3 with) @@ -539,6 +493,43 @@ namespace Godot } } + private static readonly Basis[] _orthoBases = { + new Basis(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f), + new Basis(0f, -1f, 0f, 1f, 0f, 0f, 0f, 0f, 1f), + new Basis(-1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, 1f), + new Basis(0f, 1f, 0f, -1f, 0f, 0f, 0f, 0f, 1f), + new Basis(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f), + new Basis(0f, 0f, 1f, 1f, 0f, 0f, 0f, 1f, 0f), + new Basis(-1f, 0f, 0f, 0f, 0f, 1f, 0f, 1f, 0f), + new Basis(0f, 0f, -1f, -1f, 0f, 0f, 0f, 1f, 0f), + new Basis(1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, -1f), + new Basis(0f, 1f, 0f, 1f, 0f, 0f, 0f, 0f, -1f), + new Basis(-1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, -1f), + new Basis(0f, -1f, 0f, -1f, 0f, 0f, 0f, 0f, -1f), + new Basis(1f, 0f, 0f, 0f, 0f, 1f, 0f, -1f, 0f), + new Basis(0f, 0f, -1f, 1f, 0f, 0f, 0f, -1f, 0f), + new Basis(-1f, 0f, 0f, 0f, 0f, -1f, 0f, -1f, 0f), + new Basis(0f, 0f, 1f, -1f, 0f, 0f, 0f, -1f, 0f), + new Basis(0f, 0f, 1f, 0f, 1f, 0f, -1f, 0f, 0f), + new Basis(0f, -1f, 0f, 0f, 0f, 1f, -1f, 0f, 0f), + new Basis(0f, 0f, -1f, 0f, -1f, 0f, -1f, 0f, 0f), + new Basis(0f, 1f, 0f, 0f, 0f, -1f, -1f, 0f, 0f), + new Basis(0f, 0f, 1f, 0f, -1f, 0f, 1f, 0f, 0f), + new Basis(0f, 1f, 0f, 0f, 0f, 1f, 1f, 0f, 0f), + new Basis(0f, 0f, -1f, 0f, 1f, 0f, 1f, 0f, 0f), + new Basis(0f, -1f, 0f, 0f, 0f, -1f, 1f, 0f, 0f) + }; + + private static readonly Basis _identity = new Basis(1, 0, 0, 0, 1, 0, 0, 0, 1); + private static readonly Basis _flipX = new Basis(-1, 0, 0, 0, 1, 0, 0, 0, 1); + private static readonly Basis _flipY = new Basis(1, 0, 0, 0, -1, 0, 0, 0, 1); + private static readonly Basis _flipZ = new Basis(1, 0, 0, 0, 1, 0, 0, 0, -1); + + public static Basis Identity { get { return _identity; } } + public static Basis FlipX { get { return _flipX; } } + public static Basis FlipY { get { return _flipY; } } + public static Basis FlipZ { get { return _flipZ; } } + public Basis(Quat quat) { real_t s = 2.0f / quat.LengthSquared; @@ -583,31 +574,29 @@ namespace Godot public Basis(Vector3 axis, real_t phi) { - var axis_sq = new Vector3(axis.x * axis.x, axis.y * axis.y, axis.z * axis.z); - + Vector3 axisSq = new Vector3(axis.x * axis.x, axis.y * axis.y, axis.z * axis.z); real_t cosine = Mathf.Cos(phi); + Row0.x = axisSq.x + cosine * (1.0f - axisSq.x); + Row1.y = axisSq.y + cosine * (1.0f - axisSq.y); + Row2.z = axisSq.z + cosine * (1.0f - axisSq.z); + real_t sine = Mathf.Sin(phi); + real_t t = 1.0f - cosine; - Row0 = new Vector3 - ( - axis_sq.x + cosine * (1.0f - axis_sq.x), - axis.x * axis.y * (1.0f - cosine) - axis.z * sine, - axis.z * axis.x * (1.0f - cosine) + axis.y * sine - ); + real_t xyzt = axis.x * axis.y * t; + real_t zyxs = axis.z * sine; + Row0.y = xyzt - zyxs; + Row1.x = xyzt + zyxs; - Row1 = new Vector3 - ( - axis.x * axis.y * (1.0f - cosine) + axis.z * sine, - axis_sq.y + cosine * (1.0f - axis_sq.y), - axis.y * axis.z * (1.0f - cosine) - axis.x * sine - ); + xyzt = axis.x * axis.z * t; + zyxs = axis.y * sine; + Row0.z = xyzt + zyxs; + Row2.x = xyzt - zyxs; - Row2 = new Vector3 - ( - axis.z * axis.x * (1.0f - cosine) - axis.y * sine, - axis.y * axis.z * (1.0f - cosine) + axis.x * sine, - axis_sq.z + cosine * (1.0f - axis_sq.z) - ); + xyzt = axis.y * axis.z * t; + zyxs = axis.x * sine; + Row1.z = xyzt - zyxs; + Row2.y = xyzt + zyxs; } public Basis(Vector3 column0, Vector3 column1, Vector3 column2) @@ -622,11 +611,12 @@ namespace Godot // We need to assign the struct fields here first so we can't do it that way... } - internal Basis(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz) + // Arguments are named such that xy is equal to calling x.y + internal Basis(real_t xx, real_t yx, real_t zx, real_t xy, real_t yy, real_t zy, real_t xz, real_t yz, real_t zz) { - Row0 = new Vector3(xx, xy, xz); - Row1 = new Vector3(yx, yy, yz); - Row2 = new Vector3(zx, zy, zz); + Row0 = new Vector3(xx, yx, zx); + Row1 = new Vector3(xy, yy, zy); + Row2 = new Vector3(xz, yz, zz); } public static Basis operator *(Basis left, Basis right) @@ -664,6 +654,11 @@ namespace Godot return Row0.Equals(other.Row0) && Row1.Equals(other.Row1) && Row2.Equals(other.Row2); } + public bool IsEqualApprox(Basis other) + { + return Row0.IsEqualApprox(other.Row0) && Row1.IsEqualApprox(other.Row1) && Row2.IsEqualApprox(other.Row2); + } + public override int GetHashCode() { return Row0.GetHashCode() ^ Row1.GetHashCode() ^ Row2.GetHashCode(); diff --git a/modules/mono/glue/Managed/Files/Color.cs b/modules/mono/glue/Managed/Files/Color.cs index 88fa3323c2..df817e47e9 100644 --- a/modules/mono/glue/Managed/Files/Color.cs +++ b/modules/mono/glue/Managed/Files/Color.cs @@ -1,7 +1,10 @@ using System; +using System.Runtime.InteropServices; namespace Godot { + [Serializable] + [StructLayout(LayoutKind.Sequential)] public struct Color : IEquatable<Color> { public float r; @@ -13,7 +16,11 @@ namespace Godot { get { - return (int)(r * 255.0f); + return (int)Math.Round(r * 255.0f); + } + set + { + r = value / 255.0f; } } @@ -21,7 +28,11 @@ namespace Godot { get { - return (int)(g * 255.0f); + return (int)Math.Round(g * 255.0f); + } + set + { + g = value / 255.0f; } } @@ -29,7 +40,11 @@ namespace Godot { get { - return (int)(b * 255.0f); + return (int)Math.Round(b * 255.0f); + } + set + { + b = value / 255.0f; } } @@ -37,7 +52,11 @@ namespace Godot { get { - return (int)(a * 255.0f); + return (int)Math.Round(a * 255.0f); + } + set + { + a = value / 255.0f; } } @@ -71,7 +90,7 @@ namespace Godot } set { - this = FromHsv(value, s, v); + this = FromHsv(value, s, v, a); } } @@ -88,7 +107,7 @@ namespace Godot } set { - this = FromHsv(h, value, v); + this = FromHsv(h, value, v, a); } } @@ -100,7 +119,7 @@ namespace Godot } set { - this = FromHsv(h, s, value); + this = FromHsv(h, s, value, a); } } @@ -163,10 +182,10 @@ namespace Godot } } - public static void ToHsv(Color color, out float hue, out float saturation, out float value) + public void ToHsv(out float hue, out float saturation, out float value) { - int max = Mathf.Max(color.r8, Mathf.Max(color.g8, color.b8)); - int min = Mathf.Min(color.r8, Mathf.Min(color.g8, color.b8)); + float max = (float)Mathf.Max(r, Mathf.Max(g, b)); + float min = (float)Mathf.Min(r, Mathf.Min(g, b)); float delta = max - min; @@ -176,12 +195,12 @@ namespace Godot } else { - if (color.r == max) - hue = (color.g - color.b) / delta; // Between yellow & magenta - else if (color.g == max) - hue = 2 + (color.b - color.r) / delta; // Between cyan & yellow + if (r == max) + hue = (g - b) / delta; // Between yellow & magenta + else if (g == max) + hue = 2 + (b - r) / delta; // Between cyan & yellow else - hue = 4 + (color.r - color.g) / delta; // Between magenta & cyan + hue = 4 + (r - g) / delta; // Between magenta & cyan hue /= 6.0f; @@ -190,7 +209,7 @@ namespace Godot } saturation = max == 0 ? 0 : 1f - 1f * min / max; - value = max / 255f; + value = max; } public static Color FromHsv(float hue, float saturation, float value, float alpha = 1.0f) @@ -254,7 +273,8 @@ namespace Godot return new Color( (r + 0.5f) % 1.0f, (g + 0.5f) % 1.0f, - (b + 0.5f) % 1.0f + (b + 0.5f) % 1.0f, + a ); } @@ -272,7 +292,8 @@ namespace Godot return new Color( 1.0f - r, 1.0f - g, - 1.0f - b + 1.0f - b, + a ); } @@ -375,7 +396,7 @@ namespace Godot return c; } - public string ToHtml(bool include_alpha = true) + public string ToHtml(bool includeAlpha = true) { var txt = string.Empty; @@ -383,7 +404,7 @@ namespace Godot txt += ToHex32(g); txt += ToHex32(b); - if (include_alpha) + if (includeAlpha) txt = ToHex32(a) + txt; return txt; @@ -465,13 +486,13 @@ namespace Godot for (int i = 0; i < 2; i++) { - char[] c = { (char)0, (char)0 }; + char c; int lv = v & 0xF; if (lv < 10) - c[0] = (char)('0' + lv); + c = (char)('0' + lv); else - c[0] = (char)('a' + lv - 10); + c = (char)('a' + lv - 10); v >>= 4; ret = c + ret; @@ -490,12 +511,17 @@ namespace Godot bool alpha; - if (color.Length == 8) - alpha = true; - else if (color.Length == 6) - alpha = false; - else - return false; + switch (color.Length) + { + case 8: + alpha = true; + break; + case 6: + alpha = false; + break; + default: + return false; + } if (alpha) { @@ -591,11 +617,11 @@ namespace Godot public static bool operator <(Color left, Color right) { - if (left.r == right.r) + if (Mathf.IsEqualApprox(left.r, right.r)) { - if (left.g == right.g) + if (Mathf.IsEqualApprox(left.g, right.g)) { - if (left.b == right.b) + if (Mathf.IsEqualApprox(left.b, right.b)) return left.a < right.a; return left.b < right.b; } @@ -608,11 +634,11 @@ namespace Godot public static bool operator >(Color left, Color right) { - if (left.r == right.r) + if (Mathf.IsEqualApprox(left.r, right.r)) { - if (left.g == right.g) + if (Mathf.IsEqualApprox(left.g, right.g)) { - if (left.b == right.b) + if (Mathf.IsEqualApprox(left.b, right.b)) return left.a > right.a; return left.b > right.b; } @@ -638,6 +664,11 @@ namespace Godot return r == other.r && g == other.g && b == other.b && a == other.a; } + public bool IsEqualApprox(Color other) + { + return Mathf.IsEqualApprox(r, other.r) && Mathf.IsEqualApprox(g, other.g) && Mathf.IsEqualApprox(b, other.b) && Mathf.IsEqualApprox(a, other.a); + } + public override int GetHashCode() { return r.GetHashCode() ^ g.GetHashCode() ^ b.GetHashCode() ^ a.GetHashCode(); diff --git a/modules/mono/glue/Managed/Files/Colors.cs b/modules/mono/glue/Managed/Files/Colors.cs index bc2a1a3bd7..f41f5e9fc8 100644 --- a/modules/mono/glue/Managed/Files/Colors.cs +++ b/modules/mono/glue/Managed/Files/Colors.cs @@ -141,6 +141,7 @@ namespace Godot {"teal", new Color(0.00f, 0.50f, 0.50f)}, {"thistle", new Color(0.85f, 0.75f, 0.85f)}, {"tomato", new Color(1.00f, 0.39f, 0.28f)}, + {"transparent", new Color(1.00f, 1.00f, 1.00f, 0.00f)}, {"turquoise", new Color(0.25f, 0.88f, 0.82f)}, {"violet", new Color(0.93f, 0.51f, 0.93f)}, {"webgreen", new Color(0.00f, 0.50f, 0.00f)}, @@ -187,7 +188,7 @@ namespace Godot public static Color DarkOrchid { get { return namedColors["darkorchid"]; } } public static Color DarkRed { get { return namedColors["darkred"]; } } public static Color DarkSalmon { get { return namedColors["darksalmon"]; } } - public static Color DarkSeagreen { get { return namedColors["darkseagreen"]; } } + public static Color DarkSeaGreen { get { return namedColors["darkseagreen"]; } } public static Color DarkSlateBlue { get { return namedColors["darkslateblue"]; } } public static Color DarkSlateGray { get { return namedColors["darkslategray"]; } } public static Color DarkTurquoise { get { return namedColors["darkturquoise"]; } } @@ -288,6 +289,7 @@ namespace Godot public static Color Teal { get { return namedColors["teal"]; } } public static Color Thistle { get { return namedColors["thistle"]; } } public static Color Tomato { get { return namedColors["tomato"]; } } + public static Color Transparent { get { return namedColors["transparent"]; } } public static Color Turquoise { get { return namedColors["turquoise"]; } } public static Color Violet { get { return namedColors["violet"]; } } public static Color WebGreen { get { return namedColors["webgreen"]; } } diff --git a/modules/mono/glue/Managed/Files/Dictionary.cs b/modules/mono/glue/Managed/Files/Dictionary.cs index af1782b79a..d72109de92 100644 --- a/modules/mono/glue/Managed/Files/Dictionary.cs +++ b/modules/mono/glue/Managed/Files/Dictionary.cs @@ -80,6 +80,11 @@ namespace Godot.Collections disposed = true; } + public Dictionary Duplicate(bool deep = false) + { + return new Dictionary(godot_icall_Dictionary_Duplicate(GetPtr(), deep)); + } + // IDictionary public ICollection Keys @@ -193,6 +198,11 @@ namespace Godot.Collections } } + public override string ToString() + { + return godot_icall_Dictionary_ToString(GetPtr()); + } + [MethodImpl(MethodImplOptions.InternalCall)] internal extern static IntPtr godot_icall_Dictionary_Ctor(); @@ -230,6 +240,9 @@ namespace Godot.Collections internal extern static bool godot_icall_Dictionary_ContainsKey(IntPtr ptr, object key); [MethodImpl(MethodImplOptions.InternalCall)] + internal extern static IntPtr godot_icall_Dictionary_Duplicate(IntPtr ptr, bool deep); + + [MethodImpl(MethodImplOptions.InternalCall)] internal extern static bool godot_icall_Dictionary_RemoveKey(IntPtr ptr, object key); [MethodImpl(MethodImplOptions.InternalCall)] @@ -243,6 +256,9 @@ namespace Godot.Collections [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Dictionary_Generic_GetValueTypeInfo(Type valueType, out int valTypeEncoding, out IntPtr valTypeClass); + + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern static string godot_icall_Dictionary_ToString(IntPtr ptr); } public class Dictionary<TKey, TValue> : @@ -305,6 +321,11 @@ namespace Godot.Collections return objectDict.GetPtr(); } + public Dictionary<TKey, TValue> Duplicate(bool deep = false) + { + return new Dictionary<TKey, TValue>(objectDict.Duplicate(deep)); + } + // IDictionary<TKey, TValue> public TValue this[TKey key] @@ -442,5 +463,7 @@ namespace Godot.Collections { return GetEnumerator(); } + + public override string ToString() => objectDict.ToString(); } } diff --git a/modules/mono/glue/Managed/Files/Dispatcher.cs b/modules/mono/glue/Managed/Files/Dispatcher.cs new file mode 100644 index 0000000000..072e0f20ff --- /dev/null +++ b/modules/mono/glue/Managed/Files/Dispatcher.cs @@ -0,0 +1,13 @@ +using System.Runtime.CompilerServices; + +namespace Godot +{ + public static class Dispatcher + { + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern GodotTaskScheduler godot_icall_DefaultGodotTaskScheduler(); + + public static GodotSynchronizationContext SynchronizationContext => + godot_icall_DefaultGodotTaskScheduler().Context; + } +} diff --git a/modules/mono/glue/Managed/Files/DynamicObject.cs b/modules/mono/glue/Managed/Files/DynamicObject.cs index 9504415664..a0f105d55e 100644 --- a/modules/mono/glue/Managed/Files/DynamicObject.cs +++ b/modules/mono/glue/Managed/Files/DynamicObject.cs @@ -26,7 +26,7 @@ namespace Godot /// dynamic sprite = GetNode("Sprite").DynamicGodotObject; /// sprite.add_child(this); /// - /// if ((sprite.hframes * sprite.vframes) > 0) + /// if ((sprite.hframes * sprite.vframes) > 0) /// sprite.frame = 0; /// </code> /// </example> @@ -202,7 +202,7 @@ namespace Godot //public override bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes); //public override bool TryDeleteMember(DeleteMemberBinder binder); - // Invokation on the object itself, e.g.: obj(param) + // Invocation on the object itself, e.g.: obj(param) //public override bool TryInvoke(InvokeBinder binder, object[] args, out object result); // No unnary operations to handle diff --git a/modules/mono/glue/Managed/Files/Extensions/NodeExtensions.cs b/modules/mono/glue/Managed/Files/Extensions/NodeExtensions.cs index 366d89b1c2..5023725f17 100644 --- a/modules/mono/glue/Managed/Files/Extensions/NodeExtensions.cs +++ b/modules/mono/glue/Managed/Files/Extensions/NodeExtensions.cs @@ -24,12 +24,12 @@ namespace Godot public T GetOwner<T>() where T : class { - return (T)(object)GetOwner(); + return (T)(object)Owner; } public T GetOwnerOrNull<T>() where T : class { - return GetOwner() as T; + return Owner as T; } public T GetParent<T>() where T : class diff --git a/modules/mono/glue/Managed/Files/GD.cs b/modules/mono/glue/Managed/Files/GD.cs index d968f8a78f..19962d418a 100644 --- a/modules/mono/glue/Managed/Files/GD.cs +++ b/modules/mono/glue/Managed/Files/GD.cs @@ -83,7 +83,7 @@ namespace Godot public static void Print(params object[] what) { - godot_icall_GD_print(what); + godot_icall_GD_print(Array.ConvertAll(what, x => x.ToString())); } public static void PrintStack() @@ -93,25 +93,25 @@ namespace Godot public static void PrintErr(params object[] what) { - godot_icall_GD_printerr(what); + godot_icall_GD_printerr(Array.ConvertAll(what, x => x?.ToString())); } public static void PrintRaw(params object[] what) { - godot_icall_GD_printraw(what); + godot_icall_GD_printraw(Array.ConvertAll(what, x => x?.ToString())); } public static void PrintS(params object[] what) { - godot_icall_GD_prints(what); + godot_icall_GD_prints(Array.ConvertAll(what, x => x?.ToString())); } public static void PrintT(params object[] what) { - godot_icall_GD_printt(what); + godot_icall_GD_printt(Array.ConvertAll(what, x => x?.ToString())); } - public static double Randf() + public static float Randf() { return godot_icall_GD_randf(); } @@ -224,7 +224,7 @@ namespace Godot internal extern static void godot_icall_GD_printt(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] - internal extern static double godot_icall_GD_randf(); + internal extern static float godot_icall_GD_randf(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static uint godot_icall_GD_randi(); @@ -232,6 +232,7 @@ namespace Godot [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_randomize(); + [MethodImpl(MethodImplOptions.InternalCall)] internal extern static double godot_icall_GD_rand_range(double from, double to); diff --git a/modules/mono/glue/Managed/Files/GodotSynchronizationContext.cs b/modules/mono/glue/Managed/Files/GodotSynchronizationContext.cs index e727781d63..4b5e3f8761 100644 --- a/modules/mono/glue/Managed/Files/GodotSynchronizationContext.cs +++ b/modules/mono/glue/Managed/Files/GodotSynchronizationContext.cs @@ -6,17 +6,16 @@ namespace Godot { public class GodotSynchronizationContext : SynchronizationContext { - private readonly BlockingCollection<KeyValuePair<SendOrPostCallback, object>> queue = new BlockingCollection<KeyValuePair<SendOrPostCallback, object>>(); + private readonly BlockingCollection<KeyValuePair<SendOrPostCallback, object>> _queue = new BlockingCollection<KeyValuePair<SendOrPostCallback, object>>(); public override void Post(SendOrPostCallback d, object state) { - queue.Add(new KeyValuePair<SendOrPostCallback, object>(d, state)); + _queue.Add(new KeyValuePair<SendOrPostCallback, object>(d, state)); } public void ExecutePendingContinuations() { - KeyValuePair<SendOrPostCallback, object> workItem; - while (queue.TryTake(out workItem)) + while (_queue.TryTake(out var workItem)) { workItem.Key(workItem.Value); } diff --git a/modules/mono/glue/Managed/Files/GodotTaskScheduler.cs b/modules/mono/glue/Managed/Files/GodotTaskScheduler.cs index 9a40fef5a9..8eaeea50dc 100644 --- a/modules/mono/glue/Managed/Files/GodotTaskScheduler.cs +++ b/modules/mono/glue/Managed/Files/GodotTaskScheduler.cs @@ -8,7 +8,7 @@ namespace Godot { public class GodotTaskScheduler : TaskScheduler { - private GodotSynchronizationContext Context { get; set; } + internal GodotSynchronizationContext Context { get; } private readonly LinkedList<Task> _tasks = new LinkedList<Task>(); public GodotTaskScheduler() @@ -28,14 +28,10 @@ namespace Godot protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (SynchronizationContext.Current != Context) - { return false; - } if (taskWasPreviouslyQueued) - { TryDequeue(task); - } return TryExecuteTask(task); } @@ -52,7 +48,8 @@ namespace Godot { lock (_tasks) { - return _tasks.ToArray(); + foreach (Task task in _tasks) + yield return task; } } diff --git a/modules/mono/glue/Managed/Files/Interfaces/ISerializationListener.cs b/modules/mono/glue/Managed/Files/Interfaces/ISerializationListener.cs new file mode 100644 index 0000000000..c3fa2f3e82 --- /dev/null +++ b/modules/mono/glue/Managed/Files/Interfaces/ISerializationListener.cs @@ -0,0 +1,8 @@ +namespace Godot +{ + public interface ISerializationListener + { + void OnBeforeSerialize(); + void OnAfterDeserialize(); + } +} diff --git a/modules/mono/glue/Managed/Files/MarshalUtils.cs b/modules/mono/glue/Managed/Files/MarshalUtils.cs index 7e72b0edb5..a1d63a62ef 100644 --- a/modules/mono/glue/Managed/Files/MarshalUtils.cs +++ b/modules/mono/glue/Managed/Files/MarshalUtils.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; namespace Godot { @@ -8,29 +9,151 @@ namespace Godot static class MarshalUtils { + /// <summary> + /// Returns <see langword="true"/> if the generic type definition of <paramref name="type"/> + /// is <see cref="Godot.Collections.Array{T}"/>; otherwise returns <see langword="false"/>. + /// </summary> + /// <exception cref="System.InvalidOperationException"> + /// <paramref name="type"/> is not a generic type. That is, IsGenericType returns false. + /// </exception> static bool TypeIsGenericArray(Type type) { return type.GetGenericTypeDefinition() == typeof(Godot.Collections.Array<>); } + /// <summary> + /// Returns <see langword="true"/> if the generic type definition of <paramref name="type"/> + /// is <see cref="Godot.Collections.Dictionary{TKey, TValue}"/>; otherwise returns <see langword="false"/>. + /// </summary> + /// <exception cref="System.InvalidOperationException"> + /// <paramref name="type"/> is not a generic type. That is, IsGenericType returns false. + /// </exception> static bool TypeIsGenericDictionary(Type type) { return type.GetGenericTypeDefinition() == typeof(Godot.Collections.Dictionary<,>); } - static void ArrayGetElementType(Type type, out Type elementType) + static void ArrayGetElementType(Type arrayType, out Type elementType) { - elementType = type.GetGenericArguments()[0]; + elementType = arrayType.GetGenericArguments()[0]; } - static void DictionaryGetKeyValueTypes(Type type, out Type keyType, out Type valueType) + static void DictionaryGetKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { - var genericArgs = type.GetGenericArguments(); - + var genericArgs = dictionaryType.GetGenericArguments(); keyType = genericArgs[0]; valueType = genericArgs[1]; } + static bool GenericIEnumerableIsAssignableFromType(Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + return true; + + foreach (var interfaceType in type.GetInterfaces()) + { + if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + return true; + } + + Type baseType = type.BaseType; + + if (baseType == null) + return false; + + return GenericIEnumerableIsAssignableFromType(baseType); + } + + static bool GenericIDictionaryIsAssignableFromType(Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>)) + return true; + + foreach (var interfaceType in type.GetInterfaces()) + { + if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IDictionary<,>)) + return true; + } + + Type baseType = type.BaseType; + + if (baseType == null) + return false; + + return GenericIDictionaryIsAssignableFromType(baseType); + } + + static bool GenericIEnumerableIsAssignableFromType(Type type, out Type elementType) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + { + elementType = type.GetGenericArguments()[0]; + return true; + } + + foreach (var interfaceType in type.GetInterfaces()) + { + if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + { + elementType = interfaceType.GetGenericArguments()[0]; + return true; + } + } + + Type baseType = type.BaseType; + + if (baseType == null) + { + elementType = null; + return false; + } + + return GenericIEnumerableIsAssignableFromType(baseType, out elementType); + } + + static bool GenericIDictionaryIsAssignableFromType(Type type, out Type keyType, out Type valueType) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>)) + { + var genericArgs = type.GetGenericArguments(); + keyType = genericArgs[0]; + valueType = genericArgs[1]; + return true; + } + + foreach (var interfaceType in type.GetInterfaces()) + { + if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IDictionary<,>)) + { + var genericArgs = interfaceType.GetGenericArguments(); + keyType = genericArgs[0]; + valueType = genericArgs[1]; + return true; + } + } + + Type baseType = type.BaseType; + + if (baseType == null) + { + keyType = null; + valueType = null; + return false; + } + + return GenericIDictionaryIsAssignableFromType(baseType, out keyType, out valueType); + } + + static Type MakeGenericArrayType(Type elemType) + { + return typeof(Godot.Collections.Array<>).MakeGenericType(elemType); + } + + static Type MakeGenericDictionaryType(Type keyType, Type valueType) + { + return typeof(Godot.Collections.Dictionary<,>).MakeGenericType(keyType, valueType); + } + // TODO Add support for IEnumerable<T> and IDictionary<TKey, TValue> // TODO: EnumerableToArray and IDictionaryToDictionary can be optimized @@ -64,5 +187,26 @@ namespace Godot Dictionary.godot_icall_Dictionary_Add(godotDictionaryPtr, entry.Key, entry.Value); } } + + internal static void GenericIDictionaryToDictionary(object dictionary, IntPtr godotDictionaryPtr) + { +#if DEBUG + if (!GenericIDictionaryIsAssignableFromType(dictionary.GetType())) + throw new InvalidOperationException("The type does not implement IDictionary<,>"); +#endif + + // TODO: Can we optimize this? + + var keys = ((IEnumerable)dictionary.GetType().GetProperty("Keys").GetValue(dictionary)).GetEnumerator(); + var values = ((IEnumerable)dictionary.GetType().GetProperty("Values").GetValue(dictionary)).GetEnumerator(); + + while (keys.MoveNext() && values.MoveNext()) + { + object key = keys.Current; + object value = values.Current; + + Dictionary.godot_icall_Dictionary_Add(godotDictionaryPtr, key, value); + } + } } } diff --git a/modules/mono/glue/Managed/Files/Mathf.cs b/modules/mono/glue/Managed/Files/Mathf.cs index 5f5de12959..54821fe790 100644 --- a/modules/mono/glue/Managed/Files/Mathf.cs +++ b/modules/mono/glue/Managed/Files/Mathf.cs @@ -19,12 +19,12 @@ namespace Godot private const real_t Deg2RadConst = (real_t) 0.0174532925199432957692369077M; // 0.0174532924f and 0.0174532925199433 private const real_t Rad2DegConst = (real_t) 57.295779513082320876798154814M; // 57.29578f and 57.2957795130823 - public static real_t Abs(real_t s) + public static int Abs(int s) { return Math.Abs(s); } - public static int Abs(int s) + public static real_t Abs(real_t s) { return Math.Abs(s); } @@ -44,9 +44,9 @@ namespace Godot return (real_t)Math.Atan(s); } - public static real_t Atan2(real_t x, real_t y) + public static real_t Atan2(real_t y, real_t x) { - return (real_t)Math.Atan2(x, y); + return (real_t)Math.Atan2(y, x); } public static Vector2 Cartesian2Polar(real_t x, real_t y) @@ -79,16 +79,6 @@ namespace Godot return (real_t)Math.Cosh(s); } - public static int Decimals(real_t step) - { - return Decimals((decimal)step); - } - - public static int Decimals(decimal step) - { - return BitConverter.GetBytes(decimal.GetBits(step)[3])[2]; - } - public static real_t Deg2Rad(real_t deg) { return deg * Deg2RadConst; @@ -143,6 +133,22 @@ namespace Godot return (weight - from) / (to - from); } + public static bool IsEqualApprox(real_t a, real_t b) + { + // Check for exact equality first, required to handle "infinity" values. + if (a == b) + { + return true; + } + // Then check for approximate equality. + real_t tolerance = Epsilon * Abs(a); + if (tolerance < Epsilon) + { + tolerance = Epsilon; + } + return Abs(a - b) < tolerance; + } + public static bool IsInf(real_t s) { return real_t.IsInfinity(s); @@ -153,11 +159,23 @@ namespace Godot return real_t.IsNaN(s); } + public static bool IsZeroApprox(real_t s) + { + return Abs(s) < Epsilon; + } + public static real_t Lerp(real_t from, real_t to, real_t weight) { return from + (to - from) * weight; } + public static real_t LerpAngle(real_t from, real_t to, real_t weight) + { + real_t difference = (to - from) % Mathf.Tau; + real_t distance = ((2 * difference) % Mathf.Tau) - difference; + return from + distance * weight; + } + public static real_t Log(real_t s) { return (real_t)Math.Log(s); @@ -183,6 +201,11 @@ namespace Godot return a < b ? a : b; } + public static real_t MoveToward(real_t from, real_t to, real_t delta) + { + return Abs(to - from) <= delta ? to : from + Sign(to - from) * delta; + } + public static int NearestPo2(int value) { value--; @@ -203,9 +226,9 @@ namespace Godot /// <summary> /// Performs a canonical Modulus operation, where the output is on the range [0, b). /// </summary> - public static real_t PosMod(real_t a, real_t b) + public static int PosMod(int a, int b) { - real_t c = a % b; + int c = a % b; if ((c < 0 && b > 0) || (c > 0 && b < 0)) { c += b; @@ -216,9 +239,9 @@ namespace Godot /// <summary> /// Performs a canonical Modulus operation, where the output is on the range [0, b). /// </summary> - public static int PosMod(int a, int b) + public static real_t PosMod(real_t a, real_t b) { - int c = a % b; + real_t c = a % b; if ((c < 0 && b > 0) || (c > 0 && b < 0)) { c += b; @@ -261,11 +284,46 @@ namespace Godot return (real_t)Math.Sinh(s); } + public static real_t SmoothStep(real_t from, real_t to, real_t weight) + { + if (IsEqualApprox(from, to)) + { + return from; + } + real_t x = Clamp((weight - from) / (to - from), (real_t)0.0, (real_t)1.0); + return x * x * (3 - 2 * x); + } + public static real_t Sqrt(real_t s) { return (real_t)Math.Sqrt(s); } + public static int StepDecimals(real_t step) + { + double[] sd = new double[] { + 0.9999, + 0.09999, + 0.009999, + 0.0009999, + 0.00009999, + 0.000009999, + 0.0000009999, + 0.00000009999, + 0.000000009999, + }; + double abs = Mathf.Abs(step); + double decs = abs - (int)abs; // Strip away integer part + for (int i = 0; i < sd.Length; i++) + { + if (decs >= sd[i]) + { + return i; + } + } + return 0; + } + public static real_t Stepify(real_t s, real_t step) { if (step != 0f) @@ -288,14 +346,14 @@ namespace Godot public static int Wrap(int value, int min, int max) { - int rng = max - min; - return rng != 0 ? min + ((value - min) % rng + rng) % rng : min; + int range = max - min; + return range == 0 ? min : min + ((value - min) % range + range) % range; } public static real_t Wrap(real_t value, real_t min, real_t max) { - real_t rng = max - min; - return !IsEqualApprox(rng, default(real_t)) ? min + ((value - min) % rng + rng) % rng : min; + real_t range = max - min; + return IsZeroApprox(range) ? min : min + ((value - min) % range + range) % range; } } } diff --git a/modules/mono/glue/Managed/Files/MathfEx.cs b/modules/mono/glue/Managed/Files/MathfEx.cs index 414762f7b1..1b7fd4906f 100644 --- a/modules/mono/glue/Managed/Files/MathfEx.cs +++ b/modules/mono/glue/Managed/Files/MathfEx.cs @@ -21,6 +21,16 @@ namespace Godot public const real_t Epsilon = 1e-06f; #endif + public static int DecimalCount(real_t s) + { + return DecimalCount((decimal)s); + } + + public static int DecimalCount(decimal s) + { + return BitConverter.GetBytes(decimal.GetBits(s)[3])[2]; + } + public static int CeilToInt(real_t s) { return (int)Math.Ceiling(s); @@ -36,9 +46,15 @@ namespace Godot return (int)Math.Round(s); } - public static bool IsEqualApprox(real_t a, real_t b, real_t ratio = Mathf.Epsilon) + public static bool IsEqualApprox(real_t a, real_t b, real_t tolerance) { - return Abs(a - b) < ratio; + // Check for exact equality first, required to handle "infinity" values. + if (a == b) + { + return true; + } + // Then check for approximate equality. + return Abs(a - b) < tolerance; } } -}
\ No newline at end of file +} diff --git a/modules/mono/glue/Managed/Files/NodePath.cs b/modules/mono/glue/Managed/Files/NodePath.cs index 94a4ed1de9..8c5872ba5a 100644 --- a/modules/mono/glue/Managed/Files/NodePath.cs +++ b/modules/mono/glue/Managed/Files/NodePath.cs @@ -12,7 +12,7 @@ namespace Godot internal static IntPtr GetPtr(NodePath instance) { if (instance == null) - return IntPtr.Zero; + throw new NullReferenceException($"The instance of type {nameof(NodePath)} is null."); if (instance.disposed) throw new ObjectDisposedException(instance.GetType().FullName); @@ -55,7 +55,7 @@ namespace Godot get { return ptr; } } - public NodePath() : this(string.Empty) { } + public NodePath() : this(string.Empty) {} public NodePath(string path) { diff --git a/modules/mono/glue/Managed/Files/Object.base.cs b/modules/mono/glue/Managed/Files/Object.base.cs index e152d56871..de80f7fddc 100644 --- a/modules/mono/glue/Managed/Files/Object.base.cs +++ b/modules/mono/glue/Managed/Files/Object.base.cs @@ -73,6 +73,11 @@ namespace Godot disposed = true; } + public override string ToString() + { + return godot_icall_Object_ToString(GetPtr(this)); + } + /// <summary> /// Returns a new <see cref="Godot.SignalAwaiter"/> awaiter configured to complete when the instance /// <paramref name="source"/> emits the signal specified by the <paramref name="signal"/> parameter. @@ -88,7 +93,7 @@ namespace Godot /// <code> /// public override void _Ready() /// { - /// for (int i = 0; i < 100; i++) + /// for (int i = 0; i < 100; i++) /// { /// await ToSignal(GetTree(), "idle_frame"); /// GD.Print($"Frame {i}"); @@ -115,6 +120,9 @@ namespace Godot [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Reference_Disposed(Object obj, IntPtr ptr, bool isFinalizer); + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern static string godot_icall_Object_ToString(IntPtr ptr); + // Used by the generated API [MethodImpl(MethodImplOptions.InternalCall)] internal extern static IntPtr godot_icall_Object_ClassDB_get_method(string type, string method); diff --git a/modules/mono/glue/Managed/Files/Plane.cs b/modules/mono/glue/Managed/Files/Plane.cs index f11cd490a9..885845e3a4 100644 --- a/modules/mono/glue/Managed/Files/Plane.cs +++ b/modules/mono/glue/Managed/Files/Plane.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else @@ -7,6 +8,8 @@ using real_t = System.Single; namespace Godot { + [Serializable] + [StructLayout(LayoutKind.Sequential)] public struct Plane : IEquatable<Plane> { private Vector3 _normal; @@ -79,12 +82,12 @@ namespace Godot return Mathf.Abs(dist) <= epsilon; } - public Vector3 Intersect3(Plane b, Plane c) + public Vector3? Intersect3(Plane b, Plane c) { real_t denom = _normal.Cross(b._normal).Dot(c._normal); - if (Mathf.Abs(denom) <= Mathf.Epsilon) - return new Vector3(); + if (Mathf.IsZeroApprox(denom)) + return null; Vector3 result = b._normal.Cross(c._normal) * D + c._normal.Cross(_normal) * b.D + @@ -93,34 +96,35 @@ namespace Godot return result / denom; } - public Vector3 IntersectRay(Vector3 from, Vector3 dir) + public Vector3? IntersectRay(Vector3 from, Vector3 dir) { real_t den = _normal.Dot(dir); - if (Mathf.Abs(den) <= Mathf.Epsilon) - return new Vector3(); + if (Mathf.IsZeroApprox(den)) + return null; real_t dist = (_normal.Dot(from) - D) / den; // This is a ray, before the emitting pos (from) does not exist if (dist > Mathf.Epsilon) - return new Vector3(); + return null; return from + dir * -dist; } - public Vector3 IntersectSegment(Vector3 begin, Vector3 end) + public Vector3? IntersectSegment(Vector3 begin, Vector3 end) { Vector3 segment = begin - end; real_t den = _normal.Dot(segment); - if (Mathf.Abs(den) <= Mathf.Epsilon) - return new Vector3(); + if (Mathf.IsZeroApprox(den)) + return null; real_t dist = (_normal.Dot(begin) - D) / den; + // Only allow dist to be in the range of 0 to 1, with tolerance. if (dist < -Mathf.Epsilon || dist > 1.0f + Mathf.Epsilon) - return new Vector3(); + return null; return begin + segment * -dist; } @@ -203,6 +207,11 @@ namespace Godot return _normal == other._normal && D == other.D; } + public bool IsEqualApprox(Plane other) + { + return _normal.IsEqualApprox(other._normal) && Mathf.IsEqualApprox(D, other.D); + } + public override int GetHashCode() { return _normal.GetHashCode() ^ D.GetHashCode(); diff --git a/modules/mono/glue/Managed/Files/Quat.cs b/modules/mono/glue/Managed/Files/Quat.cs index d0c15146a5..8f60867ac3 100644 --- a/modules/mono/glue/Managed/Files/Quat.cs +++ b/modules/mono/glue/Managed/Files/Quat.cs @@ -8,6 +8,7 @@ using real_t = System.Single; namespace Godot { + [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Quat : IEquatable<Quat> { @@ -95,6 +96,7 @@ namespace Godot return this / Length; } + [Obsolete("Set is deprecated. Use the Quat(" + nameof(real_t) + ", " + nameof(real_t) + ", " + nameof(real_t) + ", " + nameof(real_t) + ") constructor instead.", error: true)] public void Set(real_t x, real_t y, real_t z, real_t w) { this.x = x; @@ -103,16 +105,19 @@ namespace Godot this.w = w; } + [Obsolete("Set is deprecated. Use the Quat(" + nameof(Quat) + ") constructor instead.", error: true)] public void Set(Quat q) { this = q; } + [Obsolete("SetAxisAngle is deprecated. Use the Quat(" + nameof(Vector3) + ", " + nameof(real_t) + ") constructor instead.", error: true)] public void SetAxisAngle(Vector3 axis, real_t angle) { this = new Quat(axis, angle); } + [Obsolete("SetEuler is deprecated. Use the Quat(" + nameof(Vector3) + ") constructor instead.", error: true)] public void SetEuler(Vector3 eulerYXZ) { this = new Quat(eulerYXZ); @@ -229,9 +234,9 @@ namespace Godot public Quat(Vector3 eulerYXZ) { - real_t half_a1 = eulerYXZ.y * (real_t)0.5; - real_t half_a2 = eulerYXZ.x * (real_t)0.5; - real_t half_a3 = eulerYXZ.z * (real_t)0.5; + real_t half_a1 = eulerYXZ.y * 0.5f; + real_t half_a2 = eulerYXZ.x * 0.5f; + real_t half_a3 = eulerYXZ.z * 0.5f; // R = Y(a1).X(a2).Z(a3) convention for Euler angles. // Conversion to quaternion as listed in https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf (page A-6) @@ -246,7 +251,7 @@ namespace Godot x = sin_a1 * cos_a2 * sin_a3 + cos_a1 * sin_a2 * cos_a3; y = sin_a1 * cos_a2 * cos_a3 - cos_a1 * sin_a2 * sin_a3; - z = -sin_a1 * sin_a2 * cos_a3 + cos_a1 * cos_a2 * sin_a3; + z = cos_a1 * cos_a2 * sin_a3 - sin_a1 * sin_a2 * cos_a3; w = sin_a1 * sin_a2 * sin_a3 + cos_a1 * cos_a2 * cos_a3; } @@ -361,6 +366,11 @@ namespace Godot return x == other.x && y == other.y && z == other.z && w == other.w; } + public bool IsEqualApprox(Quat other) + { + return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y) && Mathf.IsEqualApprox(z, other.z) && Mathf.IsEqualApprox(w, other.w); + } + public override int GetHashCode() { return y.GetHashCode() ^ x.GetHashCode() ^ z.GetHashCode() ^ w.GetHashCode(); diff --git a/modules/mono/glue/Managed/Files/RID.cs b/modules/mono/glue/Managed/Files/RID.cs index f1268c8518..94761531b1 100644 --- a/modules/mono/glue/Managed/Files/RID.cs +++ b/modules/mono/glue/Managed/Files/RID.cs @@ -12,7 +12,7 @@ namespace Godot internal static IntPtr GetPtr(RID instance) { if (instance == null) - return IntPtr.Zero; + throw new NullReferenceException($"The instance of type {nameof(RID)} is null."); if (instance.disposed) throw new ObjectDisposedException(instance.GetType().FullName); @@ -70,6 +70,8 @@ namespace Godot return godot_icall_RID_get_id(RID.GetPtr(this)); } + public override string ToString() => "[RID]"; + [MethodImpl(MethodImplOptions.InternalCall)] internal extern static IntPtr godot_icall_RID_Ctor(IntPtr from); diff --git a/modules/mono/glue/Managed/Files/Rect2.cs b/modules/mono/glue/Managed/Files/Rect2.cs index 888f300347..91e614dc7b 100644 --- a/modules/mono/glue/Managed/Files/Rect2.cs +++ b/modules/mono/glue/Managed/Files/Rect2.cs @@ -8,6 +8,7 @@ using real_t = System.Single; namespace Godot { + [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Rect2 : IEquatable<Rect2> { @@ -156,13 +157,13 @@ namespace Godot public bool Intersects(Rect2 b) { - if (_position.x > b._position.x + b._size.x) + if (_position.x >= b._position.x + b._size.x) return false; - if (_position.x + _size.x < b._position.x) + if (_position.x + _size.x <= b._position.x) return false; - if (_position.y > b._position.y + b._size.y) + if (_position.y >= b._position.y + b._size.y) return false; - if (_position.y + _size.y < b._position.y) + if (_position.y + _size.y <= b._position.y) return false; return true; @@ -230,6 +231,11 @@ namespace Godot return _position.Equals(other._position) && _size.Equals(other._size); } + public bool IsEqualApprox(Rect2 other) + { + return _position.IsEqualApprox(other._position) && _size.IsEqualApprox(other.Size); + } + public override int GetHashCode() { return _position.GetHashCode() ^ _size.GetHashCode(); diff --git a/modules/mono/glue/Managed/Files/StringExtensions.cs b/modules/mono/glue/Managed/Files/StringExtensions.cs index c194facd0b..6045c83e95 100644 --- a/modules/mono/glue/Managed/Files/StringExtensions.cs +++ b/modules/mono/glue/Managed/Files/StringExtensions.cs @@ -98,6 +98,66 @@ namespace Godot } // <summary> + // Return the amount of substrings in string. + // </summary> + public static int Count(this string instance, string what, bool caseSensitive = true, int from = 0, int to = 0) + { + if (what.Length == 0) + { + return 0; + } + + int len = instance.Length; + int slen = what.Length; + + if (len < slen) + { + return 0; + } + + string str; + + if (from >= 0 && to >= 0) + { + if (to == 0) + { + to = len; + } + else if (from >= to) + { + return 0; + } + if (from == 0 && to == len) + { + str = instance; + } + else + { + str = instance.Substring(from, to - from); + } + } + else + { + return 0; + } + + int c = 0; + int idx; + + do + { + idx = str.IndexOf(what, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); + if (idx != -1) + { + str = str.Substring(idx + slen); + ++c; + } + } while (idx != -1); + + return c; + } + + // <summary> // Return a copy of the string with special characters escaped using the C language standard. // </summary> public static string CEscape(this string instance) @@ -299,14 +359,14 @@ namespace Godot if (basepos != -1) { var end = basepos + 3; - rs = instance.Substring(end, instance.Length); + rs = instance.Substring(end); @base = instance.Substring(0, end); } else { if (instance.BeginsWith("/")) { - rs = instance.Substring(1, instance.Length); + rs = instance.Substring(1); @base = "/"; } else @@ -333,7 +393,7 @@ namespace Godot if (sep == -1) return instance; - return instance.Substring(sep + 1, instance.Length); + return instance.Substring(sep + 1); } // <summary> @@ -911,7 +971,8 @@ namespace Godot // </summary> public static string Substr(this string instance, int from, int len) { - return instance.Substring(from, len); + int max = instance.Length - from; + return instance.Substring(from, len > max ? max : len); } // <summary> diff --git a/modules/mono/glue/Managed/Files/Transform.cs b/modules/mono/glue/Managed/Files/Transform.cs index bd79144873..0b84050f07 100644 --- a/modules/mono/glue/Managed/Files/Transform.cs +++ b/modules/mono/glue/Managed/Files/Transform.cs @@ -8,6 +8,7 @@ using real_t = System.Single; namespace Godot { + [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Transform : IEquatable<Transform> { @@ -33,7 +34,7 @@ namespace Godot Vector3 destinationLocation = transform.origin; var interpolated = new Transform(); - interpolated.basis.SetQuantScale(sourceRotation.Slerp(destinationRotation, c).Normalized(), sourceScale.LinearInterpolate(destinationScale, c)); + interpolated.basis.SetQuatScale(sourceRotation.Slerp(destinationRotation, c).Normalized(), sourceScale.LinearInterpolate(destinationScale, c)); interpolated.origin = sourceLocation.LinearInterpolate(destinationLocation, c); return interpolated; @@ -184,6 +185,11 @@ namespace Godot return basis.Equals(other.basis) && origin.Equals(other.origin); } + public bool IsEqualApprox(Transform other) + { + return basis.IsEqualApprox(other.basis) && origin.IsEqualApprox(other.origin); + } + public override int GetHashCode() { return basis.GetHashCode() ^ origin.GetHashCode(); diff --git a/modules/mono/glue/Managed/Files/Transform2D.cs b/modules/mono/glue/Managed/Files/Transform2D.cs index f7bb41d523..77ea3e5830 100644 --- a/modules/mono/glue/Managed/Files/Transform2D.cs +++ b/modules/mono/glue/Managed/Files/Transform2D.cs @@ -8,6 +8,7 @@ using real_t = System.Single; namespace Godot { + [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Transform2D : IEquatable<Transform2D> { @@ -98,6 +99,8 @@ namespace Godot return x[columnIndex]; case 1: return y[columnIndex]; + case 2: + return origin[columnIndex]; default: throw new IndexOutOfRangeException(); } @@ -112,6 +115,9 @@ namespace Godot case 1: y[columnIndex] = value; return; + case 2: + origin[columnIndex] = value; + return; default: throw new IndexOutOfRangeException(); } @@ -136,7 +142,7 @@ namespace Godot inv[0] *= new Vector2(detInv, -detInv); inv[1] *= new Vector2(-detInv, detInv); - inv[2] = BasisXform(-inv[2]); + inv[2] = inv.BasisXform(-inv[2]); return inv; } @@ -298,6 +304,7 @@ namespace Godot origin = originPos; } + // Arguments are named such that xy is equal to calling x.y public Transform2D(real_t xx, real_t xy, real_t yx, real_t yy, real_t ox, real_t oy) { x = new Vector2(xx, xy); @@ -350,6 +357,11 @@ namespace Godot return x.Equals(other.x) && y.Equals(other.y) && origin.Equals(other.origin); } + public bool IsEqualApprox(Transform2D other) + { + return x.IsEqualApprox(other.x) && y.IsEqualApprox(other.y) && origin.IsEqualApprox(other.origin); + } + public override int GetHashCode() { return x.GetHashCode() ^ y.GetHashCode() ^ origin.GetHashCode(); diff --git a/modules/mono/glue/Managed/Files/Vector2.cs b/modules/mono/glue/Managed/Files/Vector2.cs index 73a3252fdb..f92453f546 100644 --- a/modules/mono/glue/Managed/Files/Vector2.cs +++ b/modules/mono/glue/Managed/Files/Vector2.cs @@ -14,9 +14,19 @@ using real_t = System.Single; namespace Godot { + /// <summary> + /// 2-element structure that can be used to represent positions in 2D space or any other pair of numeric values. + /// </summary> + [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector2 : IEquatable<Vector2> { + public enum Axis + { + X = 0, + Y + } + public real_t x; public real_t y; @@ -52,11 +62,15 @@ namespace Godot internal void Normalize() { - real_t length = x * x + y * y; + real_t lengthsq = LengthSquared(); - if (length != 0f) + if (lengthsq == 0) + { + x = y = 0f; + } + else { - length = Mathf.Sqrt(length); + real_t length = Mathf.Sqrt(lengthsq); x /= length; y /= length; } @@ -132,6 +146,11 @@ namespace Godot (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); } + public Vector2 DirectionTo(Vector2 b) + { + return new Vector2(b.x - x, b.y - y).Normalized(); + } + public real_t DistanceSquaredTo(Vector2 to) { return (x - to.x) * (x - to.x) + (y - to.y) * (y - to.y); @@ -177,11 +196,35 @@ namespace Godot return res; } + public Vector2 MoveToward(Vector2 to, real_t delta) + { + var v = this; + var vd = to - v; + var len = vd.Length(); + return len <= delta || len < Mathf.Epsilon ? to : v + vd / len * delta; + } + public Vector2 Normalized() { - var result = this; - result.Normalize(); - return result; + var v = this; + v.Normalize(); + return v; + } + + public Vector2 PosMod(real_t mod) + { + Vector2 v; + v.x = Mathf.PosMod(x, mod); + v.y = Mathf.PosMod(y, mod); + return v; + } + + public Vector2 PosMod(Vector2 modv) + { + Vector2 v; + v.x = Mathf.PosMod(x, modv.x); + v.y = Mathf.PosMod(y, modv.y); + return v; } public Vector2 Project(Vector2 onNormal) @@ -205,17 +248,27 @@ namespace Godot return new Vector2(Mathf.Round(x), Mathf.Round(y)); } + [Obsolete("Set is deprecated. Use the Vector2(" + nameof(real_t) + ", " + nameof(real_t) + ") constructor instead.", error: true)] public void Set(real_t x, real_t y) { this.x = x; this.y = y; } + [Obsolete("Set is deprecated. Use the Vector2(" + nameof(Vector2) + ") constructor instead.", error: true)] public void Set(Vector2 v) { x = v.x; y = v.y; } + public Vector2 Sign() + { + Vector2 v; + v.x = Mathf.Sign(x); + v.y = Mathf.Sign(y); + return v; + } + public Vector2 Slerp(Vector2 b, real_t t) { real_t theta = AngleTo(b); @@ -245,7 +298,7 @@ namespace Godot private static readonly Vector2 _up = new Vector2(0, -1); private static readonly Vector2 _down = new Vector2(0, 1); - private static readonly Vector2 _right = new Vector2(1, 0); + private static readonly Vector2 _right = new Vector2(1, 0); private static readonly Vector2 _left = new Vector2(-1, 0); public static Vector2 Zero { get { return _zero; } } @@ -326,6 +379,20 @@ namespace Godot return left; } + public static Vector2 operator %(Vector2 vec, real_t divisor) + { + vec.x %= divisor; + vec.y %= divisor; + return vec; + } + + public static Vector2 operator %(Vector2 vec, Vector2 divisorv) + { + vec.x %= divisorv.x; + vec.y %= divisorv.y; + return vec; + } + public static bool operator ==(Vector2 left, Vector2 right) { return left.Equals(right); @@ -338,7 +405,7 @@ namespace Godot public static bool operator <(Vector2 left, Vector2 right) { - if (left.x.Equals(right.x)) + if (Mathf.IsEqualApprox(left.x, right.x)) { return left.y < right.y; } @@ -348,7 +415,7 @@ namespace Godot public static bool operator >(Vector2 left, Vector2 right) { - if (left.x.Equals(right.x)) + if (Mathf.IsEqualApprox(left.x, right.x)) { return left.y > right.y; } @@ -358,7 +425,7 @@ namespace Godot public static bool operator <=(Vector2 left, Vector2 right) { - if (left.x.Equals(right.x)) + if (Mathf.IsEqualApprox(left.x, right.x)) { return left.y <= right.y; } @@ -368,7 +435,7 @@ namespace Godot public static bool operator >=(Vector2 left, Vector2 right) { - if (left.x.Equals(right.x)) + if (Mathf.IsEqualApprox(left.x, right.x)) { return left.y >= right.y; } @@ -391,6 +458,11 @@ namespace Godot return x == other.x && y == other.y; } + public bool IsEqualApprox(Vector2 other) + { + return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y); + } + public override int GetHashCode() { return y.GetHashCode() ^ x.GetHashCode(); diff --git a/modules/mono/glue/Managed/Files/Vector3.cs b/modules/mono/glue/Managed/Files/Vector3.cs index f6ff27989d..025b09199f 100644 --- a/modules/mono/glue/Managed/Files/Vector3.cs +++ b/modules/mono/glue/Managed/Files/Vector3.cs @@ -14,6 +14,10 @@ using real_t = System.Single; namespace Godot { + /// <summary> + /// 3-element structure that can be used to represent positions in 3D space or any other pair of numeric values. + /// </summary> + [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector3 : IEquatable<Vector3> { @@ -65,14 +69,15 @@ namespace Godot internal void Normalize() { - real_t length = Length(); + real_t lengthsq = LengthSquared(); - if (length == 0f) + if (lengthsq == 0) { x = y = z = 0f; } else { + real_t length = Mathf.Sqrt(lengthsq); x /= length; y /= length; z /= length; @@ -126,6 +131,11 @@ namespace Godot ); } + public Vector3 DirectionTo(Vector3 b) + { + return new Vector3(b.x - x, b.y - y, b.z - z).Normalized(); + } + public real_t DistanceSquaredTo(Vector3 b) { return (b - this).LengthSquared(); @@ -184,6 +194,14 @@ namespace Godot ); } + public Vector3 MoveToward(Vector3 to, real_t delta) + { + var v = this; + var vd = to - v; + var len = vd.Length(); + return len <= delta || len < Mathf.Epsilon ? to : v + vd / len * delta; + } + public Axis MaxAxis() { return x < y ? (y < z ? Axis.Z : Axis.Y) : (x < z ? Axis.Z : Axis.X); @@ -210,6 +228,24 @@ namespace Godot ); } + public Vector3 PosMod(real_t mod) + { + Vector3 v; + v.x = Mathf.PosMod(x, mod); + v.y = Mathf.PosMod(y, mod); + v.z = Mathf.PosMod(z, mod); + return v; + } + + public Vector3 PosMod(Vector3 modv) + { + Vector3 v; + v.x = Mathf.PosMod(x, modv.x); + v.y = Mathf.PosMod(y, modv.y); + v.z = Mathf.PosMod(z, modv.z); + return v; + } + public Vector3 Project(Vector3 onNormal) { return onNormal * (Dot(onNormal) / onNormal.LengthSquared()); @@ -234,12 +270,14 @@ namespace Godot return new Basis(axis, phi).Xform(this); } + [Obsolete("Set is deprecated. Use the Vector3(" + nameof(real_t) + ", " + nameof(real_t) + ", " + nameof(real_t) + ") constructor instead.", error: true)] public void Set(real_t x, real_t y, real_t z) { this.x = x; this.y = y; this.z = z; } + [Obsolete("Set is deprecated. Use the Vector3(" + nameof(Vector3) + ") constructor instead.", error: true)] public void Set(Vector3 v) { x = v.x; @@ -247,6 +285,15 @@ namespace Godot z = v.z; } + public Vector3 Sign() + { + Vector3 v; + v.x = Mathf.Sign(x); + v.y = Mathf.Sign(y); + v.z = Mathf.Sign(z); + return v; + } + public Vector3 Slerp(Vector3 b, real_t t) { real_t theta = AngleTo(b); @@ -380,6 +427,22 @@ namespace Godot return left; } + public static Vector3 operator %(Vector3 vec, real_t divisor) + { + vec.x %= divisor; + vec.y %= divisor; + vec.z %= divisor; + return vec; + } + + public static Vector3 operator %(Vector3 vec, Vector3 divisorv) + { + vec.x %= divisorv.x; + vec.y %= divisorv.y; + vec.z %= divisorv.z; + return vec; + } + public static bool operator ==(Vector3 left, Vector3 right) { return left.Equals(right); @@ -392,9 +455,9 @@ namespace Godot public static bool operator <(Vector3 left, Vector3 right) { - if (left.x == right.x) + if (Mathf.IsEqualApprox(left.x, right.x)) { - if (left.y == right.y) + if (Mathf.IsEqualApprox(left.y, right.y)) return left.z < right.z; return left.y < right.y; } @@ -404,9 +467,9 @@ namespace Godot public static bool operator >(Vector3 left, Vector3 right) { - if (left.x == right.x) + if (Mathf.IsEqualApprox(left.x, right.x)) { - if (left.y == right.y) + if (Mathf.IsEqualApprox(left.y, right.y)) return left.z > right.z; return left.y > right.y; } @@ -416,9 +479,9 @@ namespace Godot public static bool operator <=(Vector3 left, Vector3 right) { - if (left.x == right.x) + if (Mathf.IsEqualApprox(left.x, right.x)) { - if (left.y == right.y) + if (Mathf.IsEqualApprox(left.y, right.y)) return left.z <= right.z; return left.y < right.y; } @@ -428,9 +491,9 @@ namespace Godot public static bool operator >=(Vector3 left, Vector3 right) { - if (left.x == right.x) + if (Mathf.IsEqualApprox(left.x, right.x)) { - if (left.y == right.y) + if (Mathf.IsEqualApprox(left.y, right.y)) return left.z >= right.z; return left.y > right.y; } @@ -453,6 +516,11 @@ namespace Godot return x == other.x && y == other.y && z == other.z; } + public bool IsEqualApprox(Vector3 other) + { + return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y) && Mathf.IsEqualApprox(z, other.z); + } + public override int GetHashCode() { return y.GetHashCode() ^ x.GetHashCode() ^ z.GetHashCode(); diff --git a/modules/mono/glue/Managed/IgnoredFiles/Node.cs b/modules/mono/glue/Managed/IgnoredFiles/Node.cs index 99ba0f827a..cff61b1e0b 100644 --- a/modules/mono/glue/Managed/IgnoredFiles/Node.cs +++ b/modules/mono/glue/Managed/IgnoredFiles/Node.cs @@ -15,9 +15,10 @@ namespace Godot throw new NotImplementedException(); } - public Node GetOwner() + public Node Owner { - throw new NotImplementedException(); + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); } public Node GetParent() diff --git a/modules/mono/glue/Managed/Managed.csproj b/modules/mono/glue/Managed/Managed.csproj index 61f738922b..c8eca71199 100644 --- a/modules/mono/glue/Managed/Managed.csproj +++ b/modules/mono/glue/Managed/Managed.csproj @@ -1,4 +1,4 @@ -<?xml version="1.0" encoding="utf-8"?> +<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> @@ -8,6 +8,7 @@ <RootNamespace>Managed</RootNamespace> <AssemblyName>Managed</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <LangVersion>7</LangVersion> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> <DebugSymbols>true</DebugSymbols> @@ -37,4 +38,4 @@ <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -</Project> +</Project>
\ No newline at end of file diff --git a/modules/mono/glue/base_object_glue.cpp b/modules/mono/glue/base_object_glue.cpp index 7f367fa095..2488f78350 100644 --- a/modules/mono/glue/base_object_glue.cpp +++ b/modules/mono/glue/base_object_glue.cpp @@ -36,6 +36,7 @@ #include "core/string_name.h" #include "../csharp_script.h" +#include "../mono_gd/gd_mono_cache.h" #include "../mono_gd/gd_mono_class.h" #include "../mono_gd/gd_mono_internals.h" #include "../mono_gd/gd_mono_utils.h" @@ -166,7 +167,7 @@ MonoArray *godot_icall_DynamicGodotObject_SetMemberList(Object *p_ptr) { int i = 0; for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) { MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E->get().name); - mono_array_set(result, MonoString *, i, boxed); + mono_array_setref(result, i, boxed); i++; } @@ -218,11 +219,27 @@ MonoBoolean godot_icall_DynamicGodotObject_SetMember(Object *p_ptr, MonoString * return valid; } +MonoString *godot_icall_Object_ToString(Object *p_ptr) { +#ifdef DEBUG_ENABLED + // Cannot happen in C#; would get an ObjectDisposedException instead. + CRASH_COND(p_ptr == NULL); + + if (ScriptDebugger::get_singleton() && !Object::cast_to<Reference>(p_ptr)) { // Only if debugging! + // Cannot happen either in C#; the handle is nullified when the object is destroyed + CRASH_COND(!ObjectDB::instance_validate(p_ptr)); + } +#endif + + String result = "[" + p_ptr->get_class() + ":" + itos(p_ptr->get_instance_id()) + "]"; + return GDMonoMarshal::mono_string_from_godot(result); +} + void godot_register_object_icalls() { mono_add_internal_call("Godot.Object::godot_icall_Object_Ctor", (void *)godot_icall_Object_Ctor); mono_add_internal_call("Godot.Object::godot_icall_Object_Disposed", (void *)godot_icall_Object_Disposed); mono_add_internal_call("Godot.Object::godot_icall_Reference_Disposed", (void *)godot_icall_Reference_Disposed); mono_add_internal_call("Godot.Object::godot_icall_Object_ClassDB_get_method", (void *)godot_icall_Object_ClassDB_get_method); + mono_add_internal_call("Godot.Object::godot_icall_Object_ToString", (void *)godot_icall_Object_ToString); mono_add_internal_call("Godot.Object::godot_icall_Object_weakref", (void *)godot_icall_Object_weakref); mono_add_internal_call("Godot.SignalAwaiter::godot_icall_SignalAwaiter_connect", (void *)godot_icall_SignalAwaiter_connect); mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMemberList", (void *)godot_icall_DynamicGodotObject_SetMemberList); diff --git a/modules/mono/glue/base_object_glue.h b/modules/mono/glue/base_object_glue.h index 9b5224a347..e4ac9fb99d 100644 --- a/modules/mono/glue/base_object_glue.h +++ b/modules/mono/glue/base_object_glue.h @@ -60,6 +60,8 @@ MonoBoolean godot_icall_DynamicGodotObject_GetMember(Object *p_ptr, MonoString * MonoBoolean godot_icall_DynamicGodotObject_SetMember(Object *p_ptr, MonoString *p_name, MonoObject *p_value); +MonoString *godot_icall_Object_ToString(Object *p_ptr); + // Register internal calls void godot_register_object_icalls(); diff --git a/modules/mono/glue/collections_glue.cpp b/modules/mono/glue/collections_glue.cpp index 84c3f354d8..e84a5becd6 100644 --- a/modules/mono/glue/collections_glue.cpp +++ b/modules/mono/glue/collections_glue.cpp @@ -34,6 +34,7 @@ #include <mono/metadata/exception.h> +#include "../mono_gd/gd_mono_cache.h" #include "../mono_gd/gd_mono_class.h" #include "../mono_gd/gd_mono_utils.h" @@ -46,7 +47,7 @@ void godot_icall_Array_Dtor(Array *ptr) { } MonoObject *godot_icall_Array_At(Array *ptr, int index) { - if (index < 0 || index > ptr->size()) { + if (index < 0 || index >= ptr->size()) { GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range()); return NULL; } @@ -54,7 +55,7 @@ MonoObject *godot_icall_Array_At(Array *ptr, int index) { } MonoObject *godot_icall_Array_At_Generic(Array *ptr, int index, uint32_t type_encoding, GDMonoClass *type_class) { - if (index < 0 || index > ptr->size()) { + if (index < 0 || index >= ptr->size()) { GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range()); return NULL; } @@ -62,7 +63,7 @@ MonoObject *godot_icall_Array_At_Generic(Array *ptr, int index, uint32_t type_en } void godot_icall_Array_SetAt(Array *ptr, int index, MonoObject *value) { - if (index < 0 || index > ptr->size()) { + if (index < 0 || index >= ptr->size()) { GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range()); return; } @@ -102,6 +103,10 @@ void godot_icall_Array_CopyTo(Array *ptr, MonoArray *array, int array_index) { } } +Array *godot_icall_Array_Duplicate(Array *ptr, MonoBoolean deep) { + return memnew(Array(ptr->duplicate(deep))); +} + int godot_icall_Array_IndexOf(Array *ptr, MonoObject *item) { return ptr->find(GDMonoMarshal::mono_object_to_variant(item)); } @@ -124,7 +129,7 @@ MonoBoolean godot_icall_Array_Remove(Array *ptr, MonoObject *item) { } void godot_icall_Array_RemoveAt(Array *ptr, int index) { - if (index < 0 || index > ptr->size()) { + if (index < 0 || index >= ptr->size()) { GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range()); return; } @@ -143,6 +148,10 @@ void godot_icall_Array_Generic_GetElementTypeInfo(MonoReflectionType *refltype, *type_class = GDMono::get_singleton()->get_class(type_class_raw); } +MonoString *godot_icall_Array_ToString(Array *ptr) { + return GDMonoMarshal::mono_string_from_godot(Variant(*ptr).operator String()); +} + Dictionary *godot_icall_Dictionary_Ctor() { return memnew(Dictionary); } @@ -158,7 +167,7 @@ MonoObject *godot_icall_Dictionary_GetValue(Dictionary *ptr, MonoObject *key) { #ifdef DEBUG_ENABLED CRASH_COND(!exc); #endif - GDMonoUtils::runtime_object_init(exc); + GDMonoUtils::runtime_object_init(exc, CACHED_CLASS(KeyNotFoundException)); GDMonoUtils::set_pending_exception((MonoException *)exc); return NULL; } @@ -172,7 +181,7 @@ MonoObject *godot_icall_Dictionary_GetValue_Generic(Dictionary *ptr, MonoObject #ifdef DEBUG_ENABLED CRASH_COND(!exc); #endif - GDMonoUtils::runtime_object_init(exc); + GDMonoUtils::runtime_object_init(exc, CACHED_CLASS(KeyNotFoundException)); GDMonoUtils::set_pending_exception((MonoException *)exc); return NULL; } @@ -219,6 +228,10 @@ MonoBoolean godot_icall_Dictionary_ContainsKey(Dictionary *ptr, MonoObject *key) return ptr->has(GDMonoMarshal::mono_object_to_variant(key)); } +Dictionary *godot_icall_Dictionary_Duplicate(Dictionary *ptr, MonoBoolean deep) { + return memnew(Dictionary(ptr->duplicate(deep))); +} + MonoBoolean godot_icall_Dictionary_RemoveKey(Dictionary *ptr, MonoObject *key) { return ptr->erase(GDMonoMarshal::mono_object_to_variant(key)); } @@ -264,6 +277,10 @@ void godot_icall_Dictionary_Generic_GetValueTypeInfo(MonoReflectionType *refltyp *type_class = GDMono::get_singleton()->get_class(type_class_raw); } +MonoString *godot_icall_Dictionary_ToString(Dictionary *ptr) { + return GDMonoMarshal::mono_string_from_godot(Variant(*ptr).operator String()); +} + void godot_register_collections_icalls() { mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Ctor", (void *)godot_icall_Array_Ctor); mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Dtor", (void *)godot_icall_Array_Dtor); @@ -275,12 +292,14 @@ void godot_register_collections_icalls() { mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Clear", (void *)godot_icall_Array_Clear); mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Contains", (void *)godot_icall_Array_Contains); mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_CopyTo", (void *)godot_icall_Array_CopyTo); + mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Duplicate", (void *)godot_icall_Array_Duplicate); mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_IndexOf", (void *)godot_icall_Array_IndexOf); mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Insert", (void *)godot_icall_Array_Insert); mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Remove", (void *)godot_icall_Array_Remove); mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_RemoveAt", (void *)godot_icall_Array_RemoveAt); mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Resize", (void *)godot_icall_Array_Resize); mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Generic_GetElementTypeInfo", (void *)godot_icall_Array_Generic_GetElementTypeInfo); + mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_ToString", (void *)godot_icall_Array_ToString); mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Ctor", (void *)godot_icall_Dictionary_Ctor); mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Dtor", (void *)godot_icall_Dictionary_Dtor); @@ -294,11 +313,13 @@ void godot_register_collections_icalls() { mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Clear", (void *)godot_icall_Dictionary_Clear); mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Contains", (void *)godot_icall_Dictionary_Contains); mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_ContainsKey", (void *)godot_icall_Dictionary_ContainsKey); + mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Duplicate", (void *)godot_icall_Dictionary_Duplicate); mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_RemoveKey", (void *)godot_icall_Dictionary_RemoveKey); mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Remove", (void *)godot_icall_Dictionary_Remove); mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_TryGetValue", (void *)godot_icall_Dictionary_TryGetValue); mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_TryGetValue_Generic", (void *)godot_icall_Dictionary_TryGetValue_Generic); mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Generic_GetValueTypeInfo", (void *)godot_icall_Dictionary_Generic_GetValueTypeInfo); + mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_ToString", (void *)godot_icall_Dictionary_ToString); } #endif // MONO_GLUE_ENABLED diff --git a/modules/mono/glue/collections_glue.h b/modules/mono/glue/collections_glue.h index 69768500d8..a79a651fcd 100644 --- a/modules/mono/glue/collections_glue.h +++ b/modules/mono/glue/collections_glue.h @@ -59,6 +59,8 @@ MonoBoolean godot_icall_Array_Contains(Array *ptr, MonoObject *item); void godot_icall_Array_CopyTo(Array *ptr, MonoArray *array, int array_index); +Array *godot_icall_Array_Duplicate(Array *ptr, MonoBoolean deep); + int godot_icall_Array_IndexOf(Array *ptr, MonoObject *item); void godot_icall_Array_Insert(Array *ptr, int index, MonoObject *item); @@ -71,6 +73,8 @@ Error godot_icall_Array_Resize(Array *ptr, int new_size); void godot_icall_Array_Generic_GetElementTypeInfo(MonoReflectionType *refltype, uint32_t *type_encoding, GDMonoClass **type_class); +MonoString *godot_icall_Array_ToString(Array *ptr); + // Dictionary Dictionary *godot_icall_Dictionary_Ctor(); @@ -97,6 +101,8 @@ MonoBoolean godot_icall_Dictionary_Contains(Dictionary *ptr, MonoObject *key, Mo MonoBoolean godot_icall_Dictionary_ContainsKey(Dictionary *ptr, MonoObject *key); +Dictionary *godot_icall_Dictionary_Duplicate(Dictionary *ptr, MonoBoolean deep); + MonoBoolean godot_icall_Dictionary_RemoveKey(Dictionary *ptr, MonoObject *key); MonoBoolean godot_icall_Dictionary_Remove(Dictionary *ptr, MonoObject *key, MonoObject *value); @@ -107,6 +113,8 @@ MonoBoolean godot_icall_Dictionary_TryGetValue_Generic(Dictionary *ptr, MonoObje void godot_icall_Dictionary_Generic_GetValueTypeInfo(MonoReflectionType *refltype, uint32_t *type_encoding, GDMonoClass **type_class); +MonoString *godot_icall_Dictionary_ToString(Dictionary *ptr); + // Register internal calls void godot_register_collections_icalls(); diff --git a/modules/mono/glue/gd_glue.cpp b/modules/mono/glue/gd_glue.cpp index d756131ac9..1381d79e2e 100644 --- a/modules/mono/glue/gd_glue.cpp +++ b/modules/mono/glue/gd_glue.cpp @@ -39,6 +39,7 @@ #include "core/variant.h" #include "core/variant_parser.h" +#include "../mono_gd/gd_mono_cache.h" #include "../mono_gd/gd_mono_utils.h" MonoObject *godot_icall_GD_bytes2var(MonoArray *p_bytes, MonoBoolean p_allow_objects) { @@ -115,7 +116,7 @@ void godot_icall_GD_printt(MonoArray *p_what) { print_line(str); } -double godot_icall_GD_randf() { +float godot_icall_GD_randf() { return Math::randf(); } @@ -167,7 +168,7 @@ MonoObject *godot_icall_GD_str2var(MonoString *p_str) { int line; Error err = VariantParser::parse(&ss, ret, errs, line); if (err != OK) { - String err_str = "Parse error at line " + itos(line) + ": " + errs; + String err_str = "Parse error at line " + itos(line) + ": " + errs + "."; ERR_PRINTS(err_str); ret = err_str; } @@ -193,8 +194,7 @@ MonoArray *godot_icall_GD_var2bytes(MonoObject *p_var, MonoBoolean p_full_object PoolByteArray barr; int len; Error err = encode_variant(var, NULL, len, p_full_objects); - ERR_EXPLAIN("Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID)."); - ERR_FAIL_COND_V(err != OK, NULL); + ERR_FAIL_COND_V_MSG(err != OK, NULL, "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID)."); barr.resize(len); { @@ -211,6 +211,10 @@ MonoString *godot_icall_GD_var2str(MonoObject *p_var) { return GDMonoMarshal::mono_string_from_godot(vars); } +MonoObject *godot_icall_DefaultGodotTaskScheduler() { + return GDMonoCache::cached_data.task_scheduler_handle->get_target(); +} + void godot_register_gd_icalls() { mono_add_internal_call("Godot.GD::godot_icall_GD_bytes2var", (void *)godot_icall_GD_bytes2var); mono_add_internal_call("Godot.GD::godot_icall_GD_convert", (void *)godot_icall_GD_convert); @@ -234,6 +238,9 @@ void godot_register_gd_icalls() { mono_add_internal_call("Godot.GD::godot_icall_GD_type_exists", (void *)godot_icall_GD_type_exists); mono_add_internal_call("Godot.GD::godot_icall_GD_var2bytes", (void *)godot_icall_GD_var2bytes); mono_add_internal_call("Godot.GD::godot_icall_GD_var2str", (void *)godot_icall_GD_var2str); + + // Dispatcher + mono_add_internal_call("Godot.Dispatcher::godot_icall_DefaultGodotTaskScheduler", (void *)godot_icall_DefaultGodotTaskScheduler); } #endif // MONO_GLUE_ENABLED diff --git a/modules/mono/glue/gd_glue.h b/modules/mono/glue/gd_glue.h index 910979aae3..a34c0bc50f 100644 --- a/modules/mono/glue/gd_glue.h +++ b/modules/mono/glue/gd_glue.h @@ -53,7 +53,7 @@ void godot_icall_GD_prints(MonoArray *p_what); void godot_icall_GD_printt(MonoArray *p_what); -double godot_icall_GD_randf(); +float godot_icall_GD_randf(); uint32_t godot_icall_GD_randi(); @@ -75,6 +75,8 @@ MonoArray *godot_icall_GD_var2bytes(MonoObject *p_var, MonoBoolean p_full_object MonoString *godot_icall_GD_var2str(MonoObject *p_var); +MonoObject *godot_icall_DefaultGodotTaskScheduler(); + // Register internal calls void godot_register_gd_icalls(); diff --git a/modules/mono/glue/string_glue.cpp b/modules/mono/glue/string_glue.cpp index a5c72160d7..e9373fb486 100644 --- a/modules/mono/glue/string_glue.cpp +++ b/modules/mono/glue/string_glue.cpp @@ -68,12 +68,12 @@ MonoString *godot_icall_String_sha256_text(MonoString *p_str) { } void godot_register_string_icalls() { - mono_add_internal_call("Godot.String::godot_icall_String_md5_buffer", (void *)godot_icall_String_md5_buffer); - mono_add_internal_call("Godot.String::godot_icall_String_md5_text", (void *)godot_icall_String_md5_text); - mono_add_internal_call("Godot.String::godot_icall_String_rfind", (void *)godot_icall_String_rfind); - mono_add_internal_call("Godot.String::godot_icall_String_rfindn", (void *)godot_icall_String_rfindn); - mono_add_internal_call("Godot.String::godot_icall_String_sha256_buffer", (void *)godot_icall_String_sha256_buffer); - mono_add_internal_call("Godot.String::godot_icall_String_sha256_text", (void *)godot_icall_String_sha256_text); + mono_add_internal_call("Godot.StringExtensions::godot_icall_String_md5_buffer", (void *)godot_icall_String_md5_buffer); + mono_add_internal_call("Godot.StringExtensions::godot_icall_String_md5_text", (void *)godot_icall_String_md5_text); + mono_add_internal_call("Godot.StringExtensions::godot_icall_String_rfind", (void *)godot_icall_String_rfind); + mono_add_internal_call("Godot.StringExtensions::godot_icall_String_rfindn", (void *)godot_icall_String_rfindn); + mono_add_internal_call("Godot.StringExtensions::godot_icall_String_sha256_buffer", (void *)godot_icall_String_sha256_buffer); + mono_add_internal_call("Godot.StringExtensions::godot_icall_String_sha256_text", (void *)godot_icall_String_sha256_text); } #endif // MONO_GLUE_ENABLED diff --git a/modules/mono/godotsharp_defs.h b/modules/mono/godotsharp_defs.h index 0d3b96d789..4c17a6ec9d 100644 --- a/modules/mono/godotsharp_defs.h +++ b/modules/mono/godotsharp_defs.h @@ -39,7 +39,8 @@ #define API_SOLUTION_NAME "GodotSharp" #define CORE_API_ASSEMBLY_NAME "GodotSharp" #define EDITOR_API_ASSEMBLY_NAME "GodotSharpEditor" -#define EDITOR_TOOLS_ASSEMBLY_NAME "GodotSharpTools" +#define TOOLS_ASM_NAME "GodotTools" +#define TOOLS_PROJECT_EDITOR_ASM_NAME "GodotTools.ProjectEditor" #define BINDINGS_CLASS_NATIVECALLS "NativeCalls" #define BINDINGS_CLASS_NATIVECALLS_EDITOR "EditorNativeCalls" diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp index 09a1fc6fbc..ef30a52b72 100644 --- a/modules/mono/godotsharp_dirs.cpp +++ b/modules/mono/godotsharp_dirs.cpp @@ -39,6 +39,12 @@ #include "editor/editor_settings.h" #endif +#ifdef ANDROID_ENABLED +#include "mono_gd/gd_mono_android.h" +#endif + +#include "mono_gd/gd_mono.h" + namespace GodotSharpDirs { String _get_expected_build_config() { @@ -84,6 +90,7 @@ class _GodotSharpDirs { public: String res_data_dir; String res_metadata_dir; + String res_assemblies_base_dir; String res_assemblies_dir; String res_config_dir; String res_temp_dir; @@ -101,6 +108,10 @@ public: String data_editor_tools_dir; String data_editor_prebuilt_api_dir; +#else + // Equivalent of res_assemblies_dir, but in the data directory rather than in 'res://'. + // Only defined on export templates. Used when exporting assemblies outside of PCKs. + String data_game_assemblies_dir; #endif String data_mono_etc_dir; @@ -114,7 +125,8 @@ private: _GodotSharpDirs() { res_data_dir = "res://.mono"; res_metadata_dir = res_data_dir.plus_file("metadata"); - res_assemblies_dir = res_data_dir.plus_file("assemblies"); + res_assemblies_base_dir = res_data_dir.plus_file("assemblies"); + res_assemblies_dir = res_assemblies_base_dir.plus_file(GDMono::get_expected_api_build_config()); res_config_dir = res_data_dir.plus_file("etc").plus_file("mono"); // TODO use paths from csproj @@ -122,22 +134,27 @@ private: res_temp_assemblies_base_dir = res_temp_dir.plus_file("bin"); res_temp_assemblies_dir = res_temp_assemblies_base_dir.plus_file(_get_expected_build_config()); +#ifdef JAVASCRIPT_ENABLED + mono_user_dir = "user://"; +#else mono_user_dir = _get_mono_user_dir(); +#endif mono_logs_dir = mono_user_dir.plus_file("mono_logs"); #ifdef TOOLS_ENABLED mono_solutions_dir = mono_user_dir.plus_file("solutions"); build_logs_dir = mono_user_dir.plus_file("build_logs"); - String name = ProjectSettings::get_singleton()->get("application/config/name"); - if (name.empty()) { - name = "UnnamedProject"; + String appname = ProjectSettings::get_singleton()->get("application/config/name"); + String appname_safe = OS::get_singleton()->get_safe_dir_name(appname); + if (appname_safe.empty()) { + appname_safe = "UnnamedProject"; } String base_path = ProjectSettings::get_singleton()->globalize_path("res://"); - sln_filepath = base_path.plus_file(name + ".sln"); - csproj_filepath = base_path.plus_file(name + ".csproj"); + sln_filepath = base_path.plus_file(appname_safe + ".sln"); + csproj_filepath = base_path.plus_file(appname_safe + ".csproj"); #endif String exe_dir = OS::get_singleton()->get_executable_path().get_base_dir(); @@ -150,7 +167,12 @@ private: String data_mono_root_dir = data_dir_root.plus_file("Mono"); data_mono_etc_dir = data_mono_root_dir.plus_file("etc"); + +#ifdef ANDROID_ENABLED + data_mono_lib_dir = GDMonoAndroid::get_app_native_lib_dir(); +#else data_mono_lib_dir = data_mono_root_dir.plus_file("lib"); +#endif #ifdef WINDOWS_ENABLED data_mono_bin_dir = data_mono_root_dir.plus_file("bin"); @@ -173,15 +195,22 @@ private: #else - String appname = OS::get_singleton()->get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name")); - String data_dir_root = exe_dir.plus_file("data_" + appname); + String appname = ProjectSettings::get_singleton()->get("application/config/name"); + String appname_safe = OS::get_singleton()->get_safe_dir_name(appname); + String data_dir_root = exe_dir.plus_file("data_" + appname_safe); if (!DirAccess::exists(data_dir_root)) { data_dir_root = exe_dir.plus_file("data_Godot"); } String data_mono_root_dir = data_dir_root.plus_file("Mono"); data_mono_etc_dir = data_mono_root_dir.plus_file("etc"); + +#ifdef ANDROID_ENABLED + data_mono_lib_dir = GDMonoAndroid::get_app_native_lib_dir(); +#else data_mono_lib_dir = data_mono_root_dir.plus_file("lib"); + data_game_assemblies_dir = data_dir_root.plus_file("Assemblies"); +#endif #ifdef WINDOWS_ENABLED data_mono_bin_dir = data_mono_root_dir.plus_file("bin"); @@ -192,6 +221,10 @@ private: data_mono_etc_dir = exe_dir.plus_file("../Resources/GodotSharp/Mono/etc"); data_mono_lib_dir = exe_dir.plus_file("../Frameworks/GodotSharp/Mono/lib"); } + + if (!DirAccess::exists(data_game_assemblies_dir)) { + data_game_assemblies_dir = exe_dir.plus_file("../Frameworks/GodotSharp/Assemblies"); + } #endif #endif @@ -215,6 +248,10 @@ String get_res_metadata_dir() { return _GodotSharpDirs::get_singleton().res_metadata_dir; } +String get_res_assemblies_base_dir() { + return _GodotSharpDirs::get_singleton().res_assemblies_base_dir; +} + String get_res_assemblies_dir() { return _GodotSharpDirs::get_singleton().res_assemblies_dir; } @@ -267,6 +304,10 @@ String get_data_editor_tools_dir() { String get_data_editor_prebuilt_api_dir() { return _GodotSharpDirs::get_singleton().data_editor_prebuilt_api_dir; } +#else +String get_data_game_assemblies_dir() { + return _GodotSharpDirs::get_singleton().data_game_assemblies_dir; +} #endif String get_data_mono_etc_dir() { diff --git a/modules/mono/godotsharp_dirs.h b/modules/mono/godotsharp_dirs.h index 556df959e2..43da44b0f5 100644 --- a/modules/mono/godotsharp_dirs.h +++ b/modules/mono/godotsharp_dirs.h @@ -37,6 +37,7 @@ namespace GodotSharpDirs { String get_res_data_dir(); String get_res_metadata_dir(); +String get_res_assemblies_base_dir(); String get_res_assemblies_dir(); String get_res_config_dir(); String get_res_temp_dir(); @@ -55,6 +56,8 @@ String get_project_csproj_path(); String get_data_editor_tools_dir(); String get_data_editor_prebuilt_api_dir(); +#else +String get_data_game_assemblies_dir(); #endif String get_data_mono_etc_dir(); diff --git a/modules/mono/icons/icon_c_#.svg b/modules/mono/icons/icon_c_#.svg new file mode 100644 index 0000000000..69664ca553 --- /dev/null +++ b/modules/mono/icons/icon_c_#.svg @@ -0,0 +1,5 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<path d="m6 1046.4c-1.6569 0-3 1.3431-3 3s1.3431 3 3 3h1v-2h-1c-0.55228 0-1-0.4478-1-1 0-0.5523 0.44772-1 1-1h1v-2zm1-9-0.56445 2.2578c-0.23643 0.076-0.46689 0.1692-0.68945 0.2793l-1.9883-1.1933-1.4141 1.414 1.1953 1.9942c-0.11191 0.2211-0.20723 0.4502-0.28516 0.6855l-2.2539 0.5625v2h5.2715c-0.17677-0.3037-0.27041-0.6486-0.27148-1 9.6e-6 -1.1046 0.89543-2 2-2s2 0.8954 2 2c-4.817e-4 0.3512-0.093442 0.6961-0.26953 1h5.2695v-2l-2.2578-0.5645c-0.07594-0.2357-0.1693-0.4655-0.2793-0.6875l1.1934-1.9902-1.4141-1.414-1.9941 1.1953c-0.22113-0.1119-0.45028-0.2073-0.68555-0.2852l-0.5625-2.2539zm4 9c-0.71466-1e-4 -1.3751 0.3811-1.7324 1-0.35727 0.6188-0.35727 1.3812 0 2 0.35733 0.6189 1.0178 1.0001 1.7324 1h-2v2h2c0.71466 1e-4 1.3751-0.3811 1.7324-1 0.35727-0.6188 0.35727-1.3812 0-2-0.35733-0.6189-1.0178-1.0001-1.7324-1h2v-2z" fill="#e0e0e0"/> +</g> +</svg> diff --git a/modules/mono/mono_gc_handle.h b/modules/mono/mono_gc_handle.h index 63b61aff18..60a1eed212 100644 --- a/modules/mono/mono_gc_handle.h +++ b/modules/mono/mono_gc_handle.h @@ -37,7 +37,7 @@ class MonoGCHandle : public Reference { - GDCLASS(MonoGCHandle, Reference) + GDCLASS(MonoGCHandle, Reference); bool released; bool weak; diff --git a/modules/mono/mono_gd/android_mono_config.h b/modules/mono/mono_gd/android_mono_config.h new file mode 100644 index 0000000000..c5cc244aec --- /dev/null +++ b/modules/mono/mono_gd/android_mono_config.h @@ -0,0 +1,43 @@ +/*************************************************************************/ +/* android_mono_config.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 ANDROID_MONO_CONFIG_H +#define ANDROID_MONO_CONFIG_H + +#ifdef ANDROID_ENABLED + +#include "core/ustring.h" + +// This function is defined in an auto-generated source file +String get_godot_android_mono_config(); + +#endif // ANDROID_ENABLED + +#endif // ANDROID_MONO_CONFIG_H diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index bba7df2c6a..33ba877352 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -30,6 +30,7 @@ #include "gd_mono.h" +#include <mono/metadata/environment.h> #include <mono/metadata/exception.h> #include <mono/metadata/mono-config.h> #include <mono/metadata/mono-debug.h> @@ -43,27 +44,39 @@ #include "core/project_settings.h" #include "../csharp_script.h" -#include "../glue/cs_glue_version.gen.h" #include "../godotsharp_dirs.h" #include "../utils/path_utils.h" +#include "gd_mono_cache.h" #include "gd_mono_class.h" #include "gd_mono_marshal.h" #include "gd_mono_utils.h" #ifdef TOOLS_ENABLED -#include "../editor/godotsharp_editor.h" #include "main/main.h" #endif -#define OUT_OF_SYNC_ERR_MESSAGE(m_assembly_name) "The assembly '" m_assembly_name "' is out of sync. " \ - "This error is expected if you just upgraded to a newer Godot version. " \ - "Building the project will update the assembly to the correct version." +#ifdef ANDROID_ENABLED +#include "android_mono_config.h" +#include "gd_mono_android.h" +#endif + +// TODO: +// This has turn into a gigantic mess. There's too much going on here. Too much #ifdef as well. +// It's just painful to read... It needs to be re-structured. Please, clean this up, future me. GDMono *GDMono::singleton = NULL; namespace { -void setup_runtime_main_args() { +#if defined(JAVASCRIPT_ENABLED) +extern "C" { +void mono_wasm_load_runtime(const char *managed_path, int enable_debugging); +} +#endif + +#if !defined(JAVASCRIPT_ENABLED) + +void gd_mono_setup_runtime_main_args() { CharString execpath = OS::get_singleton()->get_executable_path().utf8(); List<String> cmdline_args = OS::get_singleton()->get_cmdline_args(); @@ -84,7 +97,7 @@ void setup_runtime_main_args() { mono_runtime_set_main_args(main_args.size(), main_args.ptrw()); } -void gdmono_profiler_init() { +void gd_mono_profiler_init() { String profiler_args = GLOBAL_DEF("mono/profiler/args", "log:calls,alloc,sample,output=output.mlpd"); bool profiler_enabled = GLOBAL_DEF("mono/profiler/enabled", false); if (profiler_enabled) { @@ -92,9 +105,9 @@ void gdmono_profiler_init() { } } -#ifdef DEBUG_ENABLED +#if defined(DEBUG_ENABLED) -static bool _wait_for_debugger_msecs(uint32_t p_msecs) { +bool gd_mono_wait_for_debugger_msecs(uint32_t p_msecs) { do { if (mono_is_debugger_attached()) @@ -116,29 +129,33 @@ static bool _wait_for_debugger_msecs(uint32_t p_msecs) { return mono_is_debugger_attached(); } -void gdmono_debug_init() { +void gd_mono_debug_init() { mono_debug_init(MONO_DEBUG_FORMAT_MONO); + CharString da_args = OS::get_singleton()->get_environment("GODOT_MONO_DEBUGGER_AGENT").utf8(); + +#ifdef TOOLS_ENABLED int da_port = GLOBAL_DEF("mono/debugger_agent/port", 23685); bool da_suspend = GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false); int da_timeout = GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000); -#ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint() || ProjectSettings::get_singleton()->get_resource_path().empty() || Main::is_project_manager()) { - return; + if (da_args.size() == 0) + return; } -#endif - - CharString da_args = OS::get_singleton()->get_environment("GODOT_MONO_DEBUGGER_AGENT").utf8(); if (da_args.length() == 0) { da_args = String("--debugger-agent=transport=dt_socket,address=127.0.0.1:" + itos(da_port) + ",embedding=1,server=y,suspend=" + (da_suspend ? "y,timeout=" + itos(da_timeout) : "n")) .utf8(); } +#else + if (da_args.length() == 0) + return; // Exported games don't use the project settings to setup the debugger agent +#endif // --debugger-agent=help const char *options[] = { @@ -148,11 +165,37 @@ void gdmono_debug_init() { mono_jit_parse_options(2, (char **)options); } +#endif // defined(DEBUG_ENABLED) +#endif // !defined(JAVASCRIPT_ENABLED) + +#if defined(JAVASCRIPT_ENABLED) +MonoDomain *gd_initialize_mono_runtime() { + const char *vfs_prefix = "managed"; + int enable_debugging = 0; + +#ifdef DEBUG_ENABLED + enable_debugging = 1; +#endif + + mono_wasm_load_runtime(vfs_prefix, enable_debugging); + + return mono_get_root_domain(); +} +#else +MonoDomain *gd_initialize_mono_runtime() { +#ifdef DEBUG_ENABLED + gd_mono_debug_init(); +#endif + + return mono_jit_init_version("GodotEngine.RootDomain", "v4.0.30319"); +} #endif } // namespace void GDMono::add_mono_shared_libs_dir_to_path() { + // TODO: Replace this with a mono_dl_fallback + // By default Mono seems to search shared libraries in the following directories: // Current working directory, @executable_path@ and PATH // The parent directory of the image file (assembly where the dllimport method is declared) @@ -196,33 +239,24 @@ void GDMono::add_mono_shared_libs_dir_to_path() { #endif // WINDOWS_ENABLED || UNIX_ENABLED } -void GDMono::initialize() { - - ERR_FAIL_NULL(Engine::get_singleton()); - - print_verbose("Mono: Initializing module..."); +void GDMono::determine_mono_dirs(String &r_assembly_rootdir, String &r_config_dir) { -#ifdef DEBUG_METHODS_ENABLED - _initialize_and_check_api_hashes(); -#endif - - GDMonoLog::get_singleton()->initialize(); - - String assembly_rootdir; - String config_dir; + String bundled_assembly_rootdir = GodotSharpDirs::get_data_mono_lib_dir(); + String bundled_config_dir = GodotSharpDirs::get_data_mono_etc_dir(); #ifdef TOOLS_ENABLED -#ifdef WINDOWS_ENABLED + +#if defined(WINDOWS_ENABLED) mono_reg_info = MonoRegUtils::find_mono(); if (mono_reg_info.assembly_dir.length() && DirAccess::exists(mono_reg_info.assembly_dir)) { - assembly_rootdir = mono_reg_info.assembly_dir; + r_assembly_rootdir = mono_reg_info.assembly_dir; } if (mono_reg_info.config_dir.length() && DirAccess::exists(mono_reg_info.config_dir)) { - config_dir = mono_reg_info.config_dir; + r_config_dir = mono_reg_info.config_dir; } -#elif OSX_ENABLED +#elif defined(OSX_ENABLED) const char *c_assembly_rootdir = mono_assembly_getrootdir(); const char *c_config_dir = mono_get_config_dir(); @@ -232,209 +266,239 @@ void GDMono::initialize() { locations.push_back("/usr/local/var/homebrew/linked/mono/"); for (int i = 0; i < locations.size(); i++) { - String hint_assembly_rootdir = path_join(locations[i], "lib"); - String hint_mscorlib_path = path_join(hint_assembly_rootdir, "mono", "4.5", "mscorlib.dll"); - String hint_config_dir = path_join(locations[i], "etc"); + String hint_assembly_rootdir = path::join(locations[i], "lib"); + String hint_mscorlib_path = path::join(hint_assembly_rootdir, "mono", "4.5", "mscorlib.dll"); + String hint_config_dir = path::join(locations[i], "etc"); if (FileAccess::exists(hint_mscorlib_path) && DirAccess::exists(hint_config_dir)) { - assembly_rootdir = hint_assembly_rootdir; - config_dir = hint_config_dir; + r_assembly_rootdir = hint_assembly_rootdir; + r_config_dir = hint_config_dir; break; } } } #endif -#endif // TOOLS_ENABLED - String bundled_assembly_rootdir = GodotSharpDirs::get_data_mono_lib_dir(); - String bundled_config_dir = GodotSharpDirs::get_data_mono_etc_dir(); + if (DirAccess::exists(bundled_assembly_rootdir)) { + r_assembly_rootdir = bundled_assembly_rootdir; + } -#ifdef TOOLS_ENABLED - if (DirAccess::exists(bundled_assembly_rootdir) && DirAccess::exists(bundled_config_dir)) { - assembly_rootdir = bundled_assembly_rootdir; - config_dir = bundled_config_dir; + if (DirAccess::exists(bundled_config_dir)) { + r_config_dir = bundled_config_dir; } #ifdef WINDOWS_ENABLED - if (assembly_rootdir.empty() || config_dir.empty()) { + if (r_assembly_rootdir.empty() || r_config_dir.empty()) { + ERR_PRINT("Cannot find Mono in the registry."); // Assertion: if they are not set, then they weren't found in the registry CRASH_COND(mono_reg_info.assembly_dir.length() > 0 || mono_reg_info.config_dir.length() > 0); - - ERR_PRINT("Cannot find Mono in the registry"); } #endif // WINDOWS_ENABLED #else - // These are always the directories in export templates - assembly_rootdir = bundled_assembly_rootdir; - config_dir = bundled_config_dir; -#endif // TOOLS_ENABLED + // Export templates always use the bundled directories + r_assembly_rootdir = bundled_assembly_rootdir; + r_config_dir = bundled_config_dir; +#endif +} + +void GDMono::initialize() { + + ERR_FAIL_NULL(Engine::get_singleton()); + + print_verbose("Mono: Initializing module..."); + + char *runtime_build_info = mono_get_runtime_build_info(); + print_verbose("Mono JIT compiler version " + String(runtime_build_info)); + mono_free(runtime_build_info); + + _init_godot_api_hashes(); + _init_exception_policy(); + + GDMonoLog::get_singleton()->initialize(); + +#if !defined(JAVASCRIPT_ENABLED) + String assembly_rootdir; + String config_dir; + determine_mono_dirs(assembly_rootdir, config_dir); // Leak if we call mono_set_dirs more than once mono_set_dirs(assembly_rootdir.length() ? assembly_rootdir.utf8().get_data() : NULL, config_dir.length() ? config_dir.utf8().get_data() : NULL); add_mono_shared_libs_dir_to_path(); +#endif - GDMonoAssembly::initialize(); +#if defined(ANDROID_ENABLED) + GDMonoAndroid::initialize(); +#endif - gdmono_profiler_init(); + GDMonoAssembly::initialize(); -#ifdef DEBUG_ENABLED - gdmono_debug_init(); +#if !defined(JAVASCRIPT_ENABLED) + gd_mono_profiler_init(); #endif +#ifdef ANDROID_ENABLED + mono_config_parse_memory(get_godot_android_mono_config().utf8().get_data()); +#else mono_config_parse(NULL); +#endif mono_install_unhandled_exception_hook(&unhandled_exception_hook, NULL); #ifndef TOOLS_ENABLED - if (!DirAccess::exists("res://.mono")) { - // 'res://.mono/' is missing so there is nothing to load. We don't need to initialize mono, but - // we still do so unless mscorlib is missing (which is the case for projects that don't use C#). - - String mscorlib_fname("mscorlib.dll"); - - Vector<String> search_dirs; - GDMonoAssembly::fill_search_dirs(search_dirs); - - bool found = false; - for (int i = 0; i < search_dirs.size(); i++) { - if (FileAccess::exists(search_dirs[i].plus_file(mscorlib_fname))) { - found = true; - break; - } - } + // Exported games that don't use C# must still work. They likely don't ship with mscorlib. + // We only initialize the Mono runtime if we can find mscorlib. Otherwise it would crash. + if (GDMonoAssembly::find_assembly("mscorlib.dll").empty()) { + print_verbose("Mono: Skipping runtime initialization because 'mscorlib.dll' could not be found"); + return; + } +#endif - if (!found) - return; // mscorlib is missing, do not initialize mono +#if !defined(WINDOWS_ENABLED) && !defined(NO_MONO_THREADS_SUSPEND_WORKAROUND) + // FIXME: Temporary workaround. See: https://github.com/godotengine/godot/issues/29812 + if (!OS::get_singleton()->has_environment("MONO_THREADS_SUSPEND")) { + OS::get_singleton()->set_environment("MONO_THREADS_SUSPEND", "preemptive"); } #endif - root_domain = mono_jit_init_version("GodotEngine.RootDomain", "v4.0.30319"); + // NOTE: Internal calls must be registered after the Mono runtime initialization. + // Otherwise registration fails with the error: 'assertion 'hash != NULL' failed'. - ERR_EXPLAIN("Mono: Failed to initialize runtime"); - ERR_FAIL_NULL(root_domain); + root_domain = gd_initialize_mono_runtime(); + ERR_FAIL_NULL_MSG(root_domain, "Mono: Failed to initialize runtime."); GDMonoUtils::set_main_thread(GDMonoUtils::get_current_thread()); - setup_runtime_main_args(); // Required for System.Environment.GetCommandLineArgs +#if !defined(JAVASCRIPT_ENABLED) + gd_mono_setup_runtime_main_args(); // Required for System.Environment.GetCommandLineArgs +#endif runtime_initialized = true; print_verbose("Mono: Runtime initialized"); - // mscorlib assembly MUST be present at initialization - ERR_EXPLAIN("Mono: Failed to load mscorlib assembly"); - ERR_FAIL_COND(!_load_corlib_assembly()); - -#ifdef TOOLS_ENABLED - // The tools domain must be loaded here, before the scripts domain. - // Otherwise domain unload on the scripts domain will hang indefinitely. - - ERR_EXPLAIN("Mono: Failed to load tools domain"); - ERR_FAIL_COND(_load_tools_domain() != OK); - - // TODO move to editor init callback, and do it lazily when required before editor init (e.g.: bindings generation) - ERR_EXPLAIN("Mono: Failed to load Editor Tools assembly"); - ERR_FAIL_COND(!_load_editor_tools_assembly()); +#if defined(ANDROID_ENABLED) + GDMonoAndroid::register_internal_calls(); #endif - ERR_EXPLAIN("Mono: Failed to load scripts domain"); - ERR_FAIL_COND(_load_scripts_domain() != OK); + // mscorlib assembly MUST be present at initialization + bool corlib_loaded = _load_corlib_assembly(); + ERR_FAIL_COND_MSG(!corlib_loaded, "Mono: Failed to load mscorlib assembly."); -#ifdef DEBUG_ENABLED - bool debugger_attached = _wait_for_debugger_msecs(500); + Error domain_load_err = _load_scripts_domain(); + ERR_FAIL_COND_MSG(domain_load_err != OK, "Mono: Failed to load scripts domain."); + +#if defined(DEBUG_ENABLED) && !defined(JAVASCRIPT_ENABLED) + bool debugger_attached = gd_mono_wait_for_debugger_msecs(500); if (!debugger_attached && OS::get_singleton()->is_stdout_verbose()) print_error("Mono: Debugger wait timeout"); #endif _register_internal_calls(); - // The following assemblies are not required at initialization -#ifdef MONO_GLUE_ENABLED - if (_load_api_assemblies()) { - // Everything is fine with the api assemblies, load the project assembly - _load_project_assembly(); - } else { - if ((core_api_assembly && (core_api_assembly_out_of_sync || !GDMonoUtils::mono_cache.godot_api_cache_updated)) -#ifdef TOOLS_ENABLED - || (editor_api_assembly && editor_api_assembly_out_of_sync) + print_verbose("Mono: INITIALIZED"); +} + +void GDMono::initialize_load_assemblies() { + +#ifndef MONO_GLUE_ENABLED + CRASH_NOW_MSG("Mono: This binary was built with 'mono_glue=no'; cannot load assemblies."); #endif - ) { -#ifdef TOOLS_ENABLED - // The assembly was successfully loaded, but the full api could not be cached. - // This is most likely an outdated assembly loaded because of an invalid version in the - // metadata, so we invalidate the version in the metadata and unload the script domain. - - if (core_api_assembly_out_of_sync) { - ERR_PRINT(OUT_OF_SYNC_ERR_MESSAGE(CORE_API_ASSEMBLY_NAME)); - metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true); - } else if (!GDMonoUtils::mono_cache.godot_api_cache_updated) { - ERR_PRINT("The loaded assembly '" CORE_API_ASSEMBLY_NAME "' is in sync, but the cache update failed"); - metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true); - } - if (editor_api_assembly_out_of_sync) { - ERR_PRINT(OUT_OF_SYNC_ERR_MESSAGE(EDITOR_API_ASSEMBLY_NAME)); - metadata_set_api_assembly_invalidated(APIAssembly::API_EDITOR, true); - } + // Load assemblies. The API and tools assemblies are required, + // the application is aborted if these assemblies cannot be loaded. - print_line("Mono: Proceeding to unload scripts domain because of invalid API assemblies."); + _load_api_assemblies(); - Error err = _unload_scripts_domain(); - if (err != OK) { - WARN_PRINT("Mono: Failed to unload scripts domain"); - } -#else - ERR_PRINT("The loaded API assembly is invalid"); - CRASH_NOW(); -#endif // TOOLS_ENABLED - } +#if defined(TOOLS_ENABLED) + bool tool_assemblies_loaded = _load_tools_assemblies(); + CRASH_COND_MSG(!tool_assemblies_loaded, "Mono: Failed to load '" TOOLS_ASM_NAME "' assemblies."); +#endif + + // Load the project's main assembly. This doesn't necessarily need to succeed. + // The game may not be using .NET at all, or if the project does use .NET and + // we're running in the editor, it may just happen to be it wasn't built yet. + if (!_load_project_assembly()) { + if (OS::get_singleton()->is_stdout_verbose()) + print_error("Mono: Failed to load project assembly"); } -#else - print_verbose("Mono: Glue disabled, ignoring script assemblies."); -#endif // MONO_GLUE_ENABLED +} - print_verbose("Mono: INITIALIZED"); +bool GDMono::_are_api_assemblies_out_of_sync() { + bool out_of_sync = core_api_assembly.assembly && (core_api_assembly.out_of_sync || !GDMonoCache::cached_data.godot_api_cache_updated); +#ifdef TOOLS_ENABLED + if (!out_of_sync) + out_of_sync = editor_api_assembly.assembly && editor_api_assembly.out_of_sync; +#endif + return out_of_sync; } -#ifdef MONO_GLUE_ENABLED namespace GodotSharpBindings { +#ifdef MONO_GLUE_ENABLED uint64_t get_core_api_hash(); #ifdef TOOLS_ENABLED uint64_t get_editor_api_hash(); #endif uint32_t get_bindings_version(); +uint32_t get_cs_glue_version(); void register_generated_icalls(); -} // namespace GodotSharpBindings -#endif -void GDMono::_register_internal_calls() { -#ifdef MONO_GLUE_ENABLED - GodotSharpBindings::register_generated_icalls(); -#endif +#else +uint64_t get_core_api_hash() { + GD_UNREACHABLE(); +} #ifdef TOOLS_ENABLED - GodotSharpEditor::register_internal_calls(); +uint64_t get_editor_api_hash() { + GD_UNREACHABLE(); +} #endif +uint32_t get_bindings_version() { + GD_UNREACHABLE(); +} +uint32_t get_cs_glue_version() { + GD_UNREACHABLE(); } -void GDMono::_initialize_and_check_api_hashes() { +void register_generated_icalls() { + /* Fine, just do nothing */ +} -#ifdef MONO_GLUE_ENABLED +#endif // MONO_GLUE_ENABLED +} // namespace GodotSharpBindings + +void GDMono::_register_internal_calls() { + GodotSharpBindings::register_generated_icalls(); +} + +void GDMono::_init_godot_api_hashes() { +#if defined(MONO_GLUE_ENABLED) && defined(DEBUG_METHODS_ENABLED) if (get_api_core_hash() != GodotSharpBindings::get_core_api_hash()) { - ERR_PRINT("Mono: Core API hash mismatch!"); + ERR_PRINT("Mono: Core API hash mismatch."); } #ifdef TOOLS_ENABLED if (get_api_editor_hash() != GodotSharpBindings::get_editor_api_hash()) { - ERR_PRINT("Mono: Editor API hash mismatch!"); + ERR_PRINT("Mono: Editor API hash mismatch."); } #endif // TOOLS_ENABLED -#endif // MONO_GLUE_ENABLED +#endif // MONO_GLUE_ENABLED && DEBUG_METHODS_ENABLED +} + +void GDMono::_init_exception_policy() { + PropertyInfo exc_policy_prop = PropertyInfo(Variant::INT, "mono/unhandled_exception_policy", PROPERTY_HINT_ENUM, + vformat("Terminate Application:%s,Log Error:%s", (int)POLICY_TERMINATE_APP, (int)POLICY_LOG_ERROR)); + unhandled_exception_policy = (UnhandledExceptionPolicy)(int)GLOBAL_DEF(exc_policy_prop.name, (int)POLICY_TERMINATE_APP); + ProjectSettings::get_singleton()->set_custom_property_info(exc_policy_prop.name, exc_policy_prop); + + if (Engine::get_singleton()->is_editor_hint()) { + // Unhandled exceptions should not terminate the editor + unhandled_exception_policy = POLICY_LOG_ERROR; + } } void GDMono::add_assembly(uint32_t p_domain_id, GDMonoAssembly *p_assembly) { @@ -515,10 +579,10 @@ bool GDMono::load_assembly_from(const String &p_name, const String &p_path, GDMo return true; } -APIAssembly::Version APIAssembly::Version::get_from_loaded_assembly(GDMonoAssembly *p_api_assembly, APIAssembly::Type p_api_type) { - APIAssembly::Version api_assembly_version; +ApiAssemblyInfo::Version ApiAssemblyInfo::Version::get_from_loaded_assembly(GDMonoAssembly *p_api_assembly, ApiAssemblyInfo::Type p_api_type) { + ApiAssemblyInfo::Version api_assembly_version; - const char *nativecalls_name = p_api_type == APIAssembly::API_CORE ? + const char *nativecalls_name = p_api_type == ApiAssemblyInfo::API_CORE ? BINDINGS_CLASS_NATIVECALLS : BINDINGS_CLASS_NATIVECALLS_EDITOR; @@ -541,8 +605,8 @@ APIAssembly::Version APIAssembly::Version::get_from_loaded_assembly(GDMonoAssemb return api_assembly_version; } -String APIAssembly::to_string(APIAssembly::Type p_type) { - return p_type == APIAssembly::API_CORE ? "API_CORE" : "API_EDITOR"; +String ApiAssemblyInfo::to_string(ApiAssemblyInfo::Type p_type) { + return p_type == ApiAssemblyInfo::API_CORE ? "API_CORE" : "API_EDITOR"; } bool GDMono::_load_corlib_assembly() { @@ -553,225 +617,394 @@ bool GDMono::_load_corlib_assembly() { bool success = load_assembly("mscorlib", &corlib_assembly); if (success) - GDMonoUtils::update_corlib_cache(); + GDMonoCache::update_corlib_cache(); return success; } -bool GDMono::_load_core_api_assembly() { +#ifdef TOOLS_ENABLED +bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const String &p_config) { - if (core_api_assembly) - return true; + String src_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); + String dst_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config); -#ifdef TOOLS_ENABLED - if (metadata_is_api_assembly_invalidated(APIAssembly::API_CORE)) { - print_verbose("Mono: Skipping loading of Core API assembly because it was invalidated"); + String assembly_name = p_api_type == ApiAssemblyInfo::API_CORE ? CORE_API_ASSEMBLY_NAME : EDITOR_API_ASSEMBLY_NAME; + + // Create destination directory if needed + if (!DirAccess::exists(dst_dir)) { + DirAccess *da = DirAccess::create_for_path(dst_dir); + Error err = da->make_dir_recursive(dst_dir); + memdelete(da); + + if (err != OK) { + ERR_PRINTS("Failed to create destination directory for the API assemblies. Error: " + itos(err) + "."); + return false; + } + } + + DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + + String xml_file = assembly_name + ".xml"; + if (da->copy(src_dir.plus_file(xml_file), dst_dir.plus_file(xml_file)) != OK) + WARN_PRINTS("Failed to copy '" + xml_file + "'."); + + String pdb_file = assembly_name + ".pdb"; + if (da->copy(src_dir.plus_file(pdb_file), dst_dir.plus_file(pdb_file)) != OK) + WARN_PRINTS("Failed to copy '" + pdb_file + "'."); + + String assembly_file = assembly_name + ".dll"; + if (da->copy(src_dir.plus_file(assembly_file), dst_dir.plus_file(assembly_file)) != OK) { + ERR_PRINTS("Failed to copy '" + assembly_file + "'."); return false; } -#endif - String assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(CORE_API_ASSEMBLY_NAME ".dll"); + return true; +} + +static bool try_get_cached_api_hash_for(const String &p_api_assemblies_dir, bool &r_out_of_sync) { + String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); + String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); - if (!FileAccess::exists(assembly_path)) + if (!FileAccess::exists(core_api_assembly_path) || !FileAccess::exists(editor_api_assembly_path)) return false; - bool success = load_assembly_from(CORE_API_ASSEMBLY_NAME, - assembly_path, - &core_api_assembly); + String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg"); - if (success) { -#ifdef MONO_GLUE_ENABLED - APIAssembly::Version api_assembly_ver = APIAssembly::Version::get_from_loaded_assembly(core_api_assembly, APIAssembly::API_CORE); - core_api_assembly_out_of_sync = GodotSharpBindings::get_core_api_hash() != api_assembly_ver.godot_api_hash || - GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version || - CS_GLUE_VERSION != api_assembly_ver.cs_glue_version; - if (!core_api_assembly_out_of_sync) { - GDMonoUtils::update_godot_api_cache(); - - _install_trace_listener(); - } -#else - GDMonoUtils::update_godot_api_cache(); -#endif + if (!FileAccess::exists(cached_api_hash_path)) + return false; + + Ref<ConfigFile> cfg; + cfg.instance(); + Error cfg_err = cfg->load(cached_api_hash_path); + ERR_FAIL_COND_V(cfg_err != OK, false); + + // Checking the modified time is good enough + if (FileAccess::get_modified_time(core_api_assembly_path) != (uint64_t)cfg->get_value("core", "modified_time") || + FileAccess::get_modified_time(editor_api_assembly_path) != (uint64_t)cfg->get_value("editor", "modified_time")) { + return false; } - return success; + r_out_of_sync = GodotSharpBindings::get_bindings_version() != (uint32_t)cfg->get_value("core", "bindings_version") || + GodotSharpBindings::get_cs_glue_version() != (uint32_t)cfg->get_value("core", "cs_glue_version") || + GodotSharpBindings::get_bindings_version() != (uint32_t)cfg->get_value("editor", "bindings_version") || + GodotSharpBindings::get_cs_glue_version() != (uint32_t)cfg->get_value("editor", "cs_glue_version") || + GodotSharpBindings::get_core_api_hash() != (uint64_t)cfg->get_value("core", "api_hash") || + GodotSharpBindings::get_editor_api_hash() != (uint64_t)cfg->get_value("editor", "api_hash"); + + return true; } -#ifdef TOOLS_ENABLED -bool GDMono::_load_editor_api_assembly() { +static void create_cached_api_hash_for(const String &p_api_assemblies_dir) { - if (editor_api_assembly) - return true; + String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); + String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); + String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg"); - if (metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR)) { - print_verbose("Mono: Skipping loading of Editor API assembly because it was invalidated"); - return false; + Ref<ConfigFile> cfg; + cfg.instance(); + + cfg->set_value("core", "modified_time", FileAccess::get_modified_time(core_api_assembly_path)); + cfg->set_value("editor", "modified_time", FileAccess::get_modified_time(editor_api_assembly_path)); + + cfg->set_value("core", "bindings_version", GodotSharpBindings::get_bindings_version()); + cfg->set_value("core", "cs_glue_version", GodotSharpBindings::get_cs_glue_version()); + cfg->set_value("editor", "bindings_version", GodotSharpBindings::get_bindings_version()); + cfg->set_value("editor", "cs_glue_version", GodotSharpBindings::get_cs_glue_version()); + + // This assumes the prebuilt api assemblies we copied to the project are not out of sync + cfg->set_value("core", "api_hash", GodotSharpBindings::get_core_api_hash()); + cfg->set_value("editor", "api_hash", GodotSharpBindings::get_editor_api_hash()); + + Error err = cfg->save(cached_api_hash_path); + ERR_FAIL_COND(err != OK); +} + +bool GDMono::_temp_domain_load_are_assemblies_out_of_sync(const String &p_config) { + MonoDomain *temp_domain = GDMonoUtils::create_domain("GodotEngine.Domain.CheckApiAssemblies"); + ERR_FAIL_NULL_V(temp_domain, "Failed to create temporary domain to check API assemblies"); + _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(temp_domain); + + _GDMONO_SCOPE_DOMAIN_(temp_domain); + + GDMono::LoadedApiAssembly temp_core_api_assembly; + GDMono::LoadedApiAssembly temp_editor_api_assembly; + + if (!_try_load_api_assemblies(temp_core_api_assembly, temp_editor_api_assembly, + p_config, /* refonly: */ true, /* loaded_callback: */ NULL)) { + return temp_core_api_assembly.out_of_sync || temp_editor_api_assembly.out_of_sync; } - String assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); + return true; // Failed to load, assume they're outdated assemblies +} - if (!FileAccess::exists(assembly_path)) - return false; +String GDMono::update_api_assemblies_from_prebuilt(const String &p_config, const bool *p_core_api_out_of_sync, const bool *p_editor_api_out_of_sync) { - bool success = load_assembly_from(EDITOR_API_ASSEMBLY_NAME, - assembly_path, - &editor_api_assembly); +#define FAIL_REASON(m_out_of_sync, m_prebuilt_exists) \ + ( \ + (m_out_of_sync ? \ + String("The assembly is invalidated ") : \ + String("The assembly was not found ")) + \ + (m_prebuilt_exists ? \ + String("and the prebuilt assemblies are missing.") : \ + String("and we failed to copy the prebuilt assemblies."))) - if (success) { -#ifdef MONO_GLUE_ENABLED - APIAssembly::Version api_assembly_ver = APIAssembly::Version::get_from_loaded_assembly(editor_api_assembly, APIAssembly::API_EDITOR); - editor_api_assembly_out_of_sync = GodotSharpBindings::get_editor_api_hash() != api_assembly_ver.godot_api_hash || - GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version || - CS_GLUE_VERSION != api_assembly_ver.cs_glue_version; -#endif + String dst_assemblies_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config); + + String core_assembly_path = dst_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); + String editor_assembly_path = dst_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); + + bool api_assemblies_out_of_sync = false; + + if (p_core_api_out_of_sync && p_editor_api_out_of_sync) { + api_assemblies_out_of_sync = p_core_api_out_of_sync || p_editor_api_out_of_sync; + } else if (FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path)) { + // Determine if they're out of sync + if (!try_get_cached_api_hash_for(dst_assemblies_dir, api_assemblies_out_of_sync)) { + api_assemblies_out_of_sync = _temp_domain_load_are_assemblies_out_of_sync(p_config); + } } - return success; + // Note: Even if only one of the assemblies if missing or out of sync, we update both + + if (!api_assemblies_out_of_sync && FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path)) + return String(); // No update needed + + print_verbose("Updating '" + p_config + "' API assemblies"); + + String prebuilt_api_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); + String prebuilt_core_dll_path = prebuilt_api_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); + String prebuilt_editor_dll_path = prebuilt_api_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); + + if (!FileAccess::exists(prebuilt_core_dll_path) || !FileAccess::exists(prebuilt_editor_dll_path)) { + return FAIL_REASON(api_assemblies_out_of_sync, /* prebuilt_exists: */ false); + } + + // Copy the prebuilt Api + if (!copy_prebuilt_api_assembly(ApiAssemblyInfo::API_CORE, p_config) || + !copy_prebuilt_api_assembly(ApiAssemblyInfo::API_EDITOR, p_config)) { + return FAIL_REASON(api_assemblies_out_of_sync, /* prebuilt_exists: */ true); + } + + // Cache the api hash of the assemblies we just copied + create_cached_api_hash_for(dst_assemblies_dir); + + return String(); // Updated successfully + +#undef FAIL_REASON } #endif -#ifdef TOOLS_ENABLED -bool GDMono::_load_editor_tools_assembly() { +bool GDMono::_load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) { - if (editor_tools_assembly) + if (r_loaded_api_assembly.assembly) return true; - _GDMONO_SCOPE_DOMAIN_(tools_domain) +#ifdef TOOLS_ENABLED + // For the editor and the editor player we want to load it from a specific path to make sure we can keep it up to date + + // If running the project manager, load it from the prebuilt API directory + String assembly_dir = !Main::is_project_manager() ? + GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) : + GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); - return load_assembly(EDITOR_TOOLS_ASSEMBLY_NAME, &editor_tools_assembly); -} + String assembly_path = assembly_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); + + bool success = FileAccess::exists(assembly_path) && + load_assembly_from(CORE_API_ASSEMBLY_NAME, assembly_path, &r_loaded_api_assembly.assembly, p_refonly); +#else + bool success = load_assembly(CORE_API_ASSEMBLY_NAME, &r_loaded_api_assembly.assembly, p_refonly); #endif -bool GDMono::_load_project_assembly() { + if (success) { + ApiAssemblyInfo::Version api_assembly_ver = ApiAssemblyInfo::Version::get_from_loaded_assembly(r_loaded_api_assembly.assembly, ApiAssemblyInfo::API_CORE); + r_loaded_api_assembly.out_of_sync = GodotSharpBindings::get_core_api_hash() != api_assembly_ver.godot_api_hash || + GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version || + GodotSharpBindings::get_cs_glue_version() != api_assembly_ver.cs_glue_version; + } else { + r_loaded_api_assembly.out_of_sync = false; + } - if (project_assembly) + return success; +} + +#ifdef TOOLS_ENABLED +bool GDMono::_load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) { + + if (r_loaded_api_assembly.assembly) return true; - String name = ProjectSettings::get_singleton()->get("application/config/name"); - if (name.empty()) { - name = "UnnamedProject"; - } + // For the editor and the editor player we want to load it from a specific path to make sure we can keep it up to date - bool success = load_assembly(name, &project_assembly); + // If running the project manager, load it from the prebuilt API directory + String assembly_dir = !Main::is_project_manager() ? + GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) : + GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); - if (success) { - mono_assembly_set_main(project_assembly->get_assembly()); + String assembly_path = assembly_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); - CSharpLanguage::get_singleton()->project_assembly_loaded(); + bool success = FileAccess::exists(assembly_path) && + load_assembly_from(EDITOR_API_ASSEMBLY_NAME, assembly_path, &r_loaded_api_assembly.assembly, p_refonly); + + if (success) { + ApiAssemblyInfo::Version api_assembly_ver = ApiAssemblyInfo::Version::get_from_loaded_assembly(r_loaded_api_assembly.assembly, ApiAssemblyInfo::API_EDITOR); + r_loaded_api_assembly.out_of_sync = GodotSharpBindings::get_editor_api_hash() != api_assembly_ver.godot_api_hash || + GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version || + GodotSharpBindings::get_cs_glue_version() != api_assembly_ver.cs_glue_version; } else { - if (OS::get_singleton()->is_stdout_verbose()) - print_error("Mono: Failed to load project assembly"); + r_loaded_api_assembly.out_of_sync = false; } return success; } +#endif -bool GDMono::_load_api_assemblies() { - - if (!_load_core_api_assembly()) { +bool GDMono::_try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, LoadedApiAssembly &r_editor_api_assembly, + const String &p_config, bool p_refonly, CoreApiAssemblyLoadedCallback p_callback) { + if (!_load_core_api_assembly(r_core_api_assembly, p_config, p_refonly)) { if (OS::get_singleton()->is_stdout_verbose()) print_error("Mono: Failed to load Core API assembly"); return false; } - if (core_api_assembly_out_of_sync || !GDMonoUtils::mono_cache.godot_api_cache_updated) - return false; - #ifdef TOOLS_ENABLED - if (!_load_editor_api_assembly()) { + if (!_load_editor_api_assembly(r_editor_api_assembly, p_config, p_refonly)) { if (OS::get_singleton()->is_stdout_verbose()) print_error("Mono: Failed to load Editor API assembly"); return false; } - if (editor_api_assembly_out_of_sync) + if (r_editor_api_assembly.out_of_sync) return false; #endif + // Check if the core API assembly is out of sync only after trying to load the + // editor API assembly. Otherwise, if both assemblies are out of sync, we would + // only update the former as we won't know the latter also needs to be updated. + if (r_core_api_assembly.out_of_sync) + return false; + + if (p_callback) + return p_callback(); + return true; } -void GDMono::_install_trace_listener() { +bool GDMono::_on_core_api_assembly_loaded() { + GDMonoCache::update_godot_api_cache(); -#ifdef DEBUG_ENABLED - // Install the trace listener now before the project assembly is loaded - typedef void (*DebuggingUtils_InstallTraceListener)(MonoObject **); - MonoException *exc = NULL; - GDMonoClass *debug_utils = core_api_assembly->get_class(BINDINGS_NAMESPACE, "DebuggingUtils"); - DebuggingUtils_InstallTraceListener install_func = - (DebuggingUtils_InstallTraceListener)debug_utils->get_method_thunk("InstallTraceListener"); - install_func((MonoObject **)&exc); - if (exc) { - ERR_PRINT("Failed to install System.Diagnostics.Trace listener"); - GDMonoUtils::debug_print_unhandled_exception(exc); - } -#endif -} + if (!GDMonoCache::cached_data.godot_api_cache_updated) + return false; -#ifdef TOOLS_ENABLED -String GDMono::_get_api_assembly_metadata_path() { + get_singleton()->_install_trace_listener(); - return GodotSharpDirs::get_res_metadata_dir().plus_file("api_assemblies.cfg"); + return true; } -void GDMono::metadata_set_api_assembly_invalidated(APIAssembly::Type p_api_type, bool p_invalidated) { +bool GDMono::_try_load_api_assemblies_preset() { + return _try_load_api_assemblies(core_api_assembly, editor_api_assembly, + get_expected_api_build_config(), /* refonly: */ false, _on_core_api_assembly_loaded); +} - String section = APIAssembly::to_string(p_api_type); - String path = _get_api_assembly_metadata_path(); +void GDMono::_load_api_assemblies() { - Ref<ConfigFile> metadata; - metadata.instance(); - metadata->load(path); + bool api_assemblies_loaded = _try_load_api_assemblies_preset(); - metadata->set_value(section, "invalidated", p_invalidated); + if (!api_assemblies_loaded) { +#ifdef TOOLS_ENABLED + // The API assemblies are out of sync or some other error happened. Fine, try one more time, but + // this time update them from the prebuilt assemblies directory before trying to load them again. - String assembly_path = GodotSharpDirs::get_res_assemblies_dir() - .plus_file(p_api_type == APIAssembly::API_CORE ? - CORE_API_ASSEMBLY_NAME ".dll" : - EDITOR_API_ASSEMBLY_NAME ".dll"); + // Shouldn't happen. The project manager loads the prebuilt API assemblies + CRASH_COND_MSG(Main::is_project_manager(), "Failed to load one of the prebuilt API assemblies."); - ERR_FAIL_COND(!FileAccess::exists(assembly_path)); + // 1. Unload the scripts domain + Error domain_unload_err = _unload_scripts_domain(); + CRASH_COND_MSG(domain_unload_err != OK, "Mono: Failed to unload scripts domain."); - uint64_t modified_time = FileAccess::get_modified_time(assembly_path); + // 2. Update the API assemblies + String update_error = update_api_assemblies_from_prebuilt("Debug", &core_api_assembly.out_of_sync, &editor_api_assembly.out_of_sync); + CRASH_COND_MSG(!update_error.empty(), update_error); - metadata->set_value(section, "invalidated_asm_modified_time", String::num_uint64(modified_time)); + // 3. Load the scripts domain again + Error domain_load_err = _load_scripts_domain(); + CRASH_COND_MSG(domain_load_err != OK, "Mono: Failed to load scripts domain."); - String dir = path.get_base_dir(); - if (!DirAccess::exists(dir)) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND(!da); - Error err = da->make_dir_recursive(ProjectSettings::get_singleton()->globalize_path(dir)); - ERR_FAIL_COND(err != OK); + // 4. Try loading the updated assemblies + api_assemblies_loaded = _try_load_api_assemblies_preset(); +#endif } - Error save_err = metadata->save(path); - ERR_FAIL_COND(save_err != OK); + if (!api_assemblies_loaded) { + // welp... too bad + + if (_are_api_assemblies_out_of_sync()) { + if (core_api_assembly.out_of_sync) { + ERR_PRINT("The assembly '" CORE_API_ASSEMBLY_NAME "' is out of sync."); + } else if (!GDMonoCache::cached_data.godot_api_cache_updated) { + ERR_PRINT("The loaded assembly '" CORE_API_ASSEMBLY_NAME "' is in sync, but the cache update failed."); + } + +#ifdef TOOLS_ENABLED + if (editor_api_assembly.out_of_sync) { + ERR_PRINT("The assembly '" EDITOR_API_ASSEMBLY_NAME "' is out of sync."); + } +#endif + + CRASH_NOW(); + } else { + CRASH_NOW_MSG("Failed to load one of the API assemblies."); + } + } } -bool GDMono::metadata_is_api_assembly_invalidated(APIAssembly::Type p_api_type) { +#ifdef TOOLS_ENABLED +bool GDMono::_load_tools_assemblies() { - String section = APIAssembly::to_string(p_api_type); + if (tools_assembly && tools_project_editor_assembly) + return true; - Ref<ConfigFile> metadata; - metadata.instance(); - metadata->load(_get_api_assembly_metadata_path()); + bool success = load_assembly(TOOLS_ASM_NAME, &tools_assembly) && + load_assembly(TOOLS_PROJECT_EDITOR_ASM_NAME, &tools_project_editor_assembly); - String assembly_path = GodotSharpDirs::get_res_assemblies_dir() - .plus_file(p_api_type == APIAssembly::API_CORE ? - CORE_API_ASSEMBLY_NAME ".dll" : - EDITOR_API_ASSEMBLY_NAME ".dll"); + return success; +} +#endif - if (!FileAccess::exists(assembly_path)) - return false; +bool GDMono::_load_project_assembly() { + + if (project_assembly) + return true; + + String appname = ProjectSettings::get_singleton()->get("application/config/name"); + String appname_safe = OS::get_singleton()->get_safe_dir_name(appname); + if (appname_safe.empty()) { + appname_safe = "UnnamedProject"; + } - uint64_t modified_time = FileAccess::get_modified_time(assembly_path); + bool success = load_assembly(appname_safe, &project_assembly); - uint64_t stored_modified_time = metadata->get_value(section, "invalidated_asm_modified_time", 0); + if (success) { + mono_assembly_set_main(project_assembly->get_assembly()); + } - return metadata->get_value(section, "invalidated", false) && modified_time <= stored_modified_time; + return success; } + +void GDMono::_install_trace_listener() { + +#ifdef DEBUG_ENABLED + // Install the trace listener now before the project assembly is loaded + GDMonoClass *debug_utils = get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, "DebuggingUtils"); + GDMonoMethod *install_func = debug_utils->get_method("InstallTraceListener"); + + MonoException *exc = NULL; + install_func->invoke_raw(NULL, NULL, &exc); + if (exc) { + GDMonoUtils::debug_print_unhandled_exception(exc); + ERR_PRINT("Failed to install 'System.Diagnostics.Trace' listener."); + } #endif +} Error GDMono::_load_scripts_domain() { @@ -779,10 +1012,9 @@ Error GDMono::_load_scripts_domain() { print_verbose("Mono: Loading scripts domain..."); - scripts_domain = GDMonoUtils::create_domain("GodotEngine.ScriptsDomain"); + scripts_domain = GDMonoUtils::create_domain("GodotEngine.Domain.Scripts"); - ERR_EXPLAIN("Mono: Could not create scripts app domain"); - ERR_FAIL_NULL_V(scripts_domain, ERR_CANT_CREATE); + ERR_FAIL_NULL_V_MSG(scripts_domain, ERR_CANT_CREATE, "Mono: Could not create scripts app domain."); mono_domain_set(scripts_domain, true); @@ -801,24 +1033,26 @@ Error GDMono::_unload_scripts_domain() { finalizing_scripts_domain = true; if (!mono_domain_finalize(scripts_domain, 2000)) { - ERR_PRINT("Mono: Domain finalization timeout"); + ERR_PRINT("Mono: Domain finalization timeout."); } finalizing_scripts_domain = false; mono_gc_collect(mono_gc_max_generation()); + GDMonoCache::clear_godot_api_cache(); + _domain_assemblies_cleanup(mono_domain_get_id(scripts_domain)); - core_api_assembly = NULL; - project_assembly = NULL; + core_api_assembly.assembly = NULL; #ifdef TOOLS_ENABLED - editor_api_assembly = NULL; + editor_api_assembly.assembly = NULL; #endif - core_api_assembly_out_of_sync = false; + project_assembly = NULL; #ifdef TOOLS_ENABLED - editor_api_assembly_out_of_sync = false; + tools_assembly = NULL; + tools_project_editor_assembly = NULL; #endif MonoDomain *domain = scripts_domain; @@ -828,7 +1062,7 @@ Error GDMono::_unload_scripts_domain() { mono_domain_try_unload(domain, (MonoObject **)&exc); if (exc) { - ERR_PRINT("Exception thrown when unloading scripts domain"); + ERR_PRINT("Exception thrown when unloading scripts domain."); GDMonoUtils::debug_unhandled_exception(exc); return FAILED; } @@ -836,89 +1070,38 @@ Error GDMono::_unload_scripts_domain() { return OK; } -#ifdef TOOLS_ENABLED -Error GDMono::_load_tools_domain() { - - ERR_FAIL_COND_V(tools_domain != NULL, ERR_BUG); - - print_verbose("Mono: Loading tools domain..."); - - tools_domain = GDMonoUtils::create_domain("GodotEngine.ToolsDomain"); - - ERR_EXPLAIN("Mono: Could not create tools app domain"); - ERR_FAIL_NULL_V(tools_domain, ERR_CANT_CREATE); - - return OK; -} -#endif - #ifdef GD_MONO_HOT_RELOAD Error GDMono::reload_scripts_domain() { ERR_FAIL_COND_V(!runtime_initialized, ERR_BUG); if (scripts_domain) { - Error err = _unload_scripts_domain(); - if (err != OK) { - ERR_PRINT("Mono: Failed to unload scripts domain"); - return err; - } + Error domain_unload_err = _unload_scripts_domain(); + ERR_FAIL_COND_V_MSG(domain_unload_err != OK, domain_unload_err, "Mono: Failed to unload scripts domain."); } - CSharpLanguage::get_singleton()->_uninitialize_script_bindings(); + CSharpLanguage::get_singleton()->_on_scripts_domain_unloaded(); - Error err = _load_scripts_domain(); - if (err != OK) { - ERR_PRINT("Mono: Failed to load scripts domain"); - return err; - } + Error domain_load_err = _load_scripts_domain(); + ERR_FAIL_COND_V_MSG(domain_load_err != OK, domain_load_err, "Mono: Failed to load scripts domain."); -#ifdef MONO_GLUE_ENABLED - if (!_load_api_assemblies()) { - if ((core_api_assembly && (core_api_assembly_out_of_sync || !GDMonoUtils::mono_cache.godot_api_cache_updated)) -#ifdef TOOLS_ENABLED - || (editor_api_assembly && editor_api_assembly_out_of_sync) -#endif - ) { -#ifdef TOOLS_ENABLED - // The assembly was successfully loaded, but the full api could not be cached. - // This is most likely an outdated assembly loaded because of an invalid version in the - // metadata, so we invalidate the version in the metadata and unload the script domain. - - if (core_api_assembly_out_of_sync) { - ERR_PRINT(OUT_OF_SYNC_ERR_MESSAGE(CORE_API_ASSEMBLY_NAME)); - metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true); - } else if (!GDMonoUtils::mono_cache.godot_api_cache_updated) { - ERR_PRINT("The loaded Core API assembly is in sync, but the cache update failed"); - metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true); - } + // Load assemblies. The API and tools assemblies are required, + // the application is aborted if these assemblies cannot be loaded. - if (editor_api_assembly_out_of_sync) { - ERR_PRINT(OUT_OF_SYNC_ERR_MESSAGE(EDITOR_API_ASSEMBLY_NAME)); - metadata_set_api_assembly_invalidated(APIAssembly::API_EDITOR, true); - } + _load_api_assemblies(); - err = _unload_scripts_domain(); - if (err != OK) { - WARN_PRINT("Mono: Failed to unload scripts domain"); - } - - return ERR_CANT_RESOLVE; -#else - ERR_PRINT("The loaded API assembly is invalid"); - CRASH_NOW(); +#if defined(TOOLS_ENABLED) + bool tools_assemblies_loaded = _load_tools_assemblies(); + CRASH_COND_MSG(!tools_assemblies_loaded, "Mono: Failed to load '" TOOLS_ASM_NAME "' assemblies."); #endif - } else { - return ERR_CANT_OPEN; - } - } + // Load the project's main assembly. Here, during hot-reloading, we do + // consider failing to load the project's main assembly to be an error. + // However, unlike the API and tools assemblies, the application can continue working. if (!_load_project_assembly()) { + print_error("Mono: Failed to load project assembly"); return ERR_CANT_OPEN; } -#else - print_verbose("Mono: Glue disabled, ignoring script assemblies."); -#endif // MONO_GLUE_ENABLED return OK; } @@ -927,34 +1110,29 @@ Error GDMono::reload_scripts_domain() { Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) { CRASH_COND(p_domain == NULL); + CRASH_COND(p_domain == GDMono::get_singleton()->get_scripts_domain()); // Should use _unload_scripts_domain() instead String domain_name = mono_domain_get_friendly_name(p_domain); - print_verbose("Mono: Unloading domain `" + domain_name + "`..."); + print_verbose("Mono: Unloading domain '" + domain_name + "'..."); if (mono_domain_get() == p_domain) mono_domain_set(root_domain, true); if (!mono_domain_finalize(p_domain, 2000)) { - ERR_PRINT("Mono: Domain finalization timeout"); + ERR_PRINT("Mono: Domain finalization timeout."); } mono_gc_collect(mono_gc_max_generation()); _domain_assemblies_cleanup(mono_domain_get_id(p_domain)); -#ifdef TOOLS_ENABLED - if (p_domain == tools_domain) { - editor_tools_assembly = NULL; - } -#endif - MonoException *exc = NULL; mono_domain_try_unload(p_domain, (MonoObject **)&exc); if (exc) { - ERR_PRINTS("Exception thrown when unloading domain `" + domain_name + "`"); - GDMonoUtils::debug_unhandled_exception(exc); + ERR_PRINTS("Exception thrown when unloading domain '" + domain_name + "'."); + GDMonoUtils::debug_print_unhandled_exception(exc); return FAILED; } @@ -985,6 +1163,22 @@ GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) { return NULL; } +GDMonoClass *GDMono::get_class(const StringName &p_namespace, const StringName &p_name) { + + uint32_t domain_id = mono_domain_get_id(mono_domain_get()); + HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id]; + + const String *k = NULL; + while ((k = domain_assemblies.next(k))) { + GDMonoAssembly *assembly = domain_assemblies.get(*k); + GDMonoClass *klass = assembly->get_class(p_namespace, p_name); + if (klass) + return klass; + } + + return NULL; +} + void GDMono::_domain_assemblies_cleanup(uint32_t p_domain_id) { HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[p_domain_id]; @@ -1008,7 +1202,9 @@ void GDMono::unhandled_exception_hook(MonoObject *p_exc, void *) { if (ScriptDebugger::get_singleton()) ScriptDebugger::get_singleton()->idle_poll(); #endif - abort(); + + exit(mono_environment_exitcode_get()); + GD_UNREACHABLE(); } @@ -1023,46 +1219,29 @@ GDMono::GDMono() { root_domain = NULL; scripts_domain = NULL; -#ifdef TOOLS_ENABLED - tools_domain = NULL; -#endif - - core_api_assembly_out_of_sync = false; -#ifdef TOOLS_ENABLED - editor_api_assembly_out_of_sync = false; -#endif corlib_assembly = NULL; - core_api_assembly = NULL; project_assembly = NULL; #ifdef TOOLS_ENABLED - editor_api_assembly = NULL; - editor_tools_assembly = NULL; + tools_assembly = NULL; + tools_project_editor_assembly = NULL; #endif api_core_hash = 0; #ifdef TOOLS_ENABLED api_editor_hash = 0; #endif + + unhandled_exception_policy = POLICY_TERMINATE_APP; } GDMono::~GDMono() { if (is_runtime_initialized()) { - -#ifdef TOOLS_ENABLED - if (tools_domain) { - Error err = finalize_and_unload_domain(tools_domain); - if (err != OK) { - ERR_PRINT("Mono: Failed to unload tools domain"); - } - } -#endif - if (scripts_domain) { Error err = _unload_scripts_domain(); if (err != OK) { - ERR_PRINT("Mono: Failed to unload scripts domain"); + ERR_PRINT("Mono: Failed to unload scripts domain."); } } @@ -1077,12 +1256,14 @@ GDMono::~GDMono() { } assemblies.clear(); - GDMonoUtils::clear_cache(); - print_verbose("Mono: Runtime cleanup..."); mono_jit_cleanup(root_domain); +#if defined(ANDROID_ENABLED) + GDMonoAndroid::cleanup(); +#endif + print_verbose("Mono: Finalized"); runtime_initialized = false; @@ -1115,14 +1296,14 @@ int32_t _GodotSharp::get_domain_id() { int32_t _GodotSharp::get_scripts_domain_id() { - MonoDomain *domain = SCRIPTS_DOMAIN; + MonoDomain *domain = GDMono::get_singleton()->get_scripts_domain(); CRASH_COND(!domain); // User must check if scripts domain is loaded before calling this method return mono_domain_get_id(domain); } bool _GodotSharp::is_scripts_domain_loaded() { - return GDMono::get_singleton()->is_runtime_initialized() && SCRIPTS_DOMAIN != NULL; + return GDMono::get_singleton()->is_runtime_initialized() && GDMono::get_singleton()->get_scripts_domain() != NULL; } bool _GodotSharp::_is_domain_finalizing_for_unload(int32_t p_domain_id) { @@ -1144,7 +1325,7 @@ bool _GodotSharp::is_domain_finalizing_for_unload(MonoDomain *p_domain) { if (!p_domain) return true; - if (p_domain == SCRIPTS_DOMAIN && GDMono::get_singleton()->is_finalizing_scripts_domain()) + if (p_domain == GDMono::get_singleton()->get_scripts_domain() && GDMono::get_singleton()->is_finalizing_scripts_domain()) return true; return mono_domain_is_unloading(p_domain); } @@ -1159,6 +1340,12 @@ bool _GodotSharp::is_runtime_initialized() { return GDMono::get_singleton()->is_runtime_initialized(); } +void _GodotSharp::_reload_assemblies(bool p_soft_reload) { +#ifdef GD_MONO_HOT_RELOAD + CSharpLanguage::get_singleton()->reload_assemblies(p_soft_reload); +#endif +} + void _GodotSharp::_bind_methods() { ClassDB::bind_method(D_METHOD("attach_thread"), &_GodotSharp::attach_thread); @@ -1171,6 +1358,7 @@ void _GodotSharp::_bind_methods() { ClassDB::bind_method(D_METHOD("is_runtime_shutting_down"), &_GodotSharp::is_runtime_shutting_down); ClassDB::bind_method(D_METHOD("is_runtime_initialized"), &_GodotSharp::is_runtime_initialized); + ClassDB::bind_method(D_METHOD("_reload_assemblies"), &_GodotSharp::_reload_assemblies); } _GodotSharp::_GodotSharp() { diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h index 216c96a612..7fb03b82ad 100644 --- a/modules/mono/mono_gd/gd_mono.h +++ b/modules/mono/mono_gd/gd_mono.h @@ -41,7 +41,7 @@ #include "../utils/mono_reg_utils.h" #endif -namespace APIAssembly { +namespace ApiAssemblyInfo { enum Type { API_CORE, API_EDITOR @@ -76,54 +76,69 @@ struct Version { }; String to_string(Type p_type); -} // namespace APIAssembly - -#define SCRIPTS_DOMAIN GDMono::get_singleton()->get_scripts_domain() -#ifdef TOOLS_ENABLED -#define TOOLS_DOMAIN GDMono::get_singleton()->get_tools_domain() -#endif +} // namespace ApiAssemblyInfo class GDMono { +public: + enum UnhandledExceptionPolicy { + POLICY_TERMINATE_APP, + POLICY_LOG_ERROR + }; + + struct LoadedApiAssembly { + GDMonoAssembly *assembly; + bool out_of_sync; + + LoadedApiAssembly() : + assembly(NULL), + out_of_sync(false) { + } + }; + +private: bool runtime_initialized; bool finalizing_scripts_domain; + UnhandledExceptionPolicy unhandled_exception_policy; + MonoDomain *root_domain; MonoDomain *scripts_domain; -#ifdef TOOLS_ENABLED - MonoDomain *tools_domain; -#endif - bool core_api_assembly_out_of_sync; -#ifdef TOOLS_ENABLED - bool editor_api_assembly_out_of_sync; -#endif + HashMap<uint32_t, HashMap<String, GDMonoAssembly *> > assemblies; GDMonoAssembly *corlib_assembly; - GDMonoAssembly *core_api_assembly; GDMonoAssembly *project_assembly; #ifdef TOOLS_ENABLED - GDMonoAssembly *editor_api_assembly; - GDMonoAssembly *editor_tools_assembly; + GDMonoAssembly *tools_assembly; + GDMonoAssembly *tools_project_editor_assembly; #endif - HashMap<uint32_t, HashMap<String, GDMonoAssembly *> > assemblies; + LoadedApiAssembly core_api_assembly; + LoadedApiAssembly editor_api_assembly; - void _domain_assemblies_cleanup(uint32_t p_domain_id); + typedef bool (*CoreApiAssemblyLoadedCallback)(); - bool _load_corlib_assembly(); - bool _load_core_api_assembly(); + bool _are_api_assemblies_out_of_sync(); + bool _temp_domain_load_are_assemblies_out_of_sync(const String &p_config); + + bool _load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly); #ifdef TOOLS_ENABLED - bool _load_editor_api_assembly(); - bool _load_editor_tools_assembly(); + bool _load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly); #endif - bool _load_project_assembly(); - bool _load_api_assemblies(); + static bool _on_core_api_assembly_loaded(); + bool _load_corlib_assembly(); #ifdef TOOLS_ENABLED - String _get_api_assembly_metadata_path(); + bool _load_tools_assemblies(); #endif + bool _load_project_assembly(); + + bool _try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, LoadedApiAssembly &r_editor_api_assembly, + const String &p_config, bool p_refonly, CoreApiAssemblyLoadedCallback p_callback); + bool _try_load_api_assemblies_preset(); + void _load_api_assemblies(); void _install_trace_listener(); @@ -132,15 +147,14 @@ class GDMono { Error _load_scripts_domain(); Error _unload_scripts_domain(); -#ifdef TOOLS_ENABLED - Error _load_tools_domain(); -#endif + void _domain_assemblies_cleanup(uint32_t p_domain_id); uint64_t api_core_hash; #ifdef TOOLS_ENABLED uint64_t api_editor_hash; #endif - void _initialize_and_check_api_hashes(); + void _init_godot_api_hashes(); + void _init_exception_policy(); GDMonoLog *gdmono_log; @@ -149,11 +163,13 @@ class GDMono { #endif void add_mono_shared_libs_dir_to_path(); + void determine_mono_dirs(String &r_assembly_rootdir, String &r_config_dir); protected: static GDMono *singleton; public: +#ifdef DEBUG_METHODS_ENABLED uint64_t get_api_core_hash() { if (api_core_hash == 0) api_core_hash = ClassDB::get_api_hash(ClassDB::API_CORE); @@ -165,16 +181,31 @@ public: api_editor_hash = ClassDB::get_api_hash(ClassDB::API_EDITOR); return api_editor_hash; } +#endif // TOOLS_ENABLED +#endif // DEBUG_METHODS_ENABLED + + _FORCE_INLINE_ static String get_expected_api_build_config() { +#ifdef TOOLS_ENABLED + return "Debug"; +#else +#ifdef DEBUG_ENABLED + return "Debug"; +#else + return "Release"; +#endif #endif + } #ifdef TOOLS_ENABLED - void metadata_set_api_assembly_invalidated(APIAssembly::Type p_api_type, bool p_invalidated); - bool metadata_is_api_assembly_invalidated(APIAssembly::Type p_api_type); + bool copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const String &p_config); + String update_api_assemblies_from_prebuilt(const String &p_config, const bool *p_core_api_out_of_sync = NULL, const bool *p_editor_api_out_of_sync = NULL); #endif static GDMono *get_singleton() { return singleton; } - static void unhandled_exception_hook(MonoObject *p_exc, void *p_user_data); + GD_NORETURN static void unhandled_exception_hook(MonoObject *p_exc, void *p_user_data); + + UnhandledExceptionPolicy get_unhandled_exception_policy() const { return unhandled_exception_policy; } // Do not use these, unless you know what you're doing void add_assembly(uint32_t p_domain_id, GDMonoAssembly *p_assembly); @@ -185,16 +216,14 @@ public: _FORCE_INLINE_ bool is_finalizing_scripts_domain() { return finalizing_scripts_domain; } _FORCE_INLINE_ MonoDomain *get_scripts_domain() { return scripts_domain; } -#ifdef TOOLS_ENABLED - _FORCE_INLINE_ MonoDomain *get_tools_domain() { return tools_domain; } -#endif _FORCE_INLINE_ GDMonoAssembly *get_corlib_assembly() const { return corlib_assembly; } - _FORCE_INLINE_ GDMonoAssembly *get_core_api_assembly() const { return core_api_assembly; } + _FORCE_INLINE_ GDMonoAssembly *get_core_api_assembly() const { return core_api_assembly.assembly; } _FORCE_INLINE_ GDMonoAssembly *get_project_assembly() const { return project_assembly; } #ifdef TOOLS_ENABLED - _FORCE_INLINE_ GDMonoAssembly *get_editor_api_assembly() const { return editor_api_assembly; } - _FORCE_INLINE_ GDMonoAssembly *get_editor_tools_assembly() const { return editor_tools_assembly; } + _FORCE_INLINE_ GDMonoAssembly *get_editor_api_assembly() const { return editor_api_assembly.assembly; } + _FORCE_INLINE_ GDMonoAssembly *get_tools_assembly() const { return tools_assembly; } + _FORCE_INLINE_ GDMonoAssembly *get_tools_project_editor_assembly() const { return tools_project_editor_assembly; } #endif #if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED) @@ -202,6 +231,7 @@ public: #endif GDMonoClass *get_class(MonoClass *p_raw_class); + GDMonoClass *get_class(const StringName &p_namespace, const StringName &p_name); #ifdef GD_MONO_HOT_RELOAD Error reload_scripts_domain(); @@ -214,6 +244,7 @@ public: Error finalize_and_unload_domain(MonoDomain *p_domain); void initialize(); + void initialize_load_assemblies(); GDMono(); ~GDMono(); @@ -267,7 +298,7 @@ public: (void)__gdmono__scope__exit__domain__unload__; class _GodotSharp : public Object { - GDCLASS(_GodotSharp, Object) + GDCLASS(_GodotSharp, Object); friend class GDMono; @@ -276,6 +307,8 @@ class _GodotSharp : public Object { List<NodePath *> np_delete_queue; List<RID *> rid_delete_queue; + void _reload_assemblies(bool p_soft_reload); + protected: static _GodotSharp *singleton; static void _bind_methods(); diff --git a/modules/mono/mono_gd/gd_mono_android.cpp b/modules/mono/mono_gd/gd_mono_android.cpp new file mode 100644 index 0000000000..86af8d1812 --- /dev/null +++ b/modules/mono/mono_gd/gd_mono_android.cpp @@ -0,0 +1,685 @@ +/*************************************************************************/ +/* gd_mono_android.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 "gd_mono_android.h" + +#if defined(ANDROID_ENABLED) + +#include <dlfcn.h> // dlopen, dlsym +#include <mono/utils/mono-dl-fallback.h> +#include <sys/system_properties.h> +#include <cstddef> + +#if __ANDROID_API__ < 24 +#include "thirdparty/misc/ifaddrs-android.h" +#else +#include <ifaddrs.h> +#endif + +#include "core/os/os.h" +#include "core/ustring.h" +#include "platform/android/java_godot_wrapper.h" +#include "platform/android/os_android.h" +#include "platform/android/thread_jandroid.h" + +#include "../utils/path_utils.h" +#include "../utils/string_utils.h" +#include "gd_mono_cache.h" +#include "gd_mono_marshal.h" + +// Warning: JNI boilerplate ahead... continue at your own risk + +namespace GDMonoAndroid { + +template <typename T> +struct ScopedLocalRef { + JNIEnv *env; + T local_ref; + + _FORCE_INLINE_ T get() const { return local_ref; } + _FORCE_INLINE_ operator T() const { return local_ref; } + _FORCE_INLINE_ operator jvalue() const { return (jvalue)local_ref; } + + _FORCE_INLINE_ operator bool() const { return local_ref != NULL; } + + _FORCE_INLINE_ bool operator==(std::nullptr_t) const { + return local_ref == nullptr; + } + + _FORCE_INLINE_ bool operator!=(std::nullptr_t) const { + return local_ref != nullptr; + } + + ScopedLocalRef(const ScopedLocalRef &) = delete; + ScopedLocalRef &operator=(const ScopedLocalRef &) = delete; + + ScopedLocalRef(JNIEnv *p_env, T p_local_ref) : + env(p_env), local_ref(p_local_ref) { + } + + ~ScopedLocalRef() { + if (local_ref) { + env->DeleteLocalRef(local_ref); + } + } +}; + +bool jni_exception_check(JNIEnv *p_env) { + if (p_env->ExceptionCheck()) { + // Print the exception to logcat + p_env->ExceptionDescribe(); + + p_env->ExceptionClear(); + return true; + } + + return false; +} + +String app_native_lib_dir_cache; + +String determine_app_native_lib_dir() { + JNIEnv *env = ThreadAndroid::get_env(); + + ScopedLocalRef<jclass> activityThreadClass(env, env->FindClass("android/app/ActivityThread")); + jmethodID currentActivityThread = env->GetStaticMethodID(activityThreadClass, "currentActivityThread", "()Landroid/app/ActivityThread;"); + ScopedLocalRef<jobject> activityThread(env, env->CallStaticObjectMethod(activityThreadClass, currentActivityThread)); + jmethodID getApplication = env->GetMethodID(activityThreadClass, "getApplication", "()Landroid/app/Application;"); + ScopedLocalRef<jobject> ctx(env, env->CallObjectMethod(activityThread, getApplication)); + + jmethodID getApplicationInfo = env->GetMethodID(env->GetObjectClass(ctx), "getApplicationInfo", "()Landroid/content/pm/ApplicationInfo;"); + ScopedLocalRef<jobject> applicationInfo(env, env->CallObjectMethod(ctx, getApplicationInfo)); + jfieldID nativeLibraryDirField = env->GetFieldID(env->GetObjectClass(applicationInfo), "nativeLibraryDir", "Ljava/lang/String;"); + ScopedLocalRef<jstring> nativeLibraryDir(env, (jstring)env->GetObjectField(applicationInfo, nativeLibraryDirField)); + + String result; + + const char *const nativeLibraryDirUtf8 = env->GetStringUTFChars(nativeLibraryDir, NULL); + if (nativeLibraryDirUtf8) { + result.parse_utf8(nativeLibraryDirUtf8); + env->ReleaseStringUTFChars(nativeLibraryDir, nativeLibraryDirUtf8); + } + + return result; +} + +String get_app_native_lib_dir() { + if (app_native_lib_dir_cache.empty()) + app_native_lib_dir_cache = determine_app_native_lib_dir(); + return app_native_lib_dir_cache; +} + +int gd_mono_convert_dl_flags(int flags) { + // from mono's runtime-bootstrap.c + + int lflags = flags & MONO_DL_LOCAL ? 0 : RTLD_GLOBAL; + + if (flags & MONO_DL_LAZY) + lflags |= RTLD_LAZY; + else + lflags |= RTLD_NOW; + + return lflags; +} + +#ifndef GD_MONO_ANDROID_SO_NAME +#define GD_MONO_ANDROID_SO_NAME "libmonosgen-2.0.so" +#endif + +const char *mono_so_name = GD_MONO_ANDROID_SO_NAME; +const char *godot_so_name = "libgodot_android.so"; + +void *mono_dl_handle = NULL; +void *godot_dl_handle = NULL; + +void *try_dlopen(const String &p_so_path, int p_flags) { + if (!FileAccess::exists(p_so_path)) { + if (OS::get_singleton()->is_stdout_verbose()) + OS::get_singleton()->print("Cannot find shared library: '%s'\n", p_so_path.utf8().get_data()); + return NULL; + } + + int lflags = gd_mono_convert_dl_flags(p_flags); + + void *handle = dlopen(p_so_path.utf8().get_data(), lflags); + + if (!handle) { + if (OS::get_singleton()->is_stdout_verbose()) + OS::get_singleton()->print("Failed to open shared library: '%s'. Error: '%s'\n", p_so_path.utf8().get_data(), dlerror()); + return NULL; + } + + if (OS::get_singleton()->is_stdout_verbose()) + OS::get_singleton()->print("Successfully loaded shared library: '%s'\n", p_so_path.utf8().get_data()); + + return handle; +} + +void *gd_mono_android_dlopen(const char *p_name, int p_flags, char **r_err, void *p_user_data) { + if (p_name == NULL) { + // __Internal + + if (!mono_dl_handle) { + String app_native_lib_dir = get_app_native_lib_dir(); + String so_path = path::join(app_native_lib_dir, mono_so_name); + + mono_dl_handle = try_dlopen(so_path, p_flags); + } + + return mono_dl_handle; + } + + String name = String::utf8(p_name); + + if (name.ends_with(".dll.so") || name.ends_with(".exe.so")) { + String app_native_lib_dir = get_app_native_lib_dir(); + + String orig_so_name = name.get_file(); + String so_name = "lib-aot-" + orig_so_name; + String so_path = path::join(app_native_lib_dir, so_name); + + return try_dlopen(so_path, p_flags); + } + + return NULL; +} + +void *gd_mono_android_dlsym(void *p_handle, const char *p_name, char **r_err, void *p_user_data) { + void *sym_addr = dlsym(p_handle, p_name); + + if (sym_addr) + return sym_addr; + + if (p_handle == mono_dl_handle && godot_dl_handle) { + // Looking up for '__Internal' P/Invoke. We want to search in both the Mono and Godot shared libraries. + // This is needed to resolve the monodroid P/Invoke functions that are defined at the bottom of the file. + sym_addr = dlsym(godot_dl_handle, p_name); + + if (sym_addr) + return sym_addr; + } + + if (r_err) + *r_err = str_format_new("%s\n", dlerror()); + + return NULL; +} + +void *gd_mono_android_dlclose(void *p_handle, void *p_user_data) { + dlclose(p_handle); + + // Not sure if this ever happens. Does Mono close the handle for the main module? + if (p_handle == mono_dl_handle) + mono_dl_handle = NULL; + + return NULL; +} + +int32_t build_version_sdk_int = 0; + +int32_t get_build_version_sdk_int() { + // The JNI code is the equivalent of: + // + // android.os.Build.VERSION.SDK_INT + + if (build_version_sdk_int == 0) { + JNIEnv *env = ThreadAndroid::get_env(); + + jclass versionClass = env->FindClass("android/os/Build$VERSION"); + ERR_FAIL_NULL_V(versionClass, 0); + + jfieldID sdkIntField = env->GetStaticFieldID(versionClass, "SDK_INT", "I"); + ERR_FAIL_NULL_V(sdkIntField, 0); + + build_version_sdk_int = (int32_t)env->GetStaticIntField(versionClass, sdkIntField); + } + + return build_version_sdk_int; +} + +jobject certStore = NULL; // KeyStore + +MonoBoolean _gd_mono_init_cert_store() { + // The JNI code is the equivalent of: + // + // try { + // certStoreLocal = KeyStore.getInstance("AndroidCAStore"); + // certStoreLocal.load(null); + // certStore = certStoreLocal; + // return true; + // } catch (Exception e) { + // return false; + // } + + JNIEnv *env = ThreadAndroid::get_env(); + + ScopedLocalRef<jclass> keyStoreClass(env, env->FindClass("java/security/KeyStore")); + + jmethodID getInstance = env->GetStaticMethodID(keyStoreClass, "getInstance", "(Ljava/lang/String;)Ljava/security/KeyStore;"); + jmethodID load = env->GetMethodID(keyStoreClass, "load", "(Ljava/security/KeyStore$LoadStoreParameter;)V"); + + ScopedLocalRef<jstring> androidCAStoreString(env, env->NewStringUTF("AndroidCAStore")); + + ScopedLocalRef<jobject> certStoreLocal(env, env->CallStaticObjectMethod(keyStoreClass, getInstance, androidCAStoreString.get())); + + if (jni_exception_check(env)) + return 0; + + env->CallVoidMethod(certStoreLocal, load, NULL); + + if (jni_exception_check(env)) + return 0; + + certStore = env->NewGlobalRef(certStoreLocal); + + return 1; +} + +MonoArray *_gd_mono_android_cert_store_lookup(MonoString *p_alias) { + // The JNI code is the equivalent of: + // + // Certificate certificate = certStore.getCertificate(alias); + // if (certificate == null) + // return null; + // return certificate.getEncoded(); + + MonoError mono_error; + char *alias_utf8 = mono_string_to_utf8_checked(p_alias, &mono_error); + + if (!mono_error_ok(&mono_error)) { + ERR_PRINTS(String() + "Failed to convert MonoString* to UTF-8: '" + mono_error_get_message(&mono_error) + "'."); + mono_error_cleanup(&mono_error); + return NULL; + } + + JNIEnv *env = ThreadAndroid::get_env(); + + ScopedLocalRef<jstring> js_alias(env, env->NewStringUTF(alias_utf8)); + mono_free(alias_utf8); + + ScopedLocalRef<jclass> keyStoreClass(env, env->FindClass("java/security/KeyStore")); + ERR_FAIL_NULL_V(keyStoreClass, NULL); + ScopedLocalRef<jclass> certificateClass(env, env->FindClass("java/security/cert/Certificate")); + ERR_FAIL_NULL_V(certificateClass, NULL); + + jmethodID getCertificate = env->GetMethodID(keyStoreClass, "getCertificate", "(Ljava/lang/String;)Ljava/security/cert/Certificate;"); + ERR_FAIL_NULL_V(getCertificate, NULL); + + jmethodID getEncoded = env->GetMethodID(certificateClass, "getEncoded", "()[B"); + ERR_FAIL_NULL_V(getEncoded, NULL); + + ScopedLocalRef<jobject> certificate(env, env->CallObjectMethod(certStore, getCertificate, js_alias.get())); + + if (!certificate) + return NULL; + + ScopedLocalRef<jbyteArray> encoded(env, (jbyteArray)env->CallObjectMethod(certificate, getEncoded)); + jsize encodedLength = env->GetArrayLength(encoded); + + MonoArray *encoded_ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(uint8_t), encodedLength); + uint8_t *dest = (uint8_t *)mono_array_addr(encoded_ret, uint8_t, 0); + + env->GetByteArrayRegion(encoded, 0, encodedLength, reinterpret_cast<jbyte *>(dest)); + + return encoded_ret; +} + +void initialize() { + // We need to set this environment variable to make the monodroid BCL use btls instead of legacy as the default provider + OS::get_singleton()->set_environment("XA_TLS_PROVIDER", "btls"); + + mono_dl_fallback_register(gd_mono_android_dlopen, gd_mono_android_dlsym, gd_mono_android_dlclose, NULL); + + String app_native_lib_dir = get_app_native_lib_dir(); + String so_path = path::join(app_native_lib_dir, godot_so_name); + + godot_dl_handle = try_dlopen(so_path, gd_mono_convert_dl_flags(MONO_DL_LAZY)); +} + +void register_internal_calls() { + mono_add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_init_cert_store", (void *)_gd_mono_init_cert_store); + mono_add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_android_cert_store_lookup", (void *)_gd_mono_android_cert_store_lookup); +} + +void cleanup() { + // This is called after shutting down the Mono runtime + + if (mono_dl_handle) + gd_mono_android_dlclose(mono_dl_handle, NULL); + + if (godot_dl_handle) + gd_mono_android_dlclose(godot_dl_handle, NULL); + + JNIEnv *env = ThreadAndroid::get_env(); + + if (certStore) { + env->DeleteGlobalRef(certStore); + certStore = NULL; + } +} + +} // namespace GDMonoAndroid + +using namespace GDMonoAndroid; + +// The following are P/Invoke functions required by the monodroid profile of the BCL. +// These are P/Invoke functions and not internal calls, hence why they use +// 'mono_bool' and 'const char*' instead of 'MonoBoolean' and 'MonoString*'. + +#define GD_PINVOKE_EXPORT extern "C" __attribute__((visibility("default"))) + +GD_PINVOKE_EXPORT int32_t _monodroid_get_android_api_level() { + return get_build_version_sdk_int(); +} + +GD_PINVOKE_EXPORT void monodroid_free(void *ptr) { + free(ptr); +} + +GD_PINVOKE_EXPORT int32_t monodroid_get_system_property(const char *p_name, char **r_value) { + char prop_value_str[PROP_VALUE_MAX + 1] = { 0 }; + + int len = __system_property_get(p_name, prop_value_str); + + if (r_value) { + if (len >= 0) { + *r_value = (char *)malloc(len + 1); + if (!*r_value) + return -1; + memcpy(*r_value, prop_value_str, len); + (*r_value)[len] = '\0'; + } else { + *r_value = NULL; + } + } + + return len; +} + +GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_up_state(const char *p_ifname, mono_bool *r_is_up) { + // The JNI code is the equivalent of: + // + // NetworkInterface.getByName(p_ifname).isUp() + + if (!r_is_up || !p_ifname || strlen(p_ifname) == 0) + return 0; + + *r_is_up = 0; + + JNIEnv *env = ThreadAndroid::get_env(); + + jclass networkInterfaceClass = env->FindClass("java/net/NetworkInterface"); + ERR_FAIL_NULL_V(networkInterfaceClass, 0); + + jmethodID getByName = env->GetStaticMethodID(networkInterfaceClass, "getByName", "(Ljava/lang/String;)Ljava/net/NetworkInterface;"); + ERR_FAIL_NULL_V(getByName, 0); + + jmethodID isUp = env->GetMethodID(networkInterfaceClass, "isUp", "()Z"); + ERR_FAIL_NULL_V(isUp, 0); + + ScopedLocalRef<jstring> js_ifname(env, env->NewStringUTF(p_ifname)); + ScopedLocalRef<jobject> networkInterface(env, env->CallStaticObjectMethod(networkInterfaceClass, getByName, js_ifname.get())); + + if (!networkInterface) + return 0; + + *r_is_up = (mono_bool)env->CallBooleanMethod(networkInterface, isUp); + + return 1; +} + +GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_supports_multicast(const char *p_ifname, mono_bool *r_supports_multicast) { + // The JNI code is the equivalent of: + // + // NetworkInterface.getByName(p_ifname).supportsMulticast() + + if (!r_supports_multicast || !p_ifname || strlen(p_ifname) == 0) + return 0; + + *r_supports_multicast = 0; + + JNIEnv *env = ThreadAndroid::get_env(); + + jclass networkInterfaceClass = env->FindClass("java/net/NetworkInterface"); + ERR_FAIL_NULL_V(networkInterfaceClass, 0); + + jmethodID getByName = env->GetStaticMethodID(networkInterfaceClass, "getByName", "(Ljava/lang/String;)Ljava/net/NetworkInterface;"); + ERR_FAIL_NULL_V(getByName, 0); + + jmethodID supportsMulticast = env->GetMethodID(networkInterfaceClass, "supportsMulticast", "()Z"); + ERR_FAIL_NULL_V(supportsMulticast, 0); + + ScopedLocalRef<jstring> js_ifname(env, env->NewStringUTF(p_ifname)); + ScopedLocalRef<jobject> networkInterface(env, env->CallStaticObjectMethod(networkInterfaceClass, getByName, js_ifname.get())); + + if (!networkInterface) + return 0; + + *r_supports_multicast = (mono_bool)env->CallBooleanMethod(networkInterface, supportsMulticast); + + return 1; +} + +static const int dns_servers_len = 8; + +static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dns_servers_count) { + // The JNI code is the equivalent of: + // + // ConnectivityManager connectivityManager = (ConnectivityManager)getApplicationContext() + // .getSystemService(Context.CONNECTIVITY_SERVICE); + // Network activeNerwork = connectivityManager.getActiveNetwork(); + // LinkProperties linkProperties = connectivityManager.getLinkProperties(activeNerwork); + // List<String> dnsServers = linkProperties.getDnsServers().stream() + // .map(inetAddress -> inetAddress.getHostAddress()).collect(Collectors.toList()); + +#ifdef DEBUG_ENABLED + CRASH_COND(get_build_version_sdk_int() < 23); +#endif + + JNIEnv *env = ThreadAndroid::get_env(); + + GodotJavaWrapper *godot_java = ((OS_Android *)OS::get_singleton())->get_godot_java(); + jobject activity = godot_java->get_activity(); + + ScopedLocalRef<jclass> activityClass(env, env->GetObjectClass(activity)); + ERR_FAIL_NULL(activityClass); + + jmethodID getApplicationContext = env->GetMethodID(activityClass, "getApplicationContext", "()Landroid/content/Context;"); + + ScopedLocalRef<jobject> applicationContext(env, env->CallObjectMethod(activity, getApplicationContext)); + + ScopedLocalRef<jclass> contextClass(env, env->FindClass("android/content/Context")); + ERR_FAIL_NULL(contextClass); + + jfieldID connectivityServiceField = env->GetStaticFieldID(contextClass, "CONNECTIVITY_SERVICE", "Ljava/lang/String;"); + ScopedLocalRef<jstring> connectivityServiceString(env, (jstring)env->GetStaticObjectField(contextClass, connectivityServiceField)); + + jmethodID getSystemService = env->GetMethodID(contextClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); + + ScopedLocalRef<jobject> connectivityManager(env, env->CallObjectMethod(applicationContext, getSystemService, connectivityServiceString.get())); + + if (!connectivityManager) + return; + + ScopedLocalRef<jclass> connectivityManagerClass(env, env->FindClass("android/net/ConnectivityManager")); + ERR_FAIL_NULL(connectivityManagerClass); + + jmethodID getActiveNetwork = env->GetMethodID(connectivityManagerClass, "getActiveNetwork", "()Landroid/net/Network;"); + ERR_FAIL_NULL(getActiveNetwork); + + ScopedLocalRef<jobject> activeNetwork(env, env->CallObjectMethod(connectivityManager, getActiveNetwork)); + + if (!activeNetwork) + return; + + jmethodID getLinkProperties = env->GetMethodID(connectivityManagerClass, + "getLinkProperties", "(Landroid/net/Network;)Landroid/net/LinkProperties;"); + ERR_FAIL_NULL(getLinkProperties); + + ScopedLocalRef<jobject> linkProperties(env, env->CallObjectMethod(connectivityManager, getLinkProperties, activeNetwork.get())); + + if (!linkProperties) + return; + + ScopedLocalRef<jclass> linkPropertiesClass(env, env->FindClass("android/net/LinkProperties")); + ERR_FAIL_NULL(linkPropertiesClass); + + jmethodID getDnsServers = env->GetMethodID(linkPropertiesClass, "getDnsServers", "()Ljava/util/List;"); + ERR_FAIL_NULL(getDnsServers); + + ScopedLocalRef<jobject> dnsServers(env, env->CallObjectMethod(linkProperties, getDnsServers)); + + if (!dnsServers) + return; + + ScopedLocalRef<jclass> listClass(env, env->FindClass("java/util/List")); + ERR_FAIL_NULL(listClass); + + jmethodID listSize = env->GetMethodID(listClass, "size", "()I"); + ERR_FAIL_NULL(listSize); + + int dnsServersCount = env->CallIntMethod(dnsServers, listSize); + + if (dnsServersCount > dns_servers_len) + dnsServersCount = dns_servers_len; + + if (dnsServersCount <= 0) + return; + + jmethodID listGet = env->GetMethodID(listClass, "get", "(I)Ljava/lang/Object;"); + ERR_FAIL_NULL(listGet); + + ScopedLocalRef<jclass> inetAddressClass(env, env->FindClass("java/net/InetAddress")); + ERR_FAIL_NULL(inetAddressClass); + + jmethodID getHostAddress = env->GetMethodID(inetAddressClass, "getHostAddress", "()Ljava/lang/String;"); + ERR_FAIL_NULL(getHostAddress); + + for (int i = 0; i < dnsServersCount; i++) { + ScopedLocalRef<jobject> dnsServer(env, env->CallObjectMethod(dnsServers, listGet, (jint)i)); + if (!dnsServer) + continue; + + ScopedLocalRef<jstring> hostAddress(env, (jstring)env->CallObjectMethod(dnsServer, getHostAddress)); + const char *host_address = env->GetStringUTFChars(hostAddress, 0); + + r_dns_servers[i] = strdup(host_address); // freed by the BCL + (*dns_servers_count)++; + + env->ReleaseStringUTFChars(hostAddress, host_address); + } + + // jesus... +} + +GD_PINVOKE_EXPORT int32_t _monodroid_get_dns_servers(void **r_dns_servers_array) { + if (!r_dns_servers_array) + return -1; + + *r_dns_servers_array = NULL; + + char *dns_servers[dns_servers_len]; + int dns_servers_count = 0; + + if (_monodroid_get_android_api_level() < 26) { + // The 'net.dns*' system properties are no longer available in Android 8.0 (API level 26) and greater: + // https://developer.android.com/about/versions/oreo/android-8.0-changes.html#o-pri + + char prop_name[] = "net.dns*"; + + for (int i = 0; i < dns_servers_len; i++) { + prop_name[7] = (char)(i + 0x31); + char *prop_value; + int32_t len = monodroid_get_system_property(prop_name, &prop_value); + + if (len > 0) { + dns_servers[dns_servers_count] = strndup(prop_value, (size_t)len); // freed by the BCL + dns_servers_count++; + free(prop_value); + } + } + } else { + // Alternative for Oreo and greater + interop_get_active_network_dns_servers(dns_servers, &dns_servers_count); + } + + if (dns_servers_count > 0) { + size_t ret_size = sizeof(char *) * (size_t)dns_servers_count; + *r_dns_servers_array = malloc(ret_size); // freed by the BCL + memcpy(*r_dns_servers_array, dns_servers, ret_size); + } + + return dns_servers_count; +} + +GD_PINVOKE_EXPORT const char *_monodroid_timezone_get_default_id() { + // The JNI code is the equivalent of: + // + // TimeZone.getDefault().getID() + + JNIEnv *env = ThreadAndroid::get_env(); + + ScopedLocalRef<jclass> timeZoneClass(env, env->FindClass("java/util/TimeZone")); + ERR_FAIL_NULL_V(timeZoneClass, NULL); + + jmethodID getDefault = env->GetStaticMethodID(timeZoneClass, "getDefault", "()Ljava/util/TimeZone;"); + ERR_FAIL_NULL_V(getDefault, NULL); + + jmethodID getID = env->GetMethodID(timeZoneClass, "getID", "()Ljava/lang/String;"); + ERR_FAIL_NULL_V(getID, NULL); + + ScopedLocalRef<jobject> defaultTimeZone(env, env->CallStaticObjectMethod(timeZoneClass, getDefault)); + + if (!defaultTimeZone) + return NULL; + + ScopedLocalRef<jstring> defaultTimeZoneID(env, (jstring)env->CallObjectMethod(defaultTimeZone, getID)); + + if (!defaultTimeZoneID) + return NULL; + + const char *default_time_zone_id = env->GetStringUTFChars(defaultTimeZoneID, 0); + + char *result = strdup(default_time_zone_id); // freed by the BCL + + env->ReleaseStringUTFChars(defaultTimeZoneID, default_time_zone_id); + + return result; +} + +GD_PINVOKE_EXPORT int32_t _monodroid_getifaddrs(struct ifaddrs **p_ifap) { + return getifaddrs(p_ifap); +} + +GD_PINVOKE_EXPORT void _monodroid_freeifaddrs(struct ifaddrs *p_ifap) { + freeifaddrs(p_ifap); +} + +#endif diff --git a/modules/mono/editor/mono_build_info.h b/modules/mono/mono_gd/gd_mono_android.h index b0ae2ed52e..20ca266428 100644 --- a/modules/mono/editor/mono_build_info.h +++ b/modules/mono/mono_gd/gd_mono_android.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* mono_build_info.h */ +/* gd_mono_android.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,28 +28,25 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef MONO_BUILD_INFO_H -#define MONO_BUILD_INFO_H +#ifndef GD_MONO_ANDROID_H +#define GD_MONO_ANDROID_H + +#if defined(ANDROID_ENABLED) #include "core/ustring.h" -#include "core/vector.h" -struct MonoBuildInfo { +namespace GDMonoAndroid { + +String get_app_native_lib_dir(); - struct Hasher { - static uint32_t hash(const MonoBuildInfo &p_key); - }; +void initialize(); - String solution; - String configuration; - Vector<String> custom_props; +void register_internal_calls(); - bool operator==(const MonoBuildInfo &p_b) const; +void cleanup(); - String get_log_dirpath(); +} // namespace GDMonoAndroid - MonoBuildInfo(); - MonoBuildInfo(const String &p_solution, const String &p_config); -}; +#endif // ANDROID_ENABLED -#endif // MONO_BUILD_INFO_H +#endif // GD_MONO_ANDROID_H diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp index 8fec28b186..105560fe9a 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.cpp +++ b/modules/mono/mono_gd/gd_mono_assembly.cpp @@ -39,6 +39,7 @@ #include "core/project_settings.h" #include "../godotsharp_dirs.h" +#include "gd_mono_cache.h" #include "gd_mono_class.h" bool GDMonoAssembly::no_search = false; @@ -46,26 +47,50 @@ bool GDMonoAssembly::in_preload = false; Vector<String> GDMonoAssembly::search_dirs; -void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config) { +void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config, const String &p_custom_bcl_dir) { - const char *rootdir = mono_assembly_getrootdir(); - if (rootdir) { - String framework_dir = String::utf8(rootdir).plus_file("mono").plus_file("4.5"); + String framework_dir; + + if (!p_custom_bcl_dir.empty()) { + framework_dir = p_custom_bcl_dir; + } else if (mono_assembly_getrootdir()) { + framework_dir = String::utf8(mono_assembly_getrootdir()).plus_file("mono").plus_file("4.5"); + } + + if (!framework_dir.empty()) { r_search_dirs.push_back(framework_dir); r_search_dirs.push_back(framework_dir.plus_file("Facades")); } +#if !defined(TOOLS_ENABLED) + String data_game_assemblies_dir = GodotSharpDirs::get_data_game_assemblies_dir(); + if (!data_game_assemblies_dir.empty()) { + r_search_dirs.push_back(data_game_assemblies_dir); + } +#endif + if (p_custom_config.length()) { r_search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_base_dir().plus_file(p_custom_config)); } else { r_search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_dir()); } - r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir()); + if (p_custom_config.empty()) { + r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir()); + } else { + String api_config = p_custom_config == "Release" ? "Release" : "Debug"; + r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir().plus_file(api_config)); + } + + r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir()); r_search_dirs.push_back(OS::get_singleton()->get_resource_dir()); r_search_dirs.push_back(OS::get_singleton()->get_executable_path().get_base_dir()); + #ifdef TOOLS_ENABLED r_search_dirs.push_back(GodotSharpDirs::get_data_editor_tools_dir()); + + // For GodotTools to find the api assemblies + r_search_dirs.push_back(GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file("Debug")); #endif } @@ -129,19 +154,15 @@ MonoAssembly *GDMonoAssembly::_preload_hook(MonoAssemblyName *aname, char **, vo (void)user_data; // UNUSED - if (search_dirs.empty()) { - fill_search_dirs(search_dirs); - } - { - // If we find the assembly here, we load it with `mono_assembly_load_from_full`, + // If we find the assembly here, we load it with 'mono_assembly_load_from_full', // which in turn invokes load hooks before returning the MonoAssembly to us. - // One of the load hooks is `load_aot_module`. This hook can end up calling preload hooks - // again for the same assembly in certain in certain circumstances (the `do_load_image` part). + // One of the load hooks is 'load_aot_module'. This hook can end up calling preload hooks + // again for the same assembly in certain in certain circumstances (the 'do_load_image' part). // If this is the case and we return NULL due to the no_search condition below, // it will result in an internal crash later on. Therefore we need to return the assembly we didn't - // get yet from `mono_assembly_load_from_full`. Luckily we have the image, which already got it. - // This must be done here. If done in search hooks, it would cause `mono_assembly_load_from_full` + // get yet from 'mono_assembly_load_from_full'. Luckily we have the image, which already got it. + // This must be done here. If done in search hooks, it would cause 'mono_assembly_load_from_full' // to think another MonoAssembly for this assembly was already loaded, making it delete its own, // when in fact both pointers were the same... This hooks thing is confusing. if (image_corlib_loading) { @@ -210,6 +231,33 @@ GDMonoAssembly *GDMonoAssembly::_load_assembly_search(const String &p_name, cons return NULL; } +String GDMonoAssembly::find_assembly(const String &p_name) { + + String path; + + bool has_extension = p_name.ends_with(".dll") || p_name.ends_with(".exe"); + + for (int i = 0; i < search_dirs.size(); i++) { + const String &search_dir = search_dirs[i]; + + if (has_extension) { + path = search_dir.plus_file(p_name); + if (FileAccess::exists(path)) + return path; + } else { + path = search_dir.plus_file(p_name + ".dll"); + if (FileAccess::exists(path)) + return path; + + path = search_dir.plus_file(p_name + ".exe"); + if (FileAccess::exists(path)) + return path; + } + } + + return String(); +} + GDMonoAssembly *GDMonoAssembly::_load_assembly_from(const String &p_name, const String &p_path, bool p_refonly) { GDMonoAssembly *assembly = memnew(GDMonoAssembly(p_name, p_path)); @@ -246,6 +294,8 @@ void GDMonoAssembly::_wrap_mono_assembly(MonoAssembly *assembly) { void GDMonoAssembly::initialize() { + fill_search_dirs(search_dirs); + mono_install_assembly_search_hook(&assembly_search_hook, NULL); mono_install_assembly_refonly_search_hook(&assembly_refonly_search_hook, NULL); mono_install_assembly_preload_hook(&assembly_preload_hook, NULL); @@ -264,7 +314,18 @@ Error GDMonoAssembly::load(bool p_refonly) { Vector<uint8_t> data = FileAccess::get_file_as_array(path); ERR_FAIL_COND_V(data.empty(), ERR_FILE_CANT_READ); - String image_filename = ProjectSettings::get_singleton()->globalize_path(path); + String image_filename; + +#ifdef ANDROID_ENABLED + if (path.begins_with("res://")) { + image_filename = path.substr(6, path.length()); + } else { + image_filename = ProjectSettings::get_singleton()->globalize_path(path); + } +#else + // FIXME: globalize_path does not work on exported games + image_filename = ProjectSettings::get_singleton()->globalize_path(path); +#endif MonoImageOpenStatus status = MONO_IMAGE_OK; diff --git a/modules/mono/mono_gd/gd_mono_assembly.h b/modules/mono/mono_gd/gd_mono_assembly.h index 32432af37d..04a219f742 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.h +++ b/modules/mono/mono_gd/gd_mono_assembly.h @@ -122,7 +122,9 @@ public: GDMonoClass *get_object_derived_class(const StringName &p_class); - static void fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config = String()); + static String find_assembly(const String &p_name); + + static void fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config = String(), const String &p_custom_bcl_dir = String()); static GDMonoAssembly *load_from(const String &p_name, const String &p_path, bool p_refonly); diff --git a/modules/mono/mono_gd/gd_mono_cache.cpp b/modules/mono/mono_gd/gd_mono_cache.cpp new file mode 100644 index 0000000000..caa1ca9203 --- /dev/null +++ b/modules/mono/mono_gd/gd_mono_cache.cpp @@ -0,0 +1,312 @@ +/*************************************************************************/ +/* gd_mono_cache.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 "gd_mono_cache.h" + +#include "gd_mono.h" +#include "gd_mono_class.h" +#include "gd_mono_marshal.h" +#include "gd_mono_method.h" +#include "gd_mono_utils.h" + +namespace GDMonoCache { + +CachedData cached_data; + +#define CACHE_AND_CHECK(m_var, m_val) \ + { \ + CRASH_COND(m_var != NULL); \ + m_var = m_val; \ + ERR_FAIL_COND_MSG(m_var == NULL, "Mono Cache: Member " #m_var " is null."); \ + } + +#define CACHE_CLASS_AND_CHECK(m_class, m_val) CACHE_AND_CHECK(cached_data.class_##m_class, m_val) +#define CACHE_NS_CLASS_AND_CHECK(m_ns, m_class, m_val) CACHE_AND_CHECK(cached_data.class_##m_ns##_##m_class, m_val) +#define CACHE_RAW_MONO_CLASS_AND_CHECK(m_class, m_val) CACHE_AND_CHECK(cached_data.rawclass_##m_class, m_val) +#define CACHE_FIELD_AND_CHECK(m_class, m_field, m_val) CACHE_AND_CHECK(cached_data.field_##m_class##_##m_field, m_val) +#define CACHE_METHOD_AND_CHECK(m_class, m_method, m_val) CACHE_AND_CHECK(cached_data.method_##m_class##_##m_method, m_val) +#define CACHE_PROPERTY_AND_CHECK(m_class, m_property, m_val) CACHE_AND_CHECK(cached_data.property_##m_class##_##m_property, m_val) + +#define CACHE_METHOD_THUNK_AND_CHECK_IMPL(m_var, m_val) \ + { \ + CRASH_COND(!m_var.is_null()); \ + ERR_FAIL_COND_MSG(m_val == NULL, "Mono Cache: Method for member " #m_var " is null."); \ + m_var.set_from_method(m_val); \ + ERR_FAIL_COND_MSG(m_var.is_null(), "Mono Cache: Member " #m_var " is null."); \ + } + +#define CACHE_METHOD_THUNK_AND_CHECK(m_class, m_method, m_val) CACHE_METHOD_THUNK_AND_CHECK_IMPL(cached_data.methodthunk_##m_class##_##m_method, m_val) + +void CachedData::clear_corlib_cache() { + + corlib_cache_updated = false; + + class_MonoObject = NULL; + class_bool = NULL; + class_int8_t = NULL; + class_int16_t = NULL; + class_int32_t = NULL; + class_int64_t = NULL; + class_uint8_t = NULL; + class_uint16_t = NULL; + class_uint32_t = NULL; + class_uint64_t = NULL; + class_float = NULL; + class_double = NULL; + class_String = NULL; + class_IntPtr = NULL; + + class_System_Collections_IEnumerable = NULL; + class_System_Collections_IDictionary = NULL; + +#ifdef DEBUG_ENABLED + class_System_Diagnostics_StackTrace = NULL; + methodthunk_System_Diagnostics_StackTrace_GetFrames.nullify(); + method_System_Diagnostics_StackTrace_ctor_bool = NULL; + method_System_Diagnostics_StackTrace_ctor_Exception_bool = NULL; +#endif + + class_KeyNotFoundException = NULL; +} + +void CachedData::clear_godot_api_cache() { + + godot_api_cache_updated = false; + + rawclass_Dictionary = NULL; + + class_Vector2 = NULL; + class_Rect2 = NULL; + class_Transform2D = NULL; + class_Vector3 = NULL; + class_Basis = NULL; + class_Quat = NULL; + class_Transform = NULL; + class_AABB = NULL; + class_Color = NULL; + class_Plane = NULL; + class_NodePath = NULL; + class_RID = NULL; + class_GodotObject = NULL; + class_GodotResource = NULL; + class_Node = NULL; + class_Control = NULL; + class_Spatial = NULL; + class_WeakRef = NULL; + class_Array = NULL; + class_Dictionary = NULL; + class_MarshalUtils = NULL; + class_ISerializationListener = NULL; + +#ifdef DEBUG_ENABLED + class_DebuggingUtils = NULL; + methodthunk_DebuggingUtils_GetStackFrameInfo.nullify(); +#endif + + class_ExportAttribute = NULL; + field_ExportAttribute_hint = NULL; + field_ExportAttribute_hintString = NULL; + class_SignalAttribute = NULL; + class_ToolAttribute = NULL; + class_RemoteAttribute = NULL; + class_SyncAttribute = NULL; + class_MasterAttribute = NULL; + class_PuppetAttribute = NULL; + class_SlaveAttribute = NULL; + class_RemoteSyncAttribute = NULL; + class_MasterSyncAttribute = NULL; + class_PuppetSyncAttribute = NULL; + class_GodotMethodAttribute = NULL; + field_GodotMethodAttribute_methodName = NULL; + + field_GodotObject_ptr = NULL; + field_NodePath_ptr = NULL; + field_Image_ptr = NULL; + field_RID_ptr = NULL; + + methodthunk_GodotObject_Dispose.nullify(); + methodthunk_Array_GetPtr.nullify(); + methodthunk_Dictionary_GetPtr.nullify(); + methodthunk_SignalAwaiter_SignalCallback.nullify(); + methodthunk_SignalAwaiter_FailureCallback.nullify(); + methodthunk_GodotTaskScheduler_Activate.nullify(); + + // Start of MarshalUtils methods + + methodthunk_MarshalUtils_TypeIsGenericArray.nullify(); + methodthunk_MarshalUtils_TypeIsGenericDictionary.nullify(); + + methodthunk_MarshalUtils_ArrayGetElementType.nullify(); + methodthunk_MarshalUtils_DictionaryGetKeyValueTypes.nullify(); + + methodthunk_MarshalUtils_GenericIEnumerableIsAssignableFromType.nullify(); + methodthunk_MarshalUtils_GenericIDictionaryIsAssignableFromType.nullify(); + methodthunk_MarshalUtils_GenericIEnumerableIsAssignableFromType_with_info.nullify(); + methodthunk_MarshalUtils_GenericIDictionaryIsAssignableFromType_with_info.nullify(); + + methodthunk_MarshalUtils_MakeGenericArrayType.nullify(); + methodthunk_MarshalUtils_MakeGenericDictionaryType.nullify(); + + methodthunk_MarshalUtils_EnumerableToArray.nullify(); + methodthunk_MarshalUtils_IDictionaryToDictionary.nullify(); + methodthunk_MarshalUtils_GenericIDictionaryToDictionary.nullify(); + + // End of MarshalUtils methods + + task_scheduler_handle = Ref<MonoGCHandle>(); +} + +#define GODOT_API_CLASS(m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, #m_class)) +#define GODOT_API_NS_CLASS(m_ns, m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(m_ns, #m_class)) + +void update_corlib_cache() { + + CACHE_CLASS_AND_CHECK(MonoObject, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_object_class())); + CACHE_CLASS_AND_CHECK(bool, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_boolean_class())); + CACHE_CLASS_AND_CHECK(int8_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_sbyte_class())); + CACHE_CLASS_AND_CHECK(int16_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int16_class())); + CACHE_CLASS_AND_CHECK(int32_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int32_class())); + CACHE_CLASS_AND_CHECK(int64_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int64_class())); + CACHE_CLASS_AND_CHECK(uint8_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_byte_class())); + CACHE_CLASS_AND_CHECK(uint16_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint16_class())); + CACHE_CLASS_AND_CHECK(uint32_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint32_class())); + CACHE_CLASS_AND_CHECK(uint64_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint64_class())); + CACHE_CLASS_AND_CHECK(float, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_single_class())); + CACHE_CLASS_AND_CHECK(double, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_double_class())); + CACHE_CLASS_AND_CHECK(String, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_string_class())); + CACHE_CLASS_AND_CHECK(IntPtr, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_intptr_class())); + + CACHE_CLASS_AND_CHECK(System_Collections_IEnumerable, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections", "IEnumerable")); + CACHE_CLASS_AND_CHECK(System_Collections_IDictionary, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections", "IDictionary")); + +#ifdef DEBUG_ENABLED + CACHE_CLASS_AND_CHECK(System_Diagnostics_StackTrace, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Diagnostics", "StackTrace")); + CACHE_METHOD_THUNK_AND_CHECK(System_Diagnostics_StackTrace, GetFrames, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method("GetFrames")); + CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(bool)", true)); + CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_Exception_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(System.Exception,bool)", true)); +#endif + + CACHE_CLASS_AND_CHECK(KeyNotFoundException, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections.Generic", "KeyNotFoundException")); + + cached_data.corlib_cache_updated = true; +} + +void update_godot_api_cache() { + + CACHE_CLASS_AND_CHECK(Vector2, GODOT_API_CLASS(Vector2)); + CACHE_CLASS_AND_CHECK(Rect2, GODOT_API_CLASS(Rect2)); + CACHE_CLASS_AND_CHECK(Transform2D, GODOT_API_CLASS(Transform2D)); + CACHE_CLASS_AND_CHECK(Vector3, GODOT_API_CLASS(Vector3)); + CACHE_CLASS_AND_CHECK(Basis, GODOT_API_CLASS(Basis)); + CACHE_CLASS_AND_CHECK(Quat, GODOT_API_CLASS(Quat)); + CACHE_CLASS_AND_CHECK(Transform, GODOT_API_CLASS(Transform)); + CACHE_CLASS_AND_CHECK(AABB, GODOT_API_CLASS(AABB)); + CACHE_CLASS_AND_CHECK(Color, GODOT_API_CLASS(Color)); + CACHE_CLASS_AND_CHECK(Plane, GODOT_API_CLASS(Plane)); + CACHE_CLASS_AND_CHECK(NodePath, GODOT_API_CLASS(NodePath)); + CACHE_CLASS_AND_CHECK(RID, GODOT_API_CLASS(RID)); + CACHE_CLASS_AND_CHECK(GodotObject, GODOT_API_CLASS(Object)); + CACHE_CLASS_AND_CHECK(GodotResource, GODOT_API_CLASS(Resource)); + CACHE_CLASS_AND_CHECK(Node, GODOT_API_CLASS(Node)); + CACHE_CLASS_AND_CHECK(Control, GODOT_API_CLASS(Control)); + CACHE_CLASS_AND_CHECK(Spatial, GODOT_API_CLASS(Spatial)); + CACHE_CLASS_AND_CHECK(WeakRef, GODOT_API_CLASS(WeakRef)); + CACHE_CLASS_AND_CHECK(Array, GODOT_API_NS_CLASS(BINDINGS_NAMESPACE_COLLECTIONS, Array)); + CACHE_CLASS_AND_CHECK(Dictionary, GODOT_API_NS_CLASS(BINDINGS_NAMESPACE_COLLECTIONS, Dictionary)); + CACHE_CLASS_AND_CHECK(MarshalUtils, GODOT_API_CLASS(MarshalUtils)); + CACHE_CLASS_AND_CHECK(ISerializationListener, GODOT_API_CLASS(ISerializationListener)); + +#ifdef DEBUG_ENABLED + CACHE_CLASS_AND_CHECK(DebuggingUtils, GODOT_API_CLASS(DebuggingUtils)); +#endif + + // Attributes + CACHE_CLASS_AND_CHECK(ExportAttribute, GODOT_API_CLASS(ExportAttribute)); + CACHE_FIELD_AND_CHECK(ExportAttribute, hint, CACHED_CLASS(ExportAttribute)->get_field("hint")); + CACHE_FIELD_AND_CHECK(ExportAttribute, hintString, CACHED_CLASS(ExportAttribute)->get_field("hintString")); + CACHE_CLASS_AND_CHECK(SignalAttribute, GODOT_API_CLASS(SignalAttribute)); + CACHE_CLASS_AND_CHECK(ToolAttribute, GODOT_API_CLASS(ToolAttribute)); + CACHE_CLASS_AND_CHECK(RemoteAttribute, GODOT_API_CLASS(RemoteAttribute)); + CACHE_CLASS_AND_CHECK(SyncAttribute, GODOT_API_CLASS(SyncAttribute)); + CACHE_CLASS_AND_CHECK(MasterAttribute, GODOT_API_CLASS(MasterAttribute)); + CACHE_CLASS_AND_CHECK(PuppetAttribute, GODOT_API_CLASS(PuppetAttribute)); + CACHE_CLASS_AND_CHECK(SlaveAttribute, GODOT_API_CLASS(SlaveAttribute)); + CACHE_CLASS_AND_CHECK(RemoteSyncAttribute, GODOT_API_CLASS(RemoteSyncAttribute)); + CACHE_CLASS_AND_CHECK(MasterSyncAttribute, GODOT_API_CLASS(MasterSyncAttribute)); + CACHE_CLASS_AND_CHECK(PuppetSyncAttribute, GODOT_API_CLASS(PuppetSyncAttribute)); + CACHE_CLASS_AND_CHECK(GodotMethodAttribute, GODOT_API_CLASS(GodotMethodAttribute)); + CACHE_FIELD_AND_CHECK(GodotMethodAttribute, methodName, CACHED_CLASS(GodotMethodAttribute)->get_field("methodName")); + + CACHE_FIELD_AND_CHECK(GodotObject, ptr, CACHED_CLASS(GodotObject)->get_field(BINDINGS_PTR_FIELD)); + CACHE_FIELD_AND_CHECK(NodePath, ptr, CACHED_CLASS(NodePath)->get_field(BINDINGS_PTR_FIELD)); + CACHE_FIELD_AND_CHECK(RID, ptr, CACHED_CLASS(RID)->get_field(BINDINGS_PTR_FIELD)); + + CACHE_METHOD_THUNK_AND_CHECK(GodotObject, Dispose, CACHED_CLASS(GodotObject)->get_method("Dispose", 0)); + CACHE_METHOD_THUNK_AND_CHECK(Array, GetPtr, GODOT_API_NS_CLASS(BINDINGS_NAMESPACE_COLLECTIONS, Array)->get_method("GetPtr", 0)); + CACHE_METHOD_THUNK_AND_CHECK(Dictionary, GetPtr, GODOT_API_NS_CLASS(BINDINGS_NAMESPACE_COLLECTIONS, Dictionary)->get_method("GetPtr", 0)); + CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, SignalCallback, GODOT_API_CLASS(SignalAwaiter)->get_method("SignalCallback", 1)); + CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, FailureCallback, GODOT_API_CLASS(SignalAwaiter)->get_method("FailureCallback", 0)); + CACHE_METHOD_THUNK_AND_CHECK(GodotTaskScheduler, Activate, GODOT_API_CLASS(GodotTaskScheduler)->get_method("Activate", 0)); + + // Start of MarshalUtils methods + + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericArray, GODOT_API_CLASS(MarshalUtils)->get_method("TypeIsGenericArray", 1)); + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericDictionary, GODOT_API_CLASS(MarshalUtils)->get_method("TypeIsGenericDictionary", 1)); + + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, ArrayGetElementType, GODOT_API_CLASS(MarshalUtils)->get_method("ArrayGetElementType", 2)); + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, DictionaryGetKeyValueTypes, GODOT_API_CLASS(MarshalUtils)->get_method("DictionaryGetKeyValueTypes", 3)); + + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIEnumerableIsAssignableFromType, GODOT_API_CLASS(MarshalUtils)->get_method("GenericIEnumerableIsAssignableFromType", 1)); + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIDictionaryIsAssignableFromType, GODOT_API_CLASS(MarshalUtils)->get_method("GenericIDictionaryIsAssignableFromType", 1)); + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIEnumerableIsAssignableFromType_with_info, GODOT_API_CLASS(MarshalUtils)->get_method("GenericIEnumerableIsAssignableFromType", 2)); + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIDictionaryIsAssignableFromType_with_info, GODOT_API_CLASS(MarshalUtils)->get_method("GenericIDictionaryIsAssignableFromType", 3)); + + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, MakeGenericArrayType, GODOT_API_CLASS(MarshalUtils)->get_method("MakeGenericArrayType", 1)); + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, MakeGenericDictionaryType, GODOT_API_CLASS(MarshalUtils)->get_method("MakeGenericDictionaryType", 2)); + + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, EnumerableToArray, GODOT_API_CLASS(MarshalUtils)->get_method("EnumerableToArray", 2)); + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, IDictionaryToDictionary, GODOT_API_CLASS(MarshalUtils)->get_method("IDictionaryToDictionary", 2)); + CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIDictionaryToDictionary, GODOT_API_CLASS(MarshalUtils)->get_method("GenericIDictionaryToDictionary", 2)); + + // End of MarshalUtils methods + +#ifdef DEBUG_ENABLED + CACHE_METHOD_THUNK_AND_CHECK(DebuggingUtils, GetStackFrameInfo, GODOT_API_CLASS(DebuggingUtils)->get_method("GetStackFrameInfo", 4)); +#endif + + // TODO Move to CSharpLanguage::init() and do handle disposal + MonoObject *task_scheduler = mono_object_new(mono_domain_get(), GODOT_API_CLASS(GodotTaskScheduler)->get_mono_ptr()); + GDMonoUtils::runtime_object_init(task_scheduler, GODOT_API_CLASS(GodotTaskScheduler)); + cached_data.task_scheduler_handle = MonoGCHandle::create_strong(task_scheduler); + + cached_data.godot_api_cache_updated = true; +} + +} // namespace GDMonoCache diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h new file mode 100644 index 0000000000..a6d6da4f2b --- /dev/null +++ b/modules/mono/mono_gd/gd_mono_cache.h @@ -0,0 +1,204 @@ +/*************************************************************************/ +/* gd_mono_cache.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 GD_MONO_CACHE_H +#define GD_MONO_CACHE_H + +#include "gd_mono_header.h" +#include "gd_mono_method_thunk.h" + +namespace GDMonoCache { + +struct CachedData { + + // ----------------------------------------------- + // corlib classes + + // Let's use the no-namespace format for these too + GDMonoClass *class_MonoObject; // object + GDMonoClass *class_bool; // bool + GDMonoClass *class_int8_t; // sbyte + GDMonoClass *class_int16_t; // short + GDMonoClass *class_int32_t; // int + GDMonoClass *class_int64_t; // long + GDMonoClass *class_uint8_t; // byte + GDMonoClass *class_uint16_t; // ushort + GDMonoClass *class_uint32_t; // uint + GDMonoClass *class_uint64_t; // ulong + GDMonoClass *class_float; // float + GDMonoClass *class_double; // double + GDMonoClass *class_String; // string + GDMonoClass *class_IntPtr; // System.IntPtr + + GDMonoClass *class_System_Collections_IEnumerable; + GDMonoClass *class_System_Collections_IDictionary; + +#ifdef DEBUG_ENABLED + GDMonoClass *class_System_Diagnostics_StackTrace; + GDMonoMethodThunkR<MonoArray *, MonoObject *> methodthunk_System_Diagnostics_StackTrace_GetFrames; + GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_bool; + GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_Exception_bool; +#endif + + GDMonoClass *class_KeyNotFoundException; + + MonoClass *rawclass_Dictionary; + // ----------------------------------------------- + + GDMonoClass *class_Vector2; + GDMonoClass *class_Rect2; + GDMonoClass *class_Transform2D; + GDMonoClass *class_Vector3; + GDMonoClass *class_Basis; + GDMonoClass *class_Quat; + GDMonoClass *class_Transform; + GDMonoClass *class_AABB; + GDMonoClass *class_Color; + GDMonoClass *class_Plane; + GDMonoClass *class_NodePath; + GDMonoClass *class_RID; + GDMonoClass *class_GodotObject; + GDMonoClass *class_GodotResource; + GDMonoClass *class_Node; + GDMonoClass *class_Control; + GDMonoClass *class_Spatial; + GDMonoClass *class_WeakRef; + GDMonoClass *class_Array; + GDMonoClass *class_Dictionary; + GDMonoClass *class_MarshalUtils; + GDMonoClass *class_ISerializationListener; + +#ifdef DEBUG_ENABLED + GDMonoClass *class_DebuggingUtils; + GDMonoMethodThunk<MonoObject *, MonoString **, int *, MonoString **> methodthunk_DebuggingUtils_GetStackFrameInfo; +#endif + + GDMonoClass *class_ExportAttribute; + GDMonoField *field_ExportAttribute_hint; + GDMonoField *field_ExportAttribute_hintString; + GDMonoClass *class_SignalAttribute; + GDMonoClass *class_ToolAttribute; + GDMonoClass *class_RemoteAttribute; + GDMonoClass *class_SyncAttribute; + GDMonoClass *class_RemoteSyncAttribute; + GDMonoClass *class_MasterSyncAttribute; + GDMonoClass *class_PuppetSyncAttribute; + GDMonoClass *class_MasterAttribute; + GDMonoClass *class_PuppetAttribute; + GDMonoClass *class_SlaveAttribute; + GDMonoClass *class_GodotMethodAttribute; + GDMonoField *field_GodotMethodAttribute_methodName; + + GDMonoField *field_GodotObject_ptr; + GDMonoField *field_NodePath_ptr; + GDMonoField *field_Image_ptr; + GDMonoField *field_RID_ptr; + + GDMonoMethodThunk<MonoObject *> methodthunk_GodotObject_Dispose; + GDMonoMethodThunkR<Array *, MonoObject *> methodthunk_Array_GetPtr; + GDMonoMethodThunkR<Dictionary *, MonoObject *> methodthunk_Dictionary_GetPtr; + GDMonoMethodThunk<MonoObject *, MonoArray *> methodthunk_SignalAwaiter_SignalCallback; + GDMonoMethodThunk<MonoObject *> methodthunk_SignalAwaiter_FailureCallback; + GDMonoMethodThunk<MonoObject *> methodthunk_GodotTaskScheduler_Activate; + + // Start of MarshalUtils methods + + GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeIsGenericArray; + GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeIsGenericDictionary; + + GDMonoMethodThunk<MonoReflectionType *, MonoReflectionType **> methodthunk_MarshalUtils_ArrayGetElementType; + GDMonoMethodThunk<MonoReflectionType *, MonoReflectionType **, MonoReflectionType **> methodthunk_MarshalUtils_DictionaryGetKeyValueTypes; + + GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_GenericIEnumerableIsAssignableFromType; + GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_GenericIDictionaryIsAssignableFromType; + GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *, MonoReflectionType **> methodthunk_MarshalUtils_GenericIEnumerableIsAssignableFromType_with_info; + GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *, MonoReflectionType **, MonoReflectionType **> methodthunk_MarshalUtils_GenericIDictionaryIsAssignableFromType_with_info; + + GDMonoMethodThunkR<MonoReflectionType *, MonoReflectionType *> methodthunk_MarshalUtils_MakeGenericArrayType; + GDMonoMethodThunkR<MonoReflectionType *, MonoReflectionType *, MonoReflectionType *> methodthunk_MarshalUtils_MakeGenericDictionaryType; + + GDMonoMethodThunk<MonoObject *, Array *> methodthunk_MarshalUtils_EnumerableToArray; + GDMonoMethodThunk<MonoObject *, Dictionary *> methodthunk_MarshalUtils_IDictionaryToDictionary; + GDMonoMethodThunk<MonoObject *, Dictionary *> methodthunk_MarshalUtils_GenericIDictionaryToDictionary; + + // End of MarshalUtils methods + + Ref<MonoGCHandle> task_scheduler_handle; + + bool corlib_cache_updated; + bool godot_api_cache_updated; + + void clear_corlib_cache(); + void clear_godot_api_cache(); + + CachedData() { + clear_corlib_cache(); + clear_godot_api_cache(); + } +}; + +extern CachedData cached_data; + +void update_corlib_cache(); +void update_godot_api_cache(); + +inline void clear_corlib_cache() { + cached_data.clear_corlib_cache(); +} + +inline void clear_godot_api_cache() { + cached_data.clear_godot_api_cache(); +} + +_FORCE_INLINE_ bool tools_godot_api_check() { +#ifdef TOOLS_ENABLED + return cached_data.godot_api_cache_updated; +#else + return true; // Assume it's updated if this was called, otherwise it's a bug +#endif +} + +} // namespace GDMonoCache + +#define CACHED_CLASS(m_class) (GDMonoCache::cached_data.class_##m_class) +#define CACHED_CLASS_RAW(m_class) (GDMonoCache::cached_data.class_##m_class->get_mono_ptr()) +#define CACHED_RAW_MONO_CLASS(m_class) (GDMonoCache::cached_data.rawclass_##m_class) +#define CACHED_FIELD(m_class, m_field) (GDMonoCache::cached_data.field_##m_class##_##m_field) +#define CACHED_METHOD(m_class, m_method) (GDMonoCache::cached_data.method_##m_class##_##m_method) +#define CACHED_METHOD_THUNK(m_class, m_method) (GDMonoCache::cached_data.methodthunk_##m_class##_##m_method) +#define CACHED_PROPERTY(m_class, m_property) (GDMonoCache::cached_data.property_##m_class##_##m_property) + +#ifdef REAL_T_IS_DOUBLE +#define REAL_T_MONOCLASS CACHED_CLASS_RAW(double) +#else +#define REAL_T_MONOCLASS CACHED_CLASS_RAW(float) +#endif + +#endif // GD_MONO_CACHE_H diff --git a/modules/mono/mono_gd/gd_mono_class.cpp b/modules/mono/mono_gd/gd_mono_class.cpp index 4342f46109..fb9b6be3d4 100644 --- a/modules/mono/mono_gd/gd_mono_class.cpp +++ b/modules/mono/mono_gd/gd_mono_class.cpp @@ -33,6 +33,7 @@ #include <mono/metadata/attrdefs.h> #include "gd_mono_assembly.h" +#include "gd_mono_cache.h" #include "gd_mono_marshal.h" String GDMonoClass::get_full_name(MonoClass *p_mono_class) { @@ -41,7 +42,7 @@ String GDMonoClass::get_full_name(MonoClass *p_mono_class) { MonoException *exc = NULL; MonoString *str = GDMonoUtils::object_to_string((MonoObject *)type_obj, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); + UNHANDLED_EXCEPTION(exc); return GDMonoMarshal::mono_string_to_godot(str); } @@ -74,16 +75,13 @@ bool GDMonoClass::is_assignable_from(GDMonoClass *p_from) const { } GDMonoClass *GDMonoClass::get_parent_class() { + MonoClass *parent_mono_class = mono_class_get_parent(mono_class); + return parent_mono_class ? GDMono::get_singleton()->get_class(parent_mono_class) : NULL; +} - if (assembly) { - MonoClass *parent_mono_class = mono_class_get_parent(mono_class); - - if (parent_mono_class) { - return GDMono::get_singleton()->get_class(parent_mono_class); - } - } - - return NULL; +GDMonoClass *GDMonoClass::get_nesting_class() { + MonoClass *nesting_type = mono_class_get_nesting_type(mono_class); + return nesting_type ? GDMono::get_singleton()->get_class(nesting_type) : NULL; } #ifdef TOOLS_ENABLED @@ -168,8 +166,8 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base #ifdef DEBUG_ENABLED String fullname = method->get_ret_type_full_name() + " " + name + "(" + method->get_signature_desc(true) + ")"; - WARN_PRINTS("Method `" + fullname + "` is hidden by Godot API method. Should be `" + - method->get_full_name_no_class() + "`. In class `" + namespace_name + "." + class_name + "`."); + WARN_PRINTS("Method '" + fullname + "' is hidden by Godot API method. Should be '" + + method->get_full_name_no_class() + "'. In class '" + namespace_name + "." + class_name + "'."); #endif continue; } @@ -187,8 +185,8 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base if (m && m->get_name() != name) { // found String fullname = m->get_ret_type_full_name() + " " + name + "(" + m->get_signature_desc(true) + ")"; - WARN_PRINTS("Method `" + fullname + "` should be `" + m->get_full_name_no_class() + - "`. In class `" + namespace_name + "." + class_name + "`."); + WARN_PRINTS("Method '" + fullname + "' should be '" + m->get_full_name_no_class() + + "'. In class '" + namespace_name + "." + class_name + "'."); break; } @@ -335,12 +333,6 @@ GDMonoMethod *GDMonoClass::get_method_with_desc(const String &p_description, boo return get_method(method); } -void *GDMonoClass::get_method_thunk(const StringName &p_name, int p_params_count) { - - GDMonoMethod *method = get_method(p_name, p_params_count); - return method ? method->get_thunk() : NULL; -} - GDMonoField *GDMonoClass::get_field(const StringName &p_name) { Map<StringName, GDMonoField *>::Element *result = fields.find(p_name); diff --git a/modules/mono/mono_gd/gd_mono_class.h b/modules/mono/mono_gd/gd_mono_class.h index 249422b844..562c337822 100644 --- a/modules/mono/mono_gd/gd_mono_class.h +++ b/modules/mono/mono_gd/gd_mono_class.h @@ -121,6 +121,7 @@ public: _FORCE_INLINE_ const GDMonoAssembly *get_assembly() const { return assembly; } GDMonoClass *get_parent_class(); + GDMonoClass *get_nesting_class(); #ifdef TOOLS_ENABLED Vector<MonoClassField *> get_enum_fields(); @@ -143,8 +144,6 @@ public: GDMonoMethod *get_method(MonoMethod *p_raw_method, const StringName &p_name, int p_params_count); GDMonoMethod *get_method_with_desc(const String &p_description, bool p_include_namespace); - void *get_method_thunk(const StringName &p_name, int p_params_count = 0); - GDMonoField *get_field(const StringName &p_name); const Vector<GDMonoField *> &get_all_fields(); diff --git a/modules/mono/mono_gd/gd_mono_field.cpp b/modules/mono/mono_gd/gd_mono_field.cpp index 9779797d1a..d84359b1ab 100644 --- a/modules/mono/mono_gd/gd_mono_field.cpp +++ b/modules/mono/mono_gd/gd_mono_field.cpp @@ -32,8 +32,10 @@ #include <mono/metadata/attrdefs.h> +#include "gd_mono_cache.h" #include "gd_mono_class.h" #include "gd_mono_marshal.h" +#include "gd_mono_utils.h" void GDMonoField::set_value_raw(MonoObject *p_object, void *p_ptr) { mono_field_set_value(p_object, mono_field, &p_ptr); @@ -219,16 +221,14 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ break; } default: { - ERR_EXPLAIN(String() + "Attempted to convert Variant to a managed enum value of unmarshallable base type."); - ERR_FAIL(); + ERR_FAIL_MSG("Attempted to convert Variant to a managed enum value of unmarshallable base type."); } } break; } - ERR_EXPLAIN(String() + "Attempted to set the value of a field of unmarshallable type: " + tclass->get_name()); - ERR_FAIL(); + ERR_FAIL_MSG("Attempted to set the value of a field of unmarshallable type: '" + tclass->get_name() + "'."); } break; case MONO_TYPE_ARRAY: @@ -275,8 +275,7 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ break; } - ERR_EXPLAIN(String() + "Attempted to convert Variant to a managed array of unmarshallable element type."); - ERR_FAIL(); + ERR_FAIL_MSG("Attempted to convert Variant to a managed array of unmarshallable element type."); } break; case MONO_TYPE_CLASS: { @@ -313,20 +312,45 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ break; } + // The order in which we check the following interfaces is very important (dictionaries and generics first) + + MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type_class->get_mono_type()); + + MonoReflectionType *key_reftype, *value_reftype; + if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype, &key_reftype, &value_reftype)) { + MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), + GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype)); + mono_field_set_value(p_object, mono_field, managed); + break; + } + if (type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) { MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), CACHED_CLASS(Dictionary)); mono_field_set_value(p_object, mono_field, managed); break; } - if (type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { - MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array)); + MonoReflectionType *elem_reftype; + if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype, &elem_reftype)) { + MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), + GDMonoUtils::Marshal::make_generic_array_type(elem_reftype)); mono_field_set_value(p_object, mono_field, managed); break; } - ERR_EXPLAIN(String() + "Attempted to set the value of a field of unmarshallable type: " + type_class->get_name()); - ERR_FAIL(); + if (type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { + if (GDMonoCache::tools_godot_api_check()) { + MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array)); + mono_field_set_value(p_object, mono_field, managed); + break; + } else { + MonoObject *managed = (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_value.operator Array()); + mono_field_set_value(p_object, mono_field, managed); + break; + } + } + + ERR_FAIL_MSG("Attempted to set the value of a field of unmarshallable type: '" + type_class->get_name() + "'."); } break; case MONO_TYPE_OBJECT: { @@ -430,28 +454,26 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ } break; case MONO_TYPE_GENERICINST: { - MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, type.type_class->get_mono_type()); - - MonoException *exc = NULL; + MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type.type_class->get_mono_type()); - GDMonoUtils::TypeIsGenericDictionary type_is_dict = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericDictionary); - MonoBoolean is_dict = invoke_method_thunk(type_is_dict, reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - - if (is_dict) { + if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) { MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), type.type_class); mono_field_set_value(p_object, mono_field, managed); break; } - exc = NULL; + if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) { + MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), type.type_class); + mono_field_set_value(p_object, mono_field, managed); + break; + } - GDMonoUtils::TypeIsGenericArray type_is_array = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericArray); - MonoBoolean is_array = invoke_method_thunk(type_is_array, reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); + // The order in which we check the following interfaces is very important (dictionaries and generics first) - if (is_array) { - MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), type.type_class); + MonoReflectionType *key_reftype, *value_reftype; + if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype, &key_reftype, &value_reftype)) { + MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), + GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype)); mono_field_set_value(p_object, mono_field, managed); break; } @@ -462,15 +484,29 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ break; } - if (type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { - MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array)); + MonoReflectionType *elem_reftype; + if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype, &elem_reftype)) { + MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), + GDMonoUtils::Marshal::make_generic_array_type(elem_reftype)); mono_field_set_value(p_object, mono_field, managed); break; } + + if (type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { + if (GDMonoCache::tools_godot_api_check()) { + MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array)); + mono_field_set_value(p_object, mono_field, managed); + break; + } else { + MonoObject *managed = (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_value.operator Array()); + mono_field_set_value(p_object, mono_field, managed); + break; + } + } } break; default: { - ERR_PRINTS(String() + "Attempted to set the value of a field of unexpected type encoding: " + itos(type.type_encoding)); + ERR_PRINTS("Attempted to set the value of a field of unexpected type encoding: " + itos(type.type_encoding) + "."); } break; } diff --git a/modules/mono/mono_gd/gd_mono_field.h b/modules/mono/mono_gd/gd_mono_field.h index e348583370..a7727ddf34 100644 --- a/modules/mono/mono_gd/gd_mono_field.h +++ b/modules/mono/mono_gd/gd_mono_field.h @@ -47,9 +47,11 @@ class GDMonoField : public IMonoClassMember { MonoCustomAttrInfo *attributes; public: - virtual MemberType get_member_type() GD_FINAL { return MEMBER_TYPE_FIELD; } + virtual GDMonoClass *get_enclosing_class() const GD_FINAL { return owner; } - virtual StringName get_name() GD_FINAL { return name; } + virtual MemberType get_member_type() const GD_FINAL { return MEMBER_TYPE_FIELD; } + + virtual StringName get_name() const GD_FINAL { return name; } virtual bool is_static() GD_FINAL; virtual Visibility get_visibility() GD_FINAL; diff --git a/modules/mono/mono_gd/gd_mono_header.h b/modules/mono/mono_gd/gd_mono_header.h index d7962eac8b..173e1613bf 100644 --- a/modules/mono/mono_gd/gd_mono_header.h +++ b/modules/mono/mono_gd/gd_mono_header.h @@ -33,6 +33,12 @@ #include "core/int_types.h" +#ifdef WIN32 +#define GD_MONO_STDCALL __stdcall +#else +#define GD_MONO_STDCALL +#endif + class GDMonoAssembly; class GDMonoClass; class GDMonoField; diff --git a/modules/mono/mono_gd/gd_mono_internals.cpp b/modules/mono/mono_gd/gd_mono_internals.cpp index c8cba5cf1b..3324ecb3a8 100644 --- a/modules/mono/mono_gd/gd_mono_internals.cpp +++ b/modules/mono/mono_gd/gd_mono_internals.cpp @@ -48,7 +48,7 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { CRASH_COND(!unmanaged); - // All mono objects created from the managed world (e.g.: `new Player()`) + // All mono objects created from the managed world (e.g.: 'new Player()') // need to have a CSharpScript in order for their methods to be callable from the unmanaged side Reference *ref = Object::cast_to<Reference>(unmanaged); @@ -74,15 +74,14 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { script_binding.type_name = NATIVE_GDMONOCLASS_NAME(klass); script_binding.wrapper_class = klass; script_binding.gchandle = MonoGCHandle::create_strong(managed); + script_binding.owner = unmanaged; - Reference *kref = Object::cast_to<Reference>(unmanaged); - if (kref) { + if (ref) { // Unsafe refcount increment. The managed instance also counts as a reference. // This way if the unmanaged world has no references to our owner // but the managed instance is alive, the refcount will be 1 instead of 0. // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr) - - kref->reference(); + ref->reference(); } // The object was just created, no script instance binding should have been attached @@ -105,14 +104,22 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { ScriptInstance *si = CSharpInstance::create_for_managed_type(unmanaged, script.ptr(), gchandle); unmanaged->set_script_and_instance(script.get_ref_ptr(), si); - - return; } void unhandled_exception(MonoException *p_exc) { mono_unhandled_exception((MonoObject *)p_exc); // prints the exception as well - abort(); - GD_UNREACHABLE(); + + if (GDMono::get_singleton()->get_unhandled_exception_policy() == GDMono::POLICY_TERMINATE_APP) { + // Too bad 'mono_invoke_unhandled_exception_hook' is not exposed to embedders + GDMono::unhandled_exception_hook((MonoObject *)p_exc, NULL); + GD_UNREACHABLE(); + } else { +#ifdef DEBUG_ENABLED + GDMonoUtils::debug_send_unhandled_exception_error((MonoException *)p_exc); + if (ScriptDebugger::get_singleton()) + ScriptDebugger::get_singleton()->idle_poll(); +#endif + } } } // namespace GDMonoInternals diff --git a/modules/mono/mono_gd/gd_mono_internals.h b/modules/mono/mono_gd/gd_mono_internals.h index 2d77bde27c..0d82723913 100644 --- a/modules/mono/mono_gd/gd_mono_internals.h +++ b/modules/mono/mono_gd/gd_mono_internals.h @@ -45,7 +45,7 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged); * Do not call this function directly. * Use GDMonoUtils::debug_unhandled_exception(MonoException *) instead. */ -GD_NORETURN void unhandled_exception(MonoException *p_exc); +void unhandled_exception(MonoException *p_exc); } // namespace GDMonoInternals diff --git a/modules/mono/mono_gd/gd_mono_log.cpp b/modules/mono/mono_gd/gd_mono_log.cpp index ec89df1959..261b800619 100644 --- a/modules/mono/mono_gd/gd_mono_log.cpp +++ b/modules/mono/mono_gd/gd_mono_log.cpp @@ -30,15 +30,27 @@ #include "gd_mono_log.h" -#include <mono/utils/mono-logger.h> #include <stdlib.h> // abort #include "core/os/dir_access.h" #include "core/os/os.h" #include "../godotsharp_dirs.h" +#include "../utils/string_utils.h" -static int log_level_get_id(const char *p_log_level) { +static CharString get_default_log_level() { +#ifdef DEBUG_ENABLED + return String("info").utf8(); +#else + return String("warning").utf8(); +#endif +} + +GDMonoLog *GDMonoLog::singleton = NULL; + +#if !defined(JAVASCRIPT_ENABLED) + +static int get_log_level_id(const char *p_log_level) { const char *valid_log_levels[] = { "error", "critical", "warning", "message", "info", "debug", NULL }; @@ -52,11 +64,11 @@ static int log_level_get_id(const char *p_log_level) { return -1; } -static void mono_log_callback(const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *user_data) { +void GDMonoLog::mono_log_callback(const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *) { - FileAccess *f = GDMonoLog::get_singleton()->get_log_file(); + FileAccess *f = GDMonoLog::get_singleton()->log_file; - if (GDMonoLog::get_singleton()->get_log_level_id() >= log_level_get_id(log_level)) { + if (GDMonoLog::get_singleton()->log_level_id >= get_log_level_id(log_level)) { String text(message); text += " (in domain "; text += log_domain; @@ -71,45 +83,37 @@ static void mono_log_callback(const char *log_domain, const char *log_level, con } if (fatal) { - ERR_PRINTS("Mono: FATAL ERROR, ABORTING! Logfile: " + GDMonoLog::get_singleton()->get_log_file_path() + "\n"); - // If we were to abort without flushing, the log wouldn't get written. + ERR_PRINTS("Mono: FATAL ERROR, ABORTING! Logfile: '" + GDMonoLog::get_singleton()->log_file_path + "'."); + // Make sure to flush before aborting f->flush(); + f->close(); + memdelete(f); + abort(); } } -GDMonoLog *GDMonoLog::singleton = NULL; - bool GDMonoLog::_try_create_logs_dir(const String &p_logs_dir) { if (!DirAccess::exists(p_logs_dir)) { DirAccessRef diraccess = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); ERR_FAIL_COND_V(!diraccess, false); Error logs_mkdir_err = diraccess->make_dir_recursive(p_logs_dir); - ERR_EXPLAIN("Failed to create mono logs directory"); - ERR_FAIL_COND_V(logs_mkdir_err != OK, false); + ERR_FAIL_COND_V_MSG(logs_mkdir_err != OK, false, "Failed to create mono logs directory."); } return true; } -void GDMonoLog::_open_log_file(const String &p_file_path) { - - log_file = FileAccess::open(p_file_path, FileAccess::WRITE); - - ERR_EXPLAIN("Failed to create log file"); - ERR_FAIL_COND(!log_file); -} - void GDMonoLog::_delete_old_log_files(const String &p_logs_dir) { - static const uint64_t MAX_SECS = 5 * 86400; + static const uint64_t MAX_SECS = 5 * 86400; // 5 days DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); ERR_FAIL_COND(!da); Error err = da->change_dir(p_logs_dir); - ERR_FAIL_COND(err != OK); + ERR_FAIL_COND_MSG(err != OK, "Cannot change directory to '" + p_logs_dir + "'."); ERR_FAIL_COND(da->list_dir_begin() != OK); @@ -120,10 +124,9 @@ void GDMonoLog::_delete_old_log_files(const String &p_logs_dir) { if (!current.ends_with(".txt")) continue; - String name = current.get_basename(); - uint64_t unixtime = (uint64_t)name.to_int64(); + uint64_t modified_time = FileAccess::get_modified_time(da->get_current_dir().plus_file(current)); - if (OS::get_singleton()->get_unix_time() - unixtime > MAX_SECS) { + if (OS::get_singleton()->get_unix_time() - modified_time > MAX_SECS) { da->remove(current); } } @@ -133,26 +136,46 @@ void GDMonoLog::_delete_old_log_files(const String &p_logs_dir) { void GDMonoLog::initialize() { -#ifdef DEBUG_ENABLED - const char *log_level = "debug"; -#else - const char *log_level = "warning"; -#endif + CharString log_level = OS::get_singleton()->get_environment("GODOT_MONO_LOG_LEVEL").utf8(); + + if (log_level.length() != 0 && get_log_level_id(log_level.get_data()) == -1) { + ERR_PRINTS(String() + "Mono: Ignoring invalid log level (GODOT_MONO_LOG_LEVEL): '" + log_level.get_data() + "'."); + log_level = CharString(); + } + + if (log_level.length() == 0) { + log_level = get_default_log_level(); + } String logs_dir = GodotSharpDirs::get_mono_logs_dir(); if (_try_create_logs_dir(logs_dir)) { _delete_old_log_files(logs_dir); - log_file_path = logs_dir.plus_file(String::num_int64(OS::get_singleton()->get_unix_time()) + ".txt"); - _open_log_file(log_file_path); + OS::Date date_now = OS::get_singleton()->get_date(); + OS::Time time_now = OS::get_singleton()->get_time(); + + String log_file_name = str_format("%d_%02d_%02d %02d.%02d.%02d", + date_now.year, date_now.month, date_now.day, + time_now.hour, time_now.min, time_now.sec); + + log_file_name += str_format(" (%d)", OS::get_singleton()->get_process_id()); + + log_file_name += ".txt"; + + log_file_path = logs_dir.plus_file(log_file_name); + + log_file = FileAccess::open(log_file_path, FileAccess::WRITE); + if (!log_file) { + ERR_PRINTS("Mono: Cannot create log file at: " + log_file_path); + } } - mono_trace_set_level_string(log_level); - log_level_id = log_level_get_id(log_level); + mono_trace_set_level_string(log_level.get_data()); + log_level_id = get_log_level_id(log_level.get_data()); if (log_file) { - print_verbose("Mono: Logfile is " + log_file_path); + OS::get_singleton()->print("Mono: Logfile is: %s\n", log_file_path.utf8().get_data()); mono_trace_set_log_handler(mono_log_callback, this); } else { OS::get_singleton()->printerr("Mono: No log file, using default log handler\n"); @@ -175,3 +198,22 @@ GDMonoLog::~GDMonoLog() { memdelete(log_file); } } + +#else + +void GDMonoLog::initialize() { + CharString log_level = get_default_log_level(); + mono_trace_set_level_string(log_level.get_data()); +} + +GDMonoLog::GDMonoLog() { + + singleton = this; +} + +GDMonoLog::~GDMonoLog() { + + singleton = NULL; +} + +#endif // !defined(JAVASCRIPT_ENABLED) diff --git a/modules/mono/mono_gd/gd_mono_log.h b/modules/mono/mono_gd/gd_mono_log.h index a477e5edee..4cd5a662fb 100644 --- a/modules/mono/mono_gd/gd_mono_log.h +++ b/modules/mono/mono_gd/gd_mono_log.h @@ -31,19 +31,28 @@ #ifndef GD_MONO_LOG_H #define GD_MONO_LOG_H +#include <mono/utils/mono-logger.h> + +#include "core/typedefs.h" + +#if !defined(JAVASCRIPT_ENABLED) #include "core/os/file_access.h" +#endif class GDMonoLog { +#if !defined(JAVASCRIPT_ENABLED) int log_level_id; FileAccess *log_file; String log_file_path; bool _try_create_logs_dir(const String &p_logs_dir); - void _open_log_file(const String &p_file_path); void _delete_old_log_files(const String &p_logs_dir); + static void mono_log_callback(const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *user_data); +#endif + static GDMonoLog *singleton; public: @@ -51,10 +60,6 @@ public: void initialize(); - _FORCE_INLINE_ FileAccess *get_log_file() { return log_file; } - _FORCE_INLINE_ String get_log_file_path() { return log_file_path; } - _FORCE_INLINE_ int get_log_level_id() { return log_level_id; } - GDMonoLog(); ~GDMonoLog(); }; diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp index de4f3650bd..f74fe5715c 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.cpp +++ b/modules/mono/mono_gd/gd_mono_marshal.cpp @@ -31,11 +31,12 @@ #include "gd_mono_marshal.h" #include "gd_mono.h" +#include "gd_mono_cache.h" #include "gd_mono_class.h" namespace GDMonoMarshal { -Variant::Type managed_to_variant_type(const ManagedType &p_type, ExportInfo *r_export_info) { +Variant::Type managed_to_variant_type(const ManagedType &p_type) { switch (p_type.type_encoding) { case MONO_TYPE_BOOLEAN: return Variant::BOOL; @@ -157,64 +158,50 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type, ExportInfo *r_e return Variant::ARRAY; } + // The order in which we check the following interfaces is very important (dictionaries and generics first) + + MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type_class->get_mono_type()); + + if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype)) { + return Variant::DICTIONARY; + } + if (type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) { return Variant::DICTIONARY; } + if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype)) { + return Variant::ARRAY; + } + if (type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { return Variant::ARRAY; } } break; case MONO_TYPE_GENERICINST: { - MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, p_type.type_class->get_mono_type()); - - MonoException *exc = NULL; - GDMonoUtils::TypeIsGenericDictionary type_is_dict = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericDictionary); - MonoBoolean is_dict = invoke_method_thunk(type_is_dict, reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - - if (is_dict) { - if (r_export_info) { - MonoReflectionType *key_reftype; - MonoReflectionType *value_reftype; - - exc = NULL; - invoke_method_thunk(CACHED_METHOD_THUNK(MarshalUtils, DictionaryGetKeyValueTypes), - reftype, &key_reftype, &value_reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - - r_export_info->dictionary.key_type = managed_to_variant_type(ManagedType::from_reftype(key_reftype)); - r_export_info->dictionary.value_type = managed_to_variant_type(ManagedType::from_reftype(value_reftype)); - } + MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type()); + if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) { return Variant::DICTIONARY; } - exc = NULL; - GDMonoUtils::TypeIsGenericArray type_is_array = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericArray); - MonoBoolean is_array = invoke_method_thunk(type_is_array, reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - - if (is_array) { - if (r_export_info) { - MonoReflectionType *elem_reftype; - - exc = NULL; - invoke_method_thunk(CACHED_METHOD_THUNK(MarshalUtils, ArrayGetElementType), - reftype, &elem_reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - - r_export_info->array.element_type = managed_to_variant_type(ManagedType::from_reftype(elem_reftype)); - } - + if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) { return Variant::ARRAY; } + // The order in which we check the following interfaces is very important (dictionaries and generics first) + + if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype)) + return Variant::DICTIONARY; + if (p_type.type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) { return Variant::DICTIONARY; } + if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype)) + return Variant::ARRAY; + if (p_type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { return Variant::ARRAY; } @@ -228,12 +215,69 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type, ExportInfo *r_e return Variant::NIL; } +bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_elem_type) { + switch (p_array_type.type_encoding) { + case MONO_TYPE_GENERICINST: { + MonoReflectionType *array_reftype = mono_type_get_object(mono_domain_get(), p_array_type.type_class->get_mono_type()); + + if (GDMonoUtils::Marshal::type_is_generic_array(array_reftype)) { + MonoReflectionType *elem_reftype; + + GDMonoUtils::Marshal::array_get_element_type(array_reftype, &elem_reftype); + + r_elem_type = ManagedType::from_reftype(elem_reftype); + return true; + } + + MonoReflectionType *elem_reftype; + if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(array_reftype, &elem_reftype)) { + r_elem_type = ManagedType::from_reftype(elem_reftype); + return true; + } + } break; + default: { + } break; + } + + return false; +} + +bool try_get_dictionary_key_value_types(const ManagedType &p_dictionary_type, ManagedType &r_key_type, ManagedType &r_value_type) { + switch (p_dictionary_type.type_encoding) { + case MONO_TYPE_GENERICINST: { + MonoReflectionType *dict_reftype = mono_type_get_object(mono_domain_get(), p_dictionary_type.type_class->get_mono_type()); + + if (GDMonoUtils::Marshal::type_is_generic_dictionary(dict_reftype)) { + MonoReflectionType *key_reftype; + MonoReflectionType *value_reftype; + + GDMonoUtils::Marshal::dictionary_get_key_value_types(dict_reftype, &key_reftype, &value_reftype); + + r_key_type = ManagedType::from_reftype(key_reftype); + r_value_type = ManagedType::from_reftype(value_reftype); + return true; + } + + MonoReflectionType *key_reftype, *value_reftype; + if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(dict_reftype, &key_reftype, &value_reftype)) { + r_key_type = ManagedType::from_reftype(key_reftype); + r_value_type = ManagedType::from_reftype(value_reftype); + return true; + } + } break; + default: { + } break; + } + + return false; +} + String mono_to_utf8_string(MonoString *p_mono_string) { MonoError error; char *utf8 = mono_string_to_utf8_checked(p_mono_string, &error); if (!mono_error_ok(&error)) { - ERR_PRINTS(String("Failed to convert MonoString* to UTF-8: ") + mono_error_get_message(&error)); + ERR_PRINTS(String() + "Failed to convert MonoString* to UTF-8: '" + mono_error_get_message(&error) + "'."); mono_error_cleanup(&error); return String(); } @@ -431,8 +475,7 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty return BOX_ENUM(enum_baseclass, val); } default: { - ERR_EXPLAIN(String() + "Attempted to convert Variant to a managed enum value of unmarshallable base type."); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Attempted to convert Variant to a managed enum value of unmarshallable base type."); } } } @@ -466,8 +509,7 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty if (array_type->eklass == CACHED_CLASS_RAW(Color)) return (MonoObject *)PoolColorArray_to_mono_array(p_var->operator PoolColorArray()); - ERR_EXPLAIN(String() + "Attempted to convert Variant to a managed array of unmarshallable element type."); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Attempted to convert Variant to a managed array of unmarshallable element type."); } break; case MONO_TYPE_CLASS: { @@ -494,12 +536,32 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array)); } + // The order in which we check the following interfaces is very important (dictionaries and generics first) + + MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type_class->get_mono_type()); + + MonoReflectionType *key_reftype, *value_reftype; + if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype, &key_reftype, &value_reftype)) { + return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), + GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype)); + } + if (type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) { return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), CACHED_CLASS(Dictionary)); } + MonoReflectionType *elem_reftype; + if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype, &elem_reftype)) { + return GDMonoUtils::create_managed_from(p_var->operator Array(), + GDMonoUtils::Marshal::make_generic_array_type(elem_reftype)); + } + if (type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { - return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array)); + if (GDMonoCache::tools_godot_api_check()) { + return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array)); + } else { + return (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_var->operator Array()); + } } } break; case MONO_TYPE_OBJECT: { @@ -593,40 +655,47 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty } break; case MONO_TYPE_GENERICINST: { - MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, p_type.type_class->get_mono_type()); - - MonoException *exc = NULL; - GDMonoUtils::TypeIsGenericDictionary type_is_dict = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericDictionary); - MonoBoolean is_dict = invoke_method_thunk(type_is_dict, reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); + MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type()); - if (is_dict) { + if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) { return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), p_type.type_class); } - exc = NULL; - GDMonoUtils::TypeIsGenericArray type_is_array = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericArray); - MonoBoolean is_array = invoke_method_thunk(type_is_array, reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - - if (is_array) { + if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) { return GDMonoUtils::create_managed_from(p_var->operator Array(), p_type.type_class); } + // The order in which we check the following interfaces is very important (dictionaries and generics first) + + MonoReflectionType *key_reftype, *value_reftype; + if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype, &key_reftype, &value_reftype)) { + return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), + GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype)); + } + if (p_type.type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) { return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), CACHED_CLASS(Dictionary)); } + MonoReflectionType *elem_reftype; + if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype, &elem_reftype)) { + return GDMonoUtils::create_managed_from(p_var->operator Array(), + GDMonoUtils::Marshal::make_generic_array_type(elem_reftype)); + } + if (p_type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { - return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array)); + if (GDMonoCache::tools_godot_api_check()) { + return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array)); + } else { + return (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_var->operator Array()); + } } } break; } break; } - ERR_EXPLAIN(String() + "Attempted to convert Variant to an unmarshallable managed type. Name: \'" + - p_type.type_class->get_name() + "\' Encoding: " + itos(p_type.type_encoding)); - ERR_FAIL_V(NULL); + ERR_FAIL_V_MSG(NULL, "Attempted to convert Variant to an unmarshallable managed type. Name: '" + + p_type.type_class->get_name() + "' Encoding: " + itos(p_type.type_encoding) + "."); } Variant mono_object_to_variant(MonoObject *p_obj) { @@ -738,8 +807,7 @@ Variant mono_object_to_variant(MonoObject *p_obj) { if (array_type->eklass == CACHED_CLASS_RAW(Color)) return mono_array_to_PoolColorArray((MonoArray *)p_obj); - ERR_EXPLAIN(String() + "Attempted to convert a managed array of unmarshallable element type to Variant."); - ERR_FAIL_V(Variant()); + ERR_FAIL_V_MSG(Variant(), "Attempted to convert a managed array of unmarshallable element type to Variant."); } break; case MONO_TYPE_CLASS: { @@ -767,85 +835,78 @@ Variant mono_object_to_variant(MonoObject *p_obj) { if (CACHED_CLASS(Array) == type_class) { MonoException *exc = NULL; - Array *ptr = invoke_method_thunk(CACHED_METHOD_THUNK(Array, GetPtr), p_obj, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); + Array *ptr = CACHED_METHOD_THUNK(Array, GetPtr).invoke(p_obj, &exc); + UNHANDLED_EXCEPTION(exc); return ptr ? Variant(*ptr) : Variant(); } if (CACHED_CLASS(Dictionary) == type_class) { MonoException *exc = NULL; - Dictionary *ptr = invoke_method_thunk(CACHED_METHOD_THUNK(Dictionary, GetPtr), p_obj, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); + Dictionary *ptr = CACHED_METHOD_THUNK(Dictionary, GetPtr).invoke(p_obj, &exc); + UNHANDLED_EXCEPTION(exc); return ptr ? Variant(*ptr) : Variant(); } + // The order in which we check the following interfaces is very important (dictionaries and generics first) + + MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type_class->get_mono_type()); + + if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype)) { + return GDMonoUtils::Marshal::generic_idictionary_to_dictionary(p_obj); + } + if (type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) { - Dictionary dict; - MonoException *exc = NULL; - invoke_method_thunk(CACHED_METHOD_THUNK(MarshalUtils, IDictionaryToDictionary), p_obj, &dict, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - return dict; + return GDMonoUtils::Marshal::idictionary_to_dictionary(p_obj); + } + + if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype)) { + return GDMonoUtils::Marshal::enumerable_to_array(p_obj); } if (type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { - Array array; - MonoException *exc = NULL; - invoke_method_thunk(CACHED_METHOD_THUNK(MarshalUtils, EnumerableToArray), p_obj, &array, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - return array; + return GDMonoUtils::Marshal::enumerable_to_array(p_obj); } } break; case MONO_TYPE_GENERICINST: { - MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, type.type_class->get_mono_type()); + MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type.type_class->get_mono_type()); - MonoException *exc = NULL; - - GDMonoUtils::TypeIsGenericDictionary type_is_dict = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericDictionary); - MonoBoolean is_dict = invoke_method_thunk(type_is_dict, reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - - if (is_dict) { - exc = NULL; + if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) { + MonoException *exc = NULL; MonoObject *ret = type.type_class->get_method("GetPtr")->invoke(p_obj, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); + UNHANDLED_EXCEPTION(exc); return *unbox<Dictionary *>(ret); } - exc = NULL; - - GDMonoUtils::TypeIsGenericArray type_is_array = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericArray); - MonoBoolean is_array = invoke_method_thunk(type_is_array, reftype, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - - if (is_array) { - exc = NULL; + if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) { + MonoException *exc = NULL; MonoObject *ret = type.type_class->get_method("GetPtr")->invoke(p_obj, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); + UNHANDLED_EXCEPTION(exc); return *unbox<Array *>(ret); } + // The order in which we check the following interfaces is very important (dictionaries and generics first) + + if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype)) { + return GDMonoUtils::Marshal::generic_idictionary_to_dictionary(p_obj); + } + if (type.type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) { - Dictionary dict; - exc = NULL; - invoke_method_thunk(CACHED_METHOD_THUNK(MarshalUtils, IDictionaryToDictionary), p_obj, &dict, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - return dict; + return GDMonoUtils::Marshal::idictionary_to_dictionary(p_obj); + } + + if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype)) { + return GDMonoUtils::Marshal::enumerable_to_array(p_obj); } if (type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { - Array array; - exc = NULL; - invoke_method_thunk(CACHED_METHOD_THUNK(MarshalUtils, EnumerableToArray), p_obj, &array, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); - return array; + return GDMonoUtils::Marshal::enumerable_to_array(p_obj); } } break; } - ERR_EXPLAIN(String() + "Attempted to convert an unmarshallable managed type to Variant. Name: \'" + - type.type_class->get_name() + "\' Encoding: " + itos(type.type_encoding)); - ERR_FAIL_V(Variant()); + ERR_FAIL_V_MSG(Variant(), "Attempted to convert an unmarshallable managed type to Variant. Name: '" + + type.type_class->get_name() + "' Encoding: " + itos(type.type_encoding) + "."); } MonoArray *Array_to_mono_array(const Array &p_array) { @@ -874,6 +935,8 @@ Array mono_array_to_Array(MonoArray *p_array) { return ret; } +// TODO: Use memcpy where possible + MonoArray *PoolIntArray_to_mono_array(const PoolIntArray &p_array) { PoolIntArray::Read r = p_array.read(); @@ -962,7 +1025,7 @@ MonoArray *PoolStringArray_to_mono_array(const PoolStringArray &p_array) { for (int i = 0; i < p_array.size(); i++) { MonoString *boxed = mono_string_from_godot(r[i]); - mono_array_set(ret, MonoString *, i, boxed); + mono_array_setref(ret, i, boxed); } return ret; @@ -1067,4 +1130,5 @@ PoolVector3Array mono_array_to_PoolVector3Array(MonoArray *p_array) { return ret; } + } // namespace GDMonoMarshal diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h index 4a73f9e3e6..53eae45320 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.h +++ b/modules/mono/mono_gd/gd_mono_marshal.h @@ -43,6 +43,11 @@ T unbox(MonoObject *p_obj) { return *(T *)mono_object_unbox(p_obj); } +template <typename T> +T *unbox_addr(MonoObject *p_obj) { + return (T *)mono_object_unbox(p_obj); +} + #define BOX_DOUBLE(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(double), &x) #define BOX_FLOAT(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(float), &x) #define BOX_INT64(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(int64_t), &x) @@ -57,25 +62,10 @@ T unbox(MonoObject *p_obj) { #define BOX_PTR(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(IntPtr), x) #define BOX_ENUM(m_enum_class, x) mono_value_box(mono_domain_get(), m_enum_class, &x) -// FIXME: Made this struct in a hurry. It could be done differently. -struct ExportInfo { - struct ArrayInfo { - Variant::Type element_type; - - ArrayInfo() : - element_type(Variant::NIL) {} - } array; - struct DictionaryInfo { - Variant::Type key_type; - Variant::Type value_type; - - DictionaryInfo() : - key_type(Variant::NIL), - value_type(Variant::NIL) {} - } dictionary; -}; +Variant::Type managed_to_variant_type(const ManagedType &p_type); -Variant::Type managed_to_variant_type(const ManagedType &p_type, ExportInfo *r_export_info = NULL); +bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_elem_type); +bool try_get_dictionary_key_value_types(const ManagedType &p_dictionary_type, ManagedType &r_key_type, ManagedType &r_value_type); // String diff --git a/modules/mono/mono_gd/gd_mono_method.cpp b/modules/mono/mono_gd/gd_mono_method.cpp index 7f11e4671d..080b3a676a 100644 --- a/modules/mono/mono_gd/gd_mono_method.cpp +++ b/modules/mono/mono_gd/gd_mono_method.cpp @@ -30,8 +30,10 @@ #include "gd_mono_method.h" +#include "gd_mono_cache.h" #include "gd_mono_class.h" #include "gd_mono_marshal.h" +#include "gd_mono_utils.h" #include <mono/metadata/attrdefs.h> @@ -74,6 +76,10 @@ void GDMonoMethod::_update_signature(MonoMethodSignature *p_method_sig) { method_info = MethodInfo(); } +GDMonoClass *GDMonoMethod::get_enclosing_class() const { + return GDMono::get_singleton()->get_class(mono_method_get_class(mono_method)); +} + bool GDMonoMethod::is_static() { return mono_method_get_flags(mono_method, NULL) & MONO_METHOD_ATTR_STATIC; } @@ -95,17 +101,13 @@ IMonoClassMember::Visibility GDMonoMethod::get_visibility() { } } -void *GDMonoMethod::get_thunk() { - return mono_method_get_unmanaged_thunk(mono_method); -} - MonoObject *GDMonoMethod::invoke(MonoObject *p_object, const Variant **p_params, MonoException **r_exc) { if (get_return_type().type_encoding != MONO_TYPE_VOID || get_parameters_count() > 0) { MonoArray *params = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), get_parameters_count()); for (int i = 0; i < params_count; i++) { MonoObject *boxed_param = GDMonoMarshal::variant_to_mono_object(p_params[i], param_types[i]); - mono_array_set(params, MonoObject *, i, boxed_param); + mono_array_setref(params, i, boxed_param); } MonoException *exc = NULL; diff --git a/modules/mono/mono_gd/gd_mono_method.h b/modules/mono/mono_gd/gd_mono_method.h index f74cef438d..abbae92e29 100644 --- a/modules/mono/mono_gd/gd_mono_method.h +++ b/modules/mono/mono_gd/gd_mono_method.h @@ -57,9 +57,11 @@ class GDMonoMethod : public IMonoClassMember { MonoMethod *mono_method; public: - virtual MemberType get_member_type() GD_FINAL { return MEMBER_TYPE_METHOD; } + virtual GDMonoClass *get_enclosing_class() const GD_FINAL; - virtual StringName get_name() GD_FINAL { return name; } + virtual MemberType get_member_type() const GD_FINAL { return MEMBER_TYPE_METHOD; } + + virtual StringName get_name() const GD_FINAL { return name; } virtual bool is_static() GD_FINAL; @@ -69,11 +71,11 @@ public: virtual MonoObject *get_attribute(GDMonoClass *p_attr_class) GD_FINAL; void fetch_attributes(); + _FORCE_INLINE_ MonoMethod *get_mono_ptr() { return mono_method; } + _FORCE_INLINE_ int get_parameters_count() { return params_count; } _FORCE_INLINE_ ManagedType get_return_type() { return return_type; } - void *get_thunk(); - MonoObject *invoke(MonoObject *p_object, const Variant **p_params, MonoException **r_exc = NULL); MonoObject *invoke(MonoObject *p_object, MonoException **r_exc = NULL); MonoObject *invoke_raw(MonoObject *p_object, void **p_params, MonoException **r_exc = NULL); diff --git a/modules/mono/mono_gd/gd_mono_method_thunk.h b/modules/mono/mono_gd/gd_mono_method_thunk.h new file mode 100644 index 0000000000..f8cc736ec3 --- /dev/null +++ b/modules/mono/mono_gd/gd_mono_method_thunk.h @@ -0,0 +1,332 @@ +/*************************************************************************/ +/* gd_mono_method_thunk.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 GD_MONO_METHOD_THUNK_H +#define GD_MONO_METHOD_THUNK_H + +#include <type_traits> + +#include "gd_mono_class.h" +#include "gd_mono_header.h" +#include "gd_mono_marshal.h" +#include "gd_mono_method.h" +#include "gd_mono_utils.h" + +#if !defined(JAVASCRIPT_ENABLED) +#define HAVE_METHOD_THUNKS +#endif + +#ifdef HAVE_METHOD_THUNKS + +template <class... ParamTypes> +struct GDMonoMethodThunk { + + typedef void(GD_MONO_STDCALL *M)(ParamTypes... p_args, MonoException **); + + M mono_method_thunk; + +public: + _FORCE_INLINE_ void invoke(ParamTypes... p_args, MonoException **r_exc) { + GD_MONO_BEGIN_RUNTIME_INVOKE; + mono_method_thunk(p_args..., r_exc); + GD_MONO_END_RUNTIME_INVOKE; + } + + _FORCE_INLINE_ bool is_null() { + return mono_method_thunk == NULL; + } + + _FORCE_INLINE_ void nullify() { + mono_method_thunk = NULL; + } + + _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) { +#ifdef DEBUG_ENABLED + CRASH_COND(p_mono_method == NULL); + CRASH_COND(p_mono_method->get_return_type().type_encoding != MONO_TYPE_VOID); + + if (p_mono_method->is_static()) { + CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes)); + } else { + CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1)); + } +#endif + mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr()); + } + + GDMonoMethodThunk() : + mono_method_thunk(NULL) { + } + + explicit GDMonoMethodThunk(GDMonoMethod *p_mono_method) { + set_from_method(p_mono_method); + } +}; + +template <class R, class... ParamTypes> +struct GDMonoMethodThunkR { + + typedef R(GD_MONO_STDCALL *M)(ParamTypes... p_args, MonoException **); + + M mono_method_thunk; + +public: + _FORCE_INLINE_ R invoke(ParamTypes... p_args, MonoException **r_exc) { + GD_MONO_BEGIN_RUNTIME_INVOKE; + R r = mono_method_thunk(p_args..., r_exc); + GD_MONO_END_RUNTIME_INVOKE; + return r; + } + + _FORCE_INLINE_ bool is_null() { + return mono_method_thunk == NULL; + } + + _FORCE_INLINE_ void nullify() { + mono_method_thunk = NULL; + } + + _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) { +#ifdef DEBUG_ENABLED + CRASH_COND(p_mono_method == NULL); + CRASH_COND(p_mono_method->get_return_type().type_encoding == MONO_TYPE_VOID); + + if (p_mono_method->is_static()) { + CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes)); + } else { + CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1)); + } +#endif + mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr()); + } + + GDMonoMethodThunkR() : + mono_method_thunk(NULL) { + } + + explicit GDMonoMethodThunkR(GDMonoMethod *p_mono_method) { +#ifdef DEBUG_ENABLED + CRASH_COND(p_mono_method == NULL); +#endif + mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr()); + } +}; + +#else + +template <unsigned int ThunkParamCount, class P1, class... ParamTypes> +struct VariadicInvokeMonoMethodImpl { + static void invoke(GDMonoMethod *p_mono_method, P1 p_arg1, ParamTypes... p_args, MonoException **r_exc) { + if (p_mono_method->is_static()) { + void *args[ThunkParamCount] = { p_arg1, p_args... }; + p_mono_method->invoke_raw(NULL, args, r_exc); + } else { + void *args[ThunkParamCount] = { p_args... }; + p_mono_method->invoke_raw((MonoObject *)p_arg1, args, r_exc); + } + } +}; + +template <unsigned int ThunkParamCount, class... ParamTypes> +struct VariadicInvokeMonoMethod { + static void invoke(GDMonoMethod *p_mono_method, ParamTypes... p_args, MonoException **r_exc) { + VariadicInvokeMonoMethodImpl<ThunkParamCount, ParamTypes...>::invoke(p_mono_method, p_args..., r_exc); + } +}; + +template <> +struct VariadicInvokeMonoMethod<0> { + static void invoke(GDMonoMethod *p_mono_method, MonoException **r_exc) { +#ifdef DEBUG_ENABLED + CRASH_COND(!p_mono_method->is_static()); +#endif + p_mono_method->invoke_raw(NULL, NULL, r_exc); + } +}; + +template <class P1> +struct VariadicInvokeMonoMethod<1, P1> { + static void invoke(GDMonoMethod *p_mono_method, P1 p_arg1, MonoException **r_exc) { + if (p_mono_method->is_static()) { + void *args[1] = { p_arg1 }; + p_mono_method->invoke_raw(NULL, args, r_exc); + } else { + p_mono_method->invoke_raw((MonoObject *)p_arg1, NULL, r_exc); + } + } +}; + +template <class R> +R unbox_if_needed(MonoObject *p_val, const ManagedType &, typename std::enable_if<!std::is_pointer<R>::value>::type * = 0) { + return GDMonoMarshal::unbox<R>(p_val); +} + +template <class R> +R unbox_if_needed(MonoObject *p_val, const ManagedType &p_type, typename std::enable_if<std::is_pointer<R>::value>::type * = 0) { + if (mono_class_is_valuetype(p_type.type_class->get_mono_ptr())) { + return GDMonoMarshal::unbox<R>(p_val); + } else { + // If it's not a value type, we assume 'R' is a pointer to 'MonoObject' or a compatible type, like 'MonoException'. + return (R)p_val; + } +} + +template <unsigned int ThunkParamCount, class R, class P1, class... ParamTypes> +struct VariadicInvokeMonoMethodRImpl { + static R invoke(GDMonoMethod *p_mono_method, P1 p_arg1, ParamTypes... p_args, MonoException **r_exc) { + if (p_mono_method->is_static()) { + void *args[ThunkParamCount] = { p_arg1, p_args... }; + MonoObject *r = p_mono_method->invoke_raw(NULL, args, r_exc); + return unbox_if_needed<R>(r, p_mono_method->get_return_type()); + } else { + void *args[ThunkParamCount] = { p_args... }; + MonoObject *r = p_mono_method->invoke_raw((MonoObject *)p_arg1, args, r_exc); + return unbox_if_needed<R>(r, p_mono_method->get_return_type()); + } + } +}; + +template <unsigned int ThunkParamCount, class R, class... ParamTypes> +struct VariadicInvokeMonoMethodR { + static R invoke(GDMonoMethod *p_mono_method, ParamTypes... p_args, MonoException **r_exc) { + return VariadicInvokeMonoMethodRImpl<ThunkParamCount, R, ParamTypes...>::invoke(p_mono_method, p_args..., r_exc); + } +}; + +template <class R> +struct VariadicInvokeMonoMethodR<0, R> { + static R invoke(GDMonoMethod *p_mono_method, MonoException **r_exc) { +#ifdef DEBUG_ENABLED + CRASH_COND(!p_mono_method->is_static()); +#endif + MonoObject *r = p_mono_method->invoke_raw(NULL, NULL, r_exc); + return unbox_if_needed<R>(r, p_mono_method->get_return_type()); + } +}; + +template <class R, class P1> +struct VariadicInvokeMonoMethodR<1, R, P1> { + static R invoke(GDMonoMethod *p_mono_method, P1 p_arg1, MonoException **r_exc) { + if (p_mono_method->is_static()) { + void *args[1] = { p_arg1 }; + MonoObject *r = p_mono_method->invoke_raw(NULL, args, r_exc); + return unbox_if_needed<R>(r, p_mono_method->get_return_type()); + } else { + MonoObject *r = p_mono_method->invoke_raw((MonoObject *)p_arg1, NULL, r_exc); + return unbox_if_needed<R>(r, p_mono_method->get_return_type()); + } + } +}; + +template <class... ParamTypes> +struct GDMonoMethodThunk { + + GDMonoMethod *mono_method; + +public: + _FORCE_INLINE_ void invoke(ParamTypes... p_args, MonoException **r_exc) { + VariadicInvokeMonoMethod<sizeof...(ParamTypes), ParamTypes...>::invoke(mono_method, p_args..., r_exc); + } + + _FORCE_INLINE_ bool is_null() { + return mono_method == NULL; + } + + _FORCE_INLINE_ void nullify() { + mono_method = NULL; + } + + _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) { +#ifdef DEBUG_ENABLED + CRASH_COND(p_mono_method == NULL); + CRASH_COND(p_mono_method->get_return_type().type_encoding != MONO_TYPE_VOID); + + if (p_mono_method->is_static()) { + CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes)); + } else { + CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1)); + } +#endif + mono_method = p_mono_method; + } + + GDMonoMethodThunk() : + mono_method(NULL) { + } + + explicit GDMonoMethodThunk(GDMonoMethod *p_mono_method) { + set_from_method(p_mono_method); + } +}; + +template <class R, class... ParamTypes> +struct GDMonoMethodThunkR { + + GDMonoMethod *mono_method; + +public: + _FORCE_INLINE_ R invoke(ParamTypes... p_args, MonoException **r_exc) { + return VariadicInvokeMonoMethodR<sizeof...(ParamTypes), R, ParamTypes...>::invoke(mono_method, p_args..., r_exc); + } + + _FORCE_INLINE_ bool is_null() { + return mono_method == NULL; + } + + _FORCE_INLINE_ void nullify() { + mono_method = NULL; + } + + _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) { +#ifdef DEBUG_ENABLED + CRASH_COND(p_mono_method == NULL); + CRASH_COND(p_mono_method->get_return_type().type_encoding == MONO_TYPE_VOID); + + if (p_mono_method->is_static()) { + CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes)); + } else { + CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1)); + } +#endif + mono_method = p_mono_method; + } + + GDMonoMethodThunkR() : + mono_method(NULL) { + } + + explicit GDMonoMethodThunkR(GDMonoMethod *p_mono_method) { + set_from_method(p_mono_method); + } +}; + +#endif + +#endif // GD_MONO_METHOD_THUNK_H diff --git a/modules/mono/mono_gd/gd_mono_property.cpp b/modules/mono/mono_gd/gd_mono_property.cpp index 5842e26241..277fe10087 100644 --- a/modules/mono/mono_gd/gd_mono_property.cpp +++ b/modules/mono/mono_gd/gd_mono_property.cpp @@ -30,8 +30,10 @@ #include "gd_mono_property.h" +#include "gd_mono_cache.h" #include "gd_mono_class.h" #include "gd_mono_marshal.h" +#include "gd_mono_utils.h" #include <mono/metadata/attrdefs.h> @@ -142,7 +144,7 @@ bool GDMonoProperty::has_setter() { void GDMonoProperty::set_value(MonoObject *p_object, MonoObject *p_value, MonoException **r_exc) { MonoMethod *prop_method = mono_property_get_set_method(mono_property); MonoArray *params = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), 1); - mono_array_set(params, MonoObject *, 0, p_value); + mono_array_setref(params, 0, p_value); MonoException *exc = NULL; GDMonoUtils::runtime_invoke_array(prop_method, p_object, params, &exc); if (exc) { diff --git a/modules/mono/mono_gd/gd_mono_property.h b/modules/mono/mono_gd/gd_mono_property.h index 2700c460b0..d6efa60412 100644 --- a/modules/mono/mono_gd/gd_mono_property.h +++ b/modules/mono/mono_gd/gd_mono_property.h @@ -47,9 +47,11 @@ class GDMonoProperty : public IMonoClassMember { MonoCustomAttrInfo *attributes; public: - virtual MemberType get_member_type() GD_FINAL { return MEMBER_TYPE_PROPERTY; } + virtual GDMonoClass *get_enclosing_class() const GD_FINAL { return owner; } - virtual StringName get_name() GD_FINAL { return name; } + virtual MemberType get_member_type() const GD_FINAL { return MEMBER_TYPE_PROPERTY; } + + virtual StringName get_name() const GD_FINAL { return name; } virtual bool is_static() GD_FINAL; virtual Visibility get_visibility() GD_FINAL; diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp index 429d4f68d9..8d7aaa97f2 100644 --- a/modules/mono/mono_gd/gd_mono_utils.cpp +++ b/modules/mono/mono_gd/gd_mono_utils.cpp @@ -37,251 +37,21 @@ #include "core/project_settings.h" #include "core/reference.h" +#ifdef TOOLS_ENABLED +#include "editor/script_editor_debugger.h" +#endif + #include "../csharp_script.h" #include "../utils/macros.h" #include "../utils/mutex_utils.h" #include "gd_mono.h" +#include "gd_mono_cache.h" #include "gd_mono_class.h" #include "gd_mono_marshal.h" +#include "gd_mono_method_thunk.h" namespace GDMonoUtils { -MonoCache mono_cache; - -#define CACHE_AND_CHECK(m_var, m_val) \ - { \ - m_var = m_val; \ - if (!m_var) { \ - ERR_EXPLAIN("Mono Cache: Member " #m_var " is null"); \ - ERR_FAIL(); \ - } \ - } - -#define CACHE_CLASS_AND_CHECK(m_class, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.class_##m_class, m_val) -#define CACHE_NS_CLASS_AND_CHECK(m_ns, m_class, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.class_##m_ns##_##m_class, m_val) -#define CACHE_RAW_MONO_CLASS_AND_CHECK(m_class, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.rawclass_##m_class, m_val) -#define CACHE_FIELD_AND_CHECK(m_class, m_field, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.field_##m_class##_##m_field, m_val) -#define CACHE_METHOD_AND_CHECK(m_class, m_method, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.method_##m_class##_##m_method, m_val) -#define CACHE_METHOD_THUNK_AND_CHECK(m_class, m_method, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.methodthunk_##m_class##_##m_method, m_val) -#define CACHE_PROPERTY_AND_CHECK(m_class, m_property, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.property_##m_class##_##m_property, m_val) - -void MonoCache::clear_members() { - - class_MonoObject = NULL; - class_bool = NULL; - class_int8_t = NULL; - class_int16_t = NULL; - class_int32_t = NULL; - class_int64_t = NULL; - class_uint8_t = NULL; - class_uint16_t = NULL; - class_uint32_t = NULL; - class_uint64_t = NULL; - class_float = NULL; - class_double = NULL; - class_String = NULL; - class_IntPtr = NULL; - - class_System_Collections_IEnumerable = NULL; - class_System_Collections_IDictionary = NULL; - -#ifdef DEBUG_ENABLED - class_System_Diagnostics_StackTrace = NULL; - methodthunk_System_Diagnostics_StackTrace_GetFrames = NULL; - method_System_Diagnostics_StackTrace_ctor_bool = NULL; - method_System_Diagnostics_StackTrace_ctor_Exception_bool = NULL; -#endif - - class_KeyNotFoundException = NULL; - - rawclass_Dictionary = NULL; - - class_Vector2 = NULL; - class_Rect2 = NULL; - class_Transform2D = NULL; - class_Vector3 = NULL; - class_Basis = NULL; - class_Quat = NULL; - class_Transform = NULL; - class_AABB = NULL; - class_Color = NULL; - class_Plane = NULL; - class_NodePath = NULL; - class_RID = NULL; - class_GodotObject = NULL; - class_GodotReference = NULL; - class_Node = NULL; - class_Control = NULL; - class_Spatial = NULL; - class_WeakRef = NULL; - class_Array = NULL; - class_Dictionary = NULL; - class_MarshalUtils = NULL; - -#ifdef DEBUG_ENABLED - class_DebuggingUtils = NULL; - methodthunk_DebuggingUtils_GetStackFrameInfo = NULL; -#endif - - class_ExportAttribute = NULL; - field_ExportAttribute_hint = NULL; - field_ExportAttribute_hintString = NULL; - class_SignalAttribute = NULL; - class_ToolAttribute = NULL; - class_RemoteAttribute = NULL; - class_SyncAttribute = NULL; - class_MasterAttribute = NULL; - class_PuppetAttribute = NULL; - class_SlaveAttribute = NULL; - class_RemoteSyncAttribute = NULL; - class_MasterSyncAttribute = NULL; - class_PuppetSyncAttribute = NULL; - class_GodotMethodAttribute = NULL; - field_GodotMethodAttribute_methodName = NULL; - - field_GodotObject_ptr = NULL; - field_NodePath_ptr = NULL; - field_Image_ptr = NULL; - field_RID_ptr = NULL; - - methodthunk_GodotObject_Dispose = NULL; - methodthunk_Array_GetPtr = NULL; - methodthunk_Dictionary_GetPtr = NULL; - methodthunk_SignalAwaiter_SignalCallback = NULL; - methodthunk_SignalAwaiter_FailureCallback = NULL; - methodthunk_GodotTaskScheduler_Activate = NULL; - - methodthunk_MarshalUtils_TypeIsGenericArray = NULL; - methodthunk_MarshalUtils_TypeIsGenericDictionary = NULL; - methodthunk_MarshalUtils_ArrayGetElementType = NULL; - methodthunk_MarshalUtils_DictionaryGetKeyValueTypes = NULL; - methodthunk_MarshalUtils_EnumerableToArray = NULL; - methodthunk_MarshalUtils_IDictionaryToDictionary = NULL; - - task_scheduler_handle = Ref<MonoGCHandle>(); -} - -void MonoCache::cleanup() { - - corlib_cache_updated = false; - godot_api_cache_updated = false; -} - -#define GODOT_API_CLASS(m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, #m_class)) -#define GODOT_API_NS_CLAS(m_ns, m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(m_ns, #m_class)) - -void update_corlib_cache() { - - CACHE_CLASS_AND_CHECK(MonoObject, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_object_class())); - CACHE_CLASS_AND_CHECK(bool, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_boolean_class())); - CACHE_CLASS_AND_CHECK(int8_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_sbyte_class())); - CACHE_CLASS_AND_CHECK(int16_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int16_class())); - CACHE_CLASS_AND_CHECK(int32_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int32_class())); - CACHE_CLASS_AND_CHECK(int64_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int64_class())); - CACHE_CLASS_AND_CHECK(uint8_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_byte_class())); - CACHE_CLASS_AND_CHECK(uint16_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint16_class())); - CACHE_CLASS_AND_CHECK(uint32_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint32_class())); - CACHE_CLASS_AND_CHECK(uint64_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint64_class())); - CACHE_CLASS_AND_CHECK(float, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_single_class())); - CACHE_CLASS_AND_CHECK(double, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_double_class())); - CACHE_CLASS_AND_CHECK(String, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_string_class())); - CACHE_CLASS_AND_CHECK(IntPtr, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_intptr_class())); - - CACHE_CLASS_AND_CHECK(System_Collections_IEnumerable, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections", "IEnumerable")); - CACHE_CLASS_AND_CHECK(System_Collections_IDictionary, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections", "IDictionary")); - -#ifdef DEBUG_ENABLED - CACHE_CLASS_AND_CHECK(System_Diagnostics_StackTrace, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Diagnostics", "StackTrace")); - CACHE_METHOD_THUNK_AND_CHECK(System_Diagnostics_StackTrace, GetFrames, (StackTrace_GetFrames)CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_thunk("GetFrames")); - CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(bool)", true)); - CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_Exception_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(System.Exception,bool)", true)); -#endif - - CACHE_CLASS_AND_CHECK(KeyNotFoundException, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections.Generic", "KeyNotFoundException")); - - mono_cache.corlib_cache_updated = true; -} - -void update_godot_api_cache() { - - CACHE_CLASS_AND_CHECK(Vector2, GODOT_API_CLASS(Vector2)); - CACHE_CLASS_AND_CHECK(Rect2, GODOT_API_CLASS(Rect2)); - CACHE_CLASS_AND_CHECK(Transform2D, GODOT_API_CLASS(Transform2D)); - CACHE_CLASS_AND_CHECK(Vector3, GODOT_API_CLASS(Vector3)); - CACHE_CLASS_AND_CHECK(Basis, GODOT_API_CLASS(Basis)); - CACHE_CLASS_AND_CHECK(Quat, GODOT_API_CLASS(Quat)); - CACHE_CLASS_AND_CHECK(Transform, GODOT_API_CLASS(Transform)); - CACHE_CLASS_AND_CHECK(AABB, GODOT_API_CLASS(AABB)); - CACHE_CLASS_AND_CHECK(Color, GODOT_API_CLASS(Color)); - CACHE_CLASS_AND_CHECK(Plane, GODOT_API_CLASS(Plane)); - CACHE_CLASS_AND_CHECK(NodePath, GODOT_API_CLASS(NodePath)); - CACHE_CLASS_AND_CHECK(RID, GODOT_API_CLASS(RID)); - CACHE_CLASS_AND_CHECK(GodotObject, GODOT_API_CLASS(Object)); - CACHE_CLASS_AND_CHECK(GodotReference, GODOT_API_CLASS(Reference)); - CACHE_CLASS_AND_CHECK(Node, GODOT_API_CLASS(Node)); - CACHE_CLASS_AND_CHECK(Control, GODOT_API_CLASS(Control)); - CACHE_CLASS_AND_CHECK(Spatial, GODOT_API_CLASS(Spatial)); - CACHE_CLASS_AND_CHECK(WeakRef, GODOT_API_CLASS(WeakRef)); - CACHE_CLASS_AND_CHECK(Array, GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Array)); - CACHE_CLASS_AND_CHECK(Dictionary, GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Dictionary)); - CACHE_CLASS_AND_CHECK(MarshalUtils, GODOT_API_CLASS(MarshalUtils)); - -#ifdef DEBUG_ENABLED - CACHE_CLASS_AND_CHECK(DebuggingUtils, GODOT_API_CLASS(DebuggingUtils)); -#endif - - // Attributes - CACHE_CLASS_AND_CHECK(ExportAttribute, GODOT_API_CLASS(ExportAttribute)); - CACHE_FIELD_AND_CHECK(ExportAttribute, hint, CACHED_CLASS(ExportAttribute)->get_field("hint")); - CACHE_FIELD_AND_CHECK(ExportAttribute, hintString, CACHED_CLASS(ExportAttribute)->get_field("hintString")); - CACHE_CLASS_AND_CHECK(SignalAttribute, GODOT_API_CLASS(SignalAttribute)); - CACHE_CLASS_AND_CHECK(ToolAttribute, GODOT_API_CLASS(ToolAttribute)); - CACHE_CLASS_AND_CHECK(RemoteAttribute, GODOT_API_CLASS(RemoteAttribute)); - CACHE_CLASS_AND_CHECK(SyncAttribute, GODOT_API_CLASS(SyncAttribute)); - CACHE_CLASS_AND_CHECK(MasterAttribute, GODOT_API_CLASS(MasterAttribute)); - CACHE_CLASS_AND_CHECK(PuppetAttribute, GODOT_API_CLASS(PuppetAttribute)); - CACHE_CLASS_AND_CHECK(SlaveAttribute, GODOT_API_CLASS(SlaveAttribute)); - CACHE_CLASS_AND_CHECK(RemoteSyncAttribute, GODOT_API_CLASS(RemoteSyncAttribute)); - CACHE_CLASS_AND_CHECK(MasterSyncAttribute, GODOT_API_CLASS(MasterSyncAttribute)); - CACHE_CLASS_AND_CHECK(PuppetSyncAttribute, GODOT_API_CLASS(PuppetSyncAttribute)); - CACHE_CLASS_AND_CHECK(GodotMethodAttribute, GODOT_API_CLASS(GodotMethodAttribute)); - CACHE_FIELD_AND_CHECK(GodotMethodAttribute, methodName, CACHED_CLASS(GodotMethodAttribute)->get_field("methodName")); - - CACHE_FIELD_AND_CHECK(GodotObject, ptr, CACHED_CLASS(GodotObject)->get_field(BINDINGS_PTR_FIELD)); - CACHE_FIELD_AND_CHECK(NodePath, ptr, CACHED_CLASS(NodePath)->get_field(BINDINGS_PTR_FIELD)); - CACHE_FIELD_AND_CHECK(RID, ptr, CACHED_CLASS(RID)->get_field(BINDINGS_PTR_FIELD)); - - CACHE_METHOD_THUNK_AND_CHECK(GodotObject, Dispose, (GodotObject_Dispose)CACHED_CLASS(GodotObject)->get_method_thunk("Dispose", 0)); - CACHE_METHOD_THUNK_AND_CHECK(Array, GetPtr, (Array_GetPtr)GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Array)->get_method_thunk("GetPtr", 0)); - CACHE_METHOD_THUNK_AND_CHECK(Dictionary, GetPtr, (Dictionary_GetPtr)GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Dictionary)->get_method_thunk("GetPtr", 0)); - CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, SignalCallback, (SignalAwaiter_SignalCallback)GODOT_API_CLASS(SignalAwaiter)->get_method_thunk("SignalCallback", 1)); - CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, FailureCallback, (SignalAwaiter_FailureCallback)GODOT_API_CLASS(SignalAwaiter)->get_method_thunk("FailureCallback", 0)); - CACHE_METHOD_THUNK_AND_CHECK(GodotTaskScheduler, Activate, (GodotTaskScheduler_Activate)GODOT_API_CLASS(GodotTaskScheduler)->get_method_thunk("Activate", 0)); - - CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericArray, (TypeIsGenericArray)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("TypeIsGenericArray", 1)); - CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericDictionary, (TypeIsGenericDictionary)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("TypeIsGenericDictionary", 1)); - CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, ArrayGetElementType, (ArrayGetElementType)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("ArrayGetElementType", 2)); - CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, DictionaryGetKeyValueTypes, (DictionaryGetKeyValueTypes)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("DictionaryGetKeyValueTypes", 3)); - CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, EnumerableToArray, (EnumerableToArray)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("EnumerableToArray", 2)); - CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, IDictionaryToDictionary, (IDictionaryToDictionary)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("IDictionaryToDictionary", 2)); - -#ifdef DEBUG_ENABLED - CACHE_METHOD_THUNK_AND_CHECK(DebuggingUtils, GetStackFrameInfo, (DebugUtils_StackFrameInfo)GODOT_API_CLASS(DebuggingUtils)->get_method_thunk("GetStackFrameInfo", 4)); -#endif - - // TODO Move to CSharpLanguage::init() and do handle disposal - MonoObject *task_scheduler = mono_object_new(SCRIPTS_DOMAIN, GODOT_API_CLASS(GodotTaskScheduler)->get_mono_ptr()); - GDMonoUtils::runtime_object_init(task_scheduler); - mono_cache.task_scheduler_handle = MonoGCHandle::create_strong(task_scheduler); - - mono_cache.godot_api_cache_updated = true; -} - -void clear_cache() { - mono_cache.cleanup(); - mono_cache.clear_members(); -} - MonoObject *unmanaged_get_managed(Object *unmanaged) { if (!unmanaged) @@ -344,7 +114,6 @@ MonoObject *unmanaged_get_managed(Object *unmanaged) { // This way if the unmanaged world has no references to our owner // but the managed instance is alive, the refcount will be 1 instead of 0. // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr) - ref->reference(); } @@ -357,7 +126,7 @@ void set_main_thread(MonoThread *p_thread) { void attach_current_thread() { ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized()); - MonoThread *mono_thread = mono_thread_attach(SCRIPTS_DOMAIN); + MonoThread *mono_thread = mono_thread_attach(mono_get_root_domain()); ERR_FAIL_NULL(mono_thread); } @@ -372,11 +141,10 @@ MonoThread *get_current_thread() { return mono_thread_current(); } -void runtime_object_init(MonoObject *p_this_obj) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - // FIXME: Do not use mono_runtime_object_init, it aborts if an exception is thrown - mono_runtime_object_init(p_this_obj); - GD_MONO_END_RUNTIME_INVOKE; +void runtime_object_init(MonoObject *p_this_obj, GDMonoClass *p_class, MonoException **r_exc) { + GDMonoMethod *ctor = p_class->get_method(".ctor", 0); + ERR_FAIL_NULL(ctor); + ctor->invoke_raw(p_this_obj, NULL, r_exc); } GDMonoClass *get_object_class(MonoObject *p_object) { @@ -393,7 +161,7 @@ GDMonoClass *type_get_proxy_class(const StringName &p_type) { if (klass && klass->is_static()) { // A static class means this is a Godot singleton class. If an instance is needed we use Godot.Object. - return mono_cache.class_GodotObject; + return GDMonoCache::cached_data.class_GodotObject; } #ifdef TOOLS_ENABLED @@ -422,33 +190,27 @@ GDMonoClass *get_class_native_base(GDMonoClass *p_class) { } MonoObject *create_managed_for_godot_object(GDMonoClass *p_class, const StringName &p_native, Object *p_object) { - String object_type = p_object->get_class_name(); - - if (object_type[0] == '_') - object_type = object_type.substr(1, object_type.length()); - - if (!ClassDB::is_parent_class(object_type, p_native)) { - ERR_EXPLAIN("Type inherits from native type '" + p_native + "', so it can't be instanced in object of type: '" + p_object->get_class() + "'"); - ERR_FAIL_V(NULL); - } + bool parent_is_object_class = ClassDB::is_parent_class(p_object->get_class_name(), p_native); + ERR_FAIL_COND_V_MSG(!parent_is_object_class, NULL, + "Type inherits from native type '" + p_native + "', so it can't be instanced in object of type: '" + p_object->get_class() + "'."); - MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, p_class->get_mono_ptr()); + MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr()); ERR_FAIL_NULL_V(mono_object, NULL); CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, p_object); // Construct - GDMonoUtils::runtime_object_init(mono_object); + GDMonoUtils::runtime_object_init(mono_object, p_class); return mono_object; } MonoObject *create_managed_from(const NodePath &p_from) { - MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(NodePath)); + MonoObject *mono_object = mono_object_new(mono_domain_get(), CACHED_CLASS_RAW(NodePath)); ERR_FAIL_NULL_V(mono_object, NULL); // Construct - GDMonoUtils::runtime_object_init(mono_object); + GDMonoUtils::runtime_object_init(mono_object, CACHED_CLASS(NodePath)); CACHED_FIELD(NodePath, ptr)->set_value_raw(mono_object, memnew(NodePath(p_from))); @@ -456,11 +218,11 @@ MonoObject *create_managed_from(const NodePath &p_from) { } MonoObject *create_managed_from(const RID &p_from) { - MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(RID)); + MonoObject *mono_object = mono_object_new(mono_domain_get(), CACHED_CLASS_RAW(RID)); ERR_FAIL_NULL_V(mono_object, NULL); // Construct - GDMonoUtils::runtime_object_init(mono_object); + GDMonoUtils::runtime_object_init(mono_object, CACHED_CLASS(RID)); CACHED_FIELD(RID, ptr)->set_value_raw(mono_object, memnew(RID(p_from))); @@ -468,7 +230,7 @@ MonoObject *create_managed_from(const RID &p_from) { } MonoObject *create_managed_from(const Array &p_from, GDMonoClass *p_class) { - MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, p_class->get_mono_ptr()); + MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr()); ERR_FAIL_NULL_V(mono_object, NULL); // Search constructor that takes a pointer as parameter @@ -492,13 +254,13 @@ MonoObject *create_managed_from(const Array &p_from, GDMonoClass *p_class) { MonoException *exc = NULL; GDMonoUtils::runtime_invoke(m, mono_object, args, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); + UNHANDLED_EXCEPTION(exc); return mono_object; } MonoObject *create_managed_from(const Dictionary &p_from, GDMonoClass *p_class) { - MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, p_class->get_mono_ptr()); + MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr()); ERR_FAIL_NULL_V(mono_object, NULL); // Search constructor that takes a pointer as parameter @@ -522,12 +284,14 @@ MonoObject *create_managed_from(const Dictionary &p_from, GDMonoClass *p_class) MonoException *exc = NULL; GDMonoUtils::runtime_invoke(m, mono_object, args, &exc); - UNLIKELY_UNHANDLED_EXCEPTION(exc); + UNHANDLED_EXCEPTION(exc); return mono_object; } MonoDomain *create_domain(const String &p_friendly_name) { + print_verbose("Mono: Creating domain '" + p_friendly_name + "'..."); + MonoDomain *domain = mono_domain_create_appdomain((char *)p_friendly_name.utf8().get_data(), NULL); if (domain) { @@ -574,8 +338,14 @@ void debug_print_unhandled_exception(MonoException *p_exc) { void debug_send_unhandled_exception_error(MonoException *p_exc) { #ifdef DEBUG_ENABLED - if (!ScriptDebugger::get_singleton()) + if (!ScriptDebugger::get_singleton()) { +#ifdef TOOLS_ENABLED + if (Engine::get_singleton()->is_editor_hint()) { + ERR_PRINTS(GDMonoUtils::get_exception_name_and_message(p_exc)); + } +#endif return; + } _TLS_RECURSION_GUARD_; @@ -599,7 +369,7 @@ void debug_send_unhandled_exception_error(MonoException *p_exc) { if (unexpected_exc) { GDMonoInternals::unhandled_exception(unexpected_exc); - GD_UNREACHABLE(); + return; } Vector<ScriptLanguage::StackInfo> _si; @@ -632,13 +402,7 @@ void debug_send_unhandled_exception_error(MonoException *p_exc) { } void debug_unhandled_exception(MonoException *p_exc) { -#ifdef DEBUG_ENABLED - GDMonoUtils::debug_send_unhandled_exception_error(p_exc); - if (ScriptDebugger::get_singleton()) - ScriptDebugger::get_singleton()->idle_poll(); -#endif GDMonoInternals::unhandled_exception(p_exc); // prints the exception as well - GD_UNREACHABLE(); } void print_unhandled_exception(MonoException *p_exc) { @@ -646,19 +410,17 @@ void print_unhandled_exception(MonoException *p_exc) { } void set_pending_exception(MonoException *p_exc) { -#ifdef HAS_PENDING_EXCEPTIONS +#ifdef NO_PENDING_EXCEPTIONS + debug_unhandled_exception(p_exc); +#else if (get_runtime_invoke_count() == 0) { debug_unhandled_exception(p_exc); - GD_UNREACHABLE(); } if (!mono_runtime_set_pending_exception(p_exc, false)) { ERR_PRINTS("Exception thrown from managed code, but it could not be set as pending:"); GDMonoUtils::debug_print_unhandled_exception(p_exc); } -#else - debug_unhandled_exception(p_exc); - GD_UNREACHABLE(); #endif } @@ -729,7 +491,129 @@ uint64_t unbox_enum_value(MonoObject *p_boxed, MonoType *p_enum_basetype, bool & } void dispose(MonoObject *p_mono_object, MonoException **r_exc) { - invoke_method_thunk(CACHED_METHOD_THUNK(GodotObject, Dispose), p_mono_object, r_exc); + CACHED_METHOD_THUNK(GodotObject, Dispose).invoke(p_mono_object, r_exc); } +namespace Marshal { + +#ifdef MONO_GLUE_ENABLED +#ifdef TOOLS_ENABLED +#define NO_GLUE_RET(m_ret) \ + { \ + if (!GDMonoCache::cached_data.godot_api_cache_updated) return m_ret; \ + } +#else +#define NO_GLUE_RET(m_ret) \ + {} +#endif +#else +#define NO_GLUE_RET(m_ret) \ + { return m_ret; } +#endif + +bool type_is_generic_array(MonoReflectionType *p_reftype) { + NO_GLUE_RET(false); + MonoException *exc = NULL; + MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericArray).invoke(p_reftype, &exc); + UNHANDLED_EXCEPTION(exc); + return (bool)res; +} + +bool type_is_generic_dictionary(MonoReflectionType *p_reftype) { + NO_GLUE_RET(false); + MonoException *exc = NULL; + MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericDictionary).invoke(p_reftype, &exc); + UNHANDLED_EXCEPTION(exc); + return (bool)res; +} + +void array_get_element_type(MonoReflectionType *p_array_reftype, MonoReflectionType **r_elem_reftype) { + MonoException *exc = NULL; + CACHED_METHOD_THUNK(MarshalUtils, ArrayGetElementType).invoke(p_array_reftype, r_elem_reftype, &exc); + UNHANDLED_EXCEPTION(exc); +} + +void dictionary_get_key_value_types(MonoReflectionType *p_dict_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype) { + MonoException *exc = NULL; + CACHED_METHOD_THUNK(MarshalUtils, DictionaryGetKeyValueTypes).invoke(p_dict_reftype, r_key_reftype, r_value_reftype, &exc); + UNHANDLED_EXCEPTION(exc); +} + +bool generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype) { + NO_GLUE_RET(false); + MonoException *exc = NULL; + MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, GenericIEnumerableIsAssignableFromType).invoke(p_reftype, &exc); + UNHANDLED_EXCEPTION(exc); + return (bool)res; +} + +bool generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype) { + NO_GLUE_RET(false); + MonoException *exc = NULL; + MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, GenericIDictionaryIsAssignableFromType).invoke(p_reftype, &exc); + UNHANDLED_EXCEPTION(exc); + return (bool)res; +} + +bool generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_elem_reftype) { + NO_GLUE_RET(false); + MonoException *exc = NULL; + MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, GenericIEnumerableIsAssignableFromType_with_info).invoke(p_reftype, r_elem_reftype, &exc); + UNHANDLED_EXCEPTION(exc); + return (bool)res; +} + +bool generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype) { + NO_GLUE_RET(false); + MonoException *exc = NULL; + MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, GenericIDictionaryIsAssignableFromType_with_info).invoke(p_reftype, r_key_reftype, r_value_reftype, &exc); + UNHANDLED_EXCEPTION(exc); + return (bool)res; +} + +Array enumerable_to_array(MonoObject *p_enumerable) { + NO_GLUE_RET(Array()); + Array result; + MonoException *exc = NULL; + CACHED_METHOD_THUNK(MarshalUtils, EnumerableToArray).invoke(p_enumerable, &result, &exc); + UNHANDLED_EXCEPTION(exc); + return result; +} + +Dictionary idictionary_to_dictionary(MonoObject *p_idictionary) { + NO_GLUE_RET(Dictionary()); + Dictionary result; + MonoException *exc = NULL; + CACHED_METHOD_THUNK(MarshalUtils, IDictionaryToDictionary).invoke(p_idictionary, &result, &exc); + UNHANDLED_EXCEPTION(exc); + return result; +} + +Dictionary generic_idictionary_to_dictionary(MonoObject *p_generic_idictionary) { + NO_GLUE_RET(Dictionary()); + Dictionary result; + MonoException *exc = NULL; + CACHED_METHOD_THUNK(MarshalUtils, GenericIDictionaryToDictionary).invoke(p_generic_idictionary, &result, &exc); + UNHANDLED_EXCEPTION(exc); + return result; +} + +GDMonoClass *make_generic_array_type(MonoReflectionType *p_elem_reftype) { + NO_GLUE_RET(NULL); + MonoException *exc = NULL; + MonoReflectionType *reftype = CACHED_METHOD_THUNK(MarshalUtils, MakeGenericArrayType).invoke(p_elem_reftype, &exc); + UNHANDLED_EXCEPTION(exc); + return GDMono::get_singleton()->get_class(mono_class_from_mono_type(mono_reflection_type_get_type(reftype))); +} + +GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype) { + NO_GLUE_RET(NULL); + MonoException *exc = NULL; + MonoReflectionType *reftype = CACHED_METHOD_THUNK(MarshalUtils, MakeGenericDictionaryType).invoke(p_key_reftype, p_value_reftype, &exc); + UNHANDLED_EXCEPTION(exc); + return GDMono::get_singleton()->get_class(mono_class_from_mono_type(mono_reflection_type_get_type(reftype))); +} + +} // namespace Marshal + } // namespace GDMonoUtils diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h index 87610e286c..848df843fe 100644 --- a/modules/mono/mono_gd/gd_mono_utils.h +++ b/modules/mono/mono_gd/gd_mono_utils.h @@ -41,7 +41,7 @@ #include "core/object.h" #include "core/reference.h" -#define UNLIKELY_UNHANDLED_EXCEPTION(m_exc) \ +#define UNHANDLED_EXCEPTION(m_exc) \ if (unlikely(m_exc != NULL)) { \ GDMonoUtils::debug_unhandled_exception(m_exc); \ GD_UNREACHABLE(); \ @@ -49,141 +49,27 @@ namespace GDMonoUtils { -typedef void (*GodotObject_Dispose)(MonoObject *, MonoException **); -typedef Array *(*Array_GetPtr)(MonoObject *, MonoException **); -typedef Dictionary *(*Dictionary_GetPtr)(MonoObject *, MonoException **); -typedef MonoObject *(*SignalAwaiter_SignalCallback)(MonoObject *, MonoArray *, MonoException **); -typedef MonoObject *(*SignalAwaiter_FailureCallback)(MonoObject *, MonoException **); -typedef MonoObject *(*GodotTaskScheduler_Activate)(MonoObject *, MonoException **); -typedef MonoArray *(*StackTrace_GetFrames)(MonoObject *, MonoException **); -typedef void (*DebugUtils_StackFrameInfo)(MonoObject *, MonoString **, int *, MonoString **, MonoException **); - -typedef MonoBoolean (*TypeIsGenericArray)(MonoReflectionType *, MonoException **); -typedef MonoBoolean (*TypeIsGenericDictionary)(MonoReflectionType *, MonoException **); -typedef MonoBoolean (*ArrayGetElementType)(MonoReflectionType *, MonoReflectionType **, MonoException **); -typedef MonoBoolean (*DictionaryGetKeyValueTypes)(MonoReflectionType *, MonoReflectionType **, MonoReflectionType **, MonoException **); -typedef void (*EnumerableToArray)(MonoObject *, Array *, MonoException **); -typedef void (*IDictionaryToDictionary)(MonoObject *, Dictionary *, MonoException **); - -struct MonoCache { - - // ----------------------------------------------- - // corlib classes - - // Let's use the no-namespace format for these too - GDMonoClass *class_MonoObject; - GDMonoClass *class_bool; - GDMonoClass *class_int8_t; - GDMonoClass *class_int16_t; - GDMonoClass *class_int32_t; - GDMonoClass *class_int64_t; - GDMonoClass *class_uint8_t; - GDMonoClass *class_uint16_t; - GDMonoClass *class_uint32_t; - GDMonoClass *class_uint64_t; - GDMonoClass *class_float; - GDMonoClass *class_double; - GDMonoClass *class_String; - GDMonoClass *class_IntPtr; - - GDMonoClass *class_System_Collections_IEnumerable; - GDMonoClass *class_System_Collections_IDictionary; - -#ifdef DEBUG_ENABLED - GDMonoClass *class_System_Diagnostics_StackTrace; - StackTrace_GetFrames methodthunk_System_Diagnostics_StackTrace_GetFrames; - GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_bool; - GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_Exception_bool; -#endif - - GDMonoClass *class_KeyNotFoundException; - - MonoClass *rawclass_Dictionary; - // ----------------------------------------------- - - GDMonoClass *class_Vector2; - GDMonoClass *class_Rect2; - GDMonoClass *class_Transform2D; - GDMonoClass *class_Vector3; - GDMonoClass *class_Basis; - GDMonoClass *class_Quat; - GDMonoClass *class_Transform; - GDMonoClass *class_AABB; - GDMonoClass *class_Color; - GDMonoClass *class_Plane; - GDMonoClass *class_NodePath; - GDMonoClass *class_RID; - GDMonoClass *class_GodotObject; - GDMonoClass *class_GodotReference; - GDMonoClass *class_Node; - GDMonoClass *class_Control; - GDMonoClass *class_Spatial; - GDMonoClass *class_WeakRef; - GDMonoClass *class_Array; - GDMonoClass *class_Dictionary; - GDMonoClass *class_MarshalUtils; - -#ifdef DEBUG_ENABLED - GDMonoClass *class_DebuggingUtils; - DebugUtils_StackFrameInfo methodthunk_DebuggingUtils_GetStackFrameInfo; -#endif - - GDMonoClass *class_ExportAttribute; - GDMonoField *field_ExportAttribute_hint; - GDMonoField *field_ExportAttribute_hintString; - GDMonoClass *class_SignalAttribute; - GDMonoClass *class_ToolAttribute; - GDMonoClass *class_RemoteAttribute; - GDMonoClass *class_SyncAttribute; - GDMonoClass *class_RemoteSyncAttribute; - GDMonoClass *class_MasterSyncAttribute; - GDMonoClass *class_PuppetSyncAttribute; - GDMonoClass *class_MasterAttribute; - GDMonoClass *class_PuppetAttribute; - GDMonoClass *class_SlaveAttribute; - GDMonoClass *class_GodotMethodAttribute; - GDMonoField *field_GodotMethodAttribute_methodName; - - GDMonoField *field_GodotObject_ptr; - GDMonoField *field_NodePath_ptr; - GDMonoField *field_Image_ptr; - GDMonoField *field_RID_ptr; - - GodotObject_Dispose methodthunk_GodotObject_Dispose; - Array_GetPtr methodthunk_Array_GetPtr; - Dictionary_GetPtr methodthunk_Dictionary_GetPtr; - SignalAwaiter_SignalCallback methodthunk_SignalAwaiter_SignalCallback; - SignalAwaiter_FailureCallback methodthunk_SignalAwaiter_FailureCallback; - GodotTaskScheduler_Activate methodthunk_GodotTaskScheduler_Activate; - - TypeIsGenericArray methodthunk_MarshalUtils_TypeIsGenericArray; - TypeIsGenericDictionary methodthunk_MarshalUtils_TypeIsGenericDictionary; - ArrayGetElementType methodthunk_MarshalUtils_ArrayGetElementType; - DictionaryGetKeyValueTypes methodthunk_MarshalUtils_DictionaryGetKeyValueTypes; - EnumerableToArray methodthunk_MarshalUtils_EnumerableToArray; - IDictionaryToDictionary methodthunk_MarshalUtils_IDictionaryToDictionary; - - Ref<MonoGCHandle> task_scheduler_handle; - - bool corlib_cache_updated; - bool godot_api_cache_updated; - - void clear_members(); - void cleanup(); - - MonoCache() { - corlib_cache_updated = false; - godot_api_cache_updated = false; - - clear_members(); - } -}; +namespace Marshal { + +bool type_is_generic_array(MonoReflectionType *p_reftype); +bool type_is_generic_dictionary(MonoReflectionType *p_reftype); + +void array_get_element_type(MonoReflectionType *p_array_reftype, MonoReflectionType **r_elem_reftype); +void dictionary_get_key_value_types(MonoReflectionType *p_dict_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype); + +bool generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype); +bool generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype); +bool generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_elem_reftype); +bool generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype); -extern MonoCache mono_cache; +GDMonoClass *make_generic_array_type(MonoReflectionType *p_elem_reftype); +GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype); -void update_corlib_cache(); -void update_godot_api_cache(); -void clear_cache(); +Array enumerable_to_array(MonoObject *p_enumerable); +Dictionary idictionary_to_dictionary(MonoObject *p_idictionary); +Dictionary generic_idictionary_to_dictionary(MonoObject *p_generic_idictionary); + +} // namespace Marshal _FORCE_INLINE_ void hash_combine(uint32_t &p_hash, const uint32_t &p_with_hash) { p_hash ^= p_with_hash + 0x9e3779b9 + (p_hash << 6) + (p_hash >> 2); @@ -205,7 +91,7 @@ _FORCE_INLINE_ bool is_main_thread() { return mono_domain_get() != NULL && mono_thread_get_main() == mono_thread_current(); } -void runtime_object_init(MonoObject *p_this_obj); +void runtime_object_init(MonoObject *p_this_obj, GDMonoClass *p_class, MonoException **r_exc = NULL); GDMonoClass *get_object_class(MonoObject *p_object); GDMonoClass *type_get_proxy_class(const StringName &p_type); @@ -225,7 +111,7 @@ void set_exception_message(MonoException *p_exc, String message); void debug_print_unhandled_exception(MonoException *p_exc); void debug_send_unhandled_exception_error(MonoException *p_exc); -GD_NORETURN void debug_unhandled_exception(MonoException *p_exc); +void debug_unhandled_exception(MonoException *p_exc); void print_unhandled_exception(MonoException *p_exc); /** @@ -260,20 +146,6 @@ void dispose(MonoObject *p_mono_object, MonoException **r_exc); #define NATIVE_GDMONOCLASS_NAME(m_class) (GDMonoMarshal::mono_string_to_godot((MonoString *)m_class->get_field(BINDINGS_NATIVE_NAME_FIELD)->get_value(NULL))) -#define CACHED_CLASS(m_class) (GDMonoUtils::mono_cache.class_##m_class) -#define CACHED_CLASS_RAW(m_class) (GDMonoUtils::mono_cache.class_##m_class->get_mono_ptr()) -#define CACHED_RAW_MONO_CLASS(m_class) (GDMonoUtils::mono_cache.rawclass_##m_class) -#define CACHED_FIELD(m_class, m_field) (GDMonoUtils::mono_cache.field_##m_class##_##m_field) -#define CACHED_METHOD(m_class, m_method) (GDMonoUtils::mono_cache.method_##m_class##_##m_method) -#define CACHED_METHOD_THUNK(m_class, m_method) (GDMonoUtils::mono_cache.methodthunk_##m_class##_##m_method) -#define CACHED_PROPERTY(m_class, m_property) (GDMonoUtils::mono_cache.property_##m_class##_##m_property) - -#ifdef REAL_T_IS_DOUBLE -#define REAL_T_MONOCLASS CACHED_CLASS_RAW(double) -#else -#define REAL_T_MONOCLASS CACHED_CLASS_RAW(float) -#endif - #define GD_MONO_BEGIN_RUNTIME_INVOKE \ int &_runtime_invoke_count_ref = GDMonoUtils::get_runtime_invoke_count_ref(); \ _runtime_invoke_count_ref += 1; @@ -281,93 +153,4 @@ void dispose(MonoObject *p_mono_object, MonoException **r_exc); #define GD_MONO_END_RUNTIME_INVOKE \ _runtime_invoke_count_ref -= 1; -inline void invoke_method_thunk(void (*p_method_thunk)()) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - p_method_thunk(); - GD_MONO_END_RUNTIME_INVOKE; -} - -template <class R> -R invoke_method_thunk(R (*p_method_thunk)()) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - R r = p_method_thunk(); - GD_MONO_END_RUNTIME_INVOKE; - return r; -} - -template <class P1> -void invoke_method_thunk(void (*p_method_thunk)(P1), P1 p_arg1) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - p_method_thunk(p_arg1); - GD_MONO_END_RUNTIME_INVOKE; -} - -template <class R, class P1> -R invoke_method_thunk(R (*p_method_thunk)(P1), P1 p_arg1) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - R r = p_method_thunk(p_arg1); - GD_MONO_END_RUNTIME_INVOKE; - return r; -} - -template <class P1, class P2> -void invoke_method_thunk(void (*p_method_thunk)(P1, P2), P1 p_arg1, P2 p_arg2) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - p_method_thunk(p_arg1, p_arg2); - GD_MONO_END_RUNTIME_INVOKE; -} - -template <class R, class P1, class P2> -R invoke_method_thunk(R (*p_method_thunk)(P1, P2), P1 p_arg1, P2 p_arg2) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - R r = p_method_thunk(p_arg1, p_arg2); - GD_MONO_END_RUNTIME_INVOKE; - return r; -} - -template <class P1, class P2, class P3> -void invoke_method_thunk(void (*p_method_thunk)(P1, P2, P3), P1 p_arg1, P2 p_arg2, P3 p_arg3) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - p_method_thunk(p_arg1, p_arg2, p_arg3); - GD_MONO_END_RUNTIME_INVOKE; -} - -template <class R, class P1, class P2, class P3> -R invoke_method_thunk(R (*p_method_thunk)(P1, P2, P3), P1 p_arg1, P2 p_arg2, P3 p_arg3) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - R r = p_method_thunk(p_arg1, p_arg2, p_arg3); - GD_MONO_END_RUNTIME_INVOKE; - return r; -} - -template <class P1, class P2, class P3, class P4> -void invoke_method_thunk(void (*p_method_thunk)(P1, P2, P3, P4), P1 p_arg1, P2 p_arg2, P3 p_arg3, P4 p_arg4) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - p_method_thunk(p_arg1, p_arg2, p_arg3, p_arg4); - GD_MONO_END_RUNTIME_INVOKE; -} - -template <class R, class P1, class P2, class P3, class P4> -R invoke_method_thunk(R (*p_method_thunk)(P1, P2, P3, P4), P1 p_arg1, P2 p_arg2, P3 p_arg3, P4 p_arg4) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - R r = p_method_thunk(p_arg1, p_arg2, p_arg3, p_arg4); - GD_MONO_END_RUNTIME_INVOKE; - return r; -} - -template <class P1, class P2, class P3, class P4, class P5> -void invoke_method_thunk(void (*p_method_thunk)(P1, P2, P3, P4, P5), P1 p_arg1, P2 p_arg2, P3 p_arg3, P4 p_arg4, P5 p_arg5) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - p_method_thunk(p_arg1, p_arg2, p_arg3, p_arg4, p_arg5); - GD_MONO_END_RUNTIME_INVOKE; -} - -template <class R, class P1, class P2, class P3, class P4, class P5> -R invoke_method_thunk(R (*p_method_thunk)(P1, P2, P3, P4, P5), P1 p_arg1, P2 p_arg2, P3 p_arg3, P4 p_arg4, P5 p_arg5) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - R r = p_method_thunk(p_arg1, p_arg2, p_arg3, p_arg4, p_arg5); - GD_MONO_END_RUNTIME_INVOKE; - return r; -} - #endif // GD_MONOUTILS_H diff --git a/modules/mono/mono_gd/i_mono_class_member.h b/modules/mono/mono_gd/i_mono_class_member.h index 553d9edc72..f4de4e3230 100644 --- a/modules/mono/mono_gd/i_mono_class_member.h +++ b/modules/mono/mono_gd/i_mono_class_member.h @@ -53,9 +53,11 @@ public: virtual ~IMonoClassMember() {} - virtual MemberType get_member_type() = 0; + virtual GDMonoClass *get_enclosing_class() const = 0; - virtual StringName get_name() = 0; + virtual MemberType get_member_type() const = 0; + + virtual StringName get_name() const = 0; virtual bool is_static() = 0; diff --git a/modules/mono/signal_awaiter_utils.cpp b/modules/mono/signal_awaiter_utils.cpp index 5d37e8212f..ee16327856 100644 --- a/modules/mono/signal_awaiter_utils.cpp +++ b/modules/mono/signal_awaiter_utils.cpp @@ -31,6 +31,7 @@ #include "signal_awaiter_utils.h" #include "csharp_script.h" +#include "mono_gd/gd_mono_cache.h" #include "mono_gd/gd_mono_class.h" #include "mono_gd/gd_mono_marshal.h" #include "mono_gd/gd_mono_utils.h" @@ -67,10 +68,8 @@ Error connect_signal_awaiter(Object *p_source, const String &p_signal, Object *p Variant SignalAwaiterHandle::_signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { #ifdef DEBUG_ENABLED - if (conn_target_id && !ObjectDB::get_instance(conn_target_id)) { - ERR_EXPLAIN("Resumed after await, but class instance is gone"); - ERR_FAIL_V(Variant()); - } + ERR_FAIL_COND_V_MSG(conn_target_id && !ObjectDB::get_instance(conn_target_id), Variant(), + "Resumed after await, but class instance is gone."); #endif if (p_argcount < 1) { @@ -91,16 +90,16 @@ Variant SignalAwaiterHandle::_signal_callback(const Variant **p_args, int p_argc set_completed(true); int signal_argc = p_argcount - 1; - MonoArray *signal_args = mono_array_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(MonoObject), signal_argc); + MonoArray *signal_args = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), signal_argc); for (int i = 0; i < signal_argc; i++) { MonoObject *boxed = GDMonoMarshal::variant_to_mono_object(*p_args[i]); - mono_array_set(signal_args, MonoObject *, i, boxed); + mono_array_setref(signal_args, i, boxed); } MonoException *exc = NULL; GD_MONO_BEGIN_RUNTIME_INVOKE; - invoke_method_thunk(CACHED_METHOD_THUNK(SignalAwaiter, SignalCallback), get_target(), signal_args, &exc); + CACHED_METHOD_THUNK(SignalAwaiter, SignalCallback).invoke(get_target(), signal_args, &exc); GD_MONO_END_RUNTIME_INVOKE; if (exc) { @@ -132,7 +131,7 @@ SignalAwaiterHandle::~SignalAwaiterHandle() { if (awaiter) { MonoException *exc = NULL; GD_MONO_BEGIN_RUNTIME_INVOKE; - invoke_method_thunk(CACHED_METHOD_THUNK(SignalAwaiter, FailureCallback), awaiter, &exc); + CACHED_METHOD_THUNK(SignalAwaiter, FailureCallback).invoke(awaiter, &exc); GD_MONO_END_RUNTIME_INVOKE; if (exc) { diff --git a/modules/mono/signal_awaiter_utils.h b/modules/mono/signal_awaiter_utils.h index 098008ded7..4fb3cdb56d 100644 --- a/modules/mono/signal_awaiter_utils.h +++ b/modules/mono/signal_awaiter_utils.h @@ -41,7 +41,7 @@ Error connect_signal_awaiter(Object *p_source, const String &p_signal, Object *p class SignalAwaiterHandle : public MonoGCHandle { - GDCLASS(SignalAwaiterHandle, MonoGCHandle) + GDCLASS(SignalAwaiterHandle, MonoGCHandle); bool completed; diff --git a/modules/mono/utils/path_utils.cpp b/modules/mono/utils/path_utils.cpp index 6e431f51e7..20863b1afe 100644 --- a/modules/mono/utils/path_utils.cpp +++ b/modules/mono/utils/path_utils.cpp @@ -36,16 +36,21 @@ #include "core/project_settings.h" #ifdef WINDOWS_ENABLED +#include <windows.h> + #define ENV_PATH_SEP ";" #else -#define ENV_PATH_SEP ":" #include <limits.h> +#include <unistd.h> + +#define ENV_PATH_SEP ":" #endif #include <stdlib.h> -String path_which(const String &p_name) { +namespace path { +String find_executable(const String &p_name) { #ifdef WINDOWS_ENABLED Vector<String> exts = OS::get_singleton()->get_environment("PATHEXT").split(ENV_PATH_SEP, false); #endif @@ -55,7 +60,7 @@ String path_which(const String &p_name) { return String(); for (int i = 0; i < env_path.size(); i++) { - String p = path_join(env_path[i], p_name); + String p = path::join(env_path[i], p_name); #ifdef WINDOWS_ENABLED for (int j = 0; j < exts.size(); j++) { @@ -73,42 +78,96 @@ String path_which(const String &p_name) { return String(); } -void fix_path(const String &p_path, String &r_out) { - r_out = p_path.replace("\\", "/"); +String cwd() { +#ifdef WINDOWS_ENABLED + const DWORD expected_size = ::GetCurrentDirectoryW(0, NULL); + + String buffer; + buffer.resize((int)expected_size); + if (::GetCurrentDirectoryW(expected_size, buffer.ptrw()) == 0) + return "."; + + return buffer.simplify_path(); +#else + char buffer[PATH_MAX]; + if (::getcwd(buffer, sizeof(buffer)) == NULL) + return "."; + + String result; + if (result.parse_utf8(buffer)) + return "."; - while (true) { // in case of using 2 or more slash - String compare = r_out.replace("//", "/"); - if (r_out == compare) - break; - else - r_out = compare; + return result.simplify_path(); +#endif +} + +String abspath(const String &p_path) { + if (p_path.is_abs_path()) { + return p_path.simplify_path(); + } else { + return path::join(path::cwd(), p_path).simplify_path(); } } -bool rel_path_to_abs(const String &p_existing_path, String &r_abs_path) { +String realpath(const String &p_path) { #ifdef WINDOWS_ENABLED - CharType ret[_MAX_PATH]; - if (::_wfullpath(ret, p_existing_path.c_str(), _MAX_PATH)) { - String abspath = String(ret).replace("\\", "/"); - int pos = abspath.find(":/"); - if (pos != -1) { - r_abs_path = abspath.substr(pos - 1, abspath.length()); - } else { - r_abs_path = abspath; - } - return true; - } -#else - char *resolved_path = ::realpath(p_existing_path.utf8().get_data(), NULL); - if (resolved_path) { - String retstr; - bool success = !retstr.parse_utf8(resolved_path); - ::free(resolved_path); - if (success) { - r_abs_path = retstr; - return true; - } + // Open file without read/write access + HANDLE hFile = ::CreateFileW(p_path.c_str(), 0, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + + if (hFile == INVALID_HANDLE_VALUE) + return p_path; + + const DWORD expected_size = ::GetFinalPathNameByHandleW(hFile, NULL, 0, FILE_NAME_NORMALIZED); + + if (expected_size == 0) { + ::CloseHandle(hFile); + return p_path; } + + String buffer; + buffer.resize((int)expected_size); + ::GetFinalPathNameByHandleW(hFile, buffer.ptrw(), expected_size, FILE_NAME_NORMALIZED); + + ::CloseHandle(hFile); + return buffer.simplify_path(); +#elif UNIX_ENABLED + char *resolved_path = ::realpath(p_path.utf8().get_data(), NULL); + + if (!resolved_path) + return p_path; + + String result; + bool parse_ok = result.parse_utf8(resolved_path); + ::free(resolved_path); + + if (parse_ok) + return p_path; + + return result.simplify_path(); #endif - return false; } + +String join(const String &p_a, const String &p_b) { + if (p_a.empty()) + return p_b; + + const CharType a_last = p_a[p_a.length() - 1]; + if ((a_last == '/' || a_last == '\\') || + (p_b.size() > 0 && (p_b[0] == '/' || p_b[0] == '\\'))) { + return p_a + p_b; + } + + return p_a + "/" + p_b; +} + +String join(const String &p_a, const String &p_b, const String &p_c) { + return path::join(path::join(p_a, p_b), p_c); +} + +String join(const String &p_a, const String &p_b, const String &p_c, const String &p_d) { + return path::join(path::join(path::join(p_a, p_b), p_c), p_d); +} + +} // namespace path diff --git a/modules/mono/utils/path_utils.h b/modules/mono/utils/path_utils.h index 69edf4deb7..ca25bc09f7 100644 --- a/modules/mono/utils/path_utils.h +++ b/modules/mono/utils/path_utils.h @@ -31,24 +31,32 @@ #ifndef PATH_UTILS_H #define PATH_UTILS_H +#include "core/string_builder.h" #include "core/ustring.h" -_FORCE_INLINE_ String path_join(const String &e1, const String &e2) { - return e1.plus_file(e2); -} +namespace path { -_FORCE_INLINE_ String path_join(const String &e1, const String &e2, const String &e3) { - return e1.plus_file(e2).plus_file(e3); -} +String join(const String &p_a, const String &p_b); +String join(const String &p_a, const String &p_b, const String &p_c); +String join(const String &p_a, const String &p_b, const String &p_c, const String &p_d); -_FORCE_INLINE_ String path_join(const String &e1, const String &e2, const String &e3, const String &e4) { - return e1.plus_file(e2).plus_file(e3).plus_file(e4); -} +String find_executable(const String &p_name); -String path_which(const String &p_name); +/// Returns a normalized absolute path to the current working directory +String cwd(); -void fix_path(const String &p_path, String &r_out); +/** + * Obtains a normalized absolute path to p_path. Symbolic links are + * not resolved. The path p_path might not exist in the file system. + */ +String abspath(const String &p_path); -bool rel_path_to_abs(const String &p_existing_path, String &r_abs_path); +/** + * Obtains a normalized path to p_path with symbolic links resolved. + * The resulting path might be either a relative or an absolute path. + */ +String realpath(const String &p_path); + +} // namespace path #endif // PATH_UTILS_H diff --git a/modules/mono/utils/string_utils.cpp b/modules/mono/utils/string_utils.cpp index c390f8b9c2..88366a6a03 100644 --- a/modules/mono/utils/string_utils.cpp +++ b/modules/mono/utils/string_utils.cpp @@ -32,6 +32,9 @@ #include "core/os/file_access.h" +#include <stdio.h> +#include <stdlib.h> + namespace { int sfind(const String &p_text, int p_from) { @@ -41,7 +44,7 @@ int sfind(const String &p_text, int p_from) { int src_len = 2; int len = p_text.length(); - if (src_len == 0 || len == 0) + if (len == 0) return -1; const CharType *src = p_text.c_str(); @@ -52,10 +55,7 @@ int sfind(const String &p_text, int p_from) { for (int j = 0; j < src_len; j++) { int read_pos = i + j; - if (read_pos >= len) { - ERR_PRINT("read_pos >= len"); - return -1; - }; + ERR_FAIL_COND_V(read_pos >= len, -1); switch (j) { case 0: @@ -63,7 +63,7 @@ int sfind(const String &p_text, int p_from) { break; case 1: { CharType c = src[read_pos]; - found = src[read_pos] == 's' || (c >= '0' || c <= '4'); + found = src[read_pos] == 's' || (c >= '0' && c <= '4'); break; } default: @@ -165,7 +165,7 @@ Error read_all_file_utf8(const String &p_path, String &r_content) { PoolVector<uint8_t> sourcef; Error err; FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); - ERR_FAIL_COND_V(err != OK, err); + ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + p_path + "'."); int len = f->get_len(); sourcef.resize(len + 1); @@ -184,3 +184,70 @@ Error read_all_file_utf8(const String &p_path, String &r_content) { r_content = source; return OK; } + +// TODO: Move to variadic templates once we upgrade to C++11 + +String str_format(const char *p_format, ...) { + va_list list; + + va_start(list, p_format); + String res = str_format(p_format, list); + va_end(list); + + return res; +} +// va_copy was defined in the C99, but not in C++ standards before C++11. +// When you compile C++ without --std=c++<XX> option, compilers still define +// va_copy, otherwise you have to use the internal version (__va_copy). +#if !defined(va_copy) +#if defined(__GNUC__) +#define va_copy(d, s) __va_copy((d), (s)) +#else +#define va_copy(d, s) ((d) = (s)) +#endif +#endif + +#if defined(MINGW_ENABLED) || defined(_MSC_VER) && _MSC_VER < 1900 +#define gd_vsnprintf(m_buffer, m_count, m_format, m_args_copy) vsnprintf_s(m_buffer, m_count, _TRUNCATE, m_format, m_args_copy) +#define gd_vscprintf(m_format, m_args_copy) _vscprintf(m_format, m_args_copy) +#else +#define gd_vsnprintf(m_buffer, m_count, m_format, m_args_copy) vsnprintf(m_buffer, m_count, m_format, m_args_copy) +#define gd_vscprintf(m_format, m_args_copy) vsnprintf(NULL, 0, p_format, m_args_copy) +#endif + +String str_format(const char *p_format, va_list p_list) { + char *buffer = str_format_new(p_format, p_list); + + String res(buffer); + memdelete_arr(buffer); + + return res; +} + +char *str_format_new(const char *p_format, ...) { + va_list list; + + va_start(list, p_format); + char *res = str_format_new(p_format, list); + va_end(list); + + return res; +} + +char *str_format_new(const char *p_format, va_list p_list) { + va_list list; + + va_copy(list, p_list); + int len = gd_vscprintf(p_format, list); + va_end(list); + + len += 1; // for the trailing '/0' + + char *buffer(memnew_arr(char, len)); + + va_copy(list, p_list); + gd_vsnprintf(buffer, len, p_format, list); + va_end(list); + + return buffer; +} diff --git a/modules/mono/utils/string_utils.h b/modules/mono/utils/string_utils.h index 61765ccfd8..e7f02955bd 100644 --- a/modules/mono/utils/string_utils.h +++ b/modules/mono/utils/string_utils.h @@ -34,6 +34,8 @@ #include "core/ustring.h" #include "core/variant.h" +#include <stdarg.h> + String sformat(const String &p_text, const Variant &p1 = Variant(), const Variant &p2 = Variant(), const Variant &p3 = Variant(), const Variant &p4 = Variant(), const Variant &p5 = Variant()); #ifdef TOOLS_ENABLED @@ -44,4 +46,17 @@ String escape_csharp_keyword(const String &p_name); Error read_all_file_utf8(const String &p_path, String &r_content); +#if defined(__GNUC__) +#define _PRINTF_FORMAT_ATTRIBUTE_1_0 __attribute__((format(printf, 1, 0))) +#define _PRINTF_FORMAT_ATTRIBUTE_1_2 __attribute__((format(printf, 1, 2))) +#else +#define _PRINTF_FORMAT_ATTRIBUTE_1_0 +#define _PRINTF_FORMAT_ATTRIBUTE_1_2 +#endif + +String str_format(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_1_2; +String str_format(const char *p_format, va_list p_list) _PRINTF_FORMAT_ATTRIBUTE_1_0; +char *str_format_new(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_1_2; +char *str_format_new(const char *p_format, va_list p_list) _PRINTF_FORMAT_ATTRIBUTE_1_0; + #endif // STRING_FORMAT_H diff --git a/modules/mono/utils/thread_local.h b/modules/mono/utils/thread_local.h index 276db8830b..e52b6e73ef 100644 --- a/modules/mono/utils/thread_local.h +++ b/modules/mono/utils/thread_local.h @@ -39,7 +39,7 @@ #error Platform or compiler not supported #endif -#ifdef __GNUC__ +#if defined(__GNUC__) #ifdef HAVE_GCC___THREAD #define _THREAD_LOCAL_(m_t) __thread m_t @@ -47,7 +47,7 @@ #define USE_CUSTOM_THREAD_LOCAL #endif -#elif _MSC_VER +#elif defined(_MSC_VER) #ifdef HAVE_DECLSPEC_THREAD #define _THREAD_LOCAL_(m_t) __declspec(thread) m_t @@ -76,7 +76,7 @@ struct ThreadLocalStorage { void *get_value() const; void set_value(void *p_value) const; - void alloc(void(_CALLBACK_FUNC_ *p_dest_callback)(void *)); + void alloc(void(_CALLBACK_FUNC_ *p_destr_callback)(void *)); void free(); private: diff --git a/modules/ogg/SCsub b/modules/ogg/SCsub index 765a9fc11a..6a72a519fe 100644 --- a/modules/ogg/SCsub +++ b/modules/ogg/SCsub @@ -14,7 +14,7 @@ if env['builtin_libogg']: ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - env_ogg.Append(CPPPATH=[thirdparty_dir]) + env_ogg.Prepend(CPPPATH=[thirdparty_dir]) env_thirdparty = env_ogg.Clone() env_thirdparty.disable_warnings() diff --git a/modules/opensimplex/SCsub b/modules/opensimplex/SCsub index 4235f6a0b9..311d33b047 100644 --- a/modules/opensimplex/SCsub +++ b/modules/opensimplex/SCsub @@ -12,7 +12,7 @@ thirdparty_sources = [ ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] -env_opensimplex.Append(CPPPATH=[thirdparty_dir]) +env_opensimplex.Prepend(CPPPATH=[thirdparty_dir]) env_thirdparty = env_opensimplex.Clone() env_thirdparty.disable_warnings() diff --git a/modules/opensimplex/doc_classes/NoiseTexture.xml b/modules/opensimplex/doc_classes/NoiseTexture.xml index 25f104b221..07d5eb27d6 100644 --- a/modules/opensimplex/doc_classes/NoiseTexture.xml +++ b/modules/opensimplex/doc_classes/NoiseTexture.xml @@ -9,26 +9,25 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="as_normalmap" type="bool" setter="set_as_normalmap" getter="is_normalmap"> - If true, the resulting texture contains a normal map created from the original noise interpreted as a bump map. + <member name="as_normalmap" type="bool" setter="set_as_normalmap" getter="is_normalmap" default="false"> + If [code]true[/code], the resulting texture contains a normal map created from the original noise interpreted as a bump map. </member> - <member name="bump_strength" type="float" setter="set_bump_strength" getter="get_bump_strength"> + <member name="bump_strength" type="float" setter="set_bump_strength" getter="get_bump_strength" default="8.0"> </member> - <member name="height" type="int" setter="set_height" getter="get_height"> + <member name="flags" type="int" setter="set_flags" getter="get_flags" override="true" default="7" /> + <member name="height" type="int" setter="set_height" getter="get_height" default="512"> Height of the generated texture. </member> <member name="noise" type="OpenSimplexNoise" setter="set_noise" getter="get_noise"> The [OpenSimplexNoise] instance used to generate the noise. </member> - <member name="seamless" type="bool" setter="set_seamless" getter="get_seamless"> + <member name="seamless" type="bool" setter="set_seamless" getter="get_seamless" default="false"> Whether the texture can be tiled without visible seams or not. Seamless textures take longer to generate. </member> - <member name="width" type="int" setter="set_width" getter="get_width"> + <member name="width" type="int" setter="set_width" getter="get_width" default="512"> Width of the generated texture. </member> </members> diff --git a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml index b5bc35df69..f3fbbab3da 100644 --- a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml +++ b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml @@ -23,8 +23,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_image"> <return type="Image"> @@ -37,6 +35,16 @@ Generate a noise image with the requested [code]width[/code] and [code]height[/code], based on the current noise parameters. </description> </method> + <method name="get_noise_1d"> + <return type="float"> + </return> + <argument index="0" name="x" type="float"> + </argument> + <description> + Returns the 1D noise value [code][-1,1][/code] at the given x-coordinate. + [b]Note:[/b] 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"> <return type="float"> </return> @@ -100,24 +108,24 @@ <argument index="0" name="size" type="int"> </argument> <description> - Generate a tileable noise image, based on the current noise parameters. Generated seamless images are always square ([code]size[/code] x [code]size[/code]). + Generate a tileable noise image, based on the current noise parameters. Generated seamless images are always square ([code]size[/code] × [code]size[/code]). </description> </method> </methods> <members> - <member name="lacunarity" type="float" setter="set_lacunarity" getter="get_lacunarity"> + <member name="lacunarity" type="float" setter="set_lacunarity" getter="get_lacunarity" default="2.0"> Difference in period between [member octaves]. </member> - <member name="octaves" type="int" setter="set_octaves" getter="get_octaves"> + <member name="octaves" type="int" setter="set_octaves" getter="get_octaves" default="3"> Number of OpenSimplex noise layers that are sampled to get the fractal noise. </member> - <member name="period" type="float" setter="set_period" getter="get_period"> + <member name="period" type="float" setter="set_period" getter="get_period" default="64.0"> Period of the base octave. A lower period results in a higher-frequency noise (more value changes across the same distance). </member> - <member name="persistence" type="float" setter="set_persistence" getter="get_persistence"> + <member name="persistence" type="float" setter="set_persistence" getter="get_persistence" default="0.5"> Contribution factor of the different octaves. A [code]persistence[/code] value of 1 means all the octaves have the same contribution, a value of 0.5 means each octave contributes half as much as the previous one. </member> - <member name="seed" type="int" setter="set_seed" getter="get_seed"> + <member name="seed" type="int" setter="set_seed" getter="get_seed" default="0"> Seed used to generate random values, different seeds will generate different noise maps. </member> </members> diff --git a/modules/opensimplex/icons/icon_noise_texture.svg b/modules/opensimplex/icons/icon_noise_texture.svg new file mode 100644 index 0000000000..5908c2b2d4 --- /dev/null +++ b/modules/opensimplex/icons/icon_noise_texture.svg @@ -0,0 +1,3 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<path d="m2 1c-0.55228 0-1 0.44772-1 1v12c0 0.55228 0.44772 1 1 1h12c0.55228 0 1-0.44772 1-1v-12c0-0.55228-0.44772-1-1-1zm1 2h10v8h-10zm3 1v2h2v-2zm2 2v2h2v2h2v-6h-2v2zm0 2h-2v-2h-2v4h4z" fill="#e0e0e0" fill-opacity=".99608"/> +</svg> diff --git a/modules/opensimplex/noise_texture.h b/modules/opensimplex/noise_texture.h index 0d00ee154d..5e4a02fcee 100644 --- a/modules/opensimplex/noise_texture.h +++ b/modules/opensimplex/noise_texture.h @@ -40,7 +40,7 @@ #include "editor/property_editor.h" class NoiseTexture : public Texture { - GDCLASS(NoiseTexture, Texture) + GDCLASS(NoiseTexture, Texture); private: Ref<Image> data; @@ -77,12 +77,12 @@ public: Ref<OpenSimplexNoise> get_noise(); void set_width(int p_width); - void set_height(int p_hieght); + void set_height(int p_height); void set_seamless(bool p_seamless); bool get_seamless(); - void set_as_normalmap(bool p_seamless); + void set_as_normalmap(bool p_as_normalmap); bool is_normalmap(); void set_bump_strength(float p_bump_strength); diff --git a/modules/opensimplex/open_simplex_noise.h b/modules/opensimplex/open_simplex_noise.h index 96885f5893..c31cbf68c3 100644 --- a/modules/opensimplex/open_simplex_noise.h +++ b/modules/opensimplex/open_simplex_noise.h @@ -38,7 +38,7 @@ #include "thirdparty/misc/open-simplex-noise.h" class OpenSimplexNoise : public Resource { - GDCLASS(OpenSimplexNoise, Resource) + GDCLASS(OpenSimplexNoise, Resource); OBJ_SAVE_TYPE(OpenSimplexNoise); osn_context contexts[6]; diff --git a/modules/opus/SCsub b/modules/opus/SCsub index b72144c679..1db5b0987e 100644 --- a/modules/opus/SCsub +++ b/modules/opus/SCsub @@ -139,7 +139,7 @@ if env['builtin_opus']: opus_sources_silk = [] if env["platform"] in ["android", "iphone", "javascript"]: - env_opus.Append(CFLAGS=["-DFIXED_POINT"]) + env_opus.Append(CPPDEFINES=["FIXED_POINT"]) opus_sources_silk = [ "silk/fixed/LTP_analysis_filter_FIX.c", "silk/fixed/LTP_scale_ctrl_FIX.c", @@ -206,9 +206,9 @@ if env['builtin_opus']: # also requires libogg if env['builtin_libogg']: - env_opus.Append(CPPPATH=["#thirdparty/libogg"]) + env_opus.Prepend(CPPPATH=["#thirdparty/libogg"]) - env_opus.Append(CFLAGS=["-DHAVE_CONFIG_H"]) + env_opus.Append(CPPDEFINES=["HAVE_CONFIG_H"]) thirdparty_include_paths = [ "", @@ -218,18 +218,18 @@ if env['builtin_opus']: "silk/fixed", "silk/float", ] - env_opus.Append(CPPPATH=[thirdparty_dir + "/" + dir for dir in thirdparty_include_paths]) + env_opus.Prepend(CPPPATH=[thirdparty_dir + "/" + dir for dir in thirdparty_include_paths]) if env["platform"] == "android": - if ("android_arch" in env and env["android_arch"] in ["armv6", "armv7"]): - env_opus.Append(CFLAGS=["-DOPUS_ARM_OPT"]) + if ("android_arch" in env and env["android_arch"] == "armv7"): + env_opus.Append(CPPDEFINES=["OPUS_ARM_OPT"]) elif ("android_arch" in env and env["android_arch"] == "arm64v8"): - env_opus.Append(CFLAGS=["-DOPUS_ARM64_OPT"]) + env_opus.Append(CPPDEFINES=["OPUS_ARM64_OPT"]) elif env["platform"] == "iphone": if ("arch" in env and env["arch"] == "arm"): - env_opus.Append(CFLAGS=["-DOPUS_ARM_OPT"]) + env_opus.Append(CPPDEFINES=["OPUS_ARM_OPT"]) elif ("arch" in env and env["arch"] == "arm64"): - env_opus.Append(CFLAGS=["-DOPUS_ARM64_OPT"]) + env_opus.Append(CPPDEFINES=["OPUS_ARM64_OPT"]) env_thirdparty = env_opus.Clone() env_thirdparty.disable_warnings() diff --git a/modules/opus/audio_stream_opus.cpp b/modules/opus/audio_stream_opus.cpp index fda82295de..43b0aecbf1 100644 --- a/modules/opus/audio_stream_opus.cpp +++ b/modules/opus/audio_stream_opus.cpp @@ -119,9 +119,7 @@ Error AudioStreamPlaybackOpus::_load_stream() { Error err; f = FileAccess::open(file, FileAccess::READ, &err); - if (err) { - ERR_FAIL_COND_V(err, err); - } + ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + file + "'."); int _err = 0; @@ -185,9 +183,7 @@ Error AudioStreamPlaybackOpus::set_file(const String &p_file) { Error err; f = FileAccess::open(file, FileAccess::READ, &err); - if (err) { - ERR_FAIL_COND_V(err, err); - } + ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + file + "'."); int _err; @@ -280,15 +276,14 @@ int AudioStreamPlaybackOpus::mix(int16_t *p_buffer, int p_frames) { int todo = p_frames; - if (todo == 0 || todo < MIN_MIX) { + if (todo < MIN_MIX) { break; } int ret = op_read(opus_file, (opus_int16 *)p_buffer, todo * stream_channels, ¤t_section); if (ret < 0) { playing = false; - ERR_EXPLAIN("Error reading Opus File: " + file); - ERR_BREAK(ret < 0); + ERR_BREAK_MSG(ret < 0, "Error reading Opus file: " + file + "."); } else if (ret == 0) { // end of song, reload? op_free(opus_file); @@ -313,7 +308,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..04c2e9d9f0 100644 --- a/modules/opus/audio_stream_opus.h +++ b/modules/opus/audio_stream_opus.h @@ -43,7 +43,7 @@ class AudioStreamPlaybackOpus : public AudioStreamPlayback { - GDCLASS(AudioStreamPlaybackOpus, AudioStreamPlayback) + GDCLASS(AudioStreamPlaybackOpus, AudioStreamPlayback); enum { MIN_MIX = 1024 @@ -117,7 +117,7 @@ public: class AudioStreamOpus : public AudioStream { - GDCLASS(AudioStreamOpus, AudioStream) + GDCLASS(AudioStreamOpus, AudioStream); String file; @@ -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/SCsub b/modules/pvr/SCsub index 2e4a792a36..18da38fbbd 100644 --- a/modules/pvr/SCsub +++ b/modules/pvr/SCsub @@ -17,7 +17,7 @@ thirdparty_sources = [ ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] -env_pvr.Append(CPPPATH=[thirdparty_dir]) +env_pvr.Prepend(CPPPATH=[thirdparty_dir]) env_thirdparty = env_pvr.Clone() env_thirdparty.disable_warnings() diff --git a/modules/pvr/texture_loader_pvr.cpp b/modules/pvr/texture_loader_pvr.cpp index 82f323e8cf..cf6b396180 100644 --- a/modules/pvr/texture_loader_pvr.cpp +++ b/modules/pvr/texture_loader_pvr.cpp @@ -149,11 +149,10 @@ RES ResourceFormatPVR::load(const String &p_path, const String &p_original_path, format = Image::FORMAT_ETC; break; default: - ERR_EXPLAIN("Unsupported format in PVR texture: " + itos(flags & 0xFF)); - ERR_FAIL_V(RES()); + ERR_FAIL_V_MSG(RES(), "Unsupported format in PVR texture: " + itos(flags & 0xFF) + "."); } - w = PoolVector<uint8_t>::Write(); + w.release(); int tex_flags = Texture::FLAG_FILTER | Texture::FLAG_REPEAT; @@ -192,9 +191,9 @@ static void _compress_pvrtc4(Image *p_img) { Ref<Image> img = p_img->duplicate(); bool make_mipmaps = false; - if (img->get_width() % 8 || img->get_height() % 8) { + if (!img->is_size_po2() || img->get_width() != img->get_height()) { make_mipmaps = img->has_mipmaps(); - img->resize(img->get_width() + (8 - (img->get_width() % 8)), img->get_height() + (8 - (img->get_height() % 8))); + img->resize_to_po2(true); } img->convert(Image::FORMAT_RGBA8); if (!img->has_mipmaps() && make_mipmaps) @@ -204,7 +203,7 @@ static void _compress_pvrtc4(Image *p_img) { Ref<Image> new_img; new_img.instance(); - new_img->create(img->get_width(), img->get_height(), true, use_alpha ? Image::FORMAT_PVRTC4A : Image::FORMAT_PVRTC4); + new_img->create(img->get_width(), img->get_height(), img->has_mipmaps(), use_alpha ? Image::FORMAT_PVRTC4A : Image::FORMAT_PVRTC4); PoolVector<uint8_t> data = new_img->get_data(); { @@ -221,7 +220,6 @@ static void _compress_pvrtc4(Image *p_img) { /* red and Green colors are swapped. */ new (dp) Javelin::ColorRgba<unsigned char>(r[ofs + 4 * j + 2], r[ofs + 4 * j + 1], r[ofs + 4 * j], r[ofs + 4 * j + 3]); } - new_img->get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h); Javelin::PvrTcEncoder::EncodeRgba4Bpp(&wr[ofs], bm); } @@ -656,8 +654,8 @@ static void _pvrtc_decompress(Image *p_img) { decompress_pvrtc((PVRTCBlock *)r.ptr(), _2bit, p_img->get_width(), p_img->get_height(), 0, (unsigned char *)w.ptr()); - w = PoolVector<uint8_t>::Write(); - r = PoolVector<uint8_t>::Read(); + w.release(); + r.release(); bool make_mipmaps = p_img->has_mipmaps(); p_img->create(p_img->get_width(), p_img->get_height(), false, Image::FORMAT_RGBA8, newdata); 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/SCsub b/modules/recast/SCsub index 4a06653968..94d9968164 100644 --- a/modules/recast/SCsub +++ b/modules/recast/SCsub @@ -23,7 +23,7 @@ if env['builtin_recast']: ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - env_recast.Append(CPPPATH=[thirdparty_dir + "/Include"]) + env_recast.Prepend(CPPPATH=[thirdparty_dir + "/Include"]) env_thirdparty = env_recast.Clone() env_thirdparty.disable_warnings() diff --git a/modules/recast/navigation_mesh_editor_plugin.cpp b/modules/recast/navigation_mesh_editor_plugin.cpp index a068f3b0f9..9f30806925 100644 --- a/modules/recast/navigation_mesh_editor_plugin.cpp +++ b/modules/recast/navigation_mesh_editor_plugin.cpp @@ -54,28 +54,26 @@ void NavigationMeshEditor::_notification(int p_option) { } void NavigationMeshEditor::_bake_pressed() { + button_bake->set_pressed(false); ERR_FAIL_COND(!node); const String conf_warning = node->get_configuration_warning(); if (!conf_warning.empty()) { err_dialog->set_text(conf_warning); err_dialog->popup_centered_minsize(); - button_bake->set_pressed(false); return; } - NavigationMeshGenerator::clear(node->get_navigation_mesh()); - NavigationMeshGenerator::bake(node->get_navigation_mesh(), node); + 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() { if (node) - NavigationMeshGenerator::clear(node->get_navigation_mesh()); + EditorNavigationMeshGenerator::get_singleton()->clear(node->get_navigation_mesh()); button_bake->set_pressed(false); bake_info->set_text(""); diff --git a/modules/recast/navigation_mesh_generator.cpp b/modules/recast/navigation_mesh_generator.cpp index 80e98a13a5..b668085f90 100644 --- a/modules/recast/navigation_mesh_generator.cpp +++ b/modules/recast/navigation_mesh_generator.cpp @@ -29,15 +29,40 @@ /*************************************************************************/ #include "navigation_mesh_generator.h" - -void NavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> &p_verticies) { +#include "core/math/quick_hull.h" +#include "core/os/thread.h" +#include "editor/editor_settings.h" +#include "scene/3d/collision_shape.h" +#include "scene/3d/mesh_instance.h" +#include "scene/3d/physics_body.h" +#include "scene/resources/box_shape.h" +#include "scene/resources/capsule_shape.h" +#include "scene/resources/concave_polygon_shape.h" +#include "scene/resources/convex_polygon_shape.h" +#include "scene/resources/cylinder_shape.h" +#include "scene/resources/plane_shape.h" +#include "scene/resources/primitive_meshes.h" +#include "scene/resources/shape.h" +#include "scene/resources/sphere_shape.h" + +#ifdef MODULE_CSG_ENABLED +#include "modules/csg/csg_shape.h" +#endif + +#ifdef MODULE_GRIDMAP_ENABLED +#include "modules/gridmap/grid_map.h" +#endif + +EditorNavigationMeshGenerator *EditorNavigationMeshGenerator::singleton = NULL; + +void EditorNavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> &p_verticies) { p_verticies.push_back(p_vec3.x); p_verticies.push_back(p_vec3.y); p_verticies.push_back(p_vec3.z); } -void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices) { - int current_vertex_count = 0; +void EditorNavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices) { + int current_vertex_count; for (int i = 0; i < p_mesh->get_surface_count(); i++) { current_vertex_count = p_verticies.size() / 3; @@ -91,23 +116,161 @@ void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform } } -void NavigationMeshGenerator::_parse_geometry(const Transform &p_base_inverse, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices) { +void EditorNavigationMeshGenerator::_add_faces(const PoolVector3Array &p_faces, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices) { + int face_count = p_faces.size() / 3; + int current_vertex_count = p_verticies.size() / 3; + + for (int j = 0; j < face_count; j++) { + _add_vertex(p_xform.xform(p_faces[j * 3 + 0]), p_verticies); + _add_vertex(p_xform.xform(p_faces[j * 3 + 1]), p_verticies); + _add_vertex(p_xform.xform(p_faces[j * 3 + 2]), p_verticies); + + p_indices.push_back(current_vertex_count + (j * 3 + 0)); + p_indices.push_back(current_vertex_count + (j * 3 + 2)); + p_indices.push_back(current_vertex_count + (j * 3 + 1)); + } +} - if (Object::cast_to<MeshInstance>(p_node)) { +void EditorNavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices, int p_generate_from, uint32_t p_collision_mask, bool p_recurse_children) { + + if (Object::cast_to<MeshInstance>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) { MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(p_node); Ref<Mesh> mesh = mesh_instance->get_mesh(); if (mesh.is_valid()) { - _add_mesh(mesh, p_base_inverse * mesh_instance->get_global_transform(), p_verticies, p_indices); + _add_mesh(mesh, p_accumulated_transform * mesh_instance->get_transform(), p_verticies, p_indices); + } + } + +#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); + + if (static_body->get_collision_layer() & p_collision_mask) { + + for (int i = 0; i < p_node->get_child_count(); ++i) { + Node *child = p_node->get_child(i); + if (Object::cast_to<CollisionShape>(child)) { + CollisionShape *col_shape = Object::cast_to<CollisionShape>(child); + + Transform transform = p_accumulated_transform * static_body->get_transform() * col_shape->get_transform(); + + Ref<Mesh> mesh; + Ref<Shape> s = col_shape->get_shape(); + + BoxShape *box = Object::cast_to<BoxShape>(*s); + if (box) { + Ref<CubeMesh> cube_mesh; + cube_mesh.instance(); + cube_mesh->set_size(box->get_extents() * 2.0); + mesh = cube_mesh; + } + + CapsuleShape *capsule = Object::cast_to<CapsuleShape>(*s); + if (capsule) { + Ref<CapsuleMesh> capsule_mesh; + capsule_mesh.instance(); + capsule_mesh->set_radius(capsule->get_radius()); + capsule_mesh->set_mid_height(capsule->get_height() / 2.0); + mesh = capsule_mesh; + } + + CylinderShape *cylinder = Object::cast_to<CylinderShape>(*s); + if (cylinder) { + Ref<CylinderMesh> cylinder_mesh; + cylinder_mesh.instance(); + cylinder_mesh->set_height(cylinder->get_height()); + cylinder_mesh->set_bottom_radius(cylinder->get_radius()); + cylinder_mesh->set_top_radius(cylinder->get_radius()); + mesh = cylinder_mesh; + } + + SphereShape *sphere = Object::cast_to<SphereShape>(*s); + if (sphere) { + Ref<SphereMesh> sphere_mesh; + sphere_mesh.instance(); + sphere_mesh->set_radius(sphere->get_radius()); + sphere_mesh->set_height(sphere->get_radius() * 2.0); + mesh = sphere_mesh; + } + + ConcavePolygonShape *concave_polygon = Object::cast_to<ConcavePolygonShape>(*s); + if (concave_polygon) { + _add_faces(concave_polygon->get_faces(), transform, p_verticies, p_indices); + } + + ConvexPolygonShape *convex_polygon = Object::cast_to<ConvexPolygonShape>(*s); + if (convex_polygon) { + Vector<Vector3> varr = Variant(convex_polygon->get_points()); + Geometry::MeshData md; + + Error err = QuickHull::build(varr, md); + + if (err == OK) { + PoolVector3Array faces; + + for (int j = 0; j < md.faces.size(); ++j) { + Geometry::MeshData::Face face = md.faces[j]; + + for (int k = 2; k < face.indices.size(); ++k) { + faces.push_back(md.vertices[face.indices[0]]); + faces.push_back(md.vertices[face.indices[k - 1]]); + faces.push_back(md.vertices[face.indices[k]]); + } + } + + _add_faces(faces, transform, p_verticies, p_indices); + } + } + + if (mesh.is_valid()) { + _add_mesh(mesh, transform, p_verticies, p_indices); + } + } + } + } + } + +#ifdef MODULE_GRIDMAP_ENABLED + if (Object::cast_to<GridMap>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) { + GridMap *gridmap_instance = Object::cast_to<GridMap>(p_node); + Array meshes = gridmap_instance->get_meshes(); + Transform xform = gridmap_instance->get_transform(); + for (int i = 0; i < meshes.size(); i += 2) { + Ref<Mesh> mesh = meshes[i + 1]; + if (mesh.is_valid()) { + _add_mesh(mesh, p_accumulated_transform * xform * meshes[i], p_verticies, p_indices); + } } } +#endif - for (int i = 0; i < p_node->get_child_count(); i++) { - _parse_geometry(p_base_inverse, p_node->get_child(i), p_verticies, p_indices); + if (Object::cast_to<Spatial>(p_node)) { + Spatial *spatial = Object::cast_to<Spatial>(p_node); + p_accumulated_transform = p_accumulated_transform * spatial->get_transform(); + } + + if (p_recurse_children) { + for (int i = 0; i < p_node->get_child_count(); i++) { + _parse_geometry(p_accumulated_transform, p_node->get_child(i), p_verticies, p_indices, p_generate_from, p_collision_mask, p_recurse_children); + } } } -void NavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh) { +void EditorNavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh) { PoolVector<Vector3> nav_vertices; @@ -126,15 +289,16 @@ void NavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(con for (unsigned int j = 0; j < ntris; j++) { Vector<int> nav_indices; nav_indices.resize(3); + // Polygon order in recast is opposite than godot's nav_indices.write[0] = ((int)(bverts + tris[j * 4 + 0])); - nav_indices.write[1] = ((int)(bverts + tris[j * 4 + 1])); - nav_indices.write[2] = ((int)(bverts + tris[j * 4 + 2])); + nav_indices.write[1] = ((int)(bverts + tris[j * 4 + 2])); + nav_indices.write[2] = ((int)(bverts + tris[j * 4 + 1])); p_nav_mesh->add_polygon(nav_indices); } } } -void NavigationMeshGenerator::_build_recast_navigation_mesh(Ref<NavigationMesh> p_nav_mesh, EditorProgress *ep, +void EditorNavigationMeshGenerator::_build_recast_navigation_mesh(Ref<NavigationMesh> p_nav_mesh, EditorProgress *ep, rcHeightfield *hf, rcCompactHeightfield *chf, rcContourSet *cset, rcPolyMesh *poly_mesh, rcPolyMeshDetail *detail_mesh, Vector<float> &vertices, Vector<int> &indices) { rcContext ctx; @@ -256,7 +420,18 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh(Ref<NavigationMesh> detail_mesh = 0; } -void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) { +EditorNavigationMeshGenerator *EditorNavigationMeshGenerator::get_singleton() { + return singleton; +} + +EditorNavigationMeshGenerator::EditorNavigationMeshGenerator() { + singleton = this; +} + +EditorNavigationMeshGenerator::~EditorNavigationMeshGenerator() { +} + +void EditorNavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) { ERR_FAIL_COND(!p_nav_mesh.is_valid()); @@ -266,7 +441,21 @@ void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) Vector<float> vertices; Vector<int> indices; - _parse_geometry(Object::cast_to<Spatial>(p_node)->get_global_transform().affine_inverse(), p_node, vertices, indices); + List<Node *> parse_nodes; + + if (p_nav_mesh->get_source_geometry_mode() == NavigationMesh::SOURCE_GEOMETRY_NAVMESH_CHILDREN) { + parse_nodes.push_back(p_node); + } else { + p_node->get_tree()->get_nodes_in_group(p_nav_mesh->get_source_group_name(), &parse_nodes); + } + + Transform navmesh_xform = Object::cast_to<Spatial>(p_node)->get_transform().affine_inverse(); + for (const List<Node *>::Element *E = parse_nodes.front(); E; E = E->next()) { + int geometry_type = p_nav_mesh->get_parsed_geometry_type(); + uint32_t collision_mask = p_nav_mesh->get_collision_mask(); + bool recurse_children = p_nav_mesh->get_source_geometry_mode() != NavigationMesh::SOURCE_GEOMETRY_GROUPS_EXPLICIT; + _parse_geometry(navmesh_xform, E->get(), vertices, indices, geometry_type, collision_mask, recurse_children); + } if (vertices.size() > 0 && indices.size() > 0) { @@ -296,9 +485,14 @@ void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) ep.step(TTR("Done!"), 11); } -void NavigationMeshGenerator::clear(Ref<NavigationMesh> p_nav_mesh) { +void EditorNavigationMeshGenerator::clear(Ref<NavigationMesh> p_nav_mesh) { if (p_nav_mesh.is_valid()) { p_nav_mesh->clear_polygons(); p_nav_mesh->set_vertices(PoolVector<Vector3>()); } } + +void EditorNavigationMeshGenerator::_bind_methods() { + ClassDB::bind_method(D_METHOD("bake", "nav_mesh", "root_node"), &EditorNavigationMeshGenerator::bake); + ClassDB::bind_method(D_METHOD("clear", "nav_mesh"), &EditorNavigationMeshGenerator::clear); +} diff --git a/modules/recast/navigation_mesh_generator.h b/modules/recast/navigation_mesh_generator.h index 3adc01ccda..f19622a4a9 100644 --- a/modules/recast/navigation_mesh_generator.h +++ b/modules/recast/navigation_mesh_generator.h @@ -31,20 +31,23 @@ #ifndef NAVIGATION_MESH_GENERATOR_H #define NAVIGATION_MESH_GENERATOR_H -#include "core/os/thread.h" #include "editor/editor_node.h" -#include "editor/editor_settings.h" -#include "scene/3d/mesh_instance.h" #include "scene/3d/navigation_mesh.h" -#include "scene/resources/shape.h" #include <Recast.h> -class NavigationMeshGenerator { +class EditorNavigationMeshGenerator : public Object { + GDCLASS(EditorNavigationMeshGenerator, Object); + + static EditorNavigationMeshGenerator *singleton; + protected: + static void _bind_methods(); + static void _add_vertex(const Vector3 &p_vec3, Vector<float> &p_verticies); static void _add_mesh(const Ref<Mesh> &p_mesh, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices); - static void _parse_geometry(const Transform &p_base_inverse, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices); + static void _add_faces(const PoolVector3Array &p_faces, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices); + static void _parse_geometry(Transform p_accumulated_transform, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices, int p_generate_from, uint32_t p_collision_mask, bool p_recurse_children); static void _convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh); static void _build_recast_navigation_mesh(Ref<NavigationMesh> p_nav_mesh, EditorProgress *ep, @@ -52,8 +55,13 @@ protected: rcPolyMeshDetail *detail_mesh, Vector<float> &vertices, Vector<int> &indices); public: - static void bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node); - static void clear(Ref<NavigationMesh> p_nav_mesh); + static EditorNavigationMeshGenerator *get_singleton(); + + EditorNavigationMeshGenerator(); + ~EditorNavigationMeshGenerator(); + + void bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node); + void clear(Ref<NavigationMesh> p_nav_mesh); }; #endif // NAVIGATION_MESH_GENERATOR_H diff --git a/modules/recast/register_types.cpp b/modules/recast/register_types.cpp index f272cc4236..44129fbb61 100644 --- a/modules/recast/register_types.cpp +++ b/modules/recast/register_types.cpp @@ -32,8 +32,30 @@ #include "navigation_mesh_editor_plugin.h" +#ifdef TOOLS_ENABLED +EditorNavigationMeshGenerator *_nav_mesh_generator = NULL; +#endif + void register_recast_types() { +#ifdef TOOLS_ENABLED EditorPlugins::add_by_type<NavigationMeshEditorPlugin>(); + _nav_mesh_generator = memnew(EditorNavigationMeshGenerator); + + ClassDB::APIType prev_api = ClassDB::get_current_api(); + ClassDB::set_current_api(ClassDB::API_EDITOR); + + ClassDB::register_class<EditorNavigationMeshGenerator>(); + + ClassDB::set_current_api(prev_api); + + Engine::get_singleton()->add_singleton(Engine::Singleton("NavigationMeshGenerator", EditorNavigationMeshGenerator::get_singleton())); +#endif } -void unregister_recast_types() {} +void unregister_recast_types() { +#ifdef TOOLS_ENABLED + if (_nav_mesh_generator) { + memdelete(_nav_mesh_generator); + } +#endif +} diff --git a/modules/regex/SCsub b/modules/regex/SCsub index 99c25add45..6238cd3d9f 100644 --- a/modules/regex/SCsub +++ b/modules/regex/SCsub @@ -6,13 +6,11 @@ Import('env_modules') env_regex = env_modules.Clone() if env['builtin_pcre2']: - jit_blacklist = ['javascript', 'uwp'] - thirdparty_dir = '#thirdparty/pcre2/src/' - thirdparty_flags = ['-DPCRE2_STATIC', '-DHAVE_CONFIG_H'] + thirdparty_flags = ['PCRE2_STATIC', 'HAVE_CONFIG_H'] - if 'platform' in env and env['platform'] not in jit_blacklist: - thirdparty_flags.append('-DSUPPORT_JIT') + if env['builtin_pcre2_with_jit']: + thirdparty_flags.append('SUPPORT_JIT') thirdparty_sources = [ "pcre2_auto_possess.c", @@ -33,6 +31,7 @@ if env['builtin_pcre2']: "pcre2_newline.c", "pcre2_ord2utf.c", "pcre2_pattern_info.c", + "pcre2_script_run.c", "pcre2_serialize.c", "pcre2_string_utils.c", "pcre2_study.c", @@ -46,18 +45,18 @@ if env['builtin_pcre2']: thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - env_regex.Append(CPPPATH=[thirdparty_dir]) - env_regex.Append(CPPFLAGS=thirdparty_flags) + env_regex.Prepend(CPPPATH=[thirdparty_dir]) + env_regex.Append(CPPDEFINES=thirdparty_flags) def pcre2_builtin(width): env_pcre2 = env_regex.Clone() env_pcre2.disable_warnings() env_pcre2["OBJSUFFIX"] = "_" + width + env_pcre2["OBJSUFFIX"] env_pcre2.add_source_files(env.modules_sources, thirdparty_sources) - env_pcre2.Append(CPPFLAGS=["-DPCRE2_CODE_UNIT_WIDTH=" + width]) + env_pcre2.Append(CPPDEFINES=[("PCRE2_CODE_UNIT_WIDTH", width)]) pcre2_builtin("16") pcre2_builtin("32") -env_regex.Append(CPPFLAGS=["-DPCRE2_CODE_UNIT_WIDTH=0"]) +env_regex.Append(CPPDEFINES=[("PCRE2_CODE_UNIT_WIDTH", 0)]) env_regex.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/regex/doc_classes/RegEx.xml b/modules/regex/doc_classes/RegEx.xml index 20857572f3..74b06039d4 100644 --- a/modules/regex/doc_classes/RegEx.xml +++ b/modules/regex/doc_classes/RegEx.xml @@ -4,7 +4,7 @@ Class for searching text for patterns using regular expressions. </brief_description> <description> - Regular Expression (or regex) is a compact programming language that can be used to recognise strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For instance, a regex of [code]ab[0-9][/code] would find any string that is [code]ab[/code] followed by any number from [code]0[/code] to [code]9[/code]. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet. + A regular expression (or regex) is a compact language that can be used to recognise strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For instance, a regex of [code]ab[0-9][/code] would find any string that is [code]ab[/code] followed by any number from [code]0[/code] to [code]9[/code]. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet. To begin, the RegEx object needs to be compiled with the search pattern using [method compile] before it can be used. [codeblock] var regex = RegEx.new() @@ -19,7 +19,7 @@ if result: print(result.get_string()) # Would print n-0123 [/codeblock] - The results of capturing groups [code]()[/code] can be retrieved by passing the group number to the various functions in [RegExMatch]. Group 0 is the default and would always refer to the entire pattern. In the above example, calling [code]result.get_string(1)[/code] would give you [code]0123[/code]. + The results of capturing groups [code]()[/code] can be retrieved by passing the group number to the various functions in [RegExMatch]. Group 0 is the default and will always refer to the entire pattern. In the above example, calling [code]result.get_string(1)[/code] would give you [code]0123[/code]. This version of RegEx also supports named capturing groups, and the names can be used to retrieve the results. If two or more groups have the same name, the name would only refer to the first one with a match. [codeblock] var regex = RegEx.new() @@ -28,7 +28,7 @@ if result: print(result.get_string("digit")) # Would print 2f [/codeblock] - If you need to process multiple results, [method search_all] generates a list of all non-overlapping results. This can be combined with a for-loop for convenience. + If you need to process multiple results, [method search_all] generates a list of all non-overlapping results. This can be combined with a [code]for[/code] loop for convenience. [codeblock] for result in regex.search_all("d01, d03, d0c, x3f and x42"): print(result.get_string("digit")) @@ -38,14 +38,12 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="clear"> <return type="void"> </return> <description> - This method resets the state of the object, as it was freshly created. Namely, it unassigns the regular expression of this object. + This method resets the state of the object, as if it was freshly created. Namely, it unassigns the regular expression of this object. </description> </method> <method name="compile"> @@ -54,7 +52,7 @@ <argument index="0" name="pattern" type="String"> </argument> <description> - Compiles and assign the search pattern to use. Returns OK if the compilation is successful. If an error is encountered the details are printed to STDOUT and FAILED is returned. + Compiles and assign the search pattern to use. Returns [constant OK] if the compilation is successful. If an error is encountered, details are printed to standard output and an error is returned. </description> </method> <method name="get_group_count" qualifiers="const"> @@ -95,7 +93,7 @@ <argument index="2" name="end" type="int" default="-1"> </argument> <description> - Searches the text for the compiled pattern. Returns a [RegExMatch] container of the first matching result if found, otherwise null. The region to search within can be specified without modifying where the start and end anchor would be. + Searches the text for the compiled pattern. Returns a [RegExMatch] container of the first matching result if found, otherwise [code]null[/code]. The region to search within can be specified without modifying where the start and end anchor would be. </description> </method> <method name="search_all" qualifiers="const"> @@ -108,7 +106,7 @@ <argument index="2" name="end" type="int" default="-1"> </argument> <description> - Searches the text for the compiled pattern. Returns an array of [RegExMatch] containers for each non-overlapping result. If no results were found an empty array is returned instead. The region to search within can be specified without modifying where the start and end anchor would be. + Searches the text for the compiled pattern. Returns an array of [RegExMatch] containers for each non-overlapping result. If no results were found, an empty array is returned instead. The region to search within can be specified without modifying where the start and end anchor would be. </description> </method> <method name="sub" qualifiers="const"> @@ -125,7 +123,7 @@ <argument index="4" name="end" type="int" default="-1"> </argument> <description> - Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as [code]\1[/code] and [code]\g<name>[/code] expanded and resolved. By default only the first instance is replaced but it can be changed for all instances (global replacement). The region to search within can be specified without modifying where the start and end anchor would be. + Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as [code]$1[/code] and [code]$name[/code] are expanded and resolved. By default, only the first instance is replaced, but it can be changed for all instances (global replacement). The region to search within can be specified without modifying where the start and end anchor would be. </description> </method> </methods> diff --git a/modules/regex/doc_classes/RegExMatch.xml b/modules/regex/doc_classes/RegExMatch.xml index 9efec91bdc..6dec9fc516 100644 --- a/modules/regex/doc_classes/RegExMatch.xml +++ b/modules/regex/doc_classes/RegExMatch.xml @@ -1,15 +1,13 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="RegExMatch" inherits="Reference" category="Core" version="3.2"> <brief_description> - Contains the results of a regex search. + Contains the results of a [RegEx] search. </brief_description> <description> - Contains the results of a single regex match returned by [method RegEx.search] and [method RegEx.search_all]. It can be used to find the position and range of the match and its capturing groups, and it can extract its sub-string for you. + Contains the results of a single [RegEx] match returned by [method RegEx.search] and [method RegEx.search_all]. It can be used to find the position and range of the match and its capturing groups, and it can extract its substring for you. </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_end" qualifiers="const"> <return type="int"> @@ -50,13 +48,13 @@ </method> </methods> <members> - <member name="names" type="Dictionary" setter="" getter="get_names"> + <member name="names" type="Dictionary" setter="" getter="get_names" default="{}"> A dictionary of named groups and its corresponding group number. Only groups with that were matched are included. If multiple groups have the same name, that name would refer to the first matching one. </member> - <member name="strings" type="Array" setter="" getter="get_strings"> + <member name="strings" type="Array" setter="" getter="get_strings" default="[ ]"> An [Array] of the match and its capturing groups. </member> - <member name="subject" type="String" setter="" getter="get_subject"> + <member name="subject" type="String" setter="" getter="get_subject" default=""""> The source string used with the search pattern to find this matching result. </member> </members> diff --git a/modules/squish/SCsub b/modules/squish/SCsub index 3be85a1efa..15320bcd0c 100644 --- a/modules/squish/SCsub +++ b/modules/squish/SCsub @@ -22,7 +22,7 @@ if env['builtin_squish']: thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - env_squish.Append(CPPPATH=[thirdparty_dir]) + env_squish.Prepend(CPPPATH=[thirdparty_dir]) env_thirdparty = env_squish.Clone() env_thirdparty.disable_warnings() diff --git a/modules/squish/image_compress_squish.cpp b/modules/squish/image_compress_squish.cpp index d89839f06a..9b0a55eae3 100644 --- a/modules/squish/image_compress_squish.cpp +++ b/modules/squish/image_compress_squish.cpp @@ -57,8 +57,7 @@ void image_decompress_squish(Image *p_image) { } else if (p_image->get_format() == Image::FORMAT_RGTC_RG) { squish_flags = squish::kBc5; } else { - ERR_EXPLAIN("Squish: Can't decompress unknown format: " + itos(p_image->get_format())); - ERR_FAIL_COND(true); + ERR_FAIL_MSG("Squish: Can't decompress unknown format: " + itos(p_image->get_format()) + "."); return; } @@ -119,7 +118,8 @@ void image_compress_squish(Image *p_image, float p_lossy_quality, Image::Compres case Image::FORMAT_RGBA5551: { dc = Image::DETECTED_RGBA; } break; - default: {} + default: { + } } } @@ -197,8 +197,8 @@ void image_compress_squish(Image *p_image, float p_lossy_quality, Image::Compres h = MAX(h / 2, 1); } - rb = PoolVector<uint8_t>::Read(); - wb = PoolVector<uint8_t>::Write(); + rb.release(); + wb.release(); p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data); } diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp index 292ac5e97e..10097316ec 100644 --- a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp +++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp @@ -188,7 +188,7 @@ void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) { ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar.ptr(), src_data_len, &error, &ogg_alloc); if (!ogg_stream && error == VORBIS_outofmem) { - w = PoolVector<char>::Write(); + w.release(); alloc_try *= 2; } else { @@ -266,13 +266,14 @@ void AudioStreamOGGVorbis::_bind_methods() { ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOGGVorbis::get_loop_offset); ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop", "has_loop"); - ADD_PROPERTY(PropertyInfo(Variant::REAL, "loop_offset", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop_offset", "get_loop_offset"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop"), "set_loop", "has_loop"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "loop_offset"), "set_loop_offset", "get_loop_offset"); } AudioStreamOGGVorbis::AudioStreamOGGVorbis() { data = NULL; + data_len = 0; length = 0; sample_rate = 1; channels = 1; diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.h b/modules/stb_vorbis/audio_stream_ogg_vorbis.h index cbff9d47bb..c8c179554a 100644 --- a/modules/stb_vorbis/audio_stream_ogg_vorbis.h +++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.h @@ -40,7 +40,7 @@ class AudioStreamOGGVorbis; class AudioStreamPlaybackOGGVorbis : public AudioStreamPlaybackResampled { - GDCLASS(AudioStreamPlaybackOGGVorbis, AudioStreamPlaybackResampled) + GDCLASS(AudioStreamPlaybackOGGVorbis, AudioStreamPlaybackResampled); stb_vorbis *ogg_stream; stb_vorbis_alloc ogg_alloc; @@ -72,7 +72,7 @@ public: class AudioStreamOGGVorbis : public AudioStream { - GDCLASS(AudioStreamOGGVorbis, AudioStream) + GDCLASS(AudioStreamOGGVorbis, AudioStream); OBJ_SAVE_TYPE(AudioStream) //children are all saved as AudioStream, so they can be exchanged RES_BASE_EXTENSION("oggstr"); 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/doc_classes/AudioStreamOGGVorbis.xml b/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml index 574ff1ff2a..9403199398 100644 --- a/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml +++ b/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml @@ -8,17 +8,15 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="data" type="PoolByteArray" setter="set_data" getter="get_data"> + <member name="data" type="PoolByteArray" setter="set_data" getter="get_data" default="PoolByteArray( )"> Contains the audio data in bytes. </member> - <member name="loop" type="bool" setter="set_loop" getter="has_loop"> + <member name="loop" type="bool" setter="set_loop" getter="has_loop" default="false"> </member> - <member name="loop_offset" type="float" setter="set_loop_offset" getter="get_loop_offset"> + <member name="loop_offset" type="float" setter="set_loop_offset" getter="get_loop_offset" default="0.0"> </member> </members> <constants> 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/stb_vorbis/resource_importer_ogg_vorbis.cpp b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp index 7254f57672..977ff064bc 100644 --- a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp +++ b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp @@ -82,9 +82,8 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin float loop_offset = p_options["loop_offset"]; FileAccess *f = FileAccess::open(p_source_file, FileAccess::READ); - if (!f) { - ERR_FAIL_COND_V(!f, ERR_CANT_OPEN); - } + + ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot open file '" + p_source_file + "'."); size_t len = f->get_len(); diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.h b/modules/stb_vorbis/resource_importer_ogg_vorbis.h index d3d0574d56..8e4fbde916 100644 --- a/modules/stb_vorbis/resource_importer_ogg_vorbis.h +++ b/modules/stb_vorbis/resource_importer_ogg_vorbis.h @@ -35,7 +35,8 @@ #include "core/io/resource_importer.h" class ResourceImporterOGGVorbis : public ResourceImporter { - GDCLASS(ResourceImporterOGGVorbis, ResourceImporter) + GDCLASS(ResourceImporterOGGVorbis, ResourceImporter); + public: virtual String get_importer_name() const; virtual String get_visible_name() const; diff --git a/modules/svg/SCsub b/modules/svg/SCsub index 22f0b1e3eb..9324c1634b 100644 --- a/modules/svg/SCsub +++ b/modules/svg/SCsub @@ -12,11 +12,11 @@ thirdparty_sources = [ ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] -env_svg.Append(CPPPATH=[thirdparty_dir]) +env_svg.Prepend(CPPPATH=[thirdparty_dir]) # FIXME: Needed in editor/editor_themes.cpp for now, but ideally there # shouldn't be a dependency on modules/ and its own 3rd party deps. -env.Append(CPPPATH=[thirdparty_dir]) -env.Append(CCFLAGS=["-DSVG_ENABLED"]) +env.Prepend(CPPPATH=[thirdparty_dir]) +env.Append(CPPDEFINES=["SVG_ENABLED"]) env_thirdparty = env_svg.Clone() env_thirdparty.disable_warnings() diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp index e36844a1bc..a2ef88d130 100644 --- a/modules/svg/image_loader_svg.cpp +++ b/modules/svg/image_loader_svg.cpp @@ -109,12 +109,10 @@ Error ImageLoaderSVG::_create_image(Ref<Image> p_image, const PoolVector<uint8_t float upscale = upsample ? 2.0 : 1.0; int w = (int)(svg_image->width * p_scale * upscale); - ERR_EXPLAIN(vformat("Can't create image from SVG with scale %s, the resulting image size exceeds max width.", rtos(p_scale))); - ERR_FAIL_COND_V(w > Image::MAX_WIDTH, ERR_PARAMETER_RANGE_ERROR); + ERR_FAIL_COND_V_MSG(w > Image::MAX_WIDTH, ERR_PARAMETER_RANGE_ERROR, vformat("Can't create image from SVG with scale %s, the resulting image size exceeds max width.", rtos(p_scale))); int h = (int)(svg_image->height * p_scale * upscale); - ERR_EXPLAIN(vformat("Can't create image from SVG with scale %s, the resulting image size exceeds max height.", rtos(p_scale))); - ERR_FAIL_COND_V(h > Image::MAX_HEIGHT, ERR_PARAMETER_RANGE_ERROR); + ERR_FAIL_COND_V_MSG(h > Image::MAX_HEIGHT, ERR_PARAMETER_RANGE_ERROR, vformat("Can't create image from SVG with scale %s, the resulting image size exceeds max height.", rtos(p_scale))); PoolVector<uint8_t> dst_image; dst_image.resize(w * h * 4); @@ -123,7 +121,7 @@ Error ImageLoaderSVG::_create_image(Ref<Image> p_image, const PoolVector<uint8_t rasterizer.rasterize(svg_image, 0, 0, p_scale * upscale, (unsigned char *)dw.ptr(), w, h, w * 4); - dw = PoolVector<uint8_t>::Write(); + dw.release(); p_image->create(w, h, false, Image::FORMAT_RGBA8, dst_image); if (upsample) p_image->shrink_x2(); diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp index 419229677b..6ee408d472 100644 --- a/modules/tga/image_loader_tga.cpp +++ b/modules/tga/image_loader_tga.cpp @@ -148,9 +148,11 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff uint8_t a = 0xff; if (p_header.color_map_depth == 24) { - r = (p_palette[(index * 3) + 0]); + // Due to low-high byte order, the color table must be + // read in the same order as image data (little endian) + r = (p_palette[(index * 3) + 2]); g = (p_palette[(index * 3) + 1]); - b = (p_palette[(index * 3) + 2]); + b = (p_palette[(index * 3) + 0]); } else { return ERR_INVALID_DATA; } @@ -197,7 +199,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff } } - image_data_w = PoolVector<uint8_t>::Write(); + image_data_w.release(); p_image->create(width, height, 0, Image::FORMAT_RGBA8, image_data); diff --git a/modules/thekla_unwrap/SCsub b/modules/thekla_unwrap/SCsub deleted file mode 100644 index c47c760d5f..0000000000 --- a/modules/thekla_unwrap/SCsub +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python - -import platform - -Import('env') -Import('env_modules') - -env_thekla_unwrap = env_modules.Clone() - -# Thirdparty source files -if env['builtin_thekla_atlas']: - thirdparty_dir = "#thirdparty/thekla_atlas/" - thirdparty_sources = [ - "nvcore/Memory.cpp", - "nvcore/Debug.cpp", - "nvcore/StrLib.cpp", - "nvcore/FileSystem.cpp", - "nvcore/RadixSort.cpp", - "nvmath/Basis.cpp", - "nvmath/ConvexHull.cpp", - "nvmath/Fitting.cpp", - "nvmath/Plane.cpp", - "nvmath/ProximityGrid.cpp", - "nvmath/Random.cpp", - "nvmath/Solver.cpp", - "nvmath/Sparse.cpp", - "nvmath/TypeSerialization.cpp", - "poshlib/posh.c", - "nvimage/BitMap.cpp", - "nvimage/Image.cpp", - "nvmesh/BaseMesh.cpp", - "nvmesh/MeshBuilder.cpp", - "nvmesh/TriMesh.cpp", - "nvmesh/QuadTriMesh.cpp", - "nvmesh/MeshTopology.cpp", - "nvmesh/halfedge/Edge.cpp", - "nvmesh/halfedge/Mesh.cpp", - "nvmesh/halfedge/Face.cpp", - "nvmesh/halfedge/Vertex.cpp", - "nvmesh/geometry/Bounds.cpp", - "nvmesh/geometry/Measurements.cpp", - "nvmesh/raster/Raster.cpp", - "nvmesh/param/Atlas.cpp", - "nvmesh/param/AtlasBuilder.cpp", - "nvmesh/param/AtlasPacker.cpp", - "nvmesh/param/LeastSquaresConformalMap.cpp", - "nvmesh/param/OrthogonalProjectionMap.cpp", - "nvmesh/param/ParameterizationQuality.cpp", - "nvmesh/param/SingleFaceMap.cpp", - "nvmesh/param/Util.cpp", - "nvmesh/weld/VertexWeld.cpp", - "nvmesh/weld/Snap.cpp", - "thekla/thekla_atlas.cpp" - ] - thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - - env_thekla_unwrap.Append(CPPPATH=[thirdparty_dir, thirdparty_dir + "poshlib", thirdparty_dir + "nvcore", thirdparty_dir + "nvmesh"]) - - # upstream uses c++11 - if (not env.msvc): - env_thekla_unwrap.Append(CXXFLAGS="-std=c++11") - - if env["platform"] == 'x11': - # if not specifically one of the *BSD, then use LINUX as default - if platform.system() == "FreeBSD": - env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_FREEBSD", "-DPOSH_COMPILER_GCC"]) - elif platform.system() == "OpenBSD": - env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_OPENBSD", "-DPOSH_COMPILER_GCC"]) - else: - env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_LINUX", "-DPOSH_COMPILER_GCC"]) - elif env["platform"] == 'osx': - env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_DARWIN", "-DPOSH_COMPILER_GCC"]) - elif env["platform"] == 'windows': - if env.msvc: - env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_WIN32", "-DNV_CC_MSVC", "-DPOSH_COMPILER_MSVC" ]) - else: - env_thekla_unwrap.Append(CCFLAGS=["-DNV_OS_MINGW", "-DNV_CC_GNUC", "-DPOSH_COMPILER_GCC", "-U__STRICT_ANSI__"]) - env.Append(LIBS=["dbghelp"]) - - env_thirdparty = env_thekla_unwrap.Clone() - env_thirdparty.disable_warnings() - env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources) - -# Godot source files -env_thekla_unwrap.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/thekla_unwrap/config.py b/modules/thekla_unwrap/config.py deleted file mode 100644 index fad6095064..0000000000 --- a/modules/thekla_unwrap/config.py +++ /dev/null @@ -1,6 +0,0 @@ -def can_build(env, platform): - #return (env['tools'] and platform not in ["android", "ios"]) - return False - -def configure(env): - pass diff --git a/modules/thekla_unwrap/register_types.cpp b/modules/thekla_unwrap/register_types.cpp deleted file mode 100644 index 2c35adfb83..0000000000 --- a/modules/thekla_unwrap/register_types.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/*************************************************************************/ -/* register_types.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 "register_types.h" -#include "core/error_macros.h" -#include "thirdparty/thekla_atlas/thekla/thekla_atlas.h" - -#include <stdio.h> -#include <stdlib.h> -extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y); - -bool thekla_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y) { - - //set up input mesh - Thekla::Atlas_Input_Mesh input_mesh; - input_mesh.face_array = new Thekla::Atlas_Input_Face[p_index_count / 3]; - for (int i = 0; i < p_index_count / 3; i++) { - input_mesh.face_array[i].vertex_index[0] = p_indices[i * 3 + 0]; - input_mesh.face_array[i].vertex_index[1] = p_indices[i * 3 + 1]; - input_mesh.face_array[i].vertex_index[2] = p_indices[i * 3 + 2]; - //printf("face %i - %i, %i, %i - mat %i\n", i, input_mesh.face_array[i].vertex_index[0], input_mesh.face_array[i].vertex_index[1], input_mesh.face_array[i].vertex_index[2], p_face_materials[i]); - input_mesh.face_array[i].material_index = p_face_materials[i]; - } - input_mesh.vertex_array = new Thekla::Atlas_Input_Vertex[p_vertex_count]; - for (int i = 0; i < p_vertex_count; i++) { - input_mesh.vertex_array[i].first_colocal = i; //wtf - for (int j = 0; j < 3; j++) { - input_mesh.vertex_array[i].position[j] = p_vertices[i * 3 + j]; - input_mesh.vertex_array[i].normal[j] = p_normals[i * 3 + j]; - } - input_mesh.vertex_array[i].uv[0] = 0; - input_mesh.vertex_array[i].uv[1] = 0; - //printf("vertex %i - %f, %f, %f\n", i, input_mesh.vertex_array[i].position[0], input_mesh.vertex_array[i].position[1], input_mesh.vertex_array[i].position[2]); - //printf("normal %i - %f, %f, %f\n", i, input_mesh.vertex_array[i].normal[0], input_mesh.vertex_array[i].normal[1], input_mesh.vertex_array[i].normal[2]); - } - input_mesh.face_count = p_index_count / 3; - input_mesh.vertex_count = p_vertex_count; - - //set up options - Thekla::Atlas_Options options; - Thekla::atlas_set_default_options(&options); - options.packer_options.witness.packing_quality = 1; - options.packer_options.witness.texel_area = 1.0 / p_texel_size; - options.packer_options.witness.conservative = false; - - //generate - Thekla::Atlas_Error err; - Thekla::Atlas_Output_Mesh *output = atlas_generate(&input_mesh, &options, &err); - - delete[] input_mesh.face_array; - delete[] input_mesh.vertex_array; - - if (output == NULL) { - ERR_PRINT("could not generate atlas output mesh"); - return false; - } - - if (err != Thekla::Atlas_Error_Success) { - printf("error with atlas\n"); - } else { - *r_vertex = (int *)malloc(sizeof(int) * output->vertex_count); - *r_uv = (float *)malloc(sizeof(float) * output->vertex_count * 3); - *r_index = (int *)malloc(sizeof(int) * output->index_count); - - // printf("w: %i, h: %i\n", output->atlas_width, output->atlas_height); - for (int i = 0; i < output->vertex_count; i++) { - (*r_vertex)[i] = output->vertex_array[i].xref; - (*r_uv)[i * 2 + 0] = output->vertex_array[i].uv[0] / output->atlas_width; - (*r_uv)[i * 2 + 1] = output->vertex_array[i].uv[1] / output->atlas_height; - // printf("uv: %f,%f\n", (*r_uv)[i * 2 + 0], (*r_uv)[i * 2 + 1]); - } - *r_vertex_count = output->vertex_count; - - for (int i = 0; i < output->index_count; i++) { - (*r_index)[i] = output->index_array[i]; - } - - *r_index_count = output->index_count; - - *r_size_hint_x = output->atlas_height; - *r_size_hint_y = output->atlas_width; - } - - if (output) { - atlas_free(output); - } - - return err == Thekla::Atlas_Error_Success; -} - -void register_thekla_unwrap_types() { - - array_mesh_lightmap_unwrap_callback = thekla_mesh_lightmap_unwrap_callback; -} - -void unregister_thekla_unwrap_types() { -} diff --git a/modules/theora/SCsub b/modules/theora/SCsub index 98c4274a7e..ff65d2f8ec 100644 --- a/modules/theora/SCsub +++ b/modules/theora/SCsub @@ -66,17 +66,17 @@ if env['builtin_libtheora']: thirdparty_sources += thirdparty_sources_x86_vc if (env["x86_libtheora_opt_gcc"] or env["x86_libtheora_opt_vc"]): - env_theora.Append(CCFLAGS=["-DOC_X86_ASM"]) + env_theora.Append(CPPDEFINES=["OC_X86_ASM"]) thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - env_theora.Append(CPPPATH=[thirdparty_dir]) + env_theora.Prepend(CPPPATH=[thirdparty_dir]) # also requires libogg and libvorbis if env['builtin_libogg']: - env_theora.Append(CPPPATH=["#thirdparty/libogg"]) + env_theora.Prepend(CPPPATH=["#thirdparty/libogg"]) if env['builtin_libvorbis']: - env_theora.Append(CPPPATH=["#thirdparty/libvorbis"]) + env_theora.Prepend(CPPPATH=["#thirdparty/libvorbis"]) env_thirdparty = env_theora.Clone() env_thirdparty.disable_warnings() 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/doc_classes/VideoStreamTheora.xml b/modules/theora/doc_classes/VideoStreamTheora.xml index 2bd8ad862f..696101e252 100644 --- a/modules/theora/doc_classes/VideoStreamTheora.xml +++ b/modules/theora/doc_classes/VideoStreamTheora.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_file"> <return type="String"> diff --git a/modules/theora/video_stream_theora.cpp b/modules/theora/video_stream_theora.cpp index 14c5ddd7f2..12f07aa773 100644 --- a/modules/theora/video_stream_theora.cpp +++ b/modules/theora/video_stream_theora.cpp @@ -94,15 +94,15 @@ void VideoStreamPlaybackTheora::video_write(void) { if (px_fmt == TH_PF_444) { - yuv444_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2, 0); + yuv444_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2); } else if (px_fmt == TH_PF_422) { - yuv422_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2, 0); + yuv422_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2); } else if (px_fmt == TH_PF_420) { - yuv420_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[2].data, (uint8_t *)yuv[1].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2, 0); + yuv420_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2); }; format = Image::FORMAT_RGBA8; @@ -175,7 +175,7 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { memdelete(file); } file = FileAccess::open(p_file, FileAccess::READ); - ERR_FAIL_COND(!file); + ERR_FAIL_COND_MSG(!file, "Cannot open file '" + p_file + "'."); #ifdef THEORA_USE_THREAD_STREAMING thread_exit = false; @@ -365,10 +365,10 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { float VideoStreamPlaybackTheora::get_time() const { - return time - AudioServer::get_singleton()->get_output_delay() - delay_compensation; //-((get_total())/(float)vi.rate); + return time - AudioServer::get_singleton()->get_output_latency() - delay_compensation; //-((get_total())/(float)vi.rate); }; -Ref<Texture> VideoStreamPlaybackTheora::get_texture() { +Ref<Texture> VideoStreamPlaybackTheora::get_texture() const { return texture; } @@ -499,7 +499,6 @@ void VideoStreamPlaybackTheora::update(float p_delta) { /*If we are too slow, reduce the pp level.*/ pp_inc = pp_level > 0 ? -1 : 0; } - } else { } } else { @@ -742,6 +741,8 @@ RES ResourceFormatLoaderTheora::load(const String &p_path, const String &p_origi *r_error = OK; } + f->close(); + memdelete(f); return ogv_stream; } diff --git a/modules/theora/video_stream_theora.h b/modules/theora/video_stream_theora.h index 85d73d3c0d..b241722cd1 100644 --- a/modules/theora/video_stream_theora.h +++ b/modules/theora/video_stream_theora.h @@ -147,7 +147,7 @@ public: void set_file(const String &p_file); - virtual Ref<Texture> get_texture(); + virtual Ref<Texture> get_texture() const; virtual void update(float p_delta); virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata); @@ -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/SCsub b/modules/tinyexr/SCsub index 3e7bda2bca..97f9797b58 100644 --- a/modules/tinyexr/SCsub +++ b/modules/tinyexr/SCsub @@ -13,7 +13,7 @@ thirdparty_sources = [ ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] -env_tinyexr.Append(CPPPATH=[thirdparty_dir]) +env_tinyexr.Prepend(CPPPATH=[thirdparty_dir]) env_thirdparty = env_tinyexr.Clone() env_thirdparty.disable_warnings() diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp index bd84a28c84..74a584821a 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; } @@ -235,7 +235,7 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f p_image->create(exr_image.width, exr_image.height, false, format, imgdata); - w = PoolVector<uint8_t>::Write(); + w.release(); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); diff --git a/modules/tinyexr/image_loader_tinyexr.h b/modules/tinyexr/image_loader_tinyexr.h index 4003fdc802..ee8479b1b4 100644 --- a/modules/tinyexr/image_loader_tinyexr.h +++ b/modules/tinyexr/image_loader_tinyexr.h @@ -33,9 +33,6 @@ #include "core/io/image_loader.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ class ImageLoaderTinyEXR : public ImageFormatLoader { public: diff --git a/modules/tinyexr/image_saver_tinyexr.cpp b/modules/tinyexr/image_saver_tinyexr.cpp new file mode 100644 index 0000000000..894f223597 --- /dev/null +++ b/modules/tinyexr/image_saver_tinyexr.cpp @@ -0,0 +1,275 @@ +/*************************************************************************/ +/* image_saver_tinyexr.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 "image_saver_tinyexr.h" +#include "core/math/math_funcs.h" + +#include "thirdparty/tinyexr/tinyexr.h" + +static bool is_supported_format(Image::Format p_format) { + // This is checked before anything else. + // Mostly uncompressed formats are considered. + switch (p_format) { + case Image::FORMAT_RF: + case Image::FORMAT_RGF: + case Image::FORMAT_RGBF: + case Image::FORMAT_RGBAF: + case Image::FORMAT_RH: + case Image::FORMAT_RGH: + case Image::FORMAT_RGBH: + case Image::FORMAT_RGBAH: + case Image::FORMAT_R8: + case Image::FORMAT_RG8: + case Image::FORMAT_RGB8: + case Image::FORMAT_RGBA8: + return true; + default: + return false; + } +} + +enum SrcPixelType { + SRC_FLOAT, + SRC_HALF, + SRC_BYTE +}; + +static SrcPixelType get_source_pixel_type(Image::Format p_format) { + switch (p_format) { + case Image::FORMAT_RF: + case Image::FORMAT_RGF: + case Image::FORMAT_RGBF: + case Image::FORMAT_RGBAF: + return SRC_FLOAT; + case Image::FORMAT_RH: + case Image::FORMAT_RGH: + case Image::FORMAT_RGBH: + case Image::FORMAT_RGBAH: + return SRC_HALF; + case Image::FORMAT_R8: + case Image::FORMAT_RG8: + case Image::FORMAT_RGB8: + case Image::FORMAT_RGBA8: + return SRC_BYTE; + default: + CRASH_NOW(); + } +} + +static int get_target_pixel_type(Image::Format p_format) { + switch (p_format) { + case Image::FORMAT_RF: + case Image::FORMAT_RGF: + case Image::FORMAT_RGBF: + case Image::FORMAT_RGBAF: + return TINYEXR_PIXELTYPE_FLOAT; + case Image::FORMAT_RH: + case Image::FORMAT_RGH: + case Image::FORMAT_RGBH: + case Image::FORMAT_RGBAH: + // EXR doesn't support 8-bit channels so in that case we'll convert + case Image::FORMAT_R8: + case Image::FORMAT_RG8: + case Image::FORMAT_RGB8: + case Image::FORMAT_RGBA8: + return TINYEXR_PIXELTYPE_HALF; + default: + CRASH_NOW(); + } +} + +static int get_pixel_type_size(int p_pixel_type) { + switch (p_pixel_type) { + case TINYEXR_PIXELTYPE_HALF: + return 2; + case TINYEXR_PIXELTYPE_FLOAT: + return 4; + } + CRASH_NOW(); +} + +static int get_channel_count(Image::Format p_format) { + switch (p_format) { + case Image::FORMAT_RF: + case Image::FORMAT_RH: + case Image::FORMAT_R8: + return 1; + case Image::FORMAT_RGF: + case Image::FORMAT_RGH: + case Image::FORMAT_RG8: + return 2; + case Image::FORMAT_RGBF: + case Image::FORMAT_RGBH: + case Image::FORMAT_RGB8: + return 3; + case Image::FORMAT_RGBAF: + case Image::FORMAT_RGBAH: + case Image::FORMAT_RGBA8: + return 4; + default: + CRASH_NOW(); + } +} + +Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale) { + + Image::Format format = p_img->get_format(); + + if (!is_supported_format(format)) { + // Format not supported + print_error("Image format not supported for saving as EXR. Consider saving as PNG."); + return ERR_UNAVAILABLE; + } + + EXRHeader header; + InitEXRHeader(&header); + + EXRImage image; + InitEXRImage(&image); + + const int max_channels = 4; + + // Godot does not support more than 4 channels, + // so we can preallocate header infos on the stack and use only the subset we need + PoolByteArray channels[max_channels]; + unsigned char *channels_ptrs[max_channels]; + EXRChannelInfo channel_infos[max_channels]; + int pixel_types[max_channels]; + int requested_pixel_types[max_channels] = { -1 }; + + // Gimp and Blender are a bit annoying so order of channels isn't straightforward. + const int channel_mappings[4][4] = { + { 0 }, // R + { 1, 0 }, // GR + { 2, 1, 0 }, // BGR + { 2, 1, 0, 3 } // BGRA + }; + + int channel_count = get_channel_count(format); + ERR_FAIL_COND_V(p_grayscale && channel_count != 1, ERR_INVALID_PARAMETER); + + int target_pixel_type = get_target_pixel_type(format); + int target_pixel_type_size = get_pixel_type_size(target_pixel_type); + SrcPixelType src_pixel_type = get_source_pixel_type(format); + const int pixel_count = p_img->get_width() * p_img->get_height(); + + const int *channel_mapping = channel_mappings[channel_count - 1]; + + { + PoolByteArray src_data = p_img->get_data(); + PoolByteArray::Read src_r = src_data.read(); + + for (int channel_index = 0; channel_index < channel_count; ++channel_index) { + + // De-interleave channels + + PoolByteArray &dst = channels[channel_index]; + dst.resize(pixel_count * target_pixel_type_size); + + PoolByteArray::Write dst_w = dst.write(); + + if (src_pixel_type == SRC_FLOAT && target_pixel_type == TINYEXR_PIXELTYPE_FLOAT) { + + // Note: we don't save mipmaps + CRASH_COND(src_data.size() < pixel_count * channel_count * target_pixel_type_size); + + const float *src_rp = (float *)src_r.ptr(); + float *dst_wp = (float *)dst_w.ptr(); + + for (int i = 0; i < pixel_count; ++i) { + dst_wp[i] = src_rp[channel_index + i * channel_count]; + } + + } else if (src_pixel_type == SRC_HALF && target_pixel_type == TINYEXR_PIXELTYPE_HALF) { + + CRASH_COND(src_data.size() < pixel_count * channel_count * target_pixel_type_size); + + const uint16_t *src_rp = (uint16_t *)src_r.ptr(); + uint16_t *dst_wp = (uint16_t *)dst_w.ptr(); + + for (int i = 0; i < pixel_count; ++i) { + dst_wp[i] = src_rp[channel_index + i * channel_count]; + } + + } else if (src_pixel_type == SRC_BYTE && target_pixel_type == TINYEXR_PIXELTYPE_HALF) { + + CRASH_COND(src_data.size() < pixel_count * channel_count); + + const uint8_t *src_rp = (uint8_t *)src_r.ptr(); + uint16_t *dst_wp = (uint16_t *)dst_w.ptr(); + + for (int i = 0; i < pixel_count; ++i) { + dst_wp[i] = Math::make_half_float(src_rp[channel_index + i * channel_count] / 255.f); + } + + } else { + CRASH_NOW(); + } + + int remapped_index = channel_mapping[channel_index]; + + channels_ptrs[remapped_index] = dst_w.ptr(); + + // No conversion + pixel_types[remapped_index] = target_pixel_type; + requested_pixel_types[remapped_index] = target_pixel_type; + + // Write channel name + if (p_grayscale) { + channel_infos[remapped_index].name[0] = 'Y'; + channel_infos[remapped_index].name[1] = '\0'; + } else { + const char *rgba = "RGBA"; + channel_infos[remapped_index].name[0] = rgba[channel_index]; + channel_infos[remapped_index].name[1] = '\0'; + } + } + } + + image.images = channels_ptrs; + image.num_channels = channel_count; + image.width = p_img->get_width(); + image.height = p_img->get_height(); + + header.num_channels = image.num_channels; + header.channels = channel_infos; + header.pixel_types = pixel_types; + header.requested_pixel_types = requested_pixel_types; + + CharString utf8_filename = p_path.utf8(); + const char *err; + int ret = SaveEXRImageToFile(&image, &header, utf8_filename.ptr(), &err); + if (ret != TINYEXR_SUCCESS) { + print_error(String("Saving EXR failed. Error: {0}").format(varray(err))); + return ERR_FILE_CANT_WRITE; + } + + return OK; +} diff --git a/modules/tinyexr/image_saver_tinyexr.h b/modules/tinyexr/image_saver_tinyexr.h new file mode 100644 index 0000000000..298bd1d21c --- /dev/null +++ b/modules/tinyexr/image_saver_tinyexr.h @@ -0,0 +1,38 @@ +/*************************************************************************/ +/* image_saver_tinyexr.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 IMAGE_SAVER_TINYEXR_H +#define IMAGE_SAVER_TINYEXR_H + +#include "core/os/os.h" + +Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale); + +#endif // IMAGE_SAVER_TINYEXR_H diff --git a/modules/tinyexr/register_types.cpp b/modules/tinyexr/register_types.cpp index 5473a55687..233b3afa08 100644 --- a/modules/tinyexr/register_types.cpp +++ b/modules/tinyexr/register_types.cpp @@ -31,6 +31,7 @@ #include "register_types.h" #include "image_loader_tinyexr.h" +#include "image_saver_tinyexr.h" static ImageLoaderTinyEXR *image_loader_tinyexr = NULL; @@ -38,9 +39,13 @@ void register_tinyexr_types() { image_loader_tinyexr = memnew(ImageLoaderTinyEXR); ImageLoader::add_image_format_loader(image_loader_tinyexr); + + Image::save_exr_func = save_exr; } void unregister_tinyexr_types() { memdelete(image_loader_tinyexr); + + Image::save_exr_func = NULL; } diff --git a/modules/upnp/SCsub b/modules/upnp/SCsub index 2b15f7aee2..3f56a69594 100644 --- a/modules/upnp/SCsub +++ b/modules/upnp/SCsub @@ -23,10 +23,11 @@ if env['builtin_miniupnpc']: "portlistingparse.c", "upnpreplyparse.c", ] - thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] + thirdparty_sources = [thirdparty_dir + "miniupnpc/" + file for file in thirdparty_sources] - env_upnp.Append(CPPPATH=[thirdparty_dir]) - env_upnp.Append(CPPFLAGS=["-DMINIUPNP_STATICLIB"]) + env_upnp.Prepend(CPPPATH=[thirdparty_dir]) + env_upnp.Append(CPPDEFINES=["MINIUPNP_STATICLIB"]) + env_upnp.Append(CPPDEFINES=["MINIUPNPC_SET_SOCKET_TIMEOUT"]) env_thirdparty = env_upnp.Clone() env_thirdparty.disable_warnings() diff --git a/modules/upnp/doc_classes/UPNP.xml b/modules/upnp/doc_classes/UPNP.xml index 0f967c993b..aac0932995 100644 --- a/modules/upnp/doc_classes/UPNP.xml +++ b/modules/upnp/doc_classes/UPNP.xml @@ -5,11 +5,20 @@ </brief_description> <description> Provides UPNP functionality to discover [UPNPDevice]s on the local network and execute commands on them, like managing port mappings (port forwarding) and querying the local and remote network IP address. Note that methods on this class are synchronous and block the calling thread. + To forward a specific port: + [codeblock] + const PORT = 7777 + var upnp = UPNP.new() + upnp.discover(2000, 2, "InternetGatewayDevice") + upnp.add_port_mapping(port) + [/codeblock] + To close a specific port (e.g. after you have finished using it): + [codeblock] + upnp.delete_port_mapping(port) + [/codeblock] </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="add_device"> <return type="void"> @@ -125,13 +134,13 @@ </method> </methods> <members> - <member name="discover_ipv6" type="bool" setter="set_discover_ipv6" getter="is_discover_ipv6"> + <member name="discover_ipv6" type="bool" setter="set_discover_ipv6" getter="is_discover_ipv6" default="false"> If [code]true[/code], IPv6 is used for [UPNPDevice] discovery. </member> - <member name="discover_local_port" type="int" setter="set_discover_local_port" getter="get_discover_local_port"> + <member name="discover_local_port" type="int" setter="set_discover_local_port" getter="get_discover_local_port" default="0"> If [code]0[/code], the local port to use for discovery is chosen automatically by the system. If [code]1[/code], discovery will be done from the source port 1900 (same as destination port). Otherwise, the value will be used as the port. </member> - <member name="discover_multicast_if" type="String" setter="set_discover_multicast_if" getter="get_discover_multicast_if"> + <member name="discover_multicast_if" type="String" setter="set_discover_multicast_if" getter="get_discover_multicast_if" default=""""> Multicast interface to use for discovery. Uses the default multicast interface if empty. </member> </members> @@ -173,7 +182,7 @@ No port maps are available. May also be returned if port mapping functionality is not available. </constant> <constant name="UPNP_RESULT_CONFLICT_WITH_OTHER_MECHANISM" value="12" enum="UPNPResult"> - Conflict with other mechanism. May be returned instead of [code]UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING[/code] if a port mapping conflicts with an existing one. + Conflict with other mechanism. May be returned instead of [constant UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING] if a port mapping conflicts with an existing one. </constant> <constant name="UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING" value="13" enum="UPNPResult"> Conflict with an existing port mapping. diff --git a/modules/upnp/doc_classes/UPNPDevice.xml b/modules/upnp/doc_classes/UPNPDevice.xml index c9b695a651..4d3a0f4f1d 100644 --- a/modules/upnp/doc_classes/UPNPDevice.xml +++ b/modules/upnp/doc_classes/UPNPDevice.xml @@ -8,8 +8,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="add_port_mapping" qualifiers="const"> <return type="int"> @@ -55,22 +53,22 @@ </method> </methods> <members> - <member name="description_url" type="String" setter="set_description_url" getter="get_description_url"> + <member name="description_url" type="String" setter="set_description_url" getter="get_description_url" default=""""> URL to the device description. </member> - <member name="igd_control_url" type="String" setter="set_igd_control_url" getter="get_igd_control_url"> + <member name="igd_control_url" type="String" setter="set_igd_control_url" getter="get_igd_control_url" default=""""> IDG control URL. </member> - <member name="igd_our_addr" type="String" setter="set_igd_our_addr" getter="get_igd_our_addr"> + <member name="igd_our_addr" type="String" setter="set_igd_our_addr" getter="get_igd_our_addr" default=""""> Address of the local machine in the network connecting it to this [UPNPDevice]. </member> - <member name="igd_service_type" type="String" setter="set_igd_service_type" getter="get_igd_service_type"> + <member name="igd_service_type" type="String" setter="set_igd_service_type" getter="get_igd_service_type" default=""""> IGD service type. </member> - <member name="igd_status" type="int" setter="set_igd_status" getter="get_igd_status" enum="UPNPDevice.IGDStatus"> + <member name="igd_status" type="int" setter="set_igd_status" getter="get_igd_status" enum="UPNPDevice.IGDStatus" default="9"> IGD status. See [enum IGDStatus]. </member> - <member name="service_type" type="String" setter="set_service_type" getter="get_service_type"> + <member name="service_type" type="String" setter="set_service_type" getter="get_service_type" default=""""> Service type. </member> </members> diff --git a/modules/vhacd/SCsub b/modules/vhacd/SCsub new file mode 100644 index 0000000000..685976dc33 --- /dev/null +++ b/modules/vhacd/SCsub @@ -0,0 +1,33 @@ +#!/usr/bin/env python + +Import('env') +Import('env_modules') + +env_vhacd = env_modules.Clone() + +# Thirdparty source files + +thirdparty_dir = "#thirdparty/vhacd/" + +thirdparty_sources = [ + "src/vhacdManifoldMesh.cpp", + "src/FloatMath.cpp", + "src/vhacdMesh.cpp", + "src/vhacdICHull.cpp", + "src/vhacdVolume.cpp", + "src/VHACD-ASYNC.cpp", + "src/btAlignedAllocator.cpp", + "src/vhacdRaycastMesh.cpp", + "src/VHACD.cpp", + "src/btConvexHullComputer.cpp" +] + +thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] + +env_vhacd.Prepend(CPPPATH=[thirdparty_dir + "/inc"]) + +env_thirdparty = env_vhacd.Clone() +env_thirdparty.disable_warnings() +env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources) + +env_vhacd.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/vhacd/config.py b/modules/vhacd/config.py new file mode 100644 index 0000000000..9ced70d2fb --- /dev/null +++ b/modules/vhacd/config.py @@ -0,0 +1,6 @@ +def can_build(env, platform): + return True + +def configure(env): + pass + diff --git a/modules/mono/editor/monodevelop_instance.cpp b/modules/vhacd/register_types.cpp index 3caa56d1d0..076a1738ab 100644 --- a/modules/mono/editor/monodevelop_instance.cpp +++ b/modules/vhacd/register_types.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* monodevelop_instance.cpp */ +/* register_types.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,58 +28,61 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "monodevelop_instance.h" +#include "register_types.h" +#include "scene/resources/mesh.h" +#include "thirdparty/vhacd/public/VHACD.h" -#include "../mono_gd/gd_mono.h" -#include "../mono_gd/gd_mono_class.h" +static Vector<Vector<Face3> > convex_decompose(const Vector<Face3> &p_faces) { -void MonoDevelopInstance::execute(const Vector<String> &p_files) { + Vector<float> vertices; + vertices.resize(p_faces.size() * 9); + Vector<uint32_t> indices; + indices.resize(p_faces.size() * 3); - _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN) - - ERR_FAIL_NULL(execute_method); - ERR_FAIL_COND(gc_handle.is_null()); - - MonoException *exc = NULL; - - Variant files = p_files; - const Variant *args[1] = { &files }; - execute_method->invoke(gc_handle->get_target(), args, &exc); + for (int i = 0; i < p_faces.size(); i++) { + for (int j = 0; j < 3; j++) { + vertices.write[i * 9 + j * 3 + 0] = p_faces[i].vertex[j].x; + vertices.write[i * 9 + j * 3 + 1] = p_faces[i].vertex[j].y; + vertices.write[i * 9 + j * 3 + 2] = p_faces[i].vertex[j].z; + indices.write[i * 3 + j] = i * 3 + j; + } + } - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - ERR_FAIL(); + VHACD::IVHACD *decomposer = VHACD::CreateVHACD(); + VHACD::IVHACD::Parameters params; + decomposer->Compute(vertices.ptr(), vertices.size() / 3, indices.ptr(), indices.size() / 3, params); + + int hull_count = decomposer->GetNConvexHulls(); + + Vector<Vector<Face3> > ret; + + for (int i = 0; i < hull_count; i++) { + Vector<Face3> triangles; + VHACD::IVHACD::ConvexHull hull; + decomposer->GetConvexHull(i, hull); + triangles.resize(hull.m_nTriangles); + for (uint32_t j = 0; j < hull.m_nTriangles; j++) { + Face3 f; + for (int k = 0; k < 3; k++) { + for (int l = 0; l < 3; l++) { + f.vertex[k][l] = hull.m_points[hull.m_triangles[j * 3 + k] * 3 + l]; + } + } + triangles.write[j] = f; + } + ret.push_back(triangles); } -} -void MonoDevelopInstance::execute(const String &p_file) { + decomposer->Clean(); + decomposer->Release(); - Vector<String> files; - files.push_back(p_file); - execute(files); + return ret; } -MonoDevelopInstance::MonoDevelopInstance(const String &p_solution, EditorId p_editor_id) { - - _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN) - - GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Editor", "MonoDevelopInstance"); - - MonoObject *obj = mono_object_new(TOOLS_DOMAIN, klass->get_mono_ptr()); - - GDMonoMethod *ctor = klass->get_method(".ctor", 2); - MonoException *exc = NULL; - - Variant solution = p_solution; - Variant editor_id = p_editor_id; - const Variant *args[2] = { &solution, &editor_id }; - ctor->invoke(obj, args, &exc); - - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - ERR_FAIL(); - } +void register_vhacd_types() { + Mesh::convex_composition_function = convex_decompose; +} - gc_handle = MonoGCHandle::create_strong(obj); - execute_method = klass->get_method("Execute", 1); +void unregister_vhacd_types() { + Mesh::convex_composition_function = NULL; } diff --git a/modules/vhacd/register_types.h b/modules/vhacd/register_types.h new file mode 100644 index 0000000000..cb948faf44 --- /dev/null +++ b/modules/vhacd/register_types.h @@ -0,0 +1,32 @@ +/*************************************************************************/ +/* register_types.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. */ +/*************************************************************************/ + +void register_vhacd_types(); +void unregister_vhacd_types(); diff --git a/modules/visual_script/config.py b/modules/visual_script/config.py index 07a0450734..087a13a200 100644 --- a/modules/visual_script/config.py +++ b/modules/visual_script/config.py @@ -6,10 +6,12 @@ def configure(env): def get_doc_classes(): return [ + "@VisualScript", "VisualScriptBasicTypeConstant", "VisualScriptBuiltinFunc", "VisualScriptClassConstant", "VisualScriptComment", + "VisualScriptComposeArray", "VisualScriptCondition", "VisualScriptConstant", "VisualScriptConstructor", @@ -27,6 +29,7 @@ def get_doc_classes(): "VisualScriptIndexSet", "VisualScriptInputAction", "VisualScriptIterator", + "VisualScriptLists", "VisualScriptLocalVarSet", "VisualScriptLocalVar", "VisualScriptMathConstant", diff --git a/modules/visual_script/doc_classes/@VisualScript.xml b/modules/visual_script/doc_classes/@VisualScript.xml new file mode 100644 index 0000000000..8d9408e6d4 --- /dev/null +++ b/modules/visual_script/doc_classes/@VisualScript.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<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> + <methods> + </methods> + <constants> + </constants> +</class> diff --git a/modules/visual_script/doc_classes/VisualScript.xml b/modules/visual_script/doc_classes/VisualScript.xml index f4a9bc68e6..0d95075152 100644 --- a/modules/visual_script/doc_classes/VisualScript.xml +++ b/modules/visual_script/doc_classes/VisualScript.xml @@ -11,8 +11,6 @@ <tutorials> <link>https://docs.godotengine.org/en/latest/getting_started/scripting/visual_script/index.html</link> </tutorials> - <demos> - </demos> <methods> <method name="add_custom_signal"> <return type="void"> @@ -254,7 +252,7 @@ <argument index="0" name="name" type="String"> </argument> <description> - Returns the info for a given variable as a dictionary. The information includes its name, type, hint and usage. + Returns the information for a given variable as a dictionary. The information includes its name, type, hint and usage. </description> </method> <method name="has_custom_signal" qualifiers="const"> diff --git a/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml b/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml index ce49cdf3a0..6dc54dbc03 100644 --- a/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml @@ -8,12 +8,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type"> + <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type" default="0"> The type to get the constant from. </member> <member name="constant" type="String" setter="set_basic_type_constant" getter="get_basic_type_constant"> diff --git a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml index dd14d60327..b5b452ee47 100644 --- a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml +++ b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml @@ -9,12 +9,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="function" type="int" setter="set_func" getter="get_func" enum="VisualScriptBuiltinFunc.BuiltinFunc"> + <member name="function" type="int" setter="set_func" getter="get_func" enum="VisualScriptBuiltinFunc.BuiltinFunc" default="0"> The function to be executed. </member> </members> @@ -104,108 +102,125 @@ </constant> <constant name="MATH_RANGE_LERP" value="28" enum="BuiltinFunc"> </constant> - <constant name="MATH_DECTIME" value="29" enum="BuiltinFunc"> - Return the result of 'value' decreased by 'step' * 'amount'. + <constant name="MATH_MOVE_TOWARD" value="29" enum="BuiltinFunc"> + Moves the number toward a value, based on the third input. </constant> - <constant name="MATH_RANDOMIZE" value="30" enum="BuiltinFunc"> + <constant name="MATH_DECTIME" value="30" enum="BuiltinFunc"> + Return the result of [code]value[/code] decreased by [code]step[/code] * [code]amount[/code]. + </constant> + <constant name="MATH_RANDOMIZE" value="31" enum="BuiltinFunc"> Randomize the seed (or the internal state) of the random number generator. Current implementation reseeds using a number based on time. </constant> - <constant name="MATH_RAND" value="31" enum="BuiltinFunc"> + <constant name="MATH_RAND" value="32" enum="BuiltinFunc"> Return a random 32 bits integer value. To obtain a random value between 0 to N (where N is smaller than 2^32 - 1), you can use it with the remainder function. </constant> - <constant name="MATH_RANDF" value="32" enum="BuiltinFunc"> + <constant name="MATH_RANDF" value="33" enum="BuiltinFunc"> Return a random floating-point value between 0 and 1. To obtain a random value between 0 to N, you can use it with multiplication. </constant> - <constant name="MATH_RANDOM" value="33" enum="BuiltinFunc"> + <constant name="MATH_RANDOM" value="34" enum="BuiltinFunc"> Return a random floating-point value between the two inputs. </constant> - <constant name="MATH_SEED" value="34" enum="BuiltinFunc"> + <constant name="MATH_SEED" value="35" enum="BuiltinFunc"> Set the seed for the random number generator. </constant> - <constant name="MATH_RANDSEED" value="35" enum="BuiltinFunc"> + <constant name="MATH_RANDSEED" value="36" enum="BuiltinFunc"> Return a random value from the given seed, along with the new seed. </constant> - <constant name="MATH_DEG2RAD" value="36" enum="BuiltinFunc"> + <constant name="MATH_DEG2RAD" value="37" enum="BuiltinFunc"> Convert the input from degrees to radians. </constant> - <constant name="MATH_RAD2DEG" value="37" enum="BuiltinFunc"> + <constant name="MATH_RAD2DEG" value="38" enum="BuiltinFunc"> Convert the input from radians to degrees. </constant> - <constant name="MATH_LINEAR2DB" value="38" enum="BuiltinFunc"> + <constant name="MATH_LINEAR2DB" value="39" enum="BuiltinFunc"> Convert the input from linear volume to decibel volume. </constant> - <constant name="MATH_DB2LINEAR" value="39" enum="BuiltinFunc"> + <constant name="MATH_DB2LINEAR" value="40" enum="BuiltinFunc"> Convert the input from decibel volume to linear volume. </constant> - <constant name="MATH_POLAR2CARTESIAN" value="40" enum="BuiltinFunc"> - 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). + <constant name="MATH_POLAR2CARTESIAN" value="41" enum="BuiltinFunc"> + 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). </constant> - <constant name="MATH_CARTESIAN2POLAR" value="41" enum="BuiltinFunc"> - 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). + <constant name="MATH_CARTESIAN2POLAR" value="42" enum="BuiltinFunc"> + 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). </constant> - <constant name="MATH_WRAP" value="42" enum="BuiltinFunc"> + <constant name="MATH_WRAP" value="43" enum="BuiltinFunc"> </constant> - <constant name="MATH_WRAPF" value="43" enum="BuiltinFunc"> + <constant name="MATH_WRAPF" value="44" enum="BuiltinFunc"> </constant> - <constant name="LOGIC_MAX" value="44" enum="BuiltinFunc"> + <constant name="LOGIC_MAX" value="45" enum="BuiltinFunc"> Return the greater of the two numbers, also known as their maximum. </constant> - <constant name="LOGIC_MIN" value="45" enum="BuiltinFunc"> + <constant name="LOGIC_MIN" value="46" enum="BuiltinFunc"> Return the lesser of the two numbers, also known as their minimum. </constant> - <constant name="LOGIC_CLAMP" value="46" enum="BuiltinFunc"> + <constant name="LOGIC_CLAMP" value="47" enum="BuiltinFunc"> Return the input clamped inside the given range, ensuring the result is never outside it. Equivalent to [code]min(max(input, range_low), range_high)[/code]. </constant> - <constant name="LOGIC_NEAREST_PO2" value="47" enum="BuiltinFunc"> + <constant name="LOGIC_NEAREST_PO2" value="48" enum="BuiltinFunc"> Return the nearest power of 2 to the input. </constant> - <constant name="OBJ_WEAKREF" value="48" enum="BuiltinFunc"> + <constant name="OBJ_WEAKREF" value="49" enum="BuiltinFunc"> Create a [WeakRef] from the input. </constant> - <constant name="FUNC_FUNCREF" value="49" enum="BuiltinFunc"> + <constant name="FUNC_FUNCREF" value="50" enum="BuiltinFunc"> Create a [FuncRef] from the input. </constant> - <constant name="TYPE_CONVERT" value="50" enum="BuiltinFunc"> + <constant name="TYPE_CONVERT" value="51" enum="BuiltinFunc"> Convert between types. </constant> - <constant name="TYPE_OF" value="51" enum="BuiltinFunc"> + <constant name="TYPE_OF" value="52" enum="BuiltinFunc"> Return the type of the input as an integer. Check [enum Variant.Type] for the integers that might be returned. </constant> - <constant name="TYPE_EXISTS" value="52" enum="BuiltinFunc"> + <constant name="TYPE_EXISTS" value="53" enum="BuiltinFunc"> Checks if a type is registered in the [ClassDB]. </constant> - <constant name="TEXT_CHAR" value="53" enum="BuiltinFunc"> + <constant name="TEXT_CHAR" value="54" enum="BuiltinFunc"> Return a character with the given ascii value. </constant> - <constant name="TEXT_STR" value="54" enum="BuiltinFunc"> + <constant name="TEXT_STR" value="55" enum="BuiltinFunc"> Convert the input to a string. </constant> - <constant name="TEXT_PRINT" value="55" enum="BuiltinFunc"> + <constant name="TEXT_PRINT" value="56" enum="BuiltinFunc"> Print the given string to the output window. </constant> - <constant name="TEXT_PRINTERR" value="56" enum="BuiltinFunc"> + <constant name="TEXT_PRINTERR" value="57" enum="BuiltinFunc"> Print the given string to the standard error output. </constant> - <constant name="TEXT_PRINTRAW" value="57" enum="BuiltinFunc"> + <constant name="TEXT_PRINTRAW" value="58" enum="BuiltinFunc"> Print the given string to the standard output, without adding a newline. </constant> - <constant name="VAR_TO_STR" value="58" enum="BuiltinFunc"> + <constant name="VAR_TO_STR" value="59" enum="BuiltinFunc"> Serialize a [Variant] to a string. </constant> - <constant name="STR_TO_VAR" value="59" enum="BuiltinFunc"> - Deserialize a [Variant] from a string serialized using [code]VAR_TO_STR[/code]. + <constant name="STR_TO_VAR" value="60" enum="BuiltinFunc"> + Deserialize a [Variant] from a string serialized using [constant VAR_TO_STR]. </constant> - <constant name="VAR_TO_BYTES" value="60" enum="BuiltinFunc"> + <constant name="VAR_TO_BYTES" value="61" enum="BuiltinFunc"> Serialize a [Variant] to a [PoolByteArray]. </constant> - <constant name="BYTES_TO_VAR" value="61" enum="BuiltinFunc"> - Deserialize a [Variant] from a [PoolByteArray] serialized using [code]VAR_TO_BYTES[/code]. + <constant name="BYTES_TO_VAR" value="62" enum="BuiltinFunc"> + Deserialize a [Variant] from a [PoolByteArray] serialized using [constant VAR_TO_BYTES]. + </constant> + <constant name="COLORN" value="63" enum="BuiltinFunc"> + Return the [Color] with the given name and alpha ranging from 0 to 1 + [b]Note:[/b] Names are defined in [code]color_names.inc[/code]. + </constant> + <constant name="MATH_SMOOTHSTEP" value="64" enum="BuiltinFunc"> + Return a number smoothly interpolated between the first two inputs, based on the third input. Similar to [constant MATH_LERP], but interpolates faster at the beginning and slower at the end. Using Hermite interpolation formula: + [codeblock] + var t = clamp((weight - from) / (to - from), 0.0, 1.0) + return t * t * (3.0 - 2.0 * t) + [/codeblock] + </constant> + <constant name="MATH_POSMOD" value="65" enum="BuiltinFunc"> + </constant> + <constant name="MATH_LERP_ANGLE" value="66" enum="BuiltinFunc"> </constant> - <constant name="COLORN" value="62" enum="BuiltinFunc"> - Return the [Color] with the given name and alpha ranging from 0 to 1. Note: names are defined in color_names.inc. + <constant name="TEXT_ORD" value="67" enum="BuiltinFunc"> </constant> - <constant name="FUNC_MAX" value="63" enum="BuiltinFunc"> - The maximum value the [member function] property can have. + <constant name="FUNC_MAX" value="68" enum="BuiltinFunc"> + Represents the size of the [enum BuiltinFunc] enum. </constant> </constants> </class> diff --git a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml b/modules/visual_script/doc_classes/VisualScriptClassConstant.xml index 32b5924cdc..49ea7850ef 100644 --- a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptClassConstant.xml @@ -4,7 +4,7 @@ Gets a constant from a given class. </brief_description> <description> - This node returns a constant from a given class, such as [constant @GlobalScope.TYPE_INT]. See the given class' documentation for available constants. + This node returns a constant from a given class, such as [constant TYPE_INT]. See the given class' documentation for available constants. [b]Input Ports:[/b] none [b]Output Ports:[/b] @@ -12,15 +12,13 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="base_type" type="String" setter="set_base_type" getter="get_base_type"> + <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default=""Object""> The constant's parent class. </member> - <member name="constant" type="String" setter="set_class_constant" getter="get_class_constant"> + <member name="constant" type="String" setter="set_class_constant" getter="get_class_constant" default=""""> The constant to return. See the given class for its available constants. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptComment.xml b/modules/visual_script/doc_classes/VisualScriptComment.xml index 990e0ecb85..2538bc8356 100644 --- a/modules/visual_script/doc_classes/VisualScriptComment.xml +++ b/modules/visual_script/doc_classes/VisualScriptComment.xml @@ -9,18 +9,16 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="description" type="String" setter="set_description" getter="get_description"> + <member name="description" type="String" setter="set_description" getter="get_description" default=""""> The text inside the comment node. </member> - <member name="size" type="Vector2" setter="set_size" getter="get_size"> + <member name="size" type="Vector2" setter="set_size" getter="get_size" default="Vector2( 150, 150 )"> The comment node's size (in pixels). </member> - <member name="title" type="String" setter="set_title" getter="get_title"> + <member name="title" type="String" setter="set_title" getter="get_title" default=""Comment""> The comment node's title. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptComposeArray.xml b/modules/visual_script/doc_classes/VisualScriptComposeArray.xml new file mode 100644 index 0000000000..92efbc51d1 --- /dev/null +++ b/modules/visual_script/doc_classes/VisualScriptComposeArray.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="VisualScriptComposeArray" inherits="VisualScriptLists" category="Core" version="3.2"> + <brief_description> + A Visual Script Node used to create array from a list of items. + </brief_description> + <description> + A Visual Script Node used to compose array from the list of elements provided with custom in-graph UI hard coded in the VisualScript Editor. + </description> + <tutorials> + </tutorials> + <methods> + </methods> + <constants> + </constants> +</class> diff --git a/modules/visual_script/doc_classes/VisualScriptCondition.xml b/modules/visual_script/doc_classes/VisualScriptCondition.xml index 94c075205d..12d85429cf 100644 --- a/modules/visual_script/doc_classes/VisualScriptCondition.xml +++ b/modules/visual_script/doc_classes/VisualScriptCondition.xml @@ -15,8 +15,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptConstant.xml b/modules/visual_script/doc_classes/VisualScriptConstant.xml index 0fc4e87db4..eb12fc3731 100644 --- a/modules/visual_script/doc_classes/VisualScriptConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptConstant.xml @@ -12,12 +12,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="type" type="int" setter="set_constant_type" getter="get_constant_type" enum="Variant.Type"> + <member name="type" type="int" setter="set_constant_type" getter="get_constant_type" enum="Variant.Type" default="0"> The constant's type. </member> <member name="value" type="Variant" setter="set_constant_value" getter="get_constant_value"> diff --git a/modules/visual_script/doc_classes/VisualScriptConstructor.xml b/modules/visual_script/doc_classes/VisualScriptConstructor.xml index 05fc3f318d..8da5055d83 100644 --- a/modules/visual_script/doc_classes/VisualScriptConstructor.xml +++ b/modules/visual_script/doc_classes/VisualScriptConstructor.xml @@ -8,8 +8,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_constructor" qualifiers="const"> <return type="Dictionary"> diff --git a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml index 0ad4e7c1f5..f70e22c7d0 100644 --- a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml +++ b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml @@ -8,8 +8,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="_get_caption" qualifiers="virtual"> <return type="String"> @@ -47,7 +45,7 @@ <argument index="0" name="idx" type="int"> </argument> <description> - Return the specified input port's type. See the TYPE_* enum in [@GlobalScope]. + Return the specified input port's type. See the [enum Variant.Type] values. </description> </method> <method name="_get_output_sequence_port_count" qualifiers="virtual"> @@ -88,7 +86,7 @@ <argument index="0" name="idx" type="int"> </argument> <description> - Return the specified output's type. See the TYPE_* enum in [@GlobalScope]. + Return the specified output's type. See the [enum Variant.Type] values. </description> </method> <method name="_get_text" qualifiers="virtual"> @@ -127,9 +125,9 @@ Execute the custom node's logic, returning the index of the output sequence port to use or a [String] when there is an error. The [code]inputs[/code] array contains the values of the input ports. [code]outputs[/code] is an array whose indices should be set to the respective outputs. - The [code]start_mode[/code] is usually [code]START_MODE_BEGIN_SEQUENCE[/code], unless you have used the STEP_* constants. + The [code]start_mode[/code] is usually [constant START_MODE_BEGIN_SEQUENCE], unless you have used the [code]STEP_*[/code] constants. [code]working_mem[/code] is an array which can be used to persist information between runs of the custom node. - When returning, you can mask the returned value with one of the STEP_* constants. + When returning, you can mask the returned value with one of the [code]STEP_*[/code] constants. </description> </method> </methods> @@ -138,17 +136,17 @@ The start mode used the first time when [method _step] is called. </constant> <constant name="START_MODE_CONTINUE_SEQUENCE" value="1" enum="StartMode"> - The start mode used when [method _step] is called after coming back from a STEP_PUSH_STACK_BIT. + The start mode used when [method _step] is called after coming back from a [constant STEP_PUSH_STACK_BIT]. </constant> <constant name="START_MODE_RESUME_YIELD" value="2" enum="StartMode"> - The start mode used when [method _step] is called after resuming from STEP_YIELD_BIT. + The start mode used when [method _step] is called after resuming from [constant STEP_YIELD_BIT]. </constant> <constant name="STEP_PUSH_STACK_BIT" value="16777216"> Hint used by [method _step] to tell that control should return to it when there is no other node left to execute. - This is used by [VisualScriptCondition] to redirect the sequence to the "Done" port after the true/false branch has finished execution. + This is used by [VisualScriptCondition] to redirect the sequence to the "Done" port after the [code]true[/code]/[code]false[/code] branch has finished execution. </constant> <constant name="STEP_GO_BACK_BIT" value="33554432"> - Hint used by [method _step] to tell that control should return back, either hitting a previous STEP_PUSH_STACK_BIT or exiting the function. + Hint used by [method _step] to tell that control should return back, either hitting a previous [constant STEP_PUSH_STACK_BIT] or exiting the function. </constant> <constant name="STEP_NO_ADVANCE_BIT" value="67108864"> </constant> diff --git a/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml b/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml index b933a25f1d..c8543287b4 100644 --- a/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml +++ b/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml @@ -8,12 +8,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="type" type="int" setter="set_deconstruct_type" getter="get_deconstruct_type" enum="Variant.Type"> + <member name="type" type="int" setter="set_deconstruct_type" getter="get_deconstruct_type" enum="Variant.Type" default="0"> The type to deconstruct. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptEditor.xml b/modules/visual_script/doc_classes/VisualScriptEditor.xml index be4606b57c..add2eb2275 100644 --- a/modules/visual_script/doc_classes/VisualScriptEditor.xml +++ b/modules/visual_script/doc_classes/VisualScriptEditor.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="add_custom_node"> <return type="void"> diff --git a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml b/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml index 3282269811..1a567905a9 100644 --- a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml +++ b/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml @@ -12,12 +12,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="signal" type="String" setter="set_signal" getter="get_signal"> + <member name="signal" type="String" setter="set_signal" getter="get_signal" default=""""> The signal to emit. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml b/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml index 3e52fb818c..05bd87ec22 100644 --- a/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml +++ b/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml @@ -8,12 +8,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="constant" type="String" setter="set_singleton" getter="get_singleton"> + <member name="constant" type="String" setter="set_singleton" getter="get_singleton" default=""""> The singleton's name. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptExpression.xml b/modules/visual_script/doc_classes/VisualScriptExpression.xml index 4760685bfb..eb6cdbb302 100644 --- a/modules/visual_script/doc_classes/VisualScriptExpression.xml +++ b/modules/visual_script/doc_classes/VisualScriptExpression.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptFunction.xml b/modules/visual_script/doc_classes/VisualScriptFunction.xml index dc021196cd..152b48ca89 100644 --- a/modules/visual_script/doc_classes/VisualScriptFunction.xml +++ b/modules/visual_script/doc_classes/VisualScriptFunction.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml b/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml index e978437542..f7f86e8c80 100644 --- a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml +++ b/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml @@ -6,30 +6,28 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> <member name="base_script" type="String" setter="set_base_script" getter="get_base_script"> </member> - <member name="base_type" type="String" setter="set_base_type" getter="get_base_type"> + <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default=""Object""> </member> <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type"> </member> - <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptFunctionCall.CallMode"> + <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptFunctionCall.CallMode" default="0"> </member> - <member name="function" type="String" setter="set_function" getter="get_function"> + <member name="function" type="String" setter="set_function" getter="get_function" default=""""> </member> <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path"> </member> - <member name="rpc_call_mode" type="int" setter="set_rpc_call_mode" getter="get_rpc_call_mode" enum="VisualScriptFunctionCall.RPCCallMode"> + <member name="rpc_call_mode" type="int" setter="set_rpc_call_mode" getter="get_rpc_call_mode" enum="VisualScriptFunctionCall.RPCCallMode" default="0"> </member> <member name="singleton" type="String" setter="set_singleton" getter="get_singleton"> </member> <member name="use_default_args" type="int" setter="set_use_default_args" getter="get_use_default_args"> </member> - <member name="validate" type="bool" setter="set_validate" getter="get_validate"> + <member name="validate" type="bool" setter="set_validate" getter="get_validate" default="true"> </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptFunctionState.xml b/modules/visual_script/doc_classes/VisualScriptFunctionState.xml index a5e15b8da2..a8e820e6ea 100644 --- a/modules/visual_script/doc_classes/VisualScriptFunctionState.xml +++ b/modules/visual_script/doc_classes/VisualScriptFunctionState.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="connect_to_signal"> <return type="void"> diff --git a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml b/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml index 2d609ed262..6c70dc7dc4 100644 --- a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml @@ -6,12 +6,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="constant" type="int" setter="set_global_constant" getter="get_global_constant"> + <member name="constant" type="int" setter="set_global_constant" getter="get_global_constant" default="0"> </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptIndexGet.xml b/modules/visual_script/doc_classes/VisualScriptIndexGet.xml index 16499e9ec9..ba0dc1a3d0 100644 --- a/modules/visual_script/doc_classes/VisualScriptIndexGet.xml +++ b/modules/visual_script/doc_classes/VisualScriptIndexGet.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptIndexSet.xml b/modules/visual_script/doc_classes/VisualScriptIndexSet.xml index 06844ac4ae..09a8f2c8ad 100644 --- a/modules/visual_script/doc_classes/VisualScriptIndexSet.xml +++ b/modules/visual_script/doc_classes/VisualScriptIndexSet.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptInputAction.xml b/modules/visual_script/doc_classes/VisualScriptInputAction.xml index 01887e0764..8c942813b2 100644 --- a/modules/visual_script/doc_classes/VisualScriptInputAction.xml +++ b/modules/visual_script/doc_classes/VisualScriptInputAction.xml @@ -6,14 +6,12 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="action" type="String" setter="set_action_name" getter="get_action_name"> + <member name="action" type="String" setter="set_action_name" getter="get_action_name" default=""""> </member> - <member name="mode" type="int" setter="set_action_mode" getter="get_action_mode" enum="VisualScriptInputAction.Mode"> + <member name="mode" type="int" setter="set_action_mode" getter="get_action_mode" enum="VisualScriptInputAction.Mode" default="0"> </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptIterator.xml b/modules/visual_script/doc_classes/VisualScriptIterator.xml index 496c24dee4..782bbfae20 100644 --- a/modules/visual_script/doc_classes/VisualScriptIterator.xml +++ b/modules/visual_script/doc_classes/VisualScriptIterator.xml @@ -15,8 +15,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptLists.xml b/modules/visual_script/doc_classes/VisualScriptLists.xml new file mode 100644 index 0000000000..8cf3eb1d38 --- /dev/null +++ b/modules/visual_script/doc_classes/VisualScriptLists.xml @@ -0,0 +1,95 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="VisualScriptLists" inherits="VisualScriptNode" category="Core" version="3.2"> + <brief_description> + A Visual Script virtual class for in-graph editable nodes. + </brief_description> + <description> + A Visual Script virtual class that defines the shape and the default behaviour of the nodes that have to be in-graph editable nodes. + </description> + <tutorials> + </tutorials> + <methods> + <method name="add_input_data_port"> + <return type="void"> + </return> + <argument index="0" name="type" type="int" enum="Variant.Type"> + </argument> + <argument index="1" name="name" type="String"> + </argument> + <argument index="2" name="index" type="int"> + </argument> + <description> + </description> + </method> + <method name="add_output_data_port"> + <return type="void"> + </return> + <argument index="0" name="type" type="int" enum="Variant.Type"> + </argument> + <argument index="1" name="name" type="String"> + </argument> + <argument index="2" name="index" type="int"> + </argument> + <description> + </description> + </method> + <method name="remove_input_data_port"> + <return type="void"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <description> + </description> + </method> + <method name="remove_output_data_port"> + <return type="void"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <description> + </description> + </method> + <method name="set_input_data_port_name"> + <return type="void"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <argument index="1" name="name" type="String"> + </argument> + <description> + </description> + </method> + <method name="set_input_data_port_type"> + <return type="void"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <argument index="1" name="type" type="int" enum="Variant.Type"> + </argument> + <description> + </description> + </method> + <method name="set_output_data_port_name"> + <return type="void"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <argument index="1" name="name" type="String"> + </argument> + <description> + </description> + </method> + <method name="set_output_data_port_type"> + <return type="void"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <argument index="1" name="type" type="int" enum="Variant.Type"> + </argument> + <description> + </description> + </method> + </methods> + <constants> + </constants> +</class> diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml b/modules/visual_script/doc_classes/VisualScriptLocalVar.xml index cd7286b59b..8c21c3f0bc 100644 --- a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml +++ b/modules/visual_script/doc_classes/VisualScriptLocalVar.xml @@ -12,15 +12,13 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type"> + <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type" default="0"> The local variable's type. </member> - <member name="var_name" type="String" setter="set_var_name" getter="get_var_name"> + <member name="var_name" type="String" setter="set_var_name" getter="get_var_name" default=""new_local""> The local variable's name. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml b/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml index f8fe2f4b6b..a981432cdb 100644 --- a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml +++ b/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml @@ -14,15 +14,13 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type"> + <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type" default="0"> The local variable's type. </member> - <member name="var_name" type="String" setter="set_var_name" getter="get_var_name"> + <member name="var_name" type="String" setter="set_var_name" getter="get_var_name" default=""new_local""> The local variable's name. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptMathConstant.xml b/modules/visual_script/doc_classes/VisualScriptMathConstant.xml index 733b48203d..3be392aef5 100644 --- a/modules/visual_script/doc_classes/VisualScriptMathConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptMathConstant.xml @@ -12,12 +12,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="constant" type="int" setter="set_math_constant" getter="get_math_constant" enum="VisualScriptMathConstant.MathConstant"> + <member name="constant" type="int" setter="set_math_constant" getter="get_math_constant" enum="VisualScriptMathConstant.MathConstant" default="0"> The math constant. </member> </members> @@ -47,6 +45,7 @@ Not a number: [code]nan[/code] </constant> <constant name="MATH_CONSTANT_MAX" value="8" enum="MathConstant"> + Represents the size of the [enum MathConstant] enum. </constant> </constants> </class> diff --git a/modules/visual_script/doc_classes/VisualScriptNode.xml b/modules/visual_script/doc_classes/VisualScriptNode.xml index 86bd469d5c..89fb5c81f8 100644 --- a/modules/visual_script/doc_classes/VisualScriptNode.xml +++ b/modules/visual_script/doc_classes/VisualScriptNode.xml @@ -8,8 +8,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_default_input_value" qualifiers="const"> <return type="Variant"> diff --git a/modules/visual_script/doc_classes/VisualScriptOperator.xml b/modules/visual_script/doc_classes/VisualScriptOperator.xml index d722477653..80449ac521 100644 --- a/modules/visual_script/doc_classes/VisualScriptOperator.xml +++ b/modules/visual_script/doc_classes/VisualScriptOperator.xml @@ -11,14 +11,12 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="operator" type="int" setter="set_operator" getter="get_operator" enum="Variant.Operator"> + <member name="operator" type="int" setter="set_operator" getter="get_operator" enum="Variant.Operator" default="6"> </member> - <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type"> + <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type" default="0"> </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptPreload.xml b/modules/visual_script/doc_classes/VisualScriptPreload.xml index b811252c42..b3b39691c9 100644 --- a/modules/visual_script/doc_classes/VisualScriptPreload.xml +++ b/modules/visual_script/doc_classes/VisualScriptPreload.xml @@ -12,8 +12,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> diff --git a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml index 7f652b7012..af1e8e68e8 100644 --- a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml +++ b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml @@ -6,14 +6,12 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> <member name="base_script" type="String" setter="set_base_script" getter="get_base_script"> </member> - <member name="base_type" type="String" setter="set_base_type" getter="get_base_type"> + <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default=""Object""> </member> <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type"> </member> @@ -21,9 +19,9 @@ </member> <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path"> </member> - <member name="property" type="String" setter="set_property" getter="get_property"> + <member name="property" type="String" setter="set_property" getter="get_property" default=""""> </member> - <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertyGet.CallMode"> + <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertyGet.CallMode" default="0"> </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml b/modules/visual_script/doc_classes/VisualScriptPropertySet.xml index ef9938c6a7..380c196caf 100644 --- a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml +++ b/modules/visual_script/doc_classes/VisualScriptPropertySet.xml @@ -6,16 +6,14 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="assign_op" type="int" setter="set_assign_op" getter="get_assign_op" enum="VisualScriptPropertySet.AssignOp"> + <member name="assign_op" type="int" setter="set_assign_op" getter="get_assign_op" enum="VisualScriptPropertySet.AssignOp" default="0"> </member> <member name="base_script" type="String" setter="set_base_script" getter="get_base_script"> </member> - <member name="base_type" type="String" setter="set_base_type" getter="get_base_type"> + <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default=""Object""> </member> <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type"> </member> @@ -23,9 +21,9 @@ </member> <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path"> </member> - <member name="property" type="String" setter="set_property" getter="get_property"> + <member name="property" type="String" setter="set_property" getter="get_property" default=""""> </member> - <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertySet.CallMode"> + <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertySet.CallMode" default="0"> </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptResourcePath.xml b/modules/visual_script/doc_classes/VisualScriptResourcePath.xml index 2a5c56cf69..da37bbbb2c 100644 --- a/modules/visual_script/doc_classes/VisualScriptResourcePath.xml +++ b/modules/visual_script/doc_classes/VisualScriptResourcePath.xml @@ -6,12 +6,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="path" type="String" setter="set_resource_path" getter="get_resource_path"> + <member name="path" type="String" setter="set_resource_path" getter="get_resource_path" default=""""> </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptReturn.xml b/modules/visual_script/doc_classes/VisualScriptReturn.xml index 7daddc7639..9a81c671d4 100644 --- a/modules/visual_script/doc_classes/VisualScriptReturn.xml +++ b/modules/visual_script/doc_classes/VisualScriptReturn.xml @@ -13,15 +13,13 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="return_enabled" type="bool" setter="set_enable_return_value" getter="is_return_value_enabled"> + <member name="return_enabled" type="bool" setter="set_enable_return_value" getter="is_return_value_enabled" default="false"> If [code]true[/code], the [code]return[/code] input port is available. </member> - <member name="return_type" type="int" setter="set_return_type" getter="get_return_type" enum="Variant.Type"> + <member name="return_type" type="int" setter="set_return_type" getter="get_return_type" enum="Variant.Type" default="0"> The return value's data type. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptSceneNode.xml b/modules/visual_script/doc_classes/VisualScriptSceneNode.xml index 8604a0f5eb..99f4acbd27 100644 --- a/modules/visual_script/doc_classes/VisualScriptSceneNode.xml +++ b/modules/visual_script/doc_classes/VisualScriptSceneNode.xml @@ -12,12 +12,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="node_path" type="NodePath" setter="set_node_path" getter="get_node_path"> + <member name="node_path" type="NodePath" setter="set_node_path" getter="get_node_path" default="NodePath(".")"> The node's path in the scene tree. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptSceneTree.xml b/modules/visual_script/doc_classes/VisualScriptSceneTree.xml index 72a2faaa78..84718ba119 100644 --- a/modules/visual_script/doc_classes/VisualScriptSceneTree.xml +++ b/modules/visual_script/doc_classes/VisualScriptSceneTree.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptSelect.xml b/modules/visual_script/doc_classes/VisualScriptSelect.xml index c87f77ea65..e6a6cd5a48 100644 --- a/modules/visual_script/doc_classes/VisualScriptSelect.xml +++ b/modules/visual_script/doc_classes/VisualScriptSelect.xml @@ -14,12 +14,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type"> + <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type" default="0"> The input variables' type. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptSelf.xml b/modules/visual_script/doc_classes/VisualScriptSelf.xml index 42c75e56a6..231e7d8f0d 100644 --- a/modules/visual_script/doc_classes/VisualScriptSelf.xml +++ b/modules/visual_script/doc_classes/VisualScriptSelf.xml @@ -12,8 +12,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptSequence.xml b/modules/visual_script/doc_classes/VisualScriptSequence.xml index c26c72dd50..2ceceb199f 100644 --- a/modules/visual_script/doc_classes/VisualScriptSequence.xml +++ b/modules/visual_script/doc_classes/VisualScriptSequence.xml @@ -14,12 +14,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="steps" type="int" setter="set_steps" getter="get_steps"> + <member name="steps" type="int" setter="set_steps" getter="get_steps" default="1"> The number of steps in the sequence. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptSubCall.xml b/modules/visual_script/doc_classes/VisualScriptSubCall.xml index 712b4ed09b..51b0093209 100644 --- a/modules/visual_script/doc_classes/VisualScriptSubCall.xml +++ b/modules/visual_script/doc_classes/VisualScriptSubCall.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="_subcall" qualifiers="virtual"> <return type="Variant"> diff --git a/modules/visual_script/doc_classes/VisualScriptSwitch.xml b/modules/visual_script/doc_classes/VisualScriptSwitch.xml index 0053733b34..3e3b88ebe0 100644 --- a/modules/visual_script/doc_classes/VisualScriptSwitch.xml +++ b/modules/visual_script/doc_classes/VisualScriptSwitch.xml @@ -4,7 +4,7 @@ Branches program flow based on a given input's value. </brief_description> <description> - Branches the flow based on an input's value. Use "Case Count" in the Inspector to set the number of branches and each comparison's optional type. + Branches the flow based on an input's value. Use [b]Case Count[/b] in the Inspector to set the number of branches and each comparison's optional type. [b]Input Ports:[/b] - Sequence: [code]'input' is[/code] - Data (variant): [code]=[/code] @@ -17,8 +17,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml b/modules/visual_script/doc_classes/VisualScriptTypeCast.xml index 85b3980e21..999a190a9a 100644 --- a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml +++ b/modules/visual_script/doc_classes/VisualScriptTypeCast.xml @@ -6,14 +6,12 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="base_script" type="String" setter="set_base_script" getter="get_base_script"> + <member name="base_script" type="String" setter="set_base_script" getter="get_base_script" default=""""> </member> - <member name="base_type" type="String" setter="set_base_type" getter="get_base_type"> + <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default=""Object""> </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml b/modules/visual_script/doc_classes/VisualScriptVariableGet.xml index 27bf223aac..40e461294b 100644 --- a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml +++ b/modules/visual_script/doc_classes/VisualScriptVariableGet.xml @@ -12,12 +12,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="var_name" type="String" setter="set_variable" getter="get_variable"> + <member name="var_name" type="String" setter="set_variable" getter="get_variable" default=""""> The variable's name. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml b/modules/visual_script/doc_classes/VisualScriptVariableSet.xml index c55c72d55e..6c53ad61b4 100644 --- a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml +++ b/modules/visual_script/doc_classes/VisualScriptVariableSet.xml @@ -13,12 +13,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="var_name" type="String" setter="set_variable" getter="get_variable"> + <member name="var_name" type="String" setter="set_variable" getter="get_variable" default=""""> The variable's name. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptWhile.xml b/modules/visual_script/doc_classes/VisualScriptWhile.xml index b7ed56e7d2..77211fa088 100644 --- a/modules/visual_script/doc_classes/VisualScriptWhile.xml +++ b/modules/visual_script/doc_classes/VisualScriptWhile.xml @@ -14,8 +14,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptYield.xml b/modules/visual_script/doc_classes/VisualScriptYield.xml index 5aa0f76a55..c506e6db01 100644 --- a/modules/visual_script/doc_classes/VisualScriptYield.xml +++ b/modules/visual_script/doc_classes/VisualScriptYield.xml @@ -6,12 +6,10 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="mode" type="int" setter="set_yield_mode" getter="get_yield_mode" enum="VisualScriptYield.YieldMode"> + <member name="mode" type="int" setter="set_yield_mode" getter="get_yield_mode" enum="VisualScriptYield.YieldMode" default="1"> </member> <member name="wait_time" type="float" setter="set_wait_time" getter="get_wait_time"> </member> diff --git a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml b/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml index 8e3b2aec1d..b9d7aedaab 100644 --- a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml +++ b/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml @@ -6,18 +6,16 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> </methods> <members> - <member name="base_type" type="String" setter="set_base_type" getter="get_base_type"> + <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default=""Object""> </member> - <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptYieldSignal.CallMode"> + <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptYieldSignal.CallMode" default="0"> </member> <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path"> </member> - <member name="signal" type="String" setter="set_signal" getter="get_signal"> + <member name="signal" type="String" setter="set_signal" getter="get_signal" default=""""> </member> </members> <constants> diff --git a/modules/visual_script/icons/icon_visual_script.svg b/modules/visual_script/icons/icon_visual_script.svg new file mode 100644 index 0000000000..f6475d590e --- /dev/null +++ b/modules/visual_script/icons/icon_visual_script.svg @@ -0,0 +1,6 @@ +<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> +<g transform="translate(0 -1036.4)"> +<ellipse cx="3" cy="1039.4" r="2" fill="#6e6e6e"/> +<path transform="translate(0 1036.4)" d="m7 1l-0.56445 2.2578a5 5 0 0 0 -0.68945 0.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -0.28516 0.68555l-2.2539 0.5625v2h5.2715a2 2 0 0 1 -0.27148 -1 2 2 0 0 1 2 -2 2 2 0 0 1 2 2 2 2 0 0 1 -0.26953 1h5.2695v-2l-2.2578-0.56445a5 5 0 0 0 -0.2793 -0.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -0.68555 -0.28516l-0.5625-2.2539h-2zm-4 9v6h2a3 3 0 0 0 3 -3v-3h-2v3a1 1 0 0 1 -1 1v-4h-2zm8 0a2 2 0 0 0 -1.7324 1 2 2 0 0 0 0 2 2 2 0 0 0 1.7324 1h-2v2h2a2 2 0 0 0 1.7324 -1 2 2 0 0 0 0 -2 2 2 0 0 0 -1.7324 -1h2v-2h-2z" fill="#e0e0e0"/> +</g> +</svg> diff --git a/modules/visual_script/register_types.cpp b/modules/visual_script/register_types.cpp index 24b96223d7..49272345fe 100644 --- a/modules/visual_script/register_types.cpp +++ b/modules/visual_script/register_types.cpp @@ -56,6 +56,8 @@ void register_visual_script_types() { ClassDB::register_virtual_class<VisualScriptNode>(); ClassDB::register_class<VisualScriptFunctionState>(); ClassDB::register_class<VisualScriptFunction>(); + ClassDB::register_virtual_class<VisualScriptLists>(); + ClassDB::register_class<VisualScriptComposeArray>(); ClassDB::register_class<VisualScriptOperator>(); ClassDB::register_class<VisualScriptVariableSet>(); ClassDB::register_class<VisualScriptVariableGet>(); diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp index 581809fec9..bb8612af6f 100644 --- a/modules/visual_script/visual_script.cpp +++ b/modules/visual_script/visual_script.cpp @@ -30,6 +30,7 @@ #include "visual_script.h" +#include "core/core_string_names.h" #include "core/os/os.h" #include "core/project_settings.h" #include "scene/main/node.h" @@ -45,15 +46,7 @@ bool VisualScriptNode::is_breakpoint() const { return breakpoint; } -void VisualScriptNode::_notification(int p_what) { - - if (p_what == NOTIFICATION_POSTINITIALIZE) { - validate_input_default_values(); - } -} - void VisualScriptNode::ports_changed_notify() { - validate_input_default_values(); emit_signal("ports_changed"); } @@ -272,11 +265,7 @@ void VisualScript::_node_ports_changed(int p_id) { Function &func = functions[function]; Ref<VisualScriptNode> vsn = func.nodes[p_id].node; - if (OS::get_singleton()->get_main_loop() && - Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop()) && - Engine::get_singleton()->is_editor_hint()) { - vsn->validate_input_default_values(); //force validate default values when editing on editor - } + vsn->validate_input_default_values(); //must revalidate all the functions @@ -339,8 +328,7 @@ void VisualScript::add_node(const StringName &p_func, int p_id, const Ref<Visual if (Object::cast_to<VisualScriptFunction>(*p_node)) { //the function indeed - ERR_EXPLAIN("A function node already has been set here."); - ERR_FAIL_COND(func.function_id >= 0); + ERR_FAIL_COND_MSG(func.function_id >= 0, "A function node has already been set here."); func.function_id = p_id; } @@ -352,6 +340,7 @@ void VisualScript::add_node(const StringName &p_func, int p_id, const Ref<Visual Ref<VisualScriptNode> vsn = p_node; vsn->connect("ports_changed", this, "_node_ports_changed", varray(p_id)); vsn->scripts_used.insert(this); + vsn->validate_input_default_values(); // Validate when fully loaded func.nodes[p_id] = nd; } @@ -589,6 +578,10 @@ void VisualScript::get_data_connection_list(const StringName &p_func, List<DataC } } +void VisualScript::set_tool_enabled(bool p_enabled) { + is_tool_script = p_enabled; +} + void VisualScript::add_variable(const StringName &p_name, const Variant &p_default_value, bool p_export) { ERR_FAIL_COND(instances.size()); @@ -905,7 +898,7 @@ ScriptInstance *VisualScript::instance_create(Object *p_this) { #ifdef TOOLS_ENABLED - if (!ScriptServer::is_scripting_enabled()) { + if (!ScriptServer::is_scripting_enabled() && !is_tool_script) { PlaceHolderScriptInstance *sins = memnew(PlaceHolderScriptInstance(VisualScriptLanguage::singleton, Ref<Script>((Script *)this), p_this)); placeholders.insert(sins); @@ -969,7 +962,7 @@ Error VisualScript::reload(bool p_keep_state) { bool VisualScript::is_tool() const { - return false; + return is_tool_script; } bool VisualScript::is_valid() const { @@ -1021,17 +1014,16 @@ void VisualScript::get_script_method_list(List<MethodInfo> *p_list) const { Ref<VisualScriptFunction> func = E->get().nodes[E->get().function_id].node; if (func.is_valid()) { - for (int i = 0; i < func->get_argument_count(); i++) { PropertyInfo arg; arg.name = func->get_argument_name(i); arg.type = func->get_argument_type(i); mi.arguments.push_back(arg); } + + p_list->push_back(mi); } } - - p_list->push_back(mi); } } @@ -1144,6 +1136,9 @@ void VisualScript::_set_data(const Dictionary &p_data) { Array funcs = d["functions"]; functions.clear(); + Vector2 last_pos = Vector2(-100 * funcs.size(), -100 * funcs.size()); // this is the center of the last fn box + Vector2 last_size = Vector2(0.0, 0.0); + for (int i = 0; i < funcs.size(); i++) { Dictionary func = funcs[i]; @@ -1156,11 +1151,42 @@ void VisualScript::_set_data(const Dictionary &p_data) { Array nodes = func["nodes"]; - for (int j = 0; j < nodes.size(); j += 3) { + if (!d.has("vs_unify") && nodes.size() > 0) { + Vector2 top_left = nodes[1]; + Vector2 bottom_right = nodes[1]; - add_node(name, nodes[j], nodes[j + 2], nodes[j + 1]); - } + for (int j = 0; j < nodes.size(); j += 3) { + Point2 pos = nodes[j + 1]; + if (pos.y > top_left.y) { + top_left.y = pos.y; + } + if (pos.y < bottom_right.y) { + bottom_right.y = pos.y; + } + if (pos.x > bottom_right.x) { + bottom_right.x = pos.x; + } + if (pos.x < top_left.x) { + top_left.x = pos.x; + } + } + + Vector2 size = Vector2(bottom_right.x - top_left.x, top_left.y - bottom_right.y); + + Vector2 offset = last_pos + (last_size / 2.0) + (size / 2.0); // dunno I might just keep it in one axis but diagonal feels better.... + + last_pos = offset; + last_size = size; + for (int j = 0; j < nodes.size(); j += 3) { + add_node(name, nodes[j], nodes[j + 2], offset + nodes[j + 1]); // also add an additional buffer if you want to + } + + } else { + for (int j = 0; j < nodes.size(); j += 3) { + add_node(name, nodes[j], nodes[j + 2], nodes[j + 1]); + } + } Array sequence_connections = func["sequence_connections"]; for (int j = 0; j < sequence_connections.size(); j += 3) { @@ -1175,6 +1201,11 @@ void VisualScript::_set_data(const Dictionary &p_data) { data_connect(name, data_connections[j + 0], data_connections[j + 1], data_connections[j + 2], data_connections[j + 3]); } } + + if (d.has("is_tool_script")) + is_tool_script = d["is_tool_script"]; + else + is_tool_script = false; } Dictionary VisualScript::_get_data() const { @@ -1256,6 +1287,8 @@ Dictionary VisualScript::_get_data() const { } d["functions"] = funcs; + d["is_tool_script"] = is_tool_script; + d["vs_unify"] = true; return d; } @@ -1328,6 +1361,11 @@ void VisualScript::_bind_methods() { VisualScript::VisualScript() { base_type = "Object"; + is_tool_script = false; +} + +StringName VisualScript::get_default_func() const { + return StringName("f_312843592"); } Set<int> VisualScript::get_output_sequence_ports_connected(const String &edited_func, int from_node) { @@ -1403,6 +1441,10 @@ void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const { for (const Map<StringName, VisualScript::Function>::Element *E = script->functions.front(); E; E = E->next()) { + if (E->key() == script->get_default_func()) { + continue; + } + MethodInfo mi; mi.name = E->key(); if (E->get().function_id >= 0 && E->get().nodes.has(E->get().function_id)) { @@ -1421,8 +1463,6 @@ void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const { if (!vsf->is_sequenced()) { //assumed constant if not sequenced mi.flags |= METHOD_FLAG_CONST; } - - //vsf->Get_ for now at least it does not return.. } } @@ -1431,6 +1471,9 @@ void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const { } bool VisualScriptInstance::has_method(const StringName &p_method) const { + if (p_method == script->get_default_func()) + return false; + return script->functions.has(p_method); } @@ -1497,7 +1540,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p Variant **output_args = (Variant **)(input_args + max_input_args); int flow_max = f->flow_stack_size; int *flow_stack = flow_max ? (int *)(output_args + max_output_args) : (int *)NULL; - int *pass_stack = flow_stack + flow_max; + int *pass_stack = flow_stack ? (int *)(flow_stack + flow_max) : (int *)NULL; String error_str; @@ -1702,7 +1745,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p if ((ret == output || ret & VisualScriptNodeInstance::STEP_FLAG_PUSH_STACK_BIT) && node->sequence_output_count) { //if no exit bit was set, and has sequence outputs, guess next node - if (output < 0 || output >= node->sequence_output_count) { + if (output >= node->sequence_output_count) { r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; error_str = RTR("Node returned an invalid sequence output: ") + itos(output); error = true; @@ -1915,7 +1958,7 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p Variant **output_args = (Variant **)(input_args + max_input_args); int flow_max = f->flow_stack_size; int *flow_stack = flow_max ? (int *)(output_args + max_output_args) : (int *)NULL; - int *pass_stack = flow_stack + flow_max; + int *pass_stack = flow_stack ? (int *)(flow_stack + flow_max) : (int *)NULL; for (int i = 0; i < f->node_count; i++) { sequence_bits[i] = false; //all starts as false @@ -1927,8 +1970,7 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p if (!E) { r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; - ERR_EXPLAIN("No VisualScriptFunction node in function!"); - ERR_FAIL_V(Variant()); + ERR_FAIL_V_MSG(Variant(), "No VisualScriptFunction node in function."); } VisualScriptNodeInstance *node = E->get(); @@ -1976,6 +2018,26 @@ void VisualScriptInstance::notification(int p_notification) { call(VisualScriptLanguage::singleton->notification, &whatp, 1, ce); //do as call } +String VisualScriptInstance::to_string(bool *r_valid) { + if (has_method(CoreStringNames::get_singleton()->_to_string)) { + Variant::CallError ce; + Variant ret = call(CoreStringNames::get_singleton()->_to_string, NULL, 0, ce); + if (ce.error == Variant::CallError::CALL_OK) { + if (ret.get_type() != Variant::STRING) { + if (r_valid) + *r_valid = false; + ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringNames::get_singleton()->_to_string + ", must be a String."); + } + if (r_valid) + *r_valid = true; + return ret.operator String(); + } + } + if (r_valid) + *r_valid = false; + return String(); +} + Ref<Script> VisualScriptInstance::get_script() const { return script; @@ -1983,6 +2045,9 @@ Ref<Script> VisualScriptInstance::get_script() const { MultiplayerAPI::RPCMode VisualScriptInstance::get_rpc_mode(const StringName &p_method) const { + if (p_method == script->get_default_func()) + return MultiplayerAPI::RPC_MODE_DISABLED; + const Map<StringName, VisualScript::Function>::Element *E = script->functions.find(p_method); if (!E) { return MultiplayerAPI::RPC_MODE_DISABLED; @@ -2031,11 +2096,14 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o for (const Map<StringName, VisualScript::Variable>::Element *E = script->variables.front(); E; E = E->next()) { variables[E->key()] = E->get().default_value; - //no hacer que todo exporte, solo las que queres! } for (const Map<StringName, VisualScript::Function>::Element *E = script->functions.front(); E; E = E->next()) { + if (E->key() == script->get_default_func()) { + continue; + } + Function function; function.node = E->get().function_id; function.max_stack = 0; @@ -2072,6 +2140,7 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o for (const Map<int, VisualScript::Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) { Ref<VisualScriptNode> node = F->get().node; + VisualScriptNodeInstance *instance = node->instance(this); //create instance ERR_FAIL_COND(!instance); @@ -2251,15 +2320,10 @@ Variant VisualScriptFunctionState::_signal_callback(const Variant **p_args, int ERR_FAIL_COND_V(function == StringName(), Variant()); #ifdef DEBUG_ENABLED - if (instance_id && !ObjectDB::get_instance(instance_id)) { - ERR_EXPLAIN("Resumed after yield, but class instance is gone"); - ERR_FAIL_V(Variant()); - } - if (script_id && !ObjectDB::get_instance(script_id)) { - ERR_EXPLAIN("Resumed after yield, but script is gone"); - ERR_FAIL_V(Variant()); - } + ERR_FAIL_COND_V_MSG(instance_id && !ObjectDB::get_instance(instance_id), Variant(), "Resumed after yield, but class instance is gone."); + ERR_FAIL_COND_V_MSG(script_id && !ObjectDB::get_instance(script_id), Variant(), "Resumed after yield, but script is gone."); + #endif r_error.error = Variant::CallError::CALL_OK; @@ -2318,15 +2382,10 @@ Variant VisualScriptFunctionState::resume(Array p_args) { ERR_FAIL_COND_V(function == StringName(), Variant()); #ifdef DEBUG_ENABLED - if (instance_id && !ObjectDB::get_instance(instance_id)) { - ERR_EXPLAIN("Resumed after yield, but class instance is gone"); - ERR_FAIL_V(Variant()); - } - if (script_id && !ObjectDB::get_instance(script_id)) { - ERR_EXPLAIN("Resumed after yield, but script is gone"); - ERR_FAIL_V(Variant()); - } + ERR_FAIL_COND_V_MSG(instance_id && !ObjectDB::get_instance(instance_id), Variant(), "Resumed after yield, but class instance is gone."); + ERR_FAIL_COND_V_MSG(script_id && !ObjectDB::get_instance(script_id), Variant(), "Resumed after yield, but script is gone."); + #endif Variant::CallError r_error; @@ -2452,7 +2511,7 @@ bool VisualScriptLanguage::debug_break_parse(const String &p_file, int p_node, c _debug_parse_err_node = p_node; _debug_parse_err_file = p_file; _debug_error = p_error; - ScriptDebugger::get_singleton()->debug(this, false); + ScriptDebugger::get_singleton()->debug(this, false, true); return true; } else { return false; @@ -2466,7 +2525,7 @@ bool VisualScriptLanguage::debug_break(const String &p_error, bool p_allow_conti _debug_parse_err_node = -1; _debug_parse_err_file = ""; _debug_error = p_error; - ScriptDebugger::get_singleton()->debug(this, p_allow_continue); + ScriptDebugger::get_singleton()->debug(this, p_allow_continue, true); return true; } else { return false; @@ -2618,8 +2677,6 @@ void VisualScriptLanguage::debug_get_globals(List<String> *p_locals, List<Varian } String VisualScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) { - if (_debug_parse_err_node >= 0) - return ""; return ""; } diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h index 0171b8e6f1..a035f6d42d 100644 --- a/modules/visual_script/visual_script.h +++ b/modules/visual_script/visual_script.h @@ -39,7 +39,7 @@ class VisualScriptNodeInstance; class VisualScript; class VisualScriptNode : public Resource { - GDCLASS(VisualScriptNode, Resource) + GDCLASS(VisualScriptNode, Resource); friend class VisualScript; @@ -54,7 +54,6 @@ class VisualScriptNode : public Resource { void validate_input_default_values(); protected: - void _notification(int p_what); void ports_changed_notify(); static void _bind_methods(); @@ -166,7 +165,7 @@ public: class VisualScript : public Script { - GDCLASS(VisualScript, Script) + GDCLASS(VisualScript, Script); RES_BASE_EXTENSION("vs"); @@ -240,6 +239,7 @@ private: PropertyInfo info; Variant default_value; bool _export; + // add getter & setter options here }; Map<StringName, Function> functions; @@ -248,6 +248,8 @@ private: Map<Object *, VisualScriptInstance *> instances; + bool is_tool_script; + #ifdef TOOLS_ENABLED Set<PlaceHolderScriptInstance *> placeholders; //void _update_placeholder(PlaceHolderScriptInstance *p_placeholder); @@ -266,6 +268,8 @@ protected: static void _bind_methods(); public: + // TODO: Remove it in future when breaking changes are acceptable + StringName get_default_func() const; void add_function(const StringName &p_name); bool has_function(const StringName &p_name) const; void remove_function(const StringName &p_name); @@ -274,6 +278,7 @@ public: Vector2 get_function_scroll(const StringName &p_name) const; void get_function_list(List<StringName> *r_functions) const; int get_function_node_id(const StringName &p_name) const; + void set_tool_enabled(bool p_enabled); void add_node(const StringName &p_func, int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos = Point2()); void remove_node(const StringName &p_func, int p_id); @@ -405,6 +410,7 @@ public: virtual bool has_method(const StringName &p_method) const; virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error); virtual void notification(int p_notification); + String to_string(bool *r_valid); bool set_variable(const StringName &p_variable, const Variant &p_value) { diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp index 0d379205e4..3fdceacebb 100644 --- a/modules/visual_script/visual_script_builtin_funcs.cpp +++ b/modules/visual_script/visual_script_builtin_funcs.cpp @@ -68,6 +68,7 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX "lerp", "inverse_lerp", "range_lerp", + "move_toward", "dectime", "randomize", "randi", @@ -102,6 +103,10 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX "var2bytes", "bytes2var", "color_named", + "smoothstep", + "posmod", + "lerp_angle", + "ord", }; VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::find_function(const String &p_string) { @@ -177,6 +182,7 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) { case OBJ_WEAKREF: case TYPE_OF: case TEXT_CHAR: + case TEXT_ORD: case TEXT_STR: case TEXT_PRINT: case TEXT_PRINTERR: @@ -190,6 +196,7 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) { case MATH_ATAN2: case MATH_FMOD: case MATH_FPOSMOD: + case MATH_POSMOD: case MATH_POW: case MATH_EASE: case MATH_STEPIFY: @@ -203,7 +210,10 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) { case COLORN: return 2; case MATH_LERP: + case MATH_LERP_ANGLE: case MATH_INVERSE_LERP: + case MATH_SMOOTHSTEP: + case MATH_MOVE_TOWARD: case MATH_DECTIME: case MATH_WRAP: case MATH_WRAPF: @@ -257,7 +267,16 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const case MATH_ASIN: case MATH_ACOS: case MATH_ATAN: - case MATH_SQRT: { + case MATH_SQRT: + case MATH_FLOOR: + case MATH_CEIL: + case MATH_ROUND: + case MATH_ABS: + case MATH_SIGN: + case MATH_LOG: + case MATH_EXP: + case MATH_ISNAN: + case MATH_ISINF: { return PropertyInfo(Variant::REAL, "s"); } break; case MATH_ATAN2: { @@ -267,32 +286,25 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const return PropertyInfo(Variant::REAL, "x"); } break; case MATH_FMOD: - case MATH_FPOSMOD: { + case MATH_FPOSMOD: + case LOGIC_MAX: + case LOGIC_MIN: { if (p_idx == 0) - return PropertyInfo(Variant::REAL, "x"); + return PropertyInfo(Variant::REAL, "a"); else - return PropertyInfo(Variant::REAL, "y"); + return PropertyInfo(Variant::REAL, "b"); } break; - case MATH_FLOOR: - case MATH_CEIL: - case MATH_ROUND: - case MATH_ABS: - case MATH_SIGN: { - return PropertyInfo(Variant::REAL, "s"); - + case MATH_POSMOD: { + if (p_idx == 0) + return PropertyInfo(Variant::INT, "a"); + else + return PropertyInfo(Variant::INT, "b"); } break; - case MATH_POW: { if (p_idx == 0) - return PropertyInfo(Variant::REAL, "x"); + return PropertyInfo(Variant::REAL, "base"); else - return PropertyInfo(Variant::REAL, "y"); - } break; - case MATH_LOG: - case MATH_EXP: - case MATH_ISNAN: - case MATH_ISINF: { - return PropertyInfo(Variant::REAL, "s"); + return PropertyInfo(Variant::REAL, "exp"); } break; case MATH_EASE: { if (p_idx == 0) @@ -309,15 +321,10 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const else return PropertyInfo(Variant::REAL, "steps"); } break; - case MATH_LERP: { - if (p_idx == 0) - return PropertyInfo(Variant::REAL, "from"); - else if (p_idx == 1) - return PropertyInfo(Variant::REAL, "to"); - else - return PropertyInfo(Variant::REAL, "weight"); - } break; - case MATH_INVERSE_LERP: { + case MATH_LERP: + case MATH_LERP_ANGLE: + case MATH_INVERSE_LERP: + case MATH_SMOOTHSTEP: { if (p_idx == 0) return PropertyInfo(Variant::REAL, "from"); else if (p_idx == 1) @@ -337,6 +344,14 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const else return PropertyInfo(Variant::REAL, "ostop"); } break; + case MATH_MOVE_TOWARD: { + if (p_idx == 0) + return PropertyInfo(Variant::REAL, "from"); + else if (p_idx == 1) + return PropertyInfo(Variant::REAL, "to"); + else + return PropertyInfo(Variant::REAL, "delta"); + } break; case MATH_DECTIME: { if (p_idx == 0) return PropertyInfo(Variant::REAL, "value"); @@ -345,12 +360,8 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const else return PropertyInfo(Variant::REAL, "step"); } break; - case MATH_RANDOMIZE: { - - } break; - case MATH_RAND: { - - } break; + case MATH_RANDOMIZE: + case MATH_RAND: case MATH_RANDF: { } break; @@ -360,9 +371,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const else return PropertyInfo(Variant::REAL, "to"); } break; - case MATH_SEED: { - return PropertyInfo(Variant::INT, "seed"); - } break; + case MATH_SEED: case MATH_RANDSEED: { return PropertyInfo(Variant::INT, "seed"); } break; @@ -398,26 +407,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const else return PropertyInfo(Variant::INT, "max"); } break; - case MATH_WRAPF: { - if (p_idx == 0) - return PropertyInfo(Variant::REAL, "value"); - else if (p_idx == 1) - return PropertyInfo(Variant::REAL, "min"); - else - return PropertyInfo(Variant::REAL, "max"); - } break; - case LOGIC_MAX: { - if (p_idx == 0) - return PropertyInfo(Variant::REAL, "a"); - else - return PropertyInfo(Variant::REAL, "b"); - } break; - case LOGIC_MIN: { - if (p_idx == 0) - return PropertyInfo(Variant::REAL, "a"); - else - return PropertyInfo(Variant::REAL, "b"); - } break; + case MATH_WRAPF: case LOGIC_CLAMP: { if (p_idx == 0) return PropertyInfo(Variant::REAL, "value"); @@ -430,20 +420,15 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const return PropertyInfo(Variant::INT, "value"); } break; case OBJ_WEAKREF: { - return PropertyInfo(Variant::OBJECT, "source"); - } break; case FUNC_FUNCREF: { - if (p_idx == 0) return PropertyInfo(Variant::OBJECT, "instance"); else return PropertyInfo(Variant::STRING, "funcname"); - } break; case TYPE_CONVERT: { - if (p_idx == 0) return PropertyInfo(Variant::NIL, "what"); else @@ -451,45 +436,27 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const } break; case TYPE_OF: { return PropertyInfo(Variant::NIL, "what"); - } break; case TYPE_EXISTS: { - return PropertyInfo(Variant::STRING, "type"); - + } break; + case TEXT_ORD: { + return PropertyInfo(Variant::STRING, "character"); } break; case TEXT_CHAR: { - return PropertyInfo(Variant::INT, "ascii"); - - } break; - case TEXT_STR: { - - return PropertyInfo(Variant::NIL, "value"); - - } break; - case TEXT_PRINT: { - - return PropertyInfo(Variant::NIL, "value"); - - } break; - case TEXT_PRINTERR: { - return PropertyInfo(Variant::NIL, "value"); - } break; + case TEXT_STR: + case TEXT_PRINT: + case TEXT_PRINTERR: case TEXT_PRINTRAW: { - return PropertyInfo(Variant::NIL, "value"); - - } break; - case VAR_TO_STR: { - return PropertyInfo(Variant::NIL, "var"); - } break; case STR_TO_VAR: { return PropertyInfo(Variant::STRING, "string"); } break; + case VAR_TO_STR: case VAR_TO_BYTES: { if (p_idx == 0) return PropertyInfo(Variant::NIL, "var"); @@ -505,12 +472,10 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const return PropertyInfo(Variant::BOOL, "allow_objects"); } break; case COLORN: { - if (p_idx == 0) return PropertyInfo(Variant::STRING, "name"); else return PropertyInfo(Variant::REAL, "alpha"); - } break; case FUNC_MAX: { } @@ -541,6 +506,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons case MATH_CEIL: { t = Variant::REAL; } break; + case MATH_POSMOD: case MATH_ROUND: { t = Variant::INT; } break; @@ -567,8 +533,11 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons } break; case MATH_STEPIFY: case MATH_LERP: + case MATH_LERP_ANGLE: case MATH_INVERSE_LERP: case MATH_RANGE_LERP: + case MATH_SMOOTHSTEP: + case MATH_MOVE_TOWARD: case MATH_DECTIME: { t = Variant::REAL; @@ -630,6 +599,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons case TYPE_CONVERT: { } break; + case TEXT_ORD: case TYPE_OF: { t = Variant::INT; @@ -784,6 +754,12 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in VALIDATE_ARG_NUM(1); *r_return = Math::fposmod((double)*p_inputs[0], (double)*p_inputs[1]); } break; + case VisualScriptBuiltinFunc::MATH_POSMOD: { + + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + *r_return = Math::posmod((int)*p_inputs[0], (int)*p_inputs[1]); + } break; case VisualScriptBuiltinFunc::MATH_FLOOR: { VALIDATE_ARG_NUM(0); @@ -883,6 +859,13 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in VALIDATE_ARG_NUM(2); *r_return = Math::lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]); } break; + case VisualScriptBuiltinFunc::MATH_LERP_ANGLE: { + + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + VALIDATE_ARG_NUM(2); + *r_return = Math::lerp_angle((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]); + } break; case VisualScriptBuiltinFunc::MATH_INVERSE_LERP: { VALIDATE_ARG_NUM(0); @@ -899,6 +882,19 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in VALIDATE_ARG_NUM(4); *r_return = Math::range_lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2], (double)*p_inputs[3], (double)*p_inputs[4]); } break; + case VisualScriptBuiltinFunc::MATH_SMOOTHSTEP: { + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + VALIDATE_ARG_NUM(2); + *r_return = Math::smoothstep((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]); + } break; + case VisualScriptBuiltinFunc::MATH_MOVE_TOWARD: { + + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + VALIDATE_ARG_NUM(2); + *r_return = Math::move_toward((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]); + } break; case VisualScriptBuiltinFunc::MATH_DECTIME: { VALIDATE_ARG_NUM(0); @@ -1142,6 +1138,30 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in *r_return = String(result); } break; + case VisualScriptBuiltinFunc::TEXT_ORD: { + + if (p_inputs[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + + return; + } + + String str = p_inputs[0]->operator String(); + + if (str.length() != 1) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + *r_return = "Expected a string of length 1 (a character)."; + + return; + } + + *r_return = str.get(0); + + } break; case VisualScriptBuiltinFunc::TEXT_STR: { String str = *p_inputs[0]; @@ -1270,7 +1290,8 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in *r_return = String(color); } break; - default: {} + default: { + } } } @@ -1345,6 +1366,7 @@ void VisualScriptBuiltinFunc::_bind_methods() { BIND_ENUM_CONSTANT(MATH_LERP); BIND_ENUM_CONSTANT(MATH_INVERSE_LERP); BIND_ENUM_CONSTANT(MATH_RANGE_LERP); + BIND_ENUM_CONSTANT(MATH_MOVE_TOWARD); BIND_ENUM_CONSTANT(MATH_DECTIME); BIND_ENUM_CONSTANT(MATH_RANDOMIZE); BIND_ENUM_CONSTANT(MATH_RAND); @@ -1379,6 +1401,10 @@ void VisualScriptBuiltinFunc::_bind_methods() { BIND_ENUM_CONSTANT(VAR_TO_BYTES); BIND_ENUM_CONSTANT(BYTES_TO_VAR); BIND_ENUM_CONSTANT(COLORN); + BIND_ENUM_CONSTANT(MATH_SMOOTHSTEP); + BIND_ENUM_CONSTANT(MATH_POSMOD); + BIND_ENUM_CONSTANT(MATH_LERP_ANGLE); + BIND_ENUM_CONSTANT(TEXT_ORD); BIND_ENUM_CONSTANT(FUNC_MAX); } @@ -1416,6 +1442,7 @@ void register_visual_script_builtin_func_node() { VisualScriptLanguage::singleton->add_register_func("functions/built_in/sqrt", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SQRT>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/fmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FMOD>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/fposmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FPOSMOD>); + VisualScriptLanguage::singleton->add_register_func("functions/built_in/posmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_POSMOD>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/floor", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FLOOR>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/ceil", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_CEIL>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/round", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ROUND>); @@ -1431,8 +1458,11 @@ void register_visual_script_builtin_func_node() { VisualScriptLanguage::singleton->add_register_func("functions/built_in/decimals", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DECIMALS>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/stepify", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_STEPIFY>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LERP>); + VisualScriptLanguage::singleton->add_register_func("functions/built_in/lerp_angle", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LERP_ANGLE>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/inverse_lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_INVERSE_LERP>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/range_lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANGE_LERP>); + VisualScriptLanguage::singleton->add_register_func("functions/built_in/smoothstep", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SMOOTHSTEP>); + VisualScriptLanguage::singleton->add_register_func("functions/built_in/move_toward", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_MOVE_TOWARD>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/dectime", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DECTIME>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/randomize", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDOMIZE>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/rand", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RAND>); @@ -1461,6 +1491,7 @@ void register_visual_script_builtin_func_node() { VisualScriptLanguage::singleton->add_register_func("functions/built_in/typeof", create_builtin_func_node<VisualScriptBuiltinFunc::TYPE_OF>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/type_exists", create_builtin_func_node<VisualScriptBuiltinFunc::TYPE_EXISTS>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/char", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_CHAR>); + VisualScriptLanguage::singleton->add_register_func("functions/built_in/ord", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_ORD>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/str", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_STR>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/print", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINT>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/printerr", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINTERR>); diff --git a/modules/visual_script/visual_script_builtin_funcs.h b/modules/visual_script/visual_script_builtin_funcs.h index 2d8454ddd4..998a6cbc6a 100644 --- a/modules/visual_script/visual_script_builtin_funcs.h +++ b/modules/visual_script/visual_script_builtin_funcs.h @@ -35,7 +35,8 @@ class VisualScriptBuiltinFunc : public VisualScriptNode { - GDCLASS(VisualScriptBuiltinFunc, VisualScriptNode) + GDCLASS(VisualScriptBuiltinFunc, VisualScriptNode); + public: enum BuiltinFunc { MATH_SIN, @@ -67,6 +68,7 @@ public: MATH_LERP, MATH_INVERSE_LERP, MATH_RANGE_LERP, + MATH_MOVE_TOWARD, MATH_DECTIME, MATH_RANDOMIZE, MATH_RAND, @@ -101,6 +103,10 @@ public: VAR_TO_BYTES, BYTES_TO_VAR, COLORN, + MATH_SMOOTHSTEP, + MATH_POSMOD, + MATH_LERP_ANGLE, + TEXT_ORD, FUNC_MAX }; diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp index 6e7e566206..bf353d287f 100644 --- a/modules/visual_script/visual_script_editor.cpp +++ b/modules/visual_script/visual_script_editor.cpp @@ -37,6 +37,7 @@ #include "core/variant.h" #include "editor/editor_node.h" #include "editor/editor_resource_preview.h" +#include "scene/main/viewport.h" #include "visual_script_expression.h" #include "visual_script_flow_control.h" #include "visual_script_func_nodes.h" @@ -45,7 +46,7 @@ #ifdef TOOLS_ENABLED class VisualScriptEditorSignalEdit : public Object { - GDCLASS(VisualScriptEditorSignalEdit, Object) + GDCLASS(VisualScriptEditorSignalEdit, Object); StringName sig; @@ -185,7 +186,7 @@ public: class VisualScriptEditorVariableEdit : public Object { - GDCLASS(VisualScriptEditorVariableEdit, Object) + GDCLASS(VisualScriptEditorVariableEdit, Object); StringName var; @@ -340,74 +341,74 @@ static Color _color_from_type(Variant::Type p_type, bool dark_theme = true) { Color color; if (dark_theme) switch (p_type) { - case Variant::NIL: color = Color::html("#69ecbd"); break; - - case Variant::BOOL: color = Color::html("#8da6f0"); break; - case Variant::INT: color = Color::html("#7dc6ef"); break; - case Variant::REAL: color = Color::html("#61daf4"); break; - case Variant::STRING: color = Color::html("#6ba7ec"); break; - - case Variant::VECTOR2: color = Color::html("#bd91f1"); break; - case Variant::RECT2: color = Color::html("#f191a5"); break; - case Variant::VECTOR3: color = Color::html("#d67dee"); break; - case Variant::TRANSFORM2D: color = Color::html("#c4ec69"); break; - case Variant::PLANE: color = Color::html("#f77070"); break; - case Variant::QUAT: color = Color::html("#ec69a3"); break; - case Variant::AABB: color = Color::html("#ee7991"); break; - case Variant::BASIS: color = Color::html("#e3ec69"); break; - case Variant::TRANSFORM: color = Color::html("#f6a86e"); break; - - case Variant::COLOR: color = Color::html("#9dff70"); break; - case Variant::NODE_PATH: color = Color::html("#6993ec"); break; - case Variant::_RID: color = Color::html("#69ec9a"); break; - case Variant::OBJECT: color = Color::html("#79f3e8"); break; - case Variant::DICTIONARY: color = Color::html("#77edb1"); break; - - case Variant::ARRAY: color = Color::html("#e0e0e0"); break; - case Variant::POOL_BYTE_ARRAY: color = Color::html("#aaf4c8"); break; - case Variant::POOL_INT_ARRAY: color = Color::html("#afdcf5"); break; - case Variant::POOL_REAL_ARRAY: color = Color::html("#97e7f8"); break; - case Variant::POOL_STRING_ARRAY: color = Color::html("#9dc4f2"); break; - case Variant::POOL_VECTOR2_ARRAY: color = Color::html("#d1b3f5"); break; - case Variant::POOL_VECTOR3_ARRAY: color = Color::html("#df9bf2"); break; - case Variant::POOL_COLOR_ARRAY: color = Color::html("#e9ff97"); break; + case Variant::NIL: color = Color(0.41, 0.93, 0.74); break; + + case Variant::BOOL: color = Color(0.55, 0.65, 0.94); break; + case Variant::INT: color = Color(0.49, 0.78, 0.94); break; + case Variant::REAL: color = Color(0.38, 0.85, 0.96); break; + case Variant::STRING: color = Color(0.42, 0.65, 0.93); break; + + case Variant::VECTOR2: color = Color(0.74, 0.57, 0.95); break; + case Variant::RECT2: color = Color(0.95, 0.57, 0.65); break; + case Variant::VECTOR3: color = Color(0.84, 0.49, 0.93); break; + case Variant::TRANSFORM2D: color = Color(0.77, 0.93, 0.41); break; + case Variant::PLANE: color = Color(0.97, 0.44, 0.44); break; + case Variant::QUAT: color = Color(0.93, 0.41, 0.64); break; + case Variant::AABB: color = Color(0.93, 0.47, 0.57); break; + case Variant::BASIS: color = Color(0.89, 0.93, 0.41); break; + case Variant::TRANSFORM: color = Color(0.96, 0.66, 0.43); break; + + case Variant::COLOR: color = Color(0.62, 1.0, 0.44); break; + case Variant::NODE_PATH: color = Color(0.41, 0.58, 0.93); break; + case Variant::_RID: color = Color(0.41, 0.93, 0.6); break; + case Variant::OBJECT: color = Color(0.47, 0.95, 0.91); break; + case Variant::DICTIONARY: color = Color(0.47, 0.93, 0.69); break; + + case Variant::ARRAY: color = Color(0.88, 0.88, 0.88); break; + case Variant::POOL_BYTE_ARRAY: color = Color(0.67, 0.96, 0.78); break; + case Variant::POOL_INT_ARRAY: color = Color(0.69, 0.86, 0.96); break; + case Variant::POOL_REAL_ARRAY: color = Color(0.59, 0.91, 0.97); break; + case Variant::POOL_STRING_ARRAY: color = Color(0.62, 0.77, 0.95); break; + case Variant::POOL_VECTOR2_ARRAY: color = Color(0.82, 0.7, 0.96); break; + case Variant::POOL_VECTOR3_ARRAY: color = Color(0.87, 0.61, 0.95); break; + case Variant::POOL_COLOR_ARRAY: color = Color(0.91, 1.0, 0.59); break; default: color.set_hsv(p_type / float(Variant::VARIANT_MAX), 0.7, 0.7); } else switch (p_type) { - case Variant::NIL: color = Color::html("#25e3a0"); break; - - case Variant::BOOL: color = Color::html("#6d8eeb"); break; - case Variant::INT: color = Color::html("#4fb2e9"); break; - case Variant::REAL: color = Color::html("#27ccf0"); break; - case Variant::STRING: color = Color::html("#4690e7"); break; - - case Variant::VECTOR2: color = Color::html("#ad76ee"); break; - case Variant::RECT2: color = Color::html("#ee758e"); break; - case Variant::VECTOR3: color = Color::html("#dc6aed"); break; - case Variant::TRANSFORM2D: color = Color::html("#96ce1a"); break; - case Variant::PLANE: color = Color::html("#f77070"); break; - case Variant::QUAT: color = Color::html("#ec69a3"); break; - case Variant::AABB: color = Color::html("#ee7991"); break; - case Variant::BASIS: color = Color::html("#b2bb19"); break; - case Variant::TRANSFORM: color = Color::html("#f49047"); break; - - case Variant::COLOR: color = Color::html("#3cbf00"); break; - case Variant::NODE_PATH: color = Color::html("#6993ec"); break; - case Variant::_RID: color = Color::html("#2ce573"); break; - case Variant::OBJECT: color = Color::html("#12d5c3"); break; - case Variant::DICTIONARY: color = Color::html("#57e99f"); break; - - case Variant::ARRAY: color = Color::html("#737373"); break; - case Variant::POOL_BYTE_ARRAY: color = Color::html("#61ea98"); break; - case Variant::POOL_INT_ARRAY: color = Color::html("#61baeb"); break; - case Variant::POOL_REAL_ARRAY: color = Color::html("#40d3f2"); break; - case Variant::POOL_STRING_ARRAY: color = Color::html("#609fea"); break; - case Variant::POOL_VECTOR2_ARRAY: color = Color::html("#9d5dea"); break; - case Variant::POOL_VECTOR3_ARRAY: color = Color::html("#ca5aea"); break; - case Variant::POOL_COLOR_ARRAY: color = Color::html("#92ba00"); break; + case Variant::NIL: color = Color(0.15, 0.89, 0.63); break; + + case Variant::BOOL: color = Color(0.43, 0.56, 0.92); break; + case Variant::INT: color = Color(0.31, 0.7, 0.91); break; + case Variant::REAL: color = Color(0.15, 0.8, 0.94); break; + case Variant::STRING: color = Color(0.27, 0.56, 0.91); break; + + case Variant::VECTOR2: color = Color(0.68, 0.46, 0.93); break; + case Variant::RECT2: color = Color(0.93, 0.46, 0.56); break; + case Variant::VECTOR3: color = Color(0.86, 0.42, 0.93); break; + case Variant::TRANSFORM2D: color = Color(0.59, 0.81, 0.1); break; + case Variant::PLANE: color = Color(0.97, 0.44, 0.44); break; + case Variant::QUAT: color = Color(0.93, 0.41, 0.64); break; + case Variant::AABB: color = Color(0.93, 0.47, 0.57); break; + case Variant::BASIS: color = Color(0.7, 0.73, 0.1); break; + case Variant::TRANSFORM: color = Color(0.96, 0.56, 0.28); break; + + case Variant::COLOR: color = Color(0.24, 0.75, 0.0); break; + case Variant::NODE_PATH: color = Color(0.41, 0.58, 0.93); break; + case Variant::_RID: color = Color(0.17, 0.9, 0.45); break; + case Variant::OBJECT: color = Color(0.07, 0.84, 0.76); break; + case Variant::DICTIONARY: color = Color(0.34, 0.91, 0.62); break; + + case Variant::ARRAY: color = Color(0.45, 0.45, 0.45); break; + case Variant::POOL_BYTE_ARRAY: color = Color(0.38, 0.92, 0.6); break; + case Variant::POOL_INT_ARRAY: color = Color(0.38, 0.73, 0.92); break; + case Variant::POOL_REAL_ARRAY: color = Color(0.25, 0.83, 0.95); break; + case Variant::POOL_STRING_ARRAY: color = Color(0.38, 0.62, 0.92); break; + case Variant::POOL_VECTOR2_ARRAY: color = Color(0.62, 0.36, 0.92); break; + case Variant::POOL_VECTOR3_ARRAY: color = Color(0.79, 0.35, 0.92); break; + case Variant::POOL_COLOR_ARRAY: color = Color(0.57, 0.73, 0.0); break; default: color.set_hsv(p_type / float(Variant::VARIANT_MAX), 0.3, 0.3); @@ -420,31 +421,42 @@ void VisualScriptEditor::_update_graph_connections() { graph->clear_connections(); - List<VisualScript::SequenceConnection> sequence_conns; - script->get_sequence_connection_list(edited_func, &sequence_conns); - - for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { + List<StringName> funcs; + script->get_function_list(&funcs); - graph->connect_node(itos(E->get().from_node), E->get().from_output, itos(E->get().to_node), 0); + if (funcs.size() <= 0) { + updating_graph = false; + return; } - List<VisualScript::DataConnection> data_conns; - script->get_data_connection_list(edited_func, &data_conns); - - for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { + for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) { - VisualScript::DataConnection dc = E->get(); + List<VisualScript::SequenceConnection> sequence_conns; + script->get_sequence_connection_list(F->get(), &sequence_conns); - Ref<VisualScriptNode> from_node = script->get_node(edited_func, E->get().from_node); - Ref<VisualScriptNode> to_node = script->get_node(edited_func, E->get().to_node); + for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { - if (to_node->has_input_sequence_port()) { - dc.to_port++; + graph->connect_node(itos(E->get().from_node), E->get().from_output, itos(E->get().to_node), 0); } - dc.from_port += from_node->get_output_sequence_port_count(); + List<VisualScript::DataConnection> data_conns; + script->get_data_connection_list(F->get(), &data_conns); + + for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { + + VisualScript::DataConnection dc = E->get(); + + Ref<VisualScriptNode> from_node = script->get_node(F->get(), E->get().from_node); + Ref<VisualScriptNode> to_node = script->get_node(F->get(), E->get().to_node); + + if (to_node->has_input_sequence_port()) { + dc.to_port++; + } + + dc.from_port += from_node->get_output_sequence_port_count(); - graph->connect_node(itos(E->get().from_node), dc.from_port, itos(E->get().to_node), dc.to_port); + graph->connect_node(itos(E->get().from_node), dc.from_port, itos(E->get().to_node), dc.to_port); + } } } @@ -473,7 +485,10 @@ void VisualScriptEditor::_update_graph(int p_only_id) { } } - if (!script->has_function(edited_func)) { + List<StringName> funcs; + script->get_function_list(&funcs); + + if (funcs.size() <= 0) { graph->hide(); select_func_text->show(); updating_graph = false; @@ -515,253 +530,390 @@ void VisualScriptEditor::_update_graph(int p_only_id) { Ref<Texture> seq_port = Control::get_icon("VisualShaderPort", "EditorIcons"); - List<int> ids; - script->get_node_list(edited_func, &ids); - StringName editor_icons = "EditorIcons"; + for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) { // loop through all the functions - for (List<int>::Element *E = ids.front(); E; E = E->next()) { + List<int> ids; + script->get_node_list(F->get(), &ids); + StringName editor_icons = "EditorIcons"; - if (p_only_id >= 0 && p_only_id != E->get()) - continue; + for (List<int>::Element *E = ids.front(); E; E = E->next()) { - Ref<VisualScriptNode> node = script->get_node(edited_func, E->get()); - Vector2 pos = script->get_node_position(edited_func, E->get()); + if (p_only_id >= 0 && p_only_id != E->get()) + continue; - GraphNode *gnode = memnew(GraphNode); - gnode->set_title(node->get_caption()); - gnode->set_offset(pos * EDSCALE); - if (error_line == E->get()) { - gnode->set_overlay(GraphNode::OVERLAY_POSITION); - } else if (node->is_breakpoint()) { - gnode->set_overlay(GraphNode::OVERLAY_BREAKPOINT); - } + Ref<VisualScriptNode> node = script->get_node(F->get(), E->get()); + Vector2 pos = script->get_node_position(F->get(), E->get()); - gnode->set_meta("__vnode", node); - gnode->set_name(itos(E->get())); - gnode->connect("dragged", this, "_node_moved", varray(E->get())); - gnode->connect("close_request", this, "_remove_node", varray(E->get()), CONNECT_DEFERRED); + GraphNode *gnode = memnew(GraphNode); + gnode->set_title(node->get_caption()); + gnode->set_offset(pos * EDSCALE); + if (error_line == E->get()) { + gnode->set_overlay(GraphNode::OVERLAY_POSITION); + } else if (node->is_breakpoint()) { + gnode->set_overlay(GraphNode::OVERLAY_BREAKPOINT); + } - if (E->get() != script->get_function_node_id(edited_func)) { - //function can't be erased - gnode->set_show_close_button(true); - } + gnode->set_meta("__vnode", node); + gnode->set_name(itos(E->get())); + gnode->connect("dragged", this, "_node_moved", varray(E->get())); + gnode->connect("close_request", this, "_remove_node", varray(E->get()), CONNECT_DEFERRED); - bool has_gnode_text = false; + if (E->get() != script->get_function_node_id(F->get())) { + //function can't be erased + gnode->set_show_close_button(true); + } - if (Object::cast_to<VisualScriptExpression>(node.ptr())) { - has_gnode_text = true; - LineEdit *line_edit = memnew(LineEdit); - line_edit->set_text(node->get_text()); - line_edit->set_expand_to_text_length(true); - line_edit->add_font_override("font", get_font("source", "EditorFonts")); - gnode->add_child(line_edit); - line_edit->connect("text_changed", this, "_expression_text_changed", varray(E->get())); - } else { - String text = node->get_text(); - if (!text.empty()) { + bool has_gnode_text = false; + + Ref<VisualScriptLists> nd_list = node; + bool is_vslist = nd_list.is_valid(); + if (is_vslist) { + HBoxContainer *hbnc = memnew(HBoxContainer); + if (nd_list->is_input_port_editable()) { + has_gnode_text = true; + Button *btn = memnew(Button); + btn->set_text("Add Input Port"); + hbnc->add_child(btn); + btn->connect("pressed", this, "_add_input_port", varray(E->get())); + } + if (nd_list->is_output_port_editable()) { + if (nd_list->is_input_port_editable()) + hbnc->add_spacer(); + has_gnode_text = true; + Button *btn = memnew(Button); + btn->set_text("Add Output Port"); + hbnc->add_child(btn); + btn->connect("pressed", this, "_add_output_port", varray(E->get())); + } + gnode->add_child(hbnc); + } else if (Object::cast_to<VisualScriptExpression>(node.ptr())) { has_gnode_text = true; - Label *label = memnew(Label); - label->set_text(text); - gnode->add_child(label); + LineEdit *line_edit = memnew(LineEdit); + line_edit->set_text(node->get_text()); + line_edit->set_expand_to_text_length(true); + line_edit->add_font_override("font", get_font("source", "EditorFonts")); + gnode->add_child(line_edit); + line_edit->connect("text_changed", this, "_expression_text_changed", varray(E->get())); + } else { + String text = node->get_text(); + if (!text.empty()) { + has_gnode_text = true; + Label *label = memnew(Label); + label->set_text(text); + gnode->add_child(label); + } } - } - - if (Object::cast_to<VisualScriptComment>(node.ptr())) { - Ref<VisualScriptComment> vsc = node; - gnode->set_comment(true); - gnode->set_resizable(true); - gnode->set_custom_minimum_size(vsc->get_size() * EDSCALE); - gnode->connect("resize_request", this, "_comment_node_resized", varray(E->get())); - } - - if (node_styles.has(node->get_category())) { - Ref<StyleBoxFlat> sbf = node_styles[node->get_category()]; - if (gnode->is_comment()) - sbf = EditorNode::get_singleton()->get_theme_base()->get_theme()->get_stylebox("comment", "GraphNode"); - Color c = sbf->get_border_color(); - c.a = 1; - if (EditorSettings::get_singleton()->get("interface/theme/use_graph_node_headers")) { - Color mono_color = ((c.r + c.g + c.b) / 3) < 0.7 ? Color(1.0, 1.0, 1.0) : Color(0.0, 0.0, 0.0); - mono_color.a = 0.85; - c = mono_color; + if (Object::cast_to<VisualScriptComment>(node.ptr())) { + Ref<VisualScriptComment> vsc = node; + gnode->set_comment(true); + gnode->set_resizable(true); + gnode->set_custom_minimum_size(vsc->get_size() * EDSCALE); + gnode->connect("resize_request", this, "_comment_node_resized", varray(E->get())); } - gnode->add_color_override("title_color", c); - c.a = 0.7; - gnode->add_color_override("close_color", c); - gnode->add_style_override("frame", sbf); - } - - const Color mono_color = get_color("mono_color", "Editor"); - - int slot_idx = 0; - - bool single_seq_output = node->get_output_sequence_port_count() == 1 && node->get_output_sequence_port_text(0) == String(); - if ((node->has_input_sequence_port() || single_seq_output) || has_gnode_text) { - // IF has_gnode_text is true BUT we have no sequence ports to draw (in here), - // we still draw the disabled default ones to shift up the slots by one, - // so the slots DON'T start with the content text. - - // IF has_gnode_text is false, but we DO want to draw default sequence ports, - // we draw a dummy text to take up the position of the sequence nodes, so all the other ports are still aligned correctly. - if (!has_gnode_text) { - Label *dummy = memnew(Label); - dummy->set_text(" "); - gnode->add_child(dummy); + if (node_styles.has(node->get_category())) { + Ref<StyleBoxFlat> sbf = node_styles[node->get_category()]; + if (gnode->is_comment()) + sbf = EditorNode::get_singleton()->get_theme_base()->get_theme()->get_stylebox("comment", "GraphNode"); + + Color c = sbf->get_border_color(); + c.a = 1; + if (EditorSettings::get_singleton()->get("interface/theme/use_graph_node_headers")) { + Color mono_color = ((c.r + c.g + c.b) / 3) < 0.7 ? Color(1.0, 1.0, 1.0) : Color(0.0, 0.0, 0.0); + mono_color.a = 0.85; + c = mono_color; + } + gnode->add_color_override("title_color", c); + c.a = 0.7; + gnode->add_color_override("close_color", c); + gnode->add_color_override("resizer_color", c); + gnode->add_style_override("frame", sbf); } - gnode->set_slot(0, node->has_input_sequence_port(), TYPE_SEQUENCE, mono_color, single_seq_output, TYPE_SEQUENCE, mono_color, seq_port, seq_port); - slot_idx++; - } - int mixed_seq_ports = 0; + const Color mono_color = get_color("mono_color", "Editor"); - if (!single_seq_output) { + int slot_idx = 0; - if (node->has_mixed_input_and_sequence_ports()) { - mixed_seq_ports = node->get_output_sequence_port_count(); - } else { - for (int i = 0; i < node->get_output_sequence_port_count(); i++) { + bool single_seq_output = node->get_output_sequence_port_count() == 1 && node->get_output_sequence_port_text(0) == String(); + if ((node->has_input_sequence_port() || single_seq_output) || has_gnode_text) { + // IF has_gnode_text is true BUT we have no sequence ports to draw (in here), + // we still draw the disabled default ones to shift up the slots by one, + // so the slots DON'T start with the content text. - Label *text2 = memnew(Label); - text2->set_text(node->get_output_sequence_port_text(i)); - text2->set_align(Label::ALIGN_RIGHT); - gnode->add_child(text2); - gnode->set_slot(slot_idx, false, 0, Color(), true, TYPE_SEQUENCE, mono_color, seq_port, seq_port); - slot_idx++; + // IF has_gnode_text is false, but we DO want to draw default sequence ports, + // we draw a dummy text to take up the position of the sequence nodes, so all the other ports are still aligned correctly. + if (!has_gnode_text) { + Label *dummy = memnew(Label); + dummy->set_text(" "); + gnode->add_child(dummy); } + gnode->set_slot(0, node->has_input_sequence_port(), TYPE_SEQUENCE, mono_color, single_seq_output, TYPE_SEQUENCE, mono_color, seq_port, seq_port); + slot_idx++; } - } - for (int i = 0; i < MAX(node->get_output_value_port_count(), MAX(mixed_seq_ports, node->get_input_value_port_count())); i++) { + int mixed_seq_ports = 0; - bool left_ok = false; - Variant::Type left_type = Variant::NIL; - String left_name; + if (!single_seq_output) { - if (i < node->get_input_value_port_count()) { - PropertyInfo pi = node->get_input_value_port_info(i); - left_ok = true; - left_type = pi.type; - left_name = pi.name; + if (node->has_mixed_input_and_sequence_ports()) { + mixed_seq_ports = node->get_output_sequence_port_count(); + } else { + for (int i = 0; i < node->get_output_sequence_port_count(); i++) { + + Label *text2 = memnew(Label); + text2->set_text(node->get_output_sequence_port_text(i)); + text2->set_align(Label::ALIGN_RIGHT); + gnode->add_child(text2); + gnode->set_slot(slot_idx, false, 0, Color(), true, TYPE_SEQUENCE, mono_color, seq_port, seq_port); + slot_idx++; + } + } } - bool right_ok = false; - Variant::Type right_type = Variant::NIL; - String right_name; + for (int i = 0; i < MAX(node->get_output_value_port_count(), MAX(mixed_seq_ports, node->get_input_value_port_count())); i++) { - if (i >= mixed_seq_ports && i < node->get_output_value_port_count() + mixed_seq_ports) { - PropertyInfo pi = node->get_output_value_port_info(i - mixed_seq_ports); - right_ok = true; - right_type = pi.type; - right_name = pi.name; - } + bool left_ok = false; + Variant::Type left_type = Variant::NIL; + String left_name; - HBoxContainer *hbc = memnew(HBoxContainer); + if (i < node->get_input_value_port_count()) { + PropertyInfo pi = node->get_input_value_port_info(i); + left_ok = true; + left_type = pi.type; + left_name = pi.name; + } - if (left_ok) { + bool right_ok = false; + Variant::Type right_type = Variant::NIL; + String right_name; - Ref<Texture> t; - if (left_type >= 0 && left_type < Variant::VARIANT_MAX) { - t = type_icons[left_type]; - } - if (t.is_valid()) { - TextureRect *tf = memnew(TextureRect); - tf->set_texture(t); - tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); - hbc->add_child(tf); + if (i >= mixed_seq_ports && i < node->get_output_value_port_count() + mixed_seq_ports) { + PropertyInfo pi = node->get_output_value_port_info(i - mixed_seq_ports); + right_ok = true; + right_type = pi.type; + right_name = pi.name; } + VBoxContainer *vbc = memnew(VBoxContainer); + HBoxContainer *hbc = memnew(HBoxContainer); + HBoxContainer *hbc2 = memnew(HBoxContainer); + vbc->add_child(hbc); + vbc->add_child(hbc2); + if (left_ok) { + + Ref<Texture> t; + if (left_type >= 0 && left_type < Variant::VARIANT_MAX) { + t = type_icons[left_type]; + } + if (t.is_valid()) { + TextureRect *tf = memnew(TextureRect); + tf->set_texture(t); + tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); + hbc->add_child(tf); + } - hbc->add_child(memnew(Label(left_name))); + if (is_vslist) { + if (nd_list->is_input_port_name_editable()) { + LineEdit *name_box = memnew(LineEdit); + hbc->add_child(name_box); + name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0)); + name_box->set_text(left_name); + name_box->set_expand_to_text_length(true); + name_box->connect("resized", this, "_update_node_size", varray(E->get())); + name_box->connect("focus_exited", this, "_port_name_focus_out", varray(name_box, E->get(), i, true)); + } else { + hbc->add_child(memnew(Label(left_name))); + } - if (left_type != Variant::NIL && !script->is_input_value_port_connected(edited_func, E->get(), i)) { + if (nd_list->is_input_port_type_editable()) { + OptionButton *opbtn = memnew(OptionButton); + for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) { + opbtn->add_item(Variant::get_type_name(Variant::Type(j))); + } + opbtn->select(left_type); + opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + hbc->add_child(opbtn); + opbtn->connect("item_selected", this, "_change_port_type", varray(E->get(), i, true), CONNECT_DEFERRED); + } - PropertyInfo pi = node->get_input_value_port_info(i); - Button *button = memnew(Button); - Variant value = node->get_default_input_value(i); - if (value.get_type() != left_type) { - //different type? for now convert - //not the same, reconvert - Variant::CallError ce; - const Variant *existingp = &value; - value = Variant::construct(left_type, &existingp, 1, ce, false); + Button *rmbtn = memnew(Button); + rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("Remove", "EditorIcons")); + hbc->add_child(rmbtn); + rmbtn->connect("pressed", this, "_remove_input_port", varray(E->get(), i), CONNECT_DEFERRED); + } else { + hbc->add_child(memnew(Label(left_name))); } - if (left_type == Variant::COLOR) { - button->set_custom_minimum_size(Size2(30, 0) * EDSCALE); - button->connect("draw", this, "_draw_color_over_button", varray(button, value)); - } else if (left_type == Variant::OBJECT && Ref<Resource>(value).is_valid()) { + if (left_type != Variant::NIL && !script->is_input_value_port_connected(F->get(), E->get(), i)) { + + PropertyInfo pi = node->get_input_value_port_info(i); + Button *button = memnew(Button); + Variant value = node->get_default_input_value(i); + if (value.get_type() != left_type) { + //different type? for now convert + //not the same, reconvert + Variant::CallError ce; + const Variant *existingp = &value; + value = Variant::construct(left_type, &existingp, 1, ce, false); + } - Ref<Resource> res = value; - Array arr; - arr.push_back(button->get_instance_id()); - arr.push_back(String(value)); - EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_button_resource_previewed", arr); + if (left_type == Variant::COLOR) { + button->set_custom_minimum_size(Size2(30, 0) * EDSCALE); + button->connect("draw", this, "_draw_color_over_button", varray(button, value)); + } else if (left_type == Variant::OBJECT && Ref<Resource>(value).is_valid()) { - } else if (pi.type == Variant::INT && pi.hint == PROPERTY_HINT_ENUM) { + Ref<Resource> res = value; + Array arr; + arr.push_back(button->get_instance_id()); + arr.push_back(String(value)); + EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_button_resource_previewed", arr); - button->set_text(pi.hint_string.get_slice(",", value)); - } else { + } else if (pi.type == Variant::INT && pi.hint == PROPERTY_HINT_ENUM) { + + button->set_text(pi.hint_string.get_slice(",", value)); + } else { - button->set_text(value); + button->set_text(value); + } + button->connect("pressed", this, "_default_value_edited", varray(button, E->get(), i)); + hbc2->add_child(button); } - button->connect("pressed", this, "_default_value_edited", varray(button, E->get(), i)); - hbc->add_child(button); + } else { + Control *c = memnew(Control); + c->set_custom_minimum_size(Size2(10, 0) * EDSCALE); + hbc->add_child(c); } - } else { - Control *c = memnew(Control); - c->set_custom_minimum_size(Size2(10, 0) * EDSCALE); - hbc->add_child(c); - } - hbc->add_spacer(); + hbc->add_spacer(); + hbc2->add_spacer(); - if (i < mixed_seq_ports) { + if (i < mixed_seq_ports) { - Label *text2 = memnew(Label); - text2->set_text(node->get_output_sequence_port_text(i)); - text2->set_align(Label::ALIGN_RIGHT); - hbc->add_child(text2); - } + Label *text2 = memnew(Label); + text2->set_text(node->get_output_sequence_port_text(i)); + text2->set_align(Label::ALIGN_RIGHT); + hbc->add_child(text2); + } - if (right_ok) { + if (right_ok) { + + if (is_vslist) { + Button *rmbtn = memnew(Button); + rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("Remove", "EditorIcons")); + hbc->add_child(rmbtn); + rmbtn->connect("pressed", this, "_remove_output_port", varray(E->get(), i), CONNECT_DEFERRED); + + if (nd_list->is_output_port_type_editable()) { + OptionButton *opbtn = memnew(OptionButton); + for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) { + opbtn->add_item(Variant::get_type_name(Variant::Type(j))); + } + opbtn->select(right_type); + opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + hbc->add_child(opbtn); + opbtn->connect("item_selected", this, "_change_port_type", varray(E->get(), i, false), CONNECT_DEFERRED); + } - hbc->add_child(memnew(Label(right_name))); + if (nd_list->is_output_port_name_editable()) { + LineEdit *name_box = memnew(LineEdit); + hbc->add_child(name_box); + name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0)); + name_box->set_text(right_name); + name_box->set_expand_to_text_length(true); + name_box->connect("resized", this, "_update_node_size", varray(E->get())); + name_box->connect("focus_exited", this, "_port_name_focus_out", varray(name_box, E->get(), i, false)); + } else { + hbc->add_child(memnew(Label(right_name))); + } + } else { + hbc->add_child(memnew(Label(right_name))); + } - Ref<Texture> t; - if (right_type >= 0 && right_type < Variant::VARIANT_MAX) { - t = type_icons[right_type]; + Ref<Texture> t; + if (right_type >= 0 && right_type < Variant::VARIANT_MAX) { + t = type_icons[right_type]; + } + if (t.is_valid()) { + TextureRect *tf = memnew(TextureRect); + tf->set_texture(t); + tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); + hbc->add_child(tf); + } } - if (t.is_valid()) { - TextureRect *tf = memnew(TextureRect); - tf->set_texture(t); - tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); - hbc->add_child(tf); + + gnode->add_child(vbc); + + bool dark_theme = get_constant("dark_theme", "Editor"); + if (i < mixed_seq_ports) { + gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), true, TYPE_SEQUENCE, mono_color, Ref<Texture>(), seq_port); + } else { + gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), right_ok, right_type, _color_from_type(right_type, dark_theme)); } + + slot_idx++; } - gnode->add_child(hbc); + graph->add_child(gnode); - bool dark_theme = get_constant("dark_theme", "Editor"); - if (i < mixed_seq_ports) { - gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), true, TYPE_SEQUENCE, mono_color, Ref<Texture>(), seq_port); - } else { - gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), right_ok, right_type, _color_from_type(right_type, dark_theme)); + if (gnode->is_comment()) { + graph->move_child(gnode, 0); } - - slot_idx++; } + } + _update_graph_connections(); + // use default_func instead of default_func for now I think that should be good stop gap solution to ensure not breaking anything + graph->call_deferred("set_scroll_ofs", script->get_function_scroll(default_func) * EDSCALE); + updating_graph = false; +} - graph->add_child(gnode); +void VisualScriptEditor::_change_port_type(int p_select, int p_id, int p_port, bool is_input) { - if (gnode->is_comment()) { - graph->move_child(gnode, 0); - } + StringName func = _get_function_of_node(p_id); + + Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + if (!vsn.is_valid()) + return; + + undo_redo->create_action("Change Port Type"); + if (is_input) { + undo_redo->add_do_method(vsn.ptr(), "set_input_data_port_type", p_port, Variant::Type(p_select)); + undo_redo->add_undo_method(vsn.ptr(), "set_input_data_port_type", p_port, vsn->get_input_value_port_info(p_port).type); + } else { + undo_redo->add_do_method(vsn.ptr(), "set_output_data_port_type", p_port, Variant::Type(p_select)); + undo_redo->add_undo_method(vsn.ptr(), "set_output_data_port_type", p_port, vsn->get_output_value_port_info(p_port).type); } + undo_redo->commit_action(); +} - _update_graph_connections(); - graph->call_deferred("set_scroll_ofs", script->get_function_scroll(edited_func) * EDSCALE); //may need to adapt a bit, let it do so - updating_graph = false; +void VisualScriptEditor::_update_node_size(int p_id) { + + Node *node = graph->get_node(itos(p_id)); + if (Object::cast_to<Control>(node)) + Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); //shrink if text is smaller +} +void VisualScriptEditor::_port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input) { + StringName func = _get_function_of_node(p_id); + + Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + if (!vsn.is_valid()) + return; + + String text; + + if (Object::cast_to<LineEdit>(p_name_box)) + text = Object::cast_to<LineEdit>(p_name_box)->get_text(); + else + return; + + undo_redo->create_action("Change Port Name"); + if (is_input) { + undo_redo->add_do_method(vsn.ptr(), "set_input_data_port_name", p_port, text); + undo_redo->add_undo_method(vsn.ptr(), "set_input_data_port_name", p_port, vsn->get_input_value_port_info(p_port).name); + } else { + undo_redo->add_do_method(vsn.ptr(), "set_output_data_port_name", p_port, text); + undo_redo->add_undo_method(vsn.ptr(), "set_output_data_port_name", p_port, vsn->get_output_value_port_info(p_port).name); + } + undo_redo->commit_action(); } void VisualScriptEditor::_update_members() { @@ -775,18 +927,23 @@ void VisualScriptEditor::_update_members() { TreeItem *functions = members->create_item(root); functions->set_selectable(0, false); functions->set_text(0, TTR("Functions:")); - functions->add_button(0, Control::get_icon("Override", "EditorIcons"), 1); - functions->add_button(0, Control::get_icon("Add", "EditorIcons"), 0); + functions->add_button(0, Control::get_icon("Override", "EditorIcons"), 1, false, TTR("Override an existing built-in function.")); + functions->add_button(0, Control::get_icon("Add", "EditorIcons"), 0, false, TTR("Create a new function.")); functions->set_custom_color(0, Control::get_color("mono_color", "Editor")); List<StringName> func_names; script->get_function_list(&func_names); for (List<StringName>::Element *E = func_names.front(); E; E = E->next()) { + + if (E->get() == default_func) { + continue; + } + TreeItem *ti = members->create_item(functions); ti->set_text(0, E->get()); ti->set_selectable(0, true); - ti->set_editable(0, true); ti->set_metadata(0, E->get()); + ti->add_button(0, Control::get_icon("Edit", "EditorIcons"), 0); if (selected == E->get()) ti->select(0); } @@ -794,7 +951,7 @@ void VisualScriptEditor::_update_members() { TreeItem *variables = members->create_item(root); variables->set_selectable(0, false); variables->set_text(0, TTR("Variables:")); - variables->add_button(0, Control::get_icon("Add", "EditorIcons")); + variables->add_button(0, Control::get_icon("Add", "EditorIcons"), -1, false, TTR("Create a new variable.")); variables->set_custom_color(0, Control::get_color("mono_color", "Editor")); Ref<Texture> type_icons[Variant::VARIANT_MAX] = { @@ -847,7 +1004,7 @@ void VisualScriptEditor::_update_members() { TreeItem *_signals = members->create_item(root); _signals->set_selectable(0, false); _signals->set_text(0, TTR("Signals:")); - _signals->add_button(0, Control::get_icon("Add", "EditorIcons")); + _signals->add_button(0, Control::get_icon("Add", "EditorIcons"), -1, false, TTR("Create a new signal.")); _signals->set_custom_color(0, Control::get_color("mono_color", "Editor")); List<StringName> signal_names; @@ -886,15 +1043,15 @@ void VisualScriptEditor::_member_selected() { if (ti->get_parent() == members->get_root()->get_children()) { - if (edited_func != selected) { - - revert_on_drag = edited_func; - edited_func = selected; - _update_members(); - _update_graph(); +#ifdef OSX_ENABLED + bool held_ctrl = Input::get_singleton()->is_key_pressed(KEY_META); +#else + bool held_ctrl = Input::get_singleton()->is_key_pressed(KEY_CONTROL); +#endif + if (held_ctrl) { + ERR_FAIL_COND(!script->has_function(selected)); + _center_on_node(selected, script->get_function_node_id(selected)); } - - return; //or crash because it will become invalid } } @@ -934,9 +1091,6 @@ void VisualScriptEditor::_member_edited() { if (ti->get_parent() == root->get_children()) { - if (edited_func == selected) { - edited_func = new_name; - } selected = new_name; int node_id = script->get_function_node_id(name); @@ -948,10 +1102,27 @@ void VisualScriptEditor::_member_edited() { undo_redo->add_do_method(script.ptr(), "rename_function", name, new_name); undo_redo->add_undo_method(script.ptr(), "rename_function", new_name, name); if (func.is_valid()) { - undo_redo->add_do_method(func.ptr(), "set_name", new_name); undo_redo->add_undo_method(func.ptr(), "set_name", name); } + + // also fix all function calls + List<StringName> flst; + script->get_function_list(&flst); + for (List<StringName>::Element *E = flst.front(); E; E = E->next()) { + List<int> lst; + script->get_node_list(E->get(), &lst); + for (List<int>::Element *F = lst.front(); F; F = F->next()) { + Ref<VisualScriptFunctionCall> fncall = script->get_node(E->get(), F->get()); + if (!fncall.is_valid()) + continue; + if (fncall->get_function() == name) { + undo_redo->add_do_method(fncall.ptr(), "set_function", new_name); + undo_redo->add_undo_method(fncall.ptr(), "set_function", name); + } + } + } + undo_redo->add_do_method(this, "_update_members"); undo_redo->add_undo_method(this, "_update_members"); undo_redo->add_do_method(this, "_update_graph"); @@ -960,8 +1131,6 @@ void VisualScriptEditor::_member_edited() { undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); undo_redo->commit_action(); - // _update_graph(); - return; //or crash because it will become invalid } @@ -996,6 +1165,112 @@ void VisualScriptEditor::_member_edited() { } } +void VisualScriptEditor::_create_function_dialog() { + function_create_dialog->popup_centered(); + func_name_box->set_text(""); + func_name_box->grab_focus(); + for (int i = 0; i < func_input_vbox->get_child_count(); i++) { + Node *nd = func_input_vbox->get_child(i); + nd->queue_delete(); + } +} + +void VisualScriptEditor::_create_function() { + String name = _validate_name((func_name_box->get_text() == "") ? "new_func" : func_name_box->get_text()); + selected = name; + Vector2 ofs = _get_available_pos(); + + Ref<VisualScriptFunction> func_node; + func_node.instance(); + func_node->set_name(name); + + for (int i = 0; i < func_input_vbox->get_child_count(); i++) { + OptionButton *opbtn = Object::cast_to<OptionButton>(func_input_vbox->get_child(i)->get_child(3)); + LineEdit *lne = Object::cast_to<LineEdit>(func_input_vbox->get_child(i)->get_child(1)); + if (!opbtn || !lne) + continue; + Variant::Type arg_type = Variant::Type(opbtn->get_selected()); + String arg_name = lne->get_text(); + func_node->add_argument(arg_type, arg_name); + } + + undo_redo->create_action(TTR("Add Function")); + undo_redo->add_do_method(script.ptr(), "add_function", name); + undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_function", name); + undo_redo->add_do_method(this, "_update_members"); + undo_redo->add_undo_method(this, "_update_members"); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->add_do_method(this, "emit_signal", "edited_script_changed"); + undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); + undo_redo->commit_action(); + + _update_graph(); +} + +void VisualScriptEditor::_add_node_dialog() { + _generic_search(script->get_instance_base_type(), graph->get_global_position() + Vector2(55, 80), true); +} + +void VisualScriptEditor::_add_func_input() { + HBoxContainer *hbox = memnew(HBoxContainer); + hbox->set_h_size_flags(SIZE_EXPAND_FILL); + + Label *name_label = memnew(Label); + name_label->set_text(TTR("Name:")); + hbox->add_child(name_label); + + LineEdit *name_box = memnew(LineEdit); + name_box->set_h_size_flags(SIZE_EXPAND_FILL); + name_box->set_text("input"); + name_box->connect("focus_entered", this, "_deselect_input_names"); + hbox->add_child(name_box); + + Label *type_label = memnew(Label); + type_label->set_text(TTR("Type:")); + hbox->add_child(type_label); + + OptionButton *type_box = memnew(OptionButton); + type_box->set_custom_minimum_size(Size2(120 * EDSCALE, 0)); + for (int i = Variant::NIL; i < Variant::VARIANT_MAX; i++) + type_box->add_item(Variant::get_type_name(Variant::Type(i))); + type_box->select(1); + hbox->add_child(type_box); + + Button *delete_button = memnew(Button); + delete_button->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("Remove", "EditorIcons")); + delete_button->set_tooltip(vformat(TTR("Delete input port"))); + hbox->add_child(delete_button); + + for (int i = 0; i < func_input_vbox->get_child_count(); i++) { + LineEdit *line_edit = (LineEdit *)func_input_vbox->get_child(i)->get_child(1); + line_edit->deselect(); + } + + func_input_vbox->add_child(hbox); + hbox->set_meta("id", hbox->get_position_in_parent()); + + delete_button->connect("pressed", this, "_remove_func_input", varray(hbox)); + + name_box->select_all(); + name_box->grab_focus(); +} + +void VisualScriptEditor::_remove_func_input(Node *p_node) { + func_input_vbox->remove_child(p_node); + p_node->queue_delete(); +} + +void VisualScriptEditor::_deselect_input_names() { + int cn = func_input_vbox->get_child_count(); + for (int i = 0; i < cn; i++) { + LineEdit *lne = Object::cast_to<LineEdit>(func_input_vbox->get_child(i)->get_child(1)); + if (lne) + lne->deselect(); + } +} + void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_button) { TreeItem *ti = Object::cast_to<TreeItem>(p_item); @@ -1008,7 +1283,6 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt //add function, this one uses menu if (p_button == 1) { - new_virtual_method_select->select_method_from_base_type(script->get_instance_base_type(), String(), true); return; @@ -1016,7 +1290,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt String name = _validate_name("new_function"); selected = name; - edited_func = selected; + Vector2 ofs = _get_available_pos(); Ref<VisualScriptFunction> func_node; func_node.instance(); @@ -1024,7 +1298,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt undo_redo->create_action(TTR("Add Function")); undo_redo->add_do_method(script.ptr(), "add_function", name); - undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node); + undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node, ofs); undo_redo->add_undo_method(script.ptr(), "remove_function", name); undo_redo->add_do_method(this, "_update_members"); undo_redo->add_undo_method(this, "_update_members"); @@ -1071,133 +1345,193 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt undo_redo->commit_action(); return; //or crash because it will become invalid } + } else if (ti->get_parent() == root->get_children()) { + selected = ti->get_text(0); + function_name_edit->set_position(Input::get_singleton()->get_mouse_position() - Vector2(60, -10)); + function_name_edit->popup(); + function_name_box->set_text(selected); + function_name_box->select_all(); } } -void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id) { +void VisualScriptEditor::_add_input_port(int p_id) { - Ref<VisualScriptExpression> vse = script->get_node(edited_func, p_id); - if (!vse.is_valid()) + StringName func = _get_function_of_node(p_id); + + Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + if (!vsn.is_valid()) return; updating_graph = true; - undo_redo->create_action(TTR("Change Expression"), UndoRedo::MERGE_ENDS); - undo_redo->add_do_property(vse.ptr(), "expression", p_text); - undo_redo->add_undo_property(vse.ptr(), "expression", vse->get("expression")); + undo_redo->create_action(TTR("Add Input Port"), UndoRedo::MERGE_ENDS); + undo_redo->add_do_method(vsn.ptr(), "add_input_data_port", Variant::NIL, "arg", -1); undo_redo->add_do_method(this, "_update_graph", p_id); + + undo_redo->add_undo_method(vsn.ptr(), "remove_input_data_port", vsn->get_input_value_port_count()); undo_redo->add_undo_method(this, "_update_graph", p_id); + + updating_graph = false; + undo_redo->commit_action(); +} - Node *node = graph->get_node(itos(p_id)); - if (Object::cast_to<Control>(node)) - Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); //shrink if text is smaller +void VisualScriptEditor::_add_output_port(int p_id) { + + StringName func = _get_function_of_node(p_id); + + Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + if (!vsn.is_valid()) + return; + + updating_graph = true; + + undo_redo->create_action(TTR("Add Output Port"), UndoRedo::MERGE_ENDS); + undo_redo->add_do_method(vsn.ptr(), "add_output_data_port", Variant::NIL, "arg", -1); + undo_redo->add_do_method(this, "_update_graph", p_id); + + undo_redo->add_undo_method(vsn.ptr(), "remove_output_data_port", vsn->get_output_value_port_count()); + undo_redo->add_undo_method(this, "_update_graph", p_id); updating_graph = false; + + undo_redo->commit_action(); } -void VisualScriptEditor::_available_node_doubleclicked() { +void VisualScriptEditor::_remove_input_port(int p_id, int p_port) { - TreeItem *item = nodes->get_selected(); + StringName func = _get_function_of_node(p_id); - if (!item) + Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + if (!vsn.is_valid()) return; - String which = item->get_metadata(0); - if (which == String()) + updating_graph = true; + + undo_redo->create_action(TTR("Remove Input Port"), UndoRedo::MERGE_ENDS); + + int conn_from = -1, conn_port = -1; + script->get_input_value_port_connection_source(func, p_id, p_port, &conn_from, &conn_port); + + if (conn_from != -1) + undo_redo->add_do_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, p_id, p_port); + + undo_redo->add_do_method(vsn.ptr(), "remove_input_data_port", p_port); + undo_redo->add_do_method(this, "_update_graph", p_id); + + if (conn_from != -1) + undo_redo->add_undo_method(script.ptr(), "data_connect", func, conn_from, conn_port, p_id, p_port); + + undo_redo->add_undo_method(vsn.ptr(), "add_input_data_port", vsn->get_input_value_port_info(p_port).type, vsn->get_input_value_port_info(p_port).name, p_port); + undo_redo->add_undo_method(this, "_update_graph", p_id); + + updating_graph = false; + + undo_redo->commit_action(); +} + +void VisualScriptEditor::_remove_output_port(int p_id, int p_port) { + + StringName func = _get_function_of_node(p_id); + + Ref<VisualScriptLists> vsn = script->get_node(func, p_id); + if (!vsn.is_valid()) return; - Vector2 ofs = graph->get_scroll_ofs() + graph->get_size() * 0.5; + updating_graph = true; - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } + undo_redo->create_action(TTR("Remove Output Port"), UndoRedo::MERGE_ENDS); - ofs /= EDSCALE; + List<VisualScript::DataConnection> data_connections; + script->get_data_connection_list(func, &data_connections); - while (true) { - bool exists = false; - List<int> existing; - script->get_node_list(edited_func, &existing); - for (List<int>::Element *E = existing.front(); E; E = E->next()) { - Point2 pos = script->get_node_position(edited_func, E->get()); - if (pos.distance_to(ofs) < 15) { - ofs += Vector2(graph->get_snap(), graph->get_snap()); - exists = true; - break; - } + HashMap<int, Set<int> > conn_map; + for (const List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { + if (E->get().from_node == p_id && E->get().from_port == p_port) { + // push into the connections map + if (!conn_map.has(E->get().to_node)) + conn_map.set(E->get().to_node, Set<int>()); + conn_map[E->get().to_node].insert(E->get().to_port); } + } - if (exists) - continue; - break; + undo_redo->add_do_method(vsn.ptr(), "remove_output_data_port", p_port); + undo_redo->add_do_method(this, "_update_graph", p_id); + + List<int> keys; + conn_map.get_key_list(&keys); + for (const List<int>::Element *E = keys.front(); E; E = E->next()) { + for (const Set<int>::Element *F = conn_map[E->get()].front(); F; F = F->next()) { + undo_redo->add_undo_method(script.ptr(), "data_connect", func, p_id, p_port, E->get(), F->get()); + } } - Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(which); - int new_id = script->get_available_id(); + undo_redo->add_undo_method(vsn.ptr(), "add_output_data_port", vsn->get_output_value_port_info(p_port).type, vsn->get_output_value_port_info(p_port).name, p_port); + undo_redo->add_undo_method(this, "_update_graph", p_id); - undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - undo_redo->commit_action(); + updating_graph = false; - Node *node = graph->get_node(itos(new_id)); - if (node) { - graph->set_selected(node); - _node_selected(node); - } + undo_redo->commit_action(); } -void VisualScriptEditor::_update_available_nodes() { +void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id) { - nodes->clear(); + StringName func = _get_function_of_node(p_id); - TreeItem *root = nodes->create_item(); + Ref<VisualScriptExpression> vse = script->get_node(func, p_id); + if (!vse.is_valid()) + return; - Map<String, TreeItem *> path_cache; + updating_graph = true; - String filter = node_filter->get_text(); + undo_redo->create_action(TTR("Change Expression"), UndoRedo::MERGE_ENDS); + undo_redo->add_do_property(vse.ptr(), "expression", p_text); + undo_redo->add_undo_property(vse.ptr(), "expression", vse->get("expression")); + undo_redo->add_do_method(this, "_update_graph", p_id); + undo_redo->add_undo_method(this, "_update_graph", p_id); + undo_redo->commit_action(); - List<String> fnodes; - VisualScriptLanguage::singleton->get_registered_node_names(&fnodes); + Node *node = graph->get_node(itos(p_id)); + if (Object::cast_to<Control>(node)) + Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); //shrink if text is smaller - for (List<String>::Element *E = fnodes.front(); E; E = E->next()) { + updating_graph = false; +} - Vector<String> path = E->get().split("/"); +Vector2 VisualScriptEditor::_get_available_pos(bool centered, Vector2 ofs) const { + if (centered) + ofs = graph->get_scroll_ofs() + graph->get_size() * 0.5; - if (filter != String() && path.size() && path[path.size() - 1].findn(filter) == -1) - continue; + if (graph->is_using_snap()) { + int snap = graph->get_snap(); + ofs = ofs.snapped(Vector2(snap, snap)); + } + + ofs /= EDSCALE; - String sp; - TreeItem *parent = root; - - for (int i = 0; i < path.size() - 1; i++) { - - if (i > 0) - sp += ","; - sp += path[i]; - if (!path_cache.has(sp)) { - TreeItem *pathn = nodes->create_item(parent); - pathn->set_selectable(0, false); - pathn->set_text(0, path[i].capitalize()); - path_cache[sp] = pathn; - parent = pathn; - if (filter == String()) { - pathn->set_collapsed(true); //should remember state + while (true) { + bool exists = false; + List<StringName> all_fn; + script->get_function_list(&all_fn); + for (List<StringName>::Element *F = all_fn.front(); F; F = F->next()) { + StringName curr_fn = F->get(); + List<int> existing; + script->get_node_list(curr_fn, &existing); + for (List<int>::Element *E = existing.front(); E; E = E->next()) { + Point2 pos = script->get_node_position(curr_fn, E->get()); + if (pos.distance_to(ofs) < 50) { + ofs += Vector2(graph->get_snap(), graph->get_snap()); + exists = true; + break; } - } else { - parent = path_cache[sp]; } } - - TreeItem *item = nodes->create_item(parent); - item->set_text(0, path[path.size() - 1].capitalize()); - item->set_selectable(0, true); - item->set_metadata(0, E->get()); + if (exists) + continue; + break; } + + return ofs; } String VisualScriptEditor::_validate_name(const String &p_name) const { @@ -1223,6 +1557,8 @@ String VisualScriptEditor::_validate_name(const String &p_name) const { void VisualScriptEditor::_on_nodes_delete() { + // delete all the selected nodes + List<int> to_erase; for (int i = 0; i < graph->get_child_count(); i++) { @@ -1241,26 +1577,30 @@ void VisualScriptEditor::_on_nodes_delete() { for (List<int>::Element *F = to_erase.front(); F; F = F->next()) { - undo_redo->add_do_method(script.ptr(), "remove_node", edited_func, F->get()); - undo_redo->add_undo_method(script.ptr(), "add_node", edited_func, F->get(), script->get_node(edited_func, F->get()), script->get_node_position(edited_func, F->get())); + int cr_node = F->get(); + + StringName func = _get_function_of_node(cr_node); + + undo_redo->add_do_method(script.ptr(), "remove_node", func, cr_node); + undo_redo->add_undo_method(script.ptr(), "add_node", func, cr_node, script->get_node(func, cr_node), script->get_node_position(func, cr_node)); List<VisualScript::SequenceConnection> sequence_conns; - script->get_sequence_connection_list(edited_func, &sequence_conns); + script->get_sequence_connection_list(func, &sequence_conns); for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { - if (E->get().from_node == F->get() || E->get().to_node == F->get()) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", edited_func, E->get().from_node, E->get().from_output, E->get().to_node); + if (E->get().from_node == cr_node || E->get().to_node == cr_node) { + undo_redo->add_undo_method(script.ptr(), "sequence_connect", func, E->get().from_node, E->get().from_output, E->get().to_node); } } List<VisualScript::DataConnection> data_conns; - script->get_data_connection_list(edited_func, &data_conns); + script->get_data_connection_list(func, &data_conns); for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { if (E->get().from_node == F->get() || E->get().to_node == F->get()) { - undo_redo->add_undo_method(script.ptr(), "data_connect", edited_func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } } @@ -1272,13 +1612,16 @@ void VisualScriptEditor::_on_nodes_delete() { void VisualScriptEditor::_on_nodes_duplicate() { - List<int> to_duplicate; + Set<int> to_duplicate; + List<StringName> funcs; for (int i = 0; i < graph->get_child_count(); i++) { GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); if (gn) { if (gn->is_selected() && gn->is_close_button_visible()) { - to_duplicate.push_back(gn->get_name().operator String().to_int()); + int id = gn->get_name().operator String().to_int(); + to_duplicate.insert(id); + funcs.push_back(_get_function_of_node(id)); } } } @@ -1290,18 +1633,42 @@ void VisualScriptEditor::_on_nodes_duplicate() { int idc = script->get_available_id() + 1; Set<int> to_select; + HashMap<int, int> remap; - for (List<int>::Element *F = to_duplicate.front(); F; F = F->next()) { + for (Set<int>::Element *F = to_duplicate.front(); F; F = F->next()) { - Ref<VisualScriptNode> node = script->get_node(edited_func, F->get()); + // duplicate from the specific function but place it into the default func as it would lack the connections + StringName func = _get_function_of_node(F->get()); + Ref<VisualScriptNode> node = script->get_node(func, F->get()); Ref<VisualScriptNode> dupe = node->duplicate(true); int new_id = idc++; + remap.set(F->get(), new_id); + to_select.insert(new_id); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, dupe, script->get_node_position(edited_func, F->get()) + Vector2(20, 20)); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, dupe, script->get_node_position(func, F->get()) + Vector2(20, 20)); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); + } + + for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) { + List<VisualScript::SequenceConnection> seqs; + script->get_sequence_connection_list(F->get(), &seqs); + for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) { + if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", default_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); + } + } + + List<VisualScript::DataConnection> data; + script->get_data_connection_list(F->get(), &data); + for (List<VisualScript::DataConnection>::Element *E = data.front(); E; E = E->next()) { + if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) { + undo_redo->add_do_method(script.ptr(), "data_connect", default_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); + } + } } + undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); @@ -1316,21 +1683,45 @@ void VisualScriptEditor::_on_nodes_duplicate() { } if (to_select.size()) { - EditorNode::get_singleton()->push_item(script->get_node(edited_func, to_select.front()->get()).ptr()); + EditorNode::get_singleton()->push_item(script->get_node(default_func, to_select.front()->get()).ptr()); } } -void VisualScriptEditor::_input(const Ref<InputEvent> &p_event) { +void VisualScriptEditor::_generic_search(String p_base_type, Vector2 pos, bool node_centered) { + if (node_centered) + port_action_pos = graph->get_size() / 2.0f; + else + port_action_pos = graph->get_viewport()->get_mouse_position() - graph->get_global_position(); + + new_connect_node_select->select_from_visual_script(p_base_type, false, false); // neither connecting nor reset text + + // ensure that the dialog fits inside the graph + Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size(); + pos.x = pos.x > bounds.x ? bounds.x : pos.x; + pos.y = pos.y > bounds.y ? bounds.y : pos.y; - Ref<InputEventMouseButton> mb = p_event; + if (pos != Vector2()) + new_connect_node_select->set_position(pos); +} + +void VisualScriptEditor::_input(const Ref<InputEvent> &p_event) { + // GUI input for VS Editor Plugin + Ref<InputEventMouseButton> key = p_event; - if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { - revert_on_drag = String(); //so we can still drag functions + if (key.is_valid() && !key->is_pressed()) { + mouse_up_position = Input::get_singleton()->get_mouse_position(); } } -void VisualScriptEditor::_generic_search() { - new_connect_node_select->select_from_visual_script(String(""), false); +void VisualScriptEditor::_graph_gui_input(const Ref<InputEvent> &p_event) { + Ref<InputEventMouseButton> key = p_event; + + if (key.is_valid() && key->is_pressed() && key->get_button_mask() == BUTTON_RIGHT) { + saved_position = graph->get_local_mouse_position(); + + Point2 gpos = Input::get_singleton()->get_mouse_position(); + _generic_search(script->get_instance_base_type(), gpos); + } } void VisualScriptEditor::_members_gui_input(const Ref<InputEvent> &p_event) { @@ -1360,29 +1751,83 @@ void VisualScriptEditor::_members_gui_input(const Ref<InputEvent> &p_event) { } } } + + Ref<InputEventMouseButton> btn = p_event; + if (btn.is_valid() && btn->is_doubleclick()) { + TreeItem *ti = members->get_selected(); + if (ti && ti->get_parent() == members->get_root()->get_children()) // to check if it's a function + _center_on_node(ti->get_metadata(0), script->get_function_node_id(ti->get_metadata(0))); + } } -Variant VisualScriptEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) { +void VisualScriptEditor::_rename_function(const String &name, const String &new_name) { - if (p_from == nodes) { + if (!new_name.is_valid_identifier()) { - TreeItem *it = nodes->get_item_at_position(p_point); - if (!it) - return Variant(); - String type = it->get_metadata(0); - if (type == String()) - return Variant(); + EditorNode::get_singleton()->show_warning(TTR("Name is not a valid identifier:") + " " + new_name); + return; + } - Dictionary dd; - dd["type"] = "visual_script_node_drag"; - dd["node_type"] = type; + if (script->has_function(new_name) || script->has_variable(new_name) || script->has_custom_signal(new_name)) { - Label *label = memnew(Label); - label->set_text(it->get_text(0)); - set_drag_preview(label); - return dd; + EditorNode::get_singleton()->show_warning(TTR("Name already in use by another func/var/signal:") + " " + new_name); + return; + } + + int node_id = script->get_function_node_id(name); + Ref<VisualScriptFunction> func; + if (script->has_node(name, node_id)) { + func = script->get_node(name, node_id); + } + undo_redo->create_action(TTR("Rename Function")); + undo_redo->add_do_method(script.ptr(), "rename_function", name, new_name); + undo_redo->add_undo_method(script.ptr(), "rename_function", new_name, name); + if (func.is_valid()) { + undo_redo->add_do_method(func.ptr(), "set_name", new_name); + undo_redo->add_undo_method(func.ptr(), "set_name", name); + } + + // also fix all function calls + List<StringName> flst; + script->get_function_list(&flst); + for (List<StringName>::Element *E = flst.front(); E; E = E->next()) { + List<int> lst; + script->get_node_list(E->get(), &lst); + for (List<int>::Element *F = lst.front(); F; F = F->next()) { + Ref<VisualScriptFunctionCall> fncall = script->get_node(E->get(), F->get()); + if (!fncall.is_valid()) + continue; + if (fncall->get_function() == name) { + undo_redo->add_do_method(fncall.ptr(), "set_function", new_name); + undo_redo->add_undo_method(fncall.ptr(), "set_function", name); + } + } } + undo_redo->add_do_method(this, "_update_members"); + undo_redo->add_undo_method(this, "_update_members"); + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->add_do_method(this, "emit_signal", "edited_script_changed"); + undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); + undo_redo->commit_action(); +} + +void VisualScriptEditor::_fn_name_box_input(const Ref<InputEvent> &p_event) { + + if (!function_name_edit->is_visible()) + return; + + Ref<InputEventKey> key = p_event; + if (key.is_valid() && key->is_pressed() && key->get_scancode() == KEY_ENTER) { + function_name_edit->hide(); + _rename_function(selected, function_name_box->get_text()); + function_name_box->clear(); + } +} + +Variant VisualScriptEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) { + if (p_from == members) { TreeItem *it = members->get_item_at_position(p_point); @@ -1401,11 +1846,6 @@ Variant VisualScriptEditor::get_drag_data_fw(const Point2 &p_point, Control *p_f dd["type"] = "visual_script_function_drag"; dd["function"] = type; - if (revert_on_drag != String()) { - edited_func = revert_on_drag; //revert so function does not change - revert_on_drag = String(); - _update_graph(); - } } else if (it->get_parent() == root->get_children()->get_next()) { dd["type"] = "visual_script_variable_drag"; @@ -1476,8 +1916,6 @@ bool VisualScriptEditor::can_drop_data_fw(const Point2 &p_point, const Variant & return false; } -#ifdef TOOLS_ENABLED - static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) { if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) @@ -1497,8 +1935,6 @@ static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const return NULL; } -#endif - void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) { if (p_from != graph) { @@ -1525,15 +1961,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da ofs /= EDSCALE; - Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(d["node_type"]); - int new_id = script->get_available_id(); - - undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - undo_redo->commit_action(); + int new_id = _create_new_node_from_name(d["node_type"], ofs, default_func); Node *node = graph->get_node(itos(new_id)); if (node) { @@ -1574,8 +2002,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, vnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -1604,11 +2032,11 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, vnode, ofs); undo_redo->add_do_method(vnode.ptr(), "set_base_type", script->get_instance_base_type()); undo_redo->add_do_method(vnode.ptr(), "set_function", d["function"]); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -1637,8 +2065,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, vnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -1667,8 +2095,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Preload Node")); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, prnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, prnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -1708,8 +2136,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da prnode.instance(); prnode->set_preload(res); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, prnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, prnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); new_ids.push_back(new_id); new_id++; ofs += Vector2(20, 20) * EDSCALE; @@ -1735,7 +2163,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da Node *sn = _find_script_node(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root(), script); if (!sn) { - EditorNode::get_singleton()->show_warning("Can't drop nodes because script '" + get_name() + "' is not used in this scene."); + EditorNode::get_singleton()->show_warning(vformat(TTR("Can't drop nodes because script '%s' is not used in this scene."), get_name())); return; } @@ -1777,21 +2205,20 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da scene_node.instance(); scene_node->set_node_path(sn->get_path_to(node)); n = scene_node; - } else { + // ! Doesn't work properly Ref<VisualScriptFunctionCall> call; call.instance(); call->set_call_mode(VisualScriptFunctionCall::CALL_MODE_NODE_PATH); call->set_base_path(sn->get_path_to(node)); call->set_base_type(node->get_class()); n = call; - - method_select->select_from_instance(node); + method_select->select_from_instance(node, "", true, node->get_class()); selecting_method_id = base_id; } - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, base_id, n, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, base_id); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, base_id, n, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, base_id); base_id++; ofs += Vector2(25, 25); @@ -1806,7 +2233,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da Node *sn = _find_script_node(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root(), script); if (!sn && !Input::get_singleton()->is_key_pressed(KEY_SHIFT)) { - EditorNode::get_singleton()->show_warning("Can't drop properties because script '" + get_name() + "' is not used in this scene.\nDrop holding 'Shift' to just copy the signature."); + EditorNode::get_singleton()->show_warning(vformat(TTR("Can't drop properties because script '%s' is not used in this scene.\nDrop holding 'Shift' to just copy the signature."), get_name())); return; } @@ -1862,13 +2289,13 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da vnode = pget; } - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, base_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, base_id, vnode, ofs); undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]); if (!use_get) { undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]); } - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, base_id); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, base_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); @@ -1909,12 +2336,12 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } vnode = pget; } - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, base_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, base_id, vnode, ofs); undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]); if (!use_get) { undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]); } - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, base_id); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, base_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); @@ -1925,7 +2352,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da void VisualScriptEditor::_selected_method(const String &p_method, const String &p_type, const bool p_connecting) { - Ref<VisualScriptFunctionCall> vsfc = script->get_node(edited_func, selecting_method_id); + Ref<VisualScriptFunctionCall> vsfc = script->get_node(default_func, selecting_method_id); if (!vsfc.is_valid()) return; vsfc->set_function(p_method); @@ -1982,8 +2409,16 @@ void VisualScriptEditor::set_edited_resource(const RES &p_res) { script->connect("node_ports_changed", this, "_node_ports_changed"); + default_func = script->get_default_func(); + + if (!script->has_function(default_func)) // this is the supposed default function + { + script->add_function(default_func); + script->set_edited(true); //so that if a function was added it's saved + } + + _update_graph(); _update_members(); - _update_available_nodes(); } Vector<String> VisualScriptEditor::get_functions() { @@ -2017,18 +2452,14 @@ Ref<Texture> VisualScriptEditor::get_icon() { } bool VisualScriptEditor::is_unsaved() { -#ifdef TOOLS_ENABLED return script->is_edited() || script->are_subnodes_edited(); -#else - return false; -#endif } Variant VisualScriptEditor::get_edit_state() { Dictionary d; - d["function"] = edited_func; + d["function"] = default_func; d["scroll"] = graph->get_scroll_ofs(); d["zoom"] = graph->get_zoom(); d["using_snap"] = graph->is_using_snap(); @@ -2040,8 +2471,7 @@ void VisualScriptEditor::set_edit_state(const Variant &p_state) { Dictionary d = p_state; if (d.has("function")) { - edited_func = p_state; - selected = edited_func; + selected = default_func; } _update_graph(); @@ -2061,16 +2491,24 @@ void VisualScriptEditor::set_edit_state(const Variant &p_state) { } } -void VisualScriptEditor::_center_on_node(int p_id) { +void VisualScriptEditor::_center_on_node(const StringName &p_func, int p_id) { Node *n = graph->get_node(itos(p_id)); GraphNode *gn = Object::cast_to<GraphNode>(n); + + // clear selection + for (int i = 0; i < graph->get_child_count(); i++) { + GraphNode *gnd = Object::cast_to<GraphNode>(graph->get_child(i)); + if (gnd) + gnd->set_selected(false); + } + if (gn) { gn->set_selected(true); Vector2 new_scroll = gn->get_offset() - graph->get_size() * 0.5 + gn->get_size() * 0.5; graph->set_scroll_ofs(new_scroll); - script->set_function_scroll(edited_func, new_scroll / EDSCALE); - script->set_edited(true); //so it's saved + script->set_function_scroll(p_func, new_scroll / EDSCALE); + script->set_edited(true); } } @@ -2087,21 +2525,29 @@ void VisualScriptEditor::goto_line(int p_line, bool p_with_error) { if (script->has_node(E->get(), p_line)) { - edited_func = E->get(); - selected = edited_func; _update_graph(); _update_members(); - call_deferred("call_deferred", "_center_on_node", p_line); //editor might be just created and size might not exist yet - + call_deferred("call_deferred", "_center_on_node", E->get(), p_line); //editor might be just created and size might not exist yet return; } } } +void VisualScriptEditor::set_executing_line(int p_line) { + // todo: add a way to show which node is executing right now. +} + +void VisualScriptEditor::clear_executing_line() { + // todo: add a way to show which node is executing right now. +} + void VisualScriptEditor::trim_trailing_whitespace() { } +void VisualScriptEditor::insert_final_newline() { +} + void VisualScriptEditor::convert_indent_to_spaces() { } @@ -2117,6 +2563,7 @@ void VisualScriptEditor::tag_saved_version() { } void VisualScriptEditor::reload(bool p_soft) { + _update_graph(); } void VisualScriptEditor::get_breakpoints(List<int> *p_breakpoints) { @@ -2140,10 +2587,9 @@ void VisualScriptEditor::get_breakpoints(List<int> *p_breakpoints) { void VisualScriptEditor::add_callback(const String &p_function, PoolStringArray p_args) { if (script->has_function(p_function)) { - edited_func = p_function; - selected = edited_func; _update_members(); _update_graph(); + _center_on_node(p_function, script->get_function_node_id(p_function)); return; } @@ -2174,13 +2620,10 @@ void VisualScriptEditor::add_callback(const String &p_function, PoolStringArray script->add_function(p_function); script->add_node(p_function, script->get_available_id(), func); - edited_func = p_function; - selected = edited_func; _update_members(); _update_graph(); - graph->call_deferred("set_scroll_ofs", script->get_function_scroll(edited_func)); //for first time it might need to be later - //undo_redo->clear_history(); + _center_on_node(p_function, script->get_function_node_id(p_function)); } bool VisualScriptEditor::show_members_overview() { @@ -2209,12 +2652,16 @@ Control *VisualScriptEditor::get_edit_menu() { void VisualScriptEditor::_change_base_type() { - select_base_type->popup_create(true); + select_base_type->popup_create(true, true); +} + +void VisualScriptEditor::_toggle_tool_script() { + script->set_tool_enabled(!script->is_tool()); } void VisualScriptEditor::clear_edit_menu() { memdelete(edit_menu); - memdelete(left_vsplit); + memdelete(members_section); } void VisualScriptEditor::_change_base_type_callback() { @@ -2278,46 +2725,66 @@ void VisualScriptEditor::_end_node_move() { undo_redo->commit_action(); } -void VisualScriptEditor::_move_node(String func, int p_id, const Vector2 &p_to) { +void VisualScriptEditor::_move_node(const StringName &p_func, int p_id, const Vector2 &p_to) { + + if (!script->has_function(p_func)) + return; + + Node *node = graph->get_node(itos(p_id)); + + if (Object::cast_to<GraphNode>(node)) + Object::cast_to<GraphNode>(node)->set_offset(p_to); + + script->set_node_position(p_func, p_id, p_to / EDSCALE); +} + +StringName VisualScriptEditor::_get_function_of_node(int p_id) const { - if (func == String(edited_func)) { - Node *node = graph->get_node(itos(p_id)); - if (Object::cast_to<GraphNode>(node)) - Object::cast_to<GraphNode>(node)->set_offset(p_to); + List<StringName> funcs; + script->get_function_list(&funcs); + for (List<StringName>::Element *E = funcs.front(); E; E = E->next()) { + if (script->has_node(E->get(), p_id)) { + return E->get(); + } } - script->set_node_position(edited_func, p_id, p_to / EDSCALE); + + return ""; // this is passed to avoid crash and is tested against later } void VisualScriptEditor::_node_moved(Vector2 p_from, Vector2 p_to, int p_id) { - undo_redo->add_do_method(this, "_move_node", String(edited_func), p_id, p_to); - undo_redo->add_undo_method(this, "_move_node", String(edited_func), p_id, p_from); + StringName func = _get_function_of_node(p_id); + + undo_redo->add_do_method(this, "_move_node", func, p_id, p_to); + undo_redo->add_undo_method(this, "_move_node", func, p_id, p_from); } void VisualScriptEditor::_remove_node(int p_id) { undo_redo->create_action(TTR("Remove VisualScript Node")); - undo_redo->add_do_method(script.ptr(), "remove_node", edited_func, p_id); - undo_redo->add_undo_method(script.ptr(), "add_node", edited_func, p_id, script->get_node(edited_func, p_id), script->get_node_position(edited_func, p_id)); + StringName func = _get_function_of_node(p_id); + + undo_redo->add_do_method(script.ptr(), "remove_node", func, p_id); + undo_redo->add_undo_method(script.ptr(), "add_node", func, p_id, script->get_node(func, p_id), script->get_node_position(func, p_id)); List<VisualScript::SequenceConnection> sequence_conns; - script->get_sequence_connection_list(edited_func, &sequence_conns); + script->get_sequence_connection_list(func, &sequence_conns); for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { if (E->get().from_node == p_id || E->get().to_node == p_id) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", edited_func, E->get().from_node, E->get().from_output, E->get().to_node); + undo_redo->add_undo_method(script.ptr(), "sequence_connect", func, E->get().from_node, E->get().from_output, E->get().to_node); } } List<VisualScript::DataConnection> data_conns; - script->get_data_connection_list(edited_func, &data_conns); + script->get_data_connection_list(func, &data_conns); for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { if (E->get().from_node == p_id || E->get().to_node == p_id) { - undo_redo->add_undo_method(script.ptr(), "data_connect", edited_func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } @@ -2329,15 +2796,29 @@ void VisualScriptEditor::_remove_node(int p_id) { void VisualScriptEditor::_node_ports_changed(const String &p_func, int p_id) { - if (p_func != String(edited_func)) - return; - _update_graph(p_id); } +bool VisualScriptEditor::node_has_sequence_connections(const StringName &p_func, int p_id) { + List<VisualScript::SequenceConnection> sequence_conns; + script->get_sequence_connection_list(p_func, &sequence_conns); + + for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { + int from = E->get().from_node; + int to = E->get().to_node; + + if (to == p_id || from == p_id) + return true; + } + + return false; +} + void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) { - Ref<VisualScriptNode> from_node = script->get_node(edited_func, p_from.to_int()); + StringName from_func = _get_function_of_node(p_from.to_int()); + + Ref<VisualScriptNode> from_node = script->get_node(from_func, p_from.to_int()); ERR_FAIL_COND(!from_node.is_valid()); bool from_seq; @@ -2346,7 +2827,9 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, if (!_get_out_slot(from_node, p_from_slot, from_port, from_seq)) return; //can't connect this, it's invalid - Ref<VisualScriptNode> to_node = script->get_node(edited_func, p_to.to_int()); + StringName to_func = _get_function_of_node(p_to.to_int()); + + Ref<VisualScriptNode> to_node = script->get_node(to_func, p_to.to_int()); ERR_FAIL_COND(!to_node.is_valid()); bool to_seq; @@ -2357,29 +2840,170 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, ERR_FAIL_COND(from_seq != to_seq); + // Do all the checks here + StringName func; // this the func where we store the one the nodes at the end of the resolution on having multiple nodes + undo_redo->create_action(TTR("Connect Nodes")); + if (from_func == to_func) { + func = to_func; + } else if (from_seq) { + // this is a sequence connection + _move_nodes_with_rescan(to_func, from_func, p_to.to_int()); // this function moves the nodes from func1 to func2 + func = from_func; + } else { + if (node_has_sequence_connections(to_func, p_to.to_int())) { + if (node_has_sequence_connections(from_func, p_from.to_int())) { + ERR_PRINT("Trying to connect between different sequence node trees"); + return; + } else { + _move_nodes_with_rescan(from_func, to_func, p_from.to_int()); + func = to_func; + } + } else if (node_has_sequence_connections(from_func, p_from.to_int())) { + if (from_func == default_func) { + _move_nodes_with_rescan(from_func, to_func, p_from.to_int()); + func = to_func; + } else { + _move_nodes_with_rescan(to_func, from_func, p_to.to_int()); + func = from_func; + } + } else { + if (to_func == default_func) { + _move_nodes_with_rescan(to_func, from_func, p_to.to_int()); + func = from_func; + } else { + _move_nodes_with_rescan(from_func, to_func, p_from.to_int()); + func = to_func; + } + } + } + if (from_seq) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", edited_func, p_from.to_int(), from_port, p_to.to_int()); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", edited_func, p_from.to_int(), from_port, p_to.to_int()); + undo_redo->add_do_method(script.ptr(), "sequence_connect", func, p_from.to_int(), from_port, p_to.to_int()); + // this undo error on undo after move can't be removed without painful gymnastics + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, p_from.to_int(), from_port, p_to.to_int()); } else { + bool converted = false; + int conv_node = -1; + + Ref<VisualScriptOperator> oper = to_node; + if (oper.is_valid() && oper->get_typed() == Variant::NIL) { + // it's an operator Node and if the type is already nil + if (from_node->get_output_value_port_info(from_port).type != Variant::NIL) { + oper->set_typed(from_node->get_output_value_port_info(from_port).type); + } + } - // disconnect current, and connect the new one - if (script->is_input_value_port_connected(edited_func, p_to.to_int(), to_port)) { - int conn_from; - int conn_port; - script->get_input_value_port_connection_source(edited_func, p_to.to_int(), to_port, &conn_from, &conn_port); - undo_redo->add_do_method(script.ptr(), "data_disconnect", edited_func, conn_from, conn_port, p_to.to_int(), to_port); - undo_redo->add_undo_method(script.ptr(), "data_connect", edited_func, conn_from, conn_port, p_to.to_int(), to_port); + Ref<VisualScriptOperator> operf = from_node; + if (operf.is_valid() && operf->get_typed() == Variant::NIL) { + // it's an operator Node and if the type is already nil + if (to_node->get_input_value_port_info(to_port).type != Variant::NIL) { + operf->set_typed(to_node->get_input_value_port_info(to_port).type); + } } - undo_redo->add_do_method(script.ptr(), "data_connect", edited_func, p_from.to_int(), from_port, p_to.to_int(), to_port); - undo_redo->add_undo_method(script.ptr(), "data_disconnect", edited_func, p_from.to_int(), from_port, p_to.to_int(), to_port); - //update nodes in sgraph - undo_redo->add_do_method(this, "_update_graph", p_from.to_int()); - undo_redo->add_do_method(this, "_update_graph", p_to.to_int()); - undo_redo->add_undo_method(this, "_update_graph", p_from.to_int()); - undo_redo->add_undo_method(this, "_update_graph", p_to.to_int()); + Variant::Type to_type = to_node->get_input_value_port_info(to_port).type; + Variant::Type from_type = from_node->get_output_value_port_info(from_port).type; + + if (to_type != Variant::NIL && from_type != Variant::NIL && to_type != from_type) { + // add a constructor node between the ports + bool exceptions = false; // true if there are any exceptions + exceptions = exceptions || (to_type == Variant::INT && from_type == Variant::REAL); + exceptions = exceptions || (to_type == Variant::REAL && from_type == Variant::INT); + if (Variant::can_convert(from_type, to_type) && !exceptions) { + MethodInfo mi; + mi.name = Variant::get_type_name(to_type); + PropertyInfo pi; + pi.name = "from"; + pi.type = from_type; + mi.arguments.push_back(pi); + mi.return_val.type = to_type; + // we know that this is allowed so create a new constructor node + Ref<VisualScriptConstructor> constructor; + constructor.instance(); + constructor->set_constructor_type(to_type); + constructor->set_constructor(mi); + // add the new constructor node + + GraphNode *gn = Object::cast_to<GraphNode>(graph->get_node(p_from)); + GraphNode *gn2 = Object::cast_to<GraphNode>(graph->get_node(p_to)); + if (gn && gn2) { + Vector2 from_node_size = gn->get_rect().get_size(); + Vector2 to_node_size = gn2->get_rect().get_size(); + Vector2 to_node_pos = script->get_node_position(func, p_to.to_int()); + Vector2 from_node_pos = script->get_node_position(func, p_from.to_int()); + Vector2 new_to_node_pos = from_node_pos; + Vector2 constructor_pos; + if ((to_node_pos.x - from_node_pos.x) < 0) { + // to is behind from node + if (to_node_pos.x > (from_node_pos.x - to_node_size.x - 240)) + new_to_node_pos.x = from_node_pos.x - to_node_size.x - 240; // approx size of constructor node + padding + else + new_to_node_pos.x = to_node_pos.x; + new_to_node_pos.y = to_node_pos.y; + constructor_pos.x = from_node_pos.x - 210; + constructor_pos.y = to_node_pos.y; + } else { + // to is ahead of from node + if (to_node_pos.x < (from_node_size.x + from_node_pos.x + 240)) + new_to_node_pos.x = from_node_size.x + from_node_pos.x + 240; // approx size of constructor node + padding + else + new_to_node_pos.x = to_node_pos.x; + new_to_node_pos.y = to_node_pos.y; + constructor_pos.x = from_node_size.x + from_node_pos.x + 10; + constructor_pos.y = to_node_pos.y; + } + undo_redo->add_do_method(this, "_move_node", func, p_to.to_int(), new_to_node_pos); + undo_redo->add_undo_method(this, "_move_node", func, p_to.to_int(), to_node_pos); + conv_node = script->get_available_id(); + undo_redo->add_do_method(script.ptr(), "add_node", func, conv_node, constructor, _get_available_pos(false, constructor_pos)); + undo_redo->add_undo_method(script.ptr(), "remove_node", func, conv_node); + converted = true; + } + } + } + + // disconnect current, and connect the new one + if (script->is_input_value_port_connected(func, p_to.to_int(), to_port)) { + if (can_swap && data_disconnect_node == p_to.to_int()) { + int conn_from; + int conn_port; + script->get_input_value_port_connection_source(func, p_to.to_int(), to_port, &conn_from, &conn_port); + undo_redo->add_do_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, p_to.to_int(), to_port); + undo_redo->add_do_method(script.ptr(), "data_connect", func, conn_from, conn_port, data_disconnect_node, data_disconnect_port); + undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, data_disconnect_node, data_disconnect_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", func, conn_from, conn_port, p_to.to_int(), to_port); + can_swap = false; // swapped + } else { + int conn_from; + int conn_port; + script->get_input_value_port_connection_source(func, p_to.to_int(), to_port, &conn_from, &conn_port); + undo_redo->add_do_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, p_to.to_int(), to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", func, conn_from, conn_port, p_to.to_int(), to_port); + } + } + if (!converted) { + undo_redo->add_do_method(script.ptr(), "data_connect", func, p_from.to_int(), from_port, p_to.to_int(), to_port); + undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, p_from.to_int(), from_port, p_to.to_int(), to_port); + } else { + // this is noice + undo_redo->add_do_method(script.ptr(), "data_connect", func, p_from.to_int(), from_port, conv_node, 0); + undo_redo->add_do_method(script.ptr(), "data_connect", func, conv_node, 0, p_to.to_int(), to_port); + // I don't think this is needed but gonna leave it here for now... until I need to finalise it all + undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, p_from.to_int(), from_port, conv_node, 0); + undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, conv_node, 0, p_to.to_int(), to_port); + } + //update nodes in graph + if (!converted) { + undo_redo->add_do_method(this, "_update_graph", p_from.to_int()); + undo_redo->add_do_method(this, "_update_graph", p_to.to_int()); + undo_redo->add_undo_method(this, "_update_graph", p_from.to_int()); + undo_redo->add_undo_method(this, "_update_graph", p_to.to_int()); + } else { + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + } } undo_redo->add_do_method(this, "_update_graph_connections"); @@ -2390,7 +3014,10 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, void VisualScriptEditor::_graph_disconnected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) { - Ref<VisualScriptNode> from_node = script->get_node(edited_func, p_from.to_int()); + StringName func = _get_function_of_node(p_from.to_int()); + ERR_FAIL_COND(func != _get_function_of_node(p_to.to_int())); + + Ref<VisualScriptNode> from_node = script->get_node(func, p_from.to_int()); ERR_FAIL_COND(!from_node.is_valid()); bool from_seq; @@ -2399,7 +3026,7 @@ void VisualScriptEditor::_graph_disconnected(const String &p_from, int p_from_sl if (!_get_out_slot(from_node, p_from_slot, from_port, from_seq)) return; //can't connect this, it's invalid - Ref<VisualScriptNode> to_node = script->get_node(edited_func, p_to.to_int()); + Ref<VisualScriptNode> to_node = script->get_node(func, p_to.to_int()); ERR_FAIL_COND(!to_node.is_valid()); bool to_seq; @@ -2410,15 +3037,20 @@ void VisualScriptEditor::_graph_disconnected(const String &p_from, int p_from_sl ERR_FAIL_COND(from_seq != to_seq); - undo_redo->create_action(TTR("Connect Nodes")); + undo_redo->create_action(TTR("Disconnect Nodes")); if (from_seq) { - undo_redo->add_do_method(script.ptr(), "sequence_disconnect", edited_func, p_from.to_int(), from_port, p_to.to_int()); - undo_redo->add_undo_method(script.ptr(), "sequence_connect", edited_func, p_from.to_int(), from_port, p_to.to_int()); + undo_redo->add_do_method(script.ptr(), "sequence_disconnect", func, p_from.to_int(), from_port, p_to.to_int()); + undo_redo->add_undo_method(script.ptr(), "sequence_connect", func, p_from.to_int(), from_port, p_to.to_int()); } else { - undo_redo->add_do_method(script.ptr(), "data_disconnect", edited_func, p_from.to_int(), from_port, p_to.to_int(), to_port); - undo_redo->add_undo_method(script.ptr(), "data_connect", edited_func, p_from.to_int(), from_port, p_to.to_int(), to_port); - //update nodes in sgraph + + can_swap = true; + data_disconnect_node = p_to.to_int(); + data_disconnect_port = to_port; + + undo_redo->add_do_method(script.ptr(), "data_disconnect", func, p_from.to_int(), from_port, p_to.to_int(), to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", func, p_from.to_int(), from_port, p_to.to_int(), to_port); + //update relevant nodes in the graph undo_redo->add_do_method(this, "_update_graph", p_from.to_int()); undo_redo->add_do_method(this, "_update_graph", p_to.to_int()); undo_redo->add_undo_method(this, "_update_graph", p_from.to_int()); @@ -2430,6 +3062,216 @@ void VisualScriptEditor::_graph_disconnected(const String &p_from, int p_from_sl undo_redo->commit_action(); } +void VisualScriptEditor::_move_nodes_with_rescan(const StringName &p_func_from, const StringName &p_func_to, int p_id) { + + Set<int> nodes_to_move; + HashMap<int, Map<int, int> > seqconns_to_move; // from => List(outp, to) + HashMap<int, Map<int, Pair<int, int> > > dataconns_to_move; // to => List(inp_p => from, outp) + + nodes_to_move.insert(p_id); + Set<int> sequence_connections; + { + List<VisualScript::SequenceConnection> sequence_conns; + script->get_sequence_connection_list(p_func_from, &sequence_conns); + + HashMap<int, Map<int, int> > seqcons; // from => List(out_p => to) + + for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { + int from = E->get().from_node; + int to = E->get().to_node; + int out_p = E->get().from_output; + if (!seqcons.has(from)) + seqcons.set(from, Map<int, int>()); + seqcons[from].insert(out_p, to); + sequence_connections.insert(to); + sequence_connections.insert(from); + } + + int conn = p_id; + List<int> stack; + HashMap<int, Set<int> > seen; // from, outp + while (seqcons.has(conn)) { + for (auto E = seqcons[conn].front(); E; E = E->next()) { + if (seen.has(conn) && seen[conn].has(E->key())) { + if (!E->next()) { + if (stack.size() > 0) { + conn = stack.back()->get(); + stack.pop_back(); + break; + } + conn = -101; + break; + } + continue; + } + if (!seen.has(conn)) + seen.set(conn, Set<int>()); + seen[conn].insert(E->key()); + stack.push_back(conn); + if (!seqconns_to_move.has(conn)) + seqconns_to_move.set(conn, Map<int, int>()); + seqconns_to_move[conn].insert(E->key(), E->get()); + conn = E->get(); + nodes_to_move.insert(conn); + break; + } + if (!seqcons.has(conn) && stack.size() > 0) { + conn = stack.back()->get(); + stack.pop_back(); + } + } + } + + { + List<VisualScript::DataConnection> data_connections; + script->get_data_connection_list(p_func_from, &data_connections); + + HashMap<int, Map<int, Pair<int, int> > > connections; + + for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { + int from = E->get().from_node; + int to = E->get().to_node; + int out_p = E->get().from_port; + int in_p = E->get().to_port; + + if (!connections.has(to)) + connections.set(to, Map<int, Pair<int, int> >()); + connections[to].insert(in_p, Pair<int, int>(from, out_p)); + } + + // go through the HashMap and do all sorts of crazy ass stuff now... + Set<int> nodes_to_be_added; + for (Set<int>::Element *F = nodes_to_move.front(); F; F = F->next()) { + HashMap<int, Set<int> > seen; + List<int> stack; + int id = F->get(); + while (connections.has(id)) { + for (auto E = connections[id].front(); E; E = E->next()) { + if (seen.has(id) && seen[id].has(E->key())) { + if (!E->next()) { + if (stack.size() > 0) { + id = stack.back()->get(); + stack.pop_back(); + break; + } + id = -11; // I assume ids can't be negative should confirm it... + break; + } + continue; + } + + if (sequence_connections.has(E->get().first)) { + if (!nodes_to_move.has(E->get().first)) { + if (stack.size() > 0) { + id = stack.back()->get(); + stack.pop_back(); + break; + } + id = -11; // I assume ids can't be negative should confirm it... + break; + } + } + + if (!seen.has(id)) + seen.set(id, Set<int>()); + seen[id].insert(E->key()); + stack.push_back(id); + if (!dataconns_to_move.has(id)) + dataconns_to_move.set(id, Map<int, Pair<int, int> >()); + dataconns_to_move[id].insert(E->key(), Pair<int, int>(E->get().first, E->get().second)); + id = E->get().first; + nodes_to_be_added.insert(id); + break; + } + if (!connections.has(id) && stack.size() > 0) { + id = stack.back()->get(); + stack.pop_back(); + } + } + } + for (Set<int>::Element *E = nodes_to_be_added.front(); E; E = E->next()) { + nodes_to_move.insert(E->get()); + } + } + + // * this is primarily for the sake of the having proper undo + List<VisualScript::SequenceConnection> seqext; + List<VisualScript::DataConnection> dataext; + + List<VisualScript::SequenceConnection> seq_connections; + script->get_sequence_connection_list(p_func_from, &seq_connections); + + for (List<VisualScript::SequenceConnection>::Element *E = seq_connections.front(); E; E = E->next()) { + if (!nodes_to_move.has(E->get().from_node) && nodes_to_move.has(E->get().to_node)) { + seqext.push_back(E->get()); + } else if (nodes_to_move.has(E->get().from_node) && !nodes_to_move.has(E->get().to_node)) { + seqext.push_back(E->get()); + } + } + + List<VisualScript::DataConnection> data_connections; + script->get_data_connection_list(p_func_from, &data_connections); + + for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { + if (!nodes_to_move.has(E->get().from_node) && nodes_to_move.has(E->get().to_node)) { + dataext.push_back(E->get()); + } else if (nodes_to_move.has(E->get().from_node) && !nodes_to_move.has(E->get().to_node)) { + dataext.push_back(E->get()); + } + } + + // undo_redo->create_action("Rescan Functions"); + + for (Set<int>::Element *E = nodes_to_move.front(); E; E = E->next()) { + int id = E->get(); + + undo_redo->add_do_method(script.ptr(), "remove_node", p_func_from, id); + undo_redo->add_do_method(script.ptr(), "add_node", p_func_to, id, script->get_node(p_func_from, id), script->get_node_position(p_func_from, id)); + + undo_redo->add_undo_method(script.ptr(), "remove_node", p_func_to, id); + undo_redo->add_undo_method(script.ptr(), "add_node", p_func_from, id, script->get_node(p_func_from, id), script->get_node_position(p_func_from, id)); + } + + List<int> skeys; + seqconns_to_move.get_key_list(&skeys); + for (List<int>::Element *E = skeys.front(); E; E = E->next()) { + int from_node = E->get(); + for (Map<int, int>::Element *F = seqconns_to_move[from_node].front(); F; F = F->next()) { + int from_port = F->key(); + int to_node = F->get(); + undo_redo->add_do_method(script.ptr(), "sequence_connect", p_func_to, from_node, from_port, to_node); + undo_redo->add_undo_method(script.ptr(), "sequence_connect", p_func_from, from_node, from_port, to_node); + } + } + + List<int> keys; + dataconns_to_move.get_key_list(&keys); + for (List<int>::Element *E = keys.front(); E; E = E->next()) { + int to_node = E->get(); // to_node + for (Map<int, Pair<int, int> >::Element *F = dataconns_to_move[E->get()].front(); F; F = F->next()) { + int inp_p = F->key(); + Pair<int, int> fro = F->get(); + + undo_redo->add_do_method(script.ptr(), "data_connect", p_func_to, fro.first, fro.second, to_node, inp_p); + undo_redo->add_undo_method(script.ptr(), "data_connect", p_func_from, fro.first, fro.second, to_node, inp_p); + } + } + + // this to have proper undo operations + for (List<VisualScript::SequenceConnection>::Element *E = seqext.front(); E; E = E->next()) { + undo_redo->add_undo_method(script.ptr(), "sequence_connect", p_func_from, E->get().from_node, E->get().from_output, E->get().to_node); + } + for (List<VisualScript::DataConnection>::Element *E = dataext.front(); E; E = E->next()) { + undo_redo->add_undo_method(script.ptr(), "data_connect", p_func_from, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + } + // this doesn't need do methods as they are handled by the subsequent do calls implicitly + + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + + // undo_redo->commit_action(); +} + void VisualScriptEditor::_graph_connect_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_pos) { Node *node = graph->get_node(p_from); @@ -2437,7 +3279,9 @@ void VisualScriptEditor::_graph_connect_to_empty(const String &p_from, int p_fro if (!gn) return; - Ref<VisualScriptNode> vsn = script->get_node(edited_func, p_from.to_int()); + StringName func = _get_function_of_node(p_from.to_int()); + + Ref<VisualScriptNode> vsn = script->get_node(func, p_from.to_int()); if (!vsn.is_valid()) return; @@ -2447,12 +3291,11 @@ void VisualScriptEditor::_graph_connect_to_empty(const String &p_from, int p_fro port_action_node = p_from.to_int(); port_action_output = p_from_slot; - _port_action_menu(CREATE_ACTION); + _port_action_menu(CREATE_ACTION, func); } else { - port_action_output = p_from_slot - vsn->get_output_sequence_port_count(); port_action_node = p_from.to_int(); - _port_action_menu(CREATE_CALL_SET_GET); + _port_action_menu(CREATE_CALL_SET_GET, func); } } @@ -2466,7 +3309,9 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac visited_nodes.insert(p_port_action_node); - Ref<VisualScriptNode> node = script->get_node(edited_func, p_port_action_node); + StringName func = _get_function_of_node(p_port_action_node); + + Ref<VisualScriptNode> node = script->get_node(func, p_port_action_node); if (!node.is_valid()) { @@ -2485,7 +3330,7 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac int from_node; int from_port; - if (script->get_input_value_port_connection_source(edited_func, p_port_action_node, i, &from_node, &from_port)) { + if (script->get_input_value_port_connection_source(func, p_port_action_node, i, &from_node, &from_port)) { g = _guess_output_type(from_node, from_port, visited_nodes); } else { @@ -2510,7 +3355,7 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac return node->guess_output_type(in_guesses.ptrw(), p_port_action_output); } -void VisualScriptEditor::_port_action_menu(int p_option) { +void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func) { Vector2 ofs = graph->get_scroll_ofs() + port_action_pos; if (graph->is_using_snap()) { @@ -2534,8 +3379,10 @@ void VisualScriptEditor::_port_action_menu(int p_option) { } else { n->set_base_type("Object"); } - - String type_string = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + String type_string; + if (script->get_node(func, port_action_node)->get_output_value_port_count() > 0) { + type_string = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + } if (tg.type == Variant::OBJECT) { if (tg.script.is_valid()) { new_connect_node_select->select_from_script(tg.script, ""); @@ -2549,10 +3396,19 @@ void VisualScriptEditor::_port_action_menu(int p_option) { } else { new_connect_node_select->select_from_basic_type(tg.type); } + // ensure that the dialog fits inside the graph + Vector2 pos = mouse_up_position; + Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size(); + pos.x = pos.x > bounds.x ? bounds.x : pos.x; + pos.y = pos.y > bounds.y ? bounds.y : pos.y; + new_connect_node_select->set_position(pos); } break; case CREATE_ACTION: { VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn); - PropertyInfo property_info = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output); + PropertyInfo property_info; + if (script->get_node(func, port_action_node)->get_output_value_port_count() > 0) { + property_info = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output); + } if (tg.type == Variant::OBJECT) { if (property_info.type == Variant::OBJECT && property_info.hint_string != String()) { new_connect_node_select->select_from_action(property_info.hint_string); @@ -2564,25 +3420,18 @@ void VisualScriptEditor::_port_action_menu(int p_option) { } else { new_connect_node_select->select_from_action(Variant::get_type_name(tg.type)); } + // ensure that the dialog fits inside the graph + Vector2 pos = mouse_up_position; + Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size(); + pos.x = pos.x > bounds.x ? bounds.x : pos.x; + pos.y = pos.y > bounds.y ? bounds.y : pos.y; + new_connect_node_select->set_position(pos); } break; } } -void VisualScriptEditor::new_node(Ref<VisualScriptNode> vnode, Vector2 ofs) { - Set<int> vn; - Ref<VisualScriptNode> vnode_old = script->get_node(edited_func, port_action_node); - int new_id = script->get_available_id(); - undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); - undo_redo->add_do_method(this, "_update_graph", new_id); - undo_redo->add_undo_method(this, "_update_graph", new_id); - undo_redo->commit_action(); - - port_action_new_node = new_id; -} - void VisualScriptEditor::connect_data(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode, int new_id) { + undo_redo->create_action(TTR("Connect Node Data")); VisualScriptReturn *vnode_return = Object::cast_to<VisualScriptReturn>(vnode.ptr()); if (vnode_return != NULL && vnode_old->get_output_value_port_count() > 0) { @@ -2601,34 +3450,47 @@ void VisualScriptEditor::connect_data(Ref<VisualScriptNode> vnode_old, Ref<Visua if (port >= value_count) { port = 0; } - undo_redo->add_do_method(script.ptr(), "data_connect", edited_func, port_action_node, port, new_id, 0); - undo_redo->add_undo_method(script.ptr(), "data_disconnect", edited_func, port_action_node, port, new_id, 0); + StringName func = _get_function_of_node(port_action_node); + undo_redo->add_do_method(script.ptr(), "data_connect", func, port_action_node, port, new_id, 0); + undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, port_action_node, port, new_id, 0); undo_redo->commit_action(); } void VisualScriptEditor::_selected_connect_node(const String &p_text, const String &p_category, const bool p_connecting) { + Vector2 ofs = graph->get_scroll_ofs() + port_action_pos; if (graph->is_using_snap()) { int snap = graph->get_snap(); ofs = ofs.snapped(Vector2(snap, snap)); } ofs /= EDSCALE; + ofs /= graph->get_zoom(); Set<int> vn; + bool port_node_exists = true; + + StringName func = _get_function_of_node(port_action_node); + if (func == StringName()) { + func = default_func; + port_node_exists = false; + } + if (p_category == "visualscript") { Ref<VisualScriptNode> vnode_new = VisualScriptLanguage::singleton->create_node_from_name(p_text); - Ref<VisualScriptNode> vnode_old = script->get_node(edited_func, port_action_node); + Ref<VisualScriptNode> vnode_old; + if (port_node_exists) + vnode_old = script->get_node(func, port_action_node); int new_id = script->get_available_id(); - if (Object::cast_to<VisualScriptOperator>(vnode_new.ptr()) && script->get_node(edited_func, port_action_node).is_valid()) { - Variant::Type type = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).type; + if (Object::cast_to<VisualScriptOperator>(vnode_new.ptr()) && vnode_old.is_valid()) { + Variant::Type type = vnode_old->get_output_value_port_info(port_action_output).type; Object::cast_to<VisualScriptOperator>(vnode_new.ptr())->set_typed(type); } - if (Object::cast_to<VisualScriptTypeCast>(vnode_new.ptr()) && script->get_node(edited_func, port_action_node).is_valid()) { - Variant::Type type = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).type; - String hint_name = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + if (Object::cast_to<VisualScriptTypeCast>(vnode_new.ptr()) && vnode_old.is_valid()) { + Variant::Type type = vnode_old->get_output_value_port_info(port_action_output).type; + String hint_name = vnode_old->get_output_value_port_info(port_action_output).hint_string; if (type == Variant::OBJECT) { Object::cast_to<VisualScriptTypeCast>(vnode_new.ptr())->set_base_type(hint_name); @@ -2638,14 +3500,15 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri Object::cast_to<VisualScriptTypeCast>(vnode_new.ptr())->set_base_type(Variant::get_type_name(type)); } } + undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode_new, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", func, new_id, vnode_new, ofs); if (vnode_old.is_valid() && p_connecting) { connect_seq(vnode_old, vnode_new, new_id); connect_data(vnode_old, vnode_new, new_id); } - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); + undo_redo->add_undo_method(script.ptr(), "remove_node", func, new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); @@ -2653,6 +3516,7 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri } Ref<VisualScriptNode> vnode; + Ref<VisualScriptPropertySet> script_prop_set; if (p_category == String("method")) { @@ -2663,8 +3527,8 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri Ref<VisualScriptPropertySet> n; n.instance(); - n->set_property(p_text); vnode = n; + script_prop_set = n; } else if (p_category == String("get")) { Ref<VisualScriptPropertyGet> n; @@ -2708,114 +3572,133 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri } } - new_node(vnode, ofs); + int new_id = script->get_available_id(); + undo_redo->create_action(TTR("Add Node")); + undo_redo->add_do_method(script.ptr(), "add_node", func, new_id, vnode, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_node", func, new_id); + undo_redo->add_do_method(this, "_update_graph", new_id); + undo_redo->add_undo_method(this, "_update_graph", new_id); + undo_redo->commit_action(); - Ref<VisualScriptNode> vsn = script->get_node(edited_func, port_action_new_node); + if (script_prop_set.is_valid()) + script_prop_set->set_property(p_text); + + port_action_new_node = new_id; + + Ref<VisualScriptNode> vsn = script->get_node(func, port_action_new_node); if (Object::cast_to<VisualScriptFunctionCall>(vsn.ptr())) { Ref<VisualScriptFunctionCall> vsfc = vsn; vsfc->set_function(p_text); - VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn); - if (tg.type == Variant::OBJECT) { - vsfc->set_call_mode(VisualScriptFunctionCall::CALL_MODE_INSTANCE); - vsfc->set_base_type(String("")); - if (tg.gdclass != StringName()) { - vsfc->set_base_type(tg.gdclass); + if (port_node_exists && p_connecting) { + VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn); + + if (tg.type == Variant::OBJECT) { + vsfc->set_call_mode(VisualScriptFunctionCall::CALL_MODE_INSTANCE); + vsfc->set_base_type(String("")); + if (tg.gdclass != StringName()) { + vsfc->set_base_type(tg.gdclass); - } else if (script->get_node(edited_func, port_action_node).is_valid()) { - PropertyHint hint = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).hint; - String base_type = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + } else if (script->get_node(func, port_action_node).is_valid()) { + PropertyHint hint = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint; + String base_type = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; - if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) { - vsfc->set_base_type(base_type); + if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) { + vsfc->set_base_type(base_type); + } + if (p_text == "call" || p_text == "call_deferred") { + vsfc->set_function(String("")); + } } - if (p_text == "call" || p_text == "call_deferred") { - vsfc->set_function(String("")); + if (tg.script.is_valid()) { + vsfc->set_base_script(tg.script->get_path()); } + } else if (tg.type == Variant::NIL) { + vsfc->set_call_mode(VisualScriptFunctionCall::CALL_MODE_INSTANCE); + vsfc->set_base_type(String("")); + } else { + vsfc->set_call_mode(VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE); + vsfc->set_basic_type(tg.type); } - if (tg.script.is_valid()) { - vsfc->set_base_script(tg.script->get_path()); - } - } else if (tg.type == Variant::NIL) { - vsfc->set_call_mode(VisualScriptFunctionCall::CALL_MODE_INSTANCE); - vsfc->set_base_type(String("")); - } else { - vsfc->set_call_mode(VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE); - vsfc->set_basic_type(tg.type); } } - if (Object::cast_to<VisualScriptPropertySet>(vsn.ptr())) { - - Ref<VisualScriptPropertySet> vsp = vsn; + if (port_node_exists && p_connecting) { + if (Object::cast_to<VisualScriptPropertySet>(vsn.ptr())) { + Ref<VisualScriptPropertySet> vsp = vsn; - VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn); - if (tg.type == Variant::OBJECT) { - vsp->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE); - vsp->set_base_type(String("")); - if (tg.gdclass != StringName()) { - vsp->set_base_type(tg.gdclass); + VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn); + if (tg.type == Variant::OBJECT) { + vsp->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE); + vsp->set_base_type(String("")); + if (tg.gdclass != StringName()) { + vsp->set_base_type(tg.gdclass); - } else if (script->get_node(edited_func, port_action_node).is_valid()) { - PropertyHint hint = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).hint; - String base_type = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + } else if (script->get_node(func, port_action_node).is_valid()) { + PropertyHint hint = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint; + String base_type = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; - if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) { - vsp->set_base_type(base_type); + if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) { + vsp->set_base_type(base_type); + } } + if (tg.script.is_valid()) { + vsp->set_base_script(tg.script->get_path()); + } + } else if (tg.type == Variant::NIL) { + vsp->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE); + vsp->set_base_type(String("")); + } else { + vsp->set_call_mode(VisualScriptPropertySet::CALL_MODE_BASIC_TYPE); + vsp->set_basic_type(tg.type); } - if (tg.script.is_valid()) { - vsp->set_base_script(tg.script->get_path()); - } - } else if (tg.type == Variant::NIL) { - vsp->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE); - vsp->set_base_type(String("")); - } else { - vsp->set_call_mode(VisualScriptPropertySet::CALL_MODE_BASIC_TYPE); - vsp->set_basic_type(tg.type); } - } - - if (Object::cast_to<VisualScriptPropertyGet>(vsn.ptr())) { - Ref<VisualScriptPropertyGet> vsp = vsn; - VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn); - if (tg.type == Variant::OBJECT) { - vsp->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE); - vsp->set_base_type(String("")); - if (tg.gdclass != StringName()) { - vsp->set_base_type(tg.gdclass); + if (Object::cast_to<VisualScriptPropertyGet>(vsn.ptr())) { + Ref<VisualScriptPropertyGet> vsp = vsn; - } else if (script->get_node(edited_func, port_action_node).is_valid()) { - PropertyHint hint = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).hint; - String base_type = script->get_node(edited_func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; - if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) { - vsp->set_base_type(base_type); + VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn); + if (tg.type == Variant::OBJECT) { + vsp->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE); + vsp->set_base_type(String("")); + if (tg.gdclass != StringName()) { + vsp->set_base_type(tg.gdclass); + + } else if (script->get_node(func, port_action_node).is_valid()) { + PropertyHint hint = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint; + String base_type = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string; + if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) { + vsp->set_base_type(base_type); + } } + if (tg.script.is_valid()) { + vsp->set_base_script(tg.script->get_path()); + } + } else if (tg.type == Variant::NIL) { + vsp->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE); + vsp->set_base_type(String("")); + } else { + vsp->set_call_mode(VisualScriptPropertyGet::CALL_MODE_BASIC_TYPE); + vsp->set_basic_type(tg.type); } - if (tg.script.is_valid()) { - vsp->set_base_script(tg.script->get_path()); - } - } else if (tg.type == Variant::NIL) { - vsp->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE); - vsp->set_base_type(String("")); - } else { - vsp->set_call_mode(VisualScriptPropertyGet::CALL_MODE_BASIC_TYPE); - vsp->set_basic_type(tg.type); } } - Ref<VisualScriptNode> vnode_old = script->get_node(edited_func, port_action_node); - if (vnode_old.is_valid() && p_connecting) { - connect_seq(vnode_old, vnode, port_action_new_node); - connect_data(vnode_old, vnode, port_action_new_node); + if (port_node_exists) { + Ref<VisualScriptNode> vnode_old = script->get_node(func, port_action_node); + if (vnode_old.is_valid() && p_connecting) { + connect_seq(vnode_old, vnode, port_action_new_node); + connect_data(vnode_old, vnode, port_action_new_node); + } } _update_graph(port_action_new_node); - _update_graph_connections(); + if (port_node_exists) + _update_graph_connections(); } void VisualScriptEditor::connect_seq(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode_new, int new_id) { + VisualScriptOperator *vnode_operator = Object::cast_to<VisualScriptOperator>(vnode_new.ptr()); if (vnode_operator != NULL && !vnode_operator->has_input_sequence_port()) { return; @@ -2831,27 +3714,29 @@ void VisualScriptEditor::connect_seq(Ref<VisualScriptNode> vnode_old, Ref<Visual return; } + StringName func = _get_function_of_node(port_action_node); + undo_redo->create_action(TTR("Connect Node Sequence")); int pass_port = -vnode_old->get_output_sequence_port_count() + 1; int return_port = port_action_output - 1; if (vnode_old->get_output_value_port_info(port_action_output).name == String("pass") && - !script->get_output_sequence_ports_connected(edited_func, port_action_node).has(pass_port)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", edited_func, port_action_node, pass_port, new_id); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", edited_func, port_action_node, pass_port, new_id); + !script->get_output_sequence_ports_connected(func, port_action_node).has(pass_port)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, pass_port, new_id); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, pass_port, new_id); } else if (vnode_old->get_output_value_port_info(port_action_output).name == String("return") && - !script->get_output_sequence_ports_connected(edited_func, port_action_node).has(return_port)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", edited_func, port_action_node, return_port, new_id); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", edited_func, port_action_node, return_port, new_id); + !script->get_output_sequence_ports_connected(func, port_action_node).has(return_port)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, return_port, new_id); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, return_port, new_id); } else { for (int port = 0; port < vnode_old->get_output_sequence_port_count(); port++) { int count = vnode_old->get_output_sequence_port_count(); - if (port_action_output < count && !script->get_output_sequence_ports_connected(edited_func, port_action_node).has(port_action_output)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", edited_func, port_action_node, port_action_output, new_id); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", edited_func, port_action_node, port_action_output, new_id); + if (port_action_output < count && !script->get_output_sequence_ports_connected(func, port_action_node).has(port_action_output)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, port_action_output, new_id); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, port_action_output, new_id); break; - } else if (!script->get_output_sequence_ports_connected(edited_func, port_action_node).has(port)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", edited_func, port_action_node, port, new_id); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", edited_func, port_action_node, port, new_id); + } else if (!script->get_output_sequence_ports_connected(func, port_action_node).has(port)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, port, new_id); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, port, new_id); break; } } @@ -2884,7 +3769,6 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons } selected = name; - edited_func = selected; Ref<VisualScriptFunction> func_node; func_node.instance(); func_node->set_name(name); @@ -2896,14 +3780,16 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons func_node->add_argument(minfo.arguments[i].type, minfo.arguments[i].name, -1, minfo.arguments[i].hint, minfo.arguments[i].hint_string); } - undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node); + Vector2 ofs = _get_available_pos(); + + undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node, ofs); if (minfo.return_val.type != Variant::NIL || minfo.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) { Ref<VisualScriptReturn> ret_node; ret_node.instance(); ret_node->set_return_type(minfo.return_val.type); ret_node->set_enable_return_value(true); ret_node->set_name(name); - undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id() + 1, ret_node, Vector2(500, 0)); + undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id() + 1, ret_node, _get_available_pos(false, ofs + Vector2(500, 0))); } undo_redo->add_undo_method(script.ptr(), "remove_function", name); @@ -2918,31 +3804,30 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons } void VisualScriptEditor::_cancel_connect_node() { - // Causes crashes - //script->remove_node(edited_func, port_action_new_node); - _update_graph(); + // ensure the cancel is done + port_action_new_node = -1; } -void VisualScriptEditor::_create_new_node(const String &p_text, const String &p_category, const Vector2 &p_point) { - Vector2 ofs = graph->get_scroll_ofs() + p_point; - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - ofs /= EDSCALE; +int VisualScriptEditor::_create_new_node_from_name(const String &p_text, const Vector2 &p_point, const StringName &p_func) { + + StringName func = default_func; + if (p_func != StringName()) + func = p_func; + Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(p_text); int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", func, new_id, vnode, p_point); + undo_redo->add_undo_method(script.ptr(), "remove_node", func, new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); + return new_id; } void VisualScriptEditor::_default_value_changed() { - Ref<VisualScriptNode> vsn = script->get_node(edited_func, editing_id); + Ref<VisualScriptNode> vsn = script->get_node(_get_function_of_node(editing_id), editing_id); if (vsn.is_null()) return; @@ -2957,7 +3842,7 @@ void VisualScriptEditor::_default_value_changed() { void VisualScriptEditor::_default_value_edited(Node *p_button, int p_id, int p_input_port) { - Ref<VisualScriptNode> vsn = script->get_node(edited_func, p_id); + Ref<VisualScriptNode> vsn = script->get_node(_get_function_of_node(p_id), p_id); if (vsn.is_null()) return; @@ -2976,16 +3861,18 @@ void VisualScriptEditor::_default_value_edited(Node *p_button, int p_id, int p_i if (pinfo.type == Variant::NODE_PATH) { Node *edited_scene = get_tree()->get_edited_scene_root(); - Node *script_node = _find_script_node(edited_scene, edited_scene, script); + if (edited_scene) { // Fixing an old crash bug ( Visual Script Crashes on editing NodePath with an empty scene open) + Node *script_node = _find_script_node(edited_scene, edited_scene, script); - if (script_node) { - //pick a node relative to the script, IF the script exists - pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE; - pinfo.hint_string = script_node->get_path(); - } else { - //pick a path relative to edited scene - pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE; - pinfo.hint_string = get_tree()->get_edited_scene_root()->get_path(); + if (script_node) { + //pick a node relative to the script, IF the script exists + pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE; + pinfo.hint_string = script_node->get_path(); + } else { + //pick a path relative to edited scene + pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE; + pinfo.hint_string = get_tree()->get_edited_scene_root()->get_path(); + } } } @@ -3012,62 +3899,64 @@ void VisualScriptEditor::_hide_timer() { hint_text->hide(); } -void VisualScriptEditor::_node_filter_changed(const String &p_text) { - - _update_available_nodes(); -} - void VisualScriptEditor::_notification(int p_what) { - if (p_what == NOTIFICATION_READY || (p_what == NOTIFICATION_THEME_CHANGED && is_visible_in_tree())) { - - node_filter->set_right_icon(Control::get_icon("Search", "EditorIcons")); - node_filter->set_clear_button_enabled(true); - - if (p_what == NOTIFICATION_READY) { + switch (p_what) { + case NOTIFICATION_READY: { variable_editor->connect("changed", this, "_update_members"); signal_editor->connect("changed", this, "_update_members"); + FALLTHROUGH; } + case NOTIFICATION_THEME_CHANGED: { + if (p_what != NOTIFICATION_READY && !is_visible_in_tree()) { + return; + } - Ref<Theme> tm = EditorNode::get_singleton()->get_theme_base()->get_theme(); + edit_variable_edit->add_style_override("bg", get_stylebox("bg", "Tree")); + edit_signal_edit->add_style_override("bg", get_stylebox("bg", "Tree")); + func_input_scroll->add_style_override("bg", get_stylebox("bg", "Tree")); - bool dark_theme = tm->get_constant("dark_theme", "Editor"); + Ref<Theme> tm = EditorNode::get_singleton()->get_theme_base()->get_theme(); - List<Pair<String, Color> > colors; - if (dark_theme) { - colors.push_back(Pair<String, Color>("flow_control", Color::html("#f4f4f4"))); - colors.push_back(Pair<String, Color>("functions", Color::html("#f58581"))); - colors.push_back(Pair<String, Color>("data", Color::html("#80f6cf"))); - colors.push_back(Pair<String, Color>("operators", Color::html("#ab97df"))); - colors.push_back(Pair<String, Color>("custom", Color::html("#80bbf6"))); - colors.push_back(Pair<String, Color>("constants", Color::html("#f680b0"))); - } else { - colors.push_back(Pair<String, Color>("flow_control", Color::html("#424242"))); - colors.push_back(Pair<String, Color>("functions", Color::html("#f26661"))); - colors.push_back(Pair<String, Color>("data", Color::html("#13bb83"))); - colors.push_back(Pair<String, Color>("operators", Color::html("#8265d0"))); - colors.push_back(Pair<String, Color>("custom", Color::html("#4ea0f2"))); - colors.push_back(Pair<String, Color>("constants", Color::html("#f02f7d"))); - } + bool dark_theme = tm->get_constant("dark_theme", "Editor"); - for (List<Pair<String, Color> >::Element *E = colors.front(); E; E = E->next()) { - Ref<StyleBoxFlat> sb = tm->get_stylebox("frame", "GraphNode"); - if (!sb.is_null()) { - Ref<StyleBoxFlat> frame_style = sb->duplicate(); - Color c = sb->get_border_color(); - Color cn = E->get().second; - cn.a = c.a; - frame_style->set_border_color(cn); - node_styles[E->get().first] = frame_style; + List<Pair<String, Color> > colors; + if (dark_theme) { + colors.push_back(Pair<String, Color>("flow_control", Color(0.96, 0.96, 0.96))); + colors.push_back(Pair<String, Color>("functions", Color(0.96, 0.52, 0.51))); + colors.push_back(Pair<String, Color>("data", Color(0.5, 0.96, 0.81))); + colors.push_back(Pair<String, Color>("operators", Color(0.67, 0.59, 0.87))); + colors.push_back(Pair<String, Color>("custom", Color(0.5, 0.73, 0.96))); + colors.push_back(Pair<String, Color>("constants", Color(0.96, 0.5, 0.69))); + } else { + colors.push_back(Pair<String, Color>("flow_control", Color(0.26, 0.26, 0.26))); + colors.push_back(Pair<String, Color>("functions", Color(0.95, 0.4, 0.38))); + colors.push_back(Pair<String, Color>("data", Color(0.07, 0.73, 0.51))); + colors.push_back(Pair<String, Color>("operators", Color(0.51, 0.4, 0.82))); + colors.push_back(Pair<String, Color>("custom", Color(0.31, 0.63, 0.95))); + colors.push_back(Pair<String, Color>("constants", Color(0.94, 0.18, 0.49))); } - } - if (is_visible_in_tree() && script.is_valid()) { - _update_members(); - _update_graph(); - } - } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { - left_vsplit->set_visible(is_visible_in_tree()); + for (List<Pair<String, Color> >::Element *E = colors.front(); E; E = E->next()) { + Ref<StyleBoxFlat> sb = tm->get_stylebox("frame", "GraphNode"); + if (!sb.is_null()) { + Ref<StyleBoxFlat> frame_style = sb->duplicate(); + Color c = sb->get_border_color(); + Color cn = E->get().second; + cn.a = c.a; + frame_style->set_border_color(cn); + node_styles[E->get().first] = frame_style; + } + } + + if (is_visible_in_tree() && script.is_valid()) { + _update_members(); + _update_graph(); + } + } break; + case NOTIFICATION_VISIBILITY_CHANGED: { + members_section->set_visible(is_visible_in_tree()); + } break; } } @@ -3078,8 +3967,9 @@ void VisualScriptEditor::_graph_ofs_changed(const Vector2 &p_ofs) { updating_graph = true; - if (script->has_function(edited_func)) { - script->set_function_scroll(edited_func, graph->get_scroll_ofs() / EDSCALE); + // Just use the default func for all the properties that need to be handled for drawing rather than adding to the Visual Script Class + if (script->has_function(default_func)) { + script->set_function_scroll(default_func, graph->get_scroll_ofs() / EDSCALE); script->set_edited(true); } updating_graph = false; @@ -3090,7 +3980,9 @@ void VisualScriptEditor::_comment_node_resized(const Vector2 &p_new_size, int p_ if (updating_graph) return; - Ref<VisualScriptComment> vsc = script->get_node(edited_func, p_node); + StringName func = _get_function_of_node(p_node); + + Ref<VisualScriptComment> vsc = script->get_node(func, p_node); if (vsc.is_null()) return; @@ -3108,7 +4000,7 @@ void VisualScriptEditor::_comment_node_resized(const Vector2 &p_new_size, int p_ undo_redo->add_undo_method(vsc.ptr(), "set_size", vsc->get_size()); undo_redo->commit_action(); - gn->set_custom_minimum_size(p_new_size); //for this time since graph update is blocked + gn->set_custom_minimum_size(p_new_size); gn->set_size(Size2(1, 1)); graph->set_block_minimum_size_adjust(false); updating_graph = false; @@ -3128,7 +4020,8 @@ void VisualScriptEditor::_menu_option(int p_what) { if (gn) { if (gn->is_selected()) { int id = String(gn->get_name()).to_int(); - Ref<VisualScriptNode> vsn = script->get_node(edited_func, id); + StringName func = _get_function_of_node(id); + Ref<VisualScriptNode> vsn = script->get_node(func, id); if (vsn.is_valid()) { vsn->set_breakpoint(!vsn->is_breakpoint()); reselect.push_back(gn->get_name()); @@ -3146,32 +4039,34 @@ void VisualScriptEditor::_menu_option(int p_what) { } break; case EDIT_FIND_NODE_TYPE: { - _generic_search(); + _generic_search(script->get_instance_base_type()); } break; case EDIT_COPY_NODES: case EDIT_CUT_NODES: { - - if (!script->has_function(edited_func)) + if (!script->has_function(default_func)) break; clipboard->nodes.clear(); clipboard->data_connections.clear(); clipboard->sequence_connections.clear(); + Set<String> funcs; for (int i = 0; i < graph->get_child_count(); i++) { GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); if (gn) { if (gn->is_selected()) { int id = String(gn->get_name()).to_int(); - Ref<VisualScriptNode> node = script->get_node(edited_func, id); + StringName func = _get_function_of_node(id); + Ref<VisualScriptNode> node = script->get_node(func, id); if (Object::cast_to<VisualScriptFunction>(*node)) { EditorNode::get_singleton()->show_warning(TTR("Can't copy the function node.")); return; } if (node.is_valid()) { clipboard->nodes[id] = node->duplicate(true); - clipboard->nodes_positions[id] = script->get_node_position(edited_func, id); + clipboard->nodes_positions[id] = script->get_node_position(func, id); + funcs.insert(String(func)); } } } @@ -3180,37 +4075,38 @@ void VisualScriptEditor::_menu_option(int p_what) { if (clipboard->nodes.empty()) break; - List<VisualScript::SequenceConnection> sequence_connections; + for (Set<String>::Element *F = funcs.front(); F; F = F->next()) { + List<VisualScript::SequenceConnection> sequence_connections; - script->get_sequence_connection_list(edited_func, &sequence_connections); + script->get_sequence_connection_list(F->get(), &sequence_connections); - for (List<VisualScript::SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) { + for (List<VisualScript::SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) { - if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { + if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { - clipboard->sequence_connections.insert(E->get()); + clipboard->sequence_connections.insert(E->get()); + } } - } - List<VisualScript::DataConnection> data_connections; + List<VisualScript::DataConnection> data_connections; - script->get_data_connection_list(edited_func, &data_connections); + script->get_data_connection_list(F->get(), &data_connections); - for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { + for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { - if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { + if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { - clipboard->data_connections.insert(E->get()); + clipboard->data_connections.insert(E->get()); + } } } - if (p_what == EDIT_CUT_NODES) { _on_nodes_delete(); // oh yeah, also delete on cut } } break; case EDIT_PASTE_NODES: { - if (!script->has_function(edited_func)) + if (!script->has_function(default_func)) break; if (clipboard->nodes.empty()) { @@ -3228,11 +4124,15 @@ void VisualScriptEditor::_menu_option(int p_what) { Set<Vector2> existing_positions; { - List<int> nodes; - script->get_node_list(edited_func, &nodes); - for (List<int>::Element *E = nodes.front(); E; E = E->next()) { - Vector2 pos = script->get_node_position(edited_func, E->get()).snapped(Vector2(2, 2)); - existing_positions.insert(pos); + List<StringName> functions; + script->get_function_list(&functions); + for (List<StringName>::Element *F = functions.front(); F; F = F->next()) { + List<int> nodes; + script->get_node_list(F->get(), &nodes); + for (List<int>::Element *E = nodes.front(); E; E = E->next()) { + Vector2 pos = script->get_node_position(F->get(), E->get()).snapped(Vector2(2, 2)); + existing_positions.insert(pos); + } } } @@ -3251,20 +4151,20 @@ void VisualScriptEditor::_menu_option(int p_what) { paste_pos += Vector2(20, 20) * EDSCALE; } - undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, node, paste_pos); - undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id); + undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, node, paste_pos); + undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id); } for (Set<VisualScript::SequenceConnection>::Element *E = clipboard->sequence_connections.front(); E; E = E->next()) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", edited_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); - undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", edited_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); + undo_redo->add_do_method(script.ptr(), "sequence_connect", default_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); + undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", default_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); } for (Set<VisualScript::DataConnection>::Element *E = clipboard->data_connections.front(); E; E = E->next()) { - undo_redo->add_do_method(script.ptr(), "data_connect", edited_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); - undo_redo->add_undo_method(script.ptr(), "data_disconnect", edited_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); + undo_redo->add_do_method(script.ptr(), "data_connect", default_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); + undo_redo->add_undo_method(script.ptr(), "data_disconnect", default_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); } undo_redo->add_do_method(this, "_update_graph"); @@ -3280,6 +4180,275 @@ void VisualScriptEditor::_menu_option(int p_what) { } } } break; + case EDIT_CREATE_FUNCTION: { + + StringName function = ""; + Map<int, Ref<VisualScriptNode> > nodes; + Set<int> selections; + for (int i = 0; i < graph->get_child_count(); i++) { + GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); + if (gn) { + if (gn->is_selected()) { + int id = String(gn->get_name()).to_int(); + StringName func = _get_function_of_node(id); + Ref<VisualScriptNode> node = script->get_node(func, id); + if (Object::cast_to<VisualScriptFunction>(*node)) { + EditorNode::get_singleton()->show_warning(TTR("Can't create function with a function node.")); + return; + } + if (node.is_valid()) { + if (func != function && function != StringName("")) { + EditorNode::get_singleton()->show_warning(TTR("Can't create function of nodes from nodes of multiple functions.")); + return; + } + nodes.insert(id, node); + selections.insert(id); + function = func; + } + } + } + } + + if (nodes.size() == 0) { + return; // nothing to be done if there are no valid nodes selected + } + + Set<VisualScript::SequenceConnection> seqmove; + Set<VisualScript::DataConnection> datamove; + + Set<VisualScript::SequenceConnection> seqext; + Set<VisualScript::DataConnection> dataext; + + int start_node = -1; + Set<int> end_nodes; + if (nodes.size() == 1) { + Ref<VisualScriptNode> nd = script->get_node(function, nodes.front()->key()); + if (nd.is_valid() && nd->has_input_sequence_port()) + start_node = nodes.front()->key(); + else { + EditorNode::get_singleton()->show_warning(TTR("Select at least one node with sequence port.")); + return; + } + } else { + List<VisualScript::SequenceConnection> seqs; + script->get_sequence_connection_list(function, &seqs); + + if (seqs.size() == 0) { + // in case there are no sequence connections + // select the top most node cause that's probably how + // the user wants to connect the nodes + int top_nd = -1; + Vector2 top; + for (Map<int, Ref<VisualScriptNode> >::Element *E = nodes.front(); E; E = E->next()) { + Ref<VisualScriptNode> nd = script->get_node(function, E->key()); + if (nd.is_valid() && nd->has_input_sequence_port()) { + if (top_nd < 0) { + top_nd = E->key(); + top = script->get_node_position(function, top_nd); + } + Vector2 pos = script->get_node_position(function, E->key()); + if (top.y > pos.y) { + top_nd = E->key(); + top = pos; + } + } + } + Ref<VisualScriptNode> nd = script->get_node(function, top_nd); + if (nd.is_valid() && nd->has_input_sequence_port()) + start_node = top_nd; + else { + EditorNode::get_singleton()->show_warning(TTR("Select at least one node with sequence port.")); + return; + } + } else { + // pick the node with input sequence + Set<int> nodes_from; + Set<int> nodes_to; + for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) { + if (nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { + seqmove.insert(E->get()); + nodes_from.insert(E->get().from_node); + } else if (nodes.has(E->get().from_node) && !nodes.has(E->get().to_node)) { + seqext.insert(E->get()); + } else if (!nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { + if (start_node == -1) { + seqext.insert(E->get()); + start_node = E->get().to_node; + } else { + EditorNode::get_singleton()->show_warning(TTR("Try to only have one sequence input in selection.")); + return; + } + } + nodes_to.insert(E->get().to_node); + } + + // to use to add return nodes + _get_ends(start_node, seqs, selections, end_nodes); + + if (start_node == -1) { + // if we still don't have a start node then + // run through the nodes and select the first tree node + // ie node without any input sequence but output sequence + for (Set<int>::Element *E = nodes_from.front(); E; E = E->next()) { + if (!nodes_to.has(E->get())) { + start_node = E->get(); + } + } + } + } + } + + if (start_node == -1) { + return; // this should not happen, but just in case something goes wrong + } + + List<Variant::Type> inputs; // input types + List<Pair<int, int> > input_connections; + { + List<VisualScript::DataConnection> dats; + script->get_data_connection_list(function, &dats); + for (List<VisualScript::DataConnection>::Element *E = dats.front(); E; E = E->next()) { + if (nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { + datamove.insert(E->get()); + } else if (!nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { + // add all these as inputs for the Function + Ref<VisualScriptNode> node = script->get_node(function, E->get().to_node); + if (node.is_valid()) { + dataext.insert(E->get()); + PropertyInfo pi = node->get_input_value_port_info(E->get().to_port); + inputs.push_back(pi.type); + input_connections.push_back(Pair<int, int>(E->get().to_node, E->get().to_port)); + } + } else if (nodes.has(E->get().from_node) && !nodes.has(E->get().to_node)) { + dataext.insert(E->get()); + } + } + } + + String new_fn = _validate_name("new_function"); + + Vector2 ofs = _get_available_pos(false, script->get_node_position(function, start_node) - Vector2(80, 150)); + + Ref<VisualScriptFunction> func_node; + func_node.instance(); + func_node->set_name(new_fn); + + undo_redo->create_action(TTR("Create Function")); + + undo_redo->add_do_method(script.ptr(), "add_function", new_fn); + int fn_id = script->get_available_id(); + undo_redo->add_do_method(script.ptr(), "add_node", new_fn, fn_id, func_node, ofs); + undo_redo->add_undo_method(script.ptr(), "remove_function", new_fn); + undo_redo->add_do_method(this, "_update_members"); + undo_redo->add_undo_method(this, "_update_members"); + undo_redo->add_do_method(this, "emit_signal", "edited_script_changed"); + undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed"); + + // Move the nodes + + for (Map<int, Ref<VisualScriptNode> >::Element *E = nodes.front(); E; E = E->next()) { + undo_redo->add_do_method(script.ptr(), "remove_node", function, E->key()); + undo_redo->add_do_method(script.ptr(), "add_node", new_fn, E->key(), E->get(), script->get_node_position(function, E->key())); + + // undo_redo->add_undo_method(script.ptr(), "remove_node", new_fn, E->key()); not needed cause we already remove the function :P + undo_redo->add_undo_method(script.ptr(), "add_node", function, E->key(), E->get(), script->get_node_position(function, E->key())); + } + + for (Set<VisualScript::SequenceConnection>::Element *E = seqmove.front(); E; E = E->next()) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", new_fn, E->get().from_node, E->get().from_output, E->get().to_node); + undo_redo->add_undo_method(script.ptr(), "sequence_connect", function, E->get().from_node, E->get().from_output, E->get().to_node); + } + + for (Set<VisualScript::DataConnection>::Element *E = datamove.front(); E; E = E->next()) { + undo_redo->add_do_method(script.ptr(), "data_connect", new_fn, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(script.ptr(), "data_connect", function, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + } + + // Add undo for external connections as well so that it's easier to revert back and forth + // these didn't require do methods as it's already handled internally by other do calls + for (Set<VisualScript::SequenceConnection>::Element *E = seqext.front(); E; E = E->next()) { + undo_redo->add_undo_method(script.ptr(), "sequence_connect", function, E->get().from_node, E->get().from_output, E->get().to_node); + } + for (Set<VisualScript::DataConnection>::Element *E = dataext.front(); E; E = E->next()) { + undo_redo->add_undo_method(script.ptr(), "data_connect", function, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + } + + // I don't really think we need support for non sequenced functions at this moment + undo_redo->add_do_method(script.ptr(), "sequence_connect", new_fn, fn_id, 0, start_node); + + // end nodes are mapped to the return nodes with data connections if possible + int m = 1; + for (Set<int>::Element *G = end_nodes.front(); G; G = G->next()) { + Ref<VisualScriptReturn> ret_node; + ret_node.instance(); + + int ret_id = fn_id + (m++); + selections.insert(ret_id); + Vector2 ofsi = _get_available_pos(false, script->get_node_position(function, G->get()) + Vector2(80, -100)); + undo_redo->add_do_method(script.ptr(), "add_node", new_fn, ret_id, ret_node, ofsi); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_fn, ret_id); + + undo_redo->add_do_method(script.ptr(), "sequence_connect", new_fn, G->get(), 0, ret_id); + // add data outputs from each of the end_nodes + Ref<VisualScriptNode> vsn = script->get_node(function, G->get()); + if (vsn.is_valid() && vsn->get_output_value_port_count() > 0) { + ret_node->set_enable_return_value(true); + // use the zeroth data port cause that's the likely one that is planned to be used + ret_node->set_return_type(vsn->get_output_value_port_info(0).type); + undo_redo->add_do_method(script.ptr(), "data_connect", new_fn, G->get(), 0, ret_id, 0); + } + } + + // * might make the system more intelligent by checking port from info. + int i = 0; + List<Pair<int, int> >::Element *F = input_connections.front(); + for (List<Variant::Type>::Element *E = inputs.front(); E && F; E = E->next(), F = F->next()) { + func_node->add_argument(E->get(), "arg_" + String::num_int64(i), i); + undo_redo->add_do_method(script.ptr(), "data_connect", new_fn, fn_id, i, F->get().first, F->get().second); + i++; // increment i + } + + undo_redo->add_do_method(this, "_update_graph"); + undo_redo->add_undo_method(this, "_update_graph"); + + undo_redo->commit_action(); + + // make sure all Nodes get marked for selection so that they can be moved together + selections.insert(fn_id); + for (int k = 0; k < graph->get_child_count(); k++) { + GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(k)); + if (gn) { + int id = gn->get_name().operator String().to_int(); + gn->set_selected(selections.has(id)); + } + } + + // Ensure Preview Selection is of newly created function node + if (selections.size()) { + EditorNode::get_singleton()->push_item(func_node.ptr()); + } + + } break; + case REFRESH_GRAPH: { + _update_graph(); + } break; + } +} + +// this is likely going to be very slow and I am not sure if I should keep it +// but I hope that it will not be a problem considering that we won't be creating functions so frequently +// and cyclic connections would be a problem but hopefully we won't let them get to this point +void VisualScriptEditor::_get_ends(int p_node, const List<VisualScript::SequenceConnection> &p_seqs, const Set<int> &p_selected, Set<int> &r_end_nodes) { + for (const List<VisualScript::SequenceConnection>::Element *E = p_seqs.front(); E; E = E->next()) { + int from = E->get().from_node; + int to = E->get().to_node; + + if (from == p_node && p_selected.has(to)) { + // this is an interior connection move forward to the to node + _get_ends(to, p_seqs, p_selected, r_end_nodes); + } else if (from == p_node && !p_selected.has(to)) { + r_end_nodes.insert(from); + } } } @@ -3292,6 +4461,9 @@ void VisualScriptEditor::_member_rmb_selected(const Vector2 &p_pos) { member_popup->set_position(members->get_global_position() + p_pos); member_popup->set_size(Vector2()); + function_name_edit->set_position(members->get_global_position() + p_pos); + function_name_edit->set_size(Vector2()); + TreeItem *root = members->get_root(); Ref<Texture> del_icon = Control::get_icon("Remove", "EditorIcons"); @@ -3302,6 +4474,8 @@ void VisualScriptEditor::_member_rmb_selected(const Vector2 &p_pos) { member_type = MEMBER_FUNCTION; member_name = ti->get_text(0); + member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT); + member_popup->add_separator(); member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("visual_script_editor/delete_selected"), MEMBER_REMOVE); member_popup->popup(); return; @@ -3369,6 +4543,11 @@ void VisualScriptEditor::_member_option(int p_option) { undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); + } else if (p_option == MEMBER_EDIT) { + selected = members->get_selected()->get_text(0); + function_name_edit->popup(); + function_name_box->set_text(selected); + function_name_box->select_all(); } } break; case MEMBER_VARIABLE: { @@ -3405,7 +4584,6 @@ void VisualScriptEditor::_member_option(int p_option) { undo_redo->add_undo_method(this, "_update_members"); undo_redo->commit_action(); } else if (p_option == MEMBER_EDIT) { - signal_editor->edit(name); edit_signal_dialog->set_title(TTR("Editing Signal:") + " " + name); edit_signal_dialog->popup_centered_minsize(Size2(400, 300) * EDSCALE); @@ -3426,8 +4604,14 @@ void VisualScriptEditor::_bind_methods() { ClassDB::bind_method("_member_edited", &VisualScriptEditor::_member_edited); ClassDB::bind_method("_member_selected", &VisualScriptEditor::_member_selected); ClassDB::bind_method("_update_members", &VisualScriptEditor::_update_members); + ClassDB::bind_method("_members_gui_input", &VisualScriptEditor::_members_gui_input); + ClassDB::bind_method("_member_rmb_selected", &VisualScriptEditor::_member_rmb_selected); + ClassDB::bind_method("_member_option", &VisualScriptEditor::_member_option); + ClassDB::bind_method("_fn_name_box_input", &VisualScriptEditor::_fn_name_box_input); + ClassDB::bind_method("_change_base_type", &VisualScriptEditor::_change_base_type); ClassDB::bind_method("_change_base_type_callback", &VisualScriptEditor::_change_base_type_callback); + ClassDB::bind_method("_toggle_tool_script", &VisualScriptEditor::_toggle_tool_script); ClassDB::bind_method("_node_selected", &VisualScriptEditor::_node_selected); ClassDB::bind_method("_node_moved", &VisualScriptEditor::_node_moved); ClassDB::bind_method("_move_node", &VisualScriptEditor::_move_node); @@ -3436,7 +4620,14 @@ void VisualScriptEditor::_bind_methods() { ClassDB::bind_method("_remove_node", &VisualScriptEditor::_remove_node); ClassDB::bind_method("_update_graph", &VisualScriptEditor::_update_graph, DEFVAL(-1)); ClassDB::bind_method("_node_ports_changed", &VisualScriptEditor::_node_ports_changed); - ClassDB::bind_method("_available_node_doubleclicked", &VisualScriptEditor::_available_node_doubleclicked); + + ClassDB::bind_method("_create_function_dialog", &VisualScriptEditor::_create_function_dialog); + ClassDB::bind_method("_create_function", &VisualScriptEditor::_create_function); + ClassDB::bind_method("_add_node_dialog", &VisualScriptEditor::_add_node_dialog); + ClassDB::bind_method("_add_func_input", &VisualScriptEditor::_add_func_input); + ClassDB::bind_method("_remove_func_input", &VisualScriptEditor::_remove_func_input); + ClassDB::bind_method("_deselect_input_names", &VisualScriptEditor::_deselect_input_names); + ClassDB::bind_method("_default_value_edited", &VisualScriptEditor::_default_value_edited); ClassDB::bind_method("_default_value_changed", &VisualScriptEditor::_default_value_changed); ClassDB::bind_method("_menu_option", &VisualScriptEditor::_menu_option); @@ -3449,15 +4640,23 @@ void VisualScriptEditor::_bind_methods() { ClassDB::bind_method("_selected_new_virtual_method", &VisualScriptEditor::_selected_new_virtual_method); ClassDB::bind_method("_cancel_connect_node", &VisualScriptEditor::_cancel_connect_node); - ClassDB::bind_method("_create_new_node", &VisualScriptEditor::_create_new_node); + ClassDB::bind_method("_create_new_node_from_name", &VisualScriptEditor::_create_new_node_from_name); ClassDB::bind_method("_expression_text_changed", &VisualScriptEditor::_expression_text_changed); + ClassDB::bind_method("_add_input_port", &VisualScriptEditor::_add_input_port); + ClassDB::bind_method("_add_output_port", &VisualScriptEditor::_add_output_port); + ClassDB::bind_method("_remove_input_port", &VisualScriptEditor::_remove_input_port); + ClassDB::bind_method("_remove_output_port", &VisualScriptEditor::_remove_output_port); + ClassDB::bind_method("_change_port_type", &VisualScriptEditor::_change_port_type); + ClassDB::bind_method("_update_node_size", &VisualScriptEditor::_update_node_size); + ClassDB::bind_method("_port_name_focus_out", &VisualScriptEditor::_port_name_focus_out); ClassDB::bind_method("get_drag_data_fw", &VisualScriptEditor::get_drag_data_fw); ClassDB::bind_method("can_drop_data_fw", &VisualScriptEditor::can_drop_data_fw); ClassDB::bind_method("drop_data_fw", &VisualScriptEditor::drop_data_fw); ClassDB::bind_method("_input", &VisualScriptEditor::_input); - ClassDB::bind_method("_members_gui_input", &VisualScriptEditor::_members_gui_input); + ClassDB::bind_method("_graph_gui_input", &VisualScriptEditor::_graph_gui_input); + ClassDB::bind_method("_on_nodes_delete", &VisualScriptEditor::_on_nodes_delete); ClassDB::bind_method("_on_nodes_duplicate", &VisualScriptEditor::_on_nodes_duplicate); @@ -3468,17 +4667,10 @@ void VisualScriptEditor::_bind_methods() { ClassDB::bind_method("_graph_connect_to_empty", &VisualScriptEditor::_graph_connect_to_empty); ClassDB::bind_method("_update_graph_connections", &VisualScriptEditor::_update_graph_connections); - ClassDB::bind_method("_node_filter_changed", &VisualScriptEditor::_node_filter_changed); ClassDB::bind_method("_selected_method", &VisualScriptEditor::_selected_method); ClassDB::bind_method("_draw_color_over_button", &VisualScriptEditor::_draw_color_over_button); - ClassDB::bind_method("_member_rmb_selected", &VisualScriptEditor::_member_rmb_selected); - - ClassDB::bind_method("_member_option", &VisualScriptEditor::_member_option); - - ClassDB::bind_method("_update_available_nodes", &VisualScriptEditor::_update_available_nodes); - ClassDB::bind_method("_generic_search", &VisualScriptEditor::_generic_search); } @@ -3488,6 +4680,8 @@ VisualScriptEditor::VisualScriptEditor() { clipboard = memnew(Clipboard); } updating_graph = false; + saved_pos_dirty = false; + saved_position = Vector2(0, 0); edit_menu = memnew(MenuButton); edit_menu->set_text(TTR("Edit")); @@ -3499,56 +4693,50 @@ VisualScriptEditor::VisualScriptEditor() { edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/copy_nodes"), EDIT_COPY_NODES); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/cut_nodes"), EDIT_CUT_NODES); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/paste_nodes"), EDIT_PASTE_NODES); - + edit_menu->get_popup()->add_separator(); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/create_function"), EDIT_CREATE_FUNCTION); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/refresh_nodes"), REFRESH_GRAPH); edit_menu->get_popup()->connect("id_pressed", this, "_menu_option"); - left_vsplit = memnew(VSplitContainer); - ScriptEditor::get_singleton()->get_left_list_split()->call_deferred("add_child", left_vsplit); //add but wait until done settig up this - left_vsplit->set_v_size_flags(SIZE_EXPAND_FILL); - left_vsplit->set_stretch_ratio(2); - left_vsplit->hide(); + members_section = memnew(VBoxContainer); + // Add but wait until done setting up this. + ScriptEditor::get_singleton()->get_left_list_split()->call_deferred("add_child", members_section); + members_section->set_v_size_flags(SIZE_EXPAND_FILL); - VBoxContainer *left_vb = memnew(VBoxContainer); - left_vsplit->add_child(left_vb); - left_vb->set_v_size_flags(SIZE_EXPAND_FILL); - //left_vb->set_custom_minimum_size(Size2(230, 1) * EDSCALE); + CheckButton *tool_script_check = memnew(CheckButton); + tool_script_check->set_text(TTR("Make Tool:")); + members_section->add_child(tool_script_check); + tool_script_check->connect("pressed", this, "_toggle_tool_script"); - base_type_select = memnew(Button); - left_vb->add_margin_child(TTR("Base Type:"), base_type_select); - base_type_select->connect("pressed", this, "_change_base_type"); + /// Members /// members = memnew(Tree); - left_vb->add_margin_child(TTR("Members:"), members, true); + members_section->add_margin_child(TTR("Members:"), members, true); + members->set_custom_minimum_size(Size2(0, 50 * EDSCALE)); members->set_hide_root(true); members->connect("button_pressed", this, "_member_button"); members->connect("item_edited", this, "_member_edited"); members->connect("cell_selected", this, "_member_selected", varray(), CONNECT_DEFERRED); members->connect("gui_input", this, "_members_gui_input"); + members->connect("item_rmb_selected", this, "_member_rmb_selected"); + members->set_allow_rmb_select(true); members->set_allow_reselect(true); members->set_hide_folding(true); members->set_drag_forwarding(this); - VBoxContainer *left_vb2 = memnew(VBoxContainer); - left_vsplit->add_child(left_vb2); - left_vb2->set_v_size_flags(SIZE_EXPAND_FILL); - - VBoxContainer *vbc_nodes = memnew(VBoxContainer); - HBoxContainer *hbc_nodes = memnew(HBoxContainer); - node_filter = memnew(LineEdit); - node_filter->connect("text_changed", this, "_node_filter_changed"); - hbc_nodes->add_child(node_filter); - node_filter->set_h_size_flags(SIZE_EXPAND_FILL); - vbc_nodes->add_child(hbc_nodes); - - nodes = memnew(Tree); - vbc_nodes->add_child(nodes); - nodes->set_v_size_flags(SIZE_EXPAND_FILL); + member_popup = memnew(PopupMenu); + add_child(member_popup); + member_popup->connect("id_pressed", this, "_member_option"); - left_vb2->add_margin_child(TTR("Available Nodes:"), vbc_nodes, true); + function_name_edit = memnew(PopupDialog); + function_name_box = memnew(LineEdit); + function_name_edit->add_child(function_name_box); + function_name_edit->set_h_size_flags(SIZE_EXPAND); + function_name_box->connect("gui_input", this, "_fn_name_box_input"); + function_name_box->set_expand_to_text_length(true); + add_child(function_name_edit); - nodes->set_hide_root(true); - nodes->connect("item_activated", this, "_available_node_doubleclicked"); - nodes->set_drag_forwarding(this); + /// Actual Graph /// graph = memnew(GraphEdit); add_child(graph); @@ -3559,12 +4747,79 @@ VisualScriptEditor::VisualScriptEditor() { graph->connect("_end_node_move", this, "_end_node_move"); graph->connect("delete_nodes_request", this, "_on_nodes_delete"); graph->connect("duplicate_nodes_request", this, "_on_nodes_duplicate"); + graph->connect("gui_input", this, "_graph_gui_input"); graph->set_drag_forwarding(this); graph->hide(); graph->connect("scroll_offset_changed", this, "_graph_ofs_changed"); + /// Add Buttons to Top Bar/Zoom bar. + HBoxContainer *graph_hbc = graph->get_zoom_hbox(); + + Label *base_lbl = memnew(Label); + base_lbl->set_text("Change Base Type: "); + graph_hbc->add_child(base_lbl); + + base_type_select = memnew(Button); + base_type_select->connect("pressed", this, "_change_base_type"); + graph_hbc->add_child(base_type_select); + + Button *add_nds = memnew(Button); + add_nds->set_text("Add Nodes..."); + graph_hbc->add_child(add_nds); + add_nds->connect("pressed", this, "_add_node_dialog"); + + Button *fn_btn = memnew(Button); + fn_btn->set_text("Add Function..."); + graph_hbc->add_child(fn_btn); + fn_btn->connect("pressed", this, "_create_function_dialog"); + + // Add Function Dialog. + VBoxContainer *function_vb = memnew(VBoxContainer); + function_vb->set_v_size_flags(SIZE_EXPAND_FILL); + + HBoxContainer *func_name_hbox = memnew(HBoxContainer); + function_vb->add_child(func_name_hbox); + + Label *func_name_label = memnew(Label); + func_name_label->set_text(TTR("Name:")); + func_name_hbox->add_child(func_name_label); + + func_name_box = memnew(LineEdit); + func_name_box->set_h_size_flags(SIZE_EXPAND_FILL); + func_name_box->set_placeholder(TTR("function_name")); + func_name_box->set_text(""); + func_name_box->connect("focus_entered", this, "_deselect_input_names"); + func_name_hbox->add_child(func_name_box); + + // Add minor setting for function if needed, here! + + function_vb->add_child(memnew(HSeparator)); + + Button *add_input_button = memnew(Button); + add_input_button->set_h_size_flags(SIZE_EXPAND_FILL); + add_input_button->set_text(TTR("Add Input")); + add_input_button->connect("pressed", this, "_add_func_input"); + function_vb->add_child(add_input_button); + + func_input_scroll = memnew(ScrollContainer); + func_input_scroll->set_v_size_flags(SIZE_EXPAND_FILL); + function_vb->add_child(func_input_scroll); + + func_input_vbox = memnew(VBoxContainer); + func_input_vbox->set_h_size_flags(SIZE_EXPAND_FILL); + func_input_scroll->add_child(func_input_vbox); + + function_create_dialog = memnew(ConfirmationDialog); + function_create_dialog->set_custom_minimum_size(Size2(450, 300) * EDSCALE); + function_create_dialog->set_v_size_flags(SIZE_EXPAND_FILL); + function_create_dialog->set_title(TTR("Create Function")); + function_create_dialog->add_child(function_vb); + function_create_dialog->get_ok()->set_text(TTR("Create")); + function_create_dialog->get_ok()->connect("pressed", this, "_create_function"); + add_child(function_create_dialog); + select_func_text = memnew(Label); - select_func_text->set_text(TTR("Select or create a function to edit graph")); + select_func_text->set_text(TTR("Select or create a function to edit its graph.")); select_func_text->set_align(Label::ALIGN_CENTER); select_func_text->set_valign(Label::VALIGN_CENTER); select_func_text->set_h_size_flags(SIZE_EXPAND_FILL); @@ -3583,7 +4838,7 @@ VisualScriptEditor::VisualScriptEditor() { hint_text_timer->connect("timeout", this, "_hide_timer"); add_child(hint_text_timer); - //allowed casts (connections) + // Allowed casts (connections). for (int i = 0; i < Variant::VARIANT_MAX; i++) { graph->add_valid_connection_type(Variant::NIL, i); graph->add_valid_connection_type(i, Variant::NIL); @@ -3605,7 +4860,6 @@ VisualScriptEditor::VisualScriptEditor() { edit_signal_dialog = memnew(AcceptDialog); edit_signal_dialog->get_ok()->set_text(TTR("Close")); add_child(edit_signal_dialog); - edit_signal_dialog->set_title(TTR("Edit Signal Arguments:")); signal_editor = memnew(VisualScriptEditorSignalEdit); edit_signal_edit = memnew(EditorInspector); @@ -3616,7 +4870,6 @@ VisualScriptEditor::VisualScriptEditor() { edit_variable_dialog = memnew(AcceptDialog); edit_variable_dialog->get_ok()->set_text(TTR("Close")); add_child(edit_variable_dialog); - edit_variable_dialog->set_title(TTR("Edit Variable:")); variable_editor = memnew(VisualScriptEditorVariableEdit); edit_variable_edit = memnew(EditorInspector); @@ -3625,17 +4878,16 @@ VisualScriptEditor::VisualScriptEditor() { edit_variable_edit->edit(variable_editor); select_base_type = memnew(CreateDialog); - select_base_type->set_base_type("Object"); //anything goes + select_base_type->set_base_type("Object"); // Anything goes. select_base_type->connect("create", this, "_change_base_type_callback"); - select_base_type->get_ok()->set_text(TTR("Change")); add_child(select_base_type); undo_redo = EditorNode::get_singleton()->get_undo_redo(); updating_members = false; - set_process_input(true); //for revert on drag - set_process_unhandled_input(true); //for revert on drag + set_process_input(true); + set_process_unhandled_input(true); default_value_edit = memnew(CustomPropertyEditor); add_child(default_value_edit); @@ -3648,26 +4900,18 @@ VisualScriptEditor::VisualScriptEditor() { new_connect_node_select = memnew(VisualScriptPropertySelector); add_child(new_connect_node_select); + new_connect_node_select->set_resizable(true); new_connect_node_select->connect("selected", this, "_selected_connect_node"); new_connect_node_select->get_cancel()->connect("pressed", this, "_cancel_connect_node"); new_virtual_method_select = memnew(VisualScriptPropertySelector); add_child(new_virtual_method_select); new_virtual_method_select->connect("selected", this, "_selected_new_virtual_method"); - new_virtual_method_select->get_cancel(); - - member_popup = memnew(PopupMenu); - add_child(member_popup); - members->connect("item_rmb_selected", this, "_member_rmb_selected"); - members->set_allow_rmb_select(true); - member_popup->connect("id_pressed", this, "_member_option"); - - _VisualScriptEditor::get_singleton()->connect("custom_nodes_updated", this, "_update_available_nodes"); } VisualScriptEditor::~VisualScriptEditor() { - undo_redo->clear_history(); //avoid crashes + undo_redo->clear_history(); // Avoid crashes. memdelete(signal_editor); memdelete(variable_editor); } @@ -3698,12 +4942,14 @@ static void register_editor_callback() { ED_SHORTCUT("visual_script_editor/copy_nodes", TTR("Copy Nodes"), KEY_MASK_CMD + KEY_C); ED_SHORTCUT("visual_script_editor/cut_nodes", TTR("Cut Nodes"), KEY_MASK_CMD + KEY_X); ED_SHORTCUT("visual_script_editor/paste_nodes", TTR("Paste Nodes"), KEY_MASK_CMD + KEY_V); + ED_SHORTCUT("visual_script_editor/create_function", TTR("Make Function"), KEY_MASK_CMD + KEY_G); + ED_SHORTCUT("visual_script_editor/refresh_nodes", TTR("Refresh Graph"), KEY_MASK_CMD + KEY_R); ED_SHORTCUT("visual_script_editor/edit_member", TTR("Edit Member"), KEY_MASK_CMD + KEY_E); } void VisualScriptEditor::register_editor() { - //too early to register stuff here, request a callback + // Too early to register stuff here, request a callback. EditorNode::add_plugin_init_callback(register_editor_callback); } @@ -3745,4 +4991,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 f4b4a6981d..fbf021e7b6 100644 --- a/modules/visual_script/visual_script_editor.h +++ b/modules/visual_script/visual_script_editor.h @@ -44,7 +44,7 @@ class VisualScriptEditorVariableEdit; #ifdef TOOLS_ENABLED class VisualScriptEditor : public ScriptEditorBase { - GDCLASS(VisualScriptEditor, ScriptEditorBase) + GDCLASS(VisualScriptEditor, ScriptEditorBase); enum { TYPE_SEQUENCE = 1000, @@ -59,6 +59,8 @@ class VisualScriptEditor : public ScriptEditorBase { EDIT_COPY_NODES, EDIT_CUT_NODES, EDIT_PASTE_NODES, + EDIT_CREATE_FUNCTION, + REFRESH_GRAPH }; enum PortAction { @@ -79,17 +81,19 @@ class VisualScriptEditor : public ScriptEditorBase { MEMBER_SIGNAL }; - VSplitContainer *left_vsplit; + VBoxContainer *members_section; MenuButton *edit_menu; Ref<VisualScript> script; Button *base_type_select; - GraphEdit *graph; + LineEdit *func_name_box; + ScrollContainer *func_input_scroll; + VBoxContainer *func_input_vbox; + ConfirmationDialog *function_create_dialog; - LineEdit *node_filter; - TextureRect *node_filter_icon; + GraphEdit *graph; VisualScriptEditorSignalEdit *signal_editor; @@ -110,7 +114,8 @@ class VisualScriptEditor : public ScriptEditorBase { UndoRedo *undo_redo; Tree *members; - Tree *nodes; + PopupDialog *function_name_edit; + LineEdit *function_name_box; Label *hint_text; Timer *hint_text_timer; @@ -133,6 +138,7 @@ class VisualScriptEditor : public ScriptEditorBase { HashMap<StringName, Ref<StyleBox> > node_styles; StringName edited_func; + StringName default_func; void _update_graph_connections(); void _update_graph(int p_only_id = -1); @@ -165,9 +171,13 @@ class VisualScriptEditor : public ScriptEditorBase { int port_action_output; Vector2 port_action_pos; int port_action_new_node; - void _port_action_menu(int p_option); - void new_node(Ref<VisualScriptNode> vnode, Vector2 ofs); + bool saved_pos_dirty; + Vector2 saved_position; + + Vector2 mouse_up_position; + + void _port_action_menu(int p_option, const StringName &p_func); void connect_data(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode, int new_id); @@ -175,23 +185,26 @@ class VisualScriptEditor : public ScriptEditorBase { void connect_seq(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode_new, int new_id); void _cancel_connect_node(); - void _create_new_node(const String &p_text, const String &p_category, const Vector2 &p_point); + int _create_new_node_from_name(const String &p_text, const Vector2 &p_point, const StringName &p_func = StringName()); void _selected_new_virtual_method(const String &p_text, const String &p_category, const bool p_connecting); int error_line; void _node_selected(Node *p_node); - void _center_on_node(int p_id); + void _center_on_node(const StringName &p_func, int p_id); void _node_filter_changed(const String &p_text); void _change_base_type_callback(); void _change_base_type(); + void _toggle_tool_script(); void _member_selected(); void _member_edited(); void _begin_node_move(); void _end_node_move(); - void _move_node(String func, int p_id, const Vector2 &p_to); + void _move_node(const StringName &p_func, int p_id, const Vector2 &p_to); + + void _get_ends(int p_node, const List<VisualScript::SequenceConnection> &p_seqs, const Set<int> &p_selected, Set<int> &r_end_nodes); void _node_moved(Vector2 p_from, Vector2 p_to, int p_id); void _remove_node(int p_id); @@ -200,21 +213,44 @@ class VisualScriptEditor : public ScriptEditorBase { void _graph_connect_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_pos); void _node_ports_changed(const String &p_func, int p_id); - void _available_node_doubleclicked(); + void _node_create(); void _update_available_nodes(); void _member_button(Object *p_item, int p_column, int p_button); void _expression_text_changed(const String &p_text, int p_id); + void _add_input_port(int p_id); + void _add_output_port(int p_id); + void _remove_input_port(int p_id, int p_port); + void _remove_output_port(int p_id, int p_port); + void _change_port_type(int p_select, int p_id, int p_port, bool is_input); + void _update_node_size(int p_id); + void _port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input); - String revert_on_drag; + Vector2 _get_available_pos(bool centered = true, Vector2 ofs = Vector2()) const; + StringName _get_function_of_node(int p_id) const; - void _input(const Ref<InputEvent> &p_event); + void _move_nodes_with_rescan(const StringName &p_func_from, const StringName &p_func_to, int p_id); + bool node_has_sequence_connections(const StringName &p_func, int p_id); - void _generic_search(); + void _generic_search(String p_base_type = "", Vector2 pos = Vector2(), bool node_centered = false); + void _input(const Ref<InputEvent> &p_event); + void _graph_gui_input(const Ref<InputEvent> &p_event); void _members_gui_input(const Ref<InputEvent> &p_event); + void _fn_name_box_input(const Ref<InputEvent> &p_event); + void _rename_function(const String &p_name, const String &p_new_name); + + void _create_function_dialog(); + void _create_function(); + void _add_func_input(); + void _remove_func_input(Node *p_node); + void _deselect_input_names(); + void _add_node_dialog(); + void _node_item_selected(); + void _node_item_unselected(); + void _on_nodes_delete(); void _on_nodes_duplicate(); @@ -225,6 +261,10 @@ class VisualScriptEditor : public ScriptEditorBase { int editing_id; int editing_input; + bool can_swap; + int data_disconnect_node; + int data_disconnect_port; + void _default_value_changed(); void _default_value_edited(Node *p_button, int p_id, int p_input_port); @@ -239,7 +279,7 @@ class VisualScriptEditor : public ScriptEditorBase { void _draw_color_over_button(Object *obj, Color p_color); void _button_resource_previewed(const String &p_path, const Ref<Texture> &p_preview, const Ref<Texture> &p_small_preview, Variant p_ud); - VisualScriptNode::TypeGuess _guess_output_type(int p_port_action_node, int p_port_action_output, Set<int> &visited_nodes); + VisualScriptNode::TypeGuess _guess_output_type(int p_port_action_node, int p_port_action_output, Set<int> &p_visited_nodes); void _member_rmb_selected(const Vector2 &p_pos); void _member_option(int p_option); @@ -263,7 +303,10 @@ public: virtual Variant get_edit_state(); virtual void set_edit_state(const Variant &p_state); virtual void goto_line(int p_line, bool p_with_error = false); + 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(); @@ -278,6 +321,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/visual_script/visual_script_expression.cpp b/modules/visual_script/visual_script_expression.cpp index a76e4bc36f..4b74c088e0 100644 --- a/modules/visual_script/visual_script_expression.cpp +++ b/modules/visual_script/visual_script_expression.cpp @@ -1032,7 +1032,8 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() { case TK_OP_BIT_OR: op = Variant::OP_BIT_OR; break; case TK_OP_BIT_XOR: op = Variant::OP_BIT_XOR; break; case TK_OP_BIT_INVERT: op = Variant::OP_BIT_NEGATE; break; - default: {}; + default: { + }; } if (op == Variant::OP_MAX) { //stop appending stuff @@ -1129,7 +1130,7 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() { if (next_op == -1) { _set_error("Yet another parser bug...."); - ERR_FAIL_COND_V(next_op == -1, NULL); + ERR_FAIL_V(NULL); } // OK! create operator.. diff --git a/modules/visual_script/visual_script_expression.h b/modules/visual_script/visual_script_expression.h index 3b2e3b9f78..3a045d2cf7 100644 --- a/modules/visual_script/visual_script_expression.h +++ b/modules/visual_script/visual_script_expression.h @@ -36,7 +36,7 @@ class VisualScriptExpression : public VisualScriptNode { - GDCLASS(VisualScriptExpression, VisualScriptNode) + GDCLASS(VisualScriptExpression, VisualScriptNode); friend class VisualScriptNodeInstanceExpression; struct Input { diff --git a/modules/visual_script/visual_script_flow_control.h b/modules/visual_script/visual_script_flow_control.h index a42605a50e..d3c7aa68e3 100644 --- a/modules/visual_script/visual_script_flow_control.h +++ b/modules/visual_script/visual_script_flow_control.h @@ -35,7 +35,7 @@ class VisualScriptReturn : public VisualScriptNode { - GDCLASS(VisualScriptReturn, VisualScriptNode) + GDCLASS(VisualScriptReturn, VisualScriptNode); Variant::Type type; bool with_value; @@ -72,7 +72,7 @@ public: class VisualScriptCondition : public VisualScriptNode { - GDCLASS(VisualScriptCondition, VisualScriptNode) + GDCLASS(VisualScriptCondition, VisualScriptNode); protected: static void _bind_methods(); @@ -100,7 +100,7 @@ public: class VisualScriptWhile : public VisualScriptNode { - GDCLASS(VisualScriptWhile, VisualScriptNode) + GDCLASS(VisualScriptWhile, VisualScriptNode); protected: static void _bind_methods(); @@ -128,7 +128,7 @@ public: class VisualScriptIterator : public VisualScriptNode { - GDCLASS(VisualScriptIterator, VisualScriptNode) + GDCLASS(VisualScriptIterator, VisualScriptNode); protected: static void _bind_methods(); @@ -156,7 +156,7 @@ public: class VisualScriptSequence : public VisualScriptNode { - GDCLASS(VisualScriptSequence, VisualScriptNode) + GDCLASS(VisualScriptSequence, VisualScriptNode); int steps; @@ -189,7 +189,7 @@ public: class VisualScriptSwitch : public VisualScriptNode { - GDCLASS(VisualScriptSwitch, VisualScriptNode) + GDCLASS(VisualScriptSwitch, VisualScriptNode); struct Case { Variant::Type type; @@ -231,7 +231,7 @@ public: class VisualScriptTypeCast : public VisualScriptNode { - GDCLASS(VisualScriptTypeCast, VisualScriptNode) + GDCLASS(VisualScriptTypeCast, VisualScriptNode); StringName base_type; String script; diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp index bb0435a679..4e90a08009 100644 --- a/modules/visual_script/visual_script_func_nodes.cpp +++ b/modules/visual_script/visual_script_func_nodes.cpp @@ -51,10 +51,7 @@ int VisualScriptFunctionCall::get_output_sequence_port_count() const { bool VisualScriptFunctionCall::has_input_sequence_port() const { - if ((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_method_const(basic_type, function))) - return false; - else - return true; + return !((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_method_const(basic_type, function))); } #ifdef TOOLS_ENABLED @@ -136,10 +133,12 @@ int VisualScriptFunctionCall::get_input_value_port_count() const { MethodBind *mb = ClassDB::get_method(_get_base_type(), function); if (mb) { - return mb->get_argument_count() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - use_default_args; + int defaulted_args = mb->get_argument_count() < use_default_args ? mb->get_argument_count() : use_default_args; + return mb->get_argument_count() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - defaulted_args; } - return method_cache.arguments.size() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - use_default_args; + int defaulted_args = method_cache.arguments.size() < use_default_args ? method_cache.arguments.size() : use_default_args; + return method_cache.arguments.size() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - defaulted_args; } } int VisualScriptFunctionCall::get_output_value_port_count() const { @@ -573,7 +572,6 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const Node *bnode = _get_base_node(); if (bnode) { property.hint_string = bnode->get_path(); //convert to loong string - } else { } } } @@ -949,7 +947,7 @@ int VisualScriptPropertySet::get_output_sequence_port_count() const { bool VisualScriptPropertySet::has_input_sequence_port() const { - return call_mode != CALL_MODE_BASIC_TYPE ? true : false; + return call_mode != CALL_MODE_BASIC_TYPE; } Node *VisualScriptPropertySet::_get_base_node() const { @@ -1030,7 +1028,6 @@ void VisualScriptPropertySet::_adjust_input_index(PropertyInfo &pinfo) const { } PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const { - if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) { if (p_idx == 0) { PropertyInfo pi; @@ -1038,8 +1035,16 @@ PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower()); _adjust_input_index(pi); return pi; - } else { - p_idx--; + } + } + + List<PropertyInfo> props; + ClassDB::get_property_list(_get_base_type(), &props, false); + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + if (E->get().name == property) { + PropertyInfo pinfo = PropertyInfo(E->get().type, "value", PROPERTY_HINT_TYPE_STRING, E->get().hint_string); + _adjust_input_index(pinfo); + return pinfo; } } @@ -1355,7 +1360,6 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const { Node *bnode = _get_base_node(); if (bnode) { property.hint_string = bnode->get_path(); //convert to loong string - } else { } } } @@ -1562,7 +1566,8 @@ public: case VisualScriptPropertySet::ASSIGN_OP_BIT_XOR: { value = Variant::evaluate(Variant::OP_BIT_XOR, value, p_argument); } break; - default: {} + default: { + } } if (index != StringName()) { @@ -1796,22 +1801,18 @@ PropertyInfo VisualScriptPropertyGet::get_input_value_port_info(int p_idx) const pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type); pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower()); return pi; - } else { - p_idx--; } } return PropertyInfo(); } PropertyInfo VisualScriptPropertyGet::get_output_value_port_info(int p_idx) const { - - if (index != StringName()) { - - Variant v; - Variant::CallError ce; - v = Variant::construct(type_cache, NULL, 0, ce); - Variant i = v.get(index); - return PropertyInfo(i.get_type(), "value." + String(index)); + List<PropertyInfo> props; + ClassDB::get_property_list(_get_base_type(), &props, false); + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + if (E->get().name == property) { + return PropertyInfo(E->get().type, "value." + String(index)); + } } return PropertyInfo(type_cache, "value"); @@ -2075,7 +2076,6 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const { Node *bnode = _get_base_node(); if (bnode) { property.hint_string = bnode->get_path(); //convert to loong string - } else { } } } diff --git a/modules/visual_script/visual_script_func_nodes.h b/modules/visual_script/visual_script_func_nodes.h index 7b1e7871b6..11eb96293b 100644 --- a/modules/visual_script/visual_script_func_nodes.h +++ b/modules/visual_script/visual_script_func_nodes.h @@ -35,7 +35,8 @@ class VisualScriptFunctionCall : public VisualScriptNode { - GDCLASS(VisualScriptFunctionCall, VisualScriptNode) + GDCLASS(VisualScriptFunctionCall, VisualScriptNode); + public: enum CallMode { CALL_MODE_SELF, @@ -137,7 +138,8 @@ VARIANT_ENUM_CAST(VisualScriptFunctionCall::RPCCallMode); class VisualScriptPropertySet : public VisualScriptNode { - GDCLASS(VisualScriptPropertySet, VisualScriptNode) + GDCLASS(VisualScriptPropertySet, VisualScriptNode); + public: enum CallMode { CALL_MODE_SELF, @@ -242,7 +244,8 @@ VARIANT_ENUM_CAST(VisualScriptPropertySet::AssignOp); class VisualScriptPropertyGet : public VisualScriptNode { - GDCLASS(VisualScriptPropertyGet, VisualScriptNode) + GDCLASS(VisualScriptPropertyGet, VisualScriptNode); + public: enum CallMode { CALL_MODE_SELF, @@ -323,7 +326,7 @@ VARIANT_ENUM_CAST(VisualScriptPropertyGet::CallMode); class VisualScriptEmitSignal : public VisualScriptNode { - GDCLASS(VisualScriptEmitSignal, VisualScriptNode) + GDCLASS(VisualScriptEmitSignal, VisualScriptNode); private: StringName name; diff --git a/modules/visual_script/visual_script_nodes.cpp b/modules/visual_script/visual_script_nodes.cpp index 1b0e41b2de..2a8d67d403 100644 --- a/modules/visual_script/visual_script_nodes.cpp +++ b/modules/visual_script/visual_script_nodes.cpp @@ -197,7 +197,6 @@ String VisualScriptFunction::get_output_sequence_port_text(int p_port) const { PropertyInfo VisualScriptFunction::get_input_value_port_info(int p_idx) const { ERR_FAIL_V(PropertyInfo()); - return PropertyInfo(); } PropertyInfo VisualScriptFunction::get_output_value_port_info(int p_idx) const { @@ -357,6 +356,441 @@ int VisualScriptFunction::get_stack_size() const { } ////////////////////////////////////////// +/////////////////LISTS//////////////////// +////////////////////////////////////////// + +int VisualScriptLists::get_output_sequence_port_count() const { + if (sequenced) + return 1; + return 0; +} +bool VisualScriptLists::has_input_sequence_port() const { + return sequenced; +} + +String VisualScriptLists::get_output_sequence_port_text(int p_port) const { + return ""; +} + +int VisualScriptLists::get_input_value_port_count() const { + return inputports.size(); +} +int VisualScriptLists::get_output_value_port_count() const { + return outputports.size(); +} + +PropertyInfo VisualScriptLists::get_input_value_port_info(int p_idx) const { + ERR_FAIL_INDEX_V(p_idx, inputports.size(), PropertyInfo()); + + PropertyInfo pi; + pi.name = inputports[p_idx].name; + pi.type = inputports[p_idx].type; + return pi; +} +PropertyInfo VisualScriptLists::get_output_value_port_info(int p_idx) const { + ERR_FAIL_INDEX_V(p_idx, outputports.size(), PropertyInfo()); + + PropertyInfo pi; + pi.name = outputports[p_idx].name; + pi.type = outputports[p_idx].type; + return pi; +} + +bool VisualScriptLists::is_input_port_editable() const { + return ((flags & INPUT_EDITABLE) == INPUT_EDITABLE); +} +bool VisualScriptLists::is_input_port_name_editable() const { + return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE); +} +bool VisualScriptLists::is_input_port_type_editable() const { + return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE); +} + +bool VisualScriptLists::is_output_port_editable() const { + return ((flags & OUTPUT_EDITABLE) == OUTPUT_EDITABLE); +} +bool VisualScriptLists::is_output_port_name_editable() const { + return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE); +} +bool VisualScriptLists::is_output_port_type_editable() const { + return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE); +} + +// for the inspector +bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) { + + if (p_name == "input_count" && is_input_port_editable()) { + + int new_argc = p_value; + int argc = inputports.size(); + if (argc == new_argc) + return true; + + inputports.resize(new_argc); + + for (int i = argc; i < new_argc; i++) { + inputports.write[i].name = "arg" + itos(i + 1); + inputports.write[i].type = Variant::NIL; + } + ports_changed_notify(); + _change_notify(); + return true; + } + if (String(p_name).begins_with("input_") && is_input_port_editable()) { + int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1; + ERR_FAIL_INDEX_V(idx, inputports.size(), false); + String what = String(p_name).get_slice("/", 1); + if (what == "type") { + + Variant::Type new_type = Variant::Type(int(p_value)); + inputports.write[idx].type = new_type; + ports_changed_notify(); + + return true; + } + + if (what == "name") { + + inputports.write[idx].name = p_value; + ports_changed_notify(); + return true; + } + } + + if (p_name == "output_count" && is_output_port_editable()) { + + int new_argc = p_value; + int argc = outputports.size(); + if (argc == new_argc) + return true; + + outputports.resize(new_argc); + + for (int i = argc; i < new_argc; i++) { + outputports.write[i].name = "arg" + itos(i + 1); + outputports.write[i].type = Variant::NIL; + } + ports_changed_notify(); + _change_notify(); + return true; + } + if (String(p_name).begins_with("output_") && is_output_port_editable()) { + int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1; + ERR_FAIL_INDEX_V(idx, outputports.size(), false); + String what = String(p_name).get_slice("/", 1); + if (what == "type") { + + Variant::Type new_type = Variant::Type(int(p_value)); + outputports.write[idx].type = new_type; + ports_changed_notify(); + + return true; + } + + if (what == "name") { + + outputports.write[idx].name = p_value; + ports_changed_notify(); + return true; + } + } + + if (p_name == "sequenced/sequenced") { + sequenced = p_value; + ports_changed_notify(); + return true; + } + + return false; +} +bool VisualScriptLists::_get(const StringName &p_name, Variant &r_ret) const { + + if (p_name == "input_count" && is_input_port_editable()) { + r_ret = inputports.size(); + return true; + } + if (String(p_name).begins_with("input_") && is_input_port_editable()) { + int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1; + ERR_FAIL_INDEX_V(idx, inputports.size(), false); + String what = String(p_name).get_slice("/", 1); + if (what == "type") { + r_ret = inputports[idx].type; + return true; + } + if (what == "name") { + r_ret = inputports[idx].name; + return true; + } + } + + if (p_name == "output_count" && is_output_port_editable()) { + r_ret = outputports.size(); + return true; + } + if (String(p_name).begins_with("output_") && is_output_port_editable()) { + int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int() - 1; + ERR_FAIL_INDEX_V(idx, outputports.size(), false); + String what = String(p_name).get_slice("/", 1); + if (what == "type") { + r_ret = outputports[idx].type; + return true; + } + if (what == "name") { + r_ret = outputports[idx].name; + return true; + } + } + + if (p_name == "sequenced/sequenced") { + r_ret = sequenced; + return true; + } + + return false; +} +void VisualScriptLists::_get_property_list(List<PropertyInfo> *p_list) const { + + if (is_input_port_editable()) { + p_list->push_back(PropertyInfo(Variant::INT, "input_count", PROPERTY_HINT_RANGE, "0,256")); + String argt = "Any"; + for (int i = 1; i < Variant::VARIANT_MAX; i++) { + argt += "," + Variant::get_type_name(Variant::Type(i)); + } + + for (int i = 0; i < inputports.size(); i++) { + p_list->push_back(PropertyInfo(Variant::INT, "input_" + itos(i + 1) + "/type", PROPERTY_HINT_ENUM, argt)); + p_list->push_back(PropertyInfo(Variant::STRING, "input_" + itos(i + 1) + "/name")); + } + } + + if (is_output_port_editable()) { + p_list->push_back(PropertyInfo(Variant::INT, "output_count", PROPERTY_HINT_RANGE, "0,256")); + String argt = "Any"; + for (int i = 1; i < Variant::VARIANT_MAX; i++) { + argt += "," + Variant::get_type_name(Variant::Type(i)); + } + + for (int i = 0; i < outputports.size(); i++) { + p_list->push_back(PropertyInfo(Variant::INT, "output_" + itos(i + 1) + "/type", PROPERTY_HINT_ENUM, argt)); + p_list->push_back(PropertyInfo(Variant::STRING, "output_" + itos(i + 1) + "/name")); + } + } + p_list->push_back(PropertyInfo(Variant::BOOL, "sequenced/sequenced")); +} + +// input data port interaction +void VisualScriptLists::add_input_data_port(Variant::Type p_type, const String &p_name, int p_index) { + + if (!is_input_port_editable()) + return; + + Port inp; + inp.name = p_name; + inp.type = p_type; + if (p_index >= 0) + inputports.insert(p_index, inp); + else + inputports.push_back(inp); + + ports_changed_notify(); + _change_notify(); +} +void VisualScriptLists::set_input_data_port_type(int p_idx, Variant::Type p_type) { + + if (!is_input_port_type_editable()) + return; + + ERR_FAIL_INDEX(p_idx, inputports.size()); + + inputports.write[p_idx].type = p_type; + ports_changed_notify(); + _change_notify(); +} +void VisualScriptLists::set_input_data_port_name(int p_idx, const String &p_name) { + + if (!is_input_port_name_editable()) + return; + + ERR_FAIL_INDEX(p_idx, inputports.size()); + + inputports.write[p_idx].name = p_name; + ports_changed_notify(); + _change_notify(); +} +void VisualScriptLists::remove_input_data_port(int p_argidx) { + + if (!is_input_port_editable()) + return; + + ERR_FAIL_INDEX(p_argidx, inputports.size()); + + inputports.remove(p_argidx); + + ports_changed_notify(); + _change_notify(); +} + +// output data port interaction +void VisualScriptLists::add_output_data_port(Variant::Type p_type, const String &p_name, int p_index) { + + if (!is_output_port_editable()) + return; + + Port out; + out.name = p_name; + out.type = p_type; + if (p_index >= 0) + outputports.insert(p_index, out); + else + outputports.push_back(out); + + ports_changed_notify(); + _change_notify(); +} +void VisualScriptLists::set_output_data_port_type(int p_idx, Variant::Type p_type) { + + if (!is_output_port_type_editable()) + return; + + ERR_FAIL_INDEX(p_idx, outputports.size()); + + outputports.write[p_idx].type = p_type; + ports_changed_notify(); + _change_notify(); +} +void VisualScriptLists::set_output_data_port_name(int p_idx, const String &p_name) { + + if (!is_output_port_name_editable()) + return; + + ERR_FAIL_INDEX(p_idx, outputports.size()); + + outputports.write[p_idx].name = p_name; + ports_changed_notify(); + _change_notify(); +} +void VisualScriptLists::remove_output_data_port(int p_argidx) { + + if (!is_output_port_editable()) + return; + + ERR_FAIL_INDEX(p_argidx, outputports.size()); + + outputports.remove(p_argidx); + + ports_changed_notify(); + _change_notify(); +} + +// sequences +void VisualScriptLists::set_sequenced(bool p_enable) { + if (sequenced == p_enable) + return; + sequenced = p_enable; + ports_changed_notify(); +} +bool VisualScriptLists::is_sequenced() const { + return sequenced; +} + +VisualScriptLists::VisualScriptLists() { + // initialize + sequenced = false; + flags = 0; +} + +void VisualScriptLists::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_input_data_port", "type", "name", "index"), &VisualScriptLists::add_input_data_port); + ClassDB::bind_method(D_METHOD("set_input_data_port_name", "index", "name"), &VisualScriptLists::set_input_data_port_name); + ClassDB::bind_method(D_METHOD("set_input_data_port_type", "index", "type"), &VisualScriptLists::set_input_data_port_type); + ClassDB::bind_method(D_METHOD("remove_input_data_port", "index"), &VisualScriptLists::remove_input_data_port); + + ClassDB::bind_method(D_METHOD("add_output_data_port", "type", "name", "index"), &VisualScriptLists::add_output_data_port); + ClassDB::bind_method(D_METHOD("set_output_data_port_name", "index", "name"), &VisualScriptLists::set_output_data_port_name); + ClassDB::bind_method(D_METHOD("set_output_data_port_type", "index", "type"), &VisualScriptLists::set_output_data_port_type); + ClassDB::bind_method(D_METHOD("remove_output_data_port", "index"), &VisualScriptLists::remove_output_data_port); +} + +////////////////////////////////////////// +//////////////COMPOSEARRAY//////////////// +////////////////////////////////////////// + +int VisualScriptComposeArray::get_output_sequence_port_count() const { + if (sequenced) + return 1; + return 0; +} +bool VisualScriptComposeArray::has_input_sequence_port() const { + return sequenced; +} + +String VisualScriptComposeArray::get_output_sequence_port_text(int p_port) const { + return ""; +} + +int VisualScriptComposeArray::get_input_value_port_count() const { + return inputports.size(); +} +int VisualScriptComposeArray::get_output_value_port_count() const { + return 1; +} + +PropertyInfo VisualScriptComposeArray::get_input_value_port_info(int p_idx) const { + ERR_FAIL_INDEX_V(p_idx, inputports.size(), PropertyInfo()); + + PropertyInfo pi; + pi.name = inputports[p_idx].name; + pi.type = inputports[p_idx].type; + return pi; +} +PropertyInfo VisualScriptComposeArray::get_output_value_port_info(int p_idx) const { + PropertyInfo pi; + pi.name = "out"; + pi.type = Variant::ARRAY; + return pi; +} + +String VisualScriptComposeArray::get_caption() const { + return "Compose Array"; +} +String VisualScriptComposeArray::get_text() const { + return ""; +} + +class VisualScriptComposeArrayNode : public VisualScriptNodeInstance { +public: + int input_count = 0; + virtual int get_working_memory_size() const { return 0; } + + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) { + + if (input_count > 0) { + Array arr; + for (int i = 0; i < input_count; i++) + arr.push_back((*p_inputs[i])); + Variant va = Variant(arr); + + *p_outputs[0] = va; + } + + return 0; + } +}; + +VisualScriptNodeInstance *VisualScriptComposeArray::instance(VisualScriptInstance *p_instance) { + + VisualScriptComposeArrayNode *instance = memnew(VisualScriptComposeArrayNode); + instance->input_count = inputports.size(); + return instance; +} + +VisualScriptComposeArray::VisualScriptComposeArray() { + // initialize stuff here + sequenced = false; + flags = INPUT_EDITABLE; +} + +////////////////////////////////////////// ////////////////OPERATOR////////////////// ////////////////////////////////////////// @@ -418,7 +852,7 @@ PropertyInfo VisualScriptOperator::get_input_value_port_info(int p_idx) const { { Variant::NIL, Variant::NIL } //OP_IN, }; - ERR_FAIL_INDEX_V(p_idx, Variant::OP_MAX, PropertyInfo()); + ERR_FAIL_INDEX_V(p_idx, 2, PropertyInfo()); PropertyInfo pinfo; pinfo.name = p_idx == 0 ? "A" : "B"; @@ -515,7 +949,7 @@ String VisualScriptOperator::get_caption() const { //mathematic L"A + B", //OP_ADD, L"A - B", //OP_SUBTRACT, - L"A x B", //OP_MULTIPLY, + L"A \u00D7 B", //OP_MULTIPLY, L"A \u00F7 B", //OP_DIVIDE, L"\u00AC A", //OP_NEGATE, L"+ A", //OP_POSITIVE, @@ -856,7 +1290,7 @@ public: if (!instance->get_variable(variable, p_outputs[0])) { r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR("VariableGet not found in script: ") + "'" + String(variable) + "'"; - return false; + return 0; } return 0; } @@ -2531,7 +2965,7 @@ String VisualScriptCustomNode::get_category() const { if (get_script_instance() && get_script_instance()->has_method("_get_category")) { return get_script_instance()->call("_get_category"); } - return "custom"; + return "Custom"; } class VisualScriptNodeInstanceCustomNode : public VisualScriptNodeInstance { @@ -3641,6 +4075,14 @@ VisualScriptDeconstruct::VisualScriptDeconstruct() { type = Variant::NIL; } +template <Variant::Type T> +static Ref<VisualScriptNode> create_node_deconst_typed(const String &p_name) { + Ref<VisualScriptDeconstruct> node; + node.instance(); + node->set_deconstruct_type(T); + return node; +} + void register_visual_script_nodes() { VisualScriptLanguage::singleton->add_register_func("data/set_variable", create_node_generic<VisualScriptVariableSet>); @@ -3698,7 +4140,17 @@ void register_visual_script_nodes() { VisualScriptLanguage::singleton->add_register_func("operators/logic/in", create_op_node<Variant::OP_IN>); VisualScriptLanguage::singleton->add_register_func("operators/logic/select", create_node_generic<VisualScriptSelect>); - VisualScriptLanguage::singleton->add_register_func("functions/deconstruct", create_node_generic<VisualScriptDeconstruct>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::VECTOR2), create_node_deconst_typed<Variant::Type::VECTOR2>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::VECTOR3), create_node_deconst_typed<Variant::Type::VECTOR3>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::COLOR), create_node_deconst_typed<Variant::Type::COLOR>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::RECT2), create_node_deconst_typed<Variant::Type::RECT2>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::TRANSFORM2D), create_node_deconst_typed<Variant::Type::TRANSFORM2D>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::PLANE), create_node_deconst_typed<Variant::Type::PLANE>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::QUAT), create_node_deconst_typed<Variant::Type::QUAT>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::AABB), create_node_deconst_typed<Variant::Type::AABB>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::BASIS), create_node_deconst_typed<Variant::Type::BASIS>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::TRANSFORM), create_node_deconst_typed<Variant::Type::TRANSFORM>); + VisualScriptLanguage::singleton->add_register_func("functions/compose_array", create_node_generic<VisualScriptComposeArray>); for (int i = 1; i < Variant::VARIANT_MAX; i++) { diff --git a/modules/visual_script/visual_script_nodes.h b/modules/visual_script/visual_script_nodes.h index b3d199fb38..c7354cb0d8 100644 --- a/modules/visual_script/visual_script_nodes.h +++ b/modules/visual_script/visual_script_nodes.h @@ -35,7 +35,7 @@ class VisualScriptFunction : public VisualScriptNode { - GDCLASS(VisualScriptFunction, VisualScriptNode) + GDCLASS(VisualScriptFunction, VisualScriptNode); struct Argument { String name; @@ -103,9 +103,106 @@ public: VisualScriptFunction(); }; +class VisualScriptLists : public VisualScriptNode { + + GDCLASS(VisualScriptLists, VisualScriptNode) + + struct Port { + String name; + Variant::Type type; + }; + +protected: + Vector<Port> inputports; + Vector<Port> outputports; + + enum { + OUTPUT_EDITABLE = 0x0001, + OUTPUT_NAME_EDITABLE = 0x0002, + OUTPUT_TYPE_EDITABLE = 0x0004, + INPUT_EDITABLE = 0x0008, + INPUT_NAME_EDITABLE = 0x000F, + INPUT_TYPE_EDITABLE = 0x0010, + }; + + int flags; + + bool sequenced; + + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; + + static void _bind_methods(); + +public: + virtual bool is_output_port_editable() const; + virtual bool is_output_port_name_editable() const; + virtual bool is_output_port_type_editable() const; + + virtual bool is_input_port_editable() const; + virtual bool is_input_port_name_editable() const; + virtual bool is_input_port_type_editable() const; + + virtual int get_output_sequence_port_count() const; + virtual bool has_input_sequence_port() const; + + virtual String get_output_sequence_port_text(int p_port) const; + + virtual int get_input_value_port_count() const; + virtual int get_output_value_port_count() const; + + virtual PropertyInfo get_input_value_port_info(int p_idx) const; + virtual PropertyInfo get_output_value_port_info(int p_idx) const; + + virtual String get_caption() const = 0; + virtual String get_text() const = 0; + virtual String get_category() const = 0; + + void add_input_data_port(Variant::Type p_type, const String &p_name, int p_index = -1); + void set_input_data_port_type(int p_idx, Variant::Type p_type); + void set_input_data_port_name(int p_idx, const String &p_name); + void remove_input_data_port(int p_argidx); + + void add_output_data_port(Variant::Type p_type, const String &p_name, int p_index = -1); + void set_output_data_port_type(int p_idx, Variant::Type p_type); + void set_output_data_port_name(int p_idx, const String &p_name); + void remove_output_data_port(int p_argidx); + + void set_sequenced(bool p_enable); + bool is_sequenced() const; + + VisualScriptLists(); +}; + +class VisualScriptComposeArray : public VisualScriptLists { + + GDCLASS(VisualScriptComposeArray, VisualScriptLists) + +public: + virtual int get_output_sequence_port_count() const; + virtual bool has_input_sequence_port() const; + + virtual String get_output_sequence_port_text(int p_port) const; + + virtual int get_input_value_port_count() const; + virtual int get_output_value_port_count() const; + + virtual PropertyInfo get_input_value_port_info(int p_idx) const; + virtual PropertyInfo get_output_value_port_info(int p_idx) const; + + virtual String get_caption() const; + virtual String get_text() const; + virtual String get_category() const { return "functions"; } + + virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance); + + VisualScriptComposeArray(); +}; + class VisualScriptOperator : public VisualScriptNode { - GDCLASS(VisualScriptOperator, VisualScriptNode) + GDCLASS(VisualScriptOperator, VisualScriptNode); Variant::Type typed; Variant::Operator op; @@ -141,7 +238,7 @@ public: class VisualScriptSelect : public VisualScriptNode { - GDCLASS(VisualScriptSelect, VisualScriptNode) + GDCLASS(VisualScriptSelect, VisualScriptNode); Variant::Type typed; @@ -174,7 +271,7 @@ public: class VisualScriptVariableGet : public VisualScriptNode { - GDCLASS(VisualScriptVariableGet, VisualScriptNode) + GDCLASS(VisualScriptVariableGet, VisualScriptNode); StringName variable; @@ -207,7 +304,7 @@ public: class VisualScriptVariableSet : public VisualScriptNode { - GDCLASS(VisualScriptVariableSet, VisualScriptNode) + GDCLASS(VisualScriptVariableSet, VisualScriptNode); StringName variable; @@ -240,7 +337,7 @@ public: class VisualScriptConstant : public VisualScriptNode { - GDCLASS(VisualScriptConstant, VisualScriptNode) + GDCLASS(VisualScriptConstant, VisualScriptNode); Variant::Type type; Variant value; @@ -277,7 +374,7 @@ public: class VisualScriptPreload : public VisualScriptNode { - GDCLASS(VisualScriptPreload, VisualScriptNode) + GDCLASS(VisualScriptPreload, VisualScriptNode); Ref<Resource> preload; @@ -309,7 +406,7 @@ public: class VisualScriptIndexGet : public VisualScriptNode { - GDCLASS(VisualScriptIndexGet, VisualScriptNode) + GDCLASS(VisualScriptIndexGet, VisualScriptNode); public: virtual int get_output_sequence_port_count() const; @@ -333,7 +430,7 @@ public: class VisualScriptIndexSet : public VisualScriptNode { - GDCLASS(VisualScriptIndexSet, VisualScriptNode) + GDCLASS(VisualScriptIndexSet, VisualScriptNode); public: virtual int get_output_sequence_port_count() const; @@ -357,7 +454,7 @@ public: class VisualScriptGlobalConstant : public VisualScriptNode { - GDCLASS(VisualScriptGlobalConstant, VisualScriptNode) + GDCLASS(VisualScriptGlobalConstant, VisualScriptNode); int index; @@ -388,7 +485,7 @@ public: class VisualScriptClassConstant : public VisualScriptNode { - GDCLASS(VisualScriptClassConstant, VisualScriptNode) + GDCLASS(VisualScriptClassConstant, VisualScriptNode); StringName base_type; StringName name; @@ -425,7 +522,7 @@ public: class VisualScriptBasicTypeConstant : public VisualScriptNode { - GDCLASS(VisualScriptBasicTypeConstant, VisualScriptNode) + GDCLASS(VisualScriptBasicTypeConstant, VisualScriptNode); Variant::Type type; StringName name; @@ -463,7 +560,8 @@ public: class VisualScriptMathConstant : public VisualScriptNode { - GDCLASS(VisualScriptMathConstant, VisualScriptNode) + GDCLASS(VisualScriptMathConstant, VisualScriptNode); + public: enum MathConstant { MATH_CONSTANT_ONE, @@ -512,7 +610,7 @@ VARIANT_ENUM_CAST(VisualScriptMathConstant::MathConstant) class VisualScriptEngineSingleton : public VisualScriptNode { - GDCLASS(VisualScriptEngineSingleton, VisualScriptNode) + GDCLASS(VisualScriptEngineSingleton, VisualScriptNode); String singleton; @@ -545,7 +643,7 @@ public: class VisualScriptSceneNode : public VisualScriptNode { - GDCLASS(VisualScriptSceneNode, VisualScriptNode) + GDCLASS(VisualScriptSceneNode, VisualScriptNode); NodePath path; @@ -580,7 +678,7 @@ public: class VisualScriptSceneTree : public VisualScriptNode { - GDCLASS(VisualScriptSceneTree, VisualScriptNode) + GDCLASS(VisualScriptSceneTree, VisualScriptNode); protected: virtual void _validate_property(PropertyInfo &property) const; @@ -610,7 +708,7 @@ public: class VisualScriptResourcePath : public VisualScriptNode { - GDCLASS(VisualScriptResourcePath, VisualScriptNode) + GDCLASS(VisualScriptResourcePath, VisualScriptNode); String path; @@ -642,7 +740,7 @@ public: class VisualScriptSelf : public VisualScriptNode { - GDCLASS(VisualScriptSelf, VisualScriptNode) + GDCLASS(VisualScriptSelf, VisualScriptNode); protected: static void _bind_methods(); @@ -671,7 +769,7 @@ public: class VisualScriptCustomNode : public VisualScriptNode { - GDCLASS(VisualScriptCustomNode, VisualScriptNode) + GDCLASS(VisualScriptCustomNode, VisualScriptNode); protected: static void _bind_methods(); @@ -719,7 +817,7 @@ VARIANT_ENUM_CAST(VisualScriptCustomNode::StartMode); class VisualScriptSubCall : public VisualScriptNode { - GDCLASS(VisualScriptSubCall, VisualScriptNode) + GDCLASS(VisualScriptSubCall, VisualScriptNode); protected: static void _bind_methods(); @@ -747,7 +845,7 @@ public: class VisualScriptComment : public VisualScriptNode { - GDCLASS(VisualScriptComment, VisualScriptNode) + GDCLASS(VisualScriptComment, VisualScriptNode); String title; String description; @@ -788,7 +886,7 @@ public: class VisualScriptConstructor : public VisualScriptNode { - GDCLASS(VisualScriptConstructor, VisualScriptNode) + GDCLASS(VisualScriptConstructor, VisualScriptNode); Variant::Type type; MethodInfo constructor; @@ -824,7 +922,7 @@ public: class VisualScriptLocalVar : public VisualScriptNode { - GDCLASS(VisualScriptLocalVar, VisualScriptNode) + GDCLASS(VisualScriptLocalVar, VisualScriptNode); StringName name; Variant::Type type; @@ -860,7 +958,7 @@ public: class VisualScriptLocalVarSet : public VisualScriptNode { - GDCLASS(VisualScriptLocalVarSet, VisualScriptNode) + GDCLASS(VisualScriptLocalVarSet, VisualScriptNode); StringName name; Variant::Type type; @@ -897,7 +995,8 @@ public: class VisualScriptInputAction : public VisualScriptNode { - GDCLASS(VisualScriptInputAction, VisualScriptNode) + GDCLASS(VisualScriptInputAction, VisualScriptNode); + public: enum Mode { MODE_PRESSED, @@ -944,7 +1043,7 @@ VARIANT_ENUM_CAST(VisualScriptInputAction::Mode) class VisualScriptDeconstruct : public VisualScriptNode { - GDCLASS(VisualScriptDeconstruct, VisualScriptNode) + GDCLASS(VisualScriptDeconstruct, VisualScriptNode); struct Element { StringName name; diff --git a/modules/visual_script/visual_script_property_selector.cpp b/modules/visual_script/visual_script_property_selector.cpp index ac5f73d113..62b818150c 100644 --- a/modules/visual_script/visual_script_property_selector.cpp +++ b/modules/visual_script/visual_script_property_selector.cpp @@ -32,7 +32,7 @@ #include "core/os/keyboard.h" #include "editor/editor_node.h" -#include "editor_scale.h" +#include "editor/editor_scale.h" #include "modules/visual_script/visual_script.h" #include "modules/visual_script/visual_script_builtin_funcs.h" #include "modules/visual_script/visual_script_flow_control.h" @@ -87,38 +87,17 @@ void VisualScriptPropertySelector::_update_search() { TreeItem *root = search_options->create_item(); bool found = false; + StringName base = base_type; + List<StringName> base_list; + while (base) { + base_list.push_back(base); + base = ClassDB::get_parent_class_nocheck(base); + } - if (properties) { - + for (List<StringName>::Element *E = base_list.front(); E; E = E->next()) { + List<MethodInfo> methods; List<PropertyInfo> props; - - if (instance) { - instance->get_property_list(&props, true); - } else if (type != Variant::NIL) { - Variant v; - Variant::CallError ce; - v = Variant::construct(type, NULL, 0, ce); - - v.get_property_list(&props); - } else { - - Object *obj = ObjectDB::get_instance(script); - if (Object::cast_to<Script>(obj)) { - - props.push_back(PropertyInfo(Variant::NIL, "Script Variables", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CATEGORY)); - Object::cast_to<Script>(obj)->get_script_property_list(&props); - } - - StringName base = base_type; - while (base) { - props.push_back(PropertyInfo(Variant::NIL, base, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CATEGORY)); - ClassDB::get_property_list(base, &props, true); - base = ClassDB::get_parent_class_nocheck(base); - } - } - TreeItem *category = NULL; - Ref<Texture> type_icons[Variant::VARIANT_MAX] = { Control::get_icon("Variant", "EditorIcons"), Control::get_icon("bool", "EditorIcons"), @@ -148,85 +127,163 @@ void VisualScriptPropertySelector::_update_search() { Control::get_icon("PoolVector3Array", "EditorIcons"), Control::get_icon("PoolColorArray", "EditorIcons") }; - - if (!seq_connect && !visual_script_generic) { - get_visual_node_names("flow_control/type_cast", Set<String>(), found, root, search_box); - get_visual_node_names("functions/built_in/print", Set<String>(), found, root, search_box); - get_visual_node_names("functions/by_type/" + Variant::get_type_name(type), Set<String>(), found, root, search_box); - get_visual_node_names("operators/compare/", Set<String>(), found, root, search_box); - if (type == Variant::INT) { - get_visual_node_names("operators/bitwise/", Set<String>(), found, root, search_box); + { + String b = String(E->get()); + category = search_options->create_item(root); + if (category) { + category->set_text(0, b.replace_first("*", "")); + category->set_selectable(0, false); + Ref<Texture> icon; + String rep = b.replace("*", ""); + icon = EditorNode::get_singleton()->get_class_icon(rep); + category->set_icon(0, icon); } - if (type == Variant::BOOL) { - get_visual_node_names("operators/logic/", Set<String>(), found, root, search_box); + } + if (properties || seq_connect) { + if (instance) { + instance->get_property_list(&props, true); + } else { + Object *obj = ObjectDB::get_instance(script); + if (Object::cast_to<Script>(obj)) { + Object::cast_to<Script>(obj)->get_script_property_list(&props); + } else { + ClassDB::get_property_list(E->get(), &props, true); + } } - if (type == Variant::BOOL || type == Variant::INT || type == Variant::REAL || type == Variant::VECTOR2 || type == Variant::VECTOR3) { - get_visual_node_names("operators/math/", Set<String>(), found, root, search_box); + for (List<PropertyInfo>::Element *F = props.front(); F; F = F->next()) { + if (!(F->get().usage & PROPERTY_USAGE_EDITOR) && !(F->get().usage & PROPERTY_USAGE_SCRIPT_VARIABLE)) + continue; + + if (type_filter.size() && type_filter.find(F->get().type) == -1) + continue; + + // capitalize() also converts underscore to space, we'll match again both possible styles + String get_text_raw = String(vformat(TTR("Get %s"), F->get().name)); + String get_text = get_text_raw.capitalize(); + String set_text_raw = String(vformat(TTR("Set %s"), F->get().name)); + String set_text = set_text_raw.capitalize(); + String input = search_box->get_text().capitalize(); + + if (input == String() || get_text_raw.findn(input) != -1 || get_text.findn(input) != -1) { + TreeItem *item = search_options->create_item(category ? category : root); + item->set_text(0, get_text); + item->set_metadata(0, F->get().name); + item->set_icon(0, type_icons[F->get().type]); + item->set_metadata(1, "get"); + item->set_collapsed(1); + item->set_selectable(0, true); + item->set_selectable(1, false); + item->set_selectable(2, false); + item->set_metadata(2, connecting); + } + + if (input == String() || set_text_raw.findn(input) != -1 || set_text.findn(input) != -1) { + TreeItem *item = search_options->create_item(category ? category : root); + item->set_text(0, set_text); + item->set_metadata(0, F->get().name); + item->set_icon(0, type_icons[F->get().type]); + item->set_metadata(1, "set"); + item->set_selectable(0, true); + item->set_selectable(1, false); + item->set_selectable(2, false); + item->set_metadata(2, connecting); + } } } + { + if (type != Variant::NIL) { + Variant v; + Variant::CallError ce; + v = Variant::construct(type, NULL, 0, ce); + v.get_method_list(&methods); + } else { - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - if (E->get().usage == PROPERTY_USAGE_CATEGORY) { - if (category && category->get_children() == NULL) { - memdelete(category); //old category was unused + Object *obj = ObjectDB::get_instance(script); + if (Object::cast_to<Script>(obj)) { + Object::cast_to<Script>(obj)->get_script_method_list(&methods); } - category = search_options->create_item(root); - category->set_text(0, E->get().name); - category->set_selectable(0, false); - Ref<Texture> icon; - if (E->get().name == "Script Variables") { - icon = get_icon("Script", "EditorIcons"); - } else { - icon = EditorNode::get_singleton()->get_class_icon(E->get().name); - } - category->set_icon(0, icon); - continue; + ClassDB::get_method_list(E->get(), &methods, true, true); } + } + for (List<MethodInfo>::Element *M = methods.front(); M; M = M->next()) { + + String name = M->get().name.get_slice(":", 0); + if (name.begins_with("_") && !(M->get().flags & METHOD_FLAG_VIRTUAL)) + continue; - if (!(E->get().usage & PROPERTY_USAGE_EDITOR) && !(E->get().usage & PROPERTY_USAGE_SCRIPT_VARIABLE)) + if (virtuals_only && !(M->get().flags & METHOD_FLAG_VIRTUAL)) continue; - if (type_filter.size() && type_filter.find(E->get().type) == -1) + if (!virtuals_only && (M->get().flags & METHOD_FLAG_VIRTUAL)) continue; - // capitalize() also converts underscore to space, we'll match again both possible styles - String get_text_raw = String(vformat(TTR("Get %s"), E->get().name)); - String get_text = get_text_raw.capitalize(); - String set_text_raw = String(vformat(TTR("Set %s"), E->get().name)); - String set_text = set_text_raw.capitalize(); - String input = search_box->get_text().capitalize(); - - if (input == String() || get_text_raw.findn(input) != -1 || get_text.findn(input) != -1) { - TreeItem *item = search_options->create_item(category ? category : root); - item->set_text(0, get_text); - item->set_metadata(0, E->get().name); - item->set_icon(0, type_icons[E->get().type]); - item->set_metadata(1, "get"); - item->set_collapsed(1); - item->set_selectable(0, true); - item->set_selectable(1, false); - item->set_selectable(2, false); - item->set_metadata(2, connecting); + MethodInfo mi = M->get(); + String desc_arguments; + if (mi.arguments.size() > 0) { + desc_arguments = "("; + for (int i = 0; i < mi.arguments.size(); i++) { + + if (i > 0) { + desc_arguments += ", "; + } + if (mi.arguments[i].type == Variant::NIL) { + desc_arguments += "var"; + } else if (mi.arguments[i].name.find(":") != -1) { + desc_arguments += mi.arguments[i].name.get_slice(":", 1); + mi.arguments[i].name = mi.arguments[i].name.get_slice(":", 0); + } else { + desc_arguments += Variant::get_type_name(mi.arguments[i].type); + } + } + desc_arguments += ")"; } + String desc_raw = mi.name + desc_arguments; + String desc = desc_raw.capitalize().replace("( ", "("); - if (input == String() || set_text_raw.findn(input) != -1 || set_text.findn(input) != -1) { - TreeItem *item = search_options->create_item(category ? category : root); - item->set_text(0, set_text); - item->set_metadata(0, E->get().name); - item->set_icon(0, type_icons[E->get().type]); - item->set_metadata(1, "set"); - item->set_selectable(0, true); - item->set_selectable(1, false); - item->set_selectable(2, false); - item->set_metadata(2, connecting); + if (search_box->get_text() != String() && + name.findn(search_box->get_text()) == -1 && + desc.findn(search_box->get_text()) == -1 && + desc_raw.findn(search_box->get_text()) == -1) { + continue; } + + TreeItem *item = search_options->create_item(category ? category : root); + item->set_text(0, desc); + item->set_icon(0, get_icon("MemberMethod", "EditorIcons")); + item->set_metadata(0, name); + item->set_selectable(0, true); + + item->set_metadata(1, "method"); + item->set_collapsed(1); + item->set_selectable(1, false); + + item->set_selectable(2, false); + item->set_metadata(2, connecting); } if (category && category->get_children() == NULL) { memdelete(category); //old category was unused } } + if (properties) { + if (!seq_connect && !visual_script_generic) { + get_visual_node_names("flow_control/type_cast", Set<String>(), found, root, search_box); + get_visual_node_names("functions/built_in/print", Set<String>(), found, root, search_box); + get_visual_node_names("functions/by_type/" + Variant::get_type_name(type), Set<String>(), found, root, search_box); + get_visual_node_names("functions/deconstruct/" + Variant::get_type_name(type), Set<String>(), found, root, search_box); + get_visual_node_names("operators/compare/", Set<String>(), found, root, search_box); + if (type == Variant::INT) { + get_visual_node_names("operators/bitwise/", Set<String>(), found, root, search_box); + } + if (type == Variant::BOOL) { + get_visual_node_names("operators/logic/", Set<String>(), found, root, search_box); + } + if (type == Variant::BOOL || type == Variant::INT || type == Variant::REAL || type == Variant::VECTOR2 || type == Variant::VECTOR3) { + get_visual_node_names("operators/math/", Set<String>(), found, root, search_box); + } + } + } if (seq_connect && !visual_script_generic) { String text = search_box->get_text(); @@ -240,127 +297,16 @@ void VisualScriptPropertySelector::_update_search() { get_visual_node_names("functions/built_in/print", Set<String>(), found, root, search_box); } - if (visual_script_generic) { + if ((properties || seq_connect) && visual_script_generic) { get_visual_node_names("", Set<String>(), found, root, search_box); } - List<MethodInfo> methods; - - if (type != Variant::NIL) { - Variant v; - Variant::CallError ce; - v = Variant::construct(type, NULL, 0, ce); - v.get_method_list(&methods); - } else { - - Object *obj = ObjectDB::get_instance(script); - if (Object::cast_to<Script>(obj)) { - - methods.push_back(MethodInfo("*Script Methods")); - Object::cast_to<Script>(obj)->get_script_method_list(&methods); - } - - StringName base = base_type; - while (base) { - methods.push_back(MethodInfo("*" + String(base))); - ClassDB::get_method_list(base, &methods, true, true); - base = ClassDB::get_parent_class_nocheck(base); - } - } - TreeItem *category = NULL; - bool script_methods = false; - - for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - if (E->get().name.begins_with("*")) { - if (category && category->get_children() == NULL) { - memdelete(category); //old category was unused - } - category = search_options->create_item(root); - category->set_text(0, E->get().name.replace_first("*", "")); - category->set_selectable(0, false); - - Ref<Texture> icon; - script_methods = false; - String rep = E->get().name.replace("*", ""); - if (E->get().name == "*Script Methods") { - icon = get_icon("Script", "EditorIcons"); - script_methods = true; - } else { - icon = EditorNode::get_singleton()->get_class_icon(rep); - } - category->set_icon(0, icon); - - continue; - } - - String name = E->get().name.get_slice(":", 0); - if (!script_methods && name.begins_with("_") && !(E->get().flags & METHOD_FLAG_VIRTUAL)) - continue; - - if (virtuals_only && !(E->get().flags & METHOD_FLAG_VIRTUAL)) - continue; - - if (!virtuals_only && (E->get().flags & METHOD_FLAG_VIRTUAL)) - continue; - - MethodInfo mi = E->get(); - String desc_arguments; - if (mi.arguments.size() > 0) { - desc_arguments = "("; - for (int i = 0; i < mi.arguments.size(); i++) { - - if (i > 0) { - desc_arguments += ", "; - } - if (mi.arguments[i].type == Variant::NIL) { - desc_arguments += "var"; - } else if (mi.arguments[i].name.find(":") != -1) { - desc_arguments += mi.arguments[i].name.get_slice(":", 1); - mi.arguments[i].name = mi.arguments[i].name.get_slice(":", 0); - } else { - desc_arguments += Variant::get_type_name(mi.arguments[i].type); - } - } - desc_arguments += ")"; - } - String desc_raw = mi.name + desc_arguments; - String desc = desc_raw.capitalize().replace("( ", "("); - - if (search_box->get_text() != String() && - name.findn(search_box->get_text()) == -1 && - desc.findn(search_box->get_text()) == -1 && - desc_raw.findn(search_box->get_text()) == -1) { - continue; - } - - TreeItem *item = search_options->create_item(category ? category : root); - item->set_text(0, desc); - item->set_icon(0, get_icon("MemberMethod", "EditorIcons")); - item->set_metadata(0, name); - item->set_selectable(0, true); - - item->set_metadata(1, "method"); - item->set_collapsed(1); - item->set_selectable(1, false); - - item->set_selectable(2, false); - item->set_metadata(2, connecting); - - if (category && category->get_children() == NULL) { - memdelete(category); //old category was unused - } - } - TreeItem *selected_item = search_options->search_item_text(search_box->get_text()); if (!found && selected_item != NULL) { selected_item->select(0); found = true; } - if (category && category->get_children() == NULL) { - memdelete(category); //old category was unused - } - get_ok()->set_disabled(root->get_children() == NULL); } @@ -379,7 +325,7 @@ void VisualScriptPropertySelector::create_visualscript_item(const String &name, } } -void VisualScriptPropertySelector::get_visual_node_names(const String &root_filter, const Set<String> &filter, bool &found, TreeItem *const root, LineEdit *const search_box) { +void VisualScriptPropertySelector::get_visual_node_names(const String &root_filter, const Set<String> &p_modifiers, bool &found, TreeItem *const root, LineEdit *const search_box) { Map<String, TreeItem *> path_cache; List<String> fnodes; @@ -390,37 +336,59 @@ void VisualScriptPropertySelector::get_visual_node_names(const String &root_filt continue; } Vector<String> path = E->get().split("/"); - bool is_filter = false; - for (Set<String>::Element *F = filter.front(); F; F = F->next()) { - if (path.size() >= 2 && path[1].findn(F->get()) != -1) { - is_filter = true; + + // check if the name has the filter + bool in_filter = false; + Vector<String> tx_filters = search_box->get_text().split(" "); + for (int i = 0; i < tx_filters.size(); i++) { + if (tx_filters[i] == "") { + in_filter = true; + } else { + in_filter = false; + } + if (E->get().findn(tx_filters[i]) != -1) { + in_filter = true; break; } } - if (is_filter) { + if (!in_filter) { continue; } - if (search_box->get_text() != String() && E->get().findn(search_box->get_text()) == -1) { + bool in_modifier = false | p_modifiers.empty(); + for (Set<String>::Element *F = p_modifiers.front(); F && in_modifier; F = F->next()) { + if (E->get().findn(F->get()) != -1) + in_modifier = true; + } + if (!in_modifier) { continue; } + TreeItem *item = search_options->create_item(root); - VisualScriptOperator *vnode_operator = Object::cast_to<VisualScriptOperator>(*VisualScriptLanguage::singleton->create_node_from_name(E->get())); + Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(E->get()); + Ref<VisualScriptOperator> vnode_operator = vnode; String type_name; - if (vnode_operator != NULL) { + if (vnode_operator.is_valid()) { String type; if (path.size() >= 2) { type = path[1]; } type_name = type.capitalize() + " "; } - VisualScriptFunctionCall *vnode_function_call = Object::cast_to<VisualScriptFunctionCall>(*VisualScriptLanguage::singleton->create_node_from_name(E->get())); - if (vnode_function_call != NULL) { + Ref<VisualScriptFunctionCall> vnode_function_call = vnode; + if (vnode_function_call.is_valid()) { String basic_type = Variant::get_type_name(vnode_function_call->get_basic_type()); type_name = basic_type.capitalize() + " "; } - - Vector<String> desc = path[path.size() - 1].replace("(", "( ").replace(")", " )").replace(",", ", ").split(" "); + Ref<VisualScriptConstructor> vnode_constructor = vnode; + if (vnode_constructor.is_valid()) { + type_name = "Construct "; + } + Ref<VisualScriptDeconstruct> vnode_deconstruct = vnode; + if (vnode_deconstruct.is_valid()) { + type_name = "Deconstruct "; + } + Vector<String> desc = path[path.size() - 1].replace("(", " ").replace(")", " ").replace(",", " ").split(" "); for (int i = 0; i < desc.size(); i++) { desc.write[i] = desc[i].capitalize(); if (desc[i].ends_with(",")) { @@ -459,7 +427,7 @@ void VisualScriptPropertySelector::_item_selected() { String name = item->get_metadata(0); String class_type; - if (type) { + if (type != Variant::NIL) { class_type = Variant::get_type_name(type); } else { @@ -488,23 +456,23 @@ void VisualScriptPropertySelector::_item_selected() { while (at_class != String()) { - Map<String, DocData::ClassDoc>::Element *E = dd->class_list.find(at_class); - if (E) { - for (int i = 0; i < E->get().methods.size(); i++) { - if (E->get().methods[i].name == name) { - text = E->get().methods[i].description; + Map<String, DocData::ClassDoc>::Element *C = dd->class_list.find(at_class); + if (C) { + for (int i = 0; i < C->get().methods.size(); i++) { + if (C->get().methods[i].name == name) { + text = C->get().methods[i].description; } } } at_class = ClassDB::get_parent_class_nocheck(at_class); } - Map<String, DocData::ClassDoc>::Element *E = dd->class_list.find(class_type); - if (E) { - for (int i = 0; i < E->get().methods.size(); i++) { + Map<String, DocData::ClassDoc>::Element *T = dd->class_list.find(class_type); + if (T) { + for (int i = 0; i < T->get().methods.size(); i++) { Vector<String> functions = name.rsplit("/", false, 1); - if (E->get().methods[i].name == functions[functions.size() - 1]) { - text = E->get().methods[i].description; + if (T->get().methods[i].name == functions[functions.size() - 1]) { + text = T->get().methods[i].description; } } } @@ -556,7 +524,7 @@ void VisualScriptPropertySelector::_notification(int p_what) { } } -void VisualScriptPropertySelector::select_method_from_base_type(const String &p_base, const String &p_current, const bool p_virtuals_only, const bool p_connecting) { +void VisualScriptPropertySelector::select_method_from_base_type(const String &p_base, const String &p_current, const bool p_virtuals_only, const bool p_connecting, bool clear_text) { base_type = p_base; selected = p_current; @@ -567,7 +535,10 @@ void VisualScriptPropertySelector::select_method_from_base_type(const String &p_ virtuals_only = p_virtuals_only; show_window(.5f); - search_box->set_text(""); + if (clear_text) + search_box->set_text(""); + else + search_box->select_all(); search_box->grab_focus(); connecting = p_connecting; @@ -578,7 +549,7 @@ void VisualScriptPropertySelector::set_type_filter(const Vector<Variant::Type> & type_filter = p_type_filter; } -void VisualScriptPropertySelector::select_from_base_type(const String &p_base, const String &p_current, bool p_virtuals_only, bool p_seq_connect, const bool p_connecting) { +void VisualScriptPropertySelector::select_from_base_type(const String &p_base, const String &p_current, bool p_virtuals_only, bool p_seq_connect, const bool p_connecting, bool clear_text) { base_type = p_base; selected = p_current; @@ -590,7 +561,10 @@ void VisualScriptPropertySelector::select_from_base_type(const String &p_base, c virtuals_only = p_virtuals_only; show_window(.5f); - search_box->set_text(""); + if (clear_text) + search_box->set_text(""); + else + search_box->select_all(); search_box->grab_focus(); seq_connect = p_seq_connect; connecting = p_connecting; @@ -598,7 +572,7 @@ void VisualScriptPropertySelector::select_from_base_type(const String &p_base, c _update_search(); } -void VisualScriptPropertySelector::select_from_script(const Ref<Script> &p_script, const String &p_current, const bool p_connecting) { +void VisualScriptPropertySelector::select_from_script(const Ref<Script> &p_script, const String &p_current, const bool p_connecting, bool clear_text) { ERR_FAIL_COND(p_script.is_null()); base_type = p_script->get_instance_base_type(); @@ -611,7 +585,10 @@ void VisualScriptPropertySelector::select_from_script(const Ref<Script> &p_scrip virtuals_only = false; show_window(.5f); - search_box->set_text(""); + if (clear_text) + search_box->set_text(""); + else + search_box->select_all(); search_box->grab_focus(); seq_connect = false; connecting = p_connecting; @@ -619,7 +596,7 @@ void VisualScriptPropertySelector::select_from_script(const Ref<Script> &p_scrip _update_search(); } -void VisualScriptPropertySelector::select_from_basic_type(Variant::Type p_type, const String &p_current, const bool p_connecting) { +void VisualScriptPropertySelector::select_from_basic_type(Variant::Type p_type, const String &p_current, const bool p_connecting, bool clear_text) { ERR_FAIL_COND(p_type == Variant::NIL); base_type = ""; selected = p_current; @@ -631,7 +608,10 @@ void VisualScriptPropertySelector::select_from_basic_type(Variant::Type p_type, virtuals_only = false; show_window(.5f); - search_box->set_text(""); + if (clear_text) + search_box->set_text(""); + else + search_box->select_all(); search_box->grab_focus(); seq_connect = false; connecting = p_connecting; @@ -639,7 +619,7 @@ void VisualScriptPropertySelector::select_from_basic_type(Variant::Type p_type, _update_search(); } -void VisualScriptPropertySelector::select_from_action(const String &p_type, const String &p_current, const bool p_connecting) { +void VisualScriptPropertySelector::select_from_action(const String &p_type, const String &p_current, const bool p_connecting, bool clear_text) { base_type = p_type; selected = p_current; type = Variant::NIL; @@ -650,7 +630,10 @@ void VisualScriptPropertySelector::select_from_action(const String &p_type, cons virtuals_only = false; show_window(.5f); - search_box->set_text(""); + if (clear_text) + search_box->set_text(""); + else + search_box->select_all(); search_box->grab_focus(); seq_connect = true; connecting = p_connecting; @@ -658,8 +641,8 @@ void VisualScriptPropertySelector::select_from_action(const String &p_type, cons _update_search(); } -void VisualScriptPropertySelector::select_from_instance(Object *p_instance, const String &p_current, const bool p_connecting) { - base_type = ""; +void VisualScriptPropertySelector::select_from_instance(Object *p_instance, const String &p_current, const bool p_connecting, const String &p_basetype, bool clear_text) { + base_type = p_basetype; selected = p_current; type = Variant::NIL; script = 0; @@ -669,7 +652,10 @@ void VisualScriptPropertySelector::select_from_instance(Object *p_instance, cons virtuals_only = false; show_window(.5f); - search_box->set_text(""); + if (clear_text) + search_box->set_text(""); + else + search_box->select_all(); search_box->grab_focus(); seq_connect = false; connecting = p_connecting; @@ -677,7 +663,7 @@ void VisualScriptPropertySelector::select_from_instance(Object *p_instance, cons _update_search(); } -void VisualScriptPropertySelector::select_from_visual_script(const String &p_base, const bool p_connecting) { +void VisualScriptPropertySelector::select_from_visual_script(const String &p_base, const bool p_connecting, bool clear_text) { base_type = p_base; selected = ""; type = Variant::NIL; @@ -687,7 +673,10 @@ void VisualScriptPropertySelector::select_from_visual_script(const String &p_bas instance = NULL; virtuals_only = false; show_window(.5f); - search_box->set_text(""); + if (clear_text) + search_box->set_text(""); + else + search_box->select_all(); search_box->grab_focus(); connecting = p_connecting; @@ -698,7 +687,7 @@ void VisualScriptPropertySelector::show_window(float p_screen_ratio) { Rect2 rect; Point2 window_size = get_viewport_rect().size; rect.size = (window_size * p_screen_ratio).floor(); - rect.size.x = rect.size.x / 1.25f; + rect.size.x = rect.size.x / 2.2f; rect.position = ((window_size - rect.size) / 2.0f).floor(); popup(rect); } diff --git a/modules/visual_script/visual_script_property_selector.h b/modules/visual_script/visual_script_property_selector.h index 1588243bc1..3a7c8de6a2 100644 --- a/modules/visual_script/visual_script_property_selector.h +++ b/modules/visual_script/visual_script_property_selector.h @@ -31,12 +31,12 @@ #ifndef VISUALSCRIPT_PROPERTYSELECTOR_H #define VISUALSCRIPT_PROPERTYSELECTOR_H +#include "editor/editor_help.h" #include "editor/property_editor.h" -#include "editor_help.h" #include "scene/gui/rich_text_label.h" class VisualScriptPropertySelector : public ConfirmationDialog { - GDCLASS(VisualScriptPropertySelector, ConfirmationDialog) + GDCLASS(VisualScriptPropertySelector, ConfirmationDialog); LineEdit *search_box; Tree *search_options; @@ -45,7 +45,7 @@ class VisualScriptPropertySelector : public ConfirmationDialog { void create_visualscript_item(const String &name, TreeItem *const root, const String &search_input, const String &text); - void get_visual_node_names(const String &root_filter, const Set<String> &filter, bool &found, TreeItem *const root, LineEdit *const search_box); + void get_visual_node_names(const String &root_filter, const Set<String> &p_modifiers, bool &found, TreeItem *const root, LineEdit *const search_box); void _sbox_input(const Ref<InputEvent> &p_ie); @@ -74,13 +74,13 @@ protected: static void _bind_methods(); public: - void select_method_from_base_type(const String &p_base, const String &p_current = "", const bool p_virtuals_only = false, const bool p_connecting = true); - void select_from_base_type(const String &p_base, const String &p_current = "", bool p_virtuals_only = false, bool p_seq_connect = false, const bool p_connecting = true); - void select_from_script(const Ref<Script> &p_script, const String &p_current = "", const bool p_connecting = true); - void select_from_basic_type(Variant::Type p_type, const String &p_current = "", const bool p_connecting = true); - void select_from_action(const String &p_type, const String &p_current = "", const bool p_connecting = true); - void select_from_instance(Object *p_instance, const String &p_current = "", const bool p_connecting = true); - void select_from_visual_script(const String &p_base, const bool p_connecting = true); + void select_method_from_base_type(const String &p_base, const String &p_current = "", const bool p_virtuals_only = false, const bool p_connecting = true, bool clear_text = true); + void select_from_base_type(const String &p_base, const String &p_current = "", bool p_virtuals_only = false, bool p_seq_connect = false, const bool p_connecting = true, bool clear_text = true); + void select_from_script(const Ref<Script> &p_script, const String &p_current = "", const bool p_connecting = true, bool clear_text = true); + void select_from_basic_type(Variant::Type p_type, const String &p_current = "", const bool p_connecting = true, bool clear_text = true); + void select_from_action(const String &p_type, const String &p_current = "", const bool p_connecting = true, bool clear_text = true); + void select_from_instance(Object *p_instance, const String &p_current = "", const bool p_connecting = true, const String &p_basetype = "", bool clear_text = true); + void select_from_visual_script(const String &p_base, const bool p_connecting = true, bool clear_text = true); void show_window(float p_screen_ratio); diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp index 962560cc96..ebd0f0b3cb 100644 --- a/modules/visual_script/visual_script_yield_nodes.cpp +++ b/modules/visual_script/visual_script_yield_nodes.cpp @@ -431,7 +431,6 @@ void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const { Node *bnode = _get_base_node(); if (bnode) { property.hint_string = bnode->get_path(); //convert to loong string - } else { } } } diff --git a/modules/visual_script/visual_script_yield_nodes.h b/modules/visual_script/visual_script_yield_nodes.h index 851bf6aa74..647f2b1e2e 100644 --- a/modules/visual_script/visual_script_yield_nodes.h +++ b/modules/visual_script/visual_script_yield_nodes.h @@ -35,7 +35,8 @@ class VisualScriptYield : public VisualScriptNode { - GDCLASS(VisualScriptYield, VisualScriptNode) + GDCLASS(VisualScriptYield, VisualScriptNode); + public: enum YieldMode { YIELD_RETURN, @@ -84,7 +85,8 @@ VARIANT_ENUM_CAST(VisualScriptYield::YieldMode) class VisualScriptYieldSignal : public VisualScriptNode { - GDCLASS(VisualScriptYieldSignal, VisualScriptNode) + GDCLASS(VisualScriptYieldSignal, VisualScriptNode); + public: enum CallMode { CALL_MODE_SELF, diff --git a/modules/vorbis/SCsub b/modules/vorbis/SCsub index 19587563ab..3824fdd789 100644 --- a/modules/vorbis/SCsub +++ b/modules/vorbis/SCsub @@ -40,11 +40,11 @@ if env['builtin_libvorbis']: thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - env_vorbis.Append(CPPPATH=[thirdparty_dir]) + env_vorbis.Prepend(CPPPATH=[thirdparty_dir]) # also requires libogg if env['builtin_libogg']: - env_vorbis.Append(CPPPATH=["#thirdparty/libogg"]) + env_vorbis.Prepend(CPPPATH=["#thirdparty/libogg"]) env_thirdparty = env_vorbis.Clone() env_thirdparty.disable_warnings() diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp index 692705e411..c330af60a4 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.cpp +++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp @@ -103,7 +103,7 @@ int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_buffer, int p_frames) { int todo = p_frames; - if (todo == 0 || todo < MIN_MIX) { + if (todo < MIN_MIX) { break; } @@ -116,8 +116,7 @@ int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_buffer, int p_frames) { if (ret < 0) { playing = false; - ERR_EXPLAIN("Error reading OGG Vorbis File: " + file); - ERR_BREAK(ret < 0); + ERR_BREAK_MSG(ret < 0, "Error reading OGG Vorbis file: " + file + "."); } else if (ret == 0) { // end of song, reload? ov_clear(&vf); @@ -143,8 +142,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; @@ -244,10 +242,7 @@ Error AudioStreamPlaybackOGGVorbis::set_file(const String &p_file) { stream_valid = false; Error err; f = FileAccess::open(file, FileAccess::READ, &err); - - if (err) { - ERR_FAIL_COND_V(err, err); - } + ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + p_file + "'."); int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks); switch (errv) { @@ -296,9 +291,7 @@ Error AudioStreamPlaybackOGGVorbis::_load_stream() { Error err; f = FileAccess::open(file, FileAccess::READ, &err); - if (err) { - ERR_FAIL_COND_V(err, err); - } + ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + file + "'."); int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks); switch (errv) { 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/SCsub b/modules/webm/SCsub index cb35b926ab..32e6727656 100644 --- a/modules/webm/SCsub +++ b/modules/webm/SCsub @@ -15,22 +15,18 @@ thirdparty_sources = [ ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] -env_webm.Append(CPPPATH=[thirdparty_dir, thirdparty_dir + "libwebm/"]) - -# upstream uses c++11 -if (not env_webm.msvc): - env_webm.Append(CCFLAGS="-std=c++11") +env_webm.Prepend(CPPPATH=[thirdparty_dir, thirdparty_dir + "libwebm/"]) # also requires libogg, libvorbis and libopus if env['builtin_libogg']: - env_webm.Append(CPPPATH=["#thirdparty/libogg"]) + env_webm.Prepend(CPPPATH=["#thirdparty/libogg"]) if env['builtin_libvorbis']: - env_webm.Append(CPPPATH=["#thirdparty/libvorbis"]) + env_webm.Prepend(CPPPATH=["#thirdparty/libvorbis"]) if env['builtin_opus']: - env_webm.Append(CPPPATH=["#thirdparty/opus"]) + env_webm.Prepend(CPPPATH=["#thirdparty/opus"]) if env['builtin_libvpx']: - env_webm.Append(CPPPATH=["#thirdparty/libvpx"]) + env_webm.Prepend(CPPPATH=["#thirdparty/libvpx"]) SConscript("libvpx/SCsub") env_thirdparty = env_webm.Clone() 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/doc_classes/VideoStreamWebm.xml b/modules/webm/doc_classes/VideoStreamWebm.xml index 33dff0e93b..ff11bbb37d 100644 --- a/modules/webm/doc_classes/VideoStreamWebm.xml +++ b/modules/webm/doc_classes/VideoStreamWebm.xml @@ -6,8 +6,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_file"> <return type="String"> diff --git a/modules/webm/libvpx/SCsub b/modules/webm/libvpx/SCsub index 2639d20620..14fa6c1268 100644 --- a/modules/webm/libvpx/SCsub +++ b/modules/webm/libvpx/SCsub @@ -256,7 +256,7 @@ libvpx_sources_arm_neon_gas_apple = [libvpx_dir + file for file in libvpx_source env_libvpx = env_modules.Clone() env_libvpx.disable_warnings() -env_libvpx.Append(CPPPATH=[libvpx_dir]) +env_libvpx.Prepend(CPPPATH=[libvpx_dir]) webm_multithread = env["platform"] != 'javascript' @@ -323,7 +323,7 @@ if webm_cpu_x86: elif cpu_bits == '64': env_libvpx["ASCPU"] = 'X86_64' - env_libvpx.Append(CCFLAGS=['-DWEBM_X86ASM']) + env_libvpx.Append(CPPDEFINES=['WEBM_X86ASM']) webm_simd_optimizations = True @@ -337,7 +337,7 @@ if webm_cpu_arm: env_libvpx["ASFLAGS"] = '' env_libvpx["ASCOM"] = '$AS $ASFLAGS -o $TARGET $SOURCES' - env_libvpx.Append(CCFLAGS=['-DWEBM_ARMASM']) + env_libvpx.Append(CPPDEFINES=['WEBM_ARMASM']) webm_simd_optimizations = True @@ -380,12 +380,10 @@ if webm_cpu_x86: elif webm_cpu_arm: env_libvpx.add_source_files(env.modules_sources, libvpx_sources_arm) if env["platform"] == 'android': - env_libvpx.Append(CPPPATH=[libvpx_dir + "third_party/android"]) + env_libvpx.Prepend(CPPPATH=[libvpx_dir + "third_party/android"]) env_libvpx.add_source_files(env.modules_sources, [libvpx_dir + "third_party/android/cpu-features.c"]) env_libvpx_neon = env_libvpx.Clone() - if env["platform"] == 'android' and env["android_arch"] == 'armv6': - env_libvpx_neon.Append(CCFLAGS=['-mfpu=neon']) env_libvpx_neon.add_source_files(env.modules_sources, libvpx_sources_arm_neon) if env["platform"] == 'uwp': diff --git a/modules/webm/video_stream_webm.cpp b/modules/webm/video_stream_webm.cpp index 06f9e39dc7..54b284f939 100644 --- a/modules/webm/video_stream_webm.cpp +++ b/modules/webm/video_stream_webm.cpp @@ -32,6 +32,7 @@ #include "OpusVorbisDecoder.hpp" #include "VPXDecoder.hpp" +#include <vpx/vpx_image.h> #include "mkvparser/mkvparser.h" @@ -52,8 +53,7 @@ public: file = FileAccess::open(p_file, FileAccess::READ); - ERR_EXPLAIN("Failed loading resource: '" + p_file + "';"); - ERR_FAIL_COND(!file); + ERR_FAIL_COND_MSG(!file, "Failed loading resource: '" + p_file + "'."); } ~MkvReader() { @@ -230,7 +230,7 @@ void VideoStreamPlaybackWebm::set_audio_track(int p_idx) { audio_track = p_idx; } -Ref<Texture> VideoStreamPlaybackWebm::get_texture() { +Ref<Texture> VideoStreamPlaybackWebm::get_texture() const { return texture; } @@ -314,19 +314,37 @@ void VideoStreamPlaybackWebm::update(float p_delta) { PoolVector<uint8_t>::Write w = frame_data.write(); bool converted = false; - if (image.chromaShiftW == 1 && image.chromaShiftH == 1) { + if (image.chromaShiftW == 0 && image.chromaShiftH == 0 && image.cs == VPX_CS_SRGB) { + + uint8_t *wp = w.ptr(); + unsigned char *rRow = image.planes[2]; + unsigned char *gRow = image.planes[0]; + unsigned char *bRow = image.planes[1]; + for (int i = 0; i < image.h; i++) { + for (int j = 0; j < image.w; j++) { + *wp++ = rRow[j]; + *wp++ = gRow[j]; + *wp++ = bRow[j]; + *wp++ = 255; + } + rRow += image.linesize[2]; + gRow += image.linesize[0]; + bRow += image.linesize[1]; + } + converted = true; + } else if (image.chromaShiftW == 1 && image.chromaShiftH == 1) { - yuv420_2_rgb8888(w.ptr(), image.planes[0], image.planes[2], image.planes[1], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2, 0); + yuv420_2_rgb8888(w.ptr(), image.planes[0], image.planes[1], image.planes[2], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2); // libyuv::I420ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h); converted = true; } else if (image.chromaShiftW == 1 && image.chromaShiftH == 0) { - yuv422_2_rgb8888(w.ptr(), image.planes[0], image.planes[2], image.planes[1], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2, 0); + yuv422_2_rgb8888(w.ptr(), image.planes[0], image.planes[1], image.planes[2], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2); // libyuv::I422ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h); converted = true; } else if (image.chromaShiftW == 0 && image.chromaShiftH == 0) { - yuv444_2_rgb8888(w.ptr(), image.planes[0], image.planes[2], image.planes[1], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2, 0); + yuv444_2_rgb8888(w.ptr(), image.planes[0], image.planes[1], image.planes[2], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2); // libyuv::I444ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h); converted = true; } else if (image.chromaShiftW == 2 && image.chromaShiftH == 0) { @@ -375,7 +393,7 @@ int VideoStreamPlaybackWebm::get_mix_rate() const { inline bool VideoStreamPlaybackWebm::has_enough_video_frames() const { if (video_frames_pos > 0) { - const double audio_delay = AudioServer::get_singleton()->get_output_delay(); + const double audio_delay = AudioServer::get_singleton()->get_output_latency(); const double video_time = video_frames[video_frames_pos - 1]->time; return video_time >= time + audio_delay + delay_compensation; } @@ -383,7 +401,7 @@ inline bool VideoStreamPlaybackWebm::has_enough_video_frames() const { } bool VideoStreamPlaybackWebm::should_process(WebMFrame &video_frame) { - const double audio_delay = AudioServer::get_singleton()->get_output_delay(); + const double audio_delay = AudioServer::get_singleton()->get_output_latency(); return video_frame.time >= time + audio_delay + delay_compensation; } @@ -394,10 +412,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); @@ -465,6 +484,8 @@ RES ResourceFormatLoaderWebm::load(const String &p_path, const String &p_origina *r_error = OK; } + f->close(); + memdelete(f); return webm_stream; } diff --git a/modules/webm/video_stream_webm.h b/modules/webm/video_stream_webm.h index 992095ba4c..4f79d46cce 100644 --- a/modules/webm/video_stream_webm.h +++ b/modules/webm/video_stream_webm.h @@ -41,7 +41,7 @@ class OpusVorbisDecoder; class VideoStreamPlaybackWebm : public VideoStreamPlayback { - GDCLASS(VideoStreamPlaybackWebm, VideoStreamPlayback) + GDCLASS(VideoStreamPlaybackWebm, VideoStreamPlayback); String file_name; int audio_track; @@ -90,7 +90,7 @@ public: virtual void set_audio_track(int p_idx); - virtual Ref<Texture> get_texture(); + virtual Ref<Texture> get_texture() const; virtual void update(float p_delta); virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata); @@ -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/webp/SCsub b/modules/webp/SCsub index fa3896c457..666628bb44 100644 --- a/modules/webp/SCsub +++ b/modules/webp/SCsub @@ -126,7 +126,7 @@ if env['builtin_libwebp']: ] thirdparty_sources = [thirdparty_dir + "src/" + file for file in thirdparty_sources] - env_webp.Append(CPPPATH=[thirdparty_dir, thirdparty_dir + "src/"]) + env_webp.Prepend(CPPPATH=[thirdparty_dir, thirdparty_dir + "src/"]) env_thirdparty = env_webp.Clone() env_thirdparty.disable_warnings() diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp index 928a0dcbd3..d1bfa20842 100644 --- a/modules/webp/image_loader_webp.cpp +++ b/modules/webp/image_loader_webp.cpp @@ -71,7 +71,7 @@ static PoolVector<uint8_t> _webp_lossy_pack(const Ref<Image> &p_image, float p_q w[3] = 'P'; copymem(&w[4], dst_buff, dst_size); free(dst_buff); - w = PoolVector<uint8_t>::Write(); + w.release(); return dst; } @@ -84,8 +84,7 @@ static Ref<Image> _webp_lossy_unpack(const PoolVector<uint8_t> &p_buffer) { ERR_FAIL_COND_V(r[0] != 'W' || r[1] != 'E' || r[2] != 'B' || r[3] != 'P', Ref<Image>()); WebPBitstreamFeatures features; if (WebPGetFeatures(&r[4], size, &features) != VP8_STATUS_OK) { - ERR_EXPLAIN("Error unpacking WEBP image:"); - ERR_FAIL_V(Ref<Image>()); + ERR_FAIL_V_MSG(Ref<Image>(), "Error unpacking WEBP image."); } /* @@ -107,10 +106,9 @@ static Ref<Image> _webp_lossy_unpack(const PoolVector<uint8_t> &p_buffer) { errdec = WebPDecodeRGBInto(&r[4], size, dst_w.ptr(), datasize, 3 * features.width) == NULL; } - //ERR_EXPLAIN("Error decoding webp! - "+p_file); - ERR_FAIL_COND_V(errdec, Ref<Image>()); + ERR_FAIL_COND_V_MSG(errdec, Ref<Image>(), "Failed decoding WebP image."); - dst_w = PoolVector<uint8_t>::Write(); + dst_w.release(); Ref<Image> img = memnew(Image(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image)); return img; @@ -122,7 +120,6 @@ Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p WebPBitstreamFeatures features; if (WebPGetFeatures(p_buffer, p_buffer_len, &features) != VP8_STATUS_OK) { - // ERR_EXPLAIN("Error decoding WEBP image"); ERR_FAIL_V(ERR_FILE_CORRUPT); } @@ -137,10 +134,9 @@ Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p } else { errdec = WebPDecodeRGBInto(p_buffer, p_buffer_len, dst_w.ptr(), datasize, 3 * features.width) == NULL; } - dst_w = PoolVector<uint8_t>::Write(); + dst_w.release(); - //ERR_EXPLAIN("Error decoding webp!"); - ERR_FAIL_COND_V(errdec, ERR_FILE_CORRUPT); + ERR_FAIL_COND_V_MSG(errdec, ERR_FILE_CORRUPT, "Failed decoding WebP image."); p_image->create(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image); @@ -171,8 +167,6 @@ Error ImageLoaderWEBP::load_image(Ref<Image> p_image, FileAccess *f, bool p_forc Error err = webp_load_image_from_buffer(p_image.ptr(), w.ptr(), src_image_len); - w = PoolVector<uint8_t>::Write(); - return err; } diff --git a/modules/webp/image_loader_webp.h b/modules/webp/image_loader_webp.h index 0c4e54df09..5a5c038017 100644 --- a/modules/webp/image_loader_webp.h +++ b/modules/webp/image_loader_webp.h @@ -33,9 +33,6 @@ #include "core/io/image_loader.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ class ImageLoaderWEBP : public ImageFormatLoader { public: diff --git a/modules/webrtc/SCsub b/modules/webrtc/SCsub new file mode 100644 index 0000000000..868553b879 --- /dev/null +++ b/modules/webrtc/SCsub @@ -0,0 +1,15 @@ +#!/usr/bin/env python + +Import('env') +Import('env_modules') + +# Thirdparty source files + +env_webrtc = env_modules.Clone() +use_gdnative = env_webrtc["module_gdnative_enabled"] + +if use_gdnative: # GDNative is retained in Javascript for export compatibility + env_webrtc.Append(CPPDEFINES=['WEBRTC_GDNATIVE_ENABLED']) + env_webrtc.Prepend(CPPPATH=["#modules/gdnative/include/"]) + +env_webrtc.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/webrtc/config.py b/modules/webrtc/config.py new file mode 100644 index 0000000000..48b4c33c5d --- /dev/null +++ b/modules/webrtc/config.py @@ -0,0 +1,15 @@ +def can_build(env, platform): + return True + +def configure(env): + pass + +def get_doc_classes(): + return [ + "WebRTCPeerConnection", + "WebRTCDataChannel", + "WebRTCMultiplayer" + ] + +def get_doc_path(): + return "doc_classes" diff --git a/modules/webrtc/doc_classes/WebRTCDataChannel.xml b/modules/webrtc/doc_classes/WebRTCDataChannel.xml new file mode 100644 index 0000000000..98715ee99b --- /dev/null +++ b/modules/webrtc/doc_classes/WebRTCDataChannel.xml @@ -0,0 +1,116 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="WebRTCDataChannel" inherits="PacketPeer" category="Core" version="3.2"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + <method name="close"> + <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 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" default="1"> + 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..605b1ef082 --- /dev/null +++ b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml @@ -0,0 +1,89 @@ +<?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> + <members> + <member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" override="true" default="false" /> + <member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="NetworkedMultiplayerPeer.TransferMode" default="2" /> + </members> + <constants> + </constants> +</class> diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml new file mode 100644 index 0000000000..26082d73a8 --- /dev/null +++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml @@ -0,0 +1,190 @@ +<?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]A[/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> + <methods> + <method name="add_ice_candidate"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="media" type="String"> + </argument> + <argument index="1" name="index" type="int"> + </argument> + <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"> + <return type="WebRTCDataChannel"> + </return> + <argument index="0" name="label" type="String"> + </argument> + <argument index="1" name="options" type="Dictionary" default="{ + +}"> + </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] + [b]Note:[/b] 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 [constant OK], [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"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="configuration" type="Dictionary" default="{ + +}"> + </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"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="type" type="String"> + </argument> + <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"> + <return type="int" enum="Error"> + </return> + <argument index="0" name="type" type="String"> + </argument> + <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> + <signals> + <signal name="data_channel_received"> + <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"> + <argument index="0" name="media" type="String"> + </argument> + <argument index="1" name="index" type="int"> + </argument> + <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"> + <argument index="0" name="type" type="String"> + </argument> + <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, none 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 new file mode 100644 index 0000000000..6f97842064 --- /dev/null +++ b/modules/webrtc/register_types.cpp @@ -0,0 +1,68 @@ +/*************************************************************************/ +/* register_types.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 "register_types.h" +#include "core/project_settings.h" +#include "webrtc_data_channel.h" +#include "webrtc_peer_connection.h" + +#ifdef JAVASCRIPT_ENABLED +#include "emscripten.h" +#include "webrtc_peer_connection_js.h" +#endif +#ifdef WEBRTC_GDNATIVE_ENABLED +#include "webrtc_data_channel_gdnative.h" +#include "webrtc_peer_connection_gdnative.h" +#endif +#include "webrtc_multiplayer.h" + +void register_webrtc_types() { +#define _SET_HINT(NAME, _VAL_, _MAX_) \ + GLOBAL_DEF(NAME, _VAL_); \ + ProjectSettings::get_singleton()->set_custom_property_info(NAME, PropertyInfo(Variant::INT, NAME, PROPERTY_HINT_RANGE, "2," #_MAX_ ",1,or_greater")); + + _SET_HINT(WRTC_IN_BUF, 64, 4096); + +#ifdef JAVASCRIPT_ENABLED + WebRTCPeerConnectionJS::make_default(); +#elif defined(WEBRTC_GDNATIVE_ENABLED) + WebRTCPeerConnectionGDNative::make_default(); +#endif + + ClassDB::register_custom_instance_class<WebRTCPeerConnection>(); +#ifdef WEBRTC_GDNATIVE_ENABLED + ClassDB::register_class<WebRTCPeerConnectionGDNative>(); + ClassDB::register_class<WebRTCDataChannelGDNative>(); +#endif + ClassDB::register_virtual_class<WebRTCDataChannel>(); + ClassDB::register_class<WebRTCMultiplayer>(); +} + +void unregister_webrtc_types() {} diff --git a/modules/webrtc/register_types.h b/modules/webrtc/register_types.h new file mode 100644 index 0000000000..4923547a95 --- /dev/null +++ b/modules/webrtc/register_types.h @@ -0,0 +1,32 @@ +/*************************************************************************/ +/* register_types.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. */ +/*************************************************************************/ + +void register_webrtc_types(); +void unregister_webrtc_types(); diff --git a/modules/webrtc/webrtc_data_channel.cpp b/modules/webrtc/webrtc_data_channel.cpp new file mode 100644 index 0000000000..7b3843410a --- /dev/null +++ b/modules/webrtc/webrtc_data_channel.cpp @@ -0,0 +1,66 @@ +/*************************************************************************/ +/* webrtc_data_channel.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_data_channel.h" +#include "core/project_settings.h" + +void WebRTCDataChannel::_bind_methods() { + ClassDB::bind_method(D_METHOD("poll"), &WebRTCDataChannel::poll); + ClassDB::bind_method(D_METHOD("close"), &WebRTCDataChannel::close); + + ClassDB::bind_method(D_METHOD("was_string_packet"), &WebRTCDataChannel::was_string_packet); + ClassDB::bind_method(D_METHOD("set_write_mode", "write_mode"), &WebRTCDataChannel::set_write_mode); + ClassDB::bind_method(D_METHOD("get_write_mode"), &WebRTCDataChannel::get_write_mode); + ClassDB::bind_method(D_METHOD("get_ready_state"), &WebRTCDataChannel::get_ready_state); + ClassDB::bind_method(D_METHOD("get_label"), &WebRTCDataChannel::get_label); + ClassDB::bind_method(D_METHOD("is_ordered"), &WebRTCDataChannel::is_ordered); + ClassDB::bind_method(D_METHOD("get_id"), &WebRTCDataChannel::get_id); + ClassDB::bind_method(D_METHOD("get_max_packet_life_time"), &WebRTCDataChannel::get_max_packet_life_time); + ClassDB::bind_method(D_METHOD("get_max_retransmits"), &WebRTCDataChannel::get_max_retransmits); + ClassDB::bind_method(D_METHOD("get_protocol"), &WebRTCDataChannel::get_protocol); + ClassDB::bind_method(D_METHOD("is_negotiated"), &WebRTCDataChannel::is_negotiated); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "write_mode", PROPERTY_HINT_ENUM), "set_write_mode", "get_write_mode"); + + BIND_ENUM_CONSTANT(WRITE_MODE_TEXT); + BIND_ENUM_CONSTANT(WRITE_MODE_BINARY); + + BIND_ENUM_CONSTANT(STATE_CONNECTING); + BIND_ENUM_CONSTANT(STATE_OPEN); + BIND_ENUM_CONSTANT(STATE_CLOSING); + BIND_ENUM_CONSTANT(STATE_CLOSED); +} + +WebRTCDataChannel::WebRTCDataChannel() { + _in_buffer_shift = nearest_shift((int)GLOBAL_GET(WRTC_IN_BUF) - 1) + 10; +} + +WebRTCDataChannel::~WebRTCDataChannel() { +} diff --git a/modules/webrtc/webrtc_data_channel.h b/modules/webrtc/webrtc_data_channel.h new file mode 100644 index 0000000000..7e2c08d9d7 --- /dev/null +++ b/modules/webrtc/webrtc_data_channel.h @@ -0,0 +1,89 @@ +/*************************************************************************/ +/* webrtc_data_channel.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_DATA_CHANNEL_H +#define WEBRTC_DATA_CHANNEL_H + +#include "core/io/packet_peer.h" + +#define WRTC_IN_BUF "network/limits/webrtc/max_channel_in_buffer_kb" + +class WebRTCDataChannel : public PacketPeer { + GDCLASS(WebRTCDataChannel, PacketPeer); + +public: + enum WriteMode { + WRITE_MODE_TEXT, + WRITE_MODE_BINARY, + }; + + enum ChannelState { + STATE_CONNECTING, + STATE_OPEN, + STATE_CLOSING, + STATE_CLOSED + }; + +protected: + unsigned int _in_buffer_shift; + + static void _bind_methods(); + +public: + virtual void set_write_mode(WriteMode mode) = 0; + virtual WriteMode get_write_mode() const = 0; + virtual bool was_string_packet() const = 0; + + virtual ChannelState get_ready_state() const = 0; + virtual String get_label() const = 0; + virtual bool is_ordered() const = 0; + virtual int get_id() const = 0; + virtual int get_max_packet_life_time() const = 0; + virtual int get_max_retransmits() const = 0; + virtual String get_protocol() const = 0; + virtual bool is_negotiated() const = 0; + + virtual Error poll() = 0; + virtual void close() = 0; + + /** Inherited from PacketPeer: **/ + virtual int get_available_packet_count() const = 0; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) = 0; ///< buffer is GONE after next get_packet + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) = 0; + + virtual int get_max_packet_size() const = 0; + + WebRTCDataChannel(); + ~WebRTCDataChannel(); +}; + +VARIANT_ENUM_CAST(WebRTCDataChannel::WriteMode); +VARIANT_ENUM_CAST(WebRTCDataChannel::ChannelState); +#endif // WEBRTC_DATA_CHANNEL_H diff --git a/modules/webrtc/webrtc_data_channel_gdnative.cpp b/modules/webrtc/webrtc_data_channel_gdnative.cpp new file mode 100644 index 0000000000..6362634626 --- /dev/null +++ b/modules/webrtc/webrtc_data_channel_gdnative.cpp @@ -0,0 +1,137 @@ +/*************************************************************************/ +/* webrtc_data_channel_gdnative.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. */ +/*************************************************************************/ + +#ifdef WEBRTC_GDNATIVE_ENABLED + +#include "webrtc_data_channel_gdnative.h" +#include "core/io/resource_loader.h" +#include "modules/gdnative/nativescript/nativescript.h" + +void WebRTCDataChannelGDNative::_bind_methods() { + ADD_PROPERTY_DEFAULT("write_mode", WRITE_MODE_BINARY); +} + +WebRTCDataChannelGDNative::WebRTCDataChannelGDNative() { + interface = NULL; +} + +WebRTCDataChannelGDNative::~WebRTCDataChannelGDNative() { +} + +Error WebRTCDataChannelGDNative::poll() { + ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED); + return (Error)interface->poll(interface->data); +} + +void WebRTCDataChannelGDNative::close() { + ERR_FAIL_COND(interface == NULL); + interface->close(interface->data); +} + +void WebRTCDataChannelGDNative::set_write_mode(WriteMode p_mode) { + ERR_FAIL_COND(interface == NULL); + interface->set_write_mode(interface->data, p_mode); +} + +WebRTCDataChannel::WriteMode WebRTCDataChannelGDNative::get_write_mode() const { + ERR_FAIL_COND_V(interface == NULL, WRITE_MODE_BINARY); + return (WriteMode)interface->get_write_mode(interface->data); +} + +bool WebRTCDataChannelGDNative::was_string_packet() const { + ERR_FAIL_COND_V(interface == NULL, false); + return interface->was_string_packet(interface->data); +} + +WebRTCDataChannel::ChannelState WebRTCDataChannelGDNative::get_ready_state() const { + ERR_FAIL_COND_V(interface == NULL, STATE_CLOSED); + return (ChannelState)interface->get_ready_state(interface->data); +} + +String WebRTCDataChannelGDNative::get_label() const { + ERR_FAIL_COND_V(interface == NULL, ""); + return String(interface->get_label(interface->data)); +} + +bool WebRTCDataChannelGDNative::is_ordered() const { + ERR_FAIL_COND_V(interface == NULL, false); + return interface->is_ordered(interface->data); +} + +int WebRTCDataChannelGDNative::get_id() const { + ERR_FAIL_COND_V(interface == NULL, -1); + return interface->get_id(interface->data); +} + +int WebRTCDataChannelGDNative::get_max_packet_life_time() const { + ERR_FAIL_COND_V(interface == NULL, -1); + return interface->get_max_packet_life_time(interface->data); +} + +int WebRTCDataChannelGDNative::get_max_retransmits() const { + ERR_FAIL_COND_V(interface == NULL, -1); + return interface->get_max_retransmits(interface->data); +} + +String WebRTCDataChannelGDNative::get_protocol() const { + ERR_FAIL_COND_V(interface == NULL, ""); + return String(interface->get_protocol(interface->data)); +} + +bool WebRTCDataChannelGDNative::is_negotiated() const { + ERR_FAIL_COND_V(interface == NULL, false); + return interface->is_negotiated(interface->data); +} + +Error WebRTCDataChannelGDNative::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED); + return (Error)interface->get_packet(interface->data, r_buffer, &r_buffer_size); +} + +Error WebRTCDataChannelGDNative::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED); + return (Error)interface->put_packet(interface->data, p_buffer, p_buffer_size); +} + +int WebRTCDataChannelGDNative::get_max_packet_size() const { + ERR_FAIL_COND_V(interface == NULL, 0); + return interface->get_max_packet_size(interface->data); +} + +int WebRTCDataChannelGDNative::get_available_packet_count() const { + ERR_FAIL_COND_V(interface == NULL, 0); + return interface->get_available_packet_count(interface->data); +} + +void WebRTCDataChannelGDNative::set_native_webrtc_data_channel(const godot_net_webrtc_data_channel *p_impl) { + interface = p_impl; +} + +#endif // WEBRTC_GDNATIVE_ENABLED diff --git a/modules/webrtc/webrtc_data_channel_gdnative.h b/modules/webrtc/webrtc_data_channel_gdnative.h new file mode 100644 index 0000000000..3685f86353 --- /dev/null +++ b/modules/webrtc/webrtc_data_channel_gdnative.h @@ -0,0 +1,80 @@ +/*************************************************************************/ +/* webrtc_data_channel_gdnative.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. */ +/*************************************************************************/ + +#ifdef WEBRTC_GDNATIVE_ENABLED + +#ifndef WEBRTC_DATA_CHANNEL_GDNATIVE_H +#define WEBRTC_DATA_CHANNEL_GDNATIVE_H + +#include "modules/gdnative/include/net/godot_net.h" +#include "webrtc_data_channel.h" + +class WebRTCDataChannelGDNative : public WebRTCDataChannel { + GDCLASS(WebRTCDataChannelGDNative, WebRTCDataChannel); + +protected: + static void _bind_methods(); + +private: + const godot_net_webrtc_data_channel *interface; + +public: + void set_native_webrtc_data_channel(const godot_net_webrtc_data_channel *p_impl); + + virtual void set_write_mode(WriteMode mode); + virtual WriteMode get_write_mode() const; + virtual bool was_string_packet() const; + + virtual ChannelState get_ready_state() const; + virtual String get_label() const; + virtual bool is_ordered() const; + virtual int get_id() const; + virtual int get_max_packet_life_time() const; + virtual int get_max_retransmits() const; + virtual String get_protocol() const; + virtual bool is_negotiated() const; + + virtual Error poll(); + virtual void close(); + + /** Inherited from PacketPeer: **/ + virtual int get_available_packet_count() const; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); + + virtual int get_max_packet_size() const; + + WebRTCDataChannelGDNative(); + ~WebRTCDataChannelGDNative(); +}; + +#endif // WEBRTC_DATA_CHANNEL_GDNATIVE_H + +#endif // WEBRTC_GDNATIVE_ENABLED diff --git a/modules/webrtc/webrtc_data_channel_js.cpp b/modules/webrtc/webrtc_data_channel_js.cpp new file mode 100644 index 0000000000..2edd212a50 --- /dev/null +++ b/modules/webrtc/webrtc_data_channel_js.cpp @@ -0,0 +1,365 @@ +/*************************************************************************/ +/* webrtc_data_channel_js.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. */ +/*************************************************************************/ + +#ifdef JAVASCRIPT_ENABLED + +#include "webrtc_data_channel_js.h" +#include "emscripten.h" + +extern "C" { +EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_error(void *obj) { + WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj); + peer->_on_error(); +} + +EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_open(void *obj) { + WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj); + peer->_on_open(); +} + +EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_close(void *obj) { + WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj); + peer->_on_close(); +} + +EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_message(void *obj, uint8_t *p_data, uint32_t p_size, bool p_is_string) { + WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj); + peer->_on_message(p_data, p_size, p_is_string); +} +} + +void WebRTCDataChannelJS::_on_open() { + in_buffer.resize(_in_buffer_shift); +} + +void WebRTCDataChannelJS::_on_close() { + close(); +} + +void WebRTCDataChannelJS::_on_error() { + close(); +} + +void WebRTCDataChannelJS::_on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string) { + + ERR_FAIL_COND_MSG(in_buffer.space_left() < (int)(p_size + 5), "Buffer full! Dropping data."); + + uint8_t is_string = p_is_string ? 1 : 0; + in_buffer.write((uint8_t *)&p_size, 4); + in_buffer.write((uint8_t *)&is_string, 1); + in_buffer.write(p_data, p_size); + queue_count++; +} + +void WebRTCDataChannelJS::close() { + in_buffer.resize(0); + queue_count = 0; + _was_string = false; + /* clang-format off */ + EM_ASM({ + var dict = Module.IDHandler.get($0); + if (!dict) return; + var channel = dict["channel"]; + channel.onopen = null; + channel.onclose = null; + channel.onerror = null; + channel.onmessage = null; + channel.close(); + }, _js_id); + /* clang-format on */ +} + +Error WebRTCDataChannelJS::poll() { + return OK; +} + +WebRTCDataChannelJS::ChannelState WebRTCDataChannelJS::get_ready_state() const { + /* clang-format off */ + return (ChannelState) EM_ASM_INT({ + var dict = Module.IDHandler.get($0); + if (!dict) return 3; // CLOSED + var channel = dict["channel"]; + switch(channel.readyState) { + case "connecting": + return 0; + case "open": + return 1; + case "closing": + return 2; + case "closed": + return 3; + } + return 3; // CLOSED + }, _js_id); + /* clang-format on */ +} + +int WebRTCDataChannelJS::get_available_packet_count() const { + return queue_count; +} + +Error WebRTCDataChannelJS::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + ERR_FAIL_COND_V(get_ready_state() != STATE_OPEN, ERR_UNCONFIGURED); + + if (queue_count == 0) + return ERR_UNAVAILABLE; + + uint32_t to_read = 0; + uint32_t left = 0; + uint8_t is_string = 0; + r_buffer_size = 0; + + in_buffer.read((uint8_t *)&to_read, 4); + --queue_count; + left = in_buffer.data_left(); + + if (left < to_read + 1) { + in_buffer.advance_read(left); + return FAILED; + } + + in_buffer.read(&is_string, 1); + _was_string = is_string == 1; + in_buffer.read(packet_buffer, to_read); + *r_buffer = packet_buffer; + r_buffer_size = to_read; + + return OK; +} + +Error WebRTCDataChannelJS::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + ERR_FAIL_COND_V(get_ready_state() != STATE_OPEN, ERR_UNCONFIGURED); + + int is_bin = _write_mode == WebRTCDataChannel::WRITE_MODE_BINARY ? 1 : 0; + + /* clang-format off */ + EM_ASM({ + var dict = Module.IDHandler.get($0); + var channel = dict["channel"]; + var bytes_array = new Uint8Array($2); + var i = 0; + + for(i=0; i<$2; i++) { + bytes_array[i] = getValue($1+i, 'i8'); + } + + if ($3) { + channel.send(bytes_array.buffer); + } else { + var string = new TextDecoder("utf-8").decode(bytes_array); + channel.send(string); + } + }, _js_id, p_buffer, p_buffer_size, is_bin); + /* clang-format on */ + + return OK; +} + +int WebRTCDataChannelJS::get_max_packet_size() const { + return 1200; +} + +void WebRTCDataChannelJS::set_write_mode(WriteMode p_mode) { + _write_mode = p_mode; +} + +WebRTCDataChannel::WriteMode WebRTCDataChannelJS::get_write_mode() const { + return _write_mode; +} + +bool WebRTCDataChannelJS::was_string_packet() const { + return _was_string; +} + +String WebRTCDataChannelJS::get_label() const { + return _label; +} + +/* clang-format off */ +#define _JS_GET(PROP, DEF) \ +EM_ASM_INT({ \ + var dict = Module.IDHandler.get($0); \ + if (!dict || !dict["channel"]) { \ + 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, true); +} + +int WebRTCDataChannelJS::get_id() const { + return _JS_GET(id, 65535); +} + +int WebRTCDataChannelJS::get_max_packet_life_time() const { + // 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, 65535); +} + +String WebRTCDataChannelJS::get_protocol() const { + return _protocol; +} + +bool WebRTCDataChannelJS::is_negotiated() const { + return _JS_GET(negotiated, false); +} + +WebRTCDataChannelJS::WebRTCDataChannelJS() { + queue_count = 0; + _was_string = false; + _write_mode = WRITE_MODE_BINARY; + _js_id = 0; +} + +WebRTCDataChannelJS::WebRTCDataChannelJS(int js_id) { + queue_count = 0; + _was_string = false; + _write_mode = WRITE_MODE_BINARY; + _js_id = js_id; + + /* clang-format off */ + EM_ASM({ + var c_ptr = $0; + var dict = Module.IDHandler.get($1); + if (!dict) return; + var channel = dict["channel"]; + dict["ptr"] = c_ptr; + + channel.binaryType = "arraybuffer"; + channel.onopen = function (evt) { + ccall("_emrtc_on_ch_open", + "void", + ["number"], + [c_ptr] + ); + }; + channel.onclose = function (evt) { + ccall("_emrtc_on_ch_close", + "void", + ["number"], + [c_ptr] + ); + }; + channel.onerror = function (evt) { + ccall("_emrtc_on_ch_error", + "void", + ["number"], + [c_ptr] + ); + }; + channel.onmessage = function(event) { + var buffer; + var is_string = 0; + if (event.data instanceof ArrayBuffer) { + buffer = new Uint8Array(event.data); + } else if (event.data instanceof Blob) { + console.error("Blob type not supported"); + return; + } else if (typeof event.data === "string") { + is_string = 1; + var enc = new TextEncoder("utf-8"); + buffer = new Uint8Array(enc.encode(event.data)); + } else { + console.error("Unknown message type"); + return; + } + var len = buffer.length*buffer.BYTES_PER_ELEMENT; + var out = Module._malloc(len); + Module.HEAPU8.set(buffer, out); + ccall("_emrtc_on_ch_message", + "void", + ["number", "number", "number", "number"], + [c_ptr, out, len, is_string] + ); + Module._free(out); + } + + }, this, js_id); + // Parse label + char *str; + str = (char *)EM_ASM_INT({ + var dict = Module.IDHandler.get($0); + if (!dict || !dict["channel"]) return 0; + var str = dict["channel"].label; + var len = lengthBytesUTF8(str)+1; + var ptr = _malloc(str); + stringToUTF8(str, ptr, len+1); + return ptr; + }, js_id); + if(str != NULL) { + _label.parse_utf8(str); + EM_ASM({ _free($0) }, str); + } + str = (char *)EM_ASM_INT({ + var dict = Module.IDHandler.get($0); + if (!dict || !dict["channel"]) return 0; + var str = dict["channel"].protocol; + var len = lengthBytesUTF8(str)+1; + var ptr = _malloc(str); + stringToUTF8(str, ptr, len+1); + return ptr; + }, js_id); + if(str != NULL) { + _protocol.parse_utf8(str); + EM_ASM({ _free($0) }, str); + } + /* clang-format on */ +} + +WebRTCDataChannelJS::~WebRTCDataChannelJS() { + close(); + /* clang-format off */ + EM_ASM({ + Module.IDHandler.remove($0); + }, _js_id); + /* clang-format on */ +}; +#endif diff --git a/modules/webrtc/webrtc_data_channel_js.h b/modules/webrtc/webrtc_data_channel_js.h new file mode 100644 index 0000000000..b87f8e9326 --- /dev/null +++ b/modules/webrtc/webrtc_data_channel_js.h @@ -0,0 +1,93 @@ +/*************************************************************************/ +/* webrtc_data_channel_js.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. */ +/*************************************************************************/ + +#ifdef JAVASCRIPT_ENABLED + +#ifndef WEBRTC_DATA_CHANNEL_JS_H +#define WEBRTC_DATA_CHANNEL_JS_H + +#include "webrtc_data_channel.h" + +class WebRTCDataChannelJS : public WebRTCDataChannel { + GDCLASS(WebRTCDataChannelJS, WebRTCDataChannel); + +private: + String _label; + String _protocol; + + bool _was_string; + WriteMode _write_mode; + + enum { + PACKET_BUFFER_SIZE = 65536 - 5 // 4 bytes for the size, 1 for for type + }; + + int _js_id; + RingBuffer<uint8_t> in_buffer; + int queue_count; + uint8_t packet_buffer[PACKET_BUFFER_SIZE]; + +public: + void _on_open(); + void _on_close(); + void _on_error(); + void _on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string); + + virtual void set_write_mode(WriteMode mode); + virtual WriteMode get_write_mode() const; + virtual bool was_string_packet() const; + + virtual ChannelState get_ready_state() const; + virtual String get_label() const; + virtual bool is_ordered() const; + virtual int get_id() const; + virtual int get_max_packet_life_time() const; + virtual int get_max_retransmits() const; + virtual String get_protocol() const; + virtual bool is_negotiated() const; + + virtual Error poll(); + virtual void close(); + + /** Inherited from PacketPeer: **/ + virtual int get_available_packet_count() const; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); + + virtual int get_max_packet_size() const; + + WebRTCDataChannelJS(); + WebRTCDataChannelJS(int js_id); + ~WebRTCDataChannelJS(); +}; + +#endif // WEBRTC_DATA_CHANNEL_JS_H + +#endif // JAVASCRIPT_ENABLED diff --git a/modules/webrtc/webrtc_multiplayer.cpp b/modules/webrtc/webrtc_multiplayer.cpp new file mode 100644 index 0000000000..a759b17b83 --- /dev/null +++ b/modules/webrtc/webrtc_multiplayer.cpp @@ -0,0 +1,382 @@ +/*************************************************************************/ +/* 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); + ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + "."); + + 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/mono/editor/godotsharp_builds.h b/modules/webrtc/webrtc_multiplayer.h index 652d30538a..82bbfd4f68 100644 --- a/modules/mono/editor/godotsharp_builds.h +++ b/modules/webrtc/webrtc_multiplayer.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* godotsharp_builds.h */ +/* webrtc_multiplayer.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,76 +28,89 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GODOTSHARP_BUILDS_H -#define GODOTSHARP_BUILDS_H +#ifndef WEBRTC_MULTIPLAYER_H +#define WEBRTC_MULTIPLAYER_H -#include "../mono_gd/gd_mono.h" -#include "mono_bottom_panel.h" -#include "mono_build_info.h" +#include "core/io/networked_multiplayer_peer.h" +#include "webrtc_peer_connection.h" -typedef void (*GodotSharpBuild_ExitCallback)(int); +class WebRTCMultiplayer : public NetworkedMultiplayerPeer { -class GodotSharpBuilds { + GDCLASS(WebRTCMultiplayer, NetworkedMultiplayerPeer); + +protected: + static void _bind_methods(); private: - struct BuildProcess { - Ref<MonoGCHandle> build_instance; - MonoBuildInfo build_info; - MonoBuildTab *build_tab; - GodotSharpBuild_ExitCallback exit_callback; - bool exited; - int exit_code; - - void on_exit(int p_exit_code); - void start(bool p_blocking = false); - - BuildProcess() {} - BuildProcess(const MonoBuildInfo &p_build_info, GodotSharpBuild_ExitCallback p_callback = NULL); + enum { + CH_RELIABLE = 0, + CH_ORDERED = 1, + CH_UNRELIABLE = 2, + CH_RESERVED_MAX = 3 }; - HashMap<MonoBuildInfo, BuildProcess, MonoBuildInfo::Hasher> builds; - - static String _api_folder_name(APIAssembly::Type p_api_type); + class ConnectedPeer : public Reference { - static GodotSharpBuilds *singleton; + public: + Ref<WebRTCPeerConnection> connection; + List<Ref<WebRTCDataChannel> > channels; + bool connected; -public: - enum BuildTool { - MSBUILD_MONO, -#ifdef WINDOWS_ENABLED - MSBUILD_VS, -#endif - XBUILD // Deprecated + ConnectedPeer() { + connected = false; + for (int i = 0; i < CH_RESERVED_MAX; i++) + channels.push_front(Ref<WebRTCDataChannel>()); + } }; - _FORCE_INLINE_ static GodotSharpBuilds *get_singleton() { return singleton; } + 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; - static void register_internal_calls(); + Map<int, Ref<ConnectedPeer> > peer_map; - static void show_build_error_dialog(const String &p_message); + void _peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict); + void _find_next_peer(); - static const char *get_msbuild_issues_filename() { return "msbuild_issues.csv"; } - static const char *get_msbuild_log_filename() { return "msbuild_log.txt"; } +public: + WebRTCMultiplayer(); + ~WebRTCMultiplayer(); - void build_exit_callback(const MonoBuildInfo &p_build_info, int p_exit_code); + 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(); - void restart_build(MonoBuildTab *p_build_tab); - void stop_build(MonoBuildTab *p_build_tab); + // 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; - bool build(const MonoBuildInfo &p_build_info); - bool build_async(const MonoBuildInfo &p_build_info, GodotSharpBuild_ExitCallback p_callback = NULL); + // NetworkedMultiplayerPeer + void set_transfer_mode(TransferMode p_mode); + TransferMode get_transfer_mode() const; + void set_target_peer(int p_peer_id); - static bool build_api_sln(const String &p_api_sln_dir, const String &p_config); - static bool copy_api_assembly(const String &p_src_dir, const String &p_dst_dir, const String &p_assembly_name, APIAssembly::Type p_api_type); + int get_unique_id() const; + int get_packet_peer() const; - static bool make_api_assembly(APIAssembly::Type p_api_type); + bool is_server() const; - static bool build_project_blocking(const String &p_config); + void poll(); - static bool editor_build_callback(); + void set_refuse_new_connections(bool p_enable); + bool is_refusing_new_connections() const; - GodotSharpBuilds(); - ~GodotSharpBuilds(); + ConnectionStatus get_connection_status() const; }; -#endif // GODOTSHARP_BUILDS_H +#endif diff --git a/modules/webrtc/webrtc_peer_connection.cpp b/modules/webrtc/webrtc_peer_connection.cpp new file mode 100644 index 0000000000..69c7a51a40 --- /dev/null +++ b/modules/webrtc/webrtc_peer_connection.cpp @@ -0,0 +1,75 @@ +/*************************************************************************/ +/* webrtc_peer_connection.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_peer_connection.h" + +WebRTCPeerConnection *(*WebRTCPeerConnection::_create)() = NULL; + +Ref<WebRTCPeerConnection> WebRTCPeerConnection::create_ref() { + + return create(); +} + +WebRTCPeerConnection *WebRTCPeerConnection::create() { + + if (!_create) + return NULL; + return _create(); +} + +void WebRTCPeerConnection::_bind_methods() { + ClassDB::bind_method(D_METHOD("initialize", "configuration"), &WebRTCPeerConnection::initialize, DEFVAL(Dictionary())); + ClassDB::bind_method(D_METHOD("create_data_channel", "label", "options"), &WebRTCPeerConnection::create_data_channel, DEFVAL(Dictionary())); + ClassDB::bind_method(D_METHOD("create_offer"), &WebRTCPeerConnection::create_offer); + ClassDB::bind_method(D_METHOD("set_local_description", "type", "sdp"), &WebRTCPeerConnection::set_local_description); + ClassDB::bind_method(D_METHOD("set_remote_description", "type", "sdp"), &WebRTCPeerConnection::set_remote_description); + ClassDB::bind_method(D_METHOD("add_ice_candidate", "media", "index", "name"), &WebRTCPeerConnection::add_ice_candidate); + ClassDB::bind_method(D_METHOD("poll"), &WebRTCPeerConnection::poll); + ClassDB::bind_method(D_METHOD("close"), &WebRTCPeerConnection::close); + + ClassDB::bind_method(D_METHOD("get_connection_state"), &WebRTCPeerConnection::get_connection_state); + + ADD_SIGNAL(MethodInfo("session_description_created", PropertyInfo(Variant::STRING, "type"), PropertyInfo(Variant::STRING, "sdp"))); + ADD_SIGNAL(MethodInfo("ice_candidate_created", PropertyInfo(Variant::STRING, "media"), PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::STRING, "name"))); + ADD_SIGNAL(MethodInfo("data_channel_received", PropertyInfo(Variant::OBJECT, "channel"))); + + BIND_ENUM_CONSTANT(STATE_NEW); + BIND_ENUM_CONSTANT(STATE_CONNECTING); + BIND_ENUM_CONSTANT(STATE_CONNECTED); + BIND_ENUM_CONSTANT(STATE_DISCONNECTED); + BIND_ENUM_CONSTANT(STATE_FAILED); + BIND_ENUM_CONSTANT(STATE_CLOSED); +} + +WebRTCPeerConnection::WebRTCPeerConnection() { +} + +WebRTCPeerConnection::~WebRTCPeerConnection() { +} diff --git a/modules/webrtc/webrtc_peer_connection.h b/modules/webrtc/webrtc_peer_connection.h new file mode 100644 index 0000000000..7be1390dab --- /dev/null +++ b/modules/webrtc/webrtc_peer_connection.h @@ -0,0 +1,74 @@ +/*************************************************************************/ +/* webrtc_peer_connection.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_PEER_CONNECTION_H +#define WEBRTC_PEER_CONNECTION_H + +#include "core/io/packet_peer.h" +#include "modules/webrtc/webrtc_data_channel.h" + +class WebRTCPeerConnection : public Reference { + GDCLASS(WebRTCPeerConnection, Reference); + +public: + enum ConnectionState { + STATE_NEW, + STATE_CONNECTING, + STATE_CONNECTED, + STATE_DISCONNECTED, + STATE_FAILED, + STATE_CLOSED + }; + +protected: + static void _bind_methods(); + static WebRTCPeerConnection *(*_create)(); + +public: + virtual ConnectionState get_connection_state() const = 0; + + virtual Error initialize(Dictionary p_config = Dictionary()) = 0; + virtual Ref<WebRTCDataChannel> create_data_channel(String p_label, Dictionary p_options = Dictionary()) = 0; + virtual Error create_offer() = 0; + virtual Error set_remote_description(String type, String sdp) = 0; + virtual Error set_local_description(String type, String sdp) = 0; + virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) = 0; + virtual Error poll() = 0; + virtual void close() = 0; + + static Ref<WebRTCPeerConnection> create_ref(); + static WebRTCPeerConnection *create(); + + WebRTCPeerConnection(); + ~WebRTCPeerConnection(); +}; + +VARIANT_ENUM_CAST(WebRTCPeerConnection::ConnectionState); +#endif // WEBRTC_PEER_CONNECTION_H diff --git a/modules/webrtc/webrtc_peer_connection_gdnative.cpp b/modules/webrtc/webrtc_peer_connection_gdnative.cpp new file mode 100644 index 0000000000..5e9dcb5366 --- /dev/null +++ b/modules/webrtc/webrtc_peer_connection_gdnative.cpp @@ -0,0 +1,122 @@ +/*************************************************************************/ +/* webrtc_peer_connection_gdnative.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. */ +/*************************************************************************/ + +#ifdef WEBRTC_GDNATIVE_ENABLED + +#include "webrtc_peer_connection_gdnative.h" + +#include "core/io/resource_loader.h" +#include "modules/gdnative/nativescript/nativescript.h" +#include "webrtc_data_channel_gdnative.h" + +const godot_net_webrtc_library *WebRTCPeerConnectionGDNative::default_library = NULL; + +Error WebRTCPeerConnectionGDNative::set_default_library(const godot_net_webrtc_library *p_lib) { + if (default_library) { + const godot_net_webrtc_library *old = default_library; + default_library = NULL; + old->unregistered(); + } + default_library = p_lib; + return OK; // Maybe add version check and fail accordingly +} + +WebRTCPeerConnection *WebRTCPeerConnectionGDNative::_create() { + + WebRTCPeerConnectionGDNative *obj = memnew(WebRTCPeerConnectionGDNative); + ERR_FAIL_COND_V_MSG(!default_library, obj, "Default GDNative WebRTC implementation not defined."); + + // Call GDNative constructor + Error err = (Error)default_library->create_peer_connection(obj); + ERR_FAIL_COND_V_MSG(err != OK, obj, "GDNative default library constructor returned an error."); + + return obj; +} + +void WebRTCPeerConnectionGDNative::_bind_methods() { +} + +WebRTCPeerConnectionGDNative::WebRTCPeerConnectionGDNative() { + interface = NULL; +} + +WebRTCPeerConnectionGDNative::~WebRTCPeerConnectionGDNative() { +} + +Error WebRTCPeerConnectionGDNative::initialize(Dictionary p_config) { + ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED); + return (Error)interface->initialize(interface->data, (const godot_dictionary *)&p_config); +} + +Ref<WebRTCDataChannel> WebRTCPeerConnectionGDNative::create_data_channel(String p_label, Dictionary p_options) { + ERR_FAIL_COND_V(interface == NULL, NULL); + return (WebRTCDataChannel *)interface->create_data_channel(interface->data, p_label.utf8().get_data(), (const godot_dictionary *)&p_options); +} + +Error WebRTCPeerConnectionGDNative::create_offer() { + ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED); + return (Error)interface->create_offer(interface->data); +} + +Error WebRTCPeerConnectionGDNative::set_local_description(String p_type, String p_sdp) { + ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED); + return (Error)interface->set_local_description(interface->data, p_type.utf8().get_data(), p_sdp.utf8().get_data()); +} + +Error WebRTCPeerConnectionGDNative::set_remote_description(String p_type, String p_sdp) { + ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED); + return (Error)interface->set_remote_description(interface->data, p_type.utf8().get_data(), p_sdp.utf8().get_data()); +} + +Error WebRTCPeerConnectionGDNative::add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) { + ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED); + return (Error)interface->add_ice_candidate(interface->data, sdpMidName.utf8().get_data(), sdpMlineIndexName, sdpName.utf8().get_data()); +} + +Error WebRTCPeerConnectionGDNative::poll() { + ERR_FAIL_COND_V(interface == NULL, ERR_UNCONFIGURED); + return (Error)interface->poll(interface->data); +} + +void WebRTCPeerConnectionGDNative::close() { + ERR_FAIL_COND(interface == NULL); + interface->close(interface->data); +} + +WebRTCPeerConnection::ConnectionState WebRTCPeerConnectionGDNative::get_connection_state() const { + ERR_FAIL_COND_V(interface == NULL, STATE_DISCONNECTED); + return (ConnectionState)interface->get_connection_state(interface->data); +} + +void WebRTCPeerConnectionGDNative::set_native_webrtc_peer_connection(const godot_net_webrtc_peer_connection *p_impl) { + interface = p_impl; +} + +#endif // WEBRTC_GDNATIVE_ENABLED diff --git a/modules/webrtc/webrtc_peer_connection_gdnative.h b/modules/webrtc/webrtc_peer_connection_gdnative.h new file mode 100644 index 0000000000..0a281c3d89 --- /dev/null +++ b/modules/webrtc/webrtc_peer_connection_gdnative.h @@ -0,0 +1,73 @@ +/*************************************************************************/ +/* webrtc_peer_connection_gdnative.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. */ +/*************************************************************************/ + +#ifdef WEBRTC_GDNATIVE_ENABLED + +#ifndef WEBRTC_PEER_CONNECTION_GDNATIVE_H +#define WEBRTC_PEER_CONNECTION_GDNATIVE_H + +#include "modules/gdnative/include/net/godot_net.h" +#include "webrtc_peer_connection.h" + +class WebRTCPeerConnectionGDNative : public WebRTCPeerConnection { + GDCLASS(WebRTCPeerConnectionGDNative, WebRTCPeerConnection); + +protected: + static void _bind_methods(); + static WebRTCPeerConnection *_create(); + +private: + static const godot_net_webrtc_library *default_library; + const godot_net_webrtc_peer_connection *interface; + +public: + static Error set_default_library(const godot_net_webrtc_library *p_library); + static void make_default() { WebRTCPeerConnection::_create = WebRTCPeerConnectionGDNative::_create; } + + void set_native_webrtc_peer_connection(const godot_net_webrtc_peer_connection *p_impl); + + virtual ConnectionState get_connection_state() const; + + virtual Error initialize(Dictionary p_config = Dictionary()); + virtual Ref<WebRTCDataChannel> create_data_channel(String p_label, Dictionary p_options = Dictionary()); + virtual Error create_offer(); + virtual Error set_remote_description(String type, String sdp); + virtual Error set_local_description(String type, String sdp); + virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName); + virtual Error poll(); + virtual void close(); + + WebRTCPeerConnectionGDNative(); + ~WebRTCPeerConnectionGDNative(); +}; + +#endif // WEBRTC_PEER_CONNECTION_GDNATIVE_H + +#endif // WEBRTC_GDNATIVE_ENABLED diff --git a/modules/webrtc/webrtc_peer_connection_js.cpp b/modules/webrtc/webrtc_peer_connection_js.cpp new file mode 100644 index 0000000000..9758ab3644 --- /dev/null +++ b/modules/webrtc/webrtc_peer_connection_js.cpp @@ -0,0 +1,314 @@ +/*************************************************************************/ +/* webrtc_peer_connection_js.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. */ +/*************************************************************************/ + +#ifdef JAVASCRIPT_ENABLED + +#include "webrtc_peer_connection_js.h" + +#include "webrtc_data_channel_js.h" + +#include "core/io/json.h" +#include "emscripten.h" + +extern "C" { +EMSCRIPTEN_KEEPALIVE void _emrtc_on_ice_candidate(void *obj, char *p_MidName, int p_MlineIndexName, char *p_sdpName) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj); + peer->emit_signal("ice_candidate_created", String(p_MidName), p_MlineIndexName, String(p_sdpName)); +} + +EMSCRIPTEN_KEEPALIVE void _emrtc_session_description_created(void *obj, char *p_type, char *p_offer) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj); + peer->emit_signal("session_description_created", String(p_type), String(p_offer)); +} + +EMSCRIPTEN_KEEPALIVE void _emrtc_on_connection_state_changed(void *obj) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj); + peer->_on_connection_state_changed(); +} + +EMSCRIPTEN_KEEPALIVE void _emrtc_on_error() { + ERR_PRINT("RTCPeerConnection error!"); +} + +EMSCRIPTEN_KEEPALIVE void _emrtc_emit_channel(void *obj, int p_id) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj); + peer->emit_signal("data_channel_received", Ref<WebRTCDataChannelJS>(new WebRTCDataChannelJS(p_id))); +} +} + +void _emrtc_create_pc(int p_id, const Dictionary &p_config) { + String config = JSON::print(p_config); + /* clang-format off */ + EM_ASM({ + var dict = Module.IDHandler.get($0); + var c_ptr = dict["ptr"]; + var config = JSON.parse(UTF8ToString($1)); + // Setup local connaction + var conn = null; + try { + conn = new RTCPeerConnection(config); + } catch (e) { + console.log(e); + return; + } + conn.oniceconnectionstatechange = function(event) { + if (!Module.IDHandler.get($0)) return; + ccall("_emrtc_on_connection_state_changed", "void", ["number"], [c_ptr]); + }; + conn.onicecandidate = function(event) { + if (!Module.IDHandler.get($0)) return; + if (!event.candidate) return; + + var c = event.candidate; + // should emit on ice candidate + ccall("_emrtc_on_ice_candidate", + "void", + ["number", "string", "number", "string"], + [c_ptr, c.sdpMid, c.sdpMLineIndex, c.candidate] + ); + }; + conn.ondatachannel = function (evt) { + var dict = Module.IDHandler.get($0); + if (!dict) { + return; + } + var id = Module.IDHandler.add({"channel": evt.channel, "ptr": null}); + ccall("_emrtc_emit_channel", + "void", + ["number", "number"], + [c_ptr, id] + ); + }; + dict["conn"] = conn; + }, p_id, config.utf8().get_data()); + /* clang-format on */ +} + +void WebRTCPeerConnectionJS::_on_connection_state_changed() { + /* clang-format off */ + _conn_state = (ConnectionState)EM_ASM_INT({ + var dict = Module.IDHandler.get($0); + if (!dict) return 5; // CLOSED + var conn = dict["conn"]; + switch(conn.iceConnectionState) { + case "new": + return 0; + case "checking": + return 1; + case "connected": + case "completed": + return 2; + case "disconnected": + return 3; + case "failed": + return 4; + case "closed": + return 5; + } + return 5; // CLOSED + }, _js_id); + /* clang-format on */ +} + +void WebRTCPeerConnectionJS::close() { + /* clang-format off */ + EM_ASM({ + var dict = Module.IDHandler.get($0); + if (!dict) return; + if (dict["conn"]) { + dict["conn"].close(); + } + }, _js_id); + /* clang-format on */ + _conn_state = STATE_CLOSED; +} + +Error WebRTCPeerConnectionJS::create_offer() { + ERR_FAIL_COND_V(_conn_state != STATE_NEW, FAILED); + + _conn_state = STATE_CONNECTING; + /* clang-format off */ + EM_ASM({ + var dict = Module.IDHandler.get($0); + var conn = dict["conn"]; + var c_ptr = dict["ptr"]; + var onError = function(error) { + console.error(error); + ccall("_emrtc_on_error", "void", [], []); + }; + var onCreated = function(offer) { + ccall("_emrtc_session_description_created", + "void", + ["number", "string", "string"], + [c_ptr, offer.type, offer.sdp] + ); + }; + conn.createOffer().then(onCreated).catch(onError); + }, _js_id); + /* clang-format on */ + return OK; +} + +Error WebRTCPeerConnectionJS::set_local_description(String type, String sdp) { + /* clang-format off */ + EM_ASM({ + var dict = Module.IDHandler.get($0); + var conn = dict["conn"]; + var c_ptr = dict["ptr"]; + var type = UTF8ToString($1); + var sdp = UTF8ToString($2); + var onError = function(error) { + console.error(error); + ccall("_emrtc_on_error", "void", [], []); + }; + conn.setLocalDescription({ + "sdp": sdp, + "type": type + }).catch(onError); + }, _js_id, type.utf8().get_data(), sdp.utf8().get_data()); + /* clang-format on */ + return OK; +} + +Error WebRTCPeerConnectionJS::set_remote_description(String type, String sdp) { + if (type == "offer") { + ERR_FAIL_COND_V(_conn_state != STATE_NEW, FAILED); + _conn_state = STATE_CONNECTING; + } + /* clang-format off */ + EM_ASM({ + var dict = Module.IDHandler.get($0); + var conn = dict["conn"]; + var c_ptr = dict["ptr"]; + var type = UTF8ToString($1); + var sdp = UTF8ToString($2); + + var onError = function(error) { + console.error(error); + ccall("_emrtc_on_error", "void", [], []); + }; + var onCreated = function(offer) { + ccall("_emrtc_session_description_created", + "void", + ["number", "string", "string"], + [c_ptr, offer.type, offer.sdp] + ); + }; + var onSet = function() { + if (type != "offer") { + return; + } + conn.createAnswer().then(onCreated); + }; + conn.setRemoteDescription({ + "sdp": sdp, + "type": type + }).then(onSet).catch(onError); + }, _js_id, type.utf8().get_data(), sdp.utf8().get_data()); + /* clang-format on */ + return OK; +} + +Error WebRTCPeerConnectionJS::add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) { + /* clang-format off */ + EM_ASM({ + var dict = Module.IDHandler.get($0); + var conn = dict["conn"]; + var c_ptr = dict["ptr"]; + var sdpMidName = UTF8ToString($1); + var sdpMlineIndexName = UTF8ToString($2); + var sdpName = UTF8ToString($3); + conn.addIceCandidate(new RTCIceCandidate({ + "candidate": sdpName, + "sdpMid": sdpMidName, + "sdpMlineIndex": sdpMlineIndexName + })); + }, _js_id, sdpMidName.utf8().get_data(), sdpMlineIndexName, sdpName.utf8().get_data()); + /* clang-format on */ + return OK; +} + +Error WebRTCPeerConnectionJS::initialize(Dictionary p_config) { + _emrtc_create_pc(_js_id, p_config); + return OK; +} + +Ref<WebRTCDataChannel> WebRTCPeerConnectionJS::create_data_channel(String p_channel, Dictionary p_channel_config) { + String config = JSON::print(p_channel_config); + /* clang-format off */ + int id = EM_ASM_INT({ + try { + var dict = Module.IDHandler.get($0); + if (!dict) return 0; + var label = UTF8ToString($1); + var config = JSON.parse(UTF8ToString($2)); + var conn = dict["conn"]; + return Module.IDHandler.add({ + "channel": conn.createDataChannel(label, config), + "ptr": null + }) + } catch (e) { + return 0; + } + }, _js_id, p_channel.utf8().get_data(), config.utf8().get_data()); + /* clang-format on */ + ERR_FAIL_COND_V(id == 0, NULL); + return memnew(WebRTCDataChannelJS(id)); +} + +Error WebRTCPeerConnectionJS::poll() { + return OK; +} + +WebRTCPeerConnection::ConnectionState WebRTCPeerConnectionJS::get_connection_state() const { + return _conn_state; +} + +WebRTCPeerConnectionJS::WebRTCPeerConnectionJS() { + _conn_state = STATE_NEW; + + /* clang-format off */ + _js_id = EM_ASM_INT({ + return Module.IDHandler.add({"conn": null, "ptr": $0}); + }, this); + /* clang-format on */ + Dictionary config; + _emrtc_create_pc(_js_id, config); +} + +WebRTCPeerConnectionJS::~WebRTCPeerConnectionJS() { + close(); + /* clang-format off */ + EM_ASM({ + Module.IDHandler.remove($0); + }, _js_id); + /* clang-format on */ +}; +#endif diff --git a/modules/webrtc/webrtc_peer_connection_js.h b/modules/webrtc/webrtc_peer_connection_js.h new file mode 100644 index 0000000000..43c0e3d6ee --- /dev/null +++ b/modules/webrtc/webrtc_peer_connection_js.h @@ -0,0 +1,66 @@ +/*************************************************************************/ +/* webrtc_peer_connection_js.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_PEER_CONNECTION_JS_H +#define WEBRTC_PEER_CONNECTION_JS_H + +#ifdef JAVASCRIPT_ENABLED + +#include "webrtc_peer_connection.h" + +class WebRTCPeerConnectionJS : public WebRTCPeerConnection { + +private: + int _js_id; + ConnectionState _conn_state; + +public: + static WebRTCPeerConnection *_create() { return memnew(WebRTCPeerConnectionJS); } + static void make_default() { WebRTCPeerConnection::_create = WebRTCPeerConnectionJS::_create; } + + void _on_connection_state_changed(); + virtual ConnectionState get_connection_state() const; + + virtual Error initialize(Dictionary configuration = Dictionary()); + virtual Ref<WebRTCDataChannel> create_data_channel(String p_channel_name, Dictionary p_channel_config = Dictionary()); + virtual Error create_offer(); + virtual Error set_remote_description(String type, String sdp); + virtual Error set_local_description(String type, String sdp); + virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName); + virtual Error poll(); + virtual void close(); + + WebRTCPeerConnectionJS(); + ~WebRTCPeerConnectionJS(); +}; + +#endif + +#endif // WEBRTC_PEER_CONNECTION_JS_H diff --git a/modules/websocket/SCsub b/modules/websocket/SCsub index 0345e533bc..033169411f 100644 --- a/modules/websocket/SCsub +++ b/modules/websocket/SCsub @@ -5,94 +5,26 @@ Import('env_modules') # Thirdparty source files -env_lws = env_modules.Clone() - -if env['builtin_libwebsockets'] and not env["platform"] == "javascript": # already builtin for javascript - thirdparty_dir = "#thirdparty/libwebsockets/" - helper_dir = "#thirdparty/libwebsockets/win32helpers/" - thirdparty_sources = [ - - "lib/core/adopt.c", - "lib/core/alloc.c", - "lib/core/connect.c", - "lib/core/context.c", - "lib/core/dummy-callback.c", - "lib/core/libwebsockets.c", - "lib/core/output.c", - "lib/core/pollfd.c", - "lib/core/service.c", - - "lib/event-libs/poll/poll.c", - - "lib/misc/base64-decode.c", - "lib/misc/lejp.c", - "lib/misc/sha-1.c", - - "lib/roles/h1/ops-h1.c", - "lib/roles/http/header.c", - "lib/roles/http/client/client.c", - "lib/roles/http/client/client-handshake.c", - "lib/roles/http/server/fops-zip.c", - "lib/roles/http/server/lejp-conf.c", - "lib/roles/http/server/parsers.c", - "lib/roles/http/server/server.c", - "lib/roles/listen/ops-listen.c", - "lib/roles/pipe/ops-pipe.c", - "lib/roles/raw-skt/ops-raw-skt.c", - "lib/roles/raw-file/ops-raw-file.c", - - "lib/roles/ws/client-ws.c", - "lib/roles/ws/client-parser-ws.c", - "lib/roles/ws/ops-ws.c", - "lib/roles/ws/server-ws.c", - - "lib/tls/tls.c", - "lib/tls/tls-client.c", - "lib/tls/tls-server.c", - - "lib/tls/mbedtls/wrapper/library/ssl_cert.c", - "lib/tls/mbedtls/wrapper/library/ssl_pkey.c", - "lib/tls/mbedtls/wrapper/library/ssl_stack.c", - "lib/tls/mbedtls/wrapper/library/ssl_methods.c", - "lib/tls/mbedtls/wrapper/library/ssl_lib.c", - "lib/tls/mbedtls/wrapper/library/ssl_x509.c", - "lib/tls/mbedtls/wrapper/platform/ssl_port.c", - "lib/tls/mbedtls/wrapper/platform/ssl_pm.c", - "lib/tls/mbedtls/lws-genhash.c", - "lib/tls/mbedtls/mbedtls-client.c", - "lib/tls/mbedtls/lws-genrsa.c", - "lib/tls/mbedtls/ssl.c", - "lib/tls/mbedtls/mbedtls-server.c" +env_ws = env_modules.Clone() + +if env['builtin_wslay'] and not env["platform"] == "javascript": # already builtin for javascript + wslay_dir = "#thirdparty/wslay/" + wslay_sources = [ + "wslay_net.c", + "wslay_event.c", + "wslay_queue.c", + "wslay_stack.c", + "wslay_frame.c", ] - - if env["platform"] == "android": # Builtin getifaddrs - thirdparty_sources += ["lib/misc/getifaddrs.c"] - - thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - - if env["platform"] == "windows" or env["platform"] == "uwp": # Winsock - thirdparty_sources += Glob(thirdparty_dir + "lib/plat/windows/*.c") + [helper_dir + src for src in ["getopt.c", "getopt_long.c", "gettimeofday.c"]] - else: # Unix socket - thirdparty_sources += Glob(thirdparty_dir + "lib/plat/unix/*.c") - - env_lws.Append(CPPPATH=[thirdparty_dir + 'include/']) - - if env['builtin_mbedtls']: - mbedtls_includes = "#thirdparty/mbedtls/include" - env_lws.Prepend(CPPPATH=[mbedtls_includes]) - - wrapper_includes = ["#thirdparty/libwebsockets/lib/tls/mbedtls/wrapper/include/" + inc for inc in ["internal", "openssl", "platform", ""]] - env_lws.Prepend(CPPPATH=wrapper_includes) - + wslay_sources = [wslay_dir + s for s in wslay_sources] + env_ws.Prepend(CPPPATH=[wslay_dir + "includes/"]) + env_ws.Append(CPPDEFINES=["HAVE_CONFIG_H"]) if env["platform"] == "windows" or env["platform"] == "uwp": - env_lws.Append(CPPPATH=[helper_dir]) - - if env["platform"] == "uwp": - env_lws.Append(CCFLAGS=["/DLWS_MINGW_SUPPORT"]) - - env_thirdparty = env_lws.Clone() - env_thirdparty.disable_warnings() - env_thirdparty.Append(CPPPATH=[thirdparty_dir + 'lib/']) - env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources) - -env_lws.add_source_files(env.modules_sources, "*.cpp") + env_ws.Append(CPPDEFINES=["HAVE_WINSOCK2_H"]) + else: + env_ws.Append(CPPDEFINES=["HAVE_NETINET_IN_H"]) + env_wslay = env_ws.Clone() + env_wslay.disable_warnings() + env_wslay.add_source_files(env.modules_sources, wslay_sources) + +env_ws.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/websocket/doc_classes/WebSocketClient.xml b/modules/websocket/doc_classes/WebSocketClient.xml index cb85fe864d..705e3485f5 100644 --- a/modules/websocket/doc_classes/WebSocketClient.xml +++ b/modules/websocket/doc_classes/WebSocketClient.xml @@ -1,18 +1,16 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="WebSocketClient" inherits="WebSocketMultiplayerPeer" category="Core" version="3.2"> <brief_description> - A WebSocket client implementation + A WebSocket client implementation. </brief_description> <description> - This class implements a WebSocket client compatible with any RFC 6455 complaint WebSocket server. + This class implements a WebSocket client compatible with any RFC 6455-compliant WebSocket server. This client can be optionally used as a network peer for the [MultiplayerAPI]. After starting the client ([method connect_to_url]), you will need to [method NetworkedMultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). - You will received appropriate signals when connecting, disconnecting, or when new data is available. + You will receive appropriate signals when connecting, disconnecting, or when new data is available. </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="connect_to_url"> <return type="int" enum="Error"> @@ -23,10 +21,13 @@ </argument> <argument index="2" name="gd_mp_api" type="bool" default="false"> </argument> + <argument index="3" name="custom_headers" type="PoolStringArray" default="PoolStringArray( )"> + </argument> <description> - Connect to the given URL requesting one of the given [code]protocols[/code] as sub-protocol. - If [code]true[/code] is passed as [code]gd_mp_api[/code], the client will behave like a network peer for the [MultiplayerAPI], connections to non Godot servers will not work, and [signal data_received] will not be emitted. + Connects to the given URL requesting one of the given [code]protocols[/code] as sub-protocol. If the list empty (default), no sub-protocol will be requested. + If [code]true[/code] is passed as [code]gd_mp_api[/code], the client will behave like a network peer for the [MultiplayerAPI], connections to non-Godot servers will not work, and [signal data_received] will not be emitted. If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.) on the [WebSocketPeer] returned via [code]get_peer(1)[/code] and not on this object directly (e.g. [code]get_peer(1).put_packet(data)[/code]). + You can optionally pass a list of [code]custom_headers[/code] to be added to the handshake HTTP request (not supported in HTML5 platform). </description> </method> <method name="disconnect_from_host"> @@ -37,13 +38,31 @@ <argument index="1" name="reason" type="String" default=""""> </argument> <description> - Disconnect this client from the connected host. See [method WebSocketPeer.close] for more info. + Disconnects this client from the connected host. See [method WebSocketPeer.close] for more information. + </description> + </method> + <method name="get_connected_host" qualifiers="const"> + <return type="String"> + </return> + <description> + Return the IP address of the currently connected host. + </description> + </method> + <method name="get_connected_port" qualifiers="const"> + <return type="int"> + </return> + <description> + Return the IP port of the currently connected host. </description> </method> </methods> <members> + <member name="trusted_ssl_certificate" type="X509Certificate" setter="set_trusted_ssl_certificate" getter="get_trusted_ssl_certificate"> + If specified, this [X509Certificate] will be the only one accepted when connecting to an SSL host. Any other certificate provided by the server will be regarded as invalid. + </member> <member name="verify_ssl" type="bool" setter="set_verify_ssl_enabled" getter="is_verify_ssl_enabled"> - Enable or disable SSL certificate verification. Note: You must specify the certificates to be used in the project settings for it to work when exported. + If [code]true[/code], SSL certificate verification is enabled. + [b]Note:[/b] You must specify the certificates to be used in the Project Settings for it to work when exported. </member> </members> <signals> @@ -68,7 +87,8 @@ </signal> <signal name="data_received"> <description> - Emitted when a WebSocket message is received. Note: This signal is NOT emitted when used as high level multiplayer peer. + Emitted when a WebSocket message is received. + [b]Note:[/b] This signal is [i]not[/i] emitted when used as high-level multiplayer peer. </description> </signal> <signal name="server_close_request"> diff --git a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml index 139480c31f..7070cfbdab 100644 --- a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml +++ b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml @@ -8,8 +8,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="get_peer" qualifiers="const"> <return type="WebSocketPeer"> @@ -20,13 +18,36 @@ 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> + Configures the buffer sizes for this WebSocket peer. Default values can be specified in the 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. + [b]Note:[/b] HTML5 exports only use the input buffer since the output one is managed by browsers. + </description> + </method> </methods> + <members> + <member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" override="true" default="false" /> + <member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="NetworkedMultiplayerPeer.TransferMode" default="2" /> + </members> <signals> <signal name="peer_packet"> <argument index="0" name="peer_source" type="int"> </argument> <description> - Emitted when a packet is received from a peer. Note: this signal is only emitted when the client or server is configured to use Godot multiplayer API. + Emitted when a packet is received from a peer. + [b]Note:[/b] This signal is only emitted when the client or server is configured to use Godot multiplayer API. </description> </signal> </signals> diff --git a/modules/websocket/doc_classes/WebSocketPeer.xml b/modules/websocket/doc_classes/WebSocketPeer.xml index 3b3692dd87..dd95f7432e 100644 --- a/modules/websocket/doc_classes/WebSocketPeer.xml +++ b/modules/websocket/doc_classes/WebSocketPeer.xml @@ -9,8 +9,6 @@ </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="close"> <return type="void"> @@ -20,30 +18,32 @@ <argument index="1" name="reason" type="String" default=""""> </argument> <description> - Close this WebSocket connection. [code]code[/code] is the status code for the closure (see RFC6455 section 7.4 for a list of valid status codes). [code]reason[/code] is the human readable reason for closing the connection (can be any UTF8 string, must be less than 123 bytes). - Note: To achieve a clean close, you will need to keep polling until either [signal WebSocketClient.connection_closed] or [signal WebSocketServer.client_disconnected] is received. - Note: HTML5 export might not support all status codes. Please refer to browsers-specific documentation for more details. + Closes this WebSocket connection. [code]code[/code] is the status code for the closure (see RFC 6455 section 7.4 for a list of valid status codes). [code]reason[/code] is the human readable reason for closing the connection (can be any UTF-8 string that's smaller than 123 bytes). + [b]Note:[/b] To achieve a clean close, you will need to keep polling until either [signal WebSocketClient.connection_closed] or [signal WebSocketServer.client_disconnected] is received. + [b]Note:[/b] The HTML5 export might not support all status codes. Please refer to browser-specific documentation for more details. </description> </method> <method name="get_connected_host" qualifiers="const"> <return type="String"> </return> <description> - Returns the IP Address of the connected peer. (Not available in HTML5 export) + Returns the IP address of the connected peer. + [b]Note:[/b] Not available in the HTML5 export. </description> </method> <method name="get_connected_port" qualifiers="const"> <return type="int"> </return> <description> - Returns the remote port of the connected peer. (Not available in HTML5 export) + Returns the remote port of the connected peer. + [b]Note:[/b] Not available in the HTML5 export. </description> </method> <method name="get_write_mode" qualifiers="const"> <return type="int" enum="WebSocketPeer.WriteMode"> </return> <description> - Get the current selected write mode. See [enum WriteMode]. + Gets the current selected write mode. See [enum WriteMode]. </description> </method> <method name="is_connected_to_host" qualifiers="const"> @@ -72,10 +72,10 @@ </methods> <constants> <constant name="WRITE_MODE_TEXT" value="0" enum="WriteMode"> - Specify that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed). + Specifies that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed). </constant> <constant name="WRITE_MODE_BINARY" value="1" enum="WriteMode"> - Specify that WebSockets messages should be transferred as binary payload (any byte combination is allowed). + Specifies that WebSockets messages should be transferred as binary payload (any byte combination is allowed). </constant> </constants> </class> diff --git a/modules/websocket/doc_classes/WebSocketServer.xml b/modules/websocket/doc_classes/WebSocketServer.xml index 4740bd6dcf..86f2dae64f 100644 --- a/modules/websocket/doc_classes/WebSocketServer.xml +++ b/modules/websocket/doc_classes/WebSocketServer.xml @@ -1,17 +1,15 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="WebSocketServer" inherits="WebSocketMultiplayerPeer" category="Core" version="3.2"> <brief_description> - A WebSocket server implementation + A WebSocket server implementation. </brief_description> <description> - This class implements a WebSocket server that can also support the high level multiplayer API. + This class implements a WebSocket server that can also support the high-level multiplayer API. After starting the server ([method listen]), you will need to [method NetworkedMultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). When clients connect, disconnect, or send data, you will receive the appropriate signal. - Note: This class will not work in HTML5 exports due to browser restrictions. + [b]Note:[/b] This class will not work in HTML5 exports due to browser restrictions. </description> <tutorials> </tutorials> - <demos> - </demos> <methods> <method name="disconnect_peer"> <return type="void"> @@ -23,7 +21,7 @@ <argument index="2" name="reason" type="String" default=""""> </argument> <description> - Disconnects the peer identified by [code]id[/code] from the server. See [method WebSocketPeer.close] for more info. + Disconnects the peer identified by [code]id[/code] from the server. See [method WebSocketPeer.close] for more information. </description> </method> <method name="get_peer_address" qualifiers="const"> @@ -70,20 +68,31 @@ <argument index="2" name="gd_mp_api" type="bool" default="false"> </argument> <description> - Start listening on the given port. - You can specify the desired subprotocols via the "protocols" array. If the list empty (default), "binary" will be used. - If [code]true[/code] is passed as [code]gd_mp_api[/code], the server will behave like a network peer for the [MultiplayerAPI], connections from non Godot clients will not work, and [signal data_received] will not be emitted. - If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.), on the [WebSocketPeer] returned via [code]get_peer(ID)[/code] to communicate with the peer with given [code]ID[/code] (e.g. [code]get_peer(ID).get_available_packet_count[/code]). + Starts listening on the given port. + You can specify the desired subprotocols via the "protocols" array. If the list empty (default), no sub-protocol will be requested. + If [code]true[/code] is passed as [code]gd_mp_api[/code], the server will behave like a network peer for the [MultiplayerAPI], connections from non-Godot clients will not work, and [signal data_received] will not be emitted. + If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.), on the [WebSocketPeer] returned via [code]get_peer(id)[/code] to communicate with the peer with given [code]id[/code] (e.g. [code]get_peer(id).get_available_packet_count[/code]). </description> </method> <method name="stop"> <return type="void"> </return> <description> - Stop the server and clear its state. + Stops the server and clear its state. </description> </method> </methods> + <members> + <member name="ca_chain" type="X509Certificate" setter="set_ca_chain" getter="get_ca_chain"> + When using SSL (see [member private_key] and [member ssl_certificate]), you can set this to a valid [X509Certificate] to be provided as additional CA chain information during the SSL handshake. + </member> + <member name="private_key" type="CryptoKey" setter="set_private_key" getter="get_private_key"> + When set to a valid [CryptoKey] (along with [member ssl_certificate]) will cause the server to require SSL instead of regular TCP (i.e. the [code]wss://[/code] protocol). + </member> + <member name="ssl_certificate" type="X509Certificate" setter="set_ssl_certificate" getter="get_ssl_certificate"> + When set to a valid [X509Certificate] (along with [member private_key]) will cause the server to require SSL instead of regular TCP (i.e. the [code]wss://[/code] protocol). + </member> + </members> <signals> <signal name="client_close_request"> <argument index="0" name="id" type="int"> @@ -118,7 +127,8 @@ <argument index="0" name="id" type="int"> </argument> <description> - Emitted when a new message is received. Note: This signal is NOT emitted when used as high level multiplayer peer. + Emitted when a new message is received. + [b]Note:[/b] This signal is [i]not[/i] emitted when used as high-level multiplayer peer. </description> </signal> </signals> diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp index aafae8f1c2..983db60d5e 100644 --- a/modules/websocket/emws_client.cpp +++ b/modules/websocket/emws_client.cpp @@ -64,13 +64,26 @@ EMSCRIPTEN_KEEPALIVE void _esws_on_close(void *obj, int code, char *reason, int } } -Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocols) { +Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocols, const Vector<String> p_custom_headers) { + + String proto_string; + for (int i = 0; i < p_protocols.size(); i++) { + if (i != 0) + proto_string += ","; + proto_string += p_protocols[i]; + } - String proto_string = p_protocols.join(","); String str = "ws://"; - if (p_ssl) + if (p_custom_headers.size()) { + WARN_PRINT_ONCE("Custom headers are not supported in in HTML5 platform."); + } + if (p_ssl) { str = "wss://"; + if (ssl_cert.is_valid()) { + WARN_PRINT_ONCE("Custom SSL certificate is not supported in HTML5 platform."); + } + } str += p_host + ":" + itos(p_port) + p_path; _is_connecting = true; @@ -193,18 +206,24 @@ void EMWSClient::disconnect_from_host(int p_code, String p_reason) { IP_Address EMWSClient::get_connected_host() const { - return IP_Address(); + ERR_FAIL_V_MSG(IP_Address(), "Not supported in HTML5 export."); }; uint16_t EMWSClient::get_connected_port() const { - return 1025; + ERR_FAIL_V_MSG(0, "Not supported in HTML5 export."); }; 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..67705891b2 100644 --- a/modules/websocket/emws_client.h +++ b/modules/websocket/emws_client.h @@ -49,7 +49,8 @@ private: public: bool _is_connecting; - Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocol = PoolVector<String>()); + 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, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()); Ref<WebSocketPeer> get_peer(int p_peer_id) const; void disconnect_from_host(int p_code = 1000, String p_reason = ""); IP_Address get_connected_host() const; diff --git a/modules/websocket/emws_peer.cpp b/modules/websocket/emws_peer.cpp index a9f38f1a82..58d4c52688 100644 --- a/modules/websocket/emws_peer.cpp +++ b/modules/websocket/emws_peer.cpp @@ -131,14 +131,12 @@ void EMWSPeer::close(int p_code, String p_reason) { IP_Address EMWSPeer::get_connected_host() const { - ERR_EXPLAIN("Not supported in HTML5 export"); - ERR_FAIL_V(IP_Address()); + ERR_FAIL_V_MSG(IP_Address(), "Not supported in HTML5 export."); }; uint16_t EMWSPeer::get_connected_port() const { - ERR_EXPLAIN("Not supported in HTML5 export"); - ERR_FAIL_V(0); + ERR_FAIL_V_MSG(0, "Not supported in HTML5 export."); }; EMWSPeer::EMWSPeer() { diff --git a/modules/websocket/emws_server.cpp b/modules/websocket/emws_server.cpp index 0eef1c4ba9..9a6a30d613 100644 --- a/modules/websocket/emws_server.cpp +++ b/modules/websocket/emws_server.cpp @@ -33,7 +33,7 @@ #include "emws_server.h" #include "core/os/os.h" -Error EMWSServer::listen(int p_port, PoolVector<String> p_protocols, bool gd_mp_api) { +Error EMWSServer::listen(int p_port, Vector<String> p_protocols, bool gd_mp_api) { return FAILED; } @@ -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..e8da8c26b4 100644 --- a/modules/websocket/emws_server.h +++ b/modules/websocket/emws_server.h @@ -42,7 +42,8 @@ class EMWSServer : public WebSocketServer { GDCIIMPL(EMWSServer, WebSocketServer); public: - Error listen(int p_port, PoolVector<String> p_protocols = PoolVector<String>(), bool gd_mp_api = false); + Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); + Error listen(int p_port, Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false); void stop(); bool is_listening() const; bool has_peer(int p_id) const; diff --git a/modules/websocket/lws_client.cpp b/modules/websocket/lws_client.cpp deleted file mode 100644 index d09558ab22..0000000000 --- a/modules/websocket/lws_client.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/*************************************************************************/ -/* lws_client.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. */ -/*************************************************************************/ - -#ifndef JAVASCRIPT_ENABLED - -#include "lws_client.h" -#include "core/io/ip.h" -#include "core/io/stream_peer_ssl.h" -#include "core/project_settings.h" -#if defined(LWS_OPENSSL_SUPPORT) -// Not openssl, just the mbedtls wrapper -#include "openssl/ssl.h" -#endif - -Error LWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocols) { - - ERR_FAIL_COND_V(context != NULL, FAILED); - - IP_Address addr; - - if (!p_host.is_valid_ip_address()) { - addr = IP::get_singleton()->resolve_hostname(p_host); - } else { - addr = p_host; - } - - ERR_FAIL_COND_V(!addr.is_valid(), ERR_INVALID_PARAMETER); - - // Prepare protocols - _lws_make_protocols(this, &LWSClient::_lws_gd_callback, p_protocols, &_lws_ref); - - // Init lws client - struct lws_context_creation_info info; - struct lws_client_connect_info i; - - memset(&i, 0, sizeof i); - memset(&info, 0, sizeof info); - - info.port = CONTEXT_PORT_NO_LISTEN; - info.protocols = _lws_ref->lws_structs; - info.gid = -1; - info.uid = -1; - //info.ws_ping_pong_interval = 5; - info.user = _lws_ref; -#if defined(LWS_OPENSSL_SUPPORT) - info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; -#endif - context = lws_create_context(&info); - - if (context == NULL) { - _lws_free_ref(_lws_ref); - _lws_ref = NULL; - ERR_EXPLAIN("Unable to create lws context"); - ERR_FAIL_V(FAILED); - } - - i.context = context; - if (p_protocols.size() > 0) - i.protocol = _lws_ref->lws_names; - else - i.protocol = NULL; - - if (p_ssl) { - i.ssl_connection = LCCSCF_USE_SSL; - if (!verify_ssl) - i.ssl_connection |= LCCSCF_ALLOW_SELFSIGNED; - } else { - i.ssl_connection = 0; - } - - // These CharStrings needs to survive till we call lws_client_connect_via_info - CharString addr_ch = ((String)addr).ascii(); - CharString host_ch = p_host.utf8(); - CharString path_ch = p_path.utf8(); - i.address = addr_ch.get_data(); - i.host = host_ch.get_data(); - i.path = path_ch.get_data(); - i.port = p_port; - - lws_client_connect_via_info(&i); - - return OK; -}; - -int LWSClient::get_max_packet_size() const { - return (1 << _out_buf_size) - PROTO_SIZE; -} - -void LWSClient::poll() { - - _lws_poll(); -} - -int LWSClient::_handle_cb(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { - - Ref<LWSPeer> peer = static_cast<Ref<LWSPeer> >(_peer); - LWSPeer::PeerData *peer_data = (LWSPeer::PeerData *)user; - - switch (reason) { -#if defined(LWS_OPENSSL_SUPPORT) - case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: { - PoolByteArray arr = StreamPeerSSL::get_project_cert_array(); - if (arr.size() > 0) - SSL_CTX_add_client_CA((SSL_CTX *)user, d2i_X509(NULL, &arr.read()[0], arr.size())); - else if (verify_ssl) - WARN_PRINTS("No CA cert specified in project settings, SSL will not work"); - } break; -#endif - case LWS_CALLBACK_CLIENT_ESTABLISHED: - peer->set_wsi(wsi, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size); - peer_data->peer_id = 0; - peer_data->force_close = false; - peer_data->clean_close = false; - _on_connect(lws_get_protocol(wsi)->name); - break; - - case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: - _on_error(); - destroy_context(); - return -1; // We should close the connection (would probably happen anyway) - - case LWS_CALLBACK_WS_PEER_INITIATED_CLOSE: { - int code; - String reason2 = peer->get_close_reason(in, len, code); - peer_data->clean_close = true; - _on_close_request(code, reason2); - return 0; - } - - case LWS_CALLBACK_CLIENT_CLOSED: - peer->close(); - destroy_context(); - _on_disconnect(peer_data->clean_close); - return 0; // We can end here - - case LWS_CALLBACK_CLIENT_RECEIVE: - peer->read_wsi(in, len); - if (peer->get_available_packet_count() > 0) - _on_peer_packet(); - break; - - case LWS_CALLBACK_CLIENT_WRITEABLE: - if (peer_data->force_close) { - peer->send_close_status(wsi); - return -1; - } - - peer->write_wsi(); - break; - - default: - break; - } - - return 0; -} - -Ref<WebSocketPeer> LWSClient::get_peer(int p_peer_id) const { - - return _peer; -} - -NetworkedMultiplayerPeer::ConnectionStatus LWSClient::get_connection_status() const { - - if (context == NULL) - return CONNECTION_DISCONNECTED; - - if (_peer->is_connected_to_host()) - return CONNECTION_CONNECTED; - - return CONNECTION_CONNECTING; -} - -void LWSClient::disconnect_from_host(int p_code, String p_reason) { - - if (context == NULL) - return; - - _peer->close(p_code, p_reason); -}; - -IP_Address LWSClient::get_connected_host() const { - - return IP_Address(); -}; - -uint16_t LWSClient::get_connected_port() const { - - return 1025; -}; - -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); - _out_buf_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_BUF) - 1) + 10; - _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_PKT) - 1); - - context = NULL; - _lws_ref = NULL; - _peer = Ref<LWSPeer>(memnew(LWSPeer)); -}; - -LWSClient::~LWSClient() { - - invalidate_lws_ref(); // We do not want any more callback - disconnect_from_host(); - destroy_context(); - _peer = Ref<LWSPeer>(); -}; - -#endif // JAVASCRIPT_ENABLED diff --git a/modules/websocket/lws_helper.cpp b/modules/websocket/lws_helper.cpp deleted file mode 100644 index a652779960..0000000000 --- a/modules/websocket/lws_helper.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/*************************************************************************/ -/* lws_helper.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. */ -/*************************************************************************/ - -#if !defined(JAVASCRIPT_ENABLED) - -#include "lws_helper.h" - -_LWSRef *_lws_create_ref(void *obj) { - - _LWSRef *out = (_LWSRef *)memalloc(sizeof(_LWSRef)); - out->is_destroying = false; - out->free_context = false; - out->is_polling = false; - out->obj = obj; - out->is_valid = true; - out->lws_structs = NULL; - out->lws_names = NULL; - return out; -} - -void _lws_free_ref(_LWSRef *ref) { - // Free strings and structs - memfree(ref->lws_structs); - memfree(ref->lws_names); - // Free ref - memfree(ref); -} - -bool _lws_destroy(struct lws_context *context, _LWSRef *ref) { - if (context == NULL || ref->is_destroying) - return false; - - if (ref->is_polling) { - ref->free_context = true; - return false; - } - - ref->is_destroying = true; - lws_context_destroy(context); - _lws_free_ref(ref); - return true; -} - -bool _lws_poll(struct lws_context *context, _LWSRef *ref) { - - ERR_FAIL_COND_V(context == NULL, false); - ERR_FAIL_COND_V(ref == NULL, false); - - ref->is_polling = true; - lws_service(context, 0); - ref->is_polling = false; - - if (!ref->free_context) - return false; // Nothing to do - - bool is_valid = ref->is_valid; // Might have been destroyed by poll - - _lws_destroy(context, ref); // Will destroy context and ref - - return is_valid; // If the object should NULL its context and ref -} - -/* - * Prepare the protocol_structs to be fed to context. - * Also prepare the protocol string used by the client. - */ -void _lws_make_protocols(void *p_obj, lws_callback_function *p_callback, PoolVector<String> p_names, _LWSRef **r_lws_ref) { - // The input strings might go away after this call, we need to copy them. - // We will clear them when destroying the context. - int i; - int len = p_names.size(); - size_t data_size = sizeof(struct LWSPeer::PeerData); - PoolVector<String>::Read pnr = p_names.read(); - - // This is a reference connecting the object with lws keep track of status, mallocs, etc. - // Must survive as long the context. - // Must be freed manually when context creation fails. - _LWSRef *ref = _lws_create_ref(p_obj); - - // LWS protocol structs. - ref->lws_structs = (struct lws_protocols *)memalloc(sizeof(struct lws_protocols) * (len + 2)); - memset(ref->lws_structs, 0, sizeof(struct lws_protocols) * (len + 2)); - - CharString strings = p_names.join(",").ascii(); - int str_len = strings.length(); - - // Joined string of protocols, double the size: comma separated first, NULL separated last - ref->lws_names = (char *)memalloc((str_len + 1) * 2); // Plus the terminator - - char *names_ptr = ref->lws_names; - struct lws_protocols *structs_ptr = ref->lws_structs; - - // Comma separated protocols string to be used in client Sec-WebSocket-Protocol header - if (str_len > 0) - copymem(names_ptr, strings.get_data(), str_len); - names_ptr[str_len] = '\0'; // NULL terminator - - // NULL terminated protocol strings to be used in protocol structs - if (str_len > 0) - copymem(&names_ptr[str_len + 1], strings.get_data(), str_len); - names_ptr[(str_len * 2) + 1] = '\0'; // NULL terminator - int pos = str_len + 1; - - // The first protocol is the default for any http request (before upgrade). - // It is also used as the websocket protocol when no subprotocol is specified. - structs_ptr[0].name = "default"; - structs_ptr[0].callback = p_callback; - structs_ptr[0].per_session_data_size = data_size; - structs_ptr[0].rx_buffer_size = LWS_BUF_SIZE; - structs_ptr[0].tx_packet_size = LWS_PACKET_SIZE; - // Add user defined protocols - for (i = 0; i < len; i++) { - structs_ptr[i + 1].name = (const char *)&names_ptr[pos]; - structs_ptr[i + 1].callback = p_callback; - structs_ptr[i + 1].per_session_data_size = data_size; - structs_ptr[i + 1].rx_buffer_size = LWS_BUF_SIZE; - structs_ptr[i + 1].tx_packet_size = LWS_PACKET_SIZE; - pos += pnr[i].ascii().length() + 1; - names_ptr[pos - 1] = '\0'; - } - // Add protocols terminator - structs_ptr[len + 1].name = NULL; - structs_ptr[len + 1].callback = NULL; - structs_ptr[len + 1].per_session_data_size = 0; - structs_ptr[len + 1].rx_buffer_size = 0; - - *r_lws_ref = ref; -} - -#endif diff --git a/modules/websocket/lws_helper.h b/modules/websocket/lws_helper.h deleted file mode 100644 index 265dc4e6ad..0000000000 --- a/modules/websocket/lws_helper.h +++ /dev/null @@ -1,111 +0,0 @@ -/*************************************************************************/ -/* lws_helper.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 LWS_HELPER_H -#define LWS_HELPER_H - -#define LWS_BUF_SIZE 65536 -#define LWS_PACKET_SIZE LWS_BUF_SIZE - -#include "core/io/stream_peer.h" -#include "core/os/os.h" -#include "core/reference.h" -#include "core/ring_buffer.h" -#include "lws_peer.h" - -struct _LWSRef { - bool free_context; - bool is_polling; - bool is_valid; - bool is_destroying; - void *obj; - struct lws_protocols *lws_structs; - char *lws_names; -}; - -_LWSRef *_lws_create_ref(void *obj); -void _lws_free_ref(_LWSRef *ref); -bool _lws_destroy(struct lws_context *context, _LWSRef *ref); -bool _lws_poll(struct lws_context *context, _LWSRef *ref); -void _lws_make_protocols(void *p_obj, lws_callback_function *p_callback, PoolVector<String> p_names, _LWSRef **r_lws_ref); - -/* clang-format off */ -#define LWS_HELPER(CNAME) \ -protected: \ - struct _LWSRef *_lws_ref; \ - struct lws_context *context; \ - bool _keep_servicing; \ - \ - static int _lws_gd_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { \ - \ - if (wsi == NULL) { \ - return 0; \ - } \ - \ - struct _LWSRef *ref = (struct _LWSRef *)lws_context_user(lws_get_context(wsi)); \ - if (!ref->is_valid) \ - return 0; \ - CNAME *helper = (CNAME *)ref->obj; \ - helper->_keep_servicing = true; \ - return helper->_handle_cb(wsi, reason, user, in, len); \ - } \ - \ - void invalidate_lws_ref() { \ - if (_lws_ref != NULL) \ - _lws_ref->is_valid = false; \ - } \ - \ - void destroy_context() { \ - if (_lws_destroy(context, _lws_ref)) { \ - context = NULL; \ - _lws_ref = NULL; \ - } \ - } \ - \ -public: \ - virtual int _handle_cb(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len); \ - \ - void _lws_poll() { \ - ERR_FAIL_COND(context == NULL); \ - do { \ - _keep_servicing = false; \ - if (::_lws_poll(context, _lws_ref)) { \ - context = NULL; \ - _lws_ref = NULL; \ - break; \ - } \ - } while (_keep_servicing); \ - } \ - \ -protected: - -/* clang-format on */ - -#endif // LWS_HELPER_H diff --git a/modules/websocket/lws_peer.cpp b/modules/websocket/lws_peer.cpp deleted file mode 100644 index a7c85450fa..0000000000 --- a/modules/websocket/lws_peer.cpp +++ /dev/null @@ -1,270 +0,0 @@ -/*************************************************************************/ -/* lws_peer.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. */ -/*************************************************************************/ - -#ifndef JAVASCRIPT_ENABLED - -#include "lws_peer.h" - -#include "core/io/ip.h" - -// Needed for socket_helpers on Android at least. UNIXes has it, just include if not windows -#if !defined(WINDOWS_ENABLED) -#include <netinet/in.h> -#include <sys/socket.h> -#endif - -#include "drivers/unix/net_socket_posix.h" - -void LWSPeer::set_wsi(struct lws *p_wsi, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size) { - ERR_FAIL_COND(wsi != NULL); - - _in_buffer.resize(p_in_pkt_size, p_in_buf_size); - _out_buffer.resize(p_out_pkt_size, p_out_buf_size); - _packet_buffer.resize((1 << MAX(p_in_buf_size, p_out_buf_size)) + LWS_PRE); - wsi = p_wsi; -}; - -void LWSPeer::set_write_mode(WriteMode p_mode) { - write_mode = p_mode; -} - -LWSPeer::WriteMode LWSPeer::get_write_mode() const { - return write_mode; -} - -Error LWSPeer::read_wsi(void *in, size_t len) { - - ERR_FAIL_COND_V(!is_connected_to_host(), FAILED); - - if (lws_is_first_fragment(wsi)) - _in_size = 0; - else if (_in_size == -1) // Trash this frame - return ERR_FILE_CORRUPT; - - Error err = _in_buffer.write_packet((const uint8_t *)in, len, NULL); - - if (err != OK) { - _in_buffer.discard_payload(_in_size); - _in_size = -1; - ERR_FAIL_V(err); - } - - _in_size += len; - - if (lws_is_final_fragment(wsi)) { - uint8_t is_string = lws_frame_is_binary(wsi) ? 0 : 1; - err = _in_buffer.write_packet(NULL, _in_size, &is_string); - if (err != OK) { - _in_buffer.discard_payload(_in_size); - _in_size = -1; - ERR_FAIL_V(err); - } - } - - return OK; -} - -Error LWSPeer::write_wsi() { - - ERR_FAIL_COND_V(!is_connected_to_host(), FAILED); - - PoolVector<uint8_t> tmp; - int count = _out_buffer.packets_left(); - - if (count == 0) - return OK; - - int read = 0; - uint8_t is_string = 0; - PoolVector<uint8_t>::Write rw = _packet_buffer.write(); - _out_buffer.read_packet(&(rw[LWS_PRE]), _packet_buffer.size() - LWS_PRE, &is_string, read); - - enum lws_write_protocol mode = is_string ? LWS_WRITE_TEXT : LWS_WRITE_BINARY; - lws_write(wsi, &(rw[LWS_PRE]), read, mode); - - if (count > 1) - lws_callback_on_writable(wsi); // we want to write more! - - return OK; -} - -Error LWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - - ERR_FAIL_COND_V(!is_connected_to_host(), FAILED); - - uint8_t is_string = write_mode == WRITE_MODE_TEXT; - _out_buffer.write_packet(p_buffer, p_buffer_size, &is_string); - lws_callback_on_writable(wsi); // notify that we want to write - return OK; -}; - -Error LWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { - - r_buffer_size = 0; - - ERR_FAIL_COND_V(!is_connected_to_host(), FAILED); - - if (_in_buffer.packets_left() == 0) - return ERR_UNAVAILABLE; - - int read = 0; - PoolVector<uint8_t>::Write rw = _packet_buffer.write(); - _in_buffer.read_packet(rw.ptr(), _packet_buffer.size(), &_is_string, read); - - *r_buffer = rw.ptr(); - r_buffer_size = read; - - return OK; -}; - -int LWSPeer::get_available_packet_count() const { - - if (!is_connected_to_host()) - return 0; - - return _in_buffer.packets_left(); -}; - -bool LWSPeer::was_string_packet() const { - - return _is_string; -}; - -bool LWSPeer::is_connected_to_host() const { - - return wsi != NULL; -}; - -String LWSPeer::get_close_reason(void *in, size_t len, int &r_code) { - String s; - r_code = 0; - if (len < 2) // From docs this should not happen - return s; - - const uint8_t *b = (const uint8_t *)in; - r_code = b[0] << 8 | b[1]; - - if (len > 2) { - const char *utf8 = (const char *)&b[2]; - s.parse_utf8(utf8, len - 2); - } - return s; -} - -void LWSPeer::send_close_status(struct lws *p_wsi) { - if (close_code == -1) - return; - - int len = close_reason.size(); - ERR_FAIL_COND(len > 123); // Maximum allowed reason size in bytes - - lws_close_status code = (lws_close_status)close_code; - unsigned char *reason = len > 0 ? (unsigned char *)close_reason.utf8().ptrw() : NULL; - - lws_close_reason(p_wsi, code, reason, len); - - close_code = -1; - close_reason = ""; -} - -void LWSPeer::close(int p_code, String p_reason) { - if (wsi != NULL) { - close_code = p_code; - close_reason = p_reason; - PeerData *data = ((PeerData *)lws_wsi_user(wsi)); - data->force_close = true; - data->clean_close = true; - lws_callback_on_writable(wsi); // Notify that we want to disconnect - } else { - close_code = -1; - close_reason = ""; - } - wsi = NULL; - _in_buffer.clear(); - _out_buffer.clear(); - _in_size = 0; - _is_string = 0; - _packet_buffer.resize(0); -}; - -IP_Address LWSPeer::get_connected_host() const { - - ERR_FAIL_COND_V(!is_connected_to_host(), IP_Address()); - - IP_Address ip; - uint16_t port = 0; - - struct sockaddr_storage addr; - socklen_t len = sizeof(addr); - - int fd = lws_get_socket_fd(wsi); - ERR_FAIL_COND_V(fd == -1, IP_Address()); - - int ret = getpeername(fd, (struct sockaddr *)&addr, &len); - ERR_FAIL_COND_V(ret != 0, IP_Address()); - - NetSocketPosix::_set_ip_port(&addr, ip, port); - - return ip; -}; - -uint16_t LWSPeer::get_connected_port() const { - - ERR_FAIL_COND_V(!is_connected_to_host(), 0); - - IP_Address ip; - uint16_t port = 0; - - struct sockaddr_storage addr; - socklen_t len = sizeof(addr); - - int fd = lws_get_socket_fd(wsi); - ERR_FAIL_COND_V(fd == -1, 0); - - int ret = getpeername(fd, (struct sockaddr *)&addr, &len); - ERR_FAIL_COND_V(ret != 0, 0); - - NetSocketPosix::_set_ip_port(&addr, ip, port); - - return port; -}; - -LWSPeer::LWSPeer() { - wsi = NULL; - write_mode = WRITE_MODE_BINARY; - close(); -}; - -LWSPeer::~LWSPeer() { - - close(); -}; - -#endif // JAVASCRIPT_ENABLED diff --git a/modules/websocket/lws_server.cpp b/modules/websocket/lws_server.cpp deleted file mode 100644 index 61ccdca74a..0000000000 --- a/modules/websocket/lws_server.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/*************************************************************************/ -/* lws_server.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. */ -/*************************************************************************/ - -#ifndef JAVASCRIPT_ENABLED - -#include "lws_server.h" -#include "core/os/os.h" -#include "core/project_settings.h" - -Error LWSServer::listen(int p_port, PoolVector<String> p_protocols, bool gd_mp_api) { - - ERR_FAIL_COND_V(context != NULL, FAILED); - - _is_multiplayer = gd_mp_api; - - struct lws_context_creation_info info; - memset(&info, 0, sizeof info); - - // Prepare lws protocol structs - _lws_make_protocols(this, &LWSServer::_lws_gd_callback, p_protocols, &_lws_ref); - - info.port = p_port; - info.user = _lws_ref; - info.protocols = _lws_ref->lws_structs; - info.gid = -1; - info.uid = -1; - //info.ws_ping_pong_interval = 5; - - context = lws_create_context(&info); - - if (context == NULL) { - _lws_free_ref(_lws_ref); - _lws_ref = NULL; - ERR_EXPLAIN("Unable to create LWS context"); - ERR_FAIL_V(FAILED); - } - - return OK; -} - -bool LWSServer::is_listening() const { - return context != NULL; -} - -int LWSServer::get_max_packet_size() const { - return (1 << _out_buf_size) - PROTO_SIZE; -} - -int LWSServer::_handle_cb(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { - - LWSPeer::PeerData *peer_data = (LWSPeer::PeerData *)user; - - switch (reason) { - case LWS_CALLBACK_HTTP: - // no http for now - // closing immediately returning -1; - return -1; - - case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: - // check header here? - break; - - case LWS_CALLBACK_ESTABLISHED: { - int32_t id = _gen_unique_id(); - - Ref<LWSPeer> peer = Ref<LWSPeer>(memnew(LWSPeer)); - peer->set_wsi(wsi, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size); - _peer_map[id] = peer; - - peer_data->peer_id = id; - peer_data->force_close = false; - peer_data->clean_close = false; - _on_connect(id, lws_get_protocol(wsi)->name); - break; - } - - case LWS_CALLBACK_WS_PEER_INITIATED_CLOSE: { - if (peer_data == NULL) - return 0; - - int32_t id = peer_data->peer_id; - if (_peer_map.has(id)) { - int code; - Ref<LWSPeer> peer = _peer_map[id]; - String reason2 = peer->get_close_reason(in, len, code); - peer_data->clean_close = true; - _on_close_request(id, code, reason2); - } - return 0; - } - - case LWS_CALLBACK_CLOSED: { - if (peer_data == NULL) - return 0; - int32_t id = peer_data->peer_id; - bool clean = peer_data->clean_close; - if (_peer_map.has(id)) { - _peer_map[id]->close(); - _peer_map.erase(id); - } - _on_disconnect(id, clean); - return 0; // we can end here - } - - case LWS_CALLBACK_RECEIVE: { - int32_t id = peer_data->peer_id; - if (_peer_map.has(id)) { - static_cast<Ref<LWSPeer> >(_peer_map[id])->read_wsi(in, len); - if (_peer_map[id]->get_available_packet_count() > 0) - _on_peer_packet(id); - } - break; - } - - case LWS_CALLBACK_SERVER_WRITEABLE: { - int id = peer_data->peer_id; - if (peer_data->force_close) { - if (_peer_map.has(id)) { - Ref<LWSPeer> peer = _peer_map[id]; - peer->send_close_status(wsi); - } - return -1; - } - - if (_peer_map.has(id)) - static_cast<Ref<LWSPeer> >(_peer_map[id])->write_wsi(); - break; - } - - default: - break; - } - - return 0; -} - -void LWSServer::stop() { - if (context == NULL) - return; - - _peer_map.clear(); - destroy_context(); - context = NULL; -} - -bool LWSServer::has_peer(int p_id) const { - return _peer_map.has(p_id); -} - -Ref<WebSocketPeer> LWSServer::get_peer(int p_id) const { - ERR_FAIL_COND_V(!has_peer(p_id), NULL); - return _peer_map[p_id]; -} - -IP_Address LWSServer::get_peer_address(int p_peer_id) const { - ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address()); - - return _peer_map[p_peer_id]->get_connected_host(); -} - -int LWSServer::get_peer_port(int p_peer_id) const { - ERR_FAIL_COND_V(!has_peer(p_peer_id), 0); - - return _peer_map[p_peer_id]->get_connected_port(); -} - -void LWSServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) { - ERR_FAIL_COND(!has_peer(p_peer_id)); - - get_peer(p_peer_id)->close(p_code, p_reason); -} - -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); - _out_buf_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_BUF) - 1) + 10; - _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_PKT) - 1); - context = NULL; - _lws_ref = NULL; -} - -LWSServer::~LWSServer() { - invalidate_lws_ref(); // we do not want any more callbacks - stop(); -} - -#endif // JAVASCRIPT_ENABLED diff --git a/modules/websocket/register_types.cpp b/modules/websocket/register_types.cpp index ed6cc5638e..1c808f0d5c 100644 --- a/modules/websocket/register_types.cpp +++ b/modules/websocket/register_types.cpp @@ -37,9 +37,8 @@ #include "emws_peer.h" #include "emws_server.h" #else -#include "lws_client.h" -#include "lws_peer.h" -#include "lws_server.h" +#include "wsl_client.h" +#include "wsl_server.h" #endif void register_websocket_types() { @@ -60,32 +59,13 @@ void register_websocket_types() { _SET_HINT(WSS_OUT_PKT, 1024, 16384); #ifdef JAVASCRIPT_ENABLED - EM_ASM({ - var IDHandler = {}; - IDHandler["ids"] = {}; - IDHandler["has"] = function(id) { - return IDHandler.ids.hasOwnProperty(id); - }; - IDHandler["add"] = function(obj) { - var id = crypto.getRandomValues(new Int32Array(32))[0]; - IDHandler.ids[id] = obj; - return id; - }; - IDHandler["get"] = function(id) { - return IDHandler.ids[id]; - }; - IDHandler["remove"] = function(id) { - delete IDHandler.ids[id]; - }; - Module["IDHandler"] = IDHandler; - }); EMWSPeer::make_default(); EMWSClient::make_default(); EMWSServer::make_default(); #else - LWSPeer::make_default(); - LWSClient::make_default(); - LWSServer::make_default(); + WSLPeer::make_default(); + WSLClient::make_default(); + WSLServer::make_default(); #endif ClassDB::register_virtual_class<WebSocketMultiplayerPeer>(); diff --git a/modules/websocket/websocket_client.cpp b/modules/websocket/websocket_client.cpp index 4ff5404c61..8bbd5aa37f 100644 --- a/modules/websocket/websocket_client.cpp +++ b/modules/websocket/websocket_client.cpp @@ -40,7 +40,7 @@ WebSocketClient::WebSocketClient() { WebSocketClient::~WebSocketClient() { } -Error WebSocketClient::connect_to_url(String p_url, PoolVector<String> p_protocols, bool gd_mp_api) { +Error WebSocketClient::connect_to_url(String p_url, const Vector<String> p_protocols, bool gd_mp_api, const Vector<String> p_custom_headers) { _is_multiplayer = gd_mp_api; String host = p_url; @@ -72,7 +72,7 @@ Error WebSocketClient::connect_to_url(String p_url, PoolVector<String> p_protoco host = host.substr(0, p_len); } - return connect_to_host(host, path, port, ssl, p_protocols); + return connect_to_host(host, path, port, ssl, p_protocols, p_custom_headers); } void WebSocketClient::set_verify_ssl_enabled(bool p_verify_ssl) { @@ -85,6 +85,17 @@ bool WebSocketClient::is_verify_ssl_enabled() const { return verify_ssl; } +Ref<X509Certificate> WebSocketClient::get_trusted_ssl_certificate() const { + + return ssl_cert; +} + +void WebSocketClient::set_trusted_ssl_certificate(Ref<X509Certificate> p_cert) { + + ERR_FAIL_COND(get_connection_status() != CONNECTION_DISCONNECTED); + ssl_cert = p_cert; +} + bool WebSocketClient::is_server() const { return false; @@ -132,13 +143,20 @@ void WebSocketClient::_on_error() { } void WebSocketClient::_bind_methods() { - ClassDB::bind_method(D_METHOD("connect_to_url", "url", "protocols", "gd_mp_api"), &WebSocketClient::connect_to_url, DEFVAL(PoolVector<String>()), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("connect_to_url", "url", "protocols", "gd_mp_api", "custom_headers"), &WebSocketClient::connect_to_url, DEFVAL(Vector<String>()), DEFVAL(false), DEFVAL(Vector<String>())); ClassDB::bind_method(D_METHOD("disconnect_from_host", "code", "reason"), &WebSocketClient::disconnect_from_host, DEFVAL(1000), DEFVAL("")); + ClassDB::bind_method(D_METHOD("get_connected_host"), &WebSocketClient::get_connected_host); + ClassDB::bind_method(D_METHOD("get_connected_port"), &WebSocketClient::get_connected_port); ClassDB::bind_method(D_METHOD("set_verify_ssl_enabled", "enabled"), &WebSocketClient::set_verify_ssl_enabled); ClassDB::bind_method(D_METHOD("is_verify_ssl_enabled"), &WebSocketClient::is_verify_ssl_enabled); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "verify_ssl", PROPERTY_HINT_NONE, "", 0), "set_verify_ssl_enabled", "is_verify_ssl_enabled"); + ClassDB::bind_method(D_METHOD("get_trusted_ssl_certificate"), &WebSocketClient::get_trusted_ssl_certificate); + ClassDB::bind_method(D_METHOD("set_trusted_ssl_certificate"), &WebSocketClient::set_trusted_ssl_certificate); + + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "trusted_ssl_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", 0), "set_trusted_ssl_certificate", "get_trusted_ssl_certificate"); + ADD_SIGNAL(MethodInfo("data_received")); ADD_SIGNAL(MethodInfo("connection_established", PropertyInfo(Variant::STRING, "protocol"))); ADD_SIGNAL(MethodInfo("server_close_request", PropertyInfo(Variant::INT, "code"), PropertyInfo(Variant::STRING, "reason"))); diff --git a/modules/websocket/websocket_client.h b/modules/websocket/websocket_client.h index c464d97c7f..08fd6798fe 100644 --- a/modules/websocket/websocket_client.h +++ b/modules/websocket/websocket_client.h @@ -31,6 +31,7 @@ #ifndef WEBSOCKET_CLIENT_H #define WEBSOCKET_CLIENT_H +#include "core/crypto/crypto.h" #include "core/error_list.h" #include "websocket_multiplayer_peer.h" #include "websocket_peer.h" @@ -43,17 +44,20 @@ class WebSocketClient : public WebSocketMultiplayerPeer { protected: Ref<WebSocketPeer> _peer; bool verify_ssl; + Ref<X509Certificate> ssl_cert; static void _bind_methods(); public: - Error connect_to_url(String p_url, PoolVector<String> p_protocols = PoolVector<String>(), bool gd_mp_api = false); + Error connect_to_url(String p_url, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false, const Vector<String> p_custom_headers = Vector<String>()); void set_verify_ssl_enabled(bool p_verify_ssl); bool is_verify_ssl_enabled() const; + Ref<X509Certificate> get_trusted_ssl_certificate() const; + void set_trusted_ssl_certificate(Ref<X509Certificate> p_cert); virtual void poll() = 0; - virtual Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocol = PoolVector<String>()) = 0; + virtual Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) = 0; virtual void disconnect_from_host(int p_code = 1000, String p_reason = "") = 0; virtual IP_Address get_connected_host() const = 0; virtual uint16_t get_connected_port() const = 0; @@ -67,6 +71,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..dd86c758bf 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"))); @@ -97,16 +98,14 @@ void WebSocketMultiplayerPeer::_bind_methods() { // int WebSocketMultiplayerPeer::get_available_packet_count() const { - ERR_EXPLAIN("Please use get_peer(ID).get_available_packet_count to get available packet count from peers when not using the MultiplayerAPI."); - ERR_FAIL_COND_V(!_is_multiplayer, ERR_UNCONFIGURED); + ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).get_available_packet_count to get available packet count from peers when not using the MultiplayerAPI."); return _incoming_packets.size(); } Error WebSocketMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { - ERR_EXPLAIN("Please use get_peer(ID).get_packet/var to communicate with peers when not using the MultiplayerAPI."); - ERR_FAIL_COND_V(!_is_multiplayer, ERR_UNCONFIGURED); + ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).get_packet/var to communicate with peers when not using the MultiplayerAPI."); r_buffer_size = 0; @@ -126,8 +125,7 @@ Error WebSocketMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buff Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_EXPLAIN("Please use get_peer(ID).put_packet/var to communicate with peers when not using the MultiplayerAPI."); - ERR_FAIL_COND_V(!_is_multiplayer, ERR_UNCONFIGURED); + ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).put_packet/var to communicate with peers when not using the MultiplayerAPI."); PoolVector<uint8_t> buffer = _make_pkt(SYS_NONE, get_unique_id(), _target_peer, p_buffer, p_buffer_size); @@ -159,8 +157,7 @@ void WebSocketMultiplayerPeer::set_target_peer(int p_target_peer) { int WebSocketMultiplayerPeer::get_packet_peer() const { - ERR_EXPLAIN("This function is not available when not using the MultiplayerAPI."); - ERR_FAIL_COND_V(!_is_multiplayer, 1); + ERR_FAIL_COND_V_MSG(!_is_multiplayer, 1, "This function is not available when not using the MultiplayerAPI."); ERR_FAIL_COND_V(_incoming_packets.size() == 0, 1); return _incoming_packets.front()->get().source; @@ -190,7 +187,7 @@ void WebSocketMultiplayerPeer::_send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_ty p_peer->put_packet(&(message.read()[0]), message.size()); } -PoolVector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint32_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size) { +PoolVector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size) { PoolVector<uint8_t> out; out.resize(PROTO_SIZE + p_data_size); @@ -268,7 +265,10 @@ Error WebSocketMultiplayerPeer::_server_relay(int32_t p_from, int32_t p_to, cons ERR_FAIL_COND_V(p_to == p_from, FAILED); - return get_peer(p_to)->put_packet(p_buffer, p_buffer_size); // Sending to specific peer + Ref<WebSocketPeer> peer_to = get_peer(p_to); + ERR_FAIL_COND_V(peer_to.is_null(), FAILED); + + return peer_to->put_packet(p_buffer, p_buffer_size); // Sending to specific peer } } @@ -299,8 +299,6 @@ void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, u ERR_FAIL_COND(type != SYS_NONE); // Only server sends sys messages ERR_FAIL_COND(from != p_peer_id); // Someone is cheating - _server_relay(from, to, in_buffer, size); // Relay if needed - if (to == 1) { // This is for the server _store_pkt(from, to, in_buffer, data_size); @@ -315,13 +313,9 @@ void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, u // All but one, for us if not excluded if (_peer_id != -(int32_t)p_peer_id) _store_pkt(from, to, in_buffer, data_size); - - } else { - - // Send to specific peer - ERR_FAIL_COND(!_peer_map.has(to)); - get_peer(to)->put_packet(in_buffer, size); } + // Relay if needed (i.e. "to" includes a peer that is not the server) + _server_relay(from, to, in_buffer, size); } else { @@ -353,8 +347,7 @@ void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, u _peer_id = id; break; default: - ERR_EXPLAIN("Invalid multiplayer message"); - ERR_FAIL(); + ERR_FAIL_MSG("Invalid multiplayer message."); break; } } diff --git a/modules/websocket/websocket_multiplayer_peer.h b/modules/websocket/websocket_multiplayer_peer.h index b050449ee0..e3ab0784ab 100644 --- a/modules/websocket/websocket_multiplayer_peer.h +++ b/modules/websocket/websocket_multiplayer_peer.h @@ -41,7 +41,7 @@ class WebSocketMultiplayerPeer : public NetworkedMultiplayerPeer { GDCLASS(WebSocketMultiplayerPeer, NetworkedMultiplayerPeer); private: - PoolVector<uint8_t> _make_pkt(uint32_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size); + PoolVector<uint8_t> _make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size); void _store_pkt(int32_t p_source, int32_t p_dest, const uint8_t *p_data, uint32_t p_data_size); Error _server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size); @@ -82,7 +82,7 @@ public: /* NetworkedMultiplayerPeer */ void set_transfer_mode(TransferMode p_mode); TransferMode get_transfer_mode() const; - void set_target_peer(int p_peer_id); + void set_target_peer(int p_target_peer); int get_packet_peer() const; int get_unique_id() const; virtual bool is_server() const = 0; @@ -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.cpp b/modules/websocket/websocket_server.cpp index ef5f6f5c20..c7414075ed 100644 --- a/modules/websocket/websocket_server.cpp +++ b/modules/websocket/websocket_server.cpp @@ -42,19 +42,58 @@ WebSocketServer::~WebSocketServer() { void WebSocketServer::_bind_methods() { ClassDB::bind_method(D_METHOD("is_listening"), &WebSocketServer::is_listening); - ClassDB::bind_method(D_METHOD("listen", "port", "protocols", "gd_mp_api"), &WebSocketServer::listen, DEFVAL(PoolVector<String>()), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("listen", "port", "protocols", "gd_mp_api"), &WebSocketServer::listen, DEFVAL(Vector<String>()), DEFVAL(false)); ClassDB::bind_method(D_METHOD("stop"), &WebSocketServer::stop); ClassDB::bind_method(D_METHOD("has_peer", "id"), &WebSocketServer::has_peer); ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &WebSocketServer::get_peer_address); ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &WebSocketServer::get_peer_port); ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "code", "reason"), &WebSocketServer::disconnect_peer, DEFVAL(1000), DEFVAL("")); + ClassDB::bind_method(D_METHOD("get_private_key"), &WebSocketServer::get_private_key); + ClassDB::bind_method(D_METHOD("set_private_key"), &WebSocketServer::set_private_key); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "private_key", PROPERTY_HINT_RESOURCE_TYPE, "CryptoKey", 0), "set_private_key", "get_private_key"); + + ClassDB::bind_method(D_METHOD("get_ssl_certificate"), &WebSocketServer::get_ssl_certificate); + ClassDB::bind_method(D_METHOD("set_ssl_certificate"), &WebSocketServer::set_ssl_certificate); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "ssl_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", 0), "set_ssl_certificate", "get_ssl_certificate"); + + ClassDB::bind_method(D_METHOD("get_ca_chain"), &WebSocketServer::get_ca_chain); + ClassDB::bind_method(D_METHOD("set_ca_chain"), &WebSocketServer::set_ca_chain); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "ca_chain", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", 0), "set_ca_chain", "get_ca_chain"); + ADD_SIGNAL(MethodInfo("client_close_request", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::INT, "code"), PropertyInfo(Variant::STRING, "reason"))); ADD_SIGNAL(MethodInfo("client_disconnected", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::BOOL, "was_clean_close"))); ADD_SIGNAL(MethodInfo("client_connected", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::STRING, "protocol"))); ADD_SIGNAL(MethodInfo("data_received", PropertyInfo(Variant::INT, "id"))); } +Ref<CryptoKey> WebSocketServer::get_private_key() const { + return private_key; +} + +void WebSocketServer::set_private_key(Ref<CryptoKey> p_key) { + ERR_FAIL_COND(is_listening()); + private_key = p_key; +} + +Ref<X509Certificate> WebSocketServer::get_ssl_certificate() const { + return ssl_cert; +} + +void WebSocketServer::set_ssl_certificate(Ref<X509Certificate> p_cert) { + ERR_FAIL_COND(is_listening()); + ssl_cert = p_cert; +} + +Ref<X509Certificate> WebSocketServer::get_ca_chain() const { + return ca_chain; +} + +void WebSocketServer::set_ca_chain(Ref<X509Certificate> p_ca_chain) { + ERR_FAIL_COND(is_listening()); + ca_chain = p_ca_chain; +} + NetworkedMultiplayerPeer::ConnectionStatus WebSocketServer::get_connection_status() const { if (is_listening()) return CONNECTION_CONNECTED; diff --git a/modules/websocket/websocket_server.h b/modules/websocket/websocket_server.h index 7a94c4047b..0b39f94473 100644 --- a/modules/websocket/websocket_server.h +++ b/modules/websocket/websocket_server.h @@ -31,6 +31,7 @@ #ifndef WEBSOCKET_H #define WEBSOCKET_H +#include "core/crypto/crypto.h" #include "core/reference.h" #include "websocket_multiplayer_peer.h" #include "websocket_peer.h" @@ -43,9 +44,13 @@ class WebSocketServer : public WebSocketMultiplayerPeer { protected: static void _bind_methods(); + Ref<CryptoKey> private_key; + Ref<X509Certificate> ssl_cert; + Ref<X509Certificate> ca_chain; + public: virtual void poll() = 0; - virtual Error listen(int p_port, PoolVector<String> p_protocols = PoolVector<String>(), bool gd_mp_api = false) = 0; + virtual Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) = 0; virtual void stop() = 0; virtual bool is_listening() const = 0; virtual bool has_peer(int p_id) const = 0; @@ -62,6 +67,17 @@ 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); + Ref<CryptoKey> get_private_key() const; + void set_private_key(Ref<CryptoKey> p_key); + + Ref<X509Certificate> get_ssl_certificate() const; + void set_ssl_certificate(Ref<X509Certificate> p_cert); + + Ref<X509Certificate> get_ca_chain() const; + void set_ca_chain(Ref<X509Certificate> p_ca_chain); + + virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0; + WebSocketServer(); ~WebSocketServer(); }; diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp new file mode 100644 index 0000000000..ad70c9c0e1 --- /dev/null +++ b/modules/websocket/wsl_client.cpp @@ -0,0 +1,355 @@ +/*************************************************************************/ +/* wsl_client.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. */ +/*************************************************************************/ + +#ifndef JAVASCRIPT_ENABLED + +#include "wsl_client.h" +#include "core/io/ip.h" +#include "core/project_settings.h" + +void WSLClient::_do_handshake() { + if (_requested < _request.size() - 1) { + int sent = 0; + Error err = _connection->put_partial_data(((const uint8_t *)_request.get_data() + _requested), _request.size() - _requested - 1, sent); + // Sending handshake failed + if (err != OK) { + disconnect_from_host(); + _on_error(); + return; + } + _requested += sent; + + } else { + int read = 0; + while (true) { + if (_resp_pos >= WSL_MAX_HEADER_SIZE) { + // Header is too big + disconnect_from_host(); + _on_error(); + ERR_FAIL_MSG("Response headers too big."); + } + Error err = _connection->get_partial_data(&_resp_buf[_resp_pos], 1, read); + if (err == ERR_FILE_EOF) { + // We got a disconnect. + disconnect_from_host(); + _on_error(); + return; + } else if (err != OK) { + // Got some error. + disconnect_from_host(); + _on_error(); + return; + } else if (read != 1) { + // Busy, wait next poll. + break; + } + // Check "\r\n\r\n" header terminator + char *r = (char *)_resp_buf; + int l = _resp_pos; + if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') { + r[l - 3] = '\0'; + String protocol; + // Response is over, verify headers and create peer. + if (!_verify_headers(protocol)) { + disconnect_from_host(); + _on_error(); + ERR_FAIL_MSG("Invalid response headers."); + } + // Create peer. + WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData); + data->obj = this; + data->conn = _connection; + data->tcp = _tcp; + data->is_server = false; + data->id = 1; + _peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size); + _on_connect(protocol); + break; + } + _resp_pos += 1; + } + } +} + +bool WSLClient::_verify_headers(String &r_protocol) { + String s = (char *)_resp_buf; + Vector<String> psa = s.split("\r\n"); + int len = psa.size(); + ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4."); + + Vector<String> req = psa[0].split(" ", false); + ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code."); + + // Wrong protocol + ERR_FAIL_COND_V_MSG(req[0] != "HTTP/1.1" || req[1] != "101", false, "Invalid protocol or status code."); + + Map<String, String> headers; + for (int i = 1; i < len; i++) { + Vector<String> header = psa[i].split(":", false, 1); + ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i] + "."); + String name = header[0].to_lower(); + String value = header[1].strip_edges(); + if (headers.has(name)) + headers[name] += "," + value; + else + headers[name] = value; + } + +#define _WSL_CHECK(NAME, VALUE) \ + ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \ + "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); +#define _WSL_CHECK_NC(NAME, VALUE) \ + ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME] != VALUE, false, \ + "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); + _WSL_CHECK("connection", "upgrade"); + _WSL_CHECK("upgrade", "websocket"); + _WSL_CHECK_NC("sec-websocket-accept", WSLPeer::compute_key_response(_key)); +#undef _WSL_CHECK_NC +#undef _WSL_CHECK + if (_protocols.size() == 0) { + // We didn't request a custom protocol + ERR_FAIL_COND_V(headers.has("sec-websocket-protocol"), false); + } else { + ERR_FAIL_COND_V(!headers.has("sec-websocket-protocol"), false); + r_protocol = headers["sec-websocket-protocol"]; + bool valid = false; + for (int i = 0; i < _protocols.size(); i++) { + if (_protocols[i] != r_protocol) + continue; + valid = true; + break; + } + if (!valid) + return false; + } + return true; +} + +Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocols, const Vector<String> p_custom_headers) { + + ERR_FAIL_COND_V(_connection.is_valid(), ERR_ALREADY_IN_USE); + + _peer = Ref<WSLPeer>(memnew(WSLPeer)); + IP_Address addr; + + if (!p_host.is_valid_ip_address()) { + addr = IP::get_singleton()->resolve_hostname(p_host); + } else { + addr = p_host; + } + + ERR_FAIL_COND_V(!addr.is_valid(), ERR_INVALID_PARAMETER); + + String port = ""; + if ((p_port != 80 && !p_ssl) || (p_port != 443 && p_ssl)) { + port = ":" + itos(p_port); + } + + Error err = _tcp->connect_to_host(addr, p_port); + if (err != OK) { + _tcp->disconnect_from_host(); + _on_error(); + return err; + } + _connection = _tcp; + _use_ssl = p_ssl; + _host = p_host; + // Strip edges from protocols. + _protocols.resize(p_protocols.size()); + String *pw = _protocols.ptrw(); + for (int i = 0; i < p_protocols.size(); i++) { + pw[i] = p_protocols[i].strip_edges(); + } + + _key = WSLPeer::generate_key(); + // TODO custom extra headers (allow overriding this too?) + String request = "GET " + p_path + " HTTP/1.1\r\n"; + request += "Host: " + p_host + port + "\r\n"; + request += "Upgrade: websocket\r\n"; + request += "Connection: Upgrade\r\n"; + request += "Sec-WebSocket-Key: " + _key + "\r\n"; + request += "Sec-WebSocket-Version: 13\r\n"; + if (p_protocols.size() > 0) { + request += "Sec-WebSocket-Protocol: "; + for (int i = 0; i < p_protocols.size(); i++) { + if (i != 0) + request += ","; + request += p_protocols[i]; + } + request += "\r\n"; + } + for (int i = 0; i < p_custom_headers.size(); i++) { + request += p_custom_headers[i] + "\r\n"; + } + request += "\r\n"; + _request = request.utf8(); + + return OK; +} + +int WSLClient::get_max_packet_size() const { + return (1 << _out_buf_size) - PROTO_SIZE; +} + +void WSLClient::poll() { + if (_peer->is_connected_to_host()) { + _peer->poll(); + if (!_peer->is_connected_to_host()) { + disconnect_from_host(); + _on_disconnect(_peer->close_code != -1); + } + return; + } + + if (_connection.is_null()) + return; // Not connected. + + switch (_tcp->get_status()) { + case StreamPeerTCP::STATUS_NONE: + // Clean close + disconnect_from_host(); + _on_error(); + break; + case StreamPeerTCP::STATUS_CONNECTED: { + Ref<StreamPeerSSL> ssl; + if (_use_ssl) { + if (_connection == _tcp) { + // Start SSL handshake + ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create()); + ERR_FAIL_COND_MSG(ssl.is_null(), "SSL is not available in this build."); + ssl->set_blocking_handshake_enabled(false); + if (ssl->connect_to_stream(_tcp, verify_ssl, _host, ssl_cert) != OK) { + disconnect_from_host(); + _on_error(); + return; + } + _connection = ssl; + } else { + ssl = static_cast<Ref<StreamPeerSSL> >(_connection); + ERR_FAIL_COND(ssl.is_null()); // Bug? + ssl->poll(); + } + if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) + return; // Need more polling. + else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) { + disconnect_from_host(); + _on_error(); + return; // Error. + } + } + // Do websocket handshake. + _do_handshake(); + } break; + case StreamPeerTCP::STATUS_ERROR: + disconnect_from_host(); + _on_error(); + break; + case StreamPeerTCP::STATUS_CONNECTING: + break; // Wait for connection + } +} + +Ref<WebSocketPeer> WSLClient::get_peer(int p_peer_id) const { + + ERR_FAIL_COND_V(p_peer_id != 1, NULL); + + return _peer; +} + +NetworkedMultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const { + + if (_peer->is_connected_to_host()) + return CONNECTION_CONNECTED; + + if (_tcp->is_connected_to_host()) + return CONNECTION_CONNECTING; + + return CONNECTION_DISCONNECTED; +} + +void WSLClient::disconnect_from_host(int p_code, String p_reason) { + + _peer->close(p_code, p_reason); + _connection = Ref<StreamPeer>(NULL); + _tcp = Ref<StreamPeerTCP>(memnew(StreamPeerTCP)); + + _key = ""; + _host = ""; + _protocols.clear(); + _use_ssl = false; + + _request = ""; + _requested = 0; + + memset(_resp_buf, 0, sizeof(_resp_buf)); + _resp_pos = 0; +} + +IP_Address WSLClient::get_connected_host() const { + + ERR_FAIL_COND_V(!_peer->is_connected_to_host(), IP_Address()); + return _peer->get_connected_host(); +} + +uint16_t WSLClient::get_connected_port() const { + + ERR_FAIL_COND_V(!_peer->is_connected_to_host(), 0); + return _peer->get_connected_port(); +} + +Error WSLClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) { + ERR_FAIL_COND_V_MSG(_connection.is_valid(), FAILED, "Buffers sizes can only be set before listening or connecting."); + + _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; +} + +WSLClient::WSLClient() { + _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); + _out_buf_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_BUF) - 1) + 10; + _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_PKT) - 1); + + _peer.instance(); + _tcp.instance(); + disconnect_from_host(); +} + +WSLClient::~WSLClient() { + + _peer->close_now(); + _peer->invalidate(); + disconnect_from_host(); +} + +#endif // JAVASCRIPT_ENABLED diff --git a/modules/websocket/lws_client.h b/modules/websocket/wsl_client.h index b3a1237550..870be94a87 100644 --- a/modules/websocket/lws_client.h +++ b/modules/websocket/wsl_client.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* lws_client.h */ +/* wsl_client.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,21 +28,21 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef LWSCLIENT_H -#define LWSCLIENT_H +#ifndef WSLCLIENT_H +#define WSLCLIENT_H #ifndef JAVASCRIPT_ENABLED #include "core/error_list.h" -#include "lws_helper.h" -#include "lws_peer.h" +#include "core/io/stream_peer_ssl.h" +#include "core/io/stream_peer_tcp.h" #include "websocket_client.h" +#include "wsl_peer.h" +#include "wslay/wslay.h" -class LWSClient : public WebSocketClient { +class WSLClient : public WebSocketClient { - GDCIIMPL(LWSClient, WebSocketClient); - - LWS_HELPER(LWSClient); + GDCIIMPL(WSLClient, WebSocketClient); private: int _in_buf_size; @@ -50,8 +50,29 @@ private: int _out_buf_size; int _out_pkt_size; + Ref<WSLPeer> _peer; + Ref<StreamPeerTCP> _tcp; + Ref<StreamPeer> _connection; + + CharString _request; + int _requested; + + uint8_t _resp_buf[WSL_MAX_HEADER_SIZE]; + int _resp_pos; + + String _response; + + String _key; + String _host; + Vector<String> _protocols; + bool _use_ssl; + + void _do_handshake(); + bool _verify_headers(String &r_protocol); + public: - Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocol = PoolVector<String>()); + 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, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()); int get_max_packet_size() const; Ref<WebSocketPeer> get_peer(int p_peer_id) const; void disconnect_from_host(int p_code = 1000, String p_reason = ""); @@ -60,10 +81,10 @@ public: virtual ConnectionStatus get_connection_status() const; virtual void poll(); - LWSClient(); - ~LWSClient(); + WSLClient(); + ~WSLClient(); }; #endif // JAVASCRIPT_ENABLED -#endif // LWSCLIENT_H +#endif // WSLCLIENT_H diff --git a/modules/websocket/wsl_peer.cpp b/modules/websocket/wsl_peer.cpp new file mode 100644 index 0000000000..9d610109ed --- /dev/null +++ b/modules/websocket/wsl_peer.cpp @@ -0,0 +1,336 @@ +/*************************************************************************/ +/* wsl_peer.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. */ +/*************************************************************************/ + +#ifndef JAVASCRIPT_ENABLED + +#include "wsl_peer.h" + +#include "wsl_client.h" +#include "wsl_server.h" + +#include "core/crypto/crypto_core.h" +#include "core/math/random_number_generator.h" +#include "core/os/os.h" + +String WSLPeer::generate_key() { + // Random key + RandomNumberGenerator rng; + rng.set_seed(OS::get_singleton()->get_unix_time()); + PoolVector<uint8_t> bkey; + int len = 16; // 16 bytes, as per RFC + bkey.resize(len); + PoolVector<uint8_t>::Write w = bkey.write(); + for (int i = 0; i < len; i++) { + w[i] = (uint8_t)rng.randi_range(0, 255); + } + return CryptoCore::b64_encode_str(&w[0], len); +} + +String WSLPeer::compute_key_response(String p_key) { + String key = p_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Magic UUID as per RFC + Vector<uint8_t> sha = key.sha1_buffer(); + return CryptoCore::b64_encode_str(sha.ptr(), sha.size()); +} + +void WSLPeer::_wsl_destroy(struct PeerData **p_data) { + if (!p_data || !(*p_data)) + return; + struct PeerData *data = *p_data; + if (data->polling) { + data->destroy = true; + return; + } + wslay_event_context_free(data->ctx); + memdelete(data); + *p_data = NULL; +} + +bool WSLPeer::_wsl_poll(struct PeerData *p_data) { + p_data->polling = true; + int err = 0; + if ((err = wslay_event_recv(p_data->ctx)) != 0 || (err = wslay_event_send(p_data->ctx)) != 0) { + print_verbose("Websocket (wslay) poll error: " + itos(err)); + p_data->destroy = true; + } + p_data->polling = false; + + if (p_data->destroy || (wslay_event_get_close_sent(p_data->ctx) && wslay_event_get_close_received(p_data->ctx))) { + bool valid = p_data->valid; + _wsl_destroy(&p_data); + return valid; + } + return false; +} + +ssize_t wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) { + struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data; + if (!peer_data->valid) { + wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); + return -1; + } + Ref<StreamPeer> conn = peer_data->conn; + int read = 0; + Error err = conn->get_partial_data(data, len, read); + if (err != OK) { + print_verbose("Websocket get data error: " + itos(err) + ", read (should be 0!): " + itos(read)); + wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); + return -1; + } + if (read == 0) { + wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK); + return -1; + } + return read; +} + +ssize_t wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) { + struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data; + if (!peer_data->valid) { + wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); + return -1; + } + Ref<StreamPeer> conn = peer_data->conn; + int sent = 0; + Error err = conn->put_partial_data(data, len, sent); + if (err != OK) { + wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE); + return -1; + } + if (sent == 0) { + wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK); + return -1; + } + return sent; +} + +int wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) { + RandomNumberGenerator rng; + // TODO maybe use crypto in the future? + rng.set_seed(OS::get_singleton()->get_unix_time()); + for (unsigned int i = 0; i < len; i++) { + buf[i] = (uint8_t)rng.randi_range(0, 255); + } + return 0; +} + +void wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) { + struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data; + if (!peer_data->valid) { + return; + } + WSLPeer *peer = (WSLPeer *)peer_data->peer; + + if (peer->parse_message(arg) != OK) + return; + + if (peer_data->is_server) { + WSLServer *helper = (WSLServer *)peer_data->obj; + helper->_on_peer_packet(peer_data->id); + } else { + WSLClient *helper = (WSLClient *)peer_data->obj; + helper->_on_peer_packet(); + } +} + +wslay_event_callbacks wsl_callbacks = { + wsl_recv_callback, + wsl_send_callback, + wsl_genmask_callback, + NULL, /* on_frame_recv_start_callback */ + NULL, /* on_frame_recv_callback */ + NULL, /* on_frame_recv_end_callback */ + wsl_msg_recv_callback +}; + +Error WSLPeer::parse_message(const wslay_event_on_msg_recv_arg *arg) { + uint8_t is_string = 0; + if (arg->opcode == WSLAY_TEXT_FRAME) { + is_string = 1; + } else if (arg->opcode == WSLAY_CONNECTION_CLOSE) { + close_code = arg->status_code; + size_t len = arg->msg_length; + close_reason = ""; + if (len > 2 /* first 2 bytes = close code */) { + close_reason.parse_utf8((char *)arg->msg + 2, len - 2); + } + if (!wslay_event_get_close_sent(_data->ctx)) { + if (_data->is_server) { + WSLServer *helper = (WSLServer *)_data->obj; + helper->_on_close_request(_data->id, close_code, close_reason); + } else { + WSLClient *helper = (WSLClient *)_data->obj; + helper->_on_close_request(close_code, close_reason); + } + } + return ERR_FILE_EOF; + } else if (arg->opcode != WSLAY_BINARY_FRAME) { + // Ping or pong + return ERR_SKIP; + } + _in_buffer.write_packet(arg->msg, arg->msg_length, &is_string); + return OK; +} + +void WSLPeer::make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size) { + ERR_FAIL_COND(_data != NULL); + ERR_FAIL_COND(p_data == NULL); + + _in_buffer.resize(p_in_pkt_size, p_in_buf_size); + _packet_buffer.resize((1 << MAX(p_in_buf_size, p_out_buf_size))); + + _data = p_data; + _data->peer = this; + _data->valid = true; + + if (_data->is_server) + wslay_event_context_server_init(&(_data->ctx), &wsl_callbacks, _data); + else + wslay_event_context_client_init(&(_data->ctx), &wsl_callbacks, _data); + wslay_event_config_set_max_recv_msg_length(_data->ctx, (1ULL << p_in_buf_size)); +} + +void WSLPeer::set_write_mode(WriteMode p_mode) { + write_mode = p_mode; +} + +WSLPeer::WriteMode WSLPeer::get_write_mode() const { + return write_mode; +} + +void WSLPeer::poll() { + if (!_data) + return; + + if (_wsl_poll(_data)) { + _data = NULL; + } +} + +Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + + ERR_FAIL_COND_V(!is_connected_to_host(), FAILED); + + struct wslay_event_msg msg; // Should I use fragmented? + msg.opcode = write_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME; + msg.msg = p_buffer; + msg.msg_length = p_buffer_size; + + wslay_event_queue_msg(_data->ctx, &msg); + return OK; +} + +Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + + r_buffer_size = 0; + + ERR_FAIL_COND_V(!is_connected_to_host(), FAILED); + + if (_in_buffer.packets_left() == 0) + return ERR_UNAVAILABLE; + + int read = 0; + PoolVector<uint8_t>::Write rw = _packet_buffer.write(); + _in_buffer.read_packet(rw.ptr(), _packet_buffer.size(), &_is_string, read); + + *r_buffer = rw.ptr(); + r_buffer_size = read; + + return OK; +} + +int WSLPeer::get_available_packet_count() const { + + if (!is_connected_to_host()) + return 0; + + return _in_buffer.packets_left(); +} + +bool WSLPeer::was_string_packet() const { + + return _is_string; +} + +bool WSLPeer::is_connected_to_host() const { + + return _data != NULL; +} + +void WSLPeer::close_now() { + close(1000, ""); + _wsl_destroy(&_data); +} + +void WSLPeer::close(int p_code, String p_reason) { + if (_data && !wslay_event_get_close_sent(_data->ctx)) { + CharString cs = p_reason.utf8(); + wslay_event_queue_close(_data->ctx, p_code, (uint8_t *)cs.ptr(), cs.size()); + wslay_event_send(_data->ctx); + } + + _in_buffer.clear(); + _packet_buffer.resize(0); +} + +IP_Address WSLPeer::get_connected_host() const { + + ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), IP_Address()); + + return _data->tcp->get_connected_host(); +} + +uint16_t WSLPeer::get_connected_port() const { + + ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), 0); + + return _data->tcp->get_connected_port(); +} + +void WSLPeer::invalidate() { + if (_data) + _data->valid = false; +} + +WSLPeer::WSLPeer() { + _data = NULL; + _is_string = 0; + close_code = -1; + write_mode = WRITE_MODE_BINARY; +} + +WSLPeer::~WSLPeer() { + + close(); + invalidate(); + _wsl_destroy(&_data); + _data = NULL; +} + +#endif // JAVASCRIPT_ENABLED diff --git a/modules/websocket/lws_peer.h b/modules/websocket/wsl_peer.h index 6771c13094..01ad250468 100644 --- a/modules/websocket/lws_peer.h +++ b/modules/websocket/wsl_peer.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* lws_peer.h */ +/* wsl_peer.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,50 +28,77 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef LWSPEER_H -#define LWSPEER_H +#ifndef WSLPEER_H +#define WSLPEER_H #ifndef JAVASCRIPT_ENABLED #include "core/error_list.h" #include "core/io/packet_peer.h" +#include "core/io/stream_peer_tcp.h" #include "core/ring_buffer.h" -#include "libwebsockets.h" -#include "lws_config.h" #include "packet_buffer.h" #include "websocket_peer.h" +#include "wslay/wslay.h" -class LWSPeer : public WebSocketPeer { +#define WSL_MAX_HEADER_SIZE 4096 - GDCIIMPL(LWSPeer, WebSocketPeer); +class WSLPeer : public WebSocketPeer { + + GDCIIMPL(WSLPeer, WebSocketPeer); + +public: + struct PeerData { + bool polling; + bool destroy; + bool valid; + bool is_server; + void *obj; + void *peer; + Ref<StreamPeer> conn; + Ref<StreamPeerTCP> tcp; + int id; + wslay_event_context_ptr ctx; + + PeerData() { + polling = false; + destroy = false; + valid = false; + is_server = false; + id = 1; + ctx = NULL; + obj = NULL; + peer = NULL; + } + }; + + static String compute_key_response(String p_key); + static String generate_key(); private: - int _in_size; + static bool _wsl_poll(struct PeerData *p_data); + static void _wsl_destroy(struct PeerData **p_data); + + struct PeerData *_data; uint8_t _is_string; // Our packet info is just a boolean (is_string), using uint8_t for it. PacketBuffer<uint8_t> _in_buffer; - PacketBuffer<uint8_t> _out_buffer; PoolVector<uint8_t> _packet_buffer; - struct lws *wsi; WriteMode write_mode; +public: int close_code; String close_reason; - -public: - struct PeerData { - uint32_t peer_id; - bool force_close; - bool clean_close; - }; + void poll(); // Used by client and server. virtual int get_available_packet_count() const; virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); virtual int get_max_packet_size() const { return _packet_buffer.size(); }; + virtual void close_now(); virtual void close(int p_code = 1000, String p_reason = ""); virtual bool is_connected_to_host() const; virtual IP_Address get_connected_host() const; @@ -81,14 +108,12 @@ public: virtual void set_write_mode(WriteMode p_mode); virtual bool was_string_packet() const; - void set_wsi(struct lws *wsi, unsigned int _in_buf_size, unsigned int _in_pkt_size, unsigned int _out_buf_size, unsigned int _out_pkt_size); - Error read_wsi(void *in, size_t len); - Error write_wsi(); - void send_close_status(struct lws *wsi); - String get_close_reason(void *in, size_t len, int &r_code); + void make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size); + Error parse_message(const wslay_event_on_msg_recv_arg *arg); + void invalidate(); - LWSPeer(); - ~LWSPeer(); + WSLPeer(); + ~WSLPeer(); }; #endif // JAVASCRIPT_ENABLED diff --git a/modules/websocket/wsl_server.cpp b/modules/websocket/wsl_server.cpp new file mode 100644 index 0000000000..2181775b99 --- /dev/null +++ b/modules/websocket/wsl_server.cpp @@ -0,0 +1,313 @@ +/*************************************************************************/ +/* wsl_server.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. */ +/*************************************************************************/ + +#ifndef JAVASCRIPT_ENABLED + +#include "wsl_server.h" +#include "core/os/os.h" +#include "core/project_settings.h" + +WSLServer::PendingPeer::PendingPeer() { + use_ssl = false; + time = 0; + has_request = false; + response_sent = 0; + req_pos = 0; + memset(req_buf, 0, sizeof(req_buf)); +} + +bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) { + Vector<String> psa = String((char *)req_buf).split("\r\n"); + int len = psa.size(); + ERR_FAIL_COND_V_MSG(len < 4, false, "Not enough response headers, got: " + itos(len) + ", expected >= 4."); + + Vector<String> req = psa[0].split(" ", false); + ERR_FAIL_COND_V_MSG(req.size() < 2, false, "Invalid protocol or status code."); + + // Wrong protocol + ERR_FAIL_COND_V_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", false, "Invalid method or HTTP version."); + + Map<String, String> headers; + for (int i = 1; i < len; i++) { + Vector<String> header = psa[i].split(":", false, 1); + ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]); + String name = header[0].to_lower(); + String value = header[1].strip_edges(); + if (headers.has(name)) + headers[name] += "," + value; + else + headers[name] = value; + } +#define _WSL_CHECK(NAME, VALUE) \ + ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \ + "Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'."); +#define _WSL_CHECK_EX(NAME) \ + ERR_FAIL_COND_V_MSG(!headers.has(NAME), false, "Missing header '" + String(NAME) + "'."); + _WSL_CHECK("upgrade", "websocket"); + _WSL_CHECK("sec-websocket-version", "13"); + _WSL_CHECK_EX("sec-websocket-key"); + _WSL_CHECK_EX("connection"); +#undef _WSL_CHECK_EX +#undef _WSL_CHECK + key = headers["sec-websocket-key"]; + if (headers.has("sec-websocket-protocol")) { + Vector<String> protos = headers["sec-websocket-protocol"].split(","); + for (int i = 0; i < protos.size(); i++) { + String proto = protos[i].strip_edges(); + // Check if we have the given protocol + for (int j = 0; j < p_protocols.size(); j++) { + if (proto != p_protocols[j]) + continue; + protocol = proto; + break; + } + // Found a protocol + if (protocol != "") + break; + } + if (protocol == "") // Invalid protocol(s) requested + return false; + } else if (p_protocols.size() > 0) // No protocol requested, but we need one + return false; + return true; +} + +Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols) { + if (OS::get_singleton()->get_ticks_msec() - time > WSL_SERVER_TIMEOUT) + return ERR_TIMEOUT; + if (use_ssl) { + Ref<StreamPeerSSL> ssl = static_cast<Ref<StreamPeerSSL> >(connection); + if (ssl.is_null()) + return FAILED; + ssl->poll(); + if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) + return ERR_BUSY; + else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) + return FAILED; + } + if (!has_request) { + int read = 0; + while (true) { + ERR_FAIL_COND_V_MSG(req_pos >= WSL_MAX_HEADER_SIZE, ERR_OUT_OF_MEMORY, "Response headers too big."); + Error err = connection->get_partial_data(&req_buf[req_pos], 1, read); + if (err != OK) // Got an error + return FAILED; + else if (read != 1) // Busy, wait next poll + return ERR_BUSY; + char *r = (char *)req_buf; + int l = req_pos; + if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') { + r[l - 3] = '\0'; + if (!_parse_request(p_protocols)) { + return FAILED; + } + String s = "HTTP/1.1 101 Switching Protocols\r\n"; + s += "Upgrade: websocket\r\n"; + s += "Connection: Upgrade\r\n"; + s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n"; + if (protocol != "") + s += "Sec-WebSocket-Protocol: " + protocol + "\r\n"; + s += "\r\n"; + response = s.utf8(); + has_request = true; + break; + } + req_pos += 1; + } + } + if (has_request && response_sent < response.size() - 1) { + int sent = 0; + Error err = connection->put_partial_data((const uint8_t *)response.get_data() + response_sent, response.size() - response_sent - 1, sent); + if (err != OK) { + return err; + } + response_sent += sent; + } + if (response_sent < response.size() - 1) + return ERR_BUSY; + return OK; +} + +Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp_api) { + ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE); + + _is_multiplayer = gd_mp_api; + // Strip edges from protocols. + _protocols.resize(p_protocols.size()); + String *pw = _protocols.ptrw(); + for (int i = 0; i < p_protocols.size(); i++) { + pw[i] = p_protocols[i].strip_edges(); + } + _server->listen(p_port); + + return OK; +} + +void WSLServer::poll() { + + List<int> remove_ids; + for (Map<int, Ref<WebSocketPeer> >::Element *E = _peer_map.front(); E; E = E->next()) { + Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr(); + peer->poll(); + if (!peer->is_connected_to_host()) { + _on_disconnect(E->key(), peer->close_code != -1); + remove_ids.push_back(E->key()); + } + } + for (List<int>::Element *E = remove_ids.front(); E; E = E->next()) { + _peer_map.erase(E->get()); + } + remove_ids.clear(); + + List<Ref<PendingPeer> > remove_peers; + for (List<Ref<PendingPeer> >::Element *E = _pending.front(); E; E = E->next()) { + Ref<PendingPeer> ppeer = E->get(); + Error err = ppeer->do_handshake(_protocols); + if (err == ERR_BUSY) { + continue; + } else if (err != OK) { + remove_peers.push_back(ppeer); + continue; + } + // Creating new peer + int32_t id = _gen_unique_id(); + + WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData); + data->obj = this; + data->conn = ppeer->connection; + data->tcp = ppeer->tcp; + data->is_server = true; + data->id = id; + + Ref<WSLPeer> ws_peer = memnew(WSLPeer); + ws_peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size); + + _peer_map[id] = ws_peer; + remove_peers.push_back(ppeer); + _on_connect(id, ppeer->protocol); + } + for (List<Ref<PendingPeer> >::Element *E = remove_peers.front(); E; E = E->next()) { + _pending.erase(E->get()); + } + remove_peers.clear(); + + if (!_server->is_listening()) + return; + + while (_server->is_connection_available()) { + Ref<StreamPeerTCP> conn = _server->take_connection(); + if (is_refusing_new_connections()) + continue; // Conn will go out-of-scope and be closed. + + Ref<PendingPeer> peer = memnew(PendingPeer); + if (private_key.is_valid() && ssl_cert.is_valid()) { + Ref<StreamPeerSSL> ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create()); + ssl->set_blocking_handshake_enabled(false); + ssl->accept_stream(conn, private_key, ssl_cert, ca_chain); + peer->connection = ssl; + peer->use_ssl = true; + } else { + peer->connection = conn; + } + peer->tcp = conn; + peer->time = OS::get_singleton()->get_ticks_msec(); + _pending.push_back(peer); + } +} + +bool WSLServer::is_listening() const { + return _server->is_listening(); +} + +int WSLServer::get_max_packet_size() const { + return (1 << _out_buf_size) - PROTO_SIZE; +} + +void WSLServer::stop() { + _server->stop(); + for (Map<int, Ref<WebSocketPeer> >::Element *E = _peer_map.front(); E; E = E->next()) { + Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr(); + peer->close_now(); + } + _pending.clear(); + _peer_map.clear(); + _protocols.clear(); +} + +bool WSLServer::has_peer(int p_id) const { + return _peer_map.has(p_id); +} + +Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const { + ERR_FAIL_COND_V(!has_peer(p_id), NULL); + return _peer_map[p_id]; +} + +IP_Address WSLServer::get_peer_address(int p_peer_id) const { + ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address()); + + return _peer_map[p_peer_id]->get_connected_host(); +} + +int WSLServer::get_peer_port(int p_peer_id) const { + ERR_FAIL_COND_V(!has_peer(p_peer_id), 0); + + return _peer_map[p_peer_id]->get_connected_port(); +} + +void WSLServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) { + ERR_FAIL_COND(!has_peer(p_peer_id)); + + get_peer(p_peer_id)->close(p_code, p_reason); +} + +Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) { + ERR_FAIL_COND_V_MSG(_server->is_listening(), FAILED, "Buffers sizes can only be set before listening or connecting."); + + _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; +} + +WSLServer::WSLServer() { + _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); + _out_buf_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_BUF) - 1) + 10; + _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_PKT) - 1); + _server.instance(); +} + +WSLServer::~WSLServer() { + stop(); +} + +#endif // JAVASCRIPT_ENABLED diff --git a/modules/websocket/lws_server.h b/modules/websocket/wsl_server.h index 5096ee0f88..aae563355e 100644 --- a/modules/websocket/lws_server.h +++ b/modules/websocket/wsl_server.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* lws_server.h */ +/* wsl_server.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,31 +28,61 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef LWSSERVER_H -#define LWSSERVER_H +#ifndef WSLSERVER_H +#define WSLSERVER_H #ifndef JAVASCRIPT_ENABLED -#include "core/reference.h" -#include "lws_helper.h" -#include "lws_peer.h" #include "websocket_server.h" +#include "wsl_peer.h" -class LWSServer : public WebSocketServer { +#include "core/io/stream_peer_ssl.h" +#include "core/io/stream_peer_tcp.h" +#include "core/io/tcp_server.h" - GDCIIMPL(LWSServer, WebSocketServer); +#define WSL_SERVER_TIMEOUT 1000 - LWS_HELPER(LWSServer); +class WSLServer : public WebSocketServer { + + GDCIIMPL(WSLServer, WebSocketServer); private: - Map<int, Ref<LWSPeer> > peer_map; + class PendingPeer : public Reference { + + private: + bool _parse_request(const Vector<String> p_protocols); + + public: + Ref<StreamPeerTCP> tcp; + Ref<StreamPeer> connection; + bool use_ssl; + + int time; + uint8_t req_buf[WSL_MAX_HEADER_SIZE]; + int req_pos; + String key; + String protocol; + bool has_request; + CharString response; + int response_sent; + + PendingPeer(); + + Error do_handshake(const Vector<String> p_protocols); + }; + int _in_buf_size; int _in_pkt_size; int _out_buf_size; int _out_pkt_size; + List<Ref<PendingPeer> > _pending; + Ref<TCP_Server> _server; + Vector<String> _protocols; + public: - Error listen(int p_port, PoolVector<String> p_protocols = PoolVector<String>(), bool gd_mp_api = false); + Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); + Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false); void stop(); bool is_listening() const; int get_max_packet_size() const; @@ -61,12 +91,12 @@ public: IP_Address get_peer_address(int p_peer_id) const; int get_peer_port(int p_peer_id) const; void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = ""); - virtual void poll() { _lws_poll(); } + virtual void poll(); - LWSServer(); - ~LWSServer(); + WSLServer(); + ~WSLServer(); }; #endif // JAVASCRIPT_ENABLED -#endif // LWSSERVER_H +#endif // WSLSERVER_H diff --git a/modules/xatlas_unwrap/SCsub b/modules/xatlas_unwrap/SCsub index ad364d5aaf..b242fd4673 100644 --- a/modules/xatlas_unwrap/SCsub +++ b/modules/xatlas_unwrap/SCsub @@ -1,7 +1,5 @@ #!/usr/bin/env python -import platform - Import('env') Import('env_modules') @@ -15,28 +13,7 @@ if env['builtin_xatlas']: ] thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] - env_xatlas_unwrap.Append(CPPPATH=[thirdparty_dir]) - - # upstream uses c++11 - if (not env.msvc): - env_xatlas_unwrap.Append(CXXFLAGS="-std=c++11") - - if env["platform"] == 'x11': - # if not specifically one of the *BSD, then use LINUX as default - if platform.system() == "FreeBSD": - env_xatlas_unwrap.Append(CCFLAGS=["-DNV_OS_FREEBSD", "-DPOSH_COMPILER_GCC"]) - elif platform.system() == "OpenBSD": - env_xatlas_unwrap.Append(CCFLAGS=["-DNV_OS_OPENBSD", "-DPOSH_COMPILER_GCC"]) - else: - env_xatlas_unwrap.Append(CCFLAGS=["-DNV_OS_LINUX", "-DPOSH_COMPILER_GCC"]) - elif env["platform"] == 'osx': - env_xatlas_unwrap.Append(CCFLAGS=["-DNV_OS_DARWIN", "-DPOSH_COMPILER_GCC"]) - elif env["platform"] == 'windows': - if env.msvc: - env_xatlas_unwrap.Append(CCFLAGS=["-DNV_OS_WIN32", "-DNV_CC_MSVC", "-DPOSH_COMPILER_MSVC" ]) - else: - env_xatlas_unwrap.Append(CCFLAGS=["-DNV_OS_MINGW", "-DNV_CC_GNUC", "-DPOSH_COMPILER_GCC", "-U__STRICT_ANSI__"]) - env.Append(LIBS=["dbghelp"]) + env_xatlas_unwrap.Prepend(CPPPATH=[thirdparty_dir]) env_thirdparty = env_xatlas_unwrap.Clone() env_thirdparty.disable_warnings() diff --git a/modules/xatlas_unwrap/config.py b/modules/xatlas_unwrap/config.py index 2dda5db7e0..bd092bdc16 100644 --- a/modules/xatlas_unwrap/config.py +++ b/modules/xatlas_unwrap/config.py @@ -1,5 +1,4 @@ def can_build(env, platform): - #return False #xatlas is buggy return (env['tools'] and platform not in ["android", "ios"]) def configure(env): diff --git a/modules/xatlas_unwrap/register_types.cpp b/modules/xatlas_unwrap/register_types.cpp index 903b57f017..2fc554fe7a 100644 --- a/modules/xatlas_unwrap/register_types.cpp +++ b/modules/xatlas_unwrap/register_types.cpp @@ -29,108 +29,84 @@ /*************************************************************************/ #include "register_types.h" + #include "core/error_macros.h" + #include "thirdparty/xatlas/xatlas.h" #include <stdio.h> #include <stdlib.h> + extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y); bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y) { //set up input mesh - xatlas::InputMesh input_mesh; - input_mesh.indexData = malloc(sizeof(int) * p_index_count); + xatlas::MeshDecl input_mesh; + input_mesh.indexData = p_indices; input_mesh.indexCount = p_index_count; - input_mesh.indexFormat = xatlas::IndexFormat::Float; //really xatlas? - input_mesh.faceMaterialData = (uint16_t *)malloc(sizeof(uint16_t) * p_index_count); - - for (int i = 0; i < p_index_count; i++) { - int *index = (int *)input_mesh.indexData; - index[i] = p_indices[i]; - } - for (int i = 0; i < p_index_count / 3; i++) { - uint16_t *mat_index = (uint16_t *)input_mesh.faceMaterialData; - mat_index[i] = p_face_materials[i]; - } + input_mesh.indexFormat = xatlas::IndexFormat::UInt32; input_mesh.vertexCount = p_vertex_count; - input_mesh.vertexPositionData = malloc(sizeof(float) * p_vertex_count * 3); + input_mesh.vertexPositionData = p_vertices; input_mesh.vertexPositionStride = sizeof(float) * 3; - input_mesh.vertexNormalData = malloc(sizeof(float) * p_vertex_count * 3); - input_mesh.vertexNormalStride = sizeof(float) * 3; - - //material is a better hint than this i guess? + input_mesh.vertexNormalData = p_normals; + input_mesh.vertexNormalStride = sizeof(uint32_t) * 3; input_mesh.vertexUvData = NULL; input_mesh.vertexUvStride = 0; - for (int i = 0; i < p_vertex_count * 3; i++) { - float *vertex_ptr = (float *)input_mesh.vertexPositionData; - float *normal_ptr = (float *)input_mesh.vertexNormalData; - - vertex_ptr[i] = p_vertices[i]; - normal_ptr[i] = p_normals[i]; - } + xatlas::ChartOptions chart_options; + xatlas::PackOptions pack_options; - xatlas::CharterOptions chart_options; - xatlas::PackerOptions pack_options; - - pack_options.method = xatlas::PackMethod::TexelArea; - pack_options.texelArea = 1.0 / p_texel_size; - pack_options.quality = 3; + pack_options.maxChartSize = 4096; + pack_options.blockAlign = true; + pack_options.texelsPerUnit = 1.0 / p_texel_size; xatlas::Atlas *atlas = xatlas::Create(); - printf("adding mesh..\n"); - xatlas::AddMeshError err = xatlas::AddMesh(atlas, input_mesh); - ERR_EXPLAINC(xatlas::StringForEnum(err.code)); - ERR_FAIL_COND_V(err.code != xatlas::AddMeshErrorCode::Success, false); + printf("Adding mesh..\n"); + xatlas::AddMeshError::Enum err = xatlas::AddMesh(atlas, input_mesh, 1); + ERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Enum::Success, false, xatlas::StringForEnum(err)); - printf("generate..\n"); - xatlas::Generate(atlas, chart_options, pack_options); + printf("Generate..\n"); + xatlas::Generate(atlas, chart_options, NULL, pack_options); - *r_size_hint_x = xatlas::GetWidth(atlas); - *r_size_hint_y = xatlas::GetHeight(atlas); + *r_size_hint_x = atlas->width; + *r_size_hint_y = atlas->height; float w = *r_size_hint_x; float h = *r_size_hint_y; if (w == 0 || h == 0) { - return false; //could not bake + return false; //could not bake because there is no area } - const xatlas::OutputMesh *const *output_meshes = xatlas::GetOutputMeshes(atlas); - - const xatlas::OutputMesh *output = output_meshes[0]; + const xatlas::Mesh &output = atlas->meshes[0]; - *r_vertex = (int *)malloc(sizeof(int) * output->vertexCount); - *r_uv = (float *)malloc(sizeof(float) * output->vertexCount * 2); - *r_index = (int *)malloc(sizeof(int) * output->indexCount); + *r_vertex = (int *)malloc(sizeof(int) * output.vertexCount); + *r_uv = (float *)malloc(sizeof(float) * output.vertexCount * 2); + *r_index = (int *)malloc(sizeof(int) * output.indexCount); float max_x = 0; float max_y = 0; - for (uint32_t i = 0; i < output->vertexCount; i++) { - (*r_vertex)[i] = output->vertexArray[i].xref; - (*r_uv)[i * 2 + 0] = output->vertexArray[i].uv[0] / w; - (*r_uv)[i * 2 + 1] = output->vertexArray[i].uv[1] / h; - max_x = MAX(max_x, output->vertexArray[i].uv[0]); - max_y = MAX(max_y, output->vertexArray[i].uv[1]); + for (uint32_t i = 0; i < output.vertexCount; i++) { + (*r_vertex)[i] = output.vertexArray[i].xref; + (*r_uv)[i * 2 + 0] = output.vertexArray[i].uv[0] / w; + (*r_uv)[i * 2 + 1] = output.vertexArray[i].uv[1] / h; + max_x = MAX(max_x, output.vertexArray[i].uv[0]); + max_y = MAX(max_y, output.vertexArray[i].uv[1]); } - printf("final texsize: %f,%f - max %f,%f\n", w, h, max_x, max_y); - *r_vertex_count = output->vertexCount; + printf("Final texture size: %f,%f - max %f,%f\n", w, h, max_x, max_y); + *r_vertex_count = output.vertexCount; - for (uint32_t i = 0; i < output->indexCount; i++) { - (*r_index)[i] = output->indexArray[i]; + for (uint32_t i = 0; i < output.indexCount; i++) { + (*r_index)[i] = output.indexArray[i]; } - *r_index_count = output->indexCount; + *r_index_count = output.indexCount; - //xatlas::Destroy(atlas); - free((void *)input_mesh.indexData); - free((void *)input_mesh.vertexPositionData); - free((void *)input_mesh.vertexNormalData); - free((void *)input_mesh.faceMaterialData); - printf("done"); + xatlas::Destroy(atlas); + printf("Done\n"); return true; } |